From ajikoe at gmail.com Sun Jan 1 12:34:29 2006 From: ajikoe at gmail.com (Pujo Aji) Date: Sun, 1 Jan 2006 12:34:29 +0100 Subject: [Tutor] Numeric RandomArray seed problem. Message-ID: Hello, I tried calling RandomArray.seed() by calling RandomArray.get_seed() I get the seed number (x,y). My problem is that x is always 113611 any advice? Thanks pujo -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060101/4faf6747/attachment.htm From kent37 at tds.net Sun Jan 1 13:54:00 2006 From: kent37 at tds.net (Kent Johnson) Date: Sun, 01 Jan 2006 07:54:00 -0500 Subject: [Tutor] Numeric RandomArray seed problem. In-Reply-To: References: Message-ID: <43B7D0E8.8030909@tds.net> Pujo Aji wrote: > Hello, > > I tried calling RandomArray.seed() > by calling RandomArray.get_seed() I get the seed number (x,y). > My problem is that x is always 113611 any advice? Take a look at the source for RandomArray.seed(). It more-or-less splits the decimal representation of the current time in half, using the high digits for x and the low digits for y. So x will change slowly, every few hours. Kent From ajikoe at gmail.com Sun Jan 1 14:33:48 2006 From: ajikoe at gmail.com (Pujo Aji) Date: Sun, 1 Jan 2006 14:33:48 +0100 Subject: [Tutor] Numeric RandomArray seed problem. In-Reply-To: <43B7D0E8.8030909@tds.net> References: <43B7D0E8.8030909@tds.net> Message-ID: Thank you Kent. pujo On 1/1/06, Kent Johnson wrote: > > Pujo Aji wrote: > > Hello, > > > > I tried calling RandomArray.seed() > > by calling RandomArray.get_seed() I get the seed number (x,y). > > My problem is that x is always 113611 any advice? > > Take a look at the source for RandomArray.seed(). It more-or-less splits > the decimal representation of the current time in half, using the high > digits for x and the low digits for y. So x will change slowly, every > few hours. > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060101/b1b47486/attachment.html From djennings3 at earthlink.net Sun Jan 1 20:11:25 2006 From: djennings3 at earthlink.net (Don Jennings) Date: Sun, 1 Jan 2006 14:11:25 -0500 Subject: [Tutor] [OT] Python Tutor like java mailing list Message-ID: <67142FE4-7AFA-11DA-A881-0003930ACB16@earthlink.net> I suggest the beginners' forum at javaranch.com (they even give away free books on occasion : >) http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=forum&f=33 Take care, Don From eli.usmc.recon at gmail.com Mon Jan 2 08:07:10 2006 From: eli.usmc.recon at gmail.com (Eli Zabielski) Date: Mon, 2 Jan 2006 00:07:10 -0700 Subject: [Tutor] Python to C? Message-ID: <3cc822320601012307q5e5b6722x179f65060b42ca20@mail.gmail.com> Is there any way to convert a program in .py to .c? other then remakeing the program? Eli Zabielski -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060102/878f1def/attachment.htm From jjk_saji at yahoo.com Mon Jan 2 09:48:42 2006 From: jjk_saji at yahoo.com (John Joseph) Date: Mon, 2 Jan 2006 08:48:42 +0000 (GMT) Subject: [Tutor] TypeError: object doesn't support item assignment [ Trying to learn how to enter value in array ] Message-ID: <20060102084842.41254.qmail@web34814.mail.mud.yahoo.com> Hi All I am trying to write a program in which I enter the no of students and then for the students I enter the marks and later on Display the marks The script which I wrote is given below , when I run the program I get error ?TypeError: object doesn't support item assignment ? , my aim in doing this program is to learn how to enter values in a array , please advice how can I avoid this error Guidance requested Thanks Joseph ################################################################## # This program is to learn how u enter entry to the array # And how u print it , print " \nFirst Enter the No of Students ... " print "\n Then No of marks " # defining empty array a a = () # defining i i = 0 # n is the No of students which I have to enter the marks n = int(raw_input("Enter the no: of students : \n")) # m is the Marks of the students which I have to enter while i < n: m = int(raw_input("Enter the Marks for the students : \n")) a[i] = m print "Marks are ", m i = i+1 #print "Array Marks ", a[i] ___________________________________________________________ To help you stay safe and secure online, we've developed the all new Yahoo! Security Centre. http://uk.security.yahoo.com From broek at cc.umanitoba.ca Mon Jan 2 10:55:58 2006 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Mon, 02 Jan 2006 03:55:58 -0600 Subject: [Tutor] TypeError: object doesn't support item assignment [ Trying to learn how to enter value in array ] In-Reply-To: <20060102084842.41254.qmail@web34814.mail.mud.yahoo.com> References: <20060102084842.41254.qmail@web34814.mail.mud.yahoo.com> Message-ID: <43B8F8AE.3070907@cc.umanitoba.ca> John Joseph said unto the world upon 02/01/06 02:48 AM: > Hi All > I am trying to write a program in which I enter > the no of students and then for the students I enter > the marks and later on Display the marks > The script which I wrote is given below , when I run > the program I get error > ?TypeError: object doesn't support item assignment ? , > my aim in doing this program is to learn how to enter > values in a array , please advice how can I avoid > this error > Guidance requested > Thanks > Joseph > > ################################################################## > # This program is to learn how u enter entry to the > array > # And how u print it , > > > print " \nFirst Enter the No of Students ... " > print "\n Then No of marks " > > # defining empty array a > a = () > # defining i > i = 0 > > # n is the No of students which I have to enter the > marks > n = int(raw_input("Enter the no: of students : \n")) > > > # m is the Marks of the students which I have to enter > while i < n: > m = int(raw_input("Enter the Marks for the > students : \n")) > a[i] = m > print "Marks are ", m > i = i+1 > > #print "Array Marks ", a[i] Hi John, the whole traceback is helpful, as it (tries to) show the line that made Python choke: Traceback (most recent call last): File "/home/tempos/foo.py", line 16, in -toplevel- a[i] = m TypeError: object does not support item assignment See how that shows us that it is the a[i] = m that is the problem? See if this helps work it out: >>> a_tuple = () >>> a_tuple[0] = "Won't work, as tuples are immutable" Traceback (most recent call last): File "", line 1, in -toplevel- a_tuple[0] = "Won't work, as tuples are immutable" TypeError: object does not support item assignment >>> a_list = [] >>> a_list[0] = "Won't work, different reason" Traceback (most recent call last): File "", line 1, in -toplevel- a_list[0] = "Won't work, different reason" IndexError: list assignment index out of range >>> a_preloaded_list = [None] >>> a_preloaded_list[0] = "Will work, but not the best way generally" >>> a_preloaded_list ['Will work, but not the best way generally'] >>> It doesn't seem that you are aiming to correlate marks with students yet, but just want a list of marks. In that case: >>> marks = [] # 'a' is not a helpful name :-) >>> mark = raw_input("What mark?") What mark?17 >>> marks.append(mark) >>> mark = raw_input("What mark?") What mark?42 >>> marks.append(mark) >>> marks ['17', '42'] >>> HTH, Brian vdB From alan.gauld at freenet.co.uk Mon Jan 2 15:38:35 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 2 Jan 2006 14:38:35 -0000 Subject: [Tutor] Python to C? References: <3cc822320601012307q5e5b6722x179f65060b42ca20@mail.gmail.com> Message-ID: <009801c60faa$3654ec70$0b01a8c0@xp> >Is there any way to convert a program in .py to .c? other then remakeing > the program? Thee are a couuple of projects designed to make Python run faster which try to convert Python to something like C and compile it but its not a general solution and the C produced isn't in any way readable. It would be possible to write a general convertor but its value is debateable since the Python style is very different to the C style. For example C is heavily geared to the use of pointers and pointer arithmetic, whereas Python doesn't have any such concept and works at a higher level. To translate Python into C would, I suspect, result in very inefficient C. It would be much better to use Puython as executable Pseudo code and then rewrite it in 'good' C. Alan G From noahbedford at gmail.com Mon Jan 2 19:29:34 2006 From: noahbedford at gmail.com (Noah Bedford) Date: Mon, 2 Jan 2006 13:29:34 -0500 Subject: [Tutor] new to linux and I cannot find some python things In-Reply-To: <5667508E43F1B740BCFA57FF46E3530002D9E988@nav-akl-exch-c.newton.navman.com> References: <5667508E43F1B740BCFA57FF46E3530002D9E988@nav-akl-exch-c.newton.navman.com> Message-ID: <20060102132934.1fef5e2a@localhost.localdomain> On Fri, 30 Dec 2005 10:22:32 +1300 "Hans Dushanthakumar" wrote: >Anothet linux noobie here :) >How do I uninstall python? I use the SimplyMepis flavor of linux. If you installed using apt, apt-get remove python-2.3. I would reccomend just apt-get update'ing, and then apt-get install python-2.4 should do it. (but it has been a while since I switched to ubuntu from mepis, things could have changed.) -- -\n From john.corry at ntlword.com Mon Jan 2 15:55:19 2006 From: john.corry at ntlword.com (John Corry) Date: Mon, 2 Jan 2006 14:55:19 -0000 Subject: [Tutor] Printing error on Win 98SE Message-ID: Hi + Happy New Year, With help from several people from the mailing list I have been able to print out text files on my windows XP machine. I have tried using the same program on my windows 98SE machine and I get the following error: PythonWin 2.4.2 (#67, Oct 30 2005, 16:11:18) [MSC v.1310 32 bit (Intel)] on win32. Portions Copyright 1994-2004 Mark Hammond (mhammond at skippinet.com.au) - see 'Help/About PythonWin' for further copyright information. Traceback (most recent call last): File "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 310, in RunScript exec codeObject in __main__.__dict__ File "C:\test\Script1.py", line 12, in ? 0 error: (31, 'ShellExecute', 'A device attached to the system is not functioning.') >>> I can manually right click the text file and left click print and the file will print to the printer. The code that I am using is below: import win32api filename = "testprint.txt" fileobj=open (filename, "w") fileobj.write ("This is a test") fileobj.close() win32api.ShellExecute ( 0, "print", filename, None, ".", 0 ) Any help would be greatly appreciated. Thanks, John. From 3dbernard at gmail.com Mon Jan 2 19:22:52 2006 From: 3dbernard at gmail.com (Bernard Lebel) Date: Mon, 2 Jan 2006 13:22:52 -0500 Subject: [Tutor] IOError: (0, 'Error') Message-ID: <61d0e2b40601021022ld7f4823wea132b903e823843@mail.gmail.com> Hello, I am getting an IOError, and I have a hard time getting information about its meaning. Here is the full trace stack: Traceback (most recent call last): File "X:\FARM\PYTHON\DEV\farmclient_2.0_beta03.py", line 1448, in ? client.start() File "X:\FARM\PYTHON\DEV\farmclient_2.0_beta03.py", line 188, in start tGlobalRow = self.__standardQuery( "SELECT Status FROM TB_CURRENT_JOBS WHERE ID = '%s'" % ( self.globaljobid ), 'SELECT', 1 ) File "X:\FARM\PYTHON\DEV\farmclient_2.0_beta03.py", line 524, in __standardQuery self.__nodeLog( 'Query result: %s' % (str( tRow )), 4 ) File "X:\FARM\PYTHON\DEV\farmclient_2.0_beta03.py", line 1342, in __nodeLog self.nodelog.close() IOError: (0, 'Error') "self.nodelog" is a text file located on the network, that is open in "a+" mode. Everytime the program has to add a line is added to the file, the file is open, appended, then closed, in order to be able to read it at any point in time. This set of operations can happen several times a second, like 1-10 or so. In this case, every query to a MySQL database is printed, plus a few lines about the instance attributes. I have looked the built-in exception page in the Python docs, but I could not find the meaning of "0", and, well, 'Error' is not exactly a very descriptive term. Anyone has any idea how I can do something with this error? Thanks Bernard From 3dbernard at gmail.com Mon Jan 2 20:13:05 2006 From: 3dbernard at gmail.com (Bernard Lebel) Date: Mon, 2 Jan 2006 14:13:05 -0500 Subject: [Tutor] IOError: (0, 'Error') In-Reply-To: <61d0e2b40601021022ld7f4823wea132b903e823843@mail.gmail.com> References: <61d0e2b40601021022ld7f4823wea132b903e823843@mail.gmail.com> Message-ID: <61d0e2b40601021113y4c532bd9v73ff677b9a640b0e@mail.gmail.com> The __nodeLog() method looks like this: On 1/2/06, Bernard Lebel <3dbernard at gmail.com> wrote: > Hello, > > I am getting an IOError, and I have a hard time getting information > about its meaning. Here is the full trace stack: > > Traceback (most recent call last): > > File "X:\FARM\PYTHON\DEV\farmclient_2.0_beta03.py", line 1448, in ? > client.start() > > File "X:\FARM\PYTHON\DEV\farmclient_2.0_beta03.py", line 188, in start > tGlobalRow = self.__standardQuery( "SELECT Status FROM > TB_CURRENT_JOBS WHERE ID = '%s'" % ( self.globaljobid ), 'SELECT', 1 ) > > File "X:\FARM\PYTHON\DEV\farmclient_2.0_beta03.py", line 524, in > __standardQuery > self.__nodeLog( 'Query result: %s' % (str( tRow )), 4 ) > > File "X:\FARM\PYTHON\DEV\farmclient_2.0_beta03.py", line 1342, in __nodeLog > self.nodelog.close() > IOError: (0, 'Error') > > > "self.nodelog" is a text file located on the network, that is open in "a+" mode. > > Everytime the program has to add a line is added to the file, the file > is open, appended, then closed, in order to be able to read it at any > point in time. > This set of operations can happen several times a second, like 1-10 or > so. In this case, every query to a MySQL database is printed, plus a > few lines about the instance attributes. > > I have looked the built-in exception page in the Python docs, but I > could not find the meaning of "0", and, well, 'Error' is not exactly a > very descriptive term. > > > Anyone has any idea how I can do something with this error? > > > Thanks > Bernard > From 3dbernard at gmail.com Mon Jan 2 20:13:58 2006 From: 3dbernard at gmail.com (Bernard Lebel) Date: Mon, 2 Jan 2006 14:13:58 -0500 Subject: [Tutor] IOError: (0, 'Error') In-Reply-To: <61d0e2b40601021113y4c532bd9v73ff677b9a640b0e@mail.gmail.com> References: <61d0e2b40601021022ld7f4823wea132b903e823843@mail.gmail.com> <61d0e2b40601021113y4c532bd9v73ff677b9a640b0e@mail.gmail.com> Message-ID: <61d0e2b40601021113n3f7d62f0g9bf7f75dd70ea368@mail.gmail.com> (sorry for the truncated email, having big problems with internet) The __nodeLog() method looks like this: def __nodeLog( self, sMsg, iLevel ): """ Write a line from the script in its node log. ARGUMENTS: sMsg (string): the message to print iLevel (integer): the verbosity level """ if iLevel <= self.loglevel: sPrint = '%s %s [jobid: %s]: %s\n' % ( self.name, time.ctime(), self.globaljobid, sMsg ) print sPrint self.nodelog = file( os.path.join( self.nodelogs, '%s.log' % ( self.name ) ), 'a+' ) self.nodelog.write( sPrint ) self.nodelog.close() Bernard On 1/2/06, Bernard Lebel <3dbernard at gmail.com> wrote: > The __nodeLog() method looks like this: > > > > On 1/2/06, Bernard Lebel <3dbernard at gmail.com> wrote: > > Hello, > > > > I am getting an IOError, and I have a hard time getting information > > about its meaning. Here is the full trace stack: > > > > Traceback (most recent call last): > > > > File "X:\FARM\PYTHON\DEV\farmclient_2.0_beta03.py", line 1448, in ? > > client.start() > > > > File "X:\FARM\PYTHON\DEV\farmclient_2.0_beta03.py", line 188, in start > > tGlobalRow = self.__standardQuery( "SELECT Status FROM > > TB_CURRENT_JOBS WHERE ID = '%s'" % ( self.globaljobid ), 'SELECT', 1 ) > > > > File "X:\FARM\PYTHON\DEV\farmclient_2.0_beta03.py", line 524, in > > __standardQuery > > self.__nodeLog( 'Query result: %s' % (str( tRow )), 4 ) > > > > File "X:\FARM\PYTHON\DEV\farmclient_2.0_beta03.py", line 1342, in __nodeLog > > self.nodelog.close() > > IOError: (0, 'Error') > > > > > > "self.nodelog" is a text file located on the network, that is open in "a+" mode. > > > > Everytime the program has to add a line is added to the file, the file > > is open, appended, then closed, in order to be able to read it at any > > point in time. > > This set of operations can happen several times a second, like 1-10 or > > so. In this case, every query to a MySQL database is printed, plus a > > few lines about the instance attributes. > > > > I have looked the built-in exception page in the Python docs, but I > > could not find the meaning of "0", and, well, 'Error' is not exactly a > > very descriptive term. > > > > > > Anyone has any idea how I can do something with this error? > > > > > > Thanks > > Bernard > > > From dyoo at hkn.eecs.berkeley.edu Mon Jan 2 21:01:52 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 2 Jan 2006 12:01:52 -0800 (PST) Subject: [Tutor] IOError: (0, 'Error') In-Reply-To: <61d0e2b40601021022ld7f4823wea132b903e823843@mail.gmail.com> Message-ID: > Everytime the program has to add a line is added to the file, the file > is open, appended, then closed, in order to be able to read it at any > point in time. This set of operations can happen several times a second, > like 1-10 or so. In this case, every query to a MySQL database is > printed, plus a few lines about the instance attributes. Hi Bernard, Hmm... weird. Quick question: is the program multithreaded? > I have looked the built-in exception page in the Python docs, but I > could not find the meaning of "0", and, well, 'Error' is not exactly a > very descriptive term. Yeah, that's a fairly useless error message there... *sigh* From 3dbernard at gmail.com Mon Jan 2 21:49:59 2006 From: 3dbernard at gmail.com (Bernard Lebel) Date: Mon, 2 Jan 2006 15:49:59 -0500 Subject: [Tutor] IOError: (0, 'Error') In-Reply-To: References: <61d0e2b40601021022ld7f4823wea132b903e823843@mail.gmail.com> Message-ID: <61d0e2b40601021249s3e59d31fg56b3fc2007372252@mail.gmail.com> On 1/2/06, Danny Yoo wrote: > > > > Everytime the program has to add a line is added to the file, the file > > is open, appended, then closed, in order to be able to read it at any > > point in time. This set of operations can happen several times a second, > > like 1-10 or so. In this case, every query to a MySQL database is > > printed, plus a few lines about the instance attributes. > > Hi Bernard, > > Hmm... weird. Quick question: is the program multithreaded? [Bernard] Hi Danny, The program is indeed multi-threaded, although there is only one child thread running..... The parent thread runs a while loop that writes to the log every 5 seconds. I think I see where you are going with this. Are you suggesting that both parent and child thread might be trying to write to the log at once, and one of them is closing the file while it is open for both? That would make perfect sense, I had the same problem with database connections. I worked around the problem by having a seperate connection object, wich works very well. However, in the case of the log, there can only be one file. I don't know how I can "queue" the writing. So far I have prevented the error from occuring with a try/except statement, but that is not a very clean way of doing it, isn't? Any suggestion is welcomed! Thanks! Bernard From dyoo at hkn.eecs.berkeley.edu Mon Jan 2 23:15:35 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 2 Jan 2006 14:15:35 -0800 (PST) Subject: [Tutor] IOError: (0, 'Error') In-Reply-To: <61d0e2b40601021249s3e59d31fg56b3fc2007372252@mail.gmail.com> Message-ID: > I think I see where you are going with this. Are you suggesting that > both parent and child thread might be trying to write to the log at > once, and one of them is closing the file while it is open for both? Hi Bernard, One possibility is that we have a shared resource that needs some kind of mutual exclusion. If two threads try to append directly to the file, I don't know what will happen, but the result will probably not be good. But the Queue module can be especially useful here: http://www.python.org/doc/lib/module-Queue.html The idea is that we keep a separate logger thread that reads messages off a Queue instance. Something like: ###### queue = Queue() def __loggerThreadLoop(self): while True: (sMsg, iLevel) = queue.get() if iLevel <= self.loglevel: ... the rest of the original contents of __nodeLog ###### and we can just start up a thread that starts up __loggerThreadLoop(), somewhere in your instance's constructor: threading.Thread(target=self.__loggerThreadLoop).start() Initially, the queue is empty, so that logger thread sleeps till it sees a new message on the queue. __nodeLog() itself becomes a simple queuing function that just pushes new log events to the queue. If we do this, then we guarantee that only one thread is trying to write to the log file at any time: the use of the Queue serializes our access to it. Does this make sense? From kent37 at tds.net Tue Jan 3 00:30:37 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 02 Jan 2006 18:30:37 -0500 Subject: [Tutor] IOError: (0, 'Error') In-Reply-To: References: Message-ID: <43B9B79D.1010807@tds.net> Danny Yoo wrote: >>I think I see where you are going with this. Are you suggesting that >>both parent and child thread might be trying to write to the log at >>once, and one of them is closing the file while it is open for both? > > > Hi Bernard, > > One possibility is that we have a shared resource that needs some kind of > mutual exclusion. If two threads try to append directly to the file, I > don't know what will happen, but the result will probably not be good. > > > But the Queue module can be especially useful here: > > http://www.python.org/doc/lib/module-Queue.html > > The idea is that we keep a separate logger thread that reads messages off > a Queue instance. You might be interested in the standard logging module which is thread-safe and supports logging to a file, rather than inventing your own. Kent From alan.gauld at freenet.co.uk Tue Jan 3 01:43:13 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 3 Jan 2006 00:43:13 -0000 Subject: [Tutor] IOError: (0, 'Error') References: <61d0e2b40601021022ld7f4823wea132b903e823843@mail.gmail.com> Message-ID: <00da01c60ffe$ae1a3220$0b01a8c0@xp> I have no idea if this is the problem but one thing that might help is: > File "X:\FARM\PYTHON\DEV\farmclient_2.0_beta03.py", line 524, in > __standardQuery > self.__nodeLog( 'Query result: %s' % (str( tRow )), 4 ) I'd add a comma to the formatting tuple since otherwise the format operatror might get confused: self.__nodeLog( 'Query result: %s' % (str( tRow ),), 4 ) Note the comma vbefore the second last paren to force formatting to see the string expression as a single element tuple. Otherwise the parens just make it a single expression as paert of a tuple with the 4. However if that was really the mistake I'd expect formatting to complain about too many arguments... >>> '%d%' % (4,5) Traceback (most recent call last): File "", line 1, in ? ValueError: incomplete format >>> So I don't really think thats the problem. Just a nice to do... > File "X:\FARM\PYTHON\DEV\farmclient_2.0_beta03.py", line 1342, in > __nodeLog > self.nodelog.close() > IOError: (0, 'Error') > Everytime the program has to add a line is added to the file, the file > is open, appended, then closed, in order to be able to read it at any > point in time. > This set of operations can happen several times a second, like 1-10 10 transacrtions per second on a file is quite a lot, it would be easier to create a log table in your database since you already have a connection open and just add rows to that, you can then read the rows at any time - while still writing new rows if need be. Alan G. From 3dbernard at gmail.com Tue Jan 3 02:06:10 2006 From: 3dbernard at gmail.com (Bernard Lebel) Date: Mon, 2 Jan 2006 17:06:10 -0800 Subject: [Tutor] IOError: (0, 'Error') In-Reply-To: <43B9B79D.1010807@tds.net> References: <43B9B79D.1010807@tds.net> Message-ID: <61d0e2b40601021706x5556b3cai7232e027c825c80a@mail.gmail.com> Hi Kent, I'm checking out the logging module atm. I'm trying the second example in "Basic example": import logging logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s', filename='C:\\pylogger.log', filemode='w') logging.debug('A debug message') logging.info('Some information') logging.warning('A shot across the bows') However when I run that I don't get any log file, while the doc page says I should have a log file. Only the warning is printed, as if I had not run the basicConfig method. Any suggestion? Danny and Alan: thanks a lot for the suggestions, I have to say that I'd prefer a text file instead of a database table, but I guess that is just matter of habits. This could change. Thanks Bernard On 1/2/06, Kent Johnson wrote: > Danny Yoo wrote: > >>I think I see where you are going with this. Are you suggesting that > >>both parent and child thread might be trying to write to the log at > >>once, and one of them is closing the file while it is open for both? > > > > > > Hi Bernard, > > > > One possibility is that we have a shared resource that needs some kind of > > mutual exclusion. If two threads try to append directly to the file, I > > don't know what will happen, but the result will probably not be good. > > > > > > But the Queue module can be especially useful here: > > > > http://www.python.org/doc/lib/module-Queue.html > > > > The idea is that we keep a separate logger thread that reads messages off > > a Queue instance. > > You might be interested in the standard logging module which is > thread-safe and supports logging to a file, rather than inventing your own. > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Tue Jan 3 03:54:18 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 02 Jan 2006 21:54:18 -0500 Subject: [Tutor] IOError: (0, 'Error') In-Reply-To: <61d0e2b40601021706x5556b3cai7232e027c825c80a@mail.gmail.com> References: <43B9B79D.1010807@tds.net> <61d0e2b40601021706x5556b3cai7232e027c825c80a@mail.gmail.com> Message-ID: <43B9E75A.3050503@tds.net> Bernard Lebel wrote: > I'm checking out the logging module atm. I'm trying the second example > in "Basic example": > > import logging > > logging.basicConfig(level=logging.DEBUG, > format='%(asctime)s %(levelname)s %(message)s', > filename='C:\\pylogger.log', > filemode='w') > logging.debug('A debug message') > logging.info('Some information') > logging.warning('A shot across the bows') > > > However when I run that I don't get any log file, while the doc page > says I should have a log file. Only the warning is printed, as if I > had not run the basicConfig method. Any suggestion? If I copy and paste your code and run it, it works as expected creating C:\pylogger.log containing 2006-01-02 21:49:21,071 DEBUG A debug message 2006-01-02 21:49:21,071 INFO Some information 2006-01-02 21:49:21,071 WARNING A shot across the bows This is with Python 2.4.2 on Win2K. What version of Python are you using? In versions previous to 2.4, basicConfig() doesn't take keyword args. For the Python 2.3 docs see http://www.python.org/doc/2.3.5/lib/module-logging.html and the example here: http://www.python.org/doc/2.3.5/lib/node304.html Kent From jjk_saji at yahoo.com Tue Jan 3 09:02:17 2006 From: jjk_saji at yahoo.com (John Joseph) Date: Tue, 3 Jan 2006 08:02:17 +0000 (GMT) Subject: [Tutor] Thanks , Now able to do Marks entry and display it using Histogram Message-ID: <20060103080217.91204.qmail@web34802.mail.mud.yahoo.com> Hi All Thanks to Shantanoo,Brian,Alan,Owen Now I am able to enter the marks for each students , and display the results the frequency of marks in histogram Even though I am able to display the histogram of the marks with students , I would like to modify it further as I learn more , I am adding the program which I had done Thanks to the list , I am getting more encouragement here ,it is fun over here Thanks Joseph John *********************************************************** # This program is to see how can we see how many students got particular mark # And how u print it print " \nFirst Enter the No of Students ... " print "\n Then No of marks " # defining empty array array array = [] # defining i i = 0 # n is the NO of students which I have to enter the marks n = int(raw_input("Enter the no: of students : \n")) # m is the Marks of the students which I have to enter while i < n: marks = int(raw_input("Enter the Marks for the students : \n")) array.append(marks) print "Marks are ", marks i = i+1 #print "Array Marks ", array # Now to display How many students got the same marks j = 0 ########## # To Display the histograph of the students Marks # 25 is the Max marks # for j in range(25): #print j , "is ",array.count(j) print j,"x" * array.count(j) j += 1 ___________________________________________________________ To help you stay safe and secure online, we've developed the all new Yahoo! Security Centre. http://uk.security.yahoo.com From broek at cc.umanitoba.ca Tue Jan 3 09:17:52 2006 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Tue, 03 Jan 2006 02:17:52 -0600 Subject: [Tutor] Thanks , Now able to do Marks entry and display it using Histogram In-Reply-To: <20060103080217.91204.qmail@web34802.mail.mud.yahoo.com> References: <20060103080217.91204.qmail@web34802.mail.mud.yahoo.com> Message-ID: <43BA3330.3030405@cc.umanitoba.ca> John Joseph said unto the world upon 03/01/06 02:02 AM: > Hi All > Thanks to Shantanoo,Brian,Alan,Owen > Now I am able to enter the marks for each > students , and display the results the frequency of > marks in histogram > Even though I am able to display the > histogram of the marks with students , I would like > to modify it further as I learn more , I am adding the > program which I had done > Thanks to the list , I am getting more > encouragement here ,it is fun over here > Thanks > Joseph John Joseph, great :-) It is a friendly place to learn. I have a suggestion about one way you might take your efforts to improve things. > ########## > # To Display the histograph of the students Marks > # 25 is the Max marks > # > > for j in range(25): > #print j , "is ",array.count(j) > print j,"x" * array.count(j) > j += 1 Hard-coded magic numbers like 25 here are something it often pays to eliminate. If you know that every test or assignment for the entire future of time is out of 25, then it is fine. But, you can plan for the future and be more general by trying to accommodate varying point totals. If you try that and get stuck, post about it. Good luck with however you choose to improve your approach. Best, Brian vdB From alan.gauld at freenet.co.uk Tue Jan 3 13:23:03 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 3 Jan 2006 12:23:03 -0000 Subject: [Tutor] Thanks , Now able to do Marks entry and display it using Histogram References: <20060103080217.91204.qmail@web34802.mail.mud.yahoo.com> Message-ID: <00ff01c61060$725a8e80$0b01a8c0@xp> Glad you got it working, now here are some picky comments about style: > # This program is to see how can we see how many > students got particular mark > # And how u print it An introductory comment is good but in Python a common way to do that is to use documentation strings, typically using triple quotes: """This program is to see how can we see how many students got particular mark And how u print it """ Now if you import your module and do print modulename.__doc__ or even help(modulename) Python will print the doc string for you whioch can be useful and saves you opening the file in an editor to read the comments. You can do the same with functions and classes when you get around to using them... > print " \nFirst Enter the No of Students ... " > print "\n Then No of marks " This is kind of redundant since your raw_input promprts tell us what to do each time. > # defining empty array array > array = [] calling something an array is pretty meaningless, it might be better to call it marks or scores or something else that decribes its purpose rather than its structure. One of the design goals of a good programme should be to hide the details of *how* a program is built from the reader and reveal *why* the program is built the way it is.. The same applies to comments. > # defining i > i = 0 So the comment above is pretty much redundant since we can see that we are defining i.The more important question is - what is i for? Its a counter so why not call it that? > # n is the NO of students which I have to enter the > marks > n = int(raw_input("Enter the no: of students : \n")) So why not call it numStudents or similar, then you wouldn't need the comment and the following code will be much more obvious in its meaning. > # m is the Marks of the students which I have to enter m? I see no 'm'. But I do see a 'marks' variable which is self evident. Looks like to anticipated my comment here! :-) Although being really picky I'd probably suggest mark since it only holds one mark at a time... marks implies (to me at least) some kind of collection. > while i < n: > marks = int(raw_input("Enter the Marks for the > students : \n")) > array.append(marks) > print "Marks are ", marks > i = i+1 > > #print "Array Marks ", array > > # Now to display How many students got the same marks > > j = 0 Why introduice a new counter? Just use the previous one. The more names you have in a programme the harder it is to remember what they are all for - especially if they are single letter names. You finished with the counter above so why not just reinitialise it here. > ########## > # To Display the histograph of the students Marks > # 25 is the Max marks > # > > for j in range(25): > print j,"x" * array.count(j) > j += 1 Not sure why you increment j since the for loop does that for you. BTW. Another approach to this problem would be to use a dictionary. That way you can count the occurences as they are added: """ This program is to see how can we see how many students got particular mark And how u print it """ scores = {} mark = int(raw_input('mark?(-1 to end) ')) while mark != -1: try: scores[mark] += 1 except KeyError: scores[mark] = 1 # first time for this mark mark = int(raw_input('mark?(-1 to end) ')) for key in scores: print key,' x' scores[key] You can tidy that up and avoid the try/except by using the get() method of a dictionary, but I'll leave that as an excercise! Hint: use a default value of zero.:-) HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From jjk_saji at yahoo.com Tue Jan 3 13:25:19 2006 From: jjk_saji at yahoo.com (John Joseph) Date: Tue, 3 Jan 2006 12:25:19 +0000 (GMT) Subject: [Tutor] How to make to exit the loop, while typing Enter Message-ID: <20060103122519.82403.qmail@web34802.mail.mud.yahoo.com> Hi I am trying to write a program in which it ask for entries for the list , But if I press Enter it should exit the while loop without giving errors ,I have problem in making it work , right now if I press enter to exit , the program terminates showing error I am added my script which I wrote Advice requested Thanks Joseph ******************************************************************** # # How to exit , when user Press Enter # While Entering Data # # define array array = [] m = 0 print "Enter to exit" m = int(raw_input("Enter the Values for The Array : ")) array.append(m) print array while m != "": m = int(raw_input("Enter the Values for The Array : ")) array.append(m) print array ___________________________________________________________ Yahoo! Messenger - NEW crystal clear PC to PC calling worldwide with voicemail http://uk.messenger.yahoo.com From 3dbernard at gmail.com Tue Jan 3 15:36:12 2006 From: 3dbernard at gmail.com (Bernard Lebel) Date: Tue, 3 Jan 2006 09:36:12 -0500 Subject: [Tutor] IOError: (0, 'Error') In-Reply-To: <43B9E75A.3050503@tds.net> References: <43B9B79D.1010807@tds.net> <61d0e2b40601021706x5556b3cai7232e027c825c80a@mail.gmail.com> <43B9E75A.3050503@tds.net> Message-ID: <61d0e2b40601030636lb7f24b7vcc974a21f5dcac55@mail.gmail.com> On 1/2/06, Kent Johnson wrote: > Bernard Lebel wrote: > > I'm checking out the logging module atm. I'm trying the second example > > in "Basic example": > > > > import logging > > > > logging.basicConfig(level=logging.DEBUG, > > format='%(asctime)s %(levelname)s %(message)s', > > filename='C:\\pylogger.log', > > filemode='w') > > logging.debug('A debug message') > > logging.info('Some information') > > logging.warning('A shot across the bows') > > > > > > However when I run that I don't get any log file, while the doc page > > says I should have a log file. Only the warning is printed, as if I > > had not run the basicConfig method. Any suggestion? > > If I copy and paste your code and run it, it works as expected creating > C:\pylogger.log containing > > 2006-01-02 21:49:21,071 DEBUG A debug message > 2006-01-02 21:49:21,071 INFO Some information > 2006-01-02 21:49:21,071 WARNING A shot across the bows > > This is with Python 2.4.2 on Win2K. What version of Python are you > using? In versions previous to 2.4, basicConfig() doesn't take keyword > args. For the Python 2.3 docs see > http://www.python.org/doc/2.3.5/lib/module-logging.html > > and the example here: > http://www.python.org/doc/2.3.5/lib/node304.html > > Kent Ah yeah, that would be it. I'm using 2.4. Thanks Bernard From wood_yee12 at hotmail.com Tue Jan 3 17:55:05 2006 From: wood_yee12 at hotmail.com (wood yee) Date: Tue, 03 Jan 2006 16:55:05 +0000 Subject: [Tutor] Help with choosing books Message-ID: An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060103/c1bfa1b4/attachment.html From srini_iyyer_bio at yahoo.com Tue Jan 3 18:17:37 2006 From: srini_iyyer_bio at yahoo.com (Srinivas Iyyer) Date: Tue, 3 Jan 2006 09:17:37 -0800 (PST) Subject: [Tutor] Help with choosing books In-Reply-To: Message-ID: <20060103171737.36016.qmail@web31613.mail.mud.yahoo.com> Hi, I guess this has been discussed in detail in December 2005 (last month). you might want to check this thread and the replies in deteails. http://mail.python.org/pipermail/tutor/2005-December/044028.html This might help. --- wood yee wrote: --------------------------------- Hi! I got Foundations of Python Network Programming as a gift but I don't know Python. My library has several books called Beginning Python. One's by Wrox and the other is by the author of the hacking python tutorial. My question is how can I achieve my goal of becoming ready for Foundations of Python Network Programming? Which book should I start with? Is a tutorial better? Any ideas of what syllabus(sp?) to follow? I really want to tackle my Foundations book and I want to get up to speed as quickly as I can. Thanks! > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > __________________________________________ Yahoo! DSL ? Something to write home about. Just $16.99/mo. or less. dsl.yahoo.com From dyoo at hkn.eecs.berkeley.edu Tue Jan 3 18:57:32 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 3 Jan 2006 09:57:32 -0800 (PST) Subject: [Tutor] How to make to exit the loop, while typing Enter In-Reply-To: <20060103122519.82403.qmail@web34802.mail.mud.yahoo.com> Message-ID: > I am trying to write a program in which it ask for entries for the list > , But if I press Enter it should exit the while loop without giving > errors Hi John, Do you have ideas why it's getting an error? Can you point at the part of the program that's receiving the "Enter"? As a related question, what result do you expect from: int("") What does Python respond with? From adam.jtm30 at gmail.com Tue Jan 3 19:38:24 2006 From: adam.jtm30 at gmail.com (Adam) Date: Tue, 3 Jan 2006 18:38:24 +0000 Subject: [Tutor] How to make to exit the loop, while typing Enter In-Reply-To: References: <20060103122519.82403.qmail@web34802.mail.mud.yahoo.com> Message-ID: Woops, forgot to reply-all. ---------- Forwarded message ---------- From: Adam Date: 03-Jan-2006 15:48 Subject: Re: [Tutor] How to make to exit the loop, while typing Enter To: John Joseph array = [] > m = 0 > print "Enter to exit" > m = int(raw_input("Enter the Values for The Array : > ")) > array.append(m) > print array > while m != "": > m = int(raw_input("Enter the Values for The > Array : ")) > array.append(m) > print array The problem is that if a value is entered that can't be converted to an integer type, like "" or a letter then an exception is raised. What you could do is use a try, except. while 1: try: m = int(raw_input("Enter the Values for The Array: ")) array.append(m) print array except ValueError: sys.exit() alternatively you could do something like this: m=raw_input("Enter the Values for The Array: ") if m == "": sys.exit() try: int(m) array.append(m) print array except ValueError: print "Only integer values can be entered into the array, or press the enter key to exit." -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060103/5a8ecf5e/attachment.html From lsloan at umich.edu Tue Jan 3 15:12:35 2006 From: lsloan at umich.edu (Lance E Sloan) Date: Tue, 03 Jan 2006 09:12:35 -0500 Subject: [Tutor] Python code pretty-print? Message-ID: <90AFD5305EA4CAC465FB18EB@host-220.subnet-234.med.umich.edu> A colleague of mine often develops Python code under Mac OS X. He would like to be able to print the code in an easily readable format. He's found that kwrite on Linux does a very nice job, but it's inconvenient to copy his code to a Linux box just to print it out. We've found mention (mostly in manpages) of a program called "pyhtmlizer", but couldn't find source or binary for it. Can anybody recommend a similar tool that we can use on Mac OS X? Thanks! -- Lance E Sloan, Systems Research Programmer III U-M WATS: Web Applications, Technologies, and Solutions Full-service web and database design, development, and hosting. http://www.itcs.umich.edu/wats/ - "Putting U on the Web" From lfiedor at willow.iie.uz.zgora.pl Tue Jan 3 22:08:36 2006 From: lfiedor at willow.iie.uz.zgora.pl (lfiedor) Date: Tue, 03 Jan 2006 22:08:36 +0100 Subject: [Tutor] dynamic lists Message-ID: <43BAE7D4.2020805@willow.iie.uz.zgora.pl> Hi im looking for very simple DES and RSA algorithms writen in python (or C), can anyone know where i can find them From dyoo at hkn.eecs.berkeley.edu Tue Jan 3 22:29:25 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 3 Jan 2006 13:29:25 -0800 (PST) Subject: [Tutor] Python code pretty-print? In-Reply-To: <90AFD5305EA4CAC465FB18EB@host-220.subnet-234.med.umich.edu> Message-ID: On Tue, 3 Jan 2006, Lance E Sloan wrote: > A colleague of mine often develops Python code under Mac OS X. He would > like to be able to print the code in an easily readable format. He's > found that kwrite on Linux does a very nice job, but it's inconvenient > to copy his code to a Linux box just to print it out. > > We've found mention (mostly in manpages) of a program called > "pyhtmlizer", but couldn't find source or binary for it. Hi Lance, 'pyhtmlizer' is in the twisted package, under twisted.scripts: http://twistedmatrix.com/documents/current/api/twisted.scripts.htmlizer.html You should be able to get the source there. Alternatively, the Python Cookbook has a good recipe for syntax highlighting: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52298 Finally, GNU Enscript might be applicable. GNU Enscript knows how to colorize and pretty print different programming languages, and I believe it's already in Mac OS X. http://www.osxfaq.com/man/1/enscript.ws If you use the --pretty-print, --color, and -Whtml options, you should be able to get some reasonable output with it. Best of wishes! From jason.massey at gmail.com Tue Jan 3 22:30:30 2006 From: jason.massey at gmail.com (Jason Massey) Date: Tue, 3 Jan 2006 15:30:30 -0600 Subject: [Tutor] dynamic lists In-Reply-To: <43BAE7D4.2020805@willow.iie.uz.zgora.pl> References: <43BAE7D4.2020805@willow.iie.uz.zgora.pl> Message-ID: <7e3eab2c0601031330j60d707d8vdb4f765cf9092026@mail.gmail.com> googled for rsa & python: http://www.python.org/workshops/1995-05/pct.html On 1/3/06, lfiedor wrote: > > Hi > im looking for very simple DES and RSA algorithms writen in python (or > C), can anyone know where i can find them > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060103/f9d82035/attachment.htm From dyoo at hkn.eecs.berkeley.edu Tue Jan 3 22:36:52 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 3 Jan 2006 13:36:52 -0800 (PST) Subject: [Tutor] DES and RSA cryptography algorithms? (Was: Re: dynamic lists) In-Reply-To: <43BAE7D4.2020805@willow.iie.uz.zgora.pl> Message-ID: On Tue, 3 Jan 2006, lfiedor wrote: > im looking for very simple DES and RSA algorithms writen in python (or > C), can anyone know where i can find them I'm changing subject lines. Please try to make your message Subject lines descriptive enough to make it easier to find later. Also, next time, try first searching for these modules in Python's Cheese Shop code repository. It's the spiritual successor to the Vaults of Parnassus, and is steadily becoming very usable. http://cheeseshop.python.org/pypi Yes, there are implementations of those algorithms available. For example: http://cheeseshop.python.org/pypi/pyDes/ shows a pure Python implementation of DES. There's also a nice packaging of those algorithms in the Python Cryptography Toolkit: http://www.amk.ca/python/code/crypto Good luck to you. From jason.massey at gmail.com Tue Jan 3 22:43:52 2006 From: jason.massey at gmail.com (Jason Massey) Date: Tue, 3 Jan 2006 15:43:52 -0600 Subject: [Tutor] Syntax Errors Message-ID: <7e3eab2c0601031343v7b5a1abma00238c1c0129205@mail.gmail.com> I've just finished ripping out a bunch of lines in one of my wxPython programs. Testing it out I get: C:\Python24>tla2.py File "C:\Python24\tla2.py", line 412 self.grid.SetCellValue(0,0,"Site") ^ SyntaxError: invalid syntax There's nothing wrong with that line. I didn't even touch it in the overhaul (refactoring is much too delicate of a word for the surgery I just did). I can make the error go away by unindenting the line, but all that happens then is the error gets passed onto the next line down. I've had this happen before on a smaller scale. Python wouldn't like a certain line and I found that if I moved it up in the function the error would go away. Unfortunately this overhaul touched on at least three functions. Oddly enough the function where I did the majority of the work seemed to come out fine. Any pointers on tracing this down? In C I would expect I didn't have a set of matching braces or a missing semi-colon. thanks, jason -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060103/65700f28/attachment.html From rs445 at hotmail.com Tue Jan 3 22:28:24 2006 From: rs445 at hotmail.com (Ron Speerstra) Date: Tue, 03 Jan 2006 22:28:24 +0100 Subject: [Tutor] HD/DVD/CD In-Reply-To: Message-ID: Hi, M-list, my name Ron Speerstra(the Netherlands) my question: howtoo read the HD/CD/DVD serial-numbers with Python. Volume-name, dir name, file name. no problem etc. Gr Ron$ _________________________________________________________________ Vind alles terug op je PC: MSN Search Toolbar http://toolbar.msn.nl/ From alan.gauld at freenet.co.uk Tue Jan 3 22:45:54 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 3 Jan 2006 21:45:54 -0000 Subject: [Tutor] How to make to exit the loop, while typing Enter References: <20060103122519.82403.qmail@web34802.mail.mud.yahoo.com> Message-ID: <011d01c610af$12ccca10$0b01a8c0@xp> > entries for the list , But if I press Enter it should > exit the while loop without giving errors ,I have > problem in making it work , right now if I press enter > to exit , the program terminates showing error Thats because you can't convert an empty string to an int. If you defer the conversion until you add the mark to the list then it should work OK. > m = int(raw_input("Enter the Values for The Array : > ")) > array.append(m) array.append(int(m)) HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Tue Jan 3 22:49:34 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 3 Jan 2006 21:49:34 -0000 Subject: [Tutor] Help with choosing books References: Message-ID: <012201c610af$9656f400$0b01a8c0@xp> Hi, What background do you come from? Can you already program in another language? > Hi! I got Foundations of Python Network Programming > I really want to tackle my Foundations book and I want > to get up to speed as quickly as I can. Thanks! If you already program then just work through the Python tutor that comes with Python. That should be all you really need. Ask any specific questions on this list. If you are a complete beginner there is a web site that lists several tutors for non programmers (mine included) and the books you have should help too. Anything you don't understand just ask here. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From dyoo at hkn.eecs.berkeley.edu Tue Jan 3 22:52:14 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 3 Jan 2006 13:52:14 -0800 (PST) Subject: [Tutor] Syntax Errors In-Reply-To: <7e3eab2c0601031343v7b5a1abma00238c1c0129205@mail.gmail.com> Message-ID: On Tue, 3 Jan 2006, Jason Massey wrote: > I've just finished ripping out a bunch of lines in one of my wxPython > programs. Testing it out I get: > > C:\Python24>tla2.py > File "C:\Python24\tla2.py", line 412 > self.grid.SetCellValue(0,0,"Site") > ^ > SyntaxError: invalid syntax > > There's nothing wrong with that line. I didn't even touch it in the > overhaul (refactoring is much too delicate of a word for the surgery I > just did). I can make the error go away by unindenting the line, but > all that happens then is the error gets passed onto the next line down. Hi Jason, Can you show us the line in context? That is, can you show us a few lines above and below? Also, let's make sure we're not running into a silly tab-vs-spaces issue. Can you try running Python with the '-tt' command line option? This will enable Python to strictly treat mixed tabs and spaces as a bad thing. Good luck! From john at fouhy.net Tue Jan 3 22:56:08 2006 From: john at fouhy.net (John Fouhy) Date: Wed, 4 Jan 2006 10:56:08 +1300 Subject: [Tutor] HD/DVD/CD In-Reply-To: References: Message-ID: <5e58f2e40601031356x6583f0b1q@mail.gmail.com> On 04/01/06, Ron Speerstra wrote: > my question: howtoo read the HD/CD/DVD serial-numbers with Python. > Volume-name, dir name, file name. no problem etc Are you running Microsoft Windows? If so, are any of the scripts at http://www.microsoft.com/technet/scriptcenter/scripts/python/pyindex.mspx useful to you? -- John. From jason.massey at gmail.com Tue Jan 3 23:03:13 2006 From: jason.massey at gmail.com (Jason Massey) Date: Tue, 3 Jan 2006 16:03:13 -0600 Subject: [Tutor] Syntax Errors In-Reply-To: References: <7e3eab2c0601031343v7b5a1abma00238c1c0129205@mail.gmail.com> Message-ID: <7e3eab2c0601031403m6405b705ge135a0d3b3f89e89@mail.gmail.com> Danny! Thanks! It's the tab vs spaces, alright. I use tabs for my spacing and I was touching a part of the code that a co-worker wrote. Guess what he uses? Spaces. Thanks for that insight and I'll be sure to read up on the command line options. On 1/3/06, Danny Yoo wrote: > > > > On Tue, 3 Jan 2006, Jason Massey wrote: > > > I've just finished ripping out a bunch of lines in one of my wxPython > > programs. Testing it out I get: > > > > C:\Python24>tla2.py > > File "C:\Python24\tla2.py", line 412 > > self.grid.SetCellValue(0,0,"Site") > > ^ > > SyntaxError: invalid syntax > > > > There's nothing wrong with that line. I didn't even touch it in the > > overhaul (refactoring is much too delicate of a word for the surgery I > > just did). I can make the error go away by unindenting the line, but > > all that happens then is the error gets passed onto the next line down. > > Hi Jason, > > Can you show us the line in context? That is, can you show us a few lines > above and below? > > Also, let's make sure we're not running into a silly tab-vs-spaces issue. > Can you try running Python with the '-tt' command line option? This will > enable Python to strictly treat mixed tabs and spaces as a bad thing. > > > Good luck! > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060103/e6a01c55/attachment.htm From alan.gauld at freenet.co.uk Tue Jan 3 23:04:51 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 3 Jan 2006 22:04:51 -0000 Subject: [Tutor] dynamic lists References: <43BAE7D4.2020805@willow.iie.uz.zgora.pl> Message-ID: <013201c610b1$bd2e6cf0$0b01a8c0@xp> > im looking for very simple DES and RSA algorithms writen in python (or > C), can anyone know where i can find them I'll be slightly surprised if you find Python versions(but not amazed! :-) since performance is usually of high priority for cryptography. But the RSA site should have C libraries I think. They used to... Note that DES is now considered minimum security since it was broken by brute force in DesChall a few years ago... Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Tue Jan 3 23:01:33 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 3 Jan 2006 22:01:33 -0000 Subject: [Tutor] Python code pretty-print? References: <90AFD5305EA4CAC465FB18EB@host-220.subnet-234.med.umich.edu> Message-ID: <012c01c610b1$43778540$0b01a8c0@xp> Try getting gvim for MacOS vim includes a Python mode with syntax colouring and you can get it to print it out using an HTML representation. It works well IMHO (on any platform including MacOS). http://www.vim.org/download.php and MacOS specific versions : http://macvim.org/ Scite does the same trick but I don't know how well it runs on MacOS. http://mailman.lyra.org/pipermail/scintilla-interest/2003-May/002756.html Alan G. ----- Original Message ----- From: "Lance E Sloan" To: Sent: Tuesday, January 03, 2006 2:12 PM Subject: [Tutor] Python code pretty-print? >A colleague of mine often develops Python code under Mac OS X. He would >like to be able to print the code in an easily readable format. He's found >that kwrite on Linux does a very nice job, but it's inconvenient to copy >his code to a Linux box just to print it out. > > We've found mention (mostly in manpages) of a program called "pyhtmlizer", > but couldn't find source or binary for it. > > Can anybody recommend a similar tool that we can use on Mac OS X? > > Thanks! > > -- > Lance E Sloan, Systems Research Programmer III > U-M WATS: Web Applications, Technologies, and Solutions > Full-service web and database design, development, and hosting. > http://www.itcs.umich.edu/wats/ - "Putting U on the Web" > > > From alan.gauld at freenet.co.uk Wed Jan 4 00:35:20 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 3 Jan 2006 23:35:20 -0000 Subject: [Tutor] dynamic lists References: <43BAE7D4.2020805@willow.iie.uz.zgora.pl> <013201c610b1$bd2e6cf0$0b01a8c0@xp> Message-ID: <015601c610be$5da73e30$0b01a8c0@xp> >> im looking for very simple DES and RSA algorithms writen in python (or >> C), can anyone know where i can find them > > I'll be slightly surprised if you find Python versions(but not amazed! :-) > since performance is usually of high priority for cryptography. Ok, I'm duly surprised but not amazed... ;-) Batteries not included this time but available nonetheless, Python never ceased to catch me out... Mind you I still doubt I'd use Python for anything other than experimental crypto work. (But that might just be my comms background and the need for real-time encryption showing through...) Alan G. From carroll at tjc.com Wed Jan 4 02:35:30 2006 From: carroll at tjc.com (Terry Carroll) Date: Tue, 3 Jan 2006 17:35:30 -0800 (PST) Subject: [Tutor] HD/DVD/CD In-Reply-To: Message-ID: On Tue, 3 Jan 2006, Ron Speerstra wrote: > my question: howtoo read the HD/CD/DVD serial-numbers with Python. I can take you part-way there, at least under Windows. Hopefully someone can finish the job. I'm assuming you want the same serial # that shows up when you do a DIR on the CD, e.g.: >dir d: Volume in drive D is 050512_1752 Volume Serial Number is 8A73-780D Here's some code: >>> import win32api >>> CD_Info = win32api.GetVolumeInformation("D:/") >>> serno = CD_Info[1] >>> serno -1972144115 >>> "%X" % serno '-758C87F3' >>> "%X" % -serno '758C87F3' This is as far as I can get. the hex string, in this case 758C87F3 is the two's complement of the serial number that shows up when I do a "dir d:": >dir d: Volume in drive D is 050512_1752 Volume Serial Number is 8A73-780D Note that: 758C 87F3 + 8A73 780D ========= 1 0000 0000 Put another way, if you flip every bit in the 758C87F3 string and add one, you'll get the 8A73780D serial no. I hope someone more artful than I can show a quick and easy way to convert either '758C87F3' or -1972144115 to the '8A73780D' that is your goal. I'm betting there's something simple I'm missing. (By the way, it occurs to me; I guess you could just do the "dir" and capture the serial number in the output; but that's inelegant and wasteful.) From john at fouhy.net Wed Jan 4 03:00:09 2006 From: john at fouhy.net (John Fouhy) Date: Wed, 4 Jan 2006 15:00:09 +1300 Subject: [Tutor] HD/DVD/CD In-Reply-To: References: Message-ID: <5e58f2e40601031800k5a18614ax@mail.gmail.com> On 04/01/06, Terry Carroll wrote: > I hope someone more artful than I can show a quick and easy way to convert > either '758C87F3' or -1972144115 to the '8A73780D' that is your goal. Hmm, well, >>> i = -1972144115 >>> '%X' % (pow(2, 32)-(~i+1)) '8A73780D' Although my bitwise arithmetic's feeling pretty rusty.. But --- C:\Games\Civilization III\Conquests>dir d: Volume in drive D is CIV3CQST Volume Serial Number is 49BC-31DB ... >>> import win32api >>> cdi = win32api.GetVolumeInformation('D:/') >>> '%X' % cdi[1] '49BC31DB' So, on my system (ActivePython 2.4, WinXPpro) there is no need for magic. I've got Mark Hammond's pywin32 book, but it doesn't talk about win32api.GetVolumeInformation(). -- John. From carroll at tjc.com Wed Jan 4 03:13:43 2006 From: carroll at tjc.com (Terry Carroll) Date: Tue, 3 Jan 2006 18:13:43 -0800 (PST) Subject: [Tutor] HD/DVD/CD In-Reply-To: <5e58f2e40601031800k5a18614ax@mail.gmail.com> Message-ID: On Wed, 4 Jan 2006, John Fouhy wrote: > On 04/01/06, Terry Carroll wrote: > > I hope someone more artful than I can show a quick and easy way to convert > > either '758C87F3' or -1972144115 to the '8A73780D' that is your goal. > > Hmm, well, > > >>> i = -1972144115 > >>> '%X' % (pow(2, 32)-(~i+1)) > '8A73780D' Aha, I also figured another way myself in the meantime: >>> import win32api >>> CD_Info = win32api.GetVolumeInformation("D:/") >>> serno = CD_Info[1] >>> serno_str = "%X" % (0x100000000+serno) >>> serno_str '8A73780D' >>> > >>> cdi = win32api.GetVolumeInformation('D:/') > >>> '%X' % cdi[1] > '49BC31DB' > > So, on my system (ActivePython 2.4, WinXPpro) there is no need for magic. I think you just got lucky that your first digit (4) was in the range 0-7, and so didn't generate a negative. But you *do* point out a fault in my approach. I'll give an incorrect result for a non-negative. I think the correct way is: >>> import win32api >>> CD_Info = win32api.GetVolumeInformation("D:/") >>> serno = CD_Info[1] >>> if serno < 0: ... serno_str = "%X" % (0x100000000+serno) ... else: ... serno_str = "%X" % serno ... >>> serno_str '8A73780D' >>> From rdm at rcblue.com Wed Jan 4 04:19:11 2006 From: rdm at rcblue.com (Dick Moores) Date: Tue, 03 Jan 2006 19:19:11 -0800 Subject: [Tutor] Programming Python, 3rd ed.?? Message-ID: <6.2.3.4.2.20060103191839.05467eb0@rcblue.com> Several months ago I saw an item on the O'Reilly site to the effect that the 3rd. ed. of Programming Python was in the works. I made a note to myself to check back in January. I just did, but could find nothing at all about a 3rd. edition. Anyone know? Thanks, Dick Moores From jjk_saji at yahoo.com Wed Jan 4 08:22:51 2006 From: jjk_saji at yahoo.com (John Joseph) Date: Wed, 4 Jan 2006 07:22:51 +0000 (GMT) Subject: [Tutor] How to make to exit the loop, while typing Enter In-Reply-To: Message-ID: <20060104072251.48105.qmail@web34807.mail.mud.yahoo.com> Hi All I was able to exit the while loop , using sys module also I was able to find the maximum no of marks entered , I am adding my code , for comments and suggestions Thanks for the support Joseph John ********************************************************************* """ This progorm was to learn 1> How to find which is the maximum mark in list 2> How to exit the while loop, while typing enter """ import sys maxmark = [] counter = 0 while 1: try: mark = int(raw_input("Enter the Values for The Array: ")) maxmark.append(mark) print maxmark except ValueError: #print "From Here to Where " counter = 0 length = len(maxmark) #print length max = maxmark[counter] #print max for counter in range(length): if maxmark[counter] > max: max = maxmark[counter] # print " Ya U are in the if loop and the maximum no is ", max #else: #print "The ", length print "At last the Maximum Marks U got is ", max sys.exit() ~ ~ ~ --- Adam wrote: > > array = [] > > m = 0 > > print "Enter to exit" > > m = int(raw_input("Enter the Values for The > Array : > > ")) > > array.append(m) > > print array > > while m != "": > > m = int(raw_input("Enter the Values for > The > > Array : ")) > > array.append(m) > > print array > > > The problem is that if a value is entered that can't > be converted to an > integer type, like "" or a letter then an exception > is raised. What you > could do is use a try, except. > while 1: > try: > m = int(raw_input("Enter the Values for > The Array: ")) > array.append(m) > print array > except ValueError: > sys.exit() > > alternatively you could do something like this: > m=raw_input("Enter the Values for The Array: ") > if m == "": sys.exit() > try: > int(m) > array.append(m) > print array > except ValueError: > print "Only integer values can be entered into > the array, or press the > enter key to exit." > ___________________________________________________________ To help you stay safe and secure online, we've developed the all new Yahoo! Security Centre. http://uk.security.yahoo.com From meesters at uni-mainz.de Wed Jan 4 09:09:38 2006 From: meesters at uni-mainz.de (Christian Meesters) Date: Wed, 4 Jan 2006 09:09:38 +0100 Subject: [Tutor] Python code pretty-print? Message-ID: <200601040909.38412.meesters@uni-mainz.de> On Tue, 3 Jan 2006, Lance E Sloan wrote: > A colleague of mine often develops Python code under Mac OS X. He would > like to be able to print the code in an easily readable format. He's > found that kwrite on Linux does a very nice job, but it's inconvenient > to copy his code to a Linux box just to print it out. > > We've found mention (mostly in manpages) of a program called > "pyhtmlizer", but couldn't find source or binary for it. Hi Did you try subethaedit ( http://www.codingmonkeys.de/subethaedit/ )? Despite of the strange name IMHO the best editor for OS X. Excellent syntax highlighting included. Cheers Christian From rs445 at hotmail.com Wed Jan 4 12:43:43 2006 From: rs445 at hotmail.com (Ron Speerstra) Date: Wed, 04 Jan 2006 12:43:43 +0100 Subject: [Tutor] Tutor Digest, Vol 23, Issue 7 In-Reply-To: Message-ID: Wouw, this is realy good!! Thanks for all, I can go on now with my DB. you were realy helpful, all. >************************************ > >>> import win32api > >>> CD_Info = win32api.GetVolumeInformation("D:/") > >>> serno = CD_Info[1] > >>> if serno < 0: >... serno_str = "%X" % (0x100000000+serno) >... else: >... serno_str = "%X" % serno >... > >>> serno_str >'8A73780D' > >>> > >************************************ Thanks Gr Ron Speerstra _________________________________________________________________ Een audiogesprek? Pak Messenger, niet de telefoon http://www1.imagine-msn.com/Messenger/Video.aspx From alan.gauld at freenet.co.uk Wed Jan 4 13:34:26 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 4 Jan 2006 12:34:26 -0000 Subject: [Tutor] How to make to exit the loop, while typing Enter References: <20060104072251.48105.qmail@web34807.mail.mud.yahoo.com> Message-ID: <017e01c6112b$33acdaf0$0b01a8c0@xp> Hi John, The code is looking better, some minor points below: > import sys > maxmark = [] > counter = 0 > > while 1: > try: > mark = int(raw_input("Enter the Values for the Array: ")) > maxmark.append(mark) > print maxmark > except ValueError: > #print "From Here to Where " While what you have written will work, its not usually a good idea to use a try/except block to control program flow like that. In pseudo code terms what you want is: while more marks read and store marks process marks So the processing should really be outside the loop. The idiomatic way to break out of a loop in Python is to use the 'break' keyword (it has a cousin 'continue' too) while: try: loop code here if loop should end break except E: handle any exceptions either break or continue post loop processing here Hopefully that makes sense, it just makes the shape (ie the layout) of your code follow the logical structure of your design. And it doesn't confuse the error handling in the except block with the normal 'happy path' process. > counter = 0 You already did this up above so its not needed here... > length = len(maxmark) > max = maxmark[counter] > for counter in range(length): > if maxmark[counter] > max: > max = maxmark[counter] Because you only use counter to access the array you can do this more cleanly by using the for syntax directly: for mark in maxmark: if mark > max: max = mark No need for the counter, the length, or the call to range. I suspect you may have some experience in a language like C or Basic or Pascal which doesn't havce a 'foreach' kind of operation, often it can be hard to break out of the idea of using indexing to access items in a container. But the for loop is designed specifically for that purpose, using range() is just a trick to simulate conventional for loops on the rare occasions when we really do want the index.(and the new enumerate() method is reducing those occasions even more). > print "At last the Maximum Marks U got is ", max > sys.exit() Because we used break to exit the loop we no longer need the sys.exit() call here, nor by implication, the import statement at the top. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Wed Jan 4 14:15:43 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 04 Jan 2006 08:15:43 -0500 Subject: [Tutor] HD/DVD/CD In-Reply-To: References: Message-ID: <43BBCA7F.3010508@tds.net> Terry Carroll wrote: > I'm assuming you want the same serial # that shows up when you do a > DIR on the CD, e.g.: > > >dir d: > Volume in drive D is 050512_1752 > Volume Serial Number is 8A73-780D > > Here's some code: > > >>>>import win32api >>>>CD_Info = win32api.GetVolumeInformation("D:/") >>>>serno = CD_Info[1] >>>>serno > > -1972144115 > >>>>"%X" % serno > > '-758C87F3' > >>>>"%X" % -serno > > '758C87F3' > > This is as far as I can get. the hex string, in this case 758C87F3 is the > two's complement of the serial number that shows up when I do a "dir d:": > > >dir d: > Volume in drive D is 050512_1752 > Volume Serial Number is 8A73-780D > > Note that: > 758C 87F3 > + 8A73 780D > ========= > 1 0000 0000 > > Put another way, if you flip every bit in the 758C87F3 string and add one, > you'll get the 8A73780D serial no. > > I hope someone more artful than I can show a quick and easy way to convert > either '758C87F3' or -1972144115 to the '8A73780D' that is your goal. What is happening here is that Python is treating the bit pattern '8A73780D' as a signed integer. A common way to represent signed integers is with two's complement notation, so Python interprets '8A73780D' as the number -1972144115. When you convert this to hex using %x formatting, the sign is preserved and you see the representation '-758C87F3'. To get the desired representation, you have to find a way to make Python interpret the number as an unsigned integer. One way to do this is to convert it to a long integer, then mask off the sign bits: >>> i = long(-1972144115) & 0xFFFFFFFF >>> i 2322823181L >>> '%x' % i '8a73780d' As you noted, John Fouhy's number doesn't have the high bit set. So it is interpreted as a positive number. Masking the sign bits has no effect because they are already zeros: >>> i=0x49BC31DB >>> i 1237070299 >>> i = long(i) & 0xFFFFFFFF >>> i 1237070299L >>> '%x' % i '49bc31db' More about two's complement notation here: http://en.wikipedia.org/wiki/Two%27s_complement Kent From carroll at tjc.com Wed Jan 4 20:25:19 2006 From: carroll at tjc.com (Terry Carroll) Date: Wed, 4 Jan 2006 11:25:19 -0800 (PST) Subject: [Tutor] HD/DVD/CD In-Reply-To: <43BBCA7F.3010508@tds.net> Message-ID: On Wed, 4 Jan 2006, Kent Johnson wrote: > To get the desired representation, you have to find a way to make Python > interpret the number as an unsigned integer. One way to do this is to > convert it to a long integer, then mask off the sign bits: > >>> i = long(-1972144115) & 0xFFFFFFFF Ah, thanks. I've never had a need to to bit manipulation in Python (or in anything since IBM S/390 assembler, for that matter), so this is terra incognito to me. That feels much cleaner to me than using an arithmetic addition; and is has the advantages of being shorter and addressing both positive and negative numbers with the same operation, rather than using the if. So, changing my previous code, I now like the short and sweet: >>> import win32api >>> CD_Info = win32api.GetVolumeInformation("D:/") >>> serno = "%X" % (long(CD_Info[1]) & 0xFFFFFFFF) >>> serno '8A73780D' From webmeister8f at web.de Wed Jan 4 20:50:58 2006 From: webmeister8f at web.de (webmeister8f at web.de) Date: Wed, 04 Jan 2006 20:50:58 +0100 Subject: [Tutor] XOR, bytes and strings Message-ID: <511825458@web.de> i'm a totally newbie to python, but i can't resist to try to communicyte with an ICQ-server via my own tool. now i have the problem that i should encrypt a string (the password) by XOR with this bytes: f3, 26, 81, c4, 39, 86, db, 92, 71, a3, b9, e6, 53, 7a, 95, 7c. but although i have searched in the documentation for about an hour, i wasn't able to find out how to manage it. i hope you can help me, tobi. ______________________________________________________________ Verschicken Sie romantische, coole und witzige Bilder per SMS! Jetzt bei WEB.DE FreeMail: http://f.web.de/?mc=021193 From dyoo at hkn.eecs.berkeley.edu Wed Jan 4 21:55:12 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 4 Jan 2006 12:55:12 -0800 (PST) Subject: [Tutor] XOR, bytes and strings In-Reply-To: <511825458@web.de> Message-ID: > i'm a totally newbie to python, but i can't resist to try to communicyte > with an ICQ-server via my own tool. > > now i have the problem that i should encrypt a string (the password) by > XOR with this bytes: f3, 26, 81, c4, 39, 86, db, 92, 71, a3, b9, e6, 53, > 7a, 95, 7c. Hello Tobi, According to: http://www.python.org/doc/ref/bitwise.html I think you're looking for the exclusive or (XOR) bitwise operator '^'. For example: ###### >>> bits = [0, 1] >>> for x in bits: ... for y in bits: ... print x, y, x ^ y ... 0 0 0 0 1 1 1 0 1 1 1 0 ###### Is this where you're getting stuck, or is it somewhere else? Good luck to you. From deepak.gupta at hsbsoft.com Wed Jan 4 12:57:52 2006 From: deepak.gupta at hsbsoft.com (deepak.gupta) Date: Wed, 4 Jan 2006 17:27:52 +0530 Subject: [Tutor] query regarding mysql database backup?? please Help Message-ID: <000c01c61126$1b0b4270$2e01a8c0@hantz.com> Hi, I did my script like this for backing my max_everest_2006 mysql database >>import os > > target_dir = "./backup" > > os.system("mysqldump --add-drop-table -c -u root -pmysql max_everest_2006 > "+target_dir+"/table.bak.sql") root is my user name,mysql is my password,max_everest_2006 is my database name. reply me as soon as possible but it tolds me that does not recognise mysqldump as an internal or external command Please help Thanks deepak gupta -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060104/9edf6544/attachment.htm From deepak.gupta at hsbsoft.com Wed Jan 4 13:00:25 2006 From: deepak.gupta at hsbsoft.com (deepak.gupta) Date: Wed, 4 Jan 2006 17:30:25 +0530 Subject: [Tutor] Fw: query regarding mysql database backup?? please Help Message-ID: <001801c61126$75029210$2e01a8c0@hantz.com> ----- Original Message ----- From: deepak.gupta To: tutor at python.org Sent: Wednesday, January 04, 2006 5:27 PM Subject: query regarding mysql database backup?? please Help Hi, I did my script like this for backing my max_everest_2006 mysql database >>import os > > target_dir = "./backup" > > os.system("mysqldump --add-drop-table -c -u root -pmysql max_everest_2006 > "+target_dir+"table.bak.sql") root is my user name,mysql is my password,max_everest_2006 is my database name. reply me as soon as possible but it tolds me that does not recognise mysqldump as an internal or external command Please help Thanks deepak gupta -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060104/2adbf9cf/attachment.html From john.corry at ntlword.com Wed Jan 4 22:01:42 2006 From: john.corry at ntlword.com (John Corry) Date: Wed, 4 Jan 2006 21:01:42 -0000 Subject: [Tutor] Further help needed! Message-ID: I am using the following code to send a text file to the printer:- import win32api filename = "testprint.txt" fileobj=open (filename, "w") fileobj.write ("This is a test") fileobj.close() win32api.ShellExecute ( 0, "print", filename, None, ".", 0 ) This code works on windows XP + Windows 2000. However it does not work on windows 98SE. I have tried this code on 3 seperate machines with windows 98SE. They all come up with the same error: File "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 310, in RunScript exec codeObject in __main__.__dict__ File "C:\test\Script1.py", line 12, in ? 0 error: (31, 'ShellExecute', 'A device attached to the system is not functioning.') Is there another way to print out a text file on windows 98SE? Do I have to do something different on the windows 98SE machine? Any help would be greatly appreciated. Thanks, John. From 3dbernard at gmail.com Wed Jan 4 22:40:43 2006 From: 3dbernard at gmail.com (Bernard Lebel) Date: Wed, 4 Jan 2006 16:40:43 -0500 Subject: [Tutor] glibc error while Python script runs Message-ID: <61d0e2b40601041340p254a2e40g58f18a42b58ec916@mail.gmail.com> Hello, I'm not sure if it's the appropriate place for this question, but since it happens because of a Python script.... So I have this Python script that runs on render farm nodes. All seem to work well, but at one point I get this crash: rn200.bbfxa.com Wed Jan 4 16:23:36 2006 [jobid: 9]: Get status of all local jobs for this job... *** glibc detected *** double free or corruption: 0x09484d58 *** Aborted So what happens at that particular moment is the script sends a SELECT query to a MySQL database. It collects all the values of a field called Status in a certain table. I just have no idea what to do with this error. Here is the script (1550 lines, I know - just wants to get to functional code before improving the design), if it can help. http://www.bernardlebel.com/scripts/nonxsi/farmclient_2.0_beta04.txt Thanks Bernard From rich.424 at gmail.com Wed Jan 4 22:21:36 2006 From: rich.424 at gmail.com (Richard) Date: Wed, 04 Jan 2006 15:21:36 -0600 Subject: [Tutor] Design questions? Message-ID: <43BC3C60.70906@gmail.com> Hi all! First I want to thank everyone for the help in regards to learning python book and gui's!! Happy New year!! I am just learning Python, and I do have a project in mind but I am not sure where to start on it. I am in the Insurance business so the project is a rate calculator. I have a ton of questions. So bear with me please. The picture I have in my mind and what I have written down too. (Input Clients name) input text box age= spinner Male or Female= radio buttons Tobacco User yes or no Health Here I was thinking about 4-5 options Diabetic yes or no? Amount of Coverage input text box So those would be the input parameters, Here is how it would work (at least in my limited knowledge) The program is going to look at age first then Male or female then, Tobacco, and health after it accumulates all the information then it will have 5- 6 companies to find the rates from.( This will be based on the health too, because as an example if health= poor then there is only one company to look at. This is true if the person is diabetic, only one company. I can use a prefered rate too but then I would have to put in a weight chart. (sigh) So when the program looks at these companies. Let me back up a minute here. To calculate rates is as follows Rate= (Unit cost X amount) + policy fee X modal factor (modal factor is different for monthly,quarterly and semi annual. So then program looks to find the best rate and return the value into 3 box.......Monthly Quarterly and Semi Also now I bet your saying this guy is getting picky, I want to be able to write the quote to a file for future use. So I have allot of the rates in excel now, do I need to build tables with each company? I know this is a big project so I was told by someone. But I am just look for a starting point and then I will go from there. Thanks In Advance for all of your help. Richard From john at fouhy.net Wed Jan 4 22:53:48 2006 From: john at fouhy.net (John Fouhy) Date: Thu, 5 Jan 2006 10:53:48 +1300 Subject: [Tutor] Further help needed! In-Reply-To: References: Message-ID: <5e58f2e40601041353w73d0b474j@mail.gmail.com> [resending 'cause I forgot to address to tutor..] On 05/01/06, John Corry wrote: > This code works on windows XP + Windows 2000. However it does not work on > windows 98SE. I have tried this code on 3 seperate machines with windows > 98SE. They all come up with the same error: > > File > "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", > line 310, in RunScript > exec codeObject in __main__.__dict__ > File "C:\test\Script1.py", line 12, in ? > 0 > error: (31, 'ShellExecute', 'A device attached to the system is not > functioning.') Have you verified that the printer on your Win98 machine does work? For example, create a text file on that computer. In Windows Explorer, right-click on the text file and select 'print' from the context menu. What happens? -- John. From dyoo at hkn.eecs.berkeley.edu Wed Jan 4 22:58:39 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 4 Jan 2006 13:58:39 -0800 (PST) Subject: [Tutor] glibc error while Python script runs In-Reply-To: <61d0e2b40601041340p254a2e40g58f18a42b58ec916@mail.gmail.com> Message-ID: > rn200.bbfxa.com Wed Jan 4 16:23:36 2006 [jobid: 9]: Get status of all > local jobs for this job... > > *** glibc detected *** double free or corruption: 0x09484d58 *** > Aborted Hi Bernard, Ugh. I hate memory allocation bugs. Is it reproducable? Can you run this through a debugger like GDB to find out where we are when this happens? A stack trace will be invaluable because we need to know who to blame. *grin* We need to know if it's Python that's doing this, or if it's MySQLdb, or if it's something else entirely... Just checking up on this: what version of MySQLdb do you have on those systems? I do remember some ugly memory-leaking bugs that haunted ancient versions of MySQLdb, so I want to make sure we're not hitting those. Analyzing this might goes out of Tutor's scope, so you may want to bring this up on a more general forum like comp.lang.python instead. Best of wishes! From carroll at tjc.com Wed Jan 4 23:21:27 2006 From: carroll at tjc.com (Terry Carroll) Date: Wed, 4 Jan 2006 14:21:27 -0800 (PST) Subject: [Tutor] Printing in Windows (was: Further help needed! In-Reply-To: Message-ID: I've edited the subject line to be a little more clear. On Wed, 4 Jan 2006, John Corry wrote: > I am using the following code to send a text file to the printer:- [ snip ] > This code works on windows XP + Windows 2000. However it does not work on > windows 98SE. Well, at least that narrows it down. This continues to befuddle me. I don't know enough about Windows to know the differences that might be here for this purpose. Question: do you need to use the Windows print function, or can you live with printing it yourself (as below)? For example, if you use the ShellExecute approach, it actually causes an application to be invoked for you, which does the printing, just as if you right-clicked on the file and selected "print." ON my system, for example, that will invoke Notepad, which prints it with a heading and a page number at the bottom. But, if you don't care about that, assuming your file is straight text, try the win32print approach from http://tgolden.sc.sabren.com/python/win32_how_do_i/print.html . Here's an attempt that seems to work for me: ------------------------------- import win32print lines_to_print = open("testprint.txt","r").readlines() print_data = '' for line in lines_to_print: print_data=''.join([print_data,line,"\r"]) printer_name = win32print.GetDefaultPrinter() printer = win32print.OpenPrinter(printer_name) print_job = win32print.StartDocPrinter(printer, 1, ("Printer test", None, "RAW")) win32print.WritePrinter(printer, print_data) win32print.EndDocPrinter(printer) win32print.ClosePrinter(printer) ------------------------------- The for-loop is a kludge; my first attempt was something like print_data=open("testprint.txt","r").read() but it turns out my printer needs a carriage return on each line. I suspect that printer handling is more likely to be inconsistent between Win98 and Win/XP than the ShellExecute you were already using, and so this may not work; but it's worth looking into. From alan.gauld at freenet.co.uk Wed Jan 4 23:28:05 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 4 Jan 2006 22:28:05 -0000 Subject: [Tutor] HD/DVD/CD References: Message-ID: <019f01c6117e$21e7f900$0b01a8c0@xp> >> >>> i = long(-1972144115) & 0xFFFFFFFF > > Ah, thanks. I've never had a need to to bit manipulation in Python (or in For anyone interested, my new OS topic has a section on bitwise operations in Python - they are needed for checking stat flags... (see the sig for the link) Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/tutos.htm From alan.gauld at freenet.co.uk Wed Jan 4 23:30:04 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 4 Jan 2006 22:30:04 -0000 Subject: [Tutor] XOR, bytes and strings References: <511825458@web.de> Message-ID: <01a301c6117e$6903dc50$0b01a8c0@xp> > now i have the problem that i should encrypt a string (the password) by > XOR with this bytes: f3, 26, 81, c4, 39, 86, db, 92, 71, a3, b9, e6, 53, > 7a, 95, 7c. > > but although i have searched in the documentation for about an hour, Look for bitwise operators, there is a bitwise xor operator. Its amazing how often the same topic arises in different threads at the same time on this list! You can get a brief into to bitwise operators in my OS topic - look for the sidebar. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/tutos.htm From alan.gauld at freenet.co.uk Wed Jan 4 23:33:06 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 4 Jan 2006 22:33:06 -0000 Subject: [Tutor] query regarding mysql database backup?? please Help References: <000c01c61126$1b0b4270$2e01a8c0@hantz.com> Message-ID: <01ab01c6117e$d56fe730$0b01a8c0@xp> > > os.system("mysqldump --add-drop-table -c -u root -pmysql > > max_everest_2006 > "+target_dir+"/table.bak.sql") > > root is my user name,mysql is my password You shouldn't use root to adnin a database, it leaves you open to all sorts of security holes. And you shouldn't post your root password on a public list, I hope it wasn't really your password or that you changed it immediately! > but it tolds me that does not recognise mysqldump as an internal > or external command I suspect the path needs to be set or more likely you provide the full path of the mysqldump command to os.system... HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From 3dbernard at gmail.com Wed Jan 4 23:31:19 2006 From: 3dbernard at gmail.com (Bernard Lebel) Date: Wed, 4 Jan 2006 17:31:19 -0500 Subject: [Tutor] glibc error while Python script runs In-Reply-To: References: <61d0e2b40601041340p254a2e40g58f18a42b58ec916@mail.gmail.com> Message-ID: <61d0e2b40601041431j1cb5331axc26ab386e045d51a@mail.gmail.com> Hi Danny, See [Bernard] below... On 1/4/06, Danny Yoo wrote: > > > rn200.bbfxa.com Wed Jan 4 16:23:36 2006 [jobid: 9]: Get status of all > > local jobs for this job... > > > > *** glibc detected *** double free or corruption: 0x09484d58 *** > > Aborted > > > Hi Bernard, > > Ugh. I hate memory allocation bugs. > > Is it reproducable? Can you run this through a debugger like GDB to find > out where we are when this happens? A stack trace will be invaluable > because we need to know who to blame. [Bernard] I am quite unfamiliar with Linux in general and a lot more with these tools. Where can I find information about GDB? > *grin* We need to know if it's > Python that's doing this, or if it's MySQLdb, or if it's something else > entirely... > > Just checking up on this: what version of MySQLdb do you have on those > systems? I do remember some ugly memory-leaking bugs that haunted ancient > versions of MySQLdb, so I want to make sure we're not hitting those. [Bernard] I am using 1.2.0, with Python 2.3.4. > > Analyzing this might goes out of Tutor's scope, so you may want to bring > this up on a more general forum like comp.lang.python instead. [Bernard] Okay thanks a lot. I'll check it out, but if you have any idea... :-) Bernard From alan.gauld at freenet.co.uk Wed Jan 4 23:35:48 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 4 Jan 2006 22:35:48 -0000 Subject: [Tutor] Further help needed! References: Message-ID: <01c401c6117f$35a9ff50$0b01a8c0@xp> John, On Win 9X try 1) copying the text file to PRN: using os.system() 2) use the DIS PRINT command using os.system() 3) Try opening the file LPT1: and copying your text to that. All of the above should work. But I no onger have a Win9X box to check... HTH, Alan G. ----- Original Message ----- From: "John Corry" To: Sent: Wednesday, January 04, 2006 9:01 PM Subject: [Tutor] Further help needed! >I am using the following code to send a text file to the printer:- > > import win32api > filename = "testprint.txt" > fileobj=open (filename, "w") > fileobj.write ("This is a test") > fileobj.close() > win32api.ShellExecute ( > 0, > "print", > filename, > None, > ".", > 0 > ) > > This code works on windows XP + Windows 2000. However it does not work on > windows 98SE. I have tried this code on 3 seperate machines with windows > 98SE. They all come up with the same error: > > File > "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", > line 310, in RunScript > exec codeObject in __main__.__dict__ > File "C:\test\Script1.py", line 12, in ? > 0 > error: (31, 'ShellExecute', 'A device attached to the system is not > functioning.') > > Is there another way to print out a text file on windows 98SE? Do I have > to > do something different on the windows 98SE machine? Any help would be > greatly appreciated. > > Thanks, > > John. > > > From carroll at tjc.com Wed Jan 4 23:45:23 2006 From: carroll at tjc.com (Terry Carroll) Date: Wed, 4 Jan 2006 14:45:23 -0800 (PST) Subject: [Tutor] Printing in Windows (was: Further help needed! In-Reply-To: Message-ID: On Wed, 4 Jan 2006, John Corry wrote: > I am using the following code to send a text file to the printer:- > This code works on windows XP + Windows 2000. However it does not work on > windows 98SE. Here's another alternative, which might be even simpler, if it works for you, invoking the good old-fashioned DOS "print" command: import os filename = "testprint.txt" commandline = "print " + filename os.popen(commandline) From dyoo at hkn.eecs.berkeley.edu Wed Jan 4 23:54:20 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 4 Jan 2006 14:54:20 -0800 (PST) Subject: [Tutor] XOR, bytes and strings In-Reply-To: <511913848@web.de> Message-ID: On Wed, 4 Jan 2006, to bifu wrote: > thanks for the help, but my problem is how to use that for a string, Hi To, A character can be translated into an ordinal number by using the ord() function. For example: ###### >>> ord('a') 97 ###### > and those hexadecimals are confusing me, too. Let's talk about this a bit. Do you understand that hexadecimal is a compact way of writing out numbers or bit patterns? For example: ###### >>> 0xff 255 ###### shows us that the bit pattern consisting of eight 1's: 1 1 1 1 1 1 1 1 can be seen as the number 255. (2**7 + 2**6 + ... + 2**1 + 2**0). The reason that 0xff corresponds to that particular bit pattern of all-ones is because of this relationship between bits and hex digits: bits hex ---- --- 0000 0 0001 1 0010 2 0011 3 0100 4 0101 5 0110 6 0111 7 1000 8 1001 9 1010 A 1011 B 1100 C 1101 D 1110 E 1111 F > if it are only bits, it's easy to understand, but how to use XOR for bytes? XOR works for bytes too. Let's define a byte to be a number between 0 and 255, inclusive. Let's play with the pattern: 10101010 (0xaa) and xor it against: 01010101 (0x55) We know what to expect: 11111111 (0xff), but let's try it: ###### >>> 0xaa ^ 0x55 255 ###### We know that 255 corresponds to the bit pattern 11111111, so things appear to be working. If this is the first time you've seen stuff like this, this might seem really weird. Please feel free to ask more questions about this. By the way, another thread this week is doing similar stuff with bitwise arithmetic; you may want to look at it: http://mail.python.org/pipermail/tutor/2006-January/044244.html Good luck! From alan.gauld at freenet.co.uk Thu Jan 5 00:59:08 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 4 Jan 2006 23:59:08 -0000 Subject: [Tutor] Design questions? References: <43BC3C60.70906@gmail.com> Message-ID: <01d701c6118a$da271030$0b01a8c0@xp> Hi Richard, The first thiong is forget the GUI for now it will be much easier to get a command line version working then add a GUI (or web page) later. > (Input Clients name) input text box > age= spinner > Male or Female= radio buttons > Tobacco User yes or no > Health Here I was thinking about 4-5 options > Diabetic yes or no? > > Amount of Coverage input text box Just make all of these raw_input lines initially, you can do some validation for good data after you've captured it. > So those would be the input parameters, Here is how it would work (at > least in my limited knowledge) The program is going to look at age first > then Male or female then, Tobacco, and health after it accumulates all the > information then it will have 5- 6 companies to find the rates from.( This > will be based on the health too, because as an example if health= poor > then there is only one company to look at. This is true if the person is > diabetic, only one company. Try doing it with one company fdirst, then once you get the right rate its easy enough to adapt it to repeat the check for seveal companies. > I can use a prefered rate too but then I would have to put in a weight > chart. (sigh) I'd leave this bit till you get the basic one working with several companies. > So when the program looks at these companies. Let me back up a minute > here. To calculate rates is as follows > > Rate= (Unit cost X amount) + policy fee X modal factor (modal factor is > different for monthly,quarterly and semi annual. Get the calcuilations going first, then worry about repeating them per company and storiung results.... > So then program looks to find the best rate and return the value into 3 > box.......Monthly Quarterly and Semi Just get it to print the result to screen initially. > Also now I bet your saying this guy is getting picky, I want to be able to > write the quote to a file for future use. Yep, you can do that too. > So I have allot of the rates in excel now, do I need to build tables with > each company? You can actually read them from Excel but for now I'd save the Excel data in a CSV file and use the csv module to read them in. But first get it working witrh static data from one company. > I know this is a big project so I was told by someone. But I am just look > for a starting point and then I will go from there. Its actually a very good project because its possible to break it into a lot of small bite size bits. Have fun, ask questions as you go. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From webmeister8f at web.de Thu Jan 5 01:08:08 2006 From: webmeister8f at web.de (to bifu) Date: Thu, 05 Jan 2006 01:08:08 +0100 Subject: [Tutor] XOR, bytes and strings Message-ID: <511993204@web.de> congratulations, you are good in explaining something easily and in a simple english, too! i was able to get it work, thank you, tobi p.s.: sorry for this wrong 'from' field in the other message > 10101010 (0xaa) > > and xor it against: > > 01010101 (0x55) > > We know what to expect: 11111111 (0xff), but let's try it: > > ###### > >>> 0xaa ^ 0x55 > 255 > ###### ______________________________________________________________ Verschicken Sie romantische, coole und witzige Bilder per SMS! Jetzt bei WEB.DE FreeMail: http://f.web.de/?mc=021193 From kent37 at tds.net Thu Jan 5 01:13:37 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 04 Jan 2006 19:13:37 -0500 Subject: [Tutor] glibc error while Python script runs In-Reply-To: <61d0e2b40601041340p254a2e40g58f18a42b58ec916@mail.gmail.com> References: <61d0e2b40601041340p254a2e40g58f18a42b58ec916@mail.gmail.com> Message-ID: <43BC64B1.9080201@tds.net> Bernard Lebel wrote: > Here is the script (1550 lines, I know - just wants to get to > functional code before improving the design), if it can help. Hmm, a common attitude but a bad plan and false economy IMO. In my experience if I keep the code and the design clean as I go, development moves faster because - surprise! - I am always working with clean code whose design fits the current needs. At the end I have clean, well-designed maintainable code. If I ignore design and expect to clean up at the end, I end up with a frustrating mess that I would rather not look at and anyway it's too tangled to fix. And sorry, I don't have a clue what is causing your glibc error... Kent From 3dbernard at gmail.com Thu Jan 5 02:01:46 2006 From: 3dbernard at gmail.com (Bernard Lebel) Date: Wed, 4 Jan 2006 17:01:46 -0800 Subject: [Tutor] glibc error while Python script runs In-Reply-To: <43BC64B1.9080201@tds.net> References: <61d0e2b40601041340p254a2e40g58f18a42b58ec916@mail.gmail.com> <43BC64B1.9080201@tds.net> Message-ID: <61d0e2b40601041701n62775c54m735d2e523ddfd08e@mail.gmail.com> Rest assured, Kent, that I fully understand your point. My experience is quite a lot more limited than yours, and yes I experience this frustrating mess that you talk about and I'm aware that I'm not doing myself any favor with such a design. Sorting this is high on my TODO list..... but not on top I'm affraid.... for now :-) The next project will start off better, I hope :-) Cheers Bernard On 1/4/06, Kent Johnson wrote: > Bernard Lebel wrote: > > Here is the script (1550 lines, I know - just wants to get to > > functional code before improving the design), if it can help. > > Hmm, a common attitude but a bad plan and false economy IMO. In my > experience if I keep the code and the design clean as I go, development > moves faster because - surprise! - I am always working with clean code > whose design fits the current needs. At the end I have clean, > well-designed maintainable code. If I ignore design and expect to clean > up at the end, I end up with a frustrating mess that I would rather not > look at and anyway it's too tangled to fix. > > And sorry, I don't have a clue what is causing your glibc error... > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From mosinu at gmail.com Thu Jan 5 02:42:12 2006 From: mosinu at gmail.com (Will Harris) Date: Wed, 4 Jan 2006 20:42:12 -0500 Subject: [Tutor] code review request Message-ID: <5faf36700601041742q507242date72a505db92e4069@mail.gmail.com> Hoping to get some of you guru types to look over the start of a tool I am working on in python. A working version of the script is at https://mikaru.homeunix.org/py-bin/memberlist.py The site only allows https because I got sick of all the hacked windoze boxes trying to execute crap that I didn't have, so port 80(http) is blocked on my firewall. This lets you add users, divisions (groups) and put the users in divisions(groups). and list the users out by group. I haven't figure out yet how to authenticate the users from the database (postgresql) so any pointers there would be helpful. When a user is added, the password is encrypted in the database using postgresql's encrypt() function so that it would be possible to use another application to access the data. Any pointers or advise on where improvments could be made would be welcome. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060104/0a250621/attachment.html -------------- next part -------------- #!/usr/bin/python print 'Content-type: text/html\n' import psycopg import cgitb import cgi import sys cgitb.enable() def quote(string): if string: return string.replace("'", "\\'") else: return string form = cgi.FieldStorage() conn = psycopg.connect('dbname=XXX user=xxx password=xxxxx') curs = conn.cursor() div_name = quote(form.getvalue('div_name')) div_director = quote(form.getvalue('div_director')) div_email = quote(form.getvalue('div_email')) if not (div_name and div_director and div_email): print 'ALL FIELDS MUST BE COMPLETED' sys.exit() query = """INSERT INTO divisions(div_name, div_director, div_email) VALUES ('%s', '%s', '%s')""" % (div_name, div_director, div_email) curs.execute(query) conn.commit() conn.close() print """ Division added

Division created successfully


Back to the main page """ -------------- next part -------------- #!/usr/bin/python print 'Content-type: text/html\n' import psycopg import cgitb import cgi import sys cgitb.enable() def quote(string): if string: return string.replace("'", "\\'") else: return string form = cgi.FieldStorage() conn = psycopg.connect('dbname=xxxx user=xxxxx password=xxxxx') curs = conn.cursor() name = quote(form.getvalue('name')) address = quote(form.getvalue('address')) email = quote(form.getvalue('email')) password = quote(form.getvalue('password')) username = quote(form.getvalue('username')) div_id = quote(form.getvalue('division')) if not (name and username and password): print 'Please supply name, username, and password' sys.exit() query = """INSERT INTO members(name, address, email, password, username, div_id) VALUES ('%s', '%s', '%s', encrypt('%s', \'f00zball\', \'aes\'), '%s', '%i')""" % (name, address, email, password, username, int(div_id)) curs.execute(query) conn.commit() conn.close() print """ User added

User created successfully


Back to the main page """ -------------- next part -------------- #!/usr/bin/python from mod_python import apache import cgitb; cgitb.enable() import psycopg conn = psycopg.connect('dbname=xxxx user=xxxx password=xxxxx') curs = conn.cursor() print 'Content-type: text/html\n' print """ Member Management

User List

""" curs.execute('SELECT * FROM divisions') rows = curs.dictfetchall() toplevel = [] children = {} for row in rows: division = row['div_id'] print '

%(div_name)s

' % row def format(row): print '

%(div_name)s

' % row try: kids = children[row['div_id']] except KeyError: pass else: print '
' for kid in kids: format(kid) print '
' print '

' for row in toplevel: format(row) print """


Create User | Add Division

""" -------------- next part -------------- #!/usr/bin/python from mod_python import apache import cgitb; cgitb.enable() import psycopg conn = psycopg.connect('dbname=xxxxx user=xxxx password=xxxxx') curs = conn.cursor() print 'Content-type: text/html\n' print """ Member Management

User List

""" curs.execute('SELECT * FROM members') rows = curs.dictfetchall() toplevel = [] children = {} for row in rows: parent_id = row['div_id'] if parent_id is None: toplevel.append(row) else: children.setdefault(parent_id,[]).append(row) def format(row): print '

%(name)s

' % row try: kids = children[row['mem_id']] except KeyError: pass else: print '
' for kid in kids: format(kid) print '
' print '

' for row in toplevel: format(row) print """


Create User | Add Division | List Divisions

""" -------------- next part -------------- #!/usr/bin/python print 'Content-type: text/html\n' import cgitb; cgitb.enable() import psycopg conn = psycopg.connect('dbname=xxxxxx user=xxxx password=xxxxx') curs = conn.cursor() import cgi, sys form = cgi.FieldStorage() #name = form.getvalue('name') print """ Division

Add Division

""" print """ Division Name:

Director:

Division E-Mail List:

Back to the main page' """ -------------- next part -------------- #!/usr/bin/python print 'Content-type: text/html\n' import cgitb; cgitb.enable() import psycopg conn = psycopg.connect('dbname=xxxxxx user=xxxx password=xxxxx') curs = conn.cursor() import cgi, sys form = cgi.FieldStorage() curs.execute('SELECT * FROM divisions') rows = curs.dictfetchall() print """ Adduser

Add user

""" print """ Name:

Address:

E-Mail:

Password:

Username:

Select Division:



Back to the main page' """ -------------- next part -------------- #!/usr/bin/python print 'Content-type: text/html\n' import cgitb; cgitb.enable() import psycopg conn = psycopg.connect('dbname=xxxxxx user=xxxx password=xxxxx') curs = conn.cursor() import cgi, sys form = cgi.FieldStorage() div_id = form.getvalue('div_id') print """ User List

Division Members

""" try: div_id = int(div_id) except: print 'Invalid user ID' sys.exit() curs.execute('SELECT * FROM members WHERE div_id = %i' % div_id) rows = curs.dictfetchall() if not rows: print 'Unknown member ID' sys.exit() for row in rows: division = row['div_id'] print '

%(name)s

' % row print """
Back to the Memberlist | Edit | Division List """ -------------- next part -------------- #!/usr/bin/python print 'Content-type: text/html\n' import cgitb; cgitb.enable() import psycopg conn = psycopg.connect('dbname=xxxxxx user=xxxx password=xxxxx') curs = conn.cursor() import cgi, sys form = cgi.FieldStorage() mem_id = form.getvalue('mem_id') print """ User Info

View User

""" try: mem_id = int(mem_id) except: print 'Invalid user ID' sys.exit() curs.execute('SELECT * FROM members WHERE mem_id = %i' % mem_id) rows = curs.dictfetchall() if not rows: print 'Unknown member ID' sys.exit() row = rows[0] print """

Name: %(name)s

Address: %(address)s
Email: %(email)s
Username: %(username)s


Back to the Memberlist | Edit """ % row From intercodes at gmail.com Thu Jan 5 11:41:22 2006 From: intercodes at gmail.com (Intercodes) Date: Thu, 5 Jan 2006 16:11:22 +0530 Subject: [Tutor] Avoiding repetetive pattern match in re module Message-ID: <37e70e3b0601050241l157406j5a29552f3b22f108@mail.gmail.com> Hello everyone, Iam new to this mailing list as well as python(uptime-3 weeks).Today I learnt about RE from http://www.amk.ca/python/howto/regex/.This one was really helpful. I started working out with few examples on my own. The first one was to collect all the HTML tags used in an HTML file. I wrote this code. ------------------------------ import re file1=open(raw_input("\nEnter The path of the HTML file: "),"r") ans="" while 1: data=file1.readline() if data=="": break ans=ans+data ans1=re.sub(r' .*?',">",ans) # to make tags such as to rel match=re.findall(r'<[^/]?[a-zA-Z]+.*?>',ans1) print match --------------------------------- I get the output but with tags repeated. I want to display all the tags used in a file ,but no repetitions.Say the output to one of the HTML file I got was : "

" Instead of writing a new 'for,if' loop to filter the repetetive tags from the list, is there something that I can add in the re itself to match the pattern only once? Thank You -- Intercodes -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060105/40570287/attachment.htm From bgailer at alum.rpi.edu Thu Jan 5 19:15:14 2006 From: bgailer at alum.rpi.edu (bob) Date: Thu, 05 Jan 2006 10:15:14 -0800 Subject: [Tutor] Avoiding repetetive pattern match in re module In-Reply-To: <37e70e3b0601050241l157406j5a29552f3b22f108@mail.gmail.com> References: <37e70e3b0601050241l157406j5a29552f3b22f108@mail.gmail.com> Message-ID: <7.0.0.16.0.20060105101238.02373868@alum.rpi.edu> At 02:41 AM 1/5/2006, Intercodes wrote: >Hello everyone, > > Iam new to this mailing list as well as python(uptime-3 > weeks).Today I learnt about RE from > http://www.amk.ca/python/howto/regex/.This > one was really helpful. I started working out with few examples on > my own. The first one was to collect all the HTML tags used in an > HTML file. I wrote this code. > >------------------------------ >import re >file1=open(raw_input("\nEnter The path of the HTML file: "),"r") >ans="" >while 1: > data=file1.readline() > if data=="": > break > ans=ans+data Consider a shorter way to grab the entire file: ans = open(raw_input("\nEnter The path of the HTML file: "),"r").read() [snip] -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060105/ac872a37/attachment.htm From info at harrycorry.com Thu Jan 5 10:45:14 2006 From: info at harrycorry.com (John Corry) Date: Thu, 5 Jan 2006 09:45:14 -0000 Subject: [Tutor] Further help needed! In-Reply-To: <5e58f2e40601041353w73d0b474j@mail.gmail.com> Message-ID: Notepad opens and prints the text file. Regards, John. -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org]On Behalf Of John Fouhy Sent: 04 January 2006 21:54 To: Tutor Subject: Re: [Tutor] Further help needed! [resending 'cause I forgot to address to tutor..] On 05/01/06, John Corry wrote: > This code works on windows XP + Windows 2000. However it does not work on > windows 98SE. I have tried this code on 3 seperate machines with windows > 98SE. They all come up with the same error: > > File > "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", > line 310, in RunScript > exec codeObject in __main__.__dict__ > File "C:\test\Script1.py", line 12, in ? > 0 > error: (31, 'ShellExecute', 'A device attached to the system is not > functioning.') Have you verified that the printer on your Win98 machine does work? For example, create a text file on that computer. In Windows Explorer, right-click on the text file and select 'print' from the context menu. What happens? -- John. _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From dyoo at hkn.eecs.berkeley.edu Thu Jan 5 20:27:30 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 5 Jan 2006 11:27:30 -0800 (PST) Subject: [Tutor] Avoiding repetetive pattern match in re module In-Reply-To: <37e70e3b0601050241l157406j5a29552f3b22f108@mail.gmail.com> Message-ID: > Instead of writing a new 'for,if' loop to filter the repetetive tags > from the list, is there something that I can add in the re itself to > match the pattern only once? Hi Intercodes, As far as I know, no: regular expressions don't have the capacity to remember what tags they've matched in previous matching runs. You may find "sets" useful in filtering out duplicates: http://www.python.org/doc/lib/module-sets.html For example: ###### >>> from sets import Set as set >>> set([3, 1, 4, 1, 5, 9, 2, 6]) Set([1, 2, 3, 4, 5, 6, 9]) ###### So you should not need to code much extra logic to do the duplication filtering: sets do this for you already. As an aside, I want to second Alan's recommendation to avoid doing so much string concatenation: it's actually very expensive to do the following: ######################### ans = '' while 1: data=file1.readline() if data=="": break ans=ans+data ######################### >From a technical standpoint, it has "quadratic" complexity in terms of what work the computer is doing. It's related to the mathematical idea that 1 + 2 + 3 + 4 + ... + n = n(n+1). http://en.wikipedia.org/wiki/Triangle_number The string concatenation that the code does above is analogous because it rebuilds larger and larger strings in a similar fashion. Alan's approach, to use file1.read(), sucks up the string in one shot, so it's much less computationally expensive. If you do end up having to concatenate a lot of strings together, use the join() method of lists instead. We can talk about this in more detail if you'd like. From dyoo at hkn.eecs.berkeley.edu Thu Jan 5 20:38:09 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 5 Jan 2006 11:38:09 -0800 (PST) Subject: [Tutor] Avoiding repetetive pattern match in re module In-Reply-To: Message-ID: > >From a technical standpoint, it has "quadratic" complexity in terms of > what work the computer is doing. It's related to the mathematical idea > that 1 + 2 + 3 + 4 + ... + n = n(n+1). > > http://en.wikipedia.org/wiki/Triangle_number Gaa, where did my division sign go? *grin* Sorry, that equation should be: 1 + 2 + ... + n = n(n+1)/2 We can see this: ############################################### >>> import operator >>> def sumUpTo(n): ... return reduce(operator.add, range(n+1)) ... >>> for i in range(10): ... print sumUpTo(i), 'vs', i*(i+1) / 2 ... 0 vs 0 1 vs 1 3 vs 3 6 vs 6 10 vs 10 15 vs 15 21 vs 21 28 vs 28 36 vs 36 45 vs 45 ############################################### > If you do end up having to concatenate a lot of strings together, use the > join() method of lists instead. I should clarify this. I meant to say we should use the string method of join() on lists. For example, if we didn't have file1.read(), we could still do: ### ans = ''.join(file1.readlines()) ### which takes the lines of the file and joins them altogether at once. Good luck! From boyanpn at yahoo.com Thu Jan 5 21:40:10 2006 From: boyanpn at yahoo.com (Boyan R.) Date: Thu, 5 Jan 2006 21:40:10 +0100 Subject: [Tutor] string to integer Message-ID: <18vth7xyh5vqs.8du4u17m8vis.dlg@40tude.net> I need program to convert my string in integer. I remember in BASIC I used val(string) command Is there a Python equivalent ? Here is how it should work: val(7) = 7 val(bbab7) = 7 val(aa7aa) = 7 val( 7) = 7 This last is most important, currently I don't know how to convert string " 7" to integer value 7 in my program (those empty spaces are nasty) btw, I'm working with random numbers, I took 7 just for example :) Also, what are chr() values for enter and (empty) space ? If anybody have a table with chr() values, I'd appreciate if he upload it somewhere. Thanks in advance ! From dyoo at hkn.eecs.berkeley.edu Thu Jan 5 21:51:30 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 5 Jan 2006 12:51:30 -0800 (PST) Subject: [Tutor] Avoiding repetetive pattern match in re module (fwd) Message-ID: ---------- Forwarded message ---------- Date: Fri, 6 Jan 2006 01:53:41 +0530 From: Intercodes To: Danny Yoo Subject: Re: [Tutor] Avoiding repetetive pattern match in re module Hello Danny, Thanks for the response. The read() and join() method worked like charm. I couldn't tune the sets.Set() though. It eliminated duplicates from the list, but I couldn't find a method in sets to print only the set data ( instead I get " Set([data1,data2])" when a set object is printed ) Actually,I have to code an compiler for javascript , so Iam working on the basic stuff of parsing,re's and other stuff. I thought re's could do everything ;) --- Intercodes From Hans.Dushanthakumar at navman.com Thu Jan 5 22:00:36 2006 From: Hans.Dushanthakumar at navman.com (Hans Dushanthakumar) Date: Fri, 6 Jan 2006 10:00:36 +1300 Subject: [Tutor] Disabling a frame in Tkinter Message-ID: <5667508E43F1B740BCFA57FF46E3530002EA028A@nav-akl-exch-c.newton.navman.com> Hi, Is there any way to disable an entire frame (and all its included widgets) in Tkinter. It does not seem to support state=DISABLED. Another Tkinter question: In a listbox, how do I intially set a "selected" item? What I want to do here is have the 1st item in a listbox selected (ie highlighted) when the appln is run. Cheers Hans From dyoo at hkn.eecs.berkeley.edu Thu Jan 5 22:02:03 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 5 Jan 2006 13:02:03 -0800 (PST) Subject: [Tutor] string to integer In-Reply-To: <18vth7xyh5vqs.8du4u17m8vis.dlg@40tude.net> Message-ID: On Thu, 5 Jan 2006, Boyan R. wrote: > I need program to convert my string in integer. > I remember in BASIC I used val(string) command > Is there a Python equivalent ? > > Here is how it should work: > val(7) = 7 > val(bbab7) = 7 > val(aa7aa) = 7 > val( 7) = 7 Hi Boyan, Python has a function that's somewhat similar called the int() function. http://www.python.org/doc/lib/built-in-funcs.html#l2h-39 However, it's a bit more strict about its input than what you may be used to: ###### >>> int(" 5") 5 >>> int("5th") Traceback (most recent call last): File "", line 1, in ? ValueError: invalid literal for int(): 5th ###### To make something like val, we can try to pull out the first bunch of digits we see, and int()ify that. Here's one example of this approach: ############################################################### import re def val(s): """Tries to extract the first integer value we can see from string s.""" result = re.search(r"\d+", s) if not result: raise ValueError, ("invalid literal for val(): %s" % s) return int(result.group(0)) ############################################################### Let's see how this works: ###### >>> val("5th") 5 >>> val("this is 1derful") 1 >>> val("huh?") Traceback (most recent call last): File "", line 1, in ? File "", line 6, in val ValueError: invalid literal for val(): huh? ###### > Also, what are chr() values for enter and (empty) space ? If anybody > have a table with chr() values, I'd appreciate if he upload it > somewhere. Thanks in advance ! I think you're asking: what's the ordinal values that we input into chr() to get the enter and space characters? If so: do you know about the ord() builtin function? http://www.python.org/doc/lib/built-in-funcs.html#l2h-53 Play around with it, and I think you should be able to get the values you are looking for. If you have more questions, please feel free to ask. From bgailer at alum.rpi.edu Thu Jan 5 22:21:55 2006 From: bgailer at alum.rpi.edu (bob) Date: Thu, 05 Jan 2006 13:21:55 -0800 Subject: [Tutor] string to integer In-Reply-To: <18vth7xyh5vqs.8du4u17m8vis.dlg@40tude.net> References: <18vth7xyh5vqs.8du4u17m8vis.dlg@40tude.net> Message-ID: <7.0.0.16.0.20060105131759.0245c948@alum.rpi.edu> At 12:40 PM 1/5/2006, Boyan R. wrote: >I need program to convert my string in integer. >I remember in BASIC I used val(string) command >Is there a Python equivalent ? > >Here is how it should work: >val(7) = 7 >val(bbab7) = 7 >val(aa7aa) = 7 >val( 7) = 7 > >This last is most important, currently I don't know how to >convert string " 7" to integer value 7 in my program >(those empty spaces are nasty) >btw, I'm working with random numbers, I took 7 just for example :) int("7") -> 7 int(" 7") -> 7 int("aa7aa") ->ValueError: invalid literal for int(): aa7aa. You'd need to remove the non-digits using replace or re.sub. >what are chr() values for enter and (empty) space ? >If anybody have a table with chr() values Are you asking what numeric value passed to chr() gives Enter (etc)? If so consult any ASCII Chart. One is at http://www.lookuptables.com/. Of course Enter in ASCII is CR. From adam.jtm30 at gmail.com Thu Jan 5 22:39:47 2006 From: adam.jtm30 at gmail.com (Adam) Date: Thu, 5 Jan 2006 21:39:47 +0000 Subject: [Tutor] Avoiding repetetive pattern match in re module (fwd) In-Reply-To: References: Message-ID: On 05/01/06, Danny Yoo wrote: > > > > ---------- Forwarded message ---------- > Date: Fri, 6 Jan 2006 01:53:41 +0530 > From: Intercodes > To: Danny Yoo > Subject: Re: [Tutor] Avoiding repetetive pattern match in re module > > Hello Danny, > > Thanks for the response. The read() and join() method worked like charm. I > couldn't tune the sets.Set() though. It eliminated duplicates from the > list, > but I couldn't find a method in sets to print only the set data ( instead > I > get " Set([data1,data2])" when a set object is printed ) How about this >>> s = set([1,2,2,3,4,3,3,5]) >>> list(s) [1, 2, 3, 4, 5] Then it just prints out like a list. Also if the objects in the list are strings you can use the .join method to turn it into a string. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060105/c2b4d460/attachment-0001.html From boyanpn at yahoo.com Thu Jan 5 23:13:06 2006 From: boyanpn at yahoo.com (Boyan R.) Date: Thu, 5 Jan 2006 23:13:06 +0100 Subject: [Tutor] string to integer References: <18vth7xyh5vqs.8du4u17m8vis.dlg@40tude.net> Message-ID: <91o6emhv0j14.18jy0xm5uohmi.dlg@40tude.net> Thank you both I think I'll manage to continue with my program :) From alan.gauld at freenet.co.uk Thu Jan 5 23:16:44 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 5 Jan 2006 22:16:44 -0000 Subject: [Tutor] string to integer References: <18vth7xyh5vqs.8du4u17m8vis.dlg@40tude.net> Message-ID: <023301c61245$b64a64d0$0b01a8c0@xp> > Here is how it should work: > val(7) = 7 > val(bbab7) = 7 > val(aa7aa) = 7 > val( 7) = 7 There is no direct equivalent for val() as shpwn above the nearest is int() or float() but that will only work with the first and last examples. (It is a pretty arbitrary functionn to convert aa7aa to 7!) What does val do with a6b5c? You could strip all chars out of the string first: nums = [ch for ch in aString if ch in string.digits] val = int(str(nums)) Which would result in 65 for the example I gave... and that might be what you expect? > This last is most important, currently I don't know how to > convert string " 7" to integer value 7 in my program Just use int() > Also, what are chr() values for enter and (empty) space ? Why would you need chr if you know its an empty space? Just use ' ' directly. if ch = ' ':.... 'enter' is more tricky since it depends on your OS and to some extent your terminal type. For example a TekTronics terminal in an xterm window on Linux gives a different value for Enter than the default vt100 terminal... Again, if we knew why you needed to know we might be able to suggest a suitable mechanism otr alternate technique? > If anybody have a table with chr() values, I'd appreciate > if he upload it somewhere. Just do a google search for ASCII that should find several tables of the value/character combinations. Searching for Unicode will likewise find the Unicode values. chr() is just the string representation of a number. n = ord(c) print chr(ord(c)) should print c since ord() convers the character to a number and chr() converts it back... for n in range(256): print chr(n) will print all of them (although some are unprintable!) HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From srini_iyyer_bio at yahoo.com Thu Jan 5 23:35:16 2006 From: srini_iyyer_bio at yahoo.com (Srinivas Iyyer) Date: Thu, 5 Jan 2006 14:35:16 -0800 (PST) Subject: [Tutor] Excel files to Tab delim files In-Reply-To: <023301c61245$b64a64d0$0b01a8c0@xp> Message-ID: <20060105223516.18954.qmail@web31610.mail.mud.yahoo.com> Dear group, is there any library available that would convert over 2000 .xls files to tab delim text files. I have over 2000 Excel files and I want to convert them to tab delim files, which has become a pain in brain. Thanks Srini __________________________________________ Yahoo! DSL ? Something to write home about. Just $16.99/mo. or less. dsl.yahoo.com From john at fouhy.net Thu Jan 5 23:52:30 2006 From: john at fouhy.net (John Fouhy) Date: Fri, 6 Jan 2006 11:52:30 +1300 Subject: [Tutor] Excel files to Tab delim files In-Reply-To: <20060105223516.18954.qmail@web31610.mail.mud.yahoo.com> References: <023301c61245$b64a64d0$0b01a8c0@xp> <20060105223516.18954.qmail@web31610.mail.mud.yahoo.com> Message-ID: <5e58f2e40601051452m132eb504y@mail.gmail.com> On 06/01/06, Srinivas Iyyer wrote: > Dear group, > is there any library available that would convert > over 2000 .xls files to tab delim text files. Check out pyExcelerator: http://sourceforge.net/projects/pyexcelerator The documentation is a bit light, but basically, if you do: import pyExcelerator workbook = pyExcelerator.parse_xls('myFile.xls') then workbook will be a data structure looking like [(sheet name, { (row, col): data })] ie: a list of tuples, where the first element is the sheet name (eg, u'Sheet 1', u'Sheet 2') and the second element is a dictionary whose keys are (int, int) pairs representing cells (where A1 is (0, 0)) and whose values are the values of the cells. >From that, you should be able to easliy produce a tab delimited file (or anything else you want). The only issue I have had with it is that it reads integers as strings, but I haven't looked at the latest version so this may be fixed, and if you're just writing out to CSV file that won't matter anyway. [be aware, though, that any dates in the spreadsheet will turn into integers] -- John. From john at fouhy.net Fri Jan 6 00:03:18 2006 From: john at fouhy.net (John Fouhy) Date: Fri, 6 Jan 2006 12:03:18 +1300 Subject: [Tutor] Disabling a frame in Tkinter In-Reply-To: <5667508E43F1B740BCFA57FF46E3530002EA028A@nav-akl-exch-c.newton.navman.com> References: <5667508E43F1B740BCFA57FF46E3530002EA028A@nav-akl-exch-c.newton.navman.com> Message-ID: <5e58f2e40601051503v76470c78n@mail.gmail.com> On 06/01/06, Hans Dushanthakumar wrote: > Hi, > Is there any way to disable an entire frame (and all its included > widgets) in Tkinter. It does not seem to support state=DISABLED. Not that I'm aware of... You could try maybe something like this (untested): def setState(widget, state=DISABLED): try: widget.config(state=state) except TclError: # not sure what exception will be raised pass for child in widget.children: setState(child, state=state) > Another Tkinter question: In a listbox, how do I intially set a > "selected" item? What I want to do here is have the 1st item in a > listbox selected (ie highlighted) when the appln is run. Have a look at Fredrik Lundh's Introduction to Tkinter. You can use .selection_clear() to clear the selection and .selection_set(index) to select an item. So, .selection_set(0) will select the first item (just make sure the listbox isn't empty). -- John. From dyoo at hkn.eecs.berkeley.edu Fri Jan 6 01:18:54 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 5 Jan 2006 16:18:54 -0800 (PST) Subject: [Tutor] Excel files to Tab delim files In-Reply-To: <5e58f2e40601051452m132eb504y@mail.gmail.com> Message-ID: > >From that, you should be able to easliy produce a tab delimited file > (or anything else you want). There's even a 'csv' module in Python's Standard Library to handle some of the awkward cases in generating tab-delimited data: http://www.python.org/doc/lib/module-csv.html From kkerwin at insightbb.com Fri Jan 6 02:41:09 2006 From: kkerwin at insightbb.com (Kris Kerwin) Date: Thu, 5 Jan 2006 19:41:09 -0600 Subject: [Tutor] Syntax Error Message-ID: <200601051941.09640.kkerwin@insightbb.com> Hi all, I'm working on a little script, but every time that I run it, it comes back as a syntax error around line 24. However, I can't find anything wrong with it. I figure that maybe I just need another set of eyes. Please take a look at this code, and let me know if you can find anything wrong with it that would cause a syntax error? Thanks in advance! Kris Kerwin -------- Script --------- #!/usr/bin/python import commands import string import os os.chdir('/home/kris/Mail/.inbox.directory') file_string = commands.getoutput('tree -afi') new_file_string = string.replace(file_string, ' ', '_SPACE_') file_list = string.split(new_file_string) # Pop of leading '.' directory. file_list.pop(0) # Pop of directory stats. file_list.pop() index = 1 while index < (len(file_list) + 1): file_name = file_list.pop() new_file_name = string.replace(file_name, '_SPACE_', ' ') unix_name = string.replace(new_file_name, ' ', '\ ' file_type = commands.getoutput('file %s' % unix_name) # << Line 24 if file_type == '%s: ASCII mail text, with very long lines' % new_file_name: file_contents = commands.getoutput('cat %s' % unix_name) print file_contents index = index + 1 else: index = index + 1 os.chdir('/home/kris/bin/gmail_export/') -------------- next part -------------- A non-text attachment was scrubbed... Name: dircat Type: application/x-python Size: 859 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20060105/4e252b71/attachment.bin -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20060105/4e252b71/attachment.pgp From john at fouhy.net Fri Jan 6 02:57:08 2006 From: john at fouhy.net (John Fouhy) Date: Fri, 6 Jan 2006 14:57:08 +1300 Subject: [Tutor] Syntax Error In-Reply-To: <200601051941.09640.kkerwin@insightbb.com> References: <200601051941.09640.kkerwin@insightbb.com> Message-ID: <5e58f2e40601051757v15609ae3h@mail.gmail.com> On 06/01/06, Kris Kerwin wrote: > unix_name = string.replace(new_file_name, ' ', '\ ' Well, there seems to be a closing parenthesis missing on this line :-) By the way --- starting with python2.2 (?), most of the functions in the string module are deprecated in favour of calling methods on strings themeslves. So, instead of saying: > new_file_string = string.replace(file_string, ' ', '_SPACE_') You would say: new_file_string = file_string.replace(' ', '_SPACE_') HTH! -- John. From kkerwin at insightbb.com Fri Jan 6 03:01:22 2006 From: kkerwin at insightbb.com (Kris Kerwin) Date: Thu, 5 Jan 2006 20:01:22 -0600 Subject: [Tutor] Syntax Error In-Reply-To: <5e58f2e40601051757v15609ae3h@mail.gmail.com> References: <200601051941.09640.kkerwin@insightbb.com> <5e58f2e40601051757v15609ae3h@mail.gmail.com> Message-ID: <200601052001.22970.kkerwin@insightbb.com> > On 06/01/06, Kris Kerwin wrote: > > unix_name = string.replace(new_file_name, ' ', '\ ' > > Well, there seems to be a closing parenthesis missing on this line > :-) Oh. :-) > By the way --- starting with python2.2 (?), most of the functions > in the string module are deprecated in favour of calling methods on > strings themeslves. Huh. That does seem to make the code a lot cleaner. Thanks for all of your help! Kris Kerwin On Thursday 05 January 2006 19:57, John Fouhy wrote: > On 06/01/06, Kris Kerwin wrote: > > unix_name = string.replace(new_file_name, ' ', '\ ' > > Well, there seems to be a closing parenthesis missing on this line > :-) > > By the way --- starting with python2.2 (?), most of the functions > in the string module are deprecated in favour of calling methods on > strings themeslves. > > So, instead of saying: > > new_file_string = string.replace(file_string, ' ', '_SPACE_') > > You would say: > > new_file_string = file_string.replace(' ', '_SPACE_') > > HTH! > > -- > John. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From Hans.Dushanthakumar at navman.com Fri Jan 6 03:20:55 2006 From: Hans.Dushanthakumar at navman.com (Hans Dushanthakumar) Date: Fri, 6 Jan 2006 15:20:55 +1300 Subject: [Tutor] Disabling a frame in Tkinter Message-ID: <5667508E43F1B740BCFA57FF46E3530002EA0597@nav-akl-exch-c.newton.navman.com> Thanks John, Yup the code you provided disables all child-widgets: def setState(self, widget, state='disabled'): print type(widget) try: widget.configure(state=state) except Tkinter.TclError: pass for child in widget.winfo_children(): self.setState(child, state=state) Cheers Hans -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of John Fouhy Sent: Friday, 6 January 2006 12:03 p.m. To: tutor at python.org Subject: Re: [Tutor] Disabling a frame in Tkinter On 06/01/06, Hans Dushanthakumar wrote: > Hi, > Is there any way to disable an entire frame (and all its included > widgets) in Tkinter. It does not seem to support state=DISABLED. Not that I'm aware of... You could try maybe something like this (untested): def setState(widget, state=DISABLED): try: widget.config(state=state) except TclError: # not sure what exception will be raised pass for child in widget.children: setState(child, state=state) > Another Tkinter question: In a listbox, how do I intially set a > "selected" item? What I want to do here is have the 1st item in a > listbox selected (ie highlighted) when the appln is run. Have a look at Fredrik Lundh's Introduction to Tkinter. You can use .selection_clear() to clear the selection and .selection_set(index) to select an item. So, .selection_set(0) will select the first item (just make sure the listbox isn't empty). -- John. _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From srini_iyyer_bio at yahoo.com Fri Jan 6 06:19:09 2006 From: srini_iyyer_bio at yahoo.com (Srinivas Iyyer) Date: Thu, 5 Jan 2006 21:19:09 -0800 (PST) Subject: [Tutor] Python upgrade from 2.3 to 2.4 In-Reply-To: <91o6emhv0j14.18jy0xm5uohmi.dlg@40tude.net> Message-ID: <20060106051909.79757.qmail@web31607.mail.mud.yahoo.com> Hi, I might be asking this question out of context. however, eversince I started working with Python, the only mailing list that I used ever is this. So this could be also the other reason that I am posting here. I am currently using Python 2.3 for windows XP. I wanted to use PyExcellerator module. However, this module need the Python to be 2.4. So how should I upgrade from 2.3 to 2.4 without loosing the neat libraries and modules that I have been using on 2.3. these python modules and libraries are backbone for my programming skills. so how could I upgrade without loosing theh binaries and modules (eg. BioPython module, EUtils etc. I downloaded the 2.4 MSI and it was installed in Pyhthon2.4 directoryu and when I started Python2.4 windows GUI, it never came up. I do not the reason. Any suggestion and help please. .. thanks Srini __________________________________________ Yahoo! DSL ? Something to write home about. Just $16.99/mo. or less. dsl.yahoo.com From broek at cc.umanitoba.ca Fri Jan 6 06:41:06 2006 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Thu, 05 Jan 2006 23:41:06 -0600 Subject: [Tutor] string to integer In-Reply-To: <023301c61245$b64a64d0$0b01a8c0@xp> References: <18vth7xyh5vqs.8du4u17m8vis.dlg@40tude.net> <023301c61245$b64a64d0$0b01a8c0@xp> Message-ID: <43BE02F2.9030907@cc.umanitoba.ca> Alan Gauld said unto the world upon 05/01/06 04:16 PM: >>Here is how it should work: >>val(7) = 7 >>val(bbab7) = 7 >>val(aa7aa) = 7 >>val( 7) = 7 > > > There is no direct equivalent for val() as shpwn above the > nearest is int() or float() but that will only work with the first > and last examples. (It is a pretty arbitrary functionn to convert > aa7aa to 7!) > What does val do with a6b5c? > > You could strip all chars out of the string first: > > > nums = [ch for ch in aString if ch in string.digits] > val = int(str(nums)) I'd spell that nums = [ch for ch in aString if ch.isdigit()] Best, Brian vdB From alan.gauld at freenet.co.uk Fri Jan 6 09:41:53 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 6 Jan 2006 08:41:53 -0000 Subject: [Tutor] string to integer References: <18vth7xyh5vqs.8du4u17m8vis.dlg@40tude.net> <023301c61245$b64a64d0$0b01a8c0@xp> <43BE02F2.9030907@cc.umanitoba.ca> Message-ID: <026901c6129d$0b5d30e0$0b01a8c0@xp> >> nums = [ch for ch in aString if ch in string.digits] > I'd spell that > > nums = [ch for ch in aString if ch.isdigit()] Now I had a look for a digit() method but never notoced the isdigit() one. Thanks Brian. Alan G. From p.atmatzidis at gmail.com Fri Jan 6 11:59:41 2006 From: p.atmatzidis at gmail.com (Panagiotis Atmatzidis) Date: Fri, 6 Jan 2006 12:59:41 +0200 Subject: [Tutor] MySQL api does not accept variable. Message-ID: Hello, This is a snip of my code: def sql_listusers(hostname, dbusername, dbpassword, dbbase, dbasename): try: conn = MySQLdb.connect (host = hostname, user = dbusername, passwd = dbpassword, db = dbbase) cursor = conn.cursor () cursor.execute (""" use %s """, (dbasename)) # <--- here is the problem cursor.execute(""" select * from ftpuser; """) rows = cursor.fetchall() print "" print "USER DATABASE LIST" print "------------------" for row in rows: print "%s, %s" % (row[0], row[1]) cursor.close () print "------------------" print "" conn.close () except MySQLdb.Error, e: print "Error %d: %s" % (e.args[0], e.args[1]) sys.exit (1) Everything works fine in this function, except that fact that the (dbasename) variable is not accepted. I don't know why.. this is the syntax I used from the start in order to pass arguments inside to the mysql command line, and everything worked fine until now. The first version of the program did not use a variable there. Is there any obvious mistake that I can't see? Happy new year to the list members, Best Regards -- Panagiotis From Carlo.Capuano at iter.org Fri Jan 6 12:11:27 2006 From: Carlo.Capuano at iter.org (Carlo Capuano) Date: Fri, 6 Jan 2006 12:11:27 +0100 Subject: [Tutor] Excel files to Tab delim files Message-ID: <0F4FBAD10465E047ADB7E8C74B4C189B073D5C@de-iws-xch01.iter.org> Hi, If you run python on windows, you may also take the control of office (word,excel) and may others tools, for example image you have a mysheet.xls in C import pythoncom, win32com.client,os pythoncom.CoInitializeEx(pythoncom.COINIT_APARTMENTTHREADED) excelapp = win32com.client.gencache.EnsureDispatch("Excel.Application") excelapp.Workbooks.Open(Filename="C:\\mysheet.xls ") excelapp.Range('A1').Select() value = excelapp.ActiveCell.FormulaR1C1 #closing, strong way or the process may stay in the back ground excelapp.ActiveWorkbook.Close(False) excelapp.Quit() del excelapp value contains now what there is in A1, to see the syntax just record a macro on excel and than edit it. Except for the initialization of the Dispatcher the instruction are the same, so you can almost copy and paste. Carlo this work fine in python2.3 too :-) what is ITER? www.iter.org > -----Original Message----- > From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf > Of Srinivas Iyyer > Sent: Thursday, January 05, 2006 11:35 PM > To: tutor at python.org > Subject: [Tutor] Excel files to Tab delim files > > Dear group, > is there any library available that would convert > over 2000 .xls files to tab delim text files. > > I have over 2000 Excel files and I want to convert > them to tab delim files, which has become a pain in > brain. > > Thanks > Srini > > > > __________________________________________ > Yahoo! DSL - Something to write home about. > Just $16.99/mo. or less. > dsl.yahoo.com > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From alan.gauld at freenet.co.uk Fri Jan 6 13:47:53 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 6 Jan 2006 12:47:53 -0000 Subject: [Tutor] MySQL api does not accept variable. References: Message-ID: <027a01c612bf$696f8e90$0b01a8c0@xp> def sql_listusers(hostname, dbusername, dbpassword, dbbase, dbasename): try: conn = MySQLdb.connect (host = hostname, user = dbusername, passwd = dbpassword, db = dbbase) cursor = conn.cursor () cursor.execute (""" use %s """, (dbasename)) # <--- here is the problem > Everything works fine in this function, except that fact that the > (dbasename) variable is not accepted. I don't know why.. What error are you getting. Are you sure the value in dbasename is *exactly* the same as the version that worked with a hard coded value? > version of the program did not use a variable there. Is there any > obvious mistake that I can't see? Given that we can't see what you are passing into the function its hard to tell. On a general note, given that your function claims to list users it would seem reasonable that you could already have a connection to the database and you would want to pass that in rather than do all the connect stuff inside the function. Otherwise you will have to close the database connection before listing the users etc. That seems pretty inconvenient to me. I'd expect the function interface to look more like: def sql_listUsers(dbConnection, dbName): ... Just a thought, Alan G. From kent37 at tds.net Fri Jan 6 14:06:08 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 06 Jan 2006 08:06:08 -0500 Subject: [Tutor] Avoiding repetetive pattern match in re module In-Reply-To: <37e70e3b0601050241l157406j5a29552f3b22f108@mail.gmail.com> References: <37e70e3b0601050241l157406j5a29552f3b22f108@mail.gmail.com> Message-ID: <43BE6B40.7060309@tds.net> Intercodes wrote: > Hello everyone, > > Iam new to this mailing list as well as python(uptime-3 weeks).Today > I learnt about RE from http://www.amk.ca/python/howto/regex/ > .This one was really > helpful. I started working out with few examples on my own. The first > one was to collect all the HTML tags used in an HTML file. > > I get the output but with tags repeated. I want to display all the tags > used in a file ,but no repetitions.Say the output to one of the HTML > file I got was : "


" You might consider Beautiful Soup or another HTML parser to collect the tags. Then use a set to find unique tags. For example (Python 2.4 version), >>> import urllib >>> from BeautifulSoup import BeautifulSoup as BS >>> data = urllib.urlopen('http://www.python.org').read() >>> bs = BS(data) >>> help(bs.fetch) Help on method fetch in module BeautifulSoup: fetch(self, name=None, attrs={}, recursive=True, text=None, limit=None) method of BeautifulSoup.BeautifulSoup instance Extracts a list of Tag objects that match the given criteria. You can specify the name of the Tag and any attributes you want the Tag to have. >>> tags = set(tag.name for tag in bs.fetch()) >>> sorted(tags) ['a', 'b', 'body', 'br', 'center', 'div', 'font', 'form', 'h4', 'head', 'html', 'i', 'img', 'input', 'li', 'link', 'meta', 'p', 'small', 'table', 'td', 'title', 'tr', 'ul'] http://www.crummy.com/software/BeautifulSoup/index.html Kent From p.atmatzidis at gmail.com Fri Jan 6 14:52:51 2006 From: p.atmatzidis at gmail.com (Panagiotis Atmatzidis) Date: Fri, 6 Jan 2006 15:52:51 +0200 Subject: [Tutor] MySQL api does not accept variable. In-Reply-To: <027a01c612bf$696f8e90$0b01a8c0@xp> References: <027a01c612bf$696f8e90$0b01a8c0@xp> Message-ID: Hello, Thank you for the reply. You can browse the entire script code[1]. The truth is that I did not think about it. The speed is acceptable for me, but as you point you out, it does not make much sense. I can't think of the con's and the pro's of keeping open the mysql connection when the script starts and close it when it ends.. except the reply speed and the system resources maybe, but with today's computers (I run this script at a p4 2.6 Ghz 512 RAM with a lot free memory) I don't think that there will be any real difference. But, as a starter I am interested in writing -- so called -- "clean code" and follow the "right way" to do things. Hence if there is a standard practise I'd like to follow it. Thank you for your time, regards [1] http://beast.merseine.nu/files/other/vuhandle-0.1.html On 1/6/06, Alan Gauld wrote: > def sql_listusers(hostname, dbusername, dbpassword, dbbase, dbasename): > try: > conn = MySQLdb.connect (host = hostname, > user = dbusername, > passwd = dbpassword, > db = dbbase) > cursor = conn.cursor () > cursor.execute (""" > use %s """, (dbasename)) # <--- here is the problem > > > > Everything works fine in this function, except that fact that the > > (dbasename) variable is not accepted. I don't know why.. > > What error are you getting. Are you sure the value in dbasename > is *exactly* the same as the version that worked with a hard > coded value? > > > version of the program did not use a variable there. Is there any > > obvious mistake that I can't see? > > Given that we can't see what you are passing into the function its > hard to tell. > > On a general note, given that your function claims to list users it > would seem reasonable that you could already have a connection > to the database and you would want to pass that in rather than > do all the connect stuff inside the function. Otherwise you will > have to close the database connection before listing the users etc. > That seems pretty inconvenient to me. I'd expect the function > interface to look more like: > > def sql_listUsers(dbConnection, dbName): ... > > Just a thought, > > Alan G. > > -- Panagiotis From python at kapitalisten.no Fri Jan 6 15:21:46 2006 From: python at kapitalisten.no (=?iso-8859-1?Q?=D8yvind?=) Date: Fri, 6 Jan 2006 15:21:46 +0100 (CET) Subject: [Tutor] Web-log, not blog Message-ID: <62192.193.71.38.142.1136557306.squirrel@mail.sporck.net> Hello. I am trying to find some Pythonmodules to work with some webserver logs. I have found http://www.mnot.net/python/WebLog/, but it is very old (from 1999). And when I try to serach in Google and so forth, all I get is Python weblogs as in blogs. Do you have some suggestions of other sites about analyzing webtraffic with Python? Thanks in advance -- This email has been scanned for viruses & spam by Decna as - www.decna.no Denne e-posten er sjekket for virus & spam av Decna as - www.decna.no From kent37 at tds.net Fri Jan 6 16:00:28 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 06 Jan 2006 10:00:28 -0500 Subject: [Tutor] Web-log, not blog In-Reply-To: <62192.193.71.38.142.1136557306.squirrel@mail.sporck.net> References: <62192.193.71.38.142.1136557306.squirrel@mail.sporck.net> Message-ID: <43BE860C.8020209@tds.net> ?yvind wrote: > Hello. > > I am trying to find some Pythonmodules to work with some webserver logs. I > have found http://www.mnot.net/python/WebLog/, but it is very old (from > 1999). And when I try to serach in Google and so forth, all I get is > Python weblogs as in blogs. Do you have some suggestions of other sites > about analyzing webtraffic with Python? Googling "+python webserver log analyze" and checking PyPI yielded a few more choices: http://mithrandr.moria.org/code/sisynala/ http://www.phil-schwartz.com/scratchy.spy Kent From alan.gauld at freenet.co.uk Fri Jan 6 16:18:44 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 6 Jan 2006 15:18:44 -0000 Subject: [Tutor] MySQL api does not accept variable. References: <027a01c612bf$696f8e90$0b01a8c0@xp> Message-ID: <027e01c612d4$7c029ab0$0b01a8c0@xp> > I can't think of the con's and the pro's of keeping open > the mysql connection when the script starts and close > it when it ends.. The reasoning is that you want to open the connection at the start of a script do all your processing then close it. In between you might want to add data, create new tables, select data and other thoings, including getting a list of users. Now with your code you would need to close the connection before calling your function then reopen it again to fiunish off the rest of the work. Its OK if your function is only ever used in a single script and is the only access to the database, but if you ever want to get the users in any other program your function is almost unusably inconvenient. > computers (I run this script at a p4 2.6 Ghz 512 RAM with a lot free > memory) I don't think that there will be any real difference. You are quite correct for a single user on a modern PC. But... It would make a difference in a high volume environment with many users (like a web application say), or on an older machine but the real value is when you want to use the function as part of a bigger program that has already opened the connection to the database. Regards, Alan G. From srini_iyyer_bio at yahoo.com Fri Jan 6 18:05:06 2006 From: srini_iyyer_bio at yahoo.com (Srinivas Iyyer) Date: Fri, 6 Jan 2006 09:05:06 -0800 (PST) Subject: [Tutor] IDLE doesn't start in Python 2.4 in windows XP In-Reply-To: Message-ID: <20060106170506.62001.qmail@web31604.mail.mud.yahoo.com> Hi Danny, I was following some of your suggestions in making my IDLE work in Windows XP laptop. (http://mail.python.org/pipermail/tutor/2005-January/034683.html). First, i changed the IDLE shortcut path: from C:\Python24\python.exe TO C:\Python24\python.exe "C:\Python24\Lib\idlelib\idle.pyw" -n Now Idle works but throws up a lot of warning etc. in a seperate black window. ################# Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-background' from theme 'sp'. returning default value: '#ffffff' Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-foreground' from theme 'sp'. returning default value: '#000000' The same content apparently repeatedly printed for 5 times i guess in the same black window. ########################### When I close that window the whole IDLE disappears. Is this the correct way or are there some modifications incorporated now. Looking forward to your input __________________________________________ Yahoo! DSL ? Something to write home about. Just $16.99/mo. or less. dsl.yahoo.com From dyoo at hkn.eecs.berkeley.edu Fri Jan 6 20:10:55 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 6 Jan 2006 11:10:55 -0800 (PST) Subject: [Tutor] IDLE doesn't start in Python 2.4 in windows XP In-Reply-To: <20060106170506.62001.qmail@web31604.mail.mud.yahoo.com> Message-ID: On Fri, 6 Jan 2006, Srinivas Iyyer wrote: > Hi Danny, > > I was following some of your suggestions in making my IDLE work in > Windows XP laptop. > (http://mail.python.org/pipermail/tutor/2005-January/034683.html). Hi Srinivas, That suggestion, to change the desktop shortcut, wasn't mine. *grin* But look near the bottom of that message for my reply about the configHandler problems. What's going on is probably bug 1080387: http://sourceforge.net/tracker/index.php?func=detail&aid=1080387&group_id=5470&atid=105470 If you move off your '.idlerc' in your home directory to somewhere else, IDLE should be able to regenerate its configuration files. From john.corry at ntlword.com Fri Jan 6 21:40:48 2006 From: john.corry at ntlword.com (John Corry) Date: Fri, 6 Jan 2006 20:40:48 -0000 Subject: [Tutor] Nearly there Message-ID: Thanks for all the feedback and help. The good news is that I have managed to get my windows 98 SE machine to print a text file using the follwing code:- import tempfile import win32api filename = tempfile.mktemp (".txt") open (filename, "w").write ("This is a test") win32api.ShellExecute ( 0, "print", filename, None, ".", 0 ) Can anyone understand or tell me why this works but the following code does not:- import win32api filename = "testprint.txt" fileobj=open (filename, "w") fileobj.write ("This is a test") fileobj.close() win32api.ShellExecute ( 0, "print", filename, None, ".", 0 ) The code above gives me the error: (31, 'ShellExecute', 'A device attached to the system is not functioning.') However this code works fine on the windows xp + windows 2k. I am so happy it is like Christmas all over again! Thanks, John. From captnswing at gmx.net Fri Jan 6 23:47:15 2006 From: captnswing at gmx.net (captnswing) Date: Fri, 6 Jan 2006 23:47:15 +0100 Subject: [Tutor] iterate over daterange Message-ID: Hello I have a startdate and an enddate and I want to iterate over all days in between the two .... there doesn't seem to be a range function for dates?!? i.e. currently I am going through integers with something like this: ================================= startdate = datetime.date(2006,1,1) enddate = datetime.date(2006,10,19) for i in range((enddate-startdate).days + 1): currentdate = startdate + datetime.timedelta(days=i) .... ================================= this seems so 'unpythonic', there surely must be a better way, no? thx, -frank From carroll at tjc.com Sat Jan 7 01:08:02 2006 From: carroll at tjc.com (Terry Carroll) Date: Fri, 6 Jan 2006 16:08:02 -0800 (PST) Subject: [Tutor] iterate over daterange In-Reply-To: Message-ID: On Fri, 6 Jan 2006, captnswing wrote: > Hello > I have a startdate and an enddate and I want to iterate over all days > in between the two > > .... there doesn't seem to be a range function for dates?!? Sounds like a good application for a generator: ######################### def daterange(from_date, to_date, step=None): from datetime import timedelta if step is None: step = timedelta(1) yield_date = from_date while yield_date < to_date: yield yield_date yield_date = yield_date+step ######################### To use: ######################### import datetime start = datetime.date(2006,1,6) end = datetime.date(2006,1,13) print " default: one-day step:" for dx in daterange(start,end): print dx print " two-day step:" for dx in daterange(start, end, datetime.timedelta(2)): print dx ######################### prints: default: one-day step: 2006-01-06 2006-01-07 2006-01-08 2006-01-09 2006-01-10 2006-01-11 2006-01-12 two-day step: 2006-01-06 2006-01-08 2006-01-10 2006-01-12 From carroll at tjc.com Sat Jan 7 01:23:35 2006 From: carroll at tjc.com (Terry Carroll) Date: Fri, 6 Jan 2006 16:23:35 -0800 (PST) Subject: [Tutor] Nearly there In-Reply-To: Message-ID: This is itching at me, too. On Fri, 6 Jan 2006, John Corry wrote: > Can anyone understand or tell me why this works but the following code does > not:- > > import win32api > filename = "testprint.txt" > fileobj=open (filename, "w") > fileobj.write ("This is a test") > fileobj.close() > win32api.ShellExecute ( > 0, > "print", > filename, > None, > ".", > 0 > ) I'm wondering if ShellExecute needs a full path to find it under W98. Try this; add to the top of your code: import os.path and change your ShellExecute to this: win32api.ShellExecute ( 0, "print", os.path.abspath(filename), None, ".", 0 ) I have no idea if this will work; and the error message you're getting, > The code above gives me the error: (31, 'ShellExecute', 'A device attached > to the system is not functioning.') doesn't seem to indicate it, but it's one less thing. I'd love to know the answer when you get it. From mail.roma1 at gmail.com Sat Jan 7 04:05:23 2006 From: mail.roma1 at gmail.com (Ivan Furone) Date: Sat, 7 Jan 2006 04:05:23 +0100 Subject: [Tutor] Python upgrade from 2.3 to 2.4 Message-ID: <6122a57a0601061905o245169f9p@mail.gmail.com> Hello Srinivas, You can install both versions on the same platform,in separate directories,and start them individually as any other else application.Obviously each one will rely on the modules with which was coming when installed.(And,if you installed further extensions,they will work properly with the installation corresponding to the version of Python that they were designed to work correctly for.).If you need even one module alone that requires a new installation,i suggest to clean install in spite of updrading.(unless you have disk space problems most of the time.) Basically,this is the reason for which I suggest to clean install the new version,then install the new stuff packing it within its directories;and to keep the old ones alone,where you installed them,with the old version.Another point:if you need,adjust your PATH in order to point to your favourite version the more conveniently. My configuration : Python 2.3.5 Enthought Edition in C:\PYTHON23; Python 2.4 (with wxPython,BOAConstructor) in C:\py24 (sic!) Sorry,I only use IDLE on Linux,so I'm unaware of this strange behaviour of its on Windows,but I would review that the same,if I only knew what Windows version you are using and the build number of the Python version (the third number after 2.4) Cheers Ivan -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060107/e41c2c67/attachment.html From john.corry at ntlword.com Sat Jan 7 11:57:26 2006 From: john.corry at ntlword.com (John Corry) Date: Sat, 7 Jan 2006 10:57:26 -0000 Subject: [Tutor] Nearly there In-Reply-To: Message-ID: Terry, Your suggestion works. It also works consistently if you fully define the path of 'filename'. eg filename = "c:/test/testprint.txt" You are right, shell execute seems to need the full path name with windows 98SE. It is strange that it does not need the full path for win xp + win 2k. Onto my next problem. My text file is printing out in portrait. Is there any instruction that I can use so that notepad prints it in landscape? Thanks, John. -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org]On Behalf Of Terry Carroll Sent: 07 January 2006 00:24 To: tutor at python.org Subject: Re: [Tutor] Nearly there This is itching at me, too. On Fri, 6 Jan 2006, John Corry wrote: > Can anyone understand or tell me why this works but the following code does > not:- > > import win32api > filename = "testprint.txt" > fileobj=open (filename, "w") > fileobj.write ("This is a test") > fileobj.close() > win32api.ShellExecute ( > 0, > "print", > filename, > None, > ".", > 0 > ) I'm wondering if ShellExecute needs a full path to find it under W98. Try this; add to the top of your code: import os.path and change your ShellExecute to this: win32api.ShellExecute ( 0, "print", os.path.abspath(filename), None, ".", 0 ) I have no idea if this will work; and the error message you're getting, > The code above gives me the error: (31, 'ShellExecute', 'A device attached > to the system is not functioning.') doesn't seem to indicate it, but it's one less thing. I'd love to know the answer when you get it. _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From alan.gauld at freenet.co.uk Sat Jan 7 12:51:01 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 7 Jan 2006 11:51:01 -0000 Subject: [Tutor] Nearly there References: Message-ID: <02ab01c61380$a1c34b30$0b01a8c0@xp> I'm also curious, although not surprised - since this is why I tend not to try to print using the API!, but another possibility is that Win98 doesn't recognise the dot shortcut for a path. You may need to fill in the explicit path info: > win32api.ShellExecute ( > 0, > "print", > os.path.abspath(filename), > None, > ".", <--- try the full path here too. > 0 > ) HTH, Alan G. ----- Original Message ----- From: "Terry Carroll" To: Sent: Saturday, January 07, 2006 12:23 AM Subject: Re: [Tutor] Nearly there > This is itching at me, too. > > On Fri, 6 Jan 2006, John Corry wrote: > >> Can anyone understand or tell me why this works but the following code >> does >> not:- >> >> import win32api >> filename = "testprint.txt" >> fileobj=open (filename, "w") >> fileobj.write ("This is a test") >> fileobj.close() >> win32api.ShellExecute ( >> 0, >> "print", >> filename, >> None, >> ".", >> 0 >> ) > > I'm wondering if ShellExecute needs a full path to find it under W98. > > Try this; add to the top of your code: > > import os.path > > and change your ShellExecute to this: > > win32api.ShellExecute ( > 0, > "print", > os.path.abspath(filename), > None, > ".", > 0 > ) > > > I have no idea if this will work; and the error message you're getting, > >> The code above gives me the error: (31, 'ShellExecute', 'A device >> attached >> to the system is not functioning.') > > doesn't seem to indicate it, but it's one less thing. > > I'd love to know the answer when you get it. > > > From kent37 at tds.net Sat Jan 7 15:15:54 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 07 Jan 2006 09:15:54 -0500 Subject: [Tutor] iterate over daterange In-Reply-To: References: Message-ID: <43BFCD1A.8080503@tds.net> captnswing wrote: > Hello > I have a startdate and an enddate and I want to iterate over all days > in between the two > > .... there doesn't seem to be a range function for dates?!? > > i.e. currently I am going through integers with something like this: > > ================================= > startdate = datetime.date(2006,1,1) > enddate = datetime.date(2006,10,19) > > for i in range((enddate-startdate).days + 1): > currentdate = startdate + datetime.timedelta(days=i) > .... > ================================= > > this seems so 'unpythonic', there surely must be a better way, no? currentdate = datetime.date(2006,1,1) enddate = datetime.date(2006,1,19) while currentdate <= enddate: print currentdate currentdate += datetime.timedelta(days=1) seems a little better to me. Gustavo Niemeyer's dateutil package includes very flexible recurrence rules - see http://labix.org/python-dateutil#head-470fa22b2db72000d7abe698a5783a46b0731b57 Kent From kent37 at tds.net Sat Jan 7 15:23:00 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 07 Jan 2006 09:23:00 -0500 Subject: [Tutor] Python upgrade from 2.3 to 2.4 In-Reply-To: <20060106051909.79757.qmail@web31607.mail.mud.yahoo.com> References: <20060106051909.79757.qmail@web31607.mail.mud.yahoo.com> Message-ID: <43BFCEC4.9040603@tds.net> Srinivas Iyyer wrote: > So how should I upgrade from 2.3 to 2.4 without > loosing the neat libraries and modules that I have > been using on 2.3. these python modules and libraries > are backbone for my programming skills. so how could I > upgrade without loosing theh binaries and modules (eg. > BioPython module, EUtils etc. You will have to re-install the modules for Python 2.4. The two installations are independent - they each have their own set of installed modules. If the module includes binary files, make sure you get a version of the module compiled for Python 2.4. If the module contains only Python files then the same release will work for both Python versions. Kent From jjk_saji at yahoo.com Sun Jan 8 13:03:40 2006 From: jjk_saji at yahoo.com (John Joseph) Date: Sun, 8 Jan 2006 12:03:40 +0000 (GMT) Subject: [Tutor] IndexError: list index out of range [ Program work fine , but gives this message , guidance requested ] Message-ID: <20060108120340.50082.qmail@web34804.mail.mud.yahoo.com> Hi All I am trying to find out the duplicates in a list , as for beginning I wanted to compare the adjacent elements in list , for this purpose I wrote a script for checking the adjacent elements in a list, if same , it prints the result that , the adjacent numbers are same , it not it will print adjacent numbers are same My program works , but at the end of the program execution it throws error ?Traceback (most recent call last): File "arrayduplinital.py", line 27, in ? if seats[j] <> seats[j+1]: IndexError: list index out of range? I tried my best to find the logic , why this error is coming , I was not able to find the reason , I request your guidance for the reason for this error and how to avoid it I am adding the code which I wrote for this program ************************************************************************************** """ find duplicates in a list (1) Sort the array (2) counter i = 0 j = 0 (3) for j <= length if seats[j] <> seats[j+1] ==> print value j and j+1 are not same else ===> print value j , j +1 are same """ seats = [] i = 0 length = int(raw_input("Enter The Lenght of the array : ")) while i < length: num = int(raw_input("Enter the Seats : ")) seats.append(num) i += 1 print seats seats.sort() j = 0 for j in range(length): if seats[j] <> seats[j+1]: print " The Seat", j , "And the seat", j+1 , "value, which are", seats[j]," and", seats[j+1], "are not same" else: print "The Seats ",j ,"And the seats", j+1, "Values,", seats[j], "and", seats[j+1], "are same" ~ ___________________________________________________________ To help you stay safe and secure online, we've developed the all new Yahoo! Security Centre. http://uk.security.yahoo.com From guillermo.fernandez.castellanos at gmail.com Sun Jan 8 13:23:06 2006 From: guillermo.fernandez.castellanos at gmail.com (Guillermo Fernandez Castellanos) Date: Sun, 08 Jan 2006 13:23:06 +0100 Subject: [Tutor] IndexError: list index out of range [ Program work fine , but gives this message , guidance requested ] In-Reply-To: <20060108120340.50082.qmail@web34804.mail.mud.yahoo.com> References: <20060108120340.50082.qmail@web34804.mail.mud.yahoo.com> Message-ID: <43C1042A.7030006@gmail.com> Hi, Look at this: >>> i=[1,2,3] >>> i[len(i)] Traceback (most recent call last): File "", line 1, in ? IndexError: list index out of range This means that I have tried to access an element that is out of the list, in this case i[3], that is, the 4th element of the list. You are doing the same. You do a j in range(len(seats)) and then you are accessing your list with seats[j] and seats[j+1]. What happens when j = len(seats)-1 and you call seats[j+1]? :-) It happens indeed the same that in the example I gave you first. Hope it helps. Good luck, G John Joseph wrote: > Hi All > I am trying to find out the duplicates in a list > , as for beginning I wanted to compare the adjacent > elements in list , for this purpose I wrote a script > for checking the adjacent elements in a list, if same > , it prints the result that , the adjacent numbers are > same , it not it will print adjacent numbers are > same > My program works , but at the end of > the program execution it throws error > > ?Traceback (most recent call last): > File "arrayduplinital.py", line 27, in ? > if seats[j] <> seats[j+1]: > IndexError: list index out of range? > > I tried my best to find the logic > , why this error is coming , I was not able to find > the reason , I request your guidance for the reason > for this error and how to avoid it > I am adding the code which I wrote for > this program > > ************************************************************************************** > """ > find duplicates in a list > (1) Sort the array > (2) counter > i = 0 > j = 0 > (3) for j <= length > if seats[j] <> seats[j+1] ==> print > value j and j+1 are not same > else ===> print value j , j > +1 are same > > """ > > seats = [] > i = 0 > length = int(raw_input("Enter The Lenght of the array > : ")) > > while i < length: > num = int(raw_input("Enter the Seats : ")) > seats.append(num) > i += 1 > print seats > > seats.sort() > > j = 0 > for j in range(length): > if seats[j] <> seats[j+1]: > print " The Seat", j , "And the seat", > j+1 , "value, which are", seats[j]," and", seats[j+1], > "are not same" > else: > print "The Seats ",j ,"And the seats", > j+1, "Values,", seats[j], "and", seats[j+1], "are > same" > ~ > > > > > > ___________________________________________________________ > To help you stay safe and secure online, we've developed the all new Yahoo! Security Centre. http://uk.security.yahoo.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From jjk_saji at yahoo.com Sun Jan 8 13:36:57 2006 From: jjk_saji at yahoo.com (John Joseph) Date: Sun, 8 Jan 2006 12:36:57 +0000 (GMT) Subject: [Tutor] IndexError: list index out of range [ Program work fine , but gives this message , guidance requested ] In-Reply-To: <43C1042A.7030006@gmail.com> Message-ID: <20060108123657.73521.qmail@web34814.mail.mud.yahoo.com> --- Guillermo Fernandez Castellanos wrote: > Hi, > > Look at this: > >>> i=[1,2,3] > >>> i[len(i)] > Traceback (most recent call last): > File "", line 1, in ? > IndexError: list index out of range > > > This means that I have tried to access an element > that is out of the > list, in this case i[3], that is, the 4th element of > the list. > > You are doing the same. You do a > j in range(len(seats)) > and then you are accessing your list with seats[j] > and seats[j+1]. What > happens when j = len(seats)-1 and you call > seats[j+1]? :-) > > It happens indeed the same that in the example I > gave you first. > > Hope it helps. Good luck, > Thanks for the advice But I need to display the results What should I do in the for loop for this message to go my for loop is as for j in range(length) : if seats[j] <> seats[j+1]: print " The Seat", j , "And the seat", j+1 , "value, which are", seats[j]," and", seats[j+1], "are not same" else: print "The Seats ",j ,"And the seats", j+1, "Values,", seats[j], "and", seats[j+1], "are same" Thanks Joseph John ___________________________________________________________ Yahoo! Exclusive Xmas Game, help Santa with his celebrity party - http://santas-christmas-party.yahoo.net/ From john.corry at ntlword.com Sun Jan 8 14:48:32 2006 From: john.corry at ntlword.com (John Corry) Date: Sun, 8 Jan 2006 13:48:32 -0000 Subject: [Tutor] Landscape Printing Message-ID: Hi, My text file is printing out in portrait. Is there any instruction that I can use so that notepad prints it in landscape? Thanks, John. From broek at cc.umanitoba.ca Sun Jan 8 22:03:52 2006 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Sun, 08 Jan 2006 15:03:52 -0600 Subject: [Tutor] IndexError: list index out of range [ Program work fine , but gives this message , guidance requested ] In-Reply-To: <20060108123657.73521.qmail@web34814.mail.mud.yahoo.com> References: <20060108123657.73521.qmail@web34814.mail.mud.yahoo.com> Message-ID: <43C17E38.9090100@cc.umanitoba.ca> John Joseph said unto the world upon 08/01/06 06:36 AM: > --- Guillermo Fernandez Castellanos > wrote: > > >>Hi, >> >>Look at this: >> >>> i=[1,2,3] >> >>> i[len(i)] >>Traceback (most recent call last): >> File "", line 1, in ? >>IndexError: list index out of range >> >> >>This means that I have tried to access an element >>that is out of the >>list, in this case i[3], that is, the 4th element of >>the list. >> >>You are doing the same. You do a >>j in range(len(seats)) >>and then you are accessing your list with seats[j] >>and seats[j+1]. What >>happens when j = len(seats)-1 and you call >>seats[j+1]? :-) >> >>It happens indeed the same that in the example I >>gave you first. >> >>Hope it helps. Good luck, >> > > > Thanks for the advice > But I need to display the results > What should I do in the for loop for this message > to go > my for loop is as > > for j in range(length) : > if seats[j] <> seats[j+1]: > print " The Seat", j , "And the seat", > j+1 , "value, which are", seats[j]," and", seats[j+1], > "are not same" > else: > print "The Seats ",j ,"And the seats", > j+1, "Values,", seats[j], "and", seats[j+1], "are > same" > Thanks > Joseph John Joseph, I think Guillermo has already given you the answer :-). But, I'll make it more explicit. I'll also do a rather more. My intent is to give you some idea of how you can go about incrementally improving your code. The code you posted is doing something like: >>> a_list = [7,8,7] >>> for index in range(len(a_list)): print index, a_list[index] print index + 1, len(a_list), a_list[index + 1] 0 7 1 3 8 1 8 2 3 7 2 7 3 3 Traceback (most recent call last): File "", line 3, in -toplevel- print index + 1, len(a_list), a_list[index + 1] IndexError: list index out of range Examine the output. When the iteration hits the last member of the list (when it gets to the final element of range(len(a_list)), there is no next element of the list, so the request to print the next element doesn't work. The list length is 3, so I get the same exception as if I'd done: >>> a_list[3] Traceback (most recent call last): File "", line 1, in -toplevel- a_list[3] IndexError: list index out of range directly. That suggests *not* asking for an iteration which uses up the list -- leave a next element and the code will work: >>> for index in range(len(a_list) - 1): # Note the difference print index, a_list[index] print index + 1, len(a_list), a_list[index + 1] 0 7 1 3 8 1 8 2 3 7 >>> Of course, as you pointed out in your OP, right now, even with this fix, you will only be testing for sequential duplicates. My test list a_list = [7,8,7] has dupes, but your approach won't find them. Warning: I'm going to go into a number of issues that you might not yet entirely understand. If I lose you, don't worry; just ask about it. Let's both fix the requirement that the duplicates be sequential and start putting the code into functions. Consider this: >>> def dupe_detector_1(sequence): for item in sequence: if sequence.count(item) > 1: print "%s is duplicated!" %item >>> dupe_detector_1(a_list) 7 is duplicated! 7 is duplicated! >>> OK, that might be better, as we can find non-sequential duplicates. But, there are two problems. 1) The duplication warning is duplicated :-) and 2) >>> a_tuple = (4,3,4) >>> dupe_detector_1(a_tuple) Traceback (most recent call last): File "", line 1, in -toplevel- dupe_detector_1(a_tuple) File "", line 3, in dupe_detector_1 if sequence.count(item) > 1: AttributeError: 'tuple' object has no attribute 'count' >>> The function signature seems to indicate it will work for all sequences, but it chokes on tuples. The second problem is easy to fix: >>> def dupe_detector_2(sequence): # coerce to a list as lists have count methods. sequence = list(sequence) for item in sequence: if sequence.count(item) > 1: print "%s is duplicated!" %item >>> dupe_detector_2((1,1,2)) 1 is duplicated! 1 is duplicated! >>> 1 down, 1 to go. >>> def dupe_detector_3(sequence): sequence = list(sequence) seen_dupes = [] for item in sequence: if item in seen_dupes: # if it is there, we already know it is duplicated continue elif sequence.count(item) > 1: print "%s is duplicated!" %item seen_dupes.append(item) >>> dupe_detector_3(a_list) 7 is duplicated! >>> That's much better :-) There remain 2 things I'd want to do differently. First, I'd separate the print logic from the detection logic: >>> def dupe_detector_4(sequence): '''returns a list of items in sequence that are duplicated''' sequence = list(sequence) seen_dupes = [] for item in sequence: if item in seen_dupes: # if it is there, we already know it is duplicated continue elif sequence.count(item) > 1: seen_dupes.append(item) return seen_dupes >>> big_list = [1,42,3,4,2,3,54,6,7,3,45,6,4,32,43,5,32,4,4,42,3,42,3] >>> dupes_in_big_list = dupe_detector_4(big_list) >>> dupes_in_big_list [42, 3, 4, 6, 32] OK, you might say "fine, but I *wanted* an on-screen report". Let's do that this way: >>> def print_dupe_report(sequence): '''prints a report of items in sequence that are duplicated''' dupes = dupe_detector_4(sequence) dupes.sort() for d in dupes: print "%s was duplicated" %d >>> print_dupe_report(big_list) 3 was duplicated 4 was duplicated 6 was duplicated 32 was duplicated 42 was duplicated >>> The advantage of this is you might well want to do what dupe_detector_4 does without the screen output. Making the function have a smaller job makes it easier to reuse in other contexts. The last thing is a bit subtle. Say I had a sequence of length 10**6 where most items were duplicated. dupe_detector_4 has to iterate over the entire long sequence, and continually hit the continue clause as it will have seen the item already. This last version will fix that, too: >>> def dupe_detector_5(sequence): '''returns a list of items in sequence that are duplicated''' sequence = list(sequence) seen_dupes = [] for item in set(sequence): # Note the difference if sequence.count(item) > 1: seen_dupes.append(item) return seen_dupes >>> dupes_in_big_list = dupe_detector_5(big_list) >>> dupes_in_big_list [32, 3, 4, 6, 42] >>> We no longer need the continue clause, as converting to set ensures we won't ever deal with the same item twice: >>> set((1,1,1,2,2,2,2,2,3,4,4,5)) set([1, 2, 3, 4, 5]) And, preventing us from dealing with the same item twice is what makes this better. To see that, consider: >>> def iteration_comparison(sequence): list_count = 0 set_count = 0 for i in list(sequence): list_count += 1 for i in set(sequence): set_count += 1 print list_count, set_count >>> iteration_comparison((1,2,3,4)) 4 4 >>> iteration_comparison((1,2,3,4,1,2,3,4,1,2,3,4,5,1,2,3,4,1,2,3,4)) 21 5 >>> For sequences with a lot of duplication, the set version (as in dupe_detector_5) has to iterate over far fewer items. That'll be quicker. OK, I hope most of that made sense. Best, Brian vdB From carroll at tjc.com Mon Jan 9 00:19:17 2006 From: carroll at tjc.com (Terry Carroll) Date: Sun, 8 Jan 2006 15:19:17 -0800 (PST) Subject: [Tutor] Python on Windows: any way to access shortcut's info? Message-ID: I would like to know the name of the shortcut (link, I think, in Unix parlance) from which a python program is being invoked. I'd also like to be able to access the directory where the shortcut lives. Toy example: here's a directory structure: C:\ test\ argtest\ arga.py argb.py testdir\ argc.py arga.py contains: import sys,os print "ARGS:", sys.argv print "WD:", os.getcwd() raw_input() # just to keep the window open argb.py and argc.py are both shortcuts to arga.py When I run arga.py (e.g., by double-clicking on it, I get, as expected: ARGS: ['C:\\test\\argtest\\arga.py'] WD: C:\test\argtest When I run argb.py, I get the same thing. I'd hoped (but didn't really expect) sys.argv would be ['C:\\test\\argtest\\argb.py'] . When I run argc.py, same thing. In this case, I'd hoped sys.argv would be ['C:\\test\\argtest\\testdir\\argc.py']; and os.getcwd() would have given back 'C:\test\argtest\testdir'. Why do I care? Well, I'd like to set up a directory where the shortcut and all its files will live. I'd hoped keying off of the shortcut name might be an easy way to do this. I suspect I'm out of luck: my guess is that windows does all the lookup of what the shortcut points to, and then launches the file pointed to; and by the time Python gets control, the shortcut information is long gone. Anyone know for sure? From kent37 at tds.net Mon Jan 9 04:20:52 2006 From: kent37 at tds.net (Kent Johnson) Date: Sun, 08 Jan 2006 22:20:52 -0500 Subject: [Tutor] Python on Windows: any way to access shortcut's info? In-Reply-To: References: Message-ID: <43C1D694.7020106@tds.net> Terry Carroll wrote: > I would like to know the name of the shortcut (link, I think, in Unix > parlance) from which a python program is being invoked. I'd also like to > be able to access the directory where the shortcut lives. You can set the command line arguments and working directory for a shortcut by opening the properties window on the shortcut, at least in Win2k. So for example in the properties for argc.py just add 'C:\\test\\argtest\\testdir\\argc.py to the "Target" field and set the "Start in" field to 'C:\\test\\argtest\\testdir' If arga.py imports any packages in argtest\ you will have to add that dir to sys.path somehow (many options for this). Kent > > Toy example: here's a directory structure: > > C:\ > test\ > argtest\ > arga.py > argb.py > testdir\ > argc.py > > arga.py contains: > > import sys,os > print "ARGS:", sys.argv > print "WD:", os.getcwd() > raw_input() # just to keep the window open > > argb.py and argc.py are both shortcuts to arga.py > > When I run arga.py (e.g., by double-clicking on it, I get, as expected: > > ARGS: ['C:\\test\\argtest\\arga.py'] > WD: C:\test\argtest > > > When I run argb.py, I get the same thing. I'd hoped (but didn't really > expect) sys.argv would be ['C:\\test\\argtest\\argb.py'] . > > When I run argc.py, same thing. In this case, I'd hoped sys.argv would be > ['C:\\test\\argtest\\testdir\\argc.py']; and os.getcwd() would have given > back 'C:\test\argtest\testdir'. > > Why do I care? > > Well, I'd like to set up a directory where the shortcut and all its > files will live. I'd hoped keying off of the shortcut name might be an > easy way to do this. > > I suspect I'm out of luck: my guess is that windows does all the lookup of > what the shortcut points to, and then launches the file pointed to; and by > the time Python gets control, the shortcut information is long gone. > Anyone know for sure? > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From Oyvind.Dale.Sporck at intility.com Mon Jan 9 09:23:26 2006 From: Oyvind.Dale.Sporck at intility.com (=?iso-8859-1?Q?=D8yvind_Dale_Sp=F8rck?=) Date: Mon, 9 Jan 2006 09:23:26 +0100 Subject: [Tutor] Web-log, not blog Message-ID: <4F6A4CDF835E2849942371ACE74D21B196FEDE@e55-cust1-003.intilitycust1.intility.local> Hello and thank you for your help. Scratchy seems like a really good product... Have a nice day, ?yvind ?yvind wrote: > Hello. > > I am trying to find some Pythonmodules to work with some webserver logs. I > have found http://www.mnot.net/python/WebLog/, but it is very old (from > 1999). And when I try to serach in Google and so forth, all I get is > Python weblogs as in blogs. Do you have some suggestions of other sites > about analyzing webtraffic with Python? Googling "+python webserver log analyze" and checking PyPI yielded a few more choices: http://mithrandr.moria.org/code/sisynala/ http://www.phil-schwartz.com/scratchy.spy Kent --------------------------------------------------------------------- The information contained in this message may be CONFIDENTIAL and is intended for the addressee only. Any unauthorised use, dissemination of the information or copying of this message is prohibited. If you are not the addressee, please notify the sender immediately by return e-mail and delete this message. Thank you. Intility -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060109/6997d2fe/attachment.html From jjk_saji at yahoo.com Mon Jan 9 10:47:49 2006 From: jjk_saji at yahoo.com (John Joseph) Date: Mon, 9 Jan 2006 09:47:49 +0000 (GMT) Subject: [Tutor] IndexError: list index out of range [ Program work fine , but gives this message , guidance requested ] In-Reply-To: <43C17E38.9090100@cc.umanitoba.ca> Message-ID: <20060109094749.13726.qmail@web34804.mail.mud.yahoo.com> Hi Brian It was a excellent tutorial, Thanks a lot for the advice I got my concepts of def of functions , sort functions , count , cleared for me I was able to do and understand all the function example , except ?item_comparison? function I get the error for set >>> set((1,1,1,2,2,2,2,2,3,4,4,5)) Traceback (most recent call last): File "", line 1, in ? NameError: name 'set' is not defined my python versrion is Python 2.3.4 (#1, Nov 4 2004, 14:06:56) [GCC 3.4.2 20041017 (Red Hat 3.4.2-6.fc3)] on linux2 THANKS Joseph John --- Brian van den Broek wrote: > John Joseph said unto the world upon 08/01/06 06:36 We no longer need the continue clause, as converting to set ensures we won't ever deal with the same item twice: >>> set((1,1,1,2,2,2,2,2,3,4,4,5)) set([1, 2, 3, 4, 5]) And, preventing us from dealing with the same item twice is what makes this better. To see that, consider: >>> def iteration_comparison(sequence): list_count = 0 set_count = 0 for i in list(sequence): list_count += 1 for i in set(sequence): set_count += 1 print list_count, set_count === message truncated === ___________________________________________________________ Yahoo! Messenger - NEW crystal clear PC to PC calling worldwide with voicemail http://uk.messenger.yahoo.com From carroll at tjc.com Mon Jan 9 17:49:59 2006 From: carroll at tjc.com (Terry Carroll) Date: Mon, 9 Jan 2006 08:49:59 -0800 (PST) Subject: [Tutor] Python on Windows: any way to access shortcut's info? In-Reply-To: <43C1D694.7020106@tds.net> Message-ID: On Sun, 8 Jan 2006, Kent Johnson wrote: > You can set the command line arguments and working directory for a > shortcut by opening the properties window on the shortcut, at least in > Win2k. Thanks, Kent. My question is whether there's any way to get the name and directory of the shortcut from the program. From broek at cc.umanitoba.ca Mon Jan 9 19:48:24 2006 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Mon, 09 Jan 2006 12:48:24 -0600 Subject: [Tutor] IndexError: list index out of range [ Program work fine , but gives this message , guidance requested ] In-Reply-To: <20060109094749.13726.qmail@web34804.mail.mud.yahoo.com> References: <20060109094749.13726.qmail@web34804.mail.mud.yahoo.com> Message-ID: <43C2AFF8.1050707@cc.umanitoba.ca> John Joseph said unto the world upon 09/01/06 03:47 AM: > Hi Brian > It was a excellent tutorial, Thanks a > lot for the advice I got my concepts of def of > functions , sort functions , count , cleared for me > I was able to do and understand all the > function example , except ?item_comparison? function > I get the error for set > >>> set((1,1,1,2,2,2,2,2,3,4,4,5)) > Traceback (most recent call last): > File "", line 1, in ? > NameError: name 'set' is not defined > > my python versrion is > Python 2.3.4 (#1, Nov 4 2004, 14:06:56) > [GCC 3.4.2 20041017 (Red Hat 3.4.2-6.fc3)] on linux2 > THANKS > Joseph John Joseph, glad you found the ramble of use :-) Your python is a version before set was a built-in type (2.4, I believe). So, the iteration_comparison *and* dupe_detector_5 functions won't work for you. 2.3 did include the sets module, though. So, stick from sets import set at the top of the code and it ought work. Best, Brian vdB From dyoo at hkn.eecs.berkeley.edu Mon Jan 9 20:08:38 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 9 Jan 2006 11:08:38 -0800 (PST) Subject: [Tutor] IndexError: list index out of range [ Program work fine , but gives this message , guidance requested ] In-Reply-To: <20060109094749.13726.qmail@web34804.mail.mud.yahoo.com> Message-ID: > lot for the advice I got my concepts of def of functions , sort > functions , count , cleared for me > I was able to do and understand all the > function example , except “item_comparison” function > I get the error for set > >>> set((1,1,1,2,2,2,2,2,3,4,4,5)) > Traceback (most recent call last): > File "", line 1, in ? > NameError: name 'set' is not defined Hi John, For Python 2.3.4, you'll need to add the line: ###### from sets import Set as set ###### before trying to use 'set'. Sets weren't so built into Python until Python 2.4, and so examples that use 'set()' will need that above line to install the proper support. Best of wishes! From kent37 at tds.net Mon Jan 9 21:09:05 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 09 Jan 2006 15:09:05 -0500 Subject: [Tutor] IndexError: list index out of range [ Program work fine , but gives this message , guidance requested ] In-Reply-To: <43C2AFF8.1050707@cc.umanitoba.ca> References: <20060109094749.13726.qmail@web34804.mail.mud.yahoo.com> <43C2AFF8.1050707@cc.umanitoba.ca> Message-ID: <43C2C2E1.8040604@tds.net> Brian van den Broek wrote: > Your python is a version before set was a built-in type (2.4, I > believe). So, the iteration_comparison *and* dupe_detector_5 functions > won't work for you. > > 2.3 did include the sets module, though. > > So, stick > > from sets import set > > at the top of the code and it ought work. The class name is different in 2.3 also. Use from sets import Set as set to get the same spelling as in 2.4. Kent From bgailer at alum.rpi.edu Mon Jan 9 22:56:12 2006 From: bgailer at alum.rpi.edu (bob) Date: Mon, 09 Jan 2006 13:56:12 -0800 Subject: [Tutor] Landscape Printing In-Reply-To: References: Message-ID: <7.0.0.16.0.20060109135058.022fc668@alum.rpi.edu> At 05:48 AM 1/8/2006, John Corry wrote: >Hi, > >My text file is printing out in portrait. Is there any instruction that I >can use so that notepad prints it in landscape? I doubt that you can do this with notepad. Certainly not with ShelleExecute. You could do some fancy footwork with opening notepad, getting its window's handle, and sending keystrokes to navigate the pase setup and print dialogs. Or you'd need an application that can have its print setup globally configured, or one that supports command line options for printing, or one that you communicate with using COM (such as MS Word). From intercodes at gmail.com Tue Jan 10 16:00:30 2006 From: intercodes at gmail.com (Intercodes) Date: Tue, 10 Jan 2006 20:30:30 +0530 Subject: [Tutor] Python RE uses DFA or NFA for string check? Message-ID: <37e70e3b0601100700n2b8c21f7rb9bd649d23dbde79@mail.gmail.com> Hello everyone, This question is just out of curiosity. I am working with this dragon book. >From what I have learnt so far, RE uses either NFA or DFA to check whether the string is accepted or not. (Correct?) So what does the Python's RE module use to check the correctness of the string, NFA or DFA? -- Intercodes -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060110/66100eda/attachment.html From kent37 at tds.net Tue Jan 10 16:14:26 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 10 Jan 2006 10:14:26 -0500 Subject: [Tutor] Python RE uses DFA or NFA for string check? In-Reply-To: <37e70e3b0601100700n2b8c21f7rb9bd649d23dbde79@mail.gmail.com> References: <37e70e3b0601100700n2b8c21f7rb9bd649d23dbde79@mail.gmail.com> Message-ID: <43C3CF52.8020609@tds.net> Intercodes wrote: > Hello everyone, > > This question is just out of curiosity. I am working with this dragon > book. From what I have learnt so far, RE uses either NFA or DFA to check > whether the string is accepted or not. (Correct?) > > So what does the Python's RE module use to check the correctness of the > string, NFA or DFA? You could look at the source. A little digging shows that REs are parsed by sre_parse.parse() which is in Python24\Lib\sre_parse.py on my computer. Kent From tim.peters at gmail.com Tue Jan 10 17:54:57 2006 From: tim.peters at gmail.com (Tim Peters) Date: Tue, 10 Jan 2006 11:54:57 -0500 Subject: [Tutor] Python RE uses DFA or NFA for string check? In-Reply-To: <37e70e3b0601100700n2b8c21f7rb9bd649d23dbde79@mail.gmail.com> References: <37e70e3b0601100700n2b8c21f7rb9bd649d23dbde79@mail.gmail.com> Message-ID: <1f7befae0601100854y6f640b96k97169cc1e0770933@mail.gmail.com> [Intercodes] > This question is just out of curiosity. I am working with this dragon book. > From what I have learnt so far, RE uses either NFA or DFA to check whether > the string is accepted or not. (Correct?) In the world of "computer science" regular expressions, yes. But the things _called_ "regular expressions" in programming languages are generally richer than those. For example, almost all regexp implementations support backreferences, and backreferences allow recognizing languages that computer-science regexps cannot. For example, ^(a*)b+\1$ recognizes strings that begin and end with the same number of a's, separated by one or more b's. It's "the same number" part that's beyond a pure regexp's abilities. > So what does the Python's RE module use to check the correctness of the > string, NFA or DFA? Neither, but it's much closer to NFA than to DFA. Most regexp implementations in most languages supporting such a thing are implemented via backtracking search. Jeffrey Friedl's "Mastering Regular Expressions" is more useful than the dragon book if you want insight into how most programming-language regexp implementations actually work: http://www.oreilly.com/catalog/regex/ To increase confusion ;-), Friedl calls backtracking search "NFA" in that book. From intercodes at gmail.com Tue Jan 10 18:12:18 2006 From: intercodes at gmail.com (Intercodes) Date: Tue, 10 Jan 2006 22:42:18 +0530 Subject: [Tutor] Python RE uses DFA or NFA for string check? In-Reply-To: <1f7befae0601100854y6f640b96k97169cc1e0770933@mail.gmail.com> References: <37e70e3b0601100700n2b8c21f7rb9bd649d23dbde79@mail.gmail.com> <1f7befae0601100854y6f640b96k97169cc1e0770933@mail.gmail.com> Message-ID: <37e70e3b0601100912u758fbea0ga26fd5ead6606083@mail.gmail.com> Thanks Mr.Tim. That was helpful :) On 1/10/06, Tim Peters wrote: > > [Intercodes] > > This question is just out of curiosity. I am working with this dragon > book. > > From what I have learnt so far, RE uses either NFA or DFA to check > whether > > the string is accepted or not. (Correct?) > > In the world of "computer science" regular expressions, yes. But the > things _called_ "regular expressions" in programming languages are > generally richer than those. For example, almost all regexp > implementations support backreferences, and backreferences allow > recognizing languages that computer-science regexps cannot. For > example, > > ^(a*)b+\1$ > > recognizes strings that begin and end with the same number of a's, > separated by one or more b's. It's "the same number" part that's > beyond a pure regexp's abilities. > > > So what does the Python's RE module use to check the correctness of the > > string, NFA or DFA? > > Neither, but it's much closer to NFA than to DFA. Most regexp > implementations in most languages supporting such a thing are > implemented via backtracking search. Jeffrey Friedl's "Mastering > Regular Expressions" is more useful than the dragon book if you want > insight into how most programming-language regexp implementations > actually work: > > http://www.oreilly.com/catalog/regex/ > > To increase confusion ;-), Friedl calls backtracking search "NFA" in that > book. > -- Intercodes -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060110/195b118c/attachment.html From srini_iyyer_bio at yahoo.com Tue Jan 10 19:21:12 2006 From: srini_iyyer_bio at yahoo.com (Srinivas Iyyer) Date: Tue, 10 Jan 2006 10:21:12 -0800 (PST) Subject: [Tutor] How can I make a python script go directory by directory and excecute on files of choice In-Reply-To: <1f7befae0601100854y6f640b96k97169cc1e0770933@mail.gmail.com> Message-ID: <20060110182112.17377.qmail@web31607.mail.mud.yahoo.com> Dear group, I have Excel files that are arranged according to transctions under various name/directories. I found out that all these Excel files are not real OLE based files and some of them are really tab delim files with .XLS appended to the end of file name. I got fooled and started using pyExcelator module. Now I want to write a script that can go to each directory from base directory. Say: my dir path is like this: /home/srini/data/sales - jan05/(1-31).xls - feb05/(1-27).xls - mar05/(1-31).xls How can I ask my script residing in data directory to go to sales and scan all directories and report if .xls files are really Excel files or text files with .xls extension. could any one please help me here. thank you. __________________________________________ Yahoo! DSL ? Something to write home about. Just $16.99/mo. or less. dsl.yahoo.com From slow67 at gmail.com Wed Jan 11 02:25:28 2006 From: slow67 at gmail.com (bill nieuwendorp) Date: Tue, 10 Jan 2006 17:25:28 -0800 Subject: [Tutor] need help with syntax Message-ID: <60fbe7f30601101725i270d6c66xe74e8a537ef1a076@mail.gmail.com> hello all I am new to python and this list has been helpfull so far I am trying to convert binary file to ascii here is the format spec steps = int 4 value = int 4 time = float 4 * steps so in the python terminal terminal i convert it like this >>> import struct >>> import string >>> f = file('binary_file','rb') >>> line = f.readline() >>> L = tuple(line) then to get the steps value i do >>> s = L[:4] >>> s ('\x00', '\x00', '\x00', '\x06') >>> a = string.join( s , '') >>> steps = struct.unpack (">l" , a) >>> steps (6,) and for value >>> v = L[4:8] >>> v ('\x00', '\x00', '\x00', '\x08') >>> b = string.join( v , '') >>> value = struct.unpack (">l" , b) >>> value (8,) for the time value "this is where I need help" I know steps = 6 so >>> 4*6 + 8 >>> 32 >>> t = L[8:32] >>> t ('\x00', '\x00', '\x00', '\x00', '=', '\x08', '\x88', '\x89', '=', '\x88', '\x88 ', '\x89', '=', '\xcc', '\xcc', '\xcd', '>', '\x08', '\x88', '\x89', '>', '*', ' \xaa', '\xab') >>> c = string.join(t , '') >>> time = struct.unpack (">6f", c) >>> time (0.0, 0.033333335071802139, 0.066666670143604279, 0.10000000149011612, 0.1333333 4028720856, 0.1666666716337204) so I was happy to figure this much out what I need is a way to do somthing like this time = struct.unpack(">steps",c) but this does not work because steps is not an integer any help would be great thanks From john at fouhy.net Wed Jan 11 03:16:00 2006 From: john at fouhy.net (John Fouhy) Date: Wed, 11 Jan 2006 15:16:00 +1300 Subject: [Tutor] need help with syntax In-Reply-To: <60fbe7f30601101725i270d6c66xe74e8a537ef1a076@mail.gmail.com> References: <60fbe7f30601101725i270d6c66xe74e8a537ef1a076@mail.gmail.com> Message-ID: <5e58f2e40601101816teae9df2g@mail.gmail.com> On 11/01/06, bill nieuwendorp wrote: Hi Bill, Some comments --- > >>> import struct > >>> import string > >>> f = file('binary_file','rb') > >>> line = f.readline() > >>> L = tuple(line) You can do slicing (things like L[:4]) on strings as well as on lists and tuples. So there is probably no need for you to convert to a tuple --- just work with the lines directly. > >>> s = L[:4] > >>> s > ('\x00', '\x00', '\x00', '\x06') > >>> a = string.join( s , '') You can also do: a = ''.join(s) and this is considered better python these days. > what I need is a way to do somthing like this > > time = struct.unpack(">steps",c) > > but this does not work because steps is not an integer Sounds like you want string substitutions.. You can read about them here: http://python.org/doc/2.4.2/lib/typesseq-strings.html For instance: >>> steps = 6 >>> ">%s" % steps '>6' HTH! -- John. From slow67 at gmail.com Wed Jan 11 04:48:06 2006 From: slow67 at gmail.com (bill nieuwendorp) Date: Tue, 10 Jan 2006 19:48:06 -0800 Subject: [Tutor] need help with syntax In-Reply-To: <5e58f2e40601101816teae9df2g@mail.gmail.com> References: <60fbe7f30601101725i270d6c66xe74e8a537ef1a076@mail.gmail.com> <5e58f2e40601101816teae9df2g@mail.gmail.com> Message-ID: <60fbe7f30601101948g12a0dc5cha4e83e9cda344522@mail.gmail.com> Hi John thanks for the tips I had a bit of a typo in my first post time = struct.unpack(">steps",c) should read somthing more like time = struct.unpack(">steps+f",c) adding the f to tell structs it is in float format the string substitution seems like it would work but now I cant figure out how I would add the f on the end also this still requires me to reassign 6 to steps isnt this already done here ? >>> s = L[:4] >>> s ('\x00', '\x00', '\x00', '\x06') >>> a = string.join( s , '') >>> steps = struct.unpack (">l" , a) >>> steps (6,) what I would like to do in the end is take the format formula. steps = int 4 value = int 4 time = float 4 * steps and have a python script that will spit out the ascii contents, without me having to assign 6 to steps as that number will change from file to file. From ml.cyresse at gmail.com Wed Jan 11 04:52:23 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Wed, 11 Jan 2006 16:52:23 +1300 Subject: [Tutor] Fwd: need help with syntax In-Reply-To: References: <60fbe7f30601101725i270d6c66xe74e8a537ef1a076@mail.gmail.com> Message-ID: oops, forward to list. ---------- Forwarded message ---------- From: Liam Clarke Date: Jan 11, 2006 4:18 PM Subject: Re: [Tutor] need help with syntax To: bill nieuwendorp On 1/11/06, bill nieuwendorp wrote: > hello all I am new to python and this list has been helpfull so far > > I am trying to convert binary file to ascii > > here is the format spec > > steps = int 4 > value = int 4 > time = float 4 * steps > > so in the python terminal terminal i convert it like this > > > >>> import struct > >>> import string > >>> f = file('binary_file','rb') > >>> line = f.readline() > >>> L = tuple(line) Try this - import struct f = file('binary_file','rb') toUnpack = f.read(4) steps = struct.unpack(">i",toUnpack)[0] floatBytes = steps * 4 furtherUnpack = f.read(4 + floatBytes) #The first 4 for value pattern = ">i%df" % steps data = struct.unpack(pattern, furtherUnpack) value = data[0] time = data[1:] Or probably simpler to do f = file('binary_file','rb') toUnpack = f.read(8) (steps,value) = struct.unpack(">2i",toUnpack) floatBytes = steps * 4 furtherUnpack = f.read(floatBytes) pattern = ">%df" % steps time = struct.unpack(pattern, furtherUnpack) You could then call f.readline() to advance to the next line if needed, although binary data tends not to be line break delimited as such... But I found that using f.read(num_of_bytes) is the best way to do this, especially when the data you're reading is unknown but specified at a known offset. You may also want to have a look at f.seek() and f.tell(), and if the "%d" stuff is unfamiliar you may want to google - 'format string inurl:python.org' Good luck, it's a bit tricky at times*, but it works, I built a simple iPod database parser using f.read() and string substitution for the struct module patterns. Regards, Liam Clarke *Like when your brilliant plan to have objects generate patterns for the data they're working with by checking type founders thanks to shorts. From john at fouhy.net Wed Jan 11 04:52:46 2006 From: john at fouhy.net (John Fouhy) Date: Wed, 11 Jan 2006 16:52:46 +1300 Subject: [Tutor] need help with syntax In-Reply-To: <60fbe7f30601101948g12a0dc5cha4e83e9cda344522@mail.gmail.com> References: <60fbe7f30601101725i270d6c66xe74e8a537ef1a076@mail.gmail.com> <5e58f2e40601101816teae9df2g@mail.gmail.com> <60fbe7f30601101948g12a0dc5cha4e83e9cda344522@mail.gmail.com> Message-ID: <5e58f2e40601101952v655a11e2w@mail.gmail.com> On 11/01/06, bill nieuwendorp wrote: > time = struct.unpack(">steps+f",c) > adding the f to tell structs it is in float format > > the string substitution > seems like it would work but now I cant figure out how I would add the > f on the end Did you read up on string substitution? You can do a few tricks with it, but in its simplest form, it just replaces '%s' with the argument. eg: 'foo%sbar' % 'seven' == 'foosevenbar' Or even: 'x%sy%sz' % ('foo', 'bar') == 'xfooybarz' So, in your case, try something like '>%s+f'. > also this still requires me to reassign 6 to steps > > isnt this already done here ? > > >>> s = L[:4] > >>> s > ('\x00', '\x00', '\x00', '\x06') > >>> a = string.join( s , '') > >>> steps = struct.unpack (">l" , a) > >>> steps > (6,) Yes, although in this case steps is a 1-element tuple. So, steps[0] will give you what you want :-) -- John. From ml.cyresse at gmail.com Wed Jan 11 04:58:56 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Wed, 11 Jan 2006 16:58:56 +1300 Subject: [Tutor] How can I make a python script go directory by directory and excecute on files of choice In-Reply-To: <20060110182112.17377.qmail@web31607.mail.mud.yahoo.com> References: <1f7befae0601100854y6f640b96k97169cc1e0770933@mail.gmail.com> <20060110182112.17377.qmail@web31607.mail.mud.yahoo.com> Message-ID: Hi Srinivas - For walking a directory, you can use os.walk() or os.path.walk(), but I prefer the path module here - http://www.jorendorff.com/articles/python/path/. As for determining if a file is really an .XLS format file or a tab delimited file with .xls on the end, go to www.wotsit.org, have a look at the .XLS specifications; there'll probably be a sequence of identifying bytes you can read to confirm that it's an XLS. Regards, Liam Clarke On 1/11/06, Srinivas Iyyer wrote: > Dear group, > I have Excel files that are arranged according to > transctions under various name/directories. > > I found out that all these Excel files are not real > OLE based files and some of them are really tab delim > files with .XLS appended to the end of file name. I > got fooled and started using pyExcelator module. > > Now I want to write a script that can go to each > directory from base directory. > > Say: my dir path is like this: > > /home/srini/data/sales > - jan05/(1-31).xls > - feb05/(1-27).xls > - mar05/(1-31).xls > > How can I ask my script residing in data directory to > go to sales and scan all directories and report if > .xls files are really Excel files or text files with > .xls extension. > > could any one please help me here. > > thank you. > > > > > __________________________________________ > Yahoo! DSL ? Something to write home about. > Just $16.99/mo. or less. > dsl.yahoo.com > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From logesh at iafrica.com Wed Jan 11 06:28:01 2006 From: logesh at iafrica.com (Logesh Pillay) Date: Wed, 11 Jan 2006 07:28:01 +0200 Subject: [Tutor] declaring list in python Message-ID: <1136957281.8361.7.camel@localhost.localdomain> Hello list I want to declare a list of a specific size as global to some nested function like so def foo (n): A[] (of size n) def foo1 ... The only way I can think to declare the list is to use dummy values: A = [0] * n A = [] * n doesn't work. [] * n = [] I'd prefer not to use dummy values I have no use for. Is there any way? Thanks Logesh Pillay From broek at cc.umanitoba.ca Wed Jan 11 08:48:47 2006 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Wed, 11 Jan 2006 01:48:47 -0600 Subject: [Tutor] declaring list in python In-Reply-To: <1136957281.8361.7.camel@localhost.localdomain> References: <1136957281.8361.7.camel@localhost.localdomain> Message-ID: <43C4B85F.6000803@cc.umanitoba.ca> Logesh Pillay said unto the world upon 10/01/06 11:28 PM: > Hello list > > I want to declare a list of a specific size as global to some nested > function like so Hi Logesh, what problem are you trying to solve by doing this? Knowing that will help generate more useful answers, I suspect. > def foo (n): > A[] (of size n) > def foo1 > ... > > The only way I can think to declare the list is to use dummy values: > A = [0] * n > > A = [] * n doesn't work. [] * n = [] A = [None] * n would be a better way to created an n-placed list of dummy values in Python, I think. > I'd prefer not to use dummy values I have no use for. Is there any way? This is why knowing your problem would be helpful. Built-in Python data structures don't have size limitations that are declared when an instance of the data structure is created. (Python's not C.) There is no way (that I know of) to create an n-placed list save creating a list with n objects. So, I think you will have to either give up on not employing dummy values or give up on creating a list of a fixed length. You could subclass list to create a class with a max. and/or min. length, but I think knowing more about what you want to do would be helpful before getting into that :-) Best, Brian vdB From dyoo at hkn.eecs.berkeley.edu Wed Jan 11 11:46:13 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 11 Jan 2006 02:46:13 -0800 (PST) Subject: [Tutor] need help with syntax In-Reply-To: <60fbe7f30601101725i270d6c66xe74e8a537ef1a076@mail.gmail.com> Message-ID: On Tue, 10 Jan 2006, bill nieuwendorp wrote: > I am trying to convert binary file to ascii > > here is the format spec > > steps = int 4 > value = int 4 > time = float 4 * steps Hi Bill, Ok, that structure seems fairly simple so far. > >>> import struct > >>> import string > >>> f = file('binary_file','rb') > >>> line = f.readline() ^^^^^^^^^^^^ Ah. Don't do this. *grin* If our file is binary, the only safe function we can use to read from such a file is read(). "newlines()" just shouldn't be a concept in binary files: using readline() on a binary file is a major no-no. Imagine what happens if your file only contains ten steps. As a hint: look at ord('\n'). You mentioned earlier that you're expecting an integer, an integer, and then a sequence of float. Don't count bytes if you can help it: let Python's struct.calcsize() do this for you. http://www.python.org/doc/lib/module-struct.html Your machine may align bytes differently than you might expect: it may be best to let the machine handle that for you. Best of wishes to you! From singletoned at gmail.com Wed Jan 11 14:48:11 2006 From: singletoned at gmail.com (Ed Singleton) Date: Wed, 11 Jan 2006 13:48:11 +0000 Subject: [Tutor] How can I make a python script go directory by directory and excecute on files of choice In-Reply-To: References: <1f7befae0601100854y6f640b96k97169cc1e0770933@mail.gmail.com> <20060110182112.17377.qmail@web31607.mail.mud.yahoo.com> Message-ID: <34bb7f5b0601110548h1dbcbca1p@mail.gmail.com> On 11/01/06, Liam Clarke wrote: > Hi Srinivas - > > For walking a directory, you can use os.walk() or os.path.walk(), but > I prefer the path module here - > http://www.jorendorff.com/articles/python/path/. The Path module is excellent, but it's walk still doesn't take into account the depth of the current file in the folder structure. If you need that, I wrote (with Kent's help) a simple script that will take it into account (you need the Path module above for it to work). def traverse(directory, function, depth=0): import path thedir = path.path(directory) for item in thedir.files(): function(item, depth) for item in thedir.dirs(): traverse(item,function, depth+1) It can be used like: def doprint(item, depth): print item traverse(r"C:\Temp", doprint) Hope it's helpful to someone. Ed From benvinger at yahoo.co.uk Wed Jan 11 15:48:44 2006 From: benvinger at yahoo.co.uk (Ben Vinger) Date: Wed, 11 Jan 2006 14:48:44 +0000 (GMT) Subject: [Tutor] extra characters in XML Message-ID: <20060111144845.63304.qmail@web25815.mail.ukl.yahoo.com> Hello all I want to do the following in an XML file: XFile = open(XmlFile,'r') for line in XFile.readlines(): if line.find('') > 0: print line However, it does not work due to extra characters that appear in the XML file. For example if I use the previous code without the if condition, on a console it looks like: < e n d _ t i m e > And if you output that to a text file and open that in a text editor, the text editor shows a square instead of a space in between every character. What is going on? Thanks Ben ___________________________________________________________ Yahoo! Photos ? NEW, now offering a quality print service from just 8p a photo http://uk.photos.yahoo.com From burge.kurt at gmail.com Wed Jan 11 14:04:32 2006 From: burge.kurt at gmail.com (Burge Kurt) Date: Wed, 11 Jan 2006 14:04:32 +0100 Subject: [Tutor] pointers Message-ID: Hi, I f I want to translate C code to Python and have a function like void get_args(int argc, char* argv[], Argument* args) { -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060111/782b914d/attachment.htm From burge.kurt at gmail.com Wed Jan 11 14:19:57 2006 From: burge.kurt at gmail.com (Burge Kurt) Date: Wed, 11 Jan 2006 14:19:57 +0100 Subject: [Tutor] pointers In-Reply-To: References: Message-ID: Sorry for the previous message I did it by mistake.. the function was like below: void get_args(int argc, char* argv[], Argument* args) { //check the amount of the arguments if(argc%2 == 0) { printf("Error, incorrect argument numbers : %d\n",argc); print_help(); exit(1); } ..... ......... } My first question about the pointers here; how can I convert them to Python? And second and may be a little stupid; do I need to define argc how can I get arguments in python ? Thanks in advance, Burge -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060111/337300c3/attachment.html From benvinger at yahoo.co.uk Wed Jan 11 16:49:53 2006 From: benvinger at yahoo.co.uk (Ben Vinger) Date: Wed, 11 Jan 2006 15:49:53 +0000 (GMT) Subject: [Tutor] extra characters in XML In-Reply-To: <20060111144845.63304.qmail@web25815.mail.ukl.yahoo.com> Message-ID: <20060111154953.14981.qmail@web25804.mail.ukl.yahoo.com> Found the following (which solved the problem, though not on the console) at http://www.jorendorff.com/articles/unicode/python.html import codecs # Open a UTF-8 file in read mode infile = codecs.open("infile.txt", "r", "utf-8") # Read its contents as one large Unicode string. text = infile.read() # Close the file. infile.close() The same function is used to open a file for writing; just use "w" (write) or "a" (append) as the second argument. --- Ben Vinger wrote: > Hello all > > I want to do the following in an XML file: > > XFile = open(XmlFile,'r') > for line in XFile.readlines(): > if line.find('') > 0: > print line > > However, it does not work due to extra characters > that > appear in the XML file. For example if I use the > previous code without the if condition, on a console > it looks like: > < e n d _ t i m e > > And if you output that to a text file and open that > in > a text editor, the text editor shows a square > instead > of a space in between every character. What is > going > on? > > Thanks > Ben > > > > > > ___________________________________________________________ > > Yahoo! Photos ? NEW, now offering a quality print > service from just 8p a photo > http://uk.photos.yahoo.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > ___________________________________________________________ Yahoo! Messenger - NEW crystal clear PC to PC calling worldwide with voicemail http://uk.messenger.yahoo.com From kent37 at tds.net Wed Jan 11 17:08:22 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 11 Jan 2006 11:08:22 -0500 Subject: [Tutor] extra characters in XML In-Reply-To: <20060111154953.14981.qmail@web25804.mail.ukl.yahoo.com> References: <20060111154953.14981.qmail@web25804.mail.ukl.yahoo.com> Message-ID: <43C52D76.8080804@tds.net> Ben Vinger wrote: > Found the following (which solved the problem, though > not on the console) at > http://www.jorendorff.com/articles/unicode/python.html > > import codecs > # Open a UTF-8 file in read mode > infile = codecs.open("infile.txt", "r", "utf-8") > # Read its contents as one large Unicode string. > text = infile.read() > # Close the file. > infile.close() > > The same function is used to open a file for writing; > just use "w" (write) or "a" (append) as the second > argument. Ben, Most likely your XML file is 16-bit unicode, not utf-8. When ascii text is represented as unicode, every other byte will be a null byte. That is the extra character that shows up as a space or box depending on who is interpreting it. The utf-8 codec must be swallowing the null bytes. The first line of your XML should show what encoding it is if it is different from utf-8. What is in that line? In your code above, instead of utf-8 try utf_16_be and utf_16_le, one of them should work. Kent > > > --- Ben Vinger wrote: > > >>Hello all >> >>I want to do the following in an XML file: >> >>XFile = open(XmlFile,'r') >>for line in XFile.readlines(): >> if line.find('') > 0: >> print line >> >>However, it does not work due to extra characters >>that >>appear in the XML file. For example if I use the >>previous code without the if condition, on a console >>it looks like: >>< e n d _ t i m e > >>And if you output that to a text file and open that >>in >>a text editor, the text editor shows a square >>instead >>of a space in between every character. What is >>going >>on? >> >>Thanks >>Ben >> >> >> >> >> >> > > ___________________________________________________________ > >>Yahoo! Photos ? NEW, now offering a quality print >>service from just 8p a photo >>http://uk.photos.yahoo.com >>_______________________________________________ >>Tutor maillist - Tutor at python.org >>http://mail.python.org/mailman/listinfo/tutor >> > > > > > > > > ___________________________________________________________ > Yahoo! Messenger - NEW crystal clear PC to PC calling worldwide with voicemail http://uk.messenger.yahoo.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From 3dbernard at gmail.com Wed Jan 11 17:17:40 2006 From: 3dbernard at gmail.com (Bernard Lebel) Date: Wed, 11 Jan 2006 11:17:40 -0500 Subject: [Tutor] pointers In-Reply-To: References: Message-ID: <61d0e2b40601110817o548c15aeidd20f9bf34617f15@mail.gmail.com> Hi Burge, You can access command line argument via sys.argv: import sys print sys.argv This prints a list of the command line arguments. Since argv is a list, it means you can check its length to get the argument count: print len( sys.argv ) There is always at least one argument in this list, if no argument was supplied, then you get an empty string. Hope this helps Bernard On 1/11/06, Burge Kurt wrote: > Sorry for the previous message I did it by mistake.. > the function was like below: > > void get_args(int argc, char* argv[], Argument* args) > { > //check the amount of the arguments > if(argc%2 == 0) > { > printf("Error, incorrect argument numbers : %d\n",argc); > print_help(); > exit(1); > } > > ..... > ......... > } > > My first question about the pointers here; how can I convert them to Python? > > And second and may be a little stupid; do I need to define argc how can I > get arguments in python ? > > Thanks in advance, > > Burge > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From kent37 at tds.net Wed Jan 11 17:30:21 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 11 Jan 2006 11:30:21 -0500 Subject: [Tutor] pointers In-Reply-To: References: Message-ID: <43C5329D.1010408@tds.net> Burge Kurt wrote: > Sorry for the previous message I did it by mistake.. > the function was like below: > > void get_args(int argc, char* argv[], Argument* args) > { > //check the amount of the arguments > if(argc%2 == 0) > { > printf("Error, incorrect argument numbers : %d\n",argc); > print_help(); > exit(1); > } > > ..... > ......... > } > > My first question about the pointers here; how can I convert them to > Python? Python doesn't have pointers in the sense of direct references to memory. Python has very good built in support for higher-level structures than C has. Strings and lists are both built in. As Bernard has pointed out, where a C function might have a count (argc) and a pointer to an array of pointers to strings (char* argv[]), Python uses just a list of strings. I'll guess that Argument* args is a pointer to an array of Argument objects. In Python this would be represented by a list of Argument objects. Use of lists and strings should be covered in any introductory Python tutorial or book; you might find one you like here: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers http://wiki.python.org/moin/IntroductoryBooks Kent > > And second and may be a little stupid; do I need to define argc how can > I get arguments in python ? > > Thanks in advance, > > Burge > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From ds-python-tutor at sidorof.com Wed Jan 11 18:30:04 2006 From: ds-python-tutor at sidorof.com (DS) Date: Wed, 11 Jan 2006 09:30:04 -0800 Subject: [Tutor] CPU Utilization Message-ID: <43C5409C.1090407@sidorof.com> I am implementing a computational cluster and am using a job controller (for want of a better term) that contacts the worker computers, determines how busy they currently are, and then assigns more work if the worker computer is below a certain cpu utilization threshhold. For the cpu threshhold, I've been thinking I'd have the worker computer shell out to perform the top command, parse the results, and report those values to the job controller. Is there a better way, or more pythonic, way to do this? Thanks ds From wescpy at gmail.com Wed Jan 11 19:13:01 2006 From: wescpy at gmail.com (w chun) Date: Wed, 11 Jan 2006 10:13:01 -0800 Subject: [Tutor] pointers In-Reply-To: <43C5329D.1010408@tds.net> References: <43C5329D.1010408@tds.net> Message-ID: <78b3a9580601111013m5feb5509w59ef5484cd9413fb@mail.gmail.com> On 1/11/06, Kent Johnson wrote: > Burge Kurt wrote: > > > > void get_args(int argc, char* argv[], Argument* args) > > > > My first question about the pointers here; how can I convert them to > > Python? > > Python doesn't have pointers in the sense of direct references to > memory. Python has very good built in support for higher-level > structures than C has. Strings and lists are both built in. the main reason why pointers are used in C (and C++) is so that the called function has the ability to modify the object (since it is passed by reference). in Python, references to objects passed in are also "live," meaning that if it is a mutable (modifiable) object, you can manipulate it directly without using the asterisk/star (*). in bernard's example, we've replaced char* argv[] as an argument to main by doing an import of sys and using the argv attribute of the sys module, i.e., sys.argv. to access individual arguments, you would replace something like: for (int i = 0; i < argc; i++) { : ... argv[i] ... : } ... with ... for i in range(len(sys.argv)): : ... sys.argv[i] ... : ... or ... for eachArg in sys.argv: : ... eachArg ... : > I'll guess that Argument* args is a pointer to an array of Argument > objects. In Python this would be represented by a list of Argument objects. it looks like it's a set of variable arguments (varargs). Python has support for this too, and it's one of the rare places you will see asterisks (*) used. we replace "void get_args(int argc, char* argv[], Argument* args)" with "def get_args(*args)". (recall that argv is sys.argv and argc is len(sys.argv).) then to access each extra argument, you would: for eachArg in args: : ... eachArg ... hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2006,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From dyoo at hkn.eecs.berkeley.edu Wed Jan 11 20:09:05 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 11 Jan 2006 11:09:05 -0800 (PST) Subject: [Tutor] pointers In-Reply-To: Message-ID: On Wed, 11 Jan 2006, Burge Kurt wrote: > I f I want to translate C code to Python and have a function like > > void get_args(int argc, char* argv[], Argument* args) > { Hi Burge, Also wanted to note that the Standard Library already contains an argument-parsing library, so you may want to take advantage of it. The library is called 'optparse': http://python.org/doc/lib/module-optparse.html It's something to keep in mind, just in case during your porting effort you have the freedom to reuse the Standard Library. Good luck! From hugonz-lists at h-lab.net Wed Jan 11 20:56:47 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Wed, 11 Jan 2006 13:56:47 -0600 Subject: [Tutor] CPU Utilization In-Reply-To: <43C5409C.1090407@sidorof.com> References: <43C5409C.1090407@sidorof.com> Message-ID: <43C562FF.7060806@h-lab.net> Hi, top is very interactive so it would not be easy at all to parse. I can suggest reading /proc/loadavg if you're in Linux. proc(5) ('man 5 proc') says that /proc/loadavg is The load average numbers give the number of jobs in the run queue averaged over 1, 5 and 15 minutes. They are the same as the load average numbers given by uptime(1) and other programs. It can be easily parsed with split() Hope that helps, Hugo DS wrote: > I am implementing a computational cluster and am using a job controller > (for want of a better term) that contacts the worker computers, > determines how busy they currently are, and then assigns more work if > the worker computer is below a certain cpu utilization threshhold. > > For the cpu threshhold, I've been thinking I'd have the worker computer > shell out to perform the top command, parse the results, and report > those values to the job controller. > > Is there a better way, or more pythonic, way to do this? > > Thanks > > ds > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From ml.cyresse at gmail.com Wed Jan 11 21:48:58 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Thu, 12 Jan 2006 09:48:58 +1300 Subject: [Tutor] need help with syntax In-Reply-To: References: <60fbe7f30601101725i270d6c66xe74e8a537ef1a076@mail.gmail.com> Message-ID: > > You mentioned earlier that you're expecting an integer, an integer, and > then a sequence of float. Don't count bytes if you can help it: let > Python's struct.calcsize() do this for you. > > http://www.python.org/doc/lib/module-struct.html > > Your machine may align bytes differently than you might expect: it may be > best to let the machine handle that for you. Erk, Danny, is of course, right. Perhaps I could rewrite my earlier suggestion as - stepValPattern = ">2i" bytesToRead = struct.calcsize(stepValPattern) bytes = f.read(bytesToRead) (steps, value) = struct.unpack(stepValPattern, bytes) floatPattern = ">%df" % steps bytesToRead = struct.calcsize(floatPattern) bytes = f.read(bytesToRead) floatList = struct.unpack(floatPattern, bytes) f.read() works like following, (rough explanation follows) Let's say you have a 10 byte file - 00 0E A1 DC B3 09 FF AA B1 B2 00 f.read(3) will return 00 0E A1. Your file reference is now pointing at the 4th byte of the file, like so. 00 0E A1 DC B3 09 FF AA B1 B2 00 ...............^ <-current read position So calling f.read(3) again will return DC B3 09 Calling f.tell() will return the curernt read position, which would now be 6, the 7th byte (remembering computers count from 0 up.) f.seek(x) tells Python to move the read position to the xth byte of the file. You can use that with text files. I.E. If you've just called f.readlines(), you can use f.seek(0) to return to the start of the file. Anyway, I digress, but I'm trying to clarify how struct and f.read() work together. So, let's pretend all integers are 4 bytes, ditto all floats, and there's no byte alignment going on whatsoever. (of course, in real life you can't, hence using struct.calcsize()) So, you have a file like so - 03 00 00 00 0A 00 00 00 09 0B 21 CD.... That's step value step number of floats 03 00 00 00| 0A 00 00 00| 09 0B 21 CD.... ^ <-- read pos stepValPattern = ">2i" bytesToRead = struct.calcsize(stepValPattern) #bytesToRead is 8 (idealised ints) bytes = f.read(bytesToRead) At this point, bytes is 03 00 00 00 0A 00 00 00 (Python would show it as a string "\x03\x00\x00\x00\x0A\x00\x00\x00") And your file now looks like this - step value floats 03 00 00 00| 0A 00 00 00| 09 0B 21 CD.... .......................................^ <-- read pos Okay, so now to read the floats. (steps, value) = struct.unpack(stepValPattern, bytes) #Converts 03 00 00 00 0A 00 00 00 to (3, 9) 9 chosen at random #steps equals 3 So now we substitute steps into the floatPattern floatPattern = ">%df" % steps #floatPattern now equals ">3f" which is the same #struct pattern as ">fff" bytesToRead = struct.calcsize(floatPattern) #bytesToRead is 12 bytes = f.read(bytesToRead) floatList = struct.unpack(floatPattern, bytes) Does that make sense? I hope so... but suffice to say - struct.calcsize() ensures cross platform compatibility... I tend not to use the endian identifier unless I'm dealing with a data source that will always, absolutely be a certain endianess, saves having to rejig your patterns for each different platform. And use f.read(x) for binary data. Regards, Liam Clarke From ds-python-tutor at sidorof.com Wed Jan 11 22:29:05 2006 From: ds-python-tutor at sidorof.com (DS) Date: Wed, 11 Jan 2006 13:29:05 -0800 Subject: [Tutor] CPU Utilization In-Reply-To: <43C562FF.7060806@h-lab.net> References: <43C5409C.1090407@sidorof.com> <43C562FF.7060806@h-lab.net> Message-ID: <43C578A1.7060106@sidorof.com> Thanks for your responses. Michael Janssen wrote: >It's perhaps easier to read the information from the /proc filesystem >(this is where top gets it itself). "man proc" tells where the info is >stored (guess: /proc/stat). > > > stat does look in some ways easier. I will say that I found the statistics somewhat baffling, but I'm sure it's all there. Hugo Gonz?lez Monteverde wrote: >Hi, > >top is very interactive so it would not be easy at all to parse. > > > Actually top has a batch mode. This works pretty well. *def* xmlrpc_idlecpu(self): u = commands.getoutput('top -b -n 1') *return* u.split('\n')[2].split(',')[3] >I can suggest reading /proc/loadavg if you're in Linux. > >proc(5) ('man 5 proc') says that /proc/loadavg is > The load average numbers give the number of jobs in > the run queue averaged over 1, 5 and 15 minutes. > They are the same as the load average numbers given > by uptime(1) and other programs. > >It can be easily parsed with split() > > That's an interesting idea to use that. Although if you have big jobs and little jobs you might not know whether you can add another job to that computer or not, because you would necessarily be attempting to derive the utilization from those statistics. Thank you both for your answers. ds From Hans.Dushanthakumar at navman.com Wed Jan 11 23:18:42 2006 From: Hans.Dushanthakumar at navman.com (Hans Dushanthakumar) Date: Thu, 12 Jan 2006 11:18:42 +1300 Subject: [Tutor] Returning multiple values from a script Message-ID: <5667508E43F1B740BCFA57FF46E3530002FC0111@nav-akl-exch-c.newton.navman.com> Hi, Can a script return multiple values to the os? What I have in mind is something like the following: 1) Test.py ------- import sys r = 7 sys.exit(r) # What I really want to do is something along the lines of sys.exit(r, "Hans") 2) Script1.py (This script executes script test.py and prints out its exit code): ---------- import os t = "test.py" res = os.system('"python test.py") print res Thanks, Hans From burge.kurt at gmail.com Wed Jan 11 23:59:44 2006 From: burge.kurt at gmail.com (Burge Kurt) Date: Wed, 11 Jan 2006 23:59:44 +0100 Subject: [Tutor] div_t Message-ID: Hi, What is the usage of div_t in python? I have some unsigned integer variables and want to use ; div_t div_T; div_t div_N; div_t div_B; . . .. Best for all, Burge -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060111/83cccccc/attachment.htm From kent37 at tds.net Thu Jan 12 00:05:36 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 11 Jan 2006 18:05:36 -0500 Subject: [Tutor] Returning multiple values from a script In-Reply-To: <5667508E43F1B740BCFA57FF46E3530002FC0111@nav-akl-exch-c.newton.navman.com> References: <5667508E43F1B740BCFA57FF46E3530002FC0111@nav-akl-exch-c.newton.navman.com> Message-ID: <43C58F40.6090100@tds.net> Hans Dushanthakumar wrote: > Hi, > Can a script return multiple values to the os? Is there a reason why you have to call the second test.py using os.system()? I would write it to be imported and called. test.py ------ def findR(): return 7, 'Hans' script1.py --------- import test res = test.findR() print res Kent > > What I have in mind is something like the following: > > > 1) Test.py > ------- > import sys > > r = 7 > sys.exit(r) > # What I really want to do is something along the lines of sys.exit(r, > "Hans") > > > > 2) Script1.py (This script executes script test.py and prints out its > exit code): > ---------- > import os > > t = "test.py" > res = os.system('"python test.py") > print res From bgailer at alum.rpi.edu Thu Jan 12 00:30:50 2006 From: bgailer at alum.rpi.edu (bob) Date: Wed, 11 Jan 2006 15:30:50 -0800 Subject: [Tutor] div_t In-Reply-To: References: Message-ID: <7.0.0.16.0.20060111152742.01cb7860@alum.rpi.edu> At 02:59 PM 1/11/2006, Burge Kurt wrote: >Hi, > >What is the usage of div_t in python? > >I have some unsigned integer variables and want to use ; > >div_t div_T; >div_t div_N; >div_t div_B; Your question is meaningless to me! Please clarify. div_t is not a Python constant or built_in. div_t div_T; is not a Python expression. Python integers are signed. Does any of this refer to another lannguage? From Hans.Dushanthakumar at navman.com Thu Jan 12 00:37:51 2006 From: Hans.Dushanthakumar at navman.com (Hans Dushanthakumar) Date: Thu, 12 Jan 2006 12:37:51 +1300 Subject: [Tutor] Returning multiple values from a script Message-ID: <5667508E43F1B740BCFA57FF46E3530002FC02A8@nav-akl-exch-c.newton.navman.com> Yes I agree that it'd be cleaner to import the second script and call it. The reason I'm keen to find a alternate method is that I have a whole lot of scripts that were designed to run only as standalone scripts. ie each of these scripts is not a "function" that I could just call from another script. They are all of the format: 1) Test.py ------- import sys sys.exit(5) Now I'm trying to write a master script that'd run each one of these scripts. I'm sure it would have been a lot easier if the scripts were of the following format. Unfortunately they are not.: Test.py ------- import sys Def test(): return(5, "Junk") if __name__ == __main__: test() Well if there is no other way I think I'll have to alter all the scripts to be of the above format. Just wondering if anyone has any suggestions ... Cheers Hans -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Kent Johnson Sent: Thursday, 12 January 2006 12:06 p.m. Cc: Python Tutor Subject: Re: [Tutor] Returning multiple values from a script Hans Dushanthakumar wrote: > Hi, > Can a script return multiple values to the os? Is there a reason why you have to call the second test.py using os.system()? I would write it to be imported and called. test.py ------ def findR(): return 7, 'Hans' script1.py --------- import test res = test.findR() print res Kent > > What I have in mind is something like the following: > > > 1) Test.py > ------- > import sys > > r = 7 > sys.exit(r) > # What I really want to do is something along the lines of sys.exit(r, > "Hans") > > > > 2) Script1.py (This script executes script test.py and prints out its > exit code): > ---------- > import os > > t = "test.py" > res = os.system('"python test.py") > print res _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From slow67 at gmail.com Thu Jan 12 01:29:51 2006 From: slow67 at gmail.com (bill nieuwendorp) Date: Wed, 11 Jan 2006 16:29:51 -0800 Subject: [Tutor] need help with syntax In-Reply-To: References: <60fbe7f30601101725i270d6c66xe74e8a537ef1a076@mail.gmail.com> Message-ID: <60fbe7f30601111629g61236c91ldb132ff4c21bd218@mail.gmail.com> This list is full of people ready to help, I thank you all for the time you have taken to reply. Danny now I see where readline could cause headaches,. Liam thanks for the examples they work great. The endianess will always be in Big Endian (Motorola type) for this format. I see why I should be using Calcsize now, I was not too sure why I might need it before. Now I have to have a try on another bianary format, for practice. Thanks again From kent37 at tds.net Thu Jan 12 02:02:20 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 11 Jan 2006 20:02:20 -0500 Subject: [Tutor] Returning multiple values from a script In-Reply-To: <5667508E43F1B740BCFA57FF46E3530002FC02A8@nav-akl-exch-c.newton.navman.com> References: <5667508E43F1B740BCFA57FF46E3530002FC02A8@nav-akl-exch-c.newton.navman.com> Message-ID: <43C5AA9C.3020702@tds.net> Hans Dushanthakumar wrote: > Yes I agree that it'd be cleaner to import the second script and call > it. > > The reason I'm keen to find a alternate method is that I have a whole > lot of scripts that were designed to run only as standalone scripts. ie > each of these scripts is not a "function" that I could just call from > another script. They are all of the format: > > 1) Test.py > ------- > import sys > > sys.exit(5) > > > Now I'm trying to write a master script that'd run each one of these > scripts. I'm sure it would have been a lot easier if the scripts were of > the following format. Unfortunately they are not.: > > Test.py > ------- > import sys > > Def test(): > return(5, "Junk") > > if __name__ == __main__: > test() > > > Well if there is no other way I think I'll have to alter all the scripts > to be of the above format. Just wondering if anyone has any suggestions ISTM that you have to change all the scripts anyway if you want to return two values...why not change them to call a different function (other than sys.exit) that does what you want? Do the scripts still have to run standalone? For example you could make a module mysys.py: returnedvalue = None def exit(value): global returnedvalue returnedvalue = value Then just edit the scripts to import mysys and call mysys.exit(), run the script with import and get the returnedvalue from mysys. If you want a base hack that I couldn't possibly recommend :-) I suppose you could replace sys.exit() with a function of your own choosing. Something like this should work... >>> import sys >>> returnedvalue = None >>> >>> def mysysexit(value): ... global returnedvalue ... returnedvalue = value ... >>> original_exit = sys.exit # if you need to keep the old value... >>> sys.exit = mysysexit >>> >>> sys.exit(5) # here you can just import the module you want to run >>> returnedvalue 5 Isn't Python wonderful! Kent > ... > > Cheers > Hans > > > -----Original Message----- > From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On > Behalf Of Kent Johnson > Sent: Thursday, 12 January 2006 12:06 p.m. > Cc: Python Tutor > Subject: Re: [Tutor] Returning multiple values from a script > > Hans Dushanthakumar wrote: > >>Hi, >> Can a script return multiple values to the os? > > > Is there a reason why you have to call the second test.py using > os.system()? I would write it to be imported and called. > > test.py > ------ > > def findR(): > return 7, 'Hans' > > > script1.py > --------- > > import test > > res = test.findR() > print res > > Kent > > >>What I have in mind is something like the following: >> >> >>1) Test.py >>------- >>import sys >> >>r = 7 >>sys.exit(r) >># What I really want to do is something along the lines of sys.exit(r, >>"Hans") >> >> >> >>2) Script1.py (This script executes script test.py and prints out its >>exit code): >>---------- >>import os >> >>t = "test.py" >>res = os.system('"python test.py") >>print res > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From kent37 at tds.net Thu Jan 12 02:06:31 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 11 Jan 2006 20:06:31 -0500 Subject: [Tutor] div_t In-Reply-To: References: Message-ID: <43C5AB97.40103@tds.net> Burge Kurt wrote: > Hi, > > What is the usage of div_t in python? > > I have some unsigned integer variables and want to use ; > > div_t div_T; > div_t div_N; > div_t div_B; I guess this is more C code. It doesn't have any Python equivalent - Python doesn't declare variables and doesn't have unsigned integers. You might be interested in the divmod() function: >>> help(divmod) Help on built-in function divmod in module __builtin__: divmod(...) divmod(x, y) -> (div, mod) Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x. >>> divmod(10, 3) (3, 1) You will in general get a better response from this list if you tell us what problem you are trying to solve, rather than showing brief snippets of C. Even better is to attempt a solution in Python and let us see where you get stuck. Have you read any of the tutorials I pointed out? Programming Python is quite different from C and you should try to get the flavor of it. Kent From burge.kurt at gmail.com Thu Jan 12 02:07:26 2006 From: burge.kurt at gmail.com (Burge Kurt) Date: Thu, 12 Jan 2006 02:07:26 +0100 Subject: [Tutor] calloc Message-ID: Hi again (: How can I use calloc in python ? Before computing and processing my data I want to know how many bytes are available? Thanks in advance and best wishes, Burge -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060112/0b550e3a/attachment.htm From Hans.Dushanthakumar at navman.com Thu Jan 12 02:28:28 2006 From: Hans.Dushanthakumar at navman.com (Hans Dushanthakumar) Date: Thu, 12 Jan 2006 14:28:28 +1300 Subject: [Tutor] Returning multiple values from a script Message-ID: <5667508E43F1B740BCFA57FF46E3530002FC047C@nav-akl-exch-c.newton.navman.com> Thanks for your reply Kent. Is it possible to dynamically import a module? The foll snippet of code throws an error "ImportError: No module named testname" t = ["test1.py", "test2.py"] #Actually this list is filled in by a Tkinter Listbox selection. for f in t: testname = f[:-3] import "%s"%(testname) print testname.run_test() Any other means of importing dynamically? -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Kent Johnson Sent: Thursday, 12 January 2006 2:02 p.m. Cc: Python Tutor Subject: Re: [Tutor] Returning multiple values from a script Hans Dushanthakumar wrote: > Yes I agree that it'd be cleaner to import the second script and call > it. > > The reason I'm keen to find a alternate method is that I have a whole > lot of scripts that were designed to run only as standalone scripts. > ie each of these scripts is not a "function" that I could just call > from another script. They are all of the format: > > 1) Test.py > ------- > import sys > > sys.exit(5) > > > Now I'm trying to write a master script that'd run each one of these > scripts. I'm sure it would have been a lot easier if the scripts were > of the following format. Unfortunately they are not.: > > Test.py > ------- > import sys > > Def test(): > return(5, "Junk") > > if __name__ == __main__: > test() > > > Well if there is no other way I think I'll have to alter all the > scripts to be of the above format. Just wondering if anyone has any > suggestions ISTM that you have to change all the scripts anyway if you want to return two values...why not change them to call a different function (other than sys.exit) that does what you want? Do the scripts still have to run standalone? For example you could make a module mysys.py: returnedvalue = None def exit(value): global returnedvalue returnedvalue = value Then just edit the scripts to import mysys and call mysys.exit(), run the script with import and get the returnedvalue from mysys. If you want a base hack that I couldn't possibly recommend :-) I suppose you could replace sys.exit() with a function of your own choosing. Something like this should work... >>> import sys >>> returnedvalue = None >>> >>> def mysysexit(value): ... global returnedvalue ... returnedvalue = value ... >>> original_exit = sys.exit # if you need to keep the old value... >>> sys.exit = mysysexit >>> >>> sys.exit(5) # here you can just import the module you want to run >>> returnedvalue 5 Isn't Python wonderful! Kent From Hans.Dushanthakumar at navman.com Thu Jan 12 02:34:52 2006 From: Hans.Dushanthakumar at navman.com (Hans Dushanthakumar) Date: Thu, 12 Jan 2006 14:34:52 +1300 Subject: [Tutor] Returning multiple values from a script Message-ID: <5667508E43F1B740BCFA57FF46E3530002FC049C@nav-akl-exch-c.newton.navman.com> Oops answered my own question. Dynamic importing is done using the __import__ function: t = ["test1.py", "test2.py"] #Actually this list is filled in by a Tkinter Listbox selection. for f in t: testname = f[:-3] test = __import__("%s"%(testname)) res = test.run_test() Cheers Hans -----Original Message----- From: Hans Dushanthakumar Sent: Thursday, 12 January 2006 2:28 p.m. Cc: Python Tutor Subject: RE: [Tutor] Returning multiple values from a script Thanks for your reply Kent. Is it possible to dynamically import a module? The foll snippet of code throws an error "ImportError: No module named testname" t = ["test1.py", "test2.py"] #Actually this list is filled in by a Tkinter Listbox selection. for f in t: testname = f[:-3] import "%s"%(testname) print testname.run_test() Any other means of importing dynamically? -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Kent Johnson Sent: Thursday, 12 January 2006 2:02 p.m. Cc: Python Tutor Subject: Re: [Tutor] Returning multiple values from a script Hans Dushanthakumar wrote: > Yes I agree that it'd be cleaner to import the second script and call > it. > > The reason I'm keen to find a alternate method is that I have a whole > lot of scripts that were designed to run only as standalone scripts. > ie each of these scripts is not a "function" that I could just call > from another script. They are all of the format: > > 1) Test.py > ------- > import sys > > sys.exit(5) > > > Now I'm trying to write a master script that'd run each one of these > scripts. I'm sure it would have been a lot easier if the scripts were > of the following format. Unfortunately they are not.: > > Test.py > ------- > import sys > > Def test(): > return(5, "Junk") > > if __name__ == __main__: > test() > > > Well if there is no other way I think I'll have to alter all the > scripts to be of the above format. Just wondering if anyone has any > suggestions ISTM that you have to change all the scripts anyway if you want to return two values...why not change them to call a different function (other than sys.exit) that does what you want? Do the scripts still have to run standalone? For example you could make a module mysys.py: returnedvalue = None def exit(value): global returnedvalue returnedvalue = value Then just edit the scripts to import mysys and call mysys.exit(), run the script with import and get the returnedvalue from mysys. If you want a base hack that I couldn't possibly recommend :-) I suppose you could replace sys.exit() with a function of your own choosing. Something like this should work... >>> import sys >>> returnedvalue = None >>> >>> def mysysexit(value): ... global returnedvalue ... returnedvalue = value ... >>> original_exit = sys.exit # if you need to keep the old value... >>> sys.exit = mysysexit >>> >>> sys.exit(5) # here you can just import the module you want to run >>> returnedvalue 5 Isn't Python wonderful! Kent From john at fouhy.net Thu Jan 12 02:32:44 2006 From: john at fouhy.net (John Fouhy) Date: Thu, 12 Jan 2006 14:32:44 +1300 Subject: [Tutor] Returning multiple values from a script In-Reply-To: <5667508E43F1B740BCFA57FF46E3530002FC047C@nav-akl-exch-c.newton.navman.com> References: <5667508E43F1B740BCFA57FF46E3530002FC047C@nav-akl-exch-c.newton.navman.com> Message-ID: <5e58f2e40601111732r7e58215g@mail.gmail.com> On 12/01/06, Hans Dushanthakumar wrote: > Any other means of importing dynamically? There's an __import__ builtin. It's a function that takes a string and returns the module. eg: >>> sys = __import__('sys') >>> sys.platform 'win32' [actually, it does a bit more than just that; read the docs] -- John. From singingxduck at gmail.com Thu Jan 12 02:33:19 2006 From: singingxduck at gmail.com (Orri Ganel) Date: Wed, 11 Jan 2006 20:33:19 -0500 Subject: [Tutor] Returning multiple values from a script In-Reply-To: <5667508E43F1B740BCFA57FF46E3530002FC047C@nav-akl-exch-c.newton.navman.com> References: <5667508E43F1B740BCFA57FF46E3530002FC047C@nav-akl-exch-c.newton.navman.com> Message-ID: <43C5B1DF.2090605@gmail.com> Hans Dushanthakumar wrote: >Thanks for your reply Kent. > >Is it possible to dynamically import a module? > >The foll snippet of code throws an error "ImportError: No module named >testname" > > >t = ["test1.py", "test2.py"] #Actually this list is filled in by a >Tkinter Listbox selection. > >for f in t: > testname = f[:-3] > import "%s"%(testname) > print testname.run_test() > > >Any other means of importing dynamically? > > Well, it's not recommended, but the following will work (I'll leave the lectures on why it's not recommended to the more learned on the list ;-) ): eval("import %s" % testname) -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. From singingxduck at gmail.com Thu Jan 12 02:34:46 2006 From: singingxduck at gmail.com (Orri Ganel) Date: Wed, 11 Jan 2006 20:34:46 -0500 Subject: [Tutor] Returning multiple values from a script In-Reply-To: <5667508E43F1B740BCFA57FF46E3530002FC049C@nav-akl-exch-c.newton.navman.com> References: <5667508E43F1B740BCFA57FF46E3530002FC049C@nav-akl-exch-c.newton.navman.com> Message-ID: <43C5B236.9070800@gmail.com> Hans Dushanthakumar wrote: >Oops answered my own question. Dynamic importing is done using the >__import__ function: > >t = ["test1.py", "test2.py"] #Actually this list is filled in by a >Tkinter Listbox selection. > >for f in t: > testname = f[:-3] > test = __import__("%s"%(testname)) > res = test.run_test() > >Cheers >Hans > > > I think your method is less a Bad Idea (tm) than mine, so please disregard previous message. Cheers, Orri -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. From kent37 at tds.net Thu Jan 12 02:47:56 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 11 Jan 2006 20:47:56 -0500 Subject: [Tutor] Returning multiple values from a script In-Reply-To: <5667508E43F1B740BCFA57FF46E3530002FC049C@nav-akl-exch-c.newton.navman.com> References: <5667508E43F1B740BCFA57FF46E3530002FC049C@nav-akl-exch-c.newton.navman.com> Message-ID: <43C5B54C.9090205@tds.net> Hans Dushanthakumar wrote: > Oops answered my own question. Dynamic importing is done using the > __import__ function: > > t = ["test1.py", "test2.py"] #Actually this list is filled in by a > Tkinter Listbox selection. > > for f in t: > testname = f[:-3] > test = __import__("%s"%(testname)) If testname is a string, as it is here, "%s"%(testname) has the same value as testname itself, you can just use __import__(testname) Kent From dyoo at hkn.eecs.berkeley.edu Thu Jan 12 03:24:14 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 11 Jan 2006 18:24:14 -0800 (PST) Subject: [Tutor] calloc In-Reply-To: Message-ID: On Thu, 12 Jan 2006, Burge Kurt wrote: > How can I use calloc in python ? Before computing and processing my data > I want to know how many bytes are available? Hi Burge, There's no concept of manual memory allocation in Python, and we don't have direct access to calloc/malloc/free. You're asking a lot of C-ish questions: have you looked through the Python Tutorial to get aquainted with the language yet? See: http://www.python.org/doc/tut/ One of the main distinctions between Python and C is that Python programming has a very dynamic feel to it. Program properties that may be static in other languages are fairly dynamic in Python. For example, rather than predefine a line buffer to read lines from a file, we use the readline() method of a file, which itself dynamically expands if the line is very long. The small program: ###### file = open("/etc/passwd") for line in file: print line ###### does what you might expect: it displays every line in the file. Note here that there are no hardcoded places where we've defined how long line must be. (An equivalent C program would be slightly more difficult to write unless we changed its semantics to read the file character-by-character or block-by-block where each unit is the same size, rather than line-by-line where each line's length can vary.) All the memory allocation and deallocation is handed by the Python runtime. Regions of memory that no longer are reachable are freed by garbage collection (or reference counting). This GC scheme reduces the chance of making silly memory-related errors such as double-free or memory leaking. From logesh at iafrica.com Thu Jan 12 05:03:58 2006 From: logesh at iafrica.com (Logesh Pillay) Date: Thu, 12 Jan 2006 06:03:58 +0200 Subject: [Tutor] declaring list Message-ID: <1137038638.7565.9.camel@localhost.localdomain> hello list I asked yesterday how we can "declare" an array in python. Thanks Brian van den Broek and Frank Schley for your responses. A[None] * n works for me. To answer Brian's question, I was writing the standard backtracking procedure to find the permutations of 1..n taken r at a time. def permutations (n, r): A, Used = [None] * (r+1), [False] * (n+1) def choose (m): if m > r: print A[1:], else: for j in range (1, n+1): if not Used [j]: Used [j] = True A[m] = j choose (m+1) Used [j] = False choose (1) Thanks Logesh Pillay From sfhaley at gmail.com Thu Jan 12 05:31:04 2006 From: sfhaley at gmail.com (Steve Haley) Date: Wed, 11 Jan 2006 23:31:04 -0500 Subject: [Tutor] Finding the Index of a member of a Tuple Message-ID: Hello everyone, I need to do something very simple but I'm having trouble finding the way to do it - at least easily. I have created a tuple and now need to find the position of individual members of that tuple. Specifically, the tuple is something like: words = ("you", "me", "us", "we", "and", "so", "forth") and I need to be able to name a member, for example, "us" and find what the position (index) of that word is in the tuple. I would have thought there would be a simple built in function for that but I just went through the built in functions in the Python Library Reference and I didn't find anything. I could probably figure out how to write a while loop or something to do a sequential search until I found the right member but I really believe there must be an easier way and I'm just not seeing it. You can probably tell I'm just learning Python so any help would be appreciated. Thanks very much in advance, Steve -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060111/d8b18736/attachment.html From bgailer at alum.rpi.edu Thu Jan 12 05:47:02 2006 From: bgailer at alum.rpi.edu (bob) Date: Wed, 11 Jan 2006 20:47:02 -0800 Subject: [Tutor] Finding the Index of a member of a Tuple In-Reply-To: References: Message-ID: <7.0.0.16.0.20060111203829.01cebc50@alum.rpi.edu> At 08:31 PM 1/11/2006, Steve Haley wrote: >Hello everyone, > >I need to do something very simple but I'm having trouble finding >the way to do it - at least easily. I have created a tuple and now >need to find the position of individual members of that >tuple. Specifically, the tuple is something like: words = ("you", >"me", "us", "we", "and", "so", "forth") and I need to be able to >name a member, for example, "us" and find what the position (index) >of that word is in the tuple. > >I would have thought there would be a simple built in function for >that but I just went through the built in functions in the Python >Library Reference and I didn't find anything. I could probably >figure out how to write a while loop or something to do a sequential >search until I found the right member but I really believe there >must be an easier way and I'm just not seeing it. You can probably >tell I'm just learning Python so any help would be appreciated. Unfortunately there is no list method find. Sigh. Here's how I'd do it: # create a dictionary with each word as key and ordinal as value words = dict([(n,m) for m,n in enumerate(("you", "me", "us", "we", "and", "so", "forth"))]) words["me"] # returns 1 From dyoo at hkn.eecs.berkeley.edu Thu Jan 12 07:25:09 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 11 Jan 2006 22:25:09 -0800 (PST) Subject: [Tutor] calloc In-Reply-To: Message-ID: On Thu, 12 Jan 2006, Burge Kurt wrote: > Again thank you :( and sorry for asking that much questions in one day > and I know most of them were nonsense .. Don't worry about it; please feel free to continue to ask questions on the list. It wasn't quite clear what experience you had before: I have to assume that you've had a lot of C, but other than that, I'm quite clueless. > I read the tutorial and still forget lots of parts again and again > reading it! I feel mixed about recommending the official Python Tutotrial: it goes way too fast for my tastes. I pointed it out just because it's probably the quickest way to get a taste of the language, but it's not substantial. I'd instead recommend a different tutorial; there are several listed from the link here: http://wiki.python.org/moin/BeginnersGuide/Programmers I think that Dive into Python is especially good, but of course, whatever tutorial there that reads easiest for you is best. Good luck to you! From ml.cyresse at gmail.com Thu Jan 12 07:32:58 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Thu, 12 Jan 2006 19:32:58 +1300 Subject: [Tutor] Locating directory of script? Message-ID: Hi all, Let's say I have a script called bob.py in a directory called c:\pythonstuff, which is in my PATH env_var, and python is also in my PATH, and from a completely different directory I call "python bob.py" is there a right way to determine what directory bob.py resides in? So far I've found that import inspect class Foo: pass sourceP = inspect.getsourcefile(Foo) works, but I'm not too sure how resilient that is... Regards, Liam Clarke From broek at cc.umanitoba.ca Thu Jan 12 07:52:35 2006 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Thu, 12 Jan 2006 00:52:35 -0600 Subject: [Tutor] Finding the Index of a member of a Tuple In-Reply-To: <7.0.0.16.0.20060111203829.01cebc50@alum.rpi.edu> References: <7.0.0.16.0.20060111203829.01cebc50@alum.rpi.edu> Message-ID: <43C5FCB3.1080902@cc.umanitoba.ca> bob said unto the world upon 11/01/06 10:47 PM: > At 08:31 PM 1/11/2006, Steve Haley wrote: > >>Hello everyone, >> >>I need to do something very simple but I'm having trouble finding >>the way to do it - at least easily. I have created a tuple and now >>need to find the position of individual members of that >>tuple. Specifically, the tuple is something like: words = ("you", >>"me", "us", "we", "and", "so", "forth") and I need to be able to >>name a member, for example, "us" and find what the position (index) >>of that word is in the tuple. >> >>I would have thought there would be a simple built in function for >>that but I just went through the built in functions in the Python >>Library Reference and I didn't find anything. I could probably >>figure out how to write a while loop or something to do a sequential >>search until I found the right member but I really believe there >>must be an easier way and I'm just not seeing it. You can probably >>tell I'm just learning Python so any help would be appreciated. > > > Unfortunately there is no list method find. Sigh. Here's how I'd do it: > > # create a dictionary with each word as key and ordinal as value > words = dict([(n,m) for m,n in enumerate(("you", "me", "us", "we", > "and", "so", "forth"))]) > words["me"] # returns 1 > I assume Bob meant that tuples have no index or find method. His suggested procedure will work, but it seems more work than: >>> t = ("I'm", "a", "tuple.", "I", "have", "only", "magic", "methods.") >>> l = list(t) >>> l.index("have") 4 >>> t[4] 'have' >>> I say more work as the way above builds a list to turn into a dictionary. But, since dictionary access is fast, it might be quicker for long tuples where the sought item is near then end. If it matters, test. HTH, Brian vdB From broek at cc.umanitoba.ca Thu Jan 12 07:56:03 2006 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Thu, 12 Jan 2006 00:56:03 -0600 Subject: [Tutor] Locating directory of script? In-Reply-To: References: Message-ID: <43C5FD83.7010301@cc.umanitoba.ca> Liam Clarke said unto the world upon 12/01/06 12:32 AM: > Hi all, > > Let's say I have a script called bob.py in a directory called > c:\pythonstuff, which is in my PATH env_var, and python is also in my > PATH, and from a completely different directory I call "python bob.py" > is there a right way to determine what directory bob.py resides in? > > So far I've found that > > import inspect > > class Foo: > pass > > sourceP = inspect.getsourcefile(Foo) > > works, but I'm not too sure how resilient that is... > > Regards, > > Liam Clarke Hey Liam, >>> import this The Zen of Python, by Tim Peters >>> this.__file__ '/usr/lib/python2.4/this.pyc' >>> HTH, Brian vdB From carroll at tjc.com Thu Jan 12 08:04:08 2006 From: carroll at tjc.com (Terry Carroll) Date: Wed, 11 Jan 2006 23:04:08 -0800 (PST) Subject: [Tutor] Finding the Index of a member of a Tuple In-Reply-To: Message-ID: On Wed, 11 Jan 2006, Steve Haley wrote: > I need to do something very simple but I'm having trouble finding the way to > do it - at least easily. I have created a tuple and now need to find the > position of individual members of that tuple. Specifically, the tuple is > something like: words = ("you", "me", "us", "we", "and", "so", "forth") and > I need to be able to name a member, for example, "us" and find what the > position (index) of that word is in the tuple. Does it have to be a tuple? If you make it a list, you can use index(): >>> words = ["you", "me", "us", "we", "and", "so", "forth"] >>> words.index("and") 4 If it must be a tuple, you can't do that directly: >>> words = ("you", "me", "us", "we", "and", "so", "forth") >>> words.index("and") Traceback (most recent call last): File "", line 1, in ? AttributeError: 'tuple' object has no attribute 'index' but you can wrap it in a list conversion: >>> words = ("you", "me", "us", "we", "and", "so", "forth") >>> list(words).index("and") 4 I'm not sure why tuple wouldn't have this capability; but it doesn't. From kent37 at tds.net Thu Jan 12 12:06:25 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 12 Jan 2006 06:06:25 -0500 Subject: [Tutor] div_t In-Reply-To: References: <43C5AB97.40103@tds.net> Message-ID: <43C63831.1090002@tds.net> Burge Kurt wrote: >>divmod(...) >> divmod(x, y) -> (div, mod) > > > What is the easiest way to use div and mod seperately as an attribute like: > > if a = divmod(x,y) > > a.div or a.mod The result of calling divmod() is a two-element tuple. You access the elements by indexing: >>> a=divmod(10, 3) >>> a[0] 3 >>> a[1] 1 You can also use tuple assignment to assign the two values to two variables (you can use other names than div and mod): >>> div, mod = divmod(10, 3) >>> div 3 >>> mod 1 BTW you can't put an assignment in an if statement in python so your original code might be written as div, mod = divmod(x, y) if div... Kent From kent37 at tds.net Thu Jan 12 12:13:37 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 12 Jan 2006 06:13:37 -0500 Subject: [Tutor] Finding the Index of a member of a Tuple In-Reply-To: References: Message-ID: <43C639E1.7030306@tds.net> Steve Haley wrote: > Hello everyone, > > I need to do something very simple but I'm having trouble finding the > way to do it - at least easily. I have created a tuple and now need to > find the position of individual members of that tuple. Specifically, > the tuple is something like: words = ("you", "me", "us", "we", "and", > "so", "forth") and I need to be able to name a member, for example, "us" > and find what the position (index) of that word is in the tuple. If you can use a list instead of a tuple you can use the index() method. >>> words = ["you", "me", "us", "we", "and", "so", "forth"] >>> words.index('me') 1 >>> words.index('so') 5 There is no index() method for a tuple. This is probably because in GvR's view, tuples are analogous to records - they are heterogeneous collections where position matters. Lists are for homogeneous collections. In this view, tuple.index() doesn't make sense. list.index() is documented here: http://docs.python.org/lib/typesseq-mutable.html You found the right chapter of the Lib Ref but the wrong section. Kent From benvinger at yahoo.co.uk Thu Jan 12 12:26:12 2006 From: benvinger at yahoo.co.uk (Ben Vinger) Date: Thu, 12 Jan 2006 11:26:12 +0000 (GMT) Subject: [Tutor] extra characters in XML In-Reply-To: <43C52D76.8080804@tds.net> Message-ID: <20060112112612.30315.qmail@web25803.mail.ukl.yahoo.com> Thanks - it was exactly as you said --- Kent Johnson wrote: > Most likely your XML file is 16-bit unicode, not > utf-8. When ascii text > is represented as unicode, every other byte will be > a null byte. That is > the extra character that shows up as a space or box > depending on who is > interpreting it. The utf-8 codec must be swallowing > the null bytes. > > In your code above, instead of utf-8 try utf_16_be > and utf_16_le, one of > them should work. ___________________________________________________________ To help you stay safe and secure online, we've developed the all new Yahoo! Security Centre. http://uk.security.yahoo.com From bgailer at alum.rpi.edu Thu Jan 12 21:10:57 2006 From: bgailer at alum.rpi.edu (bob) Date: Thu, 12 Jan 2006 12:10:57 -0800 Subject: [Tutor] Finding the Index of a member of a Tuple In-Reply-To: <43C5FCB3.1080902@cc.umanitoba.ca> <43C639E1.7030306@tds.net> References: <7.0.0.16.0.20060111203829.01cebc50@alum.rpi.edu> <43C5FCB3.1080902@cc.umanitoba.ca> <43C639E1.7030306@tds.net> Message-ID: <7.0.0.16.0.20060112120625.022dbc80@alum.rpi.edu> At 10:52 PM 1/11/2006, Brian van den Broek wrote: >[snip] > >I assume Bob meant that tuples have no index or find method. No, Bob is sick and not thinking clearly. At 11:04 PM 1/11/2006, Terry Carroll wrote: >Does it have to be a tuple? If you make it a list, you can use index(): >[snip] At 03:13 AM 1/12/2006, Kent Johnson wrote: >[snip] >If you can use a list instead of a tuple you can use the index() method. I'm glad there are several of us contributing to this list. I hope to think things thru better before responding, but it is also nice to see that the dictionary approach stimulated things! From alan.gauld at freenet.co.uk Thu Jan 12 21:31:07 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 12 Jan 2006 20:31:07 -0000 Subject: [Tutor] CPU Utilization References: <43C5409C.1090407@sidorof.com> Message-ID: <004301c617b7$1e59bf50$0b01a8c0@xp> > shell out to perform the top command, parse the results, and report > those values to the job controller. I'd use vmstat rather than top since top is intended to run contuinuously whereas vmstat by default just returns a single line snapshot. I don't know of any native python mechanism for obtaining cpu usage. Alan G From ds-python-tutor at sidorof.com Thu Jan 12 23:06:16 2006 From: ds-python-tutor at sidorof.com (DS) Date: Thu, 12 Jan 2006 14:06:16 -0800 Subject: [Tutor] CPU Utilization] Message-ID: <43C6D2D8.5020602@sidorof.com> Alan Gauld wrote: >> shell out to perform the top command, parse the results, and report >> those values to the job controller. > > > I'd use vmstat rather than top since top is intended to run > contuinuously whereas vmstat by default just returns a single line > snapshot. > > I don't know of any native python mechanism for obtaining cpu usage. > > Alan G vmstat is a beautiful thing. Although as I mentioned in reply to others who responded to my question that top can run just once, top actually provides much more information than I am intending to use, making it seem a little wasteful. vmstat is much more focused on exactly the information I want. Although I am using linux pretty much exclusively these days, there's still a lot that I don't know and I wasn't aware that it existed. Thanks ds From cspears2002 at yahoo.com Thu Jan 12 23:53:28 2006 From: cspears2002 at yahoo.com (Christopher Spears) Date: Thu, 12 Jan 2006 14:53:28 -0800 (PST) Subject: [Tutor] defining __init__ Message-ID: <20060112225328.62697.qmail@web51612.mail.yahoo.com> I just read about __init__ in the chapter on operator overloading in Learning Python. What is __init__ exactly? Is it a special function that you can use to initialize attributes in an object upon creation? From dchristian at midsouth.rr.com Thu Jan 12 20:51:55 2006 From: dchristian at midsouth.rr.com (David Christian) Date: Thu, 12 Jan 2006 13:51:55 -0600 Subject: [Tutor] (no subject) Message-ID: Thanks in advance for any help!How do you create a script in python...sorry to be so remedial...first script. With my best regards always, David Christian -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060112/9e22f7fd/attachment.htm -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: image/gif Size: 3382 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20060112/9e22f7fd/attachment.gif -------------- next part -------------- A non-text attachment was scrubbed... Name: David Christian (dchrist1 at midsouth.rr.com).vcf Type: text/x-vcard Size: 434 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20060112/9e22f7fd/attachment.vcf From dyoo at hkn.eecs.berkeley.edu Fri Jan 13 00:09:32 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 12 Jan 2006 15:09:32 -0800 (PST) Subject: [Tutor] defining __init__ In-Reply-To: <20060112225328.62697.qmail@web51612.mail.yahoo.com> Message-ID: On Thu, 12 Jan 2006, Christopher Spears wrote: > I just read about __init__ in the chapter on operator > overloading in Learning Python. What is __init__ > exactly? Is it a special function that you can use to > initialize attributes in an object upon creation? Hi Chris, Yes, that's it. __init__'s doesn't have to do with overloading, but does have to do with initialization. It fires off when an instance is being instantiated. For example: ###### class Dog: def __init__(self, name): self.name = name def bark(self): return "%s says 'bow wow'" % self.name ###### When we instantiate a Dog, we pass parameters that will be used to call __init__, and in effect, we "initialize" our dog: ### >>> d = Dog("Ein") >>> d.bark() "Ein says 'bow wow'" >>> k = Dog("Kujo") >>> k.bark() "Kujo says 'bow wow'" >>> Dog() Traceback (most recent call last): File "", line 1, in ? TypeError: __init__() takes exactly 2 arguments (1 given) ### Note that in the third call to Dog, we see that if we don't pass enough arguments, that __init__() won't fire off properly. Does this make sense? From dyoo at hkn.eecs.berkeley.edu Fri Jan 13 00:11:32 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 12 Jan 2006 15:11:32 -0800 (PST) Subject: [Tutor] (no subject) In-Reply-To: Message-ID: On Thu, 12 Jan 2006, David Christian wrote: > Thanks in advance for any help!How do you create a script in > python...sorry to be so remedial...first script. You might want to look at: http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/ Some of the information there is a bit outdated, but it should still help you get started. If you have more questions, please feel free to ask! From john at fouhy.net Fri Jan 13 00:16:02 2006 From: john at fouhy.net (John Fouhy) Date: Fri, 13 Jan 2006 12:16:02 +1300 Subject: [Tutor] defining __init__ In-Reply-To: <20060112225328.62697.qmail@web51612.mail.yahoo.com> References: <20060112225328.62697.qmail@web51612.mail.yahoo.com> Message-ID: <5e58f2e40601121516l3075bc6bh@mail.gmail.com> On 13/01/06, Christopher Spears wrote: > I just read about __init__ in the chapter on operator > overloading in Learning Python. What is __init__ > exactly? Is it a special function that you can use to > initialize attributes in an object upon creation? Pretty much ... Have you read about defining your own classes yet? [I don't have Learning Python] If you haven't, then don't worry about it --- the book will surely cover __init__ when you get to defining classes. But, either way, here is a short example: >>> class MyClass(object): ... def __init__(self): ... print 'Initialising MyClass instance now...' ... self.x = 3 ... >>> m = MyClass() Initialising MyClass instance now... >>> m.x 3 -- John. From ds-python-tutor at sidorof.com Fri Jan 13 02:16:45 2006 From: ds-python-tutor at sidorof.com (DS) Date: Thu, 12 Jan 2006 17:16:45 -0800 Subject: [Tutor] CPU Utilization In-Reply-To: <43C6D620.5000602@wanadoo.fr> References: <43C5409C.1090407@sidorof.com> <43C6D620.5000602@wanadoo.fr> Message-ID: <43C6FF7D.6000404@sidorof.com> Nico wrote: > I think that libgtop and its python binding (used in gdesklets for > example) would do the trick. > Thank you for your thoughts on that. I think in other applications this might have a shot. In this situation I am using diskless workstations with minimal configurations, so gnome libraries will not be an option. At this point I'm going to go with vmstat. Thanks ds From alan.gauld at freenet.co.uk Fri Jan 13 10:41:03 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 13 Jan 2006 09:41:03 -0000 Subject: [Tutor] (no subject) References: Message-ID: <00a601c61825$7b4788a0$0b01a8c0@xp> Hello David, > Thanks in advance for any help!How do you create a script in > python...sorry > to be so remedial...first script. It sounds like you are a complete beginner to programming? If not forgive me for patronizing you with too much detail. A Python script is simply a text file. You can create a text file using any text editor such as notepad in Windows. There are many other text editors more suited to programming such as vim or emacs or Scite. Every programmer has his./her own favourite. Python also comes with its own programming environment called IDLE and I would recommend you, as a beginner, to use that. (If you downloaded Python from Activestate they also provide Pythonwin which is better than IDLE in my view). IDLE (and Pythonwin if its there ) should be available under Pyhon in your Start menu. When you launch IDLE it initially opens an "interactive shell" with a >>> prompt at which you can type python commands. To create a script you need to use the File->New menu and a blank window will open. You then type your python program (script) into that, save the file with a file extension of .py and run the program using IDLEs Run->Ruin module menu. The output will appear in the original interactive wi8ndow. Once your script is working properly you will also be able to run it by simply double clicking in Windows Explorer. I hope that answers your question. If you have not already done so you shjould visit the Non-Programmers page on the Python web site and choose one of the web tutorials listed there. http://wiki.python.org/moin/BeginnersGuide/NonProgrammers Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From s_david_rose at hotmail.com Fri Jan 13 20:54:42 2006 From: s_david_rose at hotmail.com (S. D. Rose) Date: Fri, 13 Jan 2006 14:54:42 -0500 Subject: [Tutor] defining __init__ References: <20060112225328.62697.qmail@web51612.mail.yahoo.com> <5e58f2e40601121516l3075bc6bh@mail.gmail.com> Message-ID: One thing about classes that really tripped me up when I first started using classes was 'self' before the variable. When you have ' self.variable ' that is a variable that can be referenced by the parent. If there's no 'self' before the variable, you can not. For instance, if you have a routine: class Dog: def __init__(self, color): self.color = color age = 16 buster = Dog('black') buddy = Dog('tan') roofus = Dog('gray') print buster.color print buddy.color print roofus.color will yield the text as answers: black, tan, gray print buster.age print buddy.age print roofus.age will -*NOT*- yield 16, 16, 16. It will error out, because you can not reference age without pre-pending a 'self.' -Dave "John Fouhy" wrote in message news:5e58f2e40601121516l3075bc6bh at mail.gmail.com... > On 13/01/06, Christopher Spears wrote: > > I just read about __init__ in the chapter on operator > > overloading in Learning Python. What is __init__ > > exactly? Is it a special function that you can use to > > initialize attributes in an object upon creation? > > Pretty much ... Have you read about defining your own classes yet? [I > don't have Learning Python] > > If you haven't, then don't worry about it --- the book will surely > cover __init__ when you get to defining classes. > > But, either way, here is a short example: > > >>> class MyClass(object): > ... def __init__(self): > ... print 'Initialising MyClass instance now...' > ... self.x = 3 > ... > >>> m = MyClass() > Initialising MyClass instance now... > >>> m.x > 3 > > -- > John. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From dyoo at hkn.eecs.berkeley.edu Fri Jan 13 21:33:15 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 13 Jan 2006 12:33:15 -0800 (PST) Subject: [Tutor] defining __init__ In-Reply-To: Message-ID: On Fri, 13 Jan 2006, S. D. Rose wrote: > One thing about classes that really tripped me up when I first started > using classes was 'self' before the variable. When you have ' > self.variable ' that is a variable that can be referenced by the parent. > If there's no 'self' before the variable, you can not. > > For instance, if you have a routine: > > class Dog: > def __init__(self, color): > self.color = color > age = 16 Hi Dave, 'age' here is a local variable, just like any other local variable that we've used in other function definitions. > It will error out, because you can not reference age without pre-pending > a 'self.' There might be some confusion here --- you mention parents and children, when there aren't any involved --- so let's talk about this in more detail. The key observation we need to make is that the first assignment: > self.color = color makes a state change to the class instance. But: > age = 16 makes an assignment to a local variable 'age', and that variable has no connection to the state of the Dog. Let's get away, for a moment, from class stuff, and let's take a quicky example with just functions: ### def initializeThing(thing): thing['color'] = 'blue' age = 42 d = {} initializeThing(d) print d ### Do we expect to see 'age' in the 'd' dictionary? If you have more questions, please feel free to ask. From kabads at gmail.com Sat Jan 14 11:44:19 2006 From: kabads at gmail.com (Adam Cripps) Date: Sat, 14 Jan 2006 10:44:19 +0000 Subject: [Tutor] Design suggestion - is a cookie the answer? Message-ID: I've developed a nice but simple cgi script [1] which produces multiplication questions for children in my class. It randomly presents a list of questions and then checks the answers once they push submit. The form builds up a fairly long list of vars which are passed to a method which checks the question against the answer. However, I knew a post to Tutor would be needed sooner or later. After 5 months of using this script one of the children has discovered that by pressing the refresh button they get the results checked and the points awarded without any work. This is a combination of my bad design and their ingenuity (bless 'em). I would like to ammend the script so that the simple refresh does not award more points. My first initial reaction is to create a cookie which somehow checks whether the string is valid. Can anyone provide some guidance on how to go about fixing this? TIA Adam [1] http://www.monkeez.org/python/times.txt -- http://www.monkeez.org PGP key: 0x7111B833 From cjhandrew at gmail.com Sat Jan 14 13:31:22 2006 From: cjhandrew at gmail.com (Chris Andrew) Date: Sat, 14 Jan 2006 12:31:22 +0000 Subject: [Tutor] Complete programming newbie requires tutorial. Message-ID: <307203ff0601140431s26e9e3c0s@mail.gmail.com> Hi, all. I wonder whether you can help. I've just subscribed to the list, so look forward to participating. I have been using GNU/ Linux since about 1999, but am a complete newbie when it comes to programming. I bought the O'Reilly "Learning Python" book, but have struggled with it. I note that resources on the python.org website, but was wondering whether anyone on the list could recommend a tutorial. Ideally the tutorial should be akin to the "Dummies Guide to n" style. In an ideal world, I should be able to print it in small chunks (html in sections, rather than continuous?). Finally, I should add that I am happy to purchase a book if necessary. I'd really appreciate your feedback. Many thanks, Chris. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060114/21ca50f4/attachment.html From jjk_saji at yahoo.com Sat Jan 14 13:56:31 2006 From: jjk_saji at yahoo.com (John Joseph) Date: Sat, 14 Jan 2006 12:56:31 +0000 (GMT) Subject: [Tutor] Complete programming newbie requires tutorial. In-Reply-To: <307203ff0601140431s26e9e3c0s@mail.gmail.com> Message-ID: <20060114125631.43161.qmail@web34802.mail.mud.yahoo.com> --- Chris Andrew wrote: > Hi, all. > > I wonder whether you can help. I've just subscribed > to the list, so look > forward to participating. I have been using GNU/ > Linux since about 1999, > but am a complete newbie when it comes to > programming. > > I bought the O'Reilly "Learning Python" book, but > have struggled with it. I > note that resources on the python.org website, but > was wondering whether > anyone on the list could recommend a tutorial. > I liked this book "Python Programming for the absolute beginner " by Michael Dawson , I am following it , now doing OOP chapters Also I like Byte of Python by Swaroop check the link http://www.byteofpython.info/read/index.html Also this list is of great help , to people like me ___________________________________________________________ Yahoo! Photos ? NEW, now offering a quality print service from just 8p a photo http://uk.photos.yahoo.com From alan.gauld at freenet.co.uk Sat Jan 14 14:18:35 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 14 Jan 2006 13:18:35 -0000 Subject: [Tutor] Design suggestion - is a cookie the answer? References: Message-ID: <00d301c6190d$0630ab80$0b01a8c0@xp> > by pressing the refresh button they get the results checked and the > points awarded without any work. This is a combination of my bad > design and their ingenuity (bless 'em). I'd recommend using client side JavaScript for this. Create a submit function in JavaScript that will only actually submit the form if all the questions have been completed. Of course that does mean learning some JavaScript if you don't already know it, but almost any JavaScript primer will tell you how to do pre-submit data validation using the onSubmit action. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From jjk_saji at yahoo.com Sat Jan 14 14:46:43 2006 From: jjk_saji at yahoo.com (John Joseph) Date: Sat, 14 Jan 2006 13:46:43 +0000 (GMT) Subject: [Tutor] IndexError: list index out of range [ Program work fine , but gives this message , guidance requested ] In-Reply-To: Message-ID: <20060114134643.14992.qmail@web34811.mail.mud.yahoo.com> --- Danny Yoo wrote: > > I get the error for set > > >>> set((1,1,1,2,2,2,2,2,3,4,4,5)) > > Traceback (most recent call last): > > File "", line 1, in ? > > NameError: name 'set' is not defined > > Hi John, > > For Python 2.3.4, you'll need to add the line: > > ###### > from sets import Set as set > ###### > > before trying to use 'set'. Sets weren't so built > into Python until > Hi Thanks to all , I was able to do the script for removing the dupes from the list , I had pasted my script along with this mail Thanks a Lot Joseph John *********************************************************************************** """ This program was to teach u (a)How to remove the dupes from the list (b) How to use try and except in case the input is wrong a_biglist => is the list which we enter i_counter = > counter in for loop length => length of the list / No of list members """ import sys from sets import Set as set a_biglist = [] i_counter = " " length = " " try: length = int(raw_input("Enter the Length of the List : ")) except: print "U should Have Enterd a integer, Now Try again " #length = int(raw_input("Enter the Length of the List : ")) sys.exit() for i_counter in range(length): try: num = int(raw_input("Enter the Number for the list : ")) a_biglist.append(num) except: print " U are not entering integer , please do enter integer" sys.exit() def dupe_detector(sequence): ''' returns a list of sequence that are duplicated''' sequence = list(sequence) seen_dupes = [] for item in set(sequence): if sequence.count(item) > 1: seen_dupes.append(item) return seen_dupes def print_dupe_report(sequence): '''prints a report of items in sequence that are duplicated''' dupes = dupe_detector(sequence) dupes.sort() for d in dupes: print "%s was duplicated" %d print "The List of Dupe No are " print "----------------------------------------------------------------------------" print dupe_detector(a_biglist) print "----------------------------------------------------------------------------" print "\t\t The Dupe record is \n \t \t It Prints which all numbers got duplicated" print_dupe_report(a_biglist) print "----------------------------------------------------------------------------" print "Now We should print only , once All the duplication number are removed " print set(a_biglist) ___________________________________________________________ Yahoo! Messenger - NEW crystal clear PC to PC calling worldwide with voicemail http://uk.messenger.yahoo.com From kent37 at tds.net Sat Jan 14 15:07:20 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 14 Jan 2006 09:07:20 -0500 Subject: [Tutor] Complete programming newbie requires tutorial. In-Reply-To: <307203ff0601140431s26e9e3c0s@mail.gmail.com> References: <307203ff0601140431s26e9e3c0s@mail.gmail.com> Message-ID: <43C90598.7020008@tds.net> Chris Andrew wrote: > Hi, all. > > I wonder whether you can help. I've just subscribed to the list, so > look forward to participating. I have been using GNU/ Linux since about > 1999, but am a complete newbie when it comes to programming. > > I bought the O'Reilly "Learning Python" book, but have struggled with > it. I note that resources on the python.org > website, but was wondering whether anyone on the list could recommend a > tutorial. Did you find this page? It lists several beginners tutorials. "Learning to Program" and "A Byte of Python" are both popular: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers "Learning Python" is not really oriented towards beginners without previous programming experience. You might prefer "Python Programming for the absolute beginner" "Python Programming: An Introduction to Computer Science" 'Beginning Python: From Novice to Professional' Links to the above and more here: http://wiki.python.org/moin/IntroductoryBooks Kent From w.damen at gmail.com Sat Jan 14 21:32:18 2006 From: w.damen at gmail.com (Rinzwind) Date: Sat, 14 Jan 2006 21:32:18 +0100 Subject: [Tutor] Learning to use pygame but running into errors when using examples from websites Message-ID: <4677730601141232u1c8b6b6dv534b325bae7328a@mail.gmail.com> Hello, I've been trying to get myself to learn using pygame. I have created some things but I still need help of examples before I can do it myself but I always run into trouble. On this website I saw a lot of great info regarding pygame: http://www.ida.liu.se/~ETE257/timetable/LecturePythonPygame.html In there is an example where you can draw lines with your mouse with the name "Mouse Input" as a header. This one and more of those examples all end up with errors like this: I saved the code of the example as PaintCircles.py, chmod it to 777 and run it. $ ./PaintCircles.py from: can't read /var/mail/pygame.locals ./PaintCircles.py: line 9: class: command not found ./PaintCircles.py: line 11: syntax error near unexpected token `(' ./PaintCircles.py: line 11: ` def __init__(self):' I expect the website uses correct code and I am doing something wrong but can someone tell me what that might be? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060114/dee51c1d/attachment.html From adam.jtm30 at gmail.com Sat Jan 14 23:14:51 2006 From: adam.jtm30 at gmail.com (Adam) Date: Sat, 14 Jan 2006 22:14:51 +0000 Subject: [Tutor] Learning to use pygame but running into errors when using examples from websites In-Reply-To: <4677730601141232u1c8b6b6dv534b325bae7328a@mail.gmail.com> References: <4677730601141232u1c8b6b6dv534b325bae7328a@mail.gmail.com> Message-ID: On 14/01/06, Rinzwind wrote: > > Hello, > > I've been trying to get myself to learn using pygame. I have created some > things but I still need help of examples before I can do it myself but I > always run into trouble. > On this website I saw a lot of great info regarding pygame: > > http://www.ida.liu.se/~ETE257/timetable/LecturePythonPygame.html > > In there is an example where you can draw lines with your mouse with the > name "Mouse Input" as a header. > This one and more of those examples all end up with errors like this: > > I saved the code of the example as PaintCircles.py, chmod it to 777 and > run it. > $ ./PaintCircles.py > from: can't read /var/mail/pygame.locals > ./PaintCircles.py: line 9: class: command not found > ./PaintCircles.py: line 11: syntax error near unexpected token `(' > ./PaintCircles.py: line 11: ` def __init__(self):' > > I expect the website uses correct code and I am doing something wrong but > can someone tell me what that might be? What are you trying to run this program with? Try 'python PaintCircles.py' instead. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060114/20b80f64/attachment.htm From ryan_gm at sbcglobal.net Sun Jan 15 02:52:13 2006 From: ryan_gm at sbcglobal.net (ryan luna) Date: Sat, 14 Jan 2006 17:52:13 -0800 (PST) Subject: [Tutor] Random in loop Message-ID: <20060115015213.92666.qmail@web80824.mail.yahoo.com> Hello, Im kinda stuck on something in the book Python Programming. The "Challenage" is to make a progam that flips a coin 100 times and then tells you the number of heads and tails. here is what i have so far, Code: import random coin = 0 heads = 0 tails = 0 heads_tails = random.randrange(2) while coin < 100: coin += 1 if (heads_tails == 0): heads += 1 elif (heads_tails == 1): tails += 1 print coin, heads, tails raw_input("Enter to exit") I know what my problem is, i just dont know the how to fix it. (Or i could just be writing this wrong all together) If im even goin at this the right way my problem is i need to randomly pick a new number at the beggening of each loop but i dont know how! other then that i think the rest of the code is good? Thanks for any help ^^ From ryan_gm at sbcglobal.net Sun Jan 15 03:12:41 2006 From: ryan_gm at sbcglobal.net (ryan luna) Date: Sat, 14 Jan 2006 18:12:41 -0800 (PST) Subject: [Tutor] Random in loop In-Reply-To: <1137291007.13820.2.camel@localhost.localdomain> Message-ID: <20060115021241.76386.qmail@web80806.mail.yahoo.com> Thank you alot ^^ so simple and i knew it, but last time i tried it i got an error on the =, most have been making a stupid mistake --- "ZIYAD A. M. AL-BATLY" wrote: > On Sat, 2006-01-14 at 17:52 -0800, ryan luna wrote: > > Hello, Im kinda stuck on something in the book > Python > > Programming. > > The "Challenage" is to make a progam that flips a > coin > > 100 times and then tells you the number of heads > and > > tails. > > here is what i have so far, > > Code: > > > > import random > > > > coin = 0 > > heads = 0 > > tails = 0 > > > > heads_tails = random.randrange(2) > Why is the above line outside the loop? Shouldn't > you be flipping it a > 100 times? You're doing it once in this program. > (I think you know by > know what you should do to correct this!) > > > while coin < 100: > > coin += 1 > > > > I hope this was helpful. > Ziyad. > > From zamb at saudi.net.sa Sun Jan 15 03:10:07 2006 From: zamb at saudi.net.sa (ZIYAD A. M. AL-BATLY) Date: Sun, 15 Jan 2006 05:10:07 +0300 Subject: [Tutor] Random in loop In-Reply-To: <20060115015213.92666.qmail@web80824.mail.yahoo.com> References: <20060115015213.92666.qmail@web80824.mail.yahoo.com> Message-ID: <1137291007.13820.2.camel@localhost.localdomain> On Sat, 2006-01-14 at 17:52 -0800, ryan luna wrote: > Hello, Im kinda stuck on something in the book Python > Programming. > The "Challenage" is to make a progam that flips a coin > 100 times and then tells you the number of heads and > tails. > here is what i have so far, > Code: > > import random > > coin = 0 > heads = 0 > tails = 0 > > heads_tails = random.randrange(2) Why is the above line outside the loop? Shouldn't you be flipping it a 100 times? You're doing it once in this program. (I think you know by know what you should do to correct this!) > while coin < 100: > coin += 1 I hope this was helpful. Ziyad. From ismaelgf at adinet.com.uy Sun Jan 15 03:44:15 2006 From: ismaelgf at adinet.com.uy (Ismael Garrido) Date: Sun, 15 Jan 2006 00:44:15 -0200 Subject: [Tutor] PAMIE but for linux Message-ID: <43C9B6FF.3020409@adinet.com.uy> Hi Is there anything like PAMIE but for a linux browser? Even better if it works in windows and linux. PAMIE lets you control Internet Explorer programmatically. I've read about PyXPCOM (for mozilla) but I coudn't find any docs or reference to using it to alter a document (like, clicking buttons, analyzing and rewriting the DOM, etc). Also, I've seen a wxMozilla proyect, but it is in early stages of development. Does it run any site mozilla runs (IE: handling scripting, CSS)? Does it run on linux? Thanks Ismael From alan.gauld at freenet.co.uk Sun Jan 15 10:33:52 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 15 Jan 2006 09:33:52 -0000 Subject: [Tutor] Complete programming newbie requires tutorial. References: <307203ff0601140431s26e9e3c0s@mail.gmail.com> Message-ID: <010901c619b6$cc36bf00$0b01a8c0@xp> > but am a complete newbie when it comes to programming. > I bought the O'Reilly "Learning Python" book, but have struggled Its really for existing programmers. Its a great book though so once you get over the initial hurdle go back and read it ahain. > note that resources on the python.org website, All the tutorials on the Non Programmers web site have their own flavour(*) and what suits one person won't suit another. Pay a visit to a few, try out a topic or two and pick your favourite. Ask questions here.... (*)For instance, my tutor majors on teaching programming per se rather than Python specifically. It uses 3 languages to reinforce the common concepts. Other tutorials are much more focused on Pythonb itself, maybe with a partiucular style of programming in mind... > I should be able to print it in small chunks Each topic in mine is a separate html file, or you can get the PDF version (although it tends to be updated less often than the main text). If you do print it all out it now comes to around 400 pages! > Finally, I should add that I am happy to purchase a book if necessary. You should never say that to an author, but.... my tutorial is available in dead tree format too (and as such is Python specific). HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From python at kapitalisten.no Sun Jan 15 13:33:46 2006 From: python at kapitalisten.no (=?iso-8859-1?Q?=D8yvind?=) Date: Sun, 15 Jan 2006 13:33:46 +0100 (CET) Subject: [Tutor] Whois Message-ID: <4930.193.71.156.239.1137328426.squirrel@mail.sporck.net> Hello. I am trying to write a module that lets me check whois-info of ip-adresses: import socket class whois: pass def ip(self, adresse): self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.s.connect(('whois.ripe.net', 43)) #self.s.connect(('whois.norid.no', 43)) self.s.send("%s \n\n" % adresse) self.data = self.s.recv(8196) self.page = '' self.page = self.page + self.data return self.page If I run the module I get the following: >>import whois >>from whois import * >>n = whois() >>n.ip('193.12.32.16') '% This is the RIPE Whois query server #2.\n% The objects are in RPSL format.\n%\n% Note: the default output of the RIPE Whois server\n% is changed. Your tools may need to be adjusted. See\n% http://www.ripe.net/db/news/abuse-proposal-20050331.html\n% for more details.\n%\n% Rights restricted by copyright.\n% See http://www.ripe.net/db/copyright.html\n\n' This is just the first part of the whois-info. However, if I don't write it into a function: >>import socket >>s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) >>s.connect(('whois.ripe.net', 43)) >>s.send("%s \n\n" % '193.12.32.16') 15 >>data = s.recv(8196) >>page = '' >>page = page + data >>page '% This is the RIPE Whois query server #2.\n% The objects are in RPSL format.\n%\n% Note: the default output of the RIPE Whois server\n% is changed. Your tools may need to be adjusted. See\n% http://www.ripe.net/db/news/abuse-proposal-20050331.html\n% for more details.\n%\n% Rights restricted by copyright.\n% See http://www.ripe.net/db/copyright.html\n\n% Note: This output has been filtered.\n% To receive output for a database update, use the "-B" flag\n\n% Information related to \'193.12.32.0 - 193.12.39.255\'\n\ninetnum: 193.12.32.0 - 193.12.39.255\nnetname: SE-CLAVISTER-NET\ndescr: Clavister AB/\xd6vikshem KabelTV\n tidigare Enternet Sweden AB\n \xd6rnsk\xf6ldsvik\n ####################################\n In case of improper use, please mail\n registry at clavister.com or abuse at swip.net\n................and so forth. Now I get everything, not only the first part as I did above. Why? And what should I do with the module in order to get all the info? Thanks in advance. -- This email has been scanned for viruses & spam by Decna as - www.decna.no Denne e-posten er sjekket for virus & spam av Decna as - www.decna.no From jjk_saji at yahoo.com Sun Jan 15 13:55:12 2006 From: jjk_saji at yahoo.com (John Joseph) Date: Sun, 15 Jan 2006 12:55:12 +0000 (GMT) Subject: [Tutor] "while" loop for satisfing two conditions , advice requested Message-ID: <20060115125512.84380.qmail@web34812.mail.mud.yahoo.com> Hi I am trying to use ?while? loop , here I want while loop to check for two conditions , I am not getting an idea how to use ?while? loop for checking two conditions I used "&" condition , but it is not giving me the expected results I used in this way while (condition no 1) & (condition no2): print ?Results? I request guidance Thanks Joseph John ___________________________________________________________ NEW Yahoo! Cars - sell your car and browse thousands of new and used cars online! http://uk.cars.yahoo.com/ From Carlo.Capuano at iter.org Sun Jan 15 14:30:03 2006 From: Carlo.Capuano at iter.org (Carlo Capuano) Date: Sun, 15 Jan 2006 14:30:03 +0100 Subject: [Tutor] "while" loop for satisfing two conditions , advice requested Message-ID: <0F4FBAD10465E047ADB7E8C74B4C189B0B2899@de-iws-xch01.iter.org> Hi >while (condition no 1) & (condition no2): > print "Results" > While (condition no 1) and (condition no2): print "Results" in python you use the words and, or, not, is like: if myvar1 is not None and myvar2 == '1': print 'what a nice snowing day!' Carlo what is ITER? www.iter.org From kent37 at tds.net Sun Jan 15 14:36:50 2006 From: kent37 at tds.net (Kent Johnson) Date: Sun, 15 Jan 2006 8:36:50 -0500 Subject: [Tutor] "while" loop for satisfing two conditions , Message-ID: <20060115133650.ZUGW23063.outaamta02.mail.tds.net@smtp.tds.net> > From: John Joseph > I am trying to use ?while? loop , here I want > while loop to check for two conditions , I am not > getting an idea how to use ?while? loop for checking > two conditions > I used "&" condition , but it is not > giving me the expected results > I used in this way > > while (condition no 1) & (condition no2): > print ?Results? Use 'and' instead of &. & is a bitwise logical AND - it operates on the individual bits of its arguments. 'and' treats the full operand as a logical value. The results can be different: >>> [1] & [2] Traceback (most recent call last): File "", line 1, in ? TypeError: unsupported operand type(s) for &: 'list' and 'list' >>> [1] and [2] [2] >>> 2 & 1 0 >>> 2 and 1 1 Kent From kent37 at tds.net Sun Jan 15 15:04:43 2006 From: kent37 at tds.net (Kent Johnson) Date: Sun, 15 Jan 2006 09:04:43 -0500 Subject: [Tutor] Whois In-Reply-To: <4930.193.71.156.239.1137328426.squirrel@mail.sporck.net> References: <4930.193.71.156.239.1137328426.squirrel@mail.sporck.net> Message-ID: <43CA567B.8010006@tds.net> ?yvind wrote: > Hello. > > I am trying to write a module that lets me check whois-info of ip-adresses: > > import socket > > class whois: > pass > > def ip(self, adresse): > self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > self.s.connect(('whois.ripe.net', 43)) > #self.s.connect(('whois.norid.no', 43)) > self.s.send("%s \n\n" % adresse) > self.data = self.s.recv(8196) > self.page = '' > self.page = self.page + self.data > return self.page > > If I run the module I get the following: > > This is just the first part of the whois-info. > > However, if I don't write it into a function: > > Now I get everything, not only the first part as I did above. Why? And > what should I do with the module in order to get all the info? You need to put socket.recv() into a loop in your program. recv() returns whatever data is available when you call it, or it blocks until more data is available. When you run interactively, there is enough of a delay between commands that the whole reply is received. When you run as a program you only get the first part. Try something like this: page = '' while True: data = s.recv(8196) if not data: break # data will be empty when the socket is closed page = page + data return page Note I have omitted the self qualifier - in the code you show, there is no benefit to making it a class, you might as well make ip() into a top-level function in your whois module. I would give it a more descriptive name as well... This essay gives some reasons why you might want to use classes; none of them apply in this case: http://www.pycs.net/users/0000323/stories/15.html Kent From ajikoe at gmail.com Sun Jan 15 17:05:37 2006 From: ajikoe at gmail.com (Pujo Aji) Date: Sun, 15 Jan 2006 17:05:37 +0100 Subject: [Tutor] "while" loop for satisfing two conditions , advice requested In-Reply-To: <20060115125512.84380.qmail@web34812.mail.mud.yahoo.com> References: <20060115125512.84380.qmail@web34812.mail.mud.yahoo.com> Message-ID: in understanding while loop someone should understand "if conditional" first. In "If conditional" there are common relational symbol "and" and "or" Let's discuss "and" conditional Condition 1 Condition 2 Result True True True True False False False True False False False False In short, and equal True if and only if both condition are true. "If the while loop result condition is true it will execute its block." example: x = 1 y = 1 while x==1 and y==1: # it will be processed if x==1 and y==1 are both true, in this case it is! another example: x=1 y=2 while x==1 and y==1: # it will be processed if x==1 and y==1 are both true, in this case it is not! Hope this help! pujo On 1/15/06, John Joseph wrote: > > Hi > I am trying to use "while" loop , here I want > while loop to check for two conditions , I am not > getting an idea how to use "while" loop for checking > two conditions > I used "&" condition , but it is not > giving me the expected results > I used in this way > > while (condition no 1) & (condition no2): > print "Results" > > I request guidance > Thanks > Joseph John > > > > > ___________________________________________________________ > NEW Yahoo! Cars - sell your car and browse thousands of new and used cars > online! http://uk.cars.yahoo.com/ > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060115/cdad57ff/attachment.html From zamb at saudi.net.sa Sun Jan 15 18:33:06 2006 From: zamb at saudi.net.sa (ZIYAD A. M. AL-BATLY) Date: Sun, 15 Jan 2006 20:33:06 +0300 Subject: [Tutor] PAMIE but for linux In-Reply-To: <43C9B6FF.3020409@adinet.com.uy> References: <43C9B6FF.3020409@adinet.com.uy> Message-ID: <1137346386.11196.6.camel@localhost.localdomain> On Sun, 2006-01-15 at 00:44 -0200, Ismael Garrido wrote: > Hi > > Is there anything like PAMIE but for a linux browser? Even better if it > works in windows and linux. PAMIE lets you control Internet Explorer > programmatically. > > I've read about PyXPCOM (for mozilla) but I coudn't find any docs or > reference to using it to alter a document (like, clicking buttons, > analyzing and rewriting the DOM, etc). > > Also, I've seen a wxMozilla proyect, but it is in early stages of > development. Does it run any site mozilla runs (IE: handling scripting, > CSS)? Does it run on linux? > > > Thanks > Ismael This is not exactly what you want. There's a web browser for GNOME (the default web browser as a matter of fact) called Epiphany?. Epiphany have a lot of _extensions_ that expands it's functionality, one of those is the Python Console? which allow some interaction between Python and Epiphany. Hope you find it useful. Ziyad. Links: 1. http://www.gnome.org/projects/epiphany/ (click on "Epiphany Extensions" down on the page.) 2. http://www.adamhooper.com:4242/epiphany-extensions/python-console.xhtml From ron.sheely at ironwoodlabs.com Sun Jan 15 21:41:06 2006 From: ron.sheely at ironwoodlabs.com (Ron Sheely) Date: Sun, 15 Jan 2006 12:41:06 -0800 (PST) Subject: [Tutor] Complete programming newbie requires tutorial. (Chris Andrew) Message-ID: <1841.24.21.72.42.1137357666.squirrel@webmail.ironwoodlabs.com> Two things. First, I've been watching this list for several weeks now. I wanted to respond to Chris Andrew's question regarding Python tutorials (Complete programming newbie requires tutorial. (Message-ID: <307203ff0601140431s26e9e3c0s at mail.gmail.com>Chris Andrew). Did I reply correctly? Second, I've found four Python tutorials helpful to new programmers. I list them in suggested order. BTW, I believe Danny's tutorial is where I heard about this list. 1) One Day of IDLE Toying, by Danny Yoo (http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/) 2) Python Org's IDLE Tutorial (http://www.python.org/idle/doc/idlemain.html) 3) A Byte of Python by Swaroop C H (http://www.ibiblio.org/g2swap/byteofpython/read/) 4) Mark Pilgrim's Python tutorial for experienced programmers (http://www.diveintopython.org/) From kabads at gmail.com Sun Jan 15 23:05:37 2006 From: kabads at gmail.com (Adam Cripps) Date: Sun, 15 Jan 2006 22:05:37 +0000 Subject: [Tutor] Design suggestion - is a cookie the answer? In-Reply-To: <667ca7b60601141709o39676976l@mail.gmail.com> References: <00d301c6190d$0630ab80$0b01a8c0@xp> <667ca7b60601141709o39676976l@mail.gmail.com> Message-ID: On 1/15/06, Simon Gerber wrote: > > I'd recommend using client side JavaScript for this. > > Create a submit function in JavaScript that will only > > actually submit the form if all the questions have been > > completed. > > I'm sure this is implied in Alan's post, but I'm going to point it out > anyway as it's not always obvious if you're just starting to learn > Javascript. > > To avoid further cheating you might want to sure there is no way to > submit the form without javascript turned on. E.g. Don't have a submit > button and a form with an 'onSubmit' validation. Which some examples > do use. Otherwise, they can just turn off Javascript support in their > browser and bypass your validation. > > Instead, have a plain old form button that uses the 'onClick' event to > call a validation function, which also submits the form itself if > everything works. > > Cheers, > Thanks Alan and Simon. I must admit, I've been avoiding Javascript, but if this is the best way of doing it, then so be it. Will the URL intervene in just presenting a URL to the browser? One of the 'cheats' was just putting the cursor within the URL bar and then pressing enter. Does Javascript pick this up as well? Many thanks again, Adam -- http://www.monkeez.org PGP key: 0x7111B833 From shuying at gmail.com Mon Jan 16 00:49:53 2006 From: shuying at gmail.com (Shuying) Date: Mon, 16 Jan 2006 10:49:53 +1100 Subject: [Tutor] setuptools question Message-ID: <75fa0c3a0601151549w128c9c58mda486485039b89c9@mail.gmail.com> Hi, I'm not sure where's the best place to ask so I thought I'd try it here. I've got python2.3 and python2.4 installed on my machine and I'm trying to upgrade setuptools for both versions of python. So I've got no problems upgrading setuptools for python2.3 but when I try to do the same for python2.4, I get : Traceback (most recent call last): File "easy_install", line 7, in ? sys.exit( File "/usr/lib/python2.4/site-packages/setuptools-0.6a5-py2.4.egg/pkg_resources.py", line 236, in load_entry_point return get_distribution(dist).load_entry_point(group, name) File "/usr/lib/python2.4/site-packages/setuptools-0.6a5-py2.4.egg/pkg_resources.py", line 229, in get_distribution if isinstance(dist,Requirement): dist = get_provider(dist) File "/usr/lib/python2.4/site-packages/setuptools-0.6a5-py2.4.egg/pkg_resources.py", line 115, in get_provider return working_set.find(moduleOrReq) or require(str(moduleOrReq))[0] File "/usr/lib/python2.4/site-packages/setuptools-0.6a5-py2.4.egg/pkg_resources.py", line 382, in find raise VersionConflict(dist,req) # XXX add more info pkg_resources.VersionConflict: (setuptools 0.6a5 (/usr/lib/python2.4/site-packages/setuptools-0.6a5-py2.4.egg), Requirement.parse('setuptools==0.6a9')) and I'm not sure what's the best way to fix it. Suggestions please! Thanks, Shuying From alan.gauld at freenet.co.uk Mon Jan 16 02:12:40 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 16 Jan 2006 01:12:40 -0000 Subject: [Tutor] Design suggestion - is a cookie the answer? References: <00d301c6190d$0630ab80$0b01a8c0@xp><667ca7b60601141709o39676976l@mail.gmail.com> Message-ID: <015701c61a39$f2833160$0b01a8c0@xp> > I'm sure this is implied in Alan's post, but I'm going to point it out ... > To avoid further cheating you might want to sure there is no way to > submit the form without javascript turned on. E.g. Don't have a submit > button and a form with an 'onSubmit' validation. Which some examples > do use. Otherwise, they can just turn off Javascript support in their > browser and bypass your validation. Nope that wasn't implied in my post. I confess I just rely on JavaScript being there. But your point is a good one! > way of doing it, then so be it. Will the URL intervene in just > presenting a URL to the browser? The onValidate technique just does a check before sending and if it returns false doesn't send. The onClick method actually requires you to explicitly submit the form to the URL, that's why it's more secure. > One of the 'cheats' was just putting the cursor within the > URL bar and then pressing enter. Does Javascript > pick this up as well? No. JavaScript is an event driven paradigm and it only picks up the explicit events you register with it(*). One of the problems of using CGI is the ese of frigging it. I assume you are using GET instead of POST? GET is the default submission method but POST is nearly always better and should avoid the problem here. (I think, I haven't tried it!) (*)Not really true it will execute any inline code too. But it won't trigger to events that have not been registered, like a direct address refresh. On the subject of JavaScript being the *right* solution it ois of course only one way to do it. You could add code in your CGI that simply checks that all answers are filled in before responding, but that means a longer delay in response. In general where you want to validate that a form has been filled in its a better user experience to do it in the browser and that means JavaScript. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From ml.cyresse at gmail.com Mon Jan 16 13:27:23 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Tue, 17 Jan 2006 01:27:23 +1300 Subject: [Tutor] setuptools question In-Reply-To: <75fa0c3a0601151549w128c9c58mda486485039b89c9@mail.gmail.com> References: <75fa0c3a0601151549w128c9c58mda486485039b89c9@mail.gmail.com> Message-ID: How were you calling easy_install? On 1/16/06, Shuying wrote: > Hi, > > I'm not sure where's the best place to ask so I thought I'd try it > here. I've got python2.3 and python2.4 installed on my machine and > I'm trying to upgrade setuptools for both versions of python. So I've > got no problems upgrading setuptools for python2.3 but when I try to > do the same for python2.4, I get : > Traceback (most recent call last): > File "easy_install", line 7, in ? > sys.exit( > File "/usr/lib/python2.4/site-packages/setuptools-0.6a5-py2.4.egg/pkg_resources.py", > line 236, in load_entry_point > return get_distribution(dist).load_entry_point(group, name) > File "/usr/lib/python2.4/site-packages/setuptools-0.6a5-py2.4.egg/pkg_resources.py", > line 229, in get_distribution > if isinstance(dist,Requirement): dist = get_provider(dist) > File "/usr/lib/python2.4/site-packages/setuptools-0.6a5-py2.4.egg/pkg_resources.py", > line 115, in get_provider > return working_set.find(moduleOrReq) or require(str(moduleOrReq))[0] > File "/usr/lib/python2.4/site-packages/setuptools-0.6a5-py2.4.egg/pkg_resources.py", > line 382, in find > raise VersionConflict(dist,req) # XXX add more info > pkg_resources.VersionConflict: (setuptools 0.6a5 > (/usr/lib/python2.4/site-packages/setuptools-0.6a5-py2.4.egg), > Requirement.parse('setuptools==0.6a9')) > > and I'm not sure what's the best way to fix it. Suggestions please! > > Thanks, > Shuying > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From ml.cyresse at gmail.com Mon Jan 16 13:30:17 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Tue, 17 Jan 2006 01:30:17 +1300 Subject: [Tutor] Complete programming newbie requires tutorial. (Chris Andrew) In-Reply-To: <1841.24.21.72.42.1137357666.squirrel@webmail.ironwoodlabs.com> References: <1841.24.21.72.42.1137357666.squirrel@webmail.ironwoodlabs.com> Message-ID: I also highly recommand Alan Gauld's tutorial - http://www.freenetpages.co.uk/hp/alan.gauld/ On 1/16/06, Ron Sheely wrote: > Two things. > > First, I've been watching this list for several weeks now. I wanted to > respond to Chris Andrew's question regarding Python tutorials (Complete > programming newbie requires tutorial. (Message-ID: > <307203ff0601140431s26e9e3c0s at mail.gmail.com>Chris Andrew). Did I reply > correctly? > > Second, I've found four Python tutorials helpful to new programmers. I > list them in suggested order. BTW, I believe Danny's tutorial is where I > heard about this list. > > 1) One Day of IDLE Toying, by Danny Yoo > (http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/) > > 2) Python Org's IDLE Tutorial (http://www.python.org/idle/doc/idlemain.html) > > 3) A Byte of Python by Swaroop C H > (http://www.ibiblio.org/g2swap/byteofpython/read/) > > 4) Mark Pilgrim's Python tutorial for experienced programmers > (http://www.diveintopython.org/) > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From frank.hoffsummer at gmail.com Mon Jan 16 14:12:48 2006 From: frank.hoffsummer at gmail.com (frank h.) Date: Mon, 16 Jan 2006 14:12:48 +0100 Subject: [Tutor] timeout Message-ID: <60fae7c30601160512ndebe0b0ha72b2ad687514ac2@mail.gmail.com> Hello how can I break a loop after a certain amount of time has passed? pseudocode: with timeout of 60sec: From frank.hoffsummer at gmail.com Mon Jan 16 14:14:16 2006 From: frank.hoffsummer at gmail.com (frank h.) Date: Mon, 16 Jan 2006 14:14:16 +0100 Subject: [Tutor] timeout In-Reply-To: <60fae7c30601160512ndebe0b0ha72b2ad687514ac2@mail.gmail.com> References: <60fae7c30601160512ndebe0b0ha72b2ad687514ac2@mail.gmail.com> Message-ID: <60fae7c30601160514j47a9e4acm54df73b0a02474b@mail.gmail.com> Hello how can I break a loop after a certain amount of time has passed? pseudocode: with timeout of 60sec: while True: pass is there a simple way? without resorting to queues etc. (this is a bit over my head....) thanks for any insight you might have -frank On 1/16/06, frank h. wrote: > Hello > how can I break a loop after a certain amount of time has passed? > > pseudocode: > > with timeout of 60sec: > From w.damen at gmail.com Mon Jan 16 14:33:58 2006 From: w.damen at gmail.com (Rinzwind) Date: Mon, 16 Jan 2006 14:33:58 +0100 Subject: [Tutor] timeout In-Reply-To: <60fae7c30601160514j47a9e4acm54df73b0a02474b@mail.gmail.com> References: <60fae7c30601160512ndebe0b0ha72b2ad687514ac2@mail.gmail.com> <60fae7c30601160514j47a9e4acm54df73b0a02474b@mail.gmail.com> Message-ID: <4677730601160533n1ffbc7f2wde989f719a68d533@mail.gmail.com> Hello, With the time module and sleep(60)? http://www.python.org/doc/2.3.5/lib/module-datetime.html *sleep*( secs) Suspend execution for the given number of seconds. The argument may be a floating point number to indicate a more precise sleep time. The actual suspension time may be less than that requested because any caught signal will terminate the sleep() following execution of that signal's catching routine. Also, the suspension time may be longer than requested by an arbitrary amount because of the scheduling of other activity in the system. Wim On 1/16/06, frank h. wrote: > > Hello > how can I break a loop after a certain amount of time has passed? > > pseudocode: > > with timeout of 60sec: > while True: > pass > > is there a simple way? without resorting to queues etc. (this is a bit > over my head....) > thanks for any insight you might have > -frank > > > On 1/16/06, frank h. wrote: > > Hello > > how can I break a loop after a certain amount of time has passed? > > > > pseudocode: > > > > with timeout of 60sec: > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060116/c0720b62/attachment.html From kent37 at tds.net Mon Jan 16 15:01:37 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 16 Jan 2006 09:01:37 -0500 Subject: [Tutor] timeout In-Reply-To: <60fae7c30601160514j47a9e4acm54df73b0a02474b@mail.gmail.com> References: <60fae7c30601160512ndebe0b0ha72b2ad687514ac2@mail.gmail.com> <60fae7c30601160514j47a9e4acm54df73b0a02474b@mail.gmail.com> Message-ID: <43CBA741.5010304@tds.net> If you just want a delay, as your empty loop pseudocode seems to do, use time.sleep() as Wim suggested. If you are processing in a loop and you want to stop processing after a certain amount of time, you could check time.time() each time through the loop and end when the allotted time has elapsed. If you want to abort the loop from outside the loop, it's a harder problem... Kent frank h. wrote: > Hello > how can I break a loop after a certain amount of time has passed? > > pseudocode: > > with timeout of 60sec: > while True: > pass > > is there a simple way? without resorting to queues etc. (this is a bit > over my head....) > thanks for any insight you might have > -frank > > > On 1/16/06, frank h. wrote: > >>Hello >>how can I break a loop after a certain amount of time has passed? >> >>pseudocode: >> >>with timeout of 60sec: >> > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From catherine.curley at gmail.com Mon Jan 16 15:26:51 2006 From: catherine.curley at gmail.com (catherine curley) Date: Mon, 16 Jan 2006 14:26:51 +0000 Subject: [Tutor] tutorials Message-ID: Hi Has anyone got an easy way of printing the Python documentation in PDF format. Its all in HTML and is time consuming to print. Catherine -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060116/8d09d833/attachment.htm From w.damen at gmail.com Mon Jan 16 16:19:43 2006 From: w.damen at gmail.com (Rinzwind) Date: Mon, 16 Jan 2006 16:19:43 +0100 Subject: [Tutor] PIL, fonts and making images Message-ID: <4677730601160719n2e7eb285o88e8d3cc9743b911@mail.gmail.com> I've been using python wih PIL to create some buttons (automatically inside my program). The following code works and creates a PNG 70x70 with the letter 'p' inside. #!/usr/bin/python import os, sys import Image, ImageFont, ImageDraw image = Image.new('RGBA',(70,70),(0,0,0)) ifo = ImageFont.truetype("arial.ttf",24) #ifo = ImageFont.truetype("MARRFONT.TTF",24) draw = ImageDraw.Draw(image) draw.text((0, 0), 'p', font=ifo) image.save('image.png','PNG') I save this program inside a temp dir and copied arial.ttf inside this directory. It works :-) Want I want though is to do this with MARRFONT.TTF. That is a (free) font that has chesspieces inside. (can be downloaded here: http://antraxja-fonts.iweb.pl/pobierz.php?font=3903 ) The font works: inside the download there's a DOC that I can open with OO.org and that let's me show the chesspieces (after I copied the font to my fontsdir). If I type a 'p' in arial and then change the font it shows a Pawn. Cool isn't it? :) But when I un-comment the line with this font and save it I get a black square. Can anyone tell me why it doesn't work? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060116/232ff226/attachment.html From broek at cc.umanitoba.ca Mon Jan 16 16:59:11 2006 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Mon, 16 Jan 2006 09:59:11 -0600 Subject: [Tutor] tutorials In-Reply-To: References: Message-ID: <43CBC2CF.6010208@cc.umanitoba.ca> catherine curley said unto the world upon 16/01/06 08:26 AM: > Hi > > Has anyone got an easy way of printing the Python documentation in PDF > format. Its all in HTML and is time consuming to print. > > Catherine pdf format is available here: . Best, Brian vdB From hugonz-lists at h-lab.net Mon Jan 16 18:01:11 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Mon, 16 Jan 2006 11:01:11 -0600 Subject: [Tutor] timeout In-Reply-To: <60fae7c30601160514j47a9e4acm54df73b0a02474b@mail.gmail.com> References: <60fae7c30601160512ndebe0b0ha72b2ad687514ac2@mail.gmail.com> <60fae7c30601160514j47a9e4acm54df73b0a02474b@mail.gmail.com> Message-ID: <43CBD157.7010304@h-lab.net> Hi Frank, > how can I break a loop after a certain amount of time has passed? > If the loop actually does something, I've used time.time() in the past: start_time = time.time() timeout = 60 #seconds while True: do_something() if time.time() - start_time >= timeout: break time.time() just keeps increasing as it reports the system's clock (in UNIX epoch time, just increasing seconds) Hope that helps, Hugo From alan.gauld at freenet.co.uk Mon Jan 16 19:20:21 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 16 Jan 2006 18:20:21 -0000 Subject: [Tutor] tutorials References: Message-ID: <003a01c61ac9$8395a950$0b01a8c0@xp> > Has anyone got an easy way of printing the Python documentation in PDF > format. Its all in HTML and is time consuming to print. You can buy it in paper book form. It's a lot cheaper than trying to print the online stuff page by page! Of course someone else may be paying for the paper in which case you may not care about printing costs... But you do realise just how much there is to print - many hundreds of pages, probably well over a thousand! Thats a lot of big ring binders. Alan G From alan.gauld at freenet.co.uk Mon Jan 16 19:17:15 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 16 Jan 2006 18:17:15 -0000 Subject: [Tutor] timeout References: <60fae7c30601160512ndebe0b0ha72b2ad687514ac2@mail.gmail.com> Message-ID: <003201c61ac9$1433de10$0b01a8c0@xp> > how can I break a loop after a certain amount of time has passed? > with timeout of 60sec: I assume you want the loop to do somerthing until the timeout? If so then the logic is: timeout = now() + 60 while now() < timeout: do something. Using the time module you can easily calculate timeout and now. It gets trickier with small values - if you wanted 60ms say, but at the seconds level it works ok. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From victor at grupocdm.com Mon Jan 16 20:12:21 2006 From: victor at grupocdm.com (Victor Bouffier) Date: Mon, 16 Jan 2006 13:12:21 -0600 Subject: [Tutor] Python debugger bummer Message-ID: <1137438741.2770.101.camel@elrond> Hi to all, I tried to look for a reference to this issue in the ASPN archive, but I can't seem to find an answer. I currently work under Linux and have never been able to properly use the Python debugger. Coming from a Perl background, I fail to find a similar simple way to step through my code the way I am able to do it through the -d flag using Perl on the command line. It is so painless. I have used Python on Windows, usually writing my programs using Vim, and entering the PythonWin environment to debug my programs. It is a good environment to do that, although I prefer my independent editor for writing my programs. I once paid for ActiveState's Komodo for Linux to use as an IDE, but I find it bloated and slow, not to mention the need to constantly upgrade if you want to keep up with versions (have not done it yet). Does anyone have any suggestions as to an alternative to PythonWin, or even better still, a reference to a good tutorial on how to use my current tools: how to use the python debugger as the way Perl debugger works? I am certain the Python interpreter (being better that Perl in that sense) must have a way to use the debugger. I work under Linux using vi/gvim and ipython (I have never really tried IDLE). Thanks in advance for any help. Victor From victor at grupocdm.com Mon Jan 16 20:58:12 2006 From: victor at grupocdm.com (Victor Bouffier) Date: Mon, 16 Jan 2006 13:58:12 -0600 Subject: [Tutor] Python debugger bummer In-Reply-To: <1137438741.2770.101.camel@elrond> References: <1137438741.2770.101.camel@elrond> Message-ID: <1137441492.2770.112.camel@elrond> Hi again, I was going through the Python library documentation and I found something I never saw before. $ python -m pdb myscript.py This is what I was looking for! Great help. Any further reference could of course help a lot. I never was able to get the hang of it until now. Victor On Mon, 2006-01-16 at 13:12 -0600, Victor Bouffier wrote: > Hi to all, > > I tried to look for a reference to this issue in the ASPN archive, but I > can't seem to find an answer. > > I currently work under Linux and have never been able to properly use > the Python debugger. Coming from a Perl background, I fail to find a > similar simple way to step through my code the way I am able to do it > through the -d flag using Perl on the command line. It is so painless. > > I have used Python on Windows, usually writing my programs using Vim, > and entering the PythonWin environment to debug my programs. It is a > good environment to do that, although I prefer my independent editor for > writing my programs. > > I once paid for ActiveState's Komodo for Linux to use as an IDE, but I find it > bloated and slow, not to mention the need to constantly upgrade if you > want to keep up with versions (have not done it yet). > > Does anyone have any suggestions as to an alternative to PythonWin, or > even better still, a reference to a good tutorial on how to use my > current tools: how to use the python debugger as the way Perl debugger > works? I am certain the Python interpreter (being better that Perl in > that sense) must have a way to use the debugger. > > I work under Linux using vi/gvim and ipython (I have never really tried > IDLE). > > Thanks in advance for any help. > Victor > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From cspears2002 at yahoo.com Mon Jan 16 21:12:20 2006 From: cspears2002 at yahoo.com (Christopher Spears) Date: Mon, 16 Jan 2006 12:12:20 -0800 (PST) Subject: [Tutor] __getitem__ Message-ID: <20060116201220.5511.qmail@web51605.mail.yahoo.com> I understand that you can use __getitem__ as a hook to modify indexing behavoir in a class. That's why __getitem__ not only affects [] but also for loops, map calls, list comprehension, etc. For loops, etc. work by indexing a sequences from zero to a higher index until out-of-bounds is reached. But why does this work? >>> class stepper: ... def __getitem__(self, i): ... return self.data[i] ... >>> 'p' in X True What does 'in' have to do with indexing? From bgailer at alum.rpi.edu Mon Jan 16 21:23:35 2006 From: bgailer at alum.rpi.edu (bob) Date: Mon, 16 Jan 2006 12:23:35 -0800 Subject: [Tutor] __getitem__ In-Reply-To: <20060116201220.5511.qmail@web51605.mail.yahoo.com> References: <20060116201220.5511.qmail@web51605.mail.yahoo.com> Message-ID: <7.0.0.16.0.20060116122257.023a0828@alum.rpi.edu> At 12:12 PM 1/16/2006, Christopher Spears wrote: >I understand that you can use __getitem__ as a hook to >modify indexing behavoir in a class. That's why >__getitem__ not only affects [] but also for loops, >map calls, list comprehension, etc. For loops, etc. >work by indexing a sequences from zero to a higher >index until out-of-bounds is reached. But why does >this work? > > >>> class stepper: >... def __getitem__(self, i): >... return self.data[i] >... > >>> 'p' in X >True > >What does 'in' have to do with indexing? What does X have to do with stepper? From cspears2002 at yahoo.com Mon Jan 16 21:45:51 2006 From: cspears2002 at yahoo.com (Christopher Spears) Date: Mon, 16 Jan 2006 12:45:51 -0800 (PST) Subject: [Tutor] __getitem__ In-Reply-To: <7.0.0.16.0.20060116122257.023a0828@alum.rpi.edu> Message-ID: <20060116204551.6568.qmail@web51612.mail.yahoo.com> Sorry! X = stepper() X.data = "Spam" --- bob wrote: > At 12:12 PM 1/16/2006, Christopher Spears wrote: > >I understand that you can use __getitem__ as a hook > to > >modify indexing behavoir in a class. That's why > >__getitem__ not only affects [] but also for loops, > >map calls, list comprehension, etc. For loops, > etc. > >work by indexing a sequences from zero to a higher > >index until out-of-bounds is reached. But why does > >this work? > > > > >>> class stepper: > >... def __getitem__(self, i): > >... return self.data[i] > >... > > >>> 'p' in X > >True > > > >What does 'in' have to do with indexing? > > What does X have to do with stepper? > > "I'm the last person to pretend that I'm a radio. I'd rather go out and be a color television set." -David Bowie "Who dares wins" -British military motto "I generally know what I'm doing." -Buster Keaton From cspears2002 at yahoo.com Mon Jan 16 21:50:14 2006 From: cspears2002 at yahoo.com (Christopher Spears) Date: Mon, 16 Jan 2006 12:50:14 -0800 (PST) Subject: [Tutor] __iter__ Message-ID: <20060116205014.51838.qmail@web51603.mail.yahoo.com> I'm not sure if I understand __iter__. You use it to create an object that iterates through itself using a next menthod ? class Squares: def __init__(self, start, stop): self.value = start - 1 self.stop = stop def __iter__(self): return self def next(self): if self.value == self.stop: raise StopIteration self.value += 1 return self.value ** 2 >>> from iters import Squares >>> for i in Squares(1, 5): ... print i, ... 1 4 9 16 25 "I'm the last person to pretend that I'm a radio. I'd rather go out and be a color television set." -David Bowie "Who dares wins" -British military motto "I generally know what I'm doing." -Buster Keaton From shuying at gmail.com Mon Jan 16 21:57:49 2006 From: shuying at gmail.com (Shuying) Date: Tue, 17 Jan 2006 07:57:49 +1100 Subject: [Tutor] setuptools question In-Reply-To: References: <75fa0c3a0601151549w128c9c58mda486485039b89c9@mail.gmail.com> Message-ID: <75fa0c3a0601161257q74a2eb0n6e9b516aefdf70ff@mail.gmail.com> I think I tried python2.4 /usr/bin/easy_install -U setuptools and directly the #! line in easy_install to use python2.4. On 1/16/06, Liam Clarke wrote: > How were you calling easy_install? > > On 1/16/06, Shuying wrote: > > Hi, > > > > I'm not sure where's the best place to ask so I thought I'd try it > > here. I've got python2.3 and python2.4 installed on my machine and > > I'm trying to upgrade setuptools for both versions of python. So I've > > got no problems upgrading setuptools for python2.3 but when I try to > > do the same for python2.4, I get : > > Traceback (most recent call last): > > File "easy_install", line 7, in ? > > sys.exit( > > File "/usr/lib/python2.4/site-packages/setuptools-0.6a5-py2.4.egg/pkg_resources.py", > > line 236, in load_entry_point > > return get_distribution(dist).load_entry_point(group, name) > > File "/usr/lib/python2.4/site-packages/setuptools-0.6a5-py2.4.egg/pkg_resources.py", > > line 229, in get_distribution > > if isinstance(dist,Requirement): dist = get_provider(dist) > > File "/usr/lib/python2.4/site-packages/setuptools-0.6a5-py2.4.egg/pkg_resources.py", > > line 115, in get_provider > > return working_set.find(moduleOrReq) or require(str(moduleOrReq))[0] > > File "/usr/lib/python2.4/site-packages/setuptools-0.6a5-py2.4.egg/pkg_resources.py", > > line 382, in find > > raise VersionConflict(dist,req) # XXX add more info > > pkg_resources.VersionConflict: (setuptools 0.6a5 > > (/usr/lib/python2.4/site-packages/setuptools-0.6a5-py2.4.egg), > > Requirement.parse('setuptools==0.6a9')) > > > > and I'm not sure what's the best way to fix it. Suggestions please! From kent37 at tds.net Mon Jan 16 22:27:36 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 16 Jan 2006 16:27:36 -0500 Subject: [Tutor] __getitem__ In-Reply-To: <20060116201220.5511.qmail@web51605.mail.yahoo.com> References: <20060116201220.5511.qmail@web51605.mail.yahoo.com> Message-ID: <43CC0FC8.9090207@tds.net> Christopher Spears wrote: > I understand that you can use __getitem__ as a hook to > modify indexing behavoir in a class. That's why > __getitem__ not only affects [] but also for loops, > map calls, list comprehension, etc. For loops, etc. > work by indexing a sequences from zero to a higher > index until out-of-bounds is reached. But why does > this work? > > >>>>class stepper: > > ... def __getitem__(self, i): > ... return self.data[i] > ... > >>>>'p' in X > > True > > What does 'in' have to do with indexing? How do you suppose 'in' works? To see if something is in a list, for example, you have to iterate over each element of the list and check if it is the item you expect. Under the hood, Python will use the __contains__() or __getitem__() special method of a class to evaluate 'x in y'. Loosely speaking, if y is an instance of a class that implements __getitem__() but not __contains__(), 'x in y' is more or less the same as this: def in(x, y): for i in y: if i == x: return True return False From the language reference: "For user-defined classes which do not define __contains__() and do define __getitem__(), x in y is true if and only if there is a non-negative integer index i such that x == y[i], and all lower integer indices do not raise IndexError exception. (If any other exception is raised, it is as if in raised that exception)." http://docs.python.org/ref/comparisons.html#l2h-432 Kent From kent37 at tds.net Mon Jan 16 22:33:56 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 16 Jan 2006 16:33:56 -0500 Subject: [Tutor] __iter__ In-Reply-To: <20060116205014.51838.qmail@web51603.mail.yahoo.com> References: <20060116205014.51838.qmail@web51603.mail.yahoo.com> Message-ID: <43CC1144.10903@tds.net> Christopher Spears wrote: > I'm not sure if I understand __iter__. You use it to > create an object that iterates through itself using a > next menthod ? Yes, you seem to have it right. Your code is fine IMO. In many cases it's easier to use a generator than an iterator class. If you are using this in real code (as opposed to just trying to understand __iter__) you should learn about them. Here is your example with a generator: >>> def squares(start, stop): ... for i in range(start, stop+1): ... yield i*i ... >>> for i in squares(1, 5): ... print i, ... 1 4 9 16 25 Learn about generators here: http://www.python.org/doc/2.3.5/whatsnew/section-generators.html Kent > > class Squares: > def __init__(self, start, stop): > self.value = start - 1 > self.stop = stop > def __iter__(self): > return self > def next(self): > if self.value == self.stop: > raise StopIteration > self.value += 1 > return self.value ** 2 > > >>>>from iters import Squares >>>>for i in Squares(1, 5): > > ... print i, > ... > 1 4 9 16 25 > > > "I'm the last person to pretend that I'm a radio. I'd rather go out and be a color television set." > -David Bowie > > "Who dares wins" > -British military motto > > "I generally know what I'm doing." > -Buster Keaton > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From alan.gauld at freenet.co.uk Tue Jan 17 00:35:40 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 16 Jan 2006 23:35:40 -0000 Subject: [Tutor] Python debugger bummer References: <1137438741.2770.101.camel@elrond> <1137441492.2770.112.camel@elrond> Message-ID: <005d01c61af5$90f2aa90$0b01a8c0@xp> > I was going through the Python library documentation and I found > something I never saw before. > > $ python -m pdb myscript.py I was just about to suggest loading pdb... And of course there is also a graphical debugger in IDLE as well as PythonWin. The paper version of my book contains a chapter (not on the web site) on how to use pdb to debug a script. pdb has its limitations but if you are used to gdb then its not too bad. (pdb) help is your friend. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Tue Jan 17 00:45:51 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 16 Jan 2006 23:45:51 -0000 Subject: [Tutor] __getitem__ References: <20060116201220.5511.qmail@web51605.mail.yahoo.com> Message-ID: <006101c61af6$fc952e70$0b01a8c0@xp> > map calls, list comprehension, etc. For loops, etc. > work by indexing a sequences from zero to a higher > index until out-of-bounds is reached. What makes you think that? So far as I know for loops work by calling next on an iterator until nothing gets returned, no indexes involved.(At least not in the for loop) But they could just as well work by calling the len() function and iterating that number of times. And len() could be stored as part of the data structure ala Pascal arrays. The point being that it is dangerous to assume how a language feature works internally, it can change from version to version. In this case the iterator solution means that the for loop can work on any iterable entity - like files for instance. > But why does this work? > >>>> class stepper: > ... def __getitem__(self, i): > ... return self.data[i] > ... >>>> 'p' in X > True > > What does 'in' have to do with indexing? Nothing unless its implementation uses a while loop and index, but thats unlikely. But your code doesn't show what X is, I assume its an instance of stepper? (The convention is for uppercase class names and lower case object names so I'm slightly unsure about that assumption!) But we don't even have the whole of stepper since there is no self.data definition. Its kind of hard to say. I'm slightly confused by the question, sorry. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Tue Jan 17 00:54:22 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 16 Jan 2006 23:54:22 -0000 Subject: [Tutor] __getitem__ References: <20060116204551.6568.qmail@web51612.mail.yahoo.com> Message-ID: <006701c61af8$2d413ea0$0b01a8c0@xp> > Sorry! > > X = stepper() > X.data = "Spam" Aha! The fog in my brain clears. >> > >>> class stepper: >> >... def __getitem__(self, i): >> >... return self.data[i] >> >... >> > >>> 'p' in X >> >True >> > >> >What does 'in' have to do with indexing? To find out if 'p' is in X Python has to step through the data in X. I'm not sure that your getitem is being called, it may just be a string search operation. But I suspect it may assume the data is an iterator and repeatedly call next() till it gets a match or runs out of data. In that case getitem may well get called. a simple print statement in getitem will find out... Alan G. From python at venix.com Mon Jan 16 22:09:10 2006 From: python at venix.com (Python) Date: Mon, 16 Jan 2006 16:09:10 -0500 Subject: [Tutor] Design suggestion - is a cookie the answer? In-Reply-To: <015701c61a39$f2833160$0b01a8c0@xp> References: <00d301c6190d$0630ab80$0b01a8c0@xp> <667ca7b60601141709o39676976l@mail.gmail.com> <015701c61a39$f2833160$0b01a8c0@xp> Message-ID: <1137445750.15004.499.camel@www.venix.com> On Mon, 2006-01-16 at 01:12 +0000, Alan Gauld wrote: > > I'm sure this is implied in Alan's post, but I'm going to point it > out > ... > > To avoid further cheating you might want to sure there is no way to > > submit the form without javascript turned on. E.g. Don't have a > submit > > button and a form with an 'onSubmit' validation. Which some examples > > do use. Otherwise, they can just turn off Javascript support in > their > > browser and bypass your validation. > Javascript might be the appropriate level of paranoia for your situation, however, remember that people do not have to use your form to submit data to your web script. An enterprising student could save the form and edit it him(her)self to bypass any javascript checks or even synthesize their own submit data (e.g. use urllib to supply answers). There is no check to make sure that the answers fed back to the script fit the problems that were written out in the form. Of course any kid who could figure out how to maximize points cheating your script can probably handle simple multiplication. I liked the variable name insertpupilsnick. If Dr Seuss had written a book on programming, I'm sure it would have had variable names like that. -- Lloyd Kvam Venix Corp From john at fouhy.net Tue Jan 17 01:25:56 2006 From: john at fouhy.net (John Fouhy) Date: Tue, 17 Jan 2006 13:25:56 +1300 Subject: [Tutor] Design suggestion - is a cookie the answer? In-Reply-To: <015701c61a39$f2833160$0b01a8c0@xp> References: <00d301c6190d$0630ab80$0b01a8c0@xp> <667ca7b60601141709o39676976l@mail.gmail.com> <015701c61a39$f2833160$0b01a8c0@xp> Message-ID: <5e58f2e40601161625g3075e4cfr@mail.gmail.com> On 16/01/06, Alan Gauld wrote: > No. JavaScript is an event driven paradigm and it only > picks up the explicit events you register with it(*). One of > the problems of using CGI is the ese of frigging it. I assume > you are using GET instead of POST? GET is the default > submission method but POST is nearly always better and > should avoid the problem here. (I think, I haven't tried it!) I believe the python CGI module is submission-method agnostic --- your code doesn't need to know or care whether the data was submitted using POST or GET. So, even if you are using POST, clever kids could, I think, construct a GET url to do the same thing. -- John. From dyoo at hkn.eecs.berkeley.edu Tue Jan 17 02:34:32 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 16 Jan 2006 17:34:32 -0800 (PST) Subject: [Tutor] Design suggestion - is a cookie the answer? In-Reply-To: <5e58f2e40601161625g3075e4cfr@mail.gmail.com> Message-ID: > On 16/01/06, Alan Gauld wrote: > > No. JavaScript is an event driven paradigm and it only picks up the > > explicit events you register with it(*). One of the problems of using > > CGI is the ese of frigging it. I assume you are using GET instead of > > POST? GET is the default submission method but POST is nearly always > > better and should avoid the problem here. (I think, I haven't tried > > it!) > > I believe the python CGI module is submission-method agnostic --- your > code doesn't need to know or care whether the data was submitted using > POST or GET. So, even if you are using POST, clever kids could, I > think, construct a GET url to do the same thing. Sorry I missed most of this thread! I wanted to interject that there are some experimental web frameworks that might allow us to get around the issues with browser reload. Most of these fall under "continuation-based" web frameworks. For example, CherryFlow: http://subway.python-hosting.com/wiki/CherryFlow There are links on that page that talk about this in more detail. However, I have to admit that the only continuation web frameworks I've been playing with have been in PLT Scheme, so I'm not so sure how mature the Python implementations are. Best of wishes! From dyoo at hkn.eecs.berkeley.edu Tue Jan 17 02:41:00 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 16 Jan 2006 17:41:00 -0800 (PST) Subject: [Tutor] PIL, fonts and making images In-Reply-To: <4677730601160719n2e7eb285o88e8d3cc9743b911@mail.gmail.com> Message-ID: > Want I want though is to do this with MARRFONT.TTF. That is a (free) font > that has chesspieces inside. (can be downloaded here: > http://antraxja-fonts.iweb.pl/pobierz.php?font=3903 ) Hi Rinzwind, You might want to contact the folks who make that font: according to the Fontbook on my Mac OS X box, that particular font has serious problems. My system says that it's defective because it's missing a "Font Name Table", whatever that is. Best of wishes to you! From dyoo at hkn.eecs.berkeley.edu Tue Jan 17 02:57:37 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 16 Jan 2006 17:57:37 -0800 (PST) Subject: [Tutor] __iter__ In-Reply-To: <20060116205014.51838.qmail@web51603.mail.yahoo.com> Message-ID: On Mon, 16 Jan 2006, Christopher Spears wrote: > I'm not sure if I understand __iter__. You use it to create an object > that iterates through itself using a next menthod ? Hi Chris, Yes, that's one application. But __iter__() doesn't necessarily have to return 'self'. For example, here's a useless toy class that might help explain what can happen if we do so without thinking: ################################ class MyListOfNumbers: def __init__(self, data): self.data = data def __iter__(self): return Pointer(self) class Pointer: def __init__(self, numbers): self.numbers = numbers self.offset = 0 def next(self): if self.offset == len(self.numbers.data): raise StopIteration element = self.numbers.data[self.offset] self.offset = self.offset + 1 return element ################################ Let's see how this might work: ####### >>> nums = MyListOfNumbers([0, 1]) >>> for x in nums: ... for y in nums: ... print x, y ... 0 0 0 1 1 0 1 1 ####### Now imagine what might happen if we didn't return a separate Pointer iterator: ################################################ class MyListOfNumbers2: def __init__(self, data): self.data = data self.offset = 0 def __iter__(self): return self def next(self): if self.offset == len(self.data): raise StopIteration element = self.data[self.offset] self.offset = self.offset + 1 return element #################################################### On a glance, this also looks reasonable: ###### >>> nums = MyListOfNumbers2([3, 1, 4, 1, 5]) >>> for n in nums: ... print n ... 3 1 4 1 5 ###### But, of course, you know that there has to be SOMETHING wrong here. *grin* And here's one example that shows a problem: ###### >>> nums = MyListOfNumbers2([0, 1]) >>> for x in nums: ... for y in nums: ... print x, y ... 0 1 >>> ###### We expected to see all pairs of 0-1 combinations, but came up way short. Do you know why? Best of wishes! From victor at grupocdm.com Tue Jan 17 03:23:36 2006 From: victor at grupocdm.com (Victor Bouffier) Date: Mon, 16 Jan 2006 20:23:36 -0600 Subject: [Tutor] Python debugger bummer In-Reply-To: <005d01c61af5$90f2aa90$0b01a8c0@xp> References: <1137438741.2770.101.camel@elrond> <1137441492.2770.112.camel@elrond> <005d01c61af5$90f2aa90$0b01a8c0@xp> Message-ID: <1137464616.18493.0.camel@elrond> Thanks Alan. As always, you are very helpful. Victor On Mon, 2006-01-16 at 23:35 +0000, Alan Gauld wrote: > > I was going through the Python library documentation and I found > > something I never saw before. > > > > $ python -m pdb myscript.py > > I was just about to suggest loading pdb... > > And of course there is also a graphical debugger in IDLE as > well as PythonWin. > > The paper version of my book contains a chapter > (not on the web site) on how to use pdb to debug a script. > pdb has its limitations but if you are used to gdb then its > not too bad. > > (pdb) help > > is your friend. > > Alan G > Author of the learn to program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld > > From james2dope at yahoo.com Tue Jan 17 03:43:44 2006 From: james2dope at yahoo.com (james middendorff) Date: Mon, 16 Jan 2006 18:43:44 -0800 (PST) Subject: [Tutor] help Message-ID: <20060117024345.97274.qmail@web31003.mail.mud.yahoo.com> I am trying to do some AGI scripting with python and asterisk, I read the book, Asterisk the Future of Telephony, which has an example of AGI + python. I have found that none of the example seems to work. My question is I have figured out how to play a recorded message sys.stdout.write('EXEC PLAYBACK name "*#"') then you do sys.stdout.flush() and you will get your message played. In the book it shows if you want to capture something the user inputs you do result = sys.stdin.readline().strip() but when I add that to my line I cannot get my message to be played? Am I totally off on this. All I want it to make a message play, then capture their input, and put it to use in the rest of my python script? Thanks for any help. I hope someone else is playing with asterisk and python James "I would kill everyone in this room for a drop of sweet beer." ----Homer Simpson---- __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From w.damen at gmail.com Tue Jan 17 11:58:57 2006 From: w.damen at gmail.com (Rinzwind) Date: Tue, 17 Jan 2006 11:58:57 +0100 Subject: [Tutor] __iter__ In-Reply-To: <4677730601170053i59d08a85s70e2383c596e99d7@mail.gmail.com> References: <20060116205014.51838.qmail@web51603.mail.yahoo.com> <4677730601170053i59d08a85s70e2383c596e99d7@mail.gmail.com> Message-ID: <4677730601170258w530e47b9pa0f7d43e9a29b178@mail.gmail.com> danny: my apologies for sending this to your email instead of the list!! (There I was looking at the list going: WTF DOES IT TAKE SO LONG when it hit me...). *cuts in* No I don't :-) With this: class MyListOfNumbers: def __init__(self, data): self.data = data def __iter__(self): return Pointer(self) class Pointer: def __init__(self, numbers): self.numbers = numbers self.offset = 0 def next(self): if self.offset == len(self.numbers.data): raise StopIteration element = self.numbers.data[self.offset] self.offset = self.offset + 1 return element Where/how/when is 'def next(self(:' called? Oh and if someone has some newby tut's on this I'd appreciate it. All I find are not-so-newby-friendly websites regarding to classes :(* Wim > On 1/17/06, Danny Yoo wrote: > > > > > > On Mon, 16 Jan 2006, Christopher Spears wrote: > > > > > I'm not sure if I understand __iter__. You use it to create an object > > > that iterates through itself using a next menthod ? > > > > Hi Chris, > > > > Yes, that's one application. > > > > > > But __iter__() doesn't necessarily have to return 'self'. For example, > > here's a useless toy class that might help explain what can happen if we > > do so without thinking: > > > > ################################ > > class MyListOfNumbers: > > def __init__(self, data): > > self.data = data > > def __iter__(self): > > return Pointer(self) > > > > > > class Pointer: > > def __init__(self, numbers): > > self.numbers = numbers > > self.offset = 0 > > def next(self): > > if self.offset == len(self.numbers.data): > > raise StopIteration > > element = self.numbers.data[self.offset] > > self.offset = self.offset + 1 > > return element > > ################################ > > > > Let's see how this might work: > > > > ####### > > >>> nums = MyListOfNumbers([0, 1]) > > >>> for x in nums: > > ... for y in nums: > > ... print x, y > > ... > > 0 0 > > 0 1 > > 1 0 > > 1 1 > > ####### > > > > > > > > Now imagine what might happen if we didn't return a separate Pointer > > iterator: > > > > ################################################ > > class MyListOfNumbers2: > > def __init__(self, data): > > self.data = data > > self.offset = 0 > > > > def __iter__(self): > > return self > > > > def next(self): > > if self.offset == len(self.data): > > raise StopIteration > > element = self.data[self.offset] > > self.offset = self.offset + 1 > > return element > > #################################################### > > > > On a glance, this also looks reasonable: > > > > ###### > > >>> nums = MyListOfNumbers2([3, 1, 4, 1, 5]) > > >>> for n in nums: > > ... print n > > ... > > 3 > > 1 > > 4 > > 1 > > 5 > > ###### > > > > > > But, of course, you know that there has to be SOMETHING wrong here. > > *grin* > > > > And here's one example that shows a problem: > > > > ###### > > >>> nums = MyListOfNumbers2([0, 1]) > > >>> for x in nums: > > ... for y in nums: > > ... print x, y > > ... > > 0 1 > > >>> > > ###### > > > > We expected to see all pairs of 0-1 combinations, but came up way short. > > Do you know why? > > > > > > Best of wishes! > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > From jonathan.r.moore at gmail.com Tue Jan 17 12:04:20 2006 From: jonathan.r.moore at gmail.com (Jon Moore) Date: Tue, 17 Jan 2006 11:04:20 +0000 Subject: [Tutor] Guess Your Number Game Message-ID: Hi I hope someone can help me! I am currently learning Python using a book by Michael Dawson. In one of the exercises I have to right a program that will guess a number chosen by the user. It is partly working, however it does not seem to keep state of numbers that should have already been ruled out as too high or low. Any pointers would be very much appreciated! import random print "Welcome to 'Guess Your Number'!" print "\nThink of a number between 1 and 100." print "And I will try and guess it!\n" print "Valid inputs are: higher, lower and correct." raw_input("\n\nPress enter once you have thought of a number.") # set the initial values guess = random.randrange(100) + 1 tries = 1 # guessing loop response = "" while response != "correct": print "Is it" ,guess, "?\n" response = raw_input ("") if response == "lower": guess = random.randrange(1, guess) elif response == "higher": guess = random.randrange(guess, 100) # Error message for invalid inputs else: print "Invalid entry!" tries += 1 print "\nI guessed it! The number was", guess print "And it only took me", tries, "tries!\n" raw_input("\n\nPress the enter key to exit.") -- Best Regards Jon -- Best Regards Jon Moore -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060117/ab245511/attachment.html From kent37 at tds.net Tue Jan 17 12:28:12 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 17 Jan 2006 06:28:12 -0500 Subject: [Tutor] __getitem__ In-Reply-To: <006101c61af6$fc952e70$0b01a8c0@xp> References: <20060116201220.5511.qmail@web51605.mail.yahoo.com> <006101c61af6$fc952e70$0b01a8c0@xp> Message-ID: <43CCD4CC.8040103@tds.net> Alan Gauld wrote: >>map calls, list comprehension, etc. For loops, etc. >>work by indexing a sequences from zero to a higher >>index until out-of-bounds is reached. > > > What makes you think that? > So far as I know for loops work by calling next on > an iterator until nothing gets returned, no indexes > involved.(At least not in the for loop) But they could > just as well work by calling the len() function and > iterating that number of times. And len() could be > stored as part of the data structure ala Pascal arrays. Hmm. From the language ref description of 'for': "The expression list is evaluated once; it should yield an iterable object." which begs the question of, what is an iterable object? The iterator protocol was introduced in Python 2.2; the "What's New" document give a good description of the old and new methods of iterating. Prior to Python 2.2, the _only_ way to make an object iterable was to give in a __getitem__() method. With Python 2.2 you can alternatively define __iter__(). http://www.python.org/doc/2.2.3/whatsnew/node4.html From the language ref description of __getitem__(): "Note: for loops expect that an IndexError will be raised for illegal indexes to allow proper detection of the end of the sequence." In fact a class that just defines __getitem__() can be iterated in a for loop: >>> class stepper: ... def __getitem__(self, i): ... if i < 5: return i ... raise IndexError ... >>> for i in stepper(): print i ... 0 1 2 3 4 > > The point being that it is dangerous to assume how > a language feature works internally, it can change from > version to version. Dangerous to assume, maybe, but special methods are there to be used, and the usage is generally well understood if not always well documented. > > In this case the iterator solution means that the for > loop can work on any iterable entity - like files for > instance. Yes, and for backward compatibility it also works on anything implementing __getitem__(). In fact strings have no __iter__() method, they use __getitem__(): >>> ''.__iter__ Traceback (most recent call last): File "", line 1, in ? AttributeError: 'str' object has no attribute '__iter__' >>> ''.__getitem__ > > >>But why does this work? >> >> >>>>>class stepper: >> >>... def __getitem__(self, i): >>... return self.data[i] >>... >> >>>>>'p' in X >> >>True >> >>What does 'in' have to do with indexing? > > > Nothing unless its implementation uses a while loop > and index, but thats unlikely. But that is pretty close to what actually happens, according to the language ref docs for 'in' (see my previous post). Kent From kent37 at tds.net Tue Jan 17 12:32:31 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 17 Jan 2006 06:32:31 -0500 Subject: [Tutor] __iter__ In-Reply-To: References: Message-ID: <43CCD5CF.3040201@tds.net> Danny Yoo wrote: > > On Mon, 16 Jan 2006, Christopher Spears wrote: > > >>I'm not sure if I understand __iter__. You use it to create an object >>that iterates through itself using a next menthod ? > > > Hi Chris, > > Yes, that's one application. > > > But __iter__() doesn't necessarily have to return 'self'. For example, > here's a useless toy class that might help explain what can happen if we > do so without thinking: > > ################################ > class MyListOfNumbers: > def __init__(self, data): > self.data = data > def __iter__(self): > return Pointer(self) > > > class Pointer: > def __init__(self, numbers): > self.numbers = numbers > self.offset = 0 > def next(self): > if self.offset == len(self.numbers.data): > raise StopIteration > element = self.numbers.data[self.offset] > self.offset = self.offset + 1 > return element > ################################ One small correction: Pointer should have an __iter__() method that returns self; this is part of the iterator protocol. See PEP 234 http://www.python.org/peps/pep-0234.html Kent From w.damen at gmail.com Tue Jan 17 13:25:26 2006 From: w.damen at gmail.com (Rinzwind) Date: Tue, 17 Jan 2006 13:25:26 +0100 Subject: [Tutor] Guess Your Number Game In-Reply-To: References: Message-ID: <4677730601170425t5d9ebf28m75c00b1f20229091@mail.gmail.com> On 1/17/06, Jon Moore wrote: > Hi > > I hope someone can help me! > > I am currently learning Python using a book by Michael Dawson. In one of the > exercises I have to right a program that will guess a number chosen by the > user. > > It is partly working, however it does not seem to keep state of numbers that > should have already been ruled out as too high or low. > > Any pointers would be very much appreciated! > > import random > > print "Welcome to 'Guess Your Number'!" > print "\nThink of a number between 1 and 100." > print "And I will try and guess it!\n" > print "Valid inputs are: higher, lower and correct." > > raw_input("\n\nPress enter once you have thought of a number.") > > > # set the initial values > guess = random.randrange(100) + 1 > tries = 1 > > > > # guessing loop > response = "" > while response != "correct": > print "Is it" ,guess, "?\n" > response = raw_input ("") > if response == "lower": > guess = random.randrange(1, guess) > elif response == "higher": > guess = random.randrange(guess, 100) > > > # Error message for invalid inputs > else: > print "Invalid entry!" > > > tries += 1 > > > print "\nI guessed it! The number was", guess > print "And it only took me", tries, "tries!\n" > > > raw_input("\n\nPress the enter key to exit.") > > -- > Best Regards > > Jon > > -- > Best Regards > > Jon Moore > sidenote: Hello, 1 thing I spotted: response = raw_input ("") if response == "lower": guess = random.randrange(1, guess) tries += 1 elif response == "higher": guess = random.randrange(guess, 100) tries += 1 # Error message for invalid inputs else: print "Invalid entry!" I myself consider an invalid entry not as a valid try ;) These 2 lines are wrong: > guess = random.randrange(1, guess) > guess = random.randrange(guess, 100) The 1 and 100 are being reset and if the answer WAS lower and is NOW higher you lost your 1st boundary. 1 and 100 should be the previous answer. Regarding your problem: A test needs to be between the highest lowest answer and the lowest highest answer you get. You test between 1 and guess and guess and 100. The 1 and 100 reset your boundary back to the original problem: it needs to be between 1 and 100. number = 40 random = 60 answer lower next test you do is between 1 and guess. new random = 20 answer = higher but now you test between 20 and 100 and NOT between 20 and 60 (<- lowest highest number). From kent37 at tds.net Tue Jan 17 14:31:01 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 17 Jan 2006 08:31:01 -0500 Subject: [Tutor] __getitem__ In-Reply-To: <43CCD4CC.8040103@tds.net> References: <20060116201220.5511.qmail@web51605.mail.yahoo.com> <006101c61af6$fc952e70$0b01a8c0@xp> <43CCD4CC.8040103@tds.net> Message-ID: <43CCF195.1010506@tds.net> Kent Johnson wrote: > Alan Gauld wrote: >>>What does 'in' have to do with indexing? >> >> >>Nothing unless its implementation uses a while loop >>and index, but thats unlikely. > > > But that is pretty close to what actually happens, according to the > language ref docs for 'in' (see my previous post). I'm curious enough about this (OK, I admit it, I like to be right, too ;) to dig in to the details, if anyone is interested...one of the benefits of Python being open-source is you can find out how it works... First step, look at the bytecodes: >>> import dis >>> def f(x, y): ... return x in y ... >>> dis.dis(f) 2 0 LOAD_FAST 0 (x) 3 LOAD_FAST 1 (y) 6 COMPARE_OP 6 (in) 9 RETURN_VALUE So 'in' is implemented as a COMPARE_OP. Looking in ceval.c for COMPARE_OP, it has some optimizations for a few fast compares, then calls cmp_outcome() which, for 'in', calls PySequence_Contains(). PySequence_Contains() is implemented in abstract.c. If the container implements __contains__, that is called, otherwise _PySequence_IterSearch() is used. _PySequence_IterSearch() calls PyObject_GetIter() to constuct an iterator on the sequence, then goes into an infinite loop (for (;;)) calling PyIter_Next() on the iterator until the item is found or the call to PyIter_Next() returns an error. PyObject_GetIter() is also in abstract.c. If the object has an __iter__() method, that is called, otherwise PySeqIter_New() is called to construct an iterator. PySeqIter_New() is implemented in iterobject.c. It's next() method is in iter_iternext(). This method calls __getitem__() on its wrapped object and increments an index for next time. So, though the details are complex, I think it is pretty fair to say that the implementation uses a while loop (in _PySequence_IterSearch()) and a counter (wrapped in PySeqIter_Type) to implement 'in' on a container that defines __getitem__ but not __iter__. By the way the implementation of 'for' also calls PyObject_GetIter(), so it uses the same mechanism to generate an iterator for a sequence that defines __getitem__(). Kent From alan.gauld at freenet.co.uk Tue Jan 17 15:34:28 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 17 Jan 2006 14:34:28 -0000 Subject: [Tutor] Design suggestion - is a cookie the answer? References: <00d301c6190d$0630ab80$0b01a8c0@xp><667ca7b60601141709o39676976l@mail.gmail.com><015701c61a39$f2833160$0b01a8c0@xp> <5e58f2e40601161625g3075e4cfr@mail.gmail.com> Message-ID: <008c01c61b73$1fb6cae0$0b01a8c0@xp> > > you are using GET instead of POST? GET is the default > > submission method but POST is nearly always better and > > should avoid the problem here. (I think, I haven't tried it!) > > I believe the python CGI module is submission-method agnostic Thats true, but to frig it you would need to know how to read and interpret html form code and how to manually construct a GET url string complete with correct escape characters etc. It isn't impossible but simply answering the quiz is a lot easier! ;-) In fact any kid smart enough to do all of that probably deserves to marks anyhow, regardless of cheating! Alan G. From andy.senoaji at gmail.com Tue Jan 17 18:11:38 2006 From: andy.senoaji at gmail.com (andy senoaji) Date: Tue, 17 Jan 2006 09:11:38 -0800 Subject: [Tutor] Open file error Message-ID: <85e10d320601170911r66b62a18u754e1b1c4f510d8b@mail.gmail.com> I am starting to pull my hair here. There were some postings in the past, similar to my problem, but the response was not clear enough. Sorry if you thingk I am reposting this. I am trying to run (on an XP box) a simple open file using this: f = open(r'C:\Test.txt', 'r') but it keeps give me nagging error of: Traceback (most recent call last): File "", line 1, in -toplevel- f = open('Test.txt', 'r') IOError: [Errno 2] No such file or directory: 'C:\Test.txt' I know for sure that the file is there, I even put copies of the files here and there, just to guess how python does the file search, but it keeps giving me 'No such file or directory'. i also tried variation of the file location string, but gave me a variation of errors :). Any suggestions? Furthermore, how does Python assumes the search path? Will it look at /LIB first? How does it knows drive lettering, network mapping etc? Is there a configuration settings that I can tweak in my Python? FYI I am using Activestate's. Thx, Andy -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060117/9ebe0f2d/attachment.html From pkraus at pelsupply.com Tue Jan 17 18:23:32 2006 From: pkraus at pelsupply.com (Paul Kraus) Date: Tue, 17 Jan 2006 12:23:32 -0500 Subject: [Tutor] Open file error In-Reply-To: <85e10d320601170911r66b62a18u754e1b1c4f510d8b@mail.gmail.com> References: <85e10d320601170911r66b62a18u754e1b1c4f510d8b@mail.gmail.com> Message-ID: <200601171223.32152.pkraus@pelsupply.com> On Tuesday 17 January 2006 12:11 pm, andy senoaji wrote: > I am starting to pull my hair here. There were some postings in the past, > similar to my problem, but the response was not clear enough. Sorry if you > thingk I am reposting this. > > I am trying to run (on an XP box) a simple open file using this: > f = open(r'C:\Test.txt', 'r')Newbie here but shouldn't it be. Newbie Here f = open( r'C:\\Test.txt','r') I think you are escaping the T with \T. Paul From carroll at tjc.com Tue Jan 17 18:46:36 2006 From: carroll at tjc.com (Terry Carroll) Date: Tue, 17 Jan 2006 09:46:36 -0800 (PST) Subject: [Tutor] Open file error In-Reply-To: <200601171223.32152.pkraus@pelsupply.com> Message-ID: On Tue, 17 Jan 2006, Paul Kraus wrote: > On Tuesday 17 January 2006 12:11 pm, andy senoaji wrote: > > I am starting to pull my hair here. There were some postings in the past, > > similar to my problem, but the response was not clear enough. Sorry if you > > thingk I am reposting this. > > > > I am trying to run (on an XP box) a simple open file using this: > > f = open(r'C:\Test.txt', 'r')Newbie here but shouldn't it be. > > Newbie Here > > f = open( r'C:\\Test.txt','r') > > I think you are escaping the T with \T. No, not if he's indicating a raw string (r' '). It should work: >>> f = open(r'C:\Test.txt', 'r') >>> f Although, even with non-raw strings, I prefer to use the forward-slash, making escaping unnecessary: >>> f = open('C:/Test.txt', 'r') >>> f But I suspect that won't help our questioner. My only suggestion is that he make very certain that the file's really there. For example, what does he get if he types: type c:\Test.txt from the DOS prompt? From python at venix.com Tue Jan 17 18:50:06 2006 From: python at venix.com (Python) Date: Tue, 17 Jan 2006 12:50:06 -0500 Subject: [Tutor] Open file error In-Reply-To: <85e10d320601170911r66b62a18u754e1b1c4f510d8b@mail.gmail.com> References: <85e10d320601170911r66b62a18u754e1b1c4f510d8b@mail.gmail.com> Message-ID: <1137520206.15004.539.camel@www.venix.com> On Tue, 2006-01-17 at 09:11 -0800, andy senoaji wrote: > I am starting to pull my hair here. There were some postings in the > past, similar to my problem, but the response was not clear enough. > Sorry if you thingk I am reposting this. > > I am trying to run (on an XP box) a simple open file using this: > f = open(r'C:\Test.txt', 'r') This looks correct! > > but it keeps give me nagging error of: > Traceback (most recent call last): > File "", line 1, in -toplevel- > f = open('Test.txt', 'r') This is not the same is the line above! > IOError: [Errno 2] No such file or directory: 'C:\Test.txt' And this does not match *either* of the lines above. If you really use that first line, I would expect it to work. If you get an error, from that line, the file will be identified as: 'C:\\Test.txt' > > I know for sure that the file is there, I even put copies of the files > here and there, just to guess how python does the file search, but it > keeps giving me 'No such file or directory'. i also tried variation of > the file location string, but gave me a variation of errors :). Any > suggestions? > > Furthermore, how does Python assumes the search path? Will it look > at /LIB first? How does it knows drive lettering, network mapping etc? > Is there a configuration settings that I can tweak in my Python? FYI I > am using Activestate's. > > > Thx, > > Andy > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From kvander11 at gmail.com Tue Jan 17 18:50:09 2006 From: kvander11 at gmail.com (Kirk Vander Meulen) Date: Tue, 17 Jan 2006 11:50:09 -0600 Subject: [Tutor] string object into reference Message-ID: <2d0c08ca0601170950v49045691ga39850575482daee@mail.gmail.com> Hi, just joined. I've got a question that I'm guessing there's a ridiculously easy answer to, but I'm having trouble (no excuses, I'm just dumb!)... My problem is I want to make a string object into a reference to another object. To be more specific, I'm reading through a text file of amino acids. The first item on each line is the amino acid name, and a later item is its exposed surface area. For each amino acid, I want to add up the surface area as I go through the text file. So what I'm doing is, for each line, assigning the reference 'residue' to the amino acid name. I'd like to then make the string referred to by 'residue' (eg, 'CYS' or 'TRP') a reference to an object that I will subsquently increment by the surface area value. Thanks for any help. Perhaps I just need to be pointed to a relevent thread or given the correct words to search for in the archives or manual. Kirk -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060117/d84b7675/attachment.htm From alan.gauld at freenet.co.uk Tue Jan 17 19:00:36 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 17 Jan 2006 18:00:36 -0000 Subject: [Tutor] __getitem__ References: <20060116201220.5511.qmail@web51605.mail.yahoo.com> <006101c61af6$fc952e70$0b01a8c0@xp><43CCD4CC.8040103@tds.net> <43CCF195.1010506@tds.net> Message-ID: <00b201c61b8f$ebb3f2f0$0b01a8c0@xp> >>>Nothing unless its implementation uses a while loop >>>and index, but thats unlikely. >> >> >> But that is pretty close to what actually happens, according to the >> language ref docs for 'in' (see my previous post). Only in certain cases. The point I was making (or trying to) is that both loops actually depend on how iterators work - and they currently use indexes, but the loops themselves don't. And its quite possible, likely even, that generic iterator code could appear that doesn't even store an index at all. > PySequence_Contains() is implemented in abstract.c. If the container > implements __contains__, that is called, otherwise > _PySequence_IterSearch() is used. And at this point we are out of the loop code and into iterator code which it where the index is stored. > So, though the details are complex, I think it is pretty fair to say > that the implementation uses a while loop (in _PySequence_IterSearch()) > and a counter (wrapped in PySeqIter_Type) to implement 'in' on a > container that defines __getitem__ but not __iter__. I'd say the implementation uses a while loop which uses an iterator and no counter - it relies on the iterator throwing an exception to detect the end, the loop code has no index and neither does the 'in' code. The 'in' is two levels of abstraction away from the index. > By the way the implementation of 'for' also calls PyObject_GetIter(), so > it uses the same mechanism to generate an iterator for a sequence that > defines __getitem__(). Which is what I said, it relies on the iterator. (But I didn't know about the legacy getitem() branch! ) In each case if the way iterators work changes the loops will carry on as they are. I'm actually surprised the C implementation uses an index, - I thought it would just manipulate pointers - but given the getitem mechanism maybe its not so surprising. Thanks for doing the research - I was too lazy to do it myself ;-) Alan G. From alan.gauld at freenet.co.uk Tue Jan 17 19:06:33 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 17 Jan 2006 18:06:33 -0000 Subject: [Tutor] Open file error References: <85e10d320601170911r66b62a18u754e1b1c4f510d8b@mail.gmail.com> Message-ID: <00ba01c61b90$bff96130$0b01a8c0@xp> > I am trying to run (on an XP box) a simple open file using this: > f = open(r'C:\Test.txt', 'r') > IOError: [Errno 2] No such file or directory: 'C:\Test.txt' > I know for sure that the file is there > Furthermore, how does Python assumes the search path? There is no search, you have specified exactly where to look so Python will look there and nowhere else. But it may not be able to open the file if it belongs to someone else who has denied access. Have you checked the security settings on C:\Test.txt? Thats the only other thing that I can think of if you are sure that a file called Test.txt exists in the root directory of the C drive. > How does it knows drive lettering, network mapping etc? Because you explicitly tell it. If you don;t specify the full path it will look in the current directory. You can find that with the os.getcwd() function. See my OS topic for more on how to test file status... http://www.freenetpages.co.uk/hp/alan.gauld/tutos.htm HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Tue Jan 17 19:08:15 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 17 Jan 2006 18:08:15 -0000 Subject: [Tutor] Open file error References: <85e10d320601170911r66b62a18u754e1b1c4f510d8b@mail.gmail.com> <200601171223.32152.pkraus@pelsupply.com> Message-ID: <00be01c61b90$fcf8c440$0b01a8c0@xp> >> I am trying to run (on an XP box) a simple open file using this: >> f = open(r'C:\Test.txt', 'r')Newbie here but shouldn't it be. > > Newbie Here > > f = open( r'C:\\Test.txt','r') > > I think you are escaping the T with \T. The r in front of the string should prevent that problem. If the r wasn't there you would be right and he would need to escape the \ ...or use a forward slash! Alan G. From dyoo at hkn.eecs.berkeley.edu Tue Jan 17 19:21:00 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 17 Jan 2006 10:21:00 -0800 (PST) Subject: [Tutor] PIL, fonts and making images (fwd) Message-ID: ---------- Forwarded message ---------- Date: Tue, 17 Jan 2006 09:47:58 +0100 From: Rinzwind To: Danny Yoo Subject: Re: PIL, fonts and making images That's not good. Well I guess it does what it is suppose to do: make it able to create diagrams and the person who made them didn't intend them to be used as text. Oh and I guess it's made for Windows :P Pity. My idea seemed cool when I thought of it :-) Oh and I did it with a detour: opened up GIMP and made my own 90x90 PNG's. In my new 'chess' game I'll convert them to smaller if needed. It's just that with the way I tgought I'd do it I'd be able to have a fonts dir and people could add their own and I'd automagically made them into screens. I'll have a look at another chess font when I am home if it's also with others (only tried with one :-P ) On 1/17/06, Danny Yoo wrote: > > Want I want though is to do this with MARRFONT.TTF. That is a (free) font > > that has chesspieces inside. (can be downloaded here: > > http://antraxja-fonts.iweb.pl/pobierz.php?font=3903 ) > > Hi Rinzwind, > > You might want to contact the folks who make that font: according to the > Fontbook on my Mac OS X box, that particular font has serious problems. > My system says that it's defective because it's missing a "Font Name > Table", whatever that is. > > Best of wishes to you! > > From dyoo at hkn.eecs.berkeley.edu Tue Jan 17 19:26:51 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 17 Jan 2006 10:26:51 -0800 (PST) Subject: [Tutor] __iter__ In-Reply-To: <43CCD5CF.3040201@tds.net> Message-ID: > One small correction: Pointer should have an __iter__() method that > returns self; this is part of the iterator protocol. See PEP 234 > http://www.python.org/peps/pep-0234.html Hi Kent, Ah, thank you! Ok, the corrected code is: ################################################# class MyListOfNumbers: def __init__(self, data): self.data = data def __iter__(self): return Pointer(self) class Pointer: def __init__(self, numbers): self.numbers = numbers self.offset = 0 def __iter__(self): return self def next(self): if self.offset == len(self.numbers.data): raise StopIteration element = self.numbers.data[self.offset] self.offset = self.offset + 1 return element ################################################# From python at venix.com Tue Jan 17 19:29:01 2006 From: python at venix.com (Python) Date: Tue, 17 Jan 2006 13:29:01 -0500 Subject: [Tutor] Open file error In-Reply-To: <85e10d320601171003s10ada7efjc3aa66c0c7126310@mail.gmail.com> References: <85e10d320601170911r66b62a18u754e1b1c4f510d8b@mail.gmail.com> <1137520206.15004.539.camel@www.venix.com> <85e10d320601171003s10ada7efjc3aa66c0c7126310@mail.gmail.com> Message-ID: <1137522541.15004.563.camel@www.venix.com> (replying back to the list also) On Tue, 2006-01-17 at 10:03 -0800, andy senoaji wrote: > Sorry for the inconsistent error message. I think I may pasted > incorretcly. I am now in a different machine, and have tested Paul's > suggestion, and it worked. But would the 'r' tackles the escape > sequence? I may misunderstood the intent of the r' switcher here. > > Thanks, > > Andy > f = open(r'C:\Test.txt', 'r') > This looks correct! r'C:\Test.txt' is a raw string. The r'strings' ignore the special use of the backslash character except that a raw string must not end with a backslash. This is strictly a convenience when entering a string. Since Windows uses backslash as the path separator, it helps ease the pain when constructing file paths in Windows. Raw strings are also very helpful when writing regular expression strings which often need to have backspace characters. Internally, a raw string is the same as any other Python string. When Python displays a raw string, Python will show the backslashes as \\ (doubled) because that is usually how you need to enter a backslash. Python does not track (as far as I know) that the string originated as a raw string. In regular strings, the backslash is used to mark characters that need special handling. '\t' is a tab character. '\n' is a newline (linefeed). '\r' is a carriage-return (Enter Key). http://docs.python.org/ref/strings.html provides the detailed documentation about how strings work and the definitive list of backspace usages. > > On 1/17/06, Python wrote: > On Tue, 2006-01-17 at 09:11 -0800, andy senoaji wrote: > > I am starting to pull my hair here. There were some postings > in the > > past, similar to my problem, but the response was not clear > enough. > > Sorry if you thingk I am reposting this. > > > > I am trying to run (on an XP box) a simple open file using > this: > > f = open(r'C:\Test.txt', 'r') > This looks correct! > > > > > but it keeps give me nagging error of: > > Traceback (most recent call last): > > File "", line 1, in -toplevel- > > f = open('Test.txt', 'r') > This is not the same is the line above! > > > IOError: [Errno 2] No such file or directory: 'C:\Test.txt' > And this does not match *either* of the lines above. > > If you really use that first line, I would expect it to > work. If you > get an error, from that line, the file will be identified as: > 'C:\\Test.txt' > > > > > I know for sure that the file is there, I even put copies of > the files > > here and there, just to guess how python does the file > search, but it > > keeps giving me 'No such file or directory'. i also tried > variation of > > the file location string, but gave me a variation of > errors :). Any > > suggestions? > > > > Furthermore, how does Python assumes the search path? Will > it look > > at /LIB first? How does it knows drive lettering, network > mapping etc? > > Is there a configuration settings that I can tweak in my > Python? FYI I > > am using Activestate's. > > > > > > Thx, > > > > Andy > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > -- > Lloyd Kvam > Venix Corp > -- Lloyd Kvam Venix Corp From bgailer at alum.rpi.edu Tue Jan 17 19:20:59 2006 From: bgailer at alum.rpi.edu (bob) Date: Tue, 17 Jan 2006 10:20:59 -0800 Subject: [Tutor] Open file error In-Reply-To: <200601171223.32152.pkraus@pelsupply.com> References: <85e10d320601170911r66b62a18u754e1b1c4f510d8b@mail.gmail.com> <200601171223.32152.pkraus@pelsupply.com> Message-ID: <7.0.0.16.0.20060117100809.023c92d8@alum.rpi.edu> At 09:23 AM 1/17/2006, Paul Kraus wrote: >On Tuesday 17 January 2006 12:11 pm, andy senoaji wrote: > > I am starting to pull my hair here. There were some postings in the past, > > similar to my problem, but the response was not clear enough. Sorry if you > > thingk I am reposting this. > > > > I am trying to run (on an XP box) a simple open file using this: > > f = open(r'C:\Test.txt', 'r')Newbie here but shouldn't it be. > >Newbie Here > >f = open( r'C:\\Test.txt','r') > >I think you are escaping the T with \T. More specifically you show us f = open(r'C:\Test.txt', 'r') but the traceback shows the statement to be f = open('Test.txt', 'r') Something is being lost between these 2 items. When I try f = open( r'C:\Test.txt','r') The traceback reports IOError: [Errno 2] No such file or directory: 'c:\\test.txt' Note the \\ Your traceback reports IOError: [Errno 2] No such file or directory: 'c:\test.txt' confirming the Paul's diagnosis. Are you using IDLE? Are you running a script vs trying a command interactively? From dyoo at hkn.eecs.berkeley.edu Tue Jan 17 19:33:21 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 17 Jan 2006 10:33:21 -0800 (PST) Subject: [Tutor] __iter__ In-Reply-To: <4677730601170258w530e47b9pa0f7d43e9a29b178@mail.gmail.com> Message-ID: > Where/how/when is 'def next(self(:' called? The 'for' loop statement does this internally when it marches across an iterable thing. We can write something something like this: ###################### for item in thing: print item ###################### Python is doing something like this behind the scenes: ###################### iterable = iter(thing) try: while True: item = iterable.next() print item except StopIteration: pass ###################### The for loop is the one that's calling next() repeatedly on its iterable. We can manually call next() ourselves, just to see what happens: ###### >>> names = ['homer', 'marge', 'sideshow bob'] >>> iterable = iter(names) >>> iterable >>> >>> >>> iterable.next() 'homer' >>> iterable.next() 'marge' >>> iterable.next() 'sideshow bob' >>> iterable.next() Traceback (most recent call last): File "", line 1, in ? StopIteration ###### Does this make sense? From ajikoe at gmail.com Tue Jan 17 22:08:20 2006 From: ajikoe at gmail.com (Pujo Aji) Date: Tue, 17 Jan 2006 22:08:20 +0100 Subject: [Tutor] string object into reference In-Reply-To: <2d0c08ca0601170950v49045691ga39850575482daee@mail.gmail.com> References: <2d0c08ca0601170950v49045691ga39850575482daee@mail.gmail.com> Message-ID: Hello Kirk, If I'm not mistaken your idea is referencing two columns: first column is your acid name and the later is your surface area. Later you want to connect the surface area if you name the acid name. If that what you want another question arises... is your acid name is unique. If it is you can make dictionary types. A csb B dsk C dsk you can create mydic = [] mydic['A'] = 'csb' mydic['B'] = 'dsk' mydic['C'] = 'dsk' you have to transform the file into a list and after that start building the dictionary variable. After this dictionary variable is filled. you can get the surface area by typing the acid name such as: print mydic['A'] # will result 'csb' Cheers, pujo On 1/17/06, Kirk Vander Meulen wrote: > > Hi, just joined. I've got a question that I'm guessing there's a > ridiculously easy answer to, but I'm having trouble (no excuses, I'm just > dumb!)... > > My problem is I want to make a string object into a reference to another > object. To be more specific, I'm reading through a text file of amino > acids. The first item on each line is the amino acid name, and a later item > is its exposed surface area. For each amino acid, I want to add up the > surface area as I go through the text file. So what I'm doing is, for each > line, assigning the reference 'residue' to the amino acid name. I'd like to > then make the string referred to by 'residue' (eg, 'CYS' or 'TRP') a > reference to an object that I will subsquently increment by the surface area > value. > > Thanks for any help. Perhaps I just need to be pointed to a relevent > thread or given the correct words to search for in the archives or manual. > > Kirk > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060117/00186bd8/attachment.html From kabads at gmail.com Tue Jan 17 22:13:25 2006 From: kabads at gmail.com (Adam Cripps) Date: Tue, 17 Jan 2006 21:13:25 +0000 Subject: [Tutor] Design suggestion - is a cookie the answer? In-Reply-To: <008c01c61b73$1fb6cae0$0b01a8c0@xp> References: <00d301c6190d$0630ab80$0b01a8c0@xp> <667ca7b60601141709o39676976l@mail.gmail.com> <015701c61a39$f2833160$0b01a8c0@xp> <5e58f2e40601161625g3075e4cfr@mail.gmail.com> <008c01c61b73$1fb6cae0$0b01a8c0@xp> Message-ID: On 1/17/06, Alan Gauld wrote: > > > you are using GET instead of POST? GET is the default > > > submission method but POST is nearly always better and > > > should avoid the problem here. (I think, I haven't tried it!) > > > > I believe the python CGI module is submission-method agnostic > > Thats true, but to frig it you would need to know how to read > and interpret html form code and how to manually construct > a GET url string complete with correct escape characters etc. > > It isn't impossible but simply answering the quiz is a lot easier! ;-) > > In fact any kid smart enough to do all of that probably deserves > to marks anyhow, regardless of cheating! > > Yes, I agree - I haven't disadvantaged the children who have worked this out (2 to date). Ingenuity should never be discouraged. OK - I think I must be using the GET method, as the url is already constructed for them and they just need to put the cursor in the URL bar and hit enter to get points each time. Sorry for not being clearer on this in this first place. Unfortunately, I've not had a chance to look at this (such is the life of a teacher). Hopefully, this weekend, I may get the chance to. Adam -- http://www.monkeez.org PGP key: 0x7111B833 From edgar.antonio.rv at gmail.com Tue Jan 17 23:02:18 2006 From: edgar.antonio.rv at gmail.com (=?ISO-8859-1?Q?Edgar_Antonio_Rodr=EDguez_Velazco?=) Date: Tue, 17 Jan 2006 16:02:18 -0600 Subject: [Tutor] Guess Your Number Game Message-ID: <9378d12c0601171402l6c020f58v6bf1412466e55641@mail.gmail.com> Check this: ########################################################### import random print "Welcome to 'Guess Your Number'!" print "\nThink of a number between 1 and 100." print "And I will try and guess it!\n" print "Valid inputs are: higher, lower and correct." raw_input("\n\nPress enter once you have thought of a number.") # set the initial values x = 1 ## Pay atention to these two variables. y = 100 guess = random.randrange(x, y) ## Now we use them tries = 1 # guessing loop response = "" while response != "correct": print "Is it" ,guess, "?\n" response = raw_input ("") if response == "lower": y = guess ## y is the 100 above, now, we take the guess as "y" and "y" as the maximum value of the parameters of guess. guess = random.randrange(x, y) elif response == "higher": x = guess guess = random.randrange(x, y) ## we take guess as the minimun value of our guess and plug it into x # Error message for invalid inputs else: print "Invalid entry!" tries += 1 print "\nI guessed it! The number was", guess print "And it only took me", tries, "tries!\n" raw_input("\n\nPress the enter key to exit.") #################################################### I hope this can help you. ---- I am newbie, so if I did a mistake I hope you to understand my self ;) --- -- Edgar A. Rodriguez -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060117/e86c241f/attachment.html From victor at grupocdm.com Tue Jan 17 23:31:28 2006 From: victor at grupocdm.com (Victor Bouffier) Date: Tue, 17 Jan 2006 16:31:28 -0600 Subject: [Tutor] string object into reference In-Reply-To: References: <2d0c08ca0601170950v49045691ga39850575482daee@mail.gmail.com> Message-ID: <1137537089.5987.50.camel@elrond> Pujo, I think your solution does not address Kirk's problem. You don't mention the addition of surface areas. If for any reason he had more than two types of amino acids, then he would need to use a dictionary for the totals, with each key being a specific amino acid. The actual steps to follow are: 1. open the file to read 2. initialize the dictionary to empty 3. for each line in the file 4. see if the key for that amino acid already \ exists in the dictionary 5. if it does not exist, create a new dictionary \ key for that new amino acid, and initialize it \ to zero 6. add the surface area of the current line to the \ corresponding dictionary key 7. print the totals dictionary Kirk, I would write the program (would take me less time), but the idea is for yo uto learn to program in Python ;-) Post your code for review. Regards. Victor On Tue, 2006-01-17 at 22:08 +0100, Pujo Aji wrote: > Hello Kirk, > > If I'm not mistaken your idea is referencing two columns: first column > is your acid name and the later is your surface area. > Later you want to connect the surface area if you name the acid name. > If that what you want another question arises... is your acid name is > unique. > If it is you can make dictionary types. > > A csb > B dsk > C dsk > > you can create > mydic = [] > mydic['A'] = 'csb' > mydic['B'] = 'dsk' > mydic['C'] = 'dsk' > > you have to transform the file into a list and after that start > building the dictionary variable. > > After this dictionary variable is filled. you can get the surface area > by typing the acid name such as: > print mydic['A'] # will result 'csb' > > Cheers, > pujo > > On 1/17/06, Kirk Vander Meulen wrote: > Hi, just joined. I've got a question that I'm guessing > there's a ridiculously easy answer to, but I'm having trouble > (no excuses, I'm just dumb!)... > > My problem is I want to make a string object into a reference > to another object. To be more specific, I'm reading through a > text file of amino acids. The first item on each line is the > amino acid name, and a later item is its exposed surface area. > For each amino acid, I want to add up the surface area as I go > through the text file. So what I'm doing is, for each line, > assigning the reference 'residue' to the amino acid name. I'd > like to then make the string referred to by 'residue' (eg, > 'CYS' or 'TRP') a reference to an object that I will > subsquently increment by the surface area value. > > Thanks for any help. Perhaps I just need to be pointed to a > relevent thread or given the correct words to search for in > the archives or manual. > > Kirk > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From victor at grupocdm.com Tue Jan 17 23:38:48 2006 From: victor at grupocdm.com (Victor Bouffier) Date: Tue, 17 Jan 2006 16:38:48 -0600 Subject: [Tutor] string object into reference In-Reply-To: <2d0c08ca0601170950v49045691ga39850575482daee@mail.gmail.com> References: <2d0c08ca0601170950v49045691ga39850575482daee@mail.gmail.com> Message-ID: <1137537529.5987.52.camel@elrond> Ooops. Did not respond to the mailing list. Here is my replied-to post. -------------- Hi Kirk, There is nothing as a dumb question. I am assuming your source file will have a amino acid residue ('CYS' or 'TRP'), followed by a space, and then the corresponding surface area. You have to define a variable for adding the surface areas of each residue type. As you only have one of two options, the easiest way is to define a variable for each (e.g. cys, trp) and then open the file and process each line, adding the surface area to the corresponding amino acid. As for reference, look for working with files (I/O), string variable splitting (split function), and basic operations to add each new surface area. Try writing some code and posting it back. Would be glad to review it. Victor On Tue, 2006-01-17 at 11:50 -0600, Kirk Vander Meulen wrote: > Hi, just joined. I've got a question that I'm guessing there's a > ridiculously easy answer to, but I'm having trouble (no excuses, I'm > just dumb!)... > > My problem is I want to make a string object into a reference to > another object. To be more specific, I'm reading through a text file > of amino acids. The first item on each line is the amino acid name, > and a later item is its exposed surface area. For each amino acid, I > want to add up the surface area as I go through the text file. So > what I'm doing is, for each line, assigning the reference 'residue' to > the amino acid name. I'd like to then make the string referred to by > 'residue' (eg, 'CYS' or 'TRP') a reference to an object that I will > subsquently increment by the surface area value. > > Thanks for any help. Perhaps I just need to be pointed to a relevent > thread or given the correct words to search for in the archives or > manual. > > Kirk > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From dyoo at hkn.eecs.berkeley.edu Wed Jan 18 01:03:16 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 17 Jan 2006 16:03:16 -0800 (PST) Subject: [Tutor] Dictionaries [Was: Re: string object into reference] In-Reply-To: <1137537529.5987.52.camel@elrond> Message-ID: > > My problem is I want to make a string object into a reference to > > another object. To be more specific, I'm reading through a text file > > of amino acids. The first item on each line is the amino acid name, > > and a later item is its exposed surface area. Hi Victor, It sounds like we'd like to maintain a mapping between amino acids and their exposed surface areas. This is traditionally known as a "key-value" pairing, and there are a few things in Python that we can use to represent this. The most direct way of doing this is with a dictionary: http://www.python.org/doc/tut/node7.html#SECTION007500000000000000000 Let's show what dictionaries look like: ###### >>> alphas = {'a': "Alpha", 'b' : 'Beta' } >>> alphas['a'] 'Alpha' >>> alphas['g'] = 'gama' >>> >>> >>> alphas {'a': 'Alpha', 'b': 'Beta', 'g': 'gama'} >>> alphas['g'] = 'gamma' ###### In this way, we can collect a bunch of key-value pairs by setting elements in a dictionary. This is often prefered to having a variable for each key-value pair. A dictionary allows to ask things like this: ###### >>> alphas.keys() ## What keys have we defined? ['a', 'b', 'g'] >>> alphas.values() ## What values do we have? ['Alpha', 'Beta', 'gamma'] ###### These kind of "bulk" questions are fairly easy to answer if we collect all the key-value pairs in a single dictionary container, because we're just asking that one container. But it's much harder to answer this if we use individual variables for each key-value pair, since we don't tell the system that those variables are somehow related as a group --- as far as Python knows, they're just disconnected variables. The terminology that the original poster uses ("references to another object") sounds a lot like the original usage of symbolic "soft" references in Perl. (http://www.perl.com/doc/manual/html/pod/perlref.html) Perl programmers, for the most part, avoid them now because they're so error prone. So if the original poster is thinking about symbolic references, then we should encourage the poster to look into dictionaries, since dictionaries are a fairly direct replacement for that usage. Best of wishes! From ml.cyresse at gmail.com Wed Jan 18 02:23:27 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Wed, 18 Jan 2006 14:23:27 +1300 Subject: [Tutor] [OT] How to report issues with Standard library modules Message-ID: Hi all, After having a frustrating night last night trying to install pyid3lib on XP, which I think is due to something in distutils.core, I'm wondering how I should report it. I have the dotNET framework 2.0 installed, which should give distutils access to the MSVC++ compiler, but it's searching for the 1.1 framework, and so tells me I have no dotNET install. This is a pain in the donkey synonym, but after some mucking about trying to compile the extension myself (which never quite worked) I found that you can specify a different compiler, so I tried mingw32. Unfortunately, that errored to the extent that where the error started exceeded my console buffer, even when set to max. So... does anyone know how to pipe stderr in a cmd.exe console to a file? foo.exe > bob.txt only pipes stdout, stderr is still hitting the screen. Secondly, how and where do bug reports go? I thought I'd ask here because I want to avoid the "noob" comments and "use a real OS" comments... (In the end I gave up and downloaded ATAudio from Plone which had a compiled copy of eyeD3 in it.) I now understand the pain that Linux users feel when they have to deal with software that assumes everyone loves dialogs. Regards, Liam Clarke From nephish at xit.net Wed Jan 18 02:54:07 2006 From: nephish at xit.net (nephish) Date: Tue, 17 Jan 2006 19:54:07 -0600 Subject: [Tutor] quick question about threads Message-ID: <1137549247.8497.6.camel@bitsbam.com> Hey there, i have a program written in python that uses four threads that run all at the same time. Now i want to add a new thread with the same basic structure (threading.thread) that will run only when needed. This one will not run in a loop, it will just run once and quit. So, i may need this to be running several times at once because it will have a 15 second delay written into it. My question is, after the script is done, will it be safe ? i mean, over the course of a few days, it may run this thing a few hundred times. if it is simple like this threading.thread print 'here is something to say' time.sleep(15) print 'here is something else' do i need to include a special command to kill the thread, or will it just finish and everything will be ok then ? thanks for any tips. shawn From forestiero at qwest.net Wed Jan 18 03:06:48 2006 From: forestiero at qwest.net (DogWalker) Date: Tue, 17 Jan 2006 18:06:48 -0800 Subject: [Tutor] Re: [OT] How to report issues with Standard library modules In-Reply-To: References: Message-ID: <20060118020118.30064.70618@linux.local> "Liam Clarke" said: >Hi all, > [...] >So... does anyone know how to pipe stderr in a cmd.exe console to a file? >foo.exe > bob.txt only pipes stdout, stderr is still hitting the screen. > To have stderr go to a separate file: foo.exe > bob.txt &2>err.txt To have stderr go to the same file as stdout: foo.exe > bob.txt &2>&1 [...] From kent37 at tds.net Wed Jan 18 03:53:33 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 17 Jan 2006 21:53:33 -0500 Subject: [Tutor] quick question about threads In-Reply-To: <1137549247.8497.6.camel@bitsbam.com> References: <1137549247.8497.6.camel@bitsbam.com> Message-ID: <43CDADAD.4020904@tds.net> nephish wrote: > Hey there, i have a program written in python that uses four threads > that run all at the same time. Now i want to add a new thread with the > same basic structure (threading.thread) that will run only when needed. > This one will not run in a loop, it will just run once and quit. > So, i may need this to be running several times at once because it will > have a 15 second delay written into it. > My question is, after the script is done, will it be safe ? i mean, over > the course of a few days, it may run this thing a few hundred times. if > it is simple like this > > threading.thread > print 'here is something to say' > time.sleep(15) > print 'here is something else' > > do i need to include a special command to kill the thread, or will it > just finish and everything will be ok then ? Assuming you are showing the run() method of your thread above, it should be fine. If the run() method exits the thread terminates and you don't have to worry about it any more. Make sure you don't keep any references to the threads so they can be garbage-collected. Kent From nephish at xit.net Wed Jan 18 03:59:13 2006 From: nephish at xit.net (nephish) Date: Tue, 17 Jan 2006 20:59:13 -0600 Subject: [Tutor] quick question about threads In-Reply-To: <43CDADAD.4020904@tds.net> References: <1137549247.8497.6.camel@bitsbam.com> <43CDADAD.4020904@tds.net> Message-ID: <1137553153.8781.0.camel@bitsbam.com> all i needed to know, thanks very much shawn On Tue, 2006-01-17 at 21:53 -0500, Kent Johnson wrote: > nephish wrote: > > Hey there, i have a program written in python that uses four threads > > that run all at the same time. Now i want to add a new thread with the > > same basic structure (threading.thread) that will run only when needed. > > This one will not run in a loop, it will just run once and quit. > > So, i may need this to be running several times at once because it will > > have a 15 second delay written into it. > > My question is, after the script is done, will it be safe ? i mean, over > > the course of a few days, it may run this thing a few hundred times. if > > it is simple like this > > > > threading.thread > > print 'here is something to say' > > time.sleep(15) > > print 'here is something else' > > > > do i need to include a special command to kill the thread, or will it > > just finish and everything will be ok then ? > > Assuming you are showing the run() method of your thread above, it > should be fine. If the run() method exits the thread terminates and you > don't have to worry about it any more. Make sure you don't keep any > references to the threads so they can be garbage-collected. > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From victor at grupocdm.com Wed Jan 18 05:48:50 2006 From: victor at grupocdm.com (Victor Bouffier) Date: Tue, 17 Jan 2006 22:48:50 -0600 Subject: [Tutor] Dictionaries [Was: Re: string object into reference] In-Reply-To: References: Message-ID: <1137559730.2964.25.camel@elrond> Hi Danny, On Tue, 2006-01-17 at 16:03 -0800, Danny Yoo wrote: > > > My problem is I want to make a string object into a reference to > > > another object. To be more specific, I'm reading through a text file > > > of amino acids. The first item on each line is the amino acid name, > > > and a later item is its exposed surface area. > > These kind of "bulk" questions are fairly easy to answer if we collect all > the key-value pairs in a single dictionary container, because we're just > asking that one container. > > But it's much harder to answer this if we use individual variables for > each key-value pair, since we don't tell the system that those variables > are somehow related as a group --- as far as Python knows, they're just > disconnected variables. > I couldn't agree more. I love using dictionaries. I don't know why I suggested individual variables instead of the usage of a dictionary in the first place. > > The terminology that the original poster uses ("references to another > object") sounds a lot like the original usage of symbolic "soft" > references in Perl. > (http://www.perl.com/doc/manual/html/pod/perlref.html) > > Perl programmers, for the most part, avoid them now because they're so > error prone. So if the original poster is thinking about symbolic > references, then we should encourage the poster to look into dictionaries, > since dictionaries are a fairly direct replacement for that usage. > I did not know Perl programmers were moving away from references. That's new to me, and an interesting point. On the other hand, Kirk's comment about "references to another object" takes us into a discussion over references, when we actually should be focusing on Perl's hashes (or references to hashes for that matter). Or better still, get away from Perl and start programming in Python and use dictionaries instead! ;-) > Best of wishes! > Thanks a lot. Victor From andy.senoaji at gmail.com Wed Jan 18 06:01:30 2006 From: andy.senoaji at gmail.com (andy senoaji) Date: Tue, 17 Jan 2006 21:01:30 -0800 Subject: [Tutor] Open file error In-Reply-To: <1137522541.15004.563.camel@www.venix.com> References: <85e10d320601170911r66b62a18u754e1b1c4f510d8b@mail.gmail.com> <1137520206.15004.539.camel@www.venix.com> <85e10d320601171003s10ada7efjc3aa66c0c7126310@mail.gmail.com> <1137522541.15004.563.camel@www.venix.com> Message-ID: <85e10d320601172101r39c53ec4xb13e33fe19c96022@mail.gmail.com> I'm back to my home machine, and ran again the open method, just to test my sanity Here are the results: >>> f=open(r'c:\Test.txt','r') Traceback (most recent call last): File "", line 1, in ? IOError: [Errno 2] No such file or directory: 'c:\\Test.txt' >>> f=open(r'c:\\Test.txt','r') Traceback (most recent call last): File "", line 1, in ? IOError: [Errno 2] No such file or directory: 'c:\\\\Test.txt' >>> f=open(r'C:/Test.txt','r') Traceback (most recent call last): File "", line 1, in ? IOError: [Errno 2] No such file or directory: 'C:/Test.txt' >>> f=open('c:\\Test.txt','r') Traceback (most recent call last): File "", line 1, in ? IOError: [Errno 2] No such file or directory: 'c:\\Test.txt' Now with all the explanations of r, slash, double slash, and backslash, I can't really figure out what's going on..... Any hints is much appreciated. Thanks, Andy On 1/17/06, Python wrote: > > (replying back to the list also) > On Tue, 2006-01-17 at 10:03 -0800, andy senoaji wrote: > > Sorry for the inconsistent error message. I think I may pasted > > incorretcly. I am now in a different machine, and have tested Paul's > > suggestion, and it worked. But would the 'r' tackles the escape > > sequence? I may misunderstood the intent of the r' switcher here. > > > > Thanks, > > > > Andy > > f = open(r'C:\Test.txt', 'r') > > This looks correct! > > r'C:\Test.txt' is a raw string. The r'strings' ignore the special use > of the backslash character except that a raw string must not end with a > backslash. This is strictly a convenience when entering a string. > Since Windows uses backslash as the path separator, it helps ease the > pain when constructing file paths in Windows. Raw strings are also very > helpful when writing regular expression strings which often need to have > backspace characters. > > Internally, a raw string is the same as any other Python string. When > Python displays a raw string, Python will show the backslashes as \\ > (doubled) because that is usually how you need to enter a backslash. > Python does not track (as far as I know) that the string originated as a > raw string. > > In regular strings, the backslash is used to mark characters that need > special handling. '\t' is a tab character. '\n' is a newline (linefeed). > '\r' is a carriage-return (Enter Key). > > http://docs.python.org/ref/strings.html > provides the detailed documentation about how strings work and the > definitive list of backspace usages. > > > > > > On 1/17/06, Python wrote: > > On Tue, 2006-01-17 at 09:11 -0800, andy senoaji wrote: > > > I am starting to pull my hair here. There were some postings > > in the > > > past, similar to my problem, but the response was not clear > > enough. > > > Sorry if you thingk I am reposting this. > > > > > > I am trying to run (on an XP box) a simple open file using > > this: > > > f = open(r'C:\Test.txt', 'r') > > This looks correct! > > > > > > > > but it keeps give me nagging error of: > > > Traceback (most recent call last): > > > File "", line 1, in -toplevel- > > > f = open('Test.txt', 'r') > > This is not the same is the line above! > > > > > IOError: [Errno 2] No such file or directory: 'C:\Test.txt' > > And this does not match *either* of the lines above. > > > > If you really use that first line, I would expect it to > > work. If you > > get an error, from that line, the file will be identified as: > > 'C:\\Test.txt' > > > > > > > > I know for sure that the file is there, I even put copies of > > the files > > > here and there, just to guess how python does the file > > search, but it > > > keeps giving me 'No such file or directory'. i also tried > > variation of > > > the file location string, but gave me a variation of > > errors :). Any > > > suggestions? > > > > > > Furthermore, how does Python assumes the search path? Will > > it look > > > at /LIB first? How does it knows drive lettering, network > > mapping etc? > > > Is there a configuration settings that I can tweak in my > > Python? FYI I > > > am using Activestate's. > > > > > > > > > Thx, > > > > > > Andy > > > _______________________________________________ > > > Tutor maillist - Tutor at python.org > > > http://mail.python.org/mailman/listinfo/tutor > > -- > > Lloyd Kvam > > Venix Corp > > > > -- > Lloyd Kvam > Venix Corp > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060117/1a27bc9c/attachment.htm From alan.gauld at freenet.co.uk Wed Jan 18 06:24:00 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 18 Jan 2006 05:24:00 -0000 Subject: [Tutor] Open file error References: <85e10d320601170911r66b62a18u754e1b1c4f510d8b@mail.gmail.com><1137520206.15004.539.camel@www.venix.com><85e10d320601171003s10ada7efjc3aa66c0c7126310@mail.gmail.com><1137522541.15004.563.camel@www.venix.com> <85e10d320601172101r39c53ec4xb13e33fe19c96022@mail.gmail.com> Message-ID: <012c01c61bef$63b7a030$0b01a8c0@xp> >>> f=open(r'c:\Test.txt','r') Traceback (most recent call last): File "", line 1, in ? IOError: [Errno 2] No such file or directory: 'c:\\Test.txt' Its pretty determined that Test.txt doesn't exist. What happens if you do: import os os.listdir('C:\\') In other words does Python see the file at all? And have you checked that you have access to the file in Windows Explorer? Alan G. From dyoo at hkn.eecs.berkeley.edu Wed Jan 18 07:57:51 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 17 Jan 2006 22:57:51 -0800 (PST) Subject: [Tutor] References and list aliasing in Perl and Python [Was: Re: Dictionaries] In-Reply-To: <1137559730.2964.25.camel@elrond> Message-ID: > > The terminology that the original poster uses ("references to another > > object") sounds a lot like the original usage of symbolic "soft" > > references in Perl. > > (http://www.perl.com/doc/manual/html/pod/perlref.html) > > > > Perl programmers, for the most part, avoid them now because they're so > > error prone. So if the original poster is thinking about symbolic > > references, then we should encourage the poster to look into > > dictionaries, since dictionaries are a fairly direct replacement for > > that usage. > > > I did not know Perl programmers were moving away from references. That's > new to me, and an interesting point. [Note: I'll write some Perl code below. Probably bad, nonidiomatic Perl code. I also have a high chance of saying something wrong. If I do so, someone please correct me. *grin* Also, whenever I say "Perl", I'll mean Perl 5 --- I understand that Perl 6 has a model that's similar to Python now.] Hi Victor, No, no, I'd better clarify this to try to avoid someone getting angry at me. Maybe I'll dig myself into a deeper hole, but oh well. Perl has a distinction between "soft" symbolic references and "hard" references. I think symbolic references may have been a language mistake; I think good Perl style these days has been to phase them out of usage. Perl programmers seem to be perfectly happy with "hard" references: (http://search.cpan.org/~nwclark/perl-5.8.7/pod/perlreftut.pod) Python programmers like myself struggle a little when we talk about this because, truthfully, we don't think about this much. In Python, we pass references around without with abandon: we might not even realize it! Values in Python are all references. For example: ### Python ### >>> msg = list("hello world"); >>> greeting = msg >>> id(msg) 466880 >>> id(greeting) 466880 ############## In Python, both 'msg' and 'greeting' are names that refer to the same list value. We see this because they have the same id(). And if we apply mutation on the list value, we'll see this from both names: ### Python ### >>> msg[1] = 'a' >>> msg ['h', 'a', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'] >>> greeting ['h', 'a', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'] ############## Perl makes a distinction between values and references to those values, so the following shows different results: ### Perl ######################### mumak:~ dyoo$ cat > test.pl my @msg = split //, "hello world"; my @greeting = @msg; print \@msg, "\n"; print \@greeting, "\n"; $msg[1] = 'a'; print "@msg\n"; print "@greeting\n"; mumak:~ dyoo$ perl -w test.pl ARRAY(0x180b560) ARRAY(0x180b5b4) h a l l o w o r l d h e l l o w o r l d ################################## Here, we see that @msg and @greeting are really separate things in Perl: the values are in different memory locations, and assignment copies the data structures around. To get the same aliasing effect as in Python, we'd have to explicitely ask Perl to reference and dereference: ### Perl ########################### my $msg = [split //, "hello world"]; my $greeting = $msg; print $msg, "\n"; print $greeting, "\n"; $msg->[1] = 'a'; print "@$msg\n"; print "@$greeting\n"; ##################################### So Perl folks have a slightly more complex conceptual model: they make a distinction bewteen values and references. Python just has references. There are tradeoffs here. On the one hand, Python folks get caught off guard when they first encounter list aliasing. On the other, Perl folks get caught off guard when they first try to make a hash whose values are themselves lists. *grin* Hope this helps! From dyoo at hkn.eecs.berkeley.edu Wed Jan 18 08:05:57 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 17 Jan 2006 23:05:57 -0800 (PST) Subject: [Tutor] Open file error In-Reply-To: <85e10d320601172101r39c53ec4xb13e33fe19c96022@mail.gmail.com> Message-ID: On Tue, 17 Jan 2006, andy senoaji wrote: > I'm back to my home machine, and ran again the open method, just to test > my sanity Here are the results: [cut] Hi Andy, Unfortunately, there are a few things that might be happening here. You mentioned earlier that: > I know for sure that the file is there, I even put copies of the files > here and there, just to guess how python does the file search, but it Do you mind trying the following? I want to double check that the filename doesn't have anything silly in it like spaces. ####### import os print repr(os.listdir("C:/")) ####### Can you copy-and-paste what you see from this? This will show us the names of things in the toplevel directory, and should help to reveal why we're having so much trouble opening up that darn file. *grin* Good luck to you! From wescpy at gmail.com Wed Jan 18 08:13:39 2006 From: wescpy at gmail.com (w chun) Date: Tue, 17 Jan 2006 23:13:39 -0800 Subject: [Tutor] tutorials In-Reply-To: <003a01c61ac9$8395a950$0b01a8c0@xp> References: <003a01c61ac9$8395a950$0b01a8c0@xp> Message-ID: <78b3a9580601172313v438c9274s9512ba0c3a180b72@mail.gmail.com> On 1/16/06, Alan Gauld wrote: > > Has anyone got an easy way of printing the Python documentation in PDF > > format. Its all in HTML and is time consuming to print. > > You can buy it in paper book form. > It's a lot cheaper than trying to print the online stuff page by page! > ... But you do realise just how > much there is to print - many hundreds of pages, probably well over > a thousand! Thats a lot of big ring binders. i remember printing out the library reference for 1.4 (waaay back in '97), then having to take it to Kinko's to dupe for our engineering team... it was already BIG then -- i can't imagine doing it now. with that said, i've organized all of Python's downloadable doc files (all types) for most versions of Python in a nice easy-to-read grid. just go to http://corepython.com and click "Documentation" on the left-hand side. hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2006,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From johan at accesstel.co.za Wed Jan 18 10:00:59 2006 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Wed, 18 Jan 2006 11:00:59 +0200 Subject: [Tutor] Internet programming with python Message-ID: <43CE03CB.1090300@accesstel.co.za> Hi all, Has the book 'Internet programming with Python' (ISBN: 1558514848, publisher: M&T Books, 1996) ever been revised or is there a secod editin available? I don't have it, but I would like this or something simular very much. Any ideas what the status is or where I can find it? Thanks, Johan From wescpy at gmail.com Wed Jan 18 10:54:08 2006 From: wescpy at gmail.com (w chun) Date: Wed, 18 Jan 2006 01:54:08 -0800 Subject: [Tutor] Internet programming with python In-Reply-To: <43CE03CB.1090300@accesstel.co.za> References: <43CE03CB.1090300@accesstel.co.za> Message-ID: <78b3a9580601180154u320287b8w477f5e8e69bd5de7@mail.gmail.com> On 1/18/06, Johan Geldenhuys wrote: > > Has the book 'Internet programming with Python' (ISBN: 1558514848, > publisher: M&T Books, 1996) ever been revised or is there a secod editin > available? > I don't have it, but I would like this or something simular very much. > > Any ideas what the status is or where I can find it? hi johan, this book is long out-of-print, and i doubt any revision is coming in the near-term (but i don't know for sure). what is it about this book that interests you? is it the title alone? if so, there are plenty of current books out there with material that you're looking for. you could also tell us what topics are of interest to you. if not, then we should still be able to help you with your interest areas. for example, i teach a 3-hour tutorial with that very same name, i.e., http://wiki.python.org/moin/PyCon2006/Tutorials/InternetProgrammingWithPython and it involves 3 distinct areas of "internet programming," namely socket programming, internet *client* programming (i.e., FTP, NNTP, SMTP, POP3, etc.), and finally, web and CGI programming. there are corresponding chapters in my book, "Core Python" too. other books out there include "Foundations of Python Network Programming" by John Goerzen, and another one by Steve Holden, "Python Web Programming," both of which are very good. hope this helps, but if you want more help, you need to be more specific about your interest areas. cheers, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2006,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From johan at accesstel.co.za Wed Jan 18 12:03:13 2006 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Wed, 18 Jan 2006 13:03:13 +0200 Subject: [Tutor] Internet programming with python In-Reply-To: <78b3a9580601180154u320287b8w477f5e8e69bd5de7@mail.gmail.com> References: <43CE03CB.1090300@accesstel.co.za> <78b3a9580601180154u320287b8w477f5e8e69bd5de7@mail.gmail.com> Message-ID: <43CE2071.50100@accesstel.co.za> Wesley, I am doing some socket programming in my work and I need to learn about writing webpages and CGI stuff in Pyhon. I have Apache on my PC and could start and write some pages to test on it. It is still a bit vage to me how to do that and thought that a book like hat could be beneficial. I read about your tutorial in Feb. but can't make it, unless you come to South Africa ;-) . I will check out "Foundations of Python Network Programming" by John Goerzen. Any tutorials on the net I could use? Thanks for he help Johan w chun wrote: >On 1/18/06, Johan Geldenhuys wrote: > > >>Has the book 'Internet programming with Python' (ISBN: 1558514848, >>publisher: M&T Books, 1996) ever been revised or is there a secod editin >>available? >>I don't have it, but I would like this or something simular very much. >> >>Any ideas what the status is or where I can find it? >> >> > > >hi johan, > >this book is long out-of-print, and i doubt any revision is coming in >the near-term (but i don't know for sure). what is it about this book >that interests you? is it the title alone? > >if so, there are plenty of current books out there with material that >you're looking for. you could also tell us what topics are of >interest to you. if not, then we should still be able to help you >with your interest areas. > >for example, i teach a 3-hour tutorial with that very same name, i.e., >http://wiki.python.org/moin/PyCon2006/Tutorials/InternetProgrammingWithPython >and it involves 3 distinct areas of "internet programming," namely >socket programming, internet *client* programming (i.e., FTP, NNTP, >SMTP, POP3, etc.), and finally, web and CGI programming. there are >corresponding chapters in my book, "Core Python" too. other books out >there include "Foundations of Python Network Programming" by John >Goerzen, and another one by Steve Holden, "Python Web Programming," >both of which are very good. > >hope this helps, but if you want more help, you need to be more >specific about your interest areas. > >cheers, >-- wesley >- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - >"Core Python Programming", Prentice Hall, (c)2006,2001 > http://corepython.com > >wesley.j.chun :: wescpy-at-gmail.com >cyberweb.consulting : silicon valley, ca >http://cyberwebconsulting.com > > > From kent37 at tds.net Wed Jan 18 12:28:10 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 18 Jan 2006 06:28:10 -0500 Subject: [Tutor] Internet programming with python In-Reply-To: <43CE2071.50100@accesstel.co.za> References: <43CE03CB.1090300@accesstel.co.za> <78b3a9580601180154u320287b8w477f5e8e69bd5de7@mail.gmail.com> <43CE2071.50100@accesstel.co.za> Message-ID: <43CE264A.7080808@tds.net> Johan Geldenhuys wrote: > Wesley, > > I am doing some socket programming in my work and I need to learn about > writing webpages and CGI stuff in Pyhon. I have Apache on my PC and > could start and write some pages to test on it. It is still a bit vage > to me how to do that and thought that a book like hat could be beneficial. > > I read about your tutorial in Feb. but can't make it, unless you come to > South Africa ;-) . > > I will check out "Foundations of Python Network Programming" by John > Goerzen. > > Any tutorials on the net I could use? Socket Programming HOW TO: http://www.amk.ca/python/howto/sockets/ The docs for the CGI module are fairly extensive: http://docs.python.org/lib/module-cgi.html Voidspace has a number of useful CGI-related modules and recipes: http://www.voidspace.org.uk/python/cgi.shtml http://www.voidspace.org.uk/python/recipebook.shtml More links here: http://wiki.python.org/moin/CgiScripts Kent From johan at accesstel.co.za Wed Jan 18 12:36:05 2006 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Wed, 18 Jan 2006 13:36:05 +0200 Subject: [Tutor] Internet programming with python In-Reply-To: <43CE264A.7080808@tds.net> References: <43CE03CB.1090300@accesstel.co.za> <78b3a9580601180154u320287b8w477f5e8e69bd5de7@mail.gmail.com> <43CE2071.50100@accesstel.co.za> <43CE264A.7080808@tds.net> Message-ID: <43CE2825.9060205@accesstel.co.za> Thanks, Kent. I found this one also. There is a wide range of tutorials here. Johan Kent Johnson wrote: >Johan Geldenhuys wrote: > > >>Wesley, >> >>I am doing some socket programming in my work and I need to learn about >>writing webpages and CGI stuff in Pyhon. I have Apache on my PC and >>could start and write some pages to test on it. It is still a bit vage >>to me how to do that and thought that a book like hat could be beneficial. >> >>I read about your tutorial in Feb. but can't make it, unless you come to >>South Africa ;-) . >> >>I will check out "Foundations of Python Network Programming" by John >>Goerzen. >> >>Any tutorials on the net I could use? >> >> > >Socket Programming HOW TO: http://www.amk.ca/python/howto/sockets/ >The docs for the CGI module are fairly extensive: >http://docs.python.org/lib/module-cgi.html > >Voidspace has a number of useful CGI-related modules and recipes: >http://www.voidspace.org.uk/python/cgi.shtml >http://www.voidspace.org.uk/python/recipebook.shtml > >More links here: http://wiki.python.org/moin/CgiScripts > >Kent > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > > From kent37 at tds.net Wed Jan 18 13:53:33 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 18 Jan 2006 07:53:33 -0500 Subject: [Tutor] [OT] How to report issues with Standard library modules In-Reply-To: References: Message-ID: <43CE3A4D.9090209@tds.net> Liam Clarke wrote: > Hi all, > > After having a frustrating night last night trying to install pyid3lib > on XP, which I think is due to something in distutils.core, I'm > wondering how I should report it. > > I have the dotNET framework 2.0 installed, which should give distutils > access to the MSVC++ compiler, but it's searching for the 1.1 > framework, and so tells me I have no dotNET install. > > This is a pain in the donkey synonym, but after some mucking about > trying to compile the extension myself (which never quite worked) I > found that you can specify a different compiler, so I tried mingw32. > Unfortunately, that errored to the extent that where the error started > exceeded my console buffer, even when set to max. > > Secondly, how and where do bug reports go? I thought I'd ask here > because I want to avoid the "noob" comments and "use a real OS" > comments... If you want to pursue this I suggest you post a detailed report on your problem to comp.lang.python. Don't assume it is a distutils bug, you will get a better response if you assume that you are doing something wrong and ask for help. You can speculate that it might be a bug, but one of the maxims of c.l.py is something like, "If you think you have found a bug in Python, you're probably wrong" - and the maxim is often right. c.l.py is pretty friendly to newbies who give a clear problem statement and don't start with the belief that Python is broken. I don't think I have ever seen a "use a real OS" comment there and it's clear that some of the Python heavyweights are very familiar with Windows. Bug reports go to SourceForge - http://sourceforge.net/tracker/?group_id=5470&atid=105470 - but I would try c.l.py first. Kent From cspears2002 at yahoo.com Wed Jan 18 23:25:20 2006 From: cspears2002 at yahoo.com (Christopher Spears) Date: Wed, 18 Jan 2006 14:25:20 -0800 (PST) Subject: [Tutor] namespace confusion Message-ID: <20060118222520.39893.qmail@web51613.mail.yahoo.com> Let's say I have two classes: >>> class super: ... def hello(self): ... self.data1 = 'spam' ... >>> class sub(super): ... def hola(self): ... self.data2 = 'eggs' ... Now let's look in the classes' namespaces using __dict__: >>> sub.__dict__ {'__module__': '__main__', '__doc__': None, 'hola': } >>> super.__dict__ {'__module__': '__main__', 'hello': , '__doc__': None} I was first confused why 'hello' did not appear in sub as well. Then I read about dir(): >>> dir(sub) ['__doc__', '__module__', 'hello', 'hola'] >>> dir(super) ['__doc__', '__module__', 'hello'] The above result makes more sense to me. Why doesn't __dict__ give the same response as dir()? How come I don't see super in sub's namespace? -Chris From ryan_gm at sbcglobal.net Thu Jan 19 00:12:53 2006 From: ryan_gm at sbcglobal.net (ryan luna) Date: Wed, 18 Jan 2006 15:12:53 -0800 (PST) Subject: [Tutor] Strings backwards Message-ID: <20060118231253.78827.qmail@web80825.mail.yahoo.com> Hello, what i need to do is get user input and then print the string backwards ^^ i have no idea how to do that, print "Enter a word and i well tell you how to say it backwards" word = raw_input("Your word: ") print word all that is simple enough im sure printing it out backwards is to, just dont know how ^^, thanks for any help. From Hans.Dushanthakumar at navman.com Thu Jan 19 00:23:40 2006 From: Hans.Dushanthakumar at navman.com (Hans Dushanthakumar) Date: Thu, 19 Jan 2006 12:23:40 +1300 Subject: [Tutor] Strings backwards Message-ID: <5667508E43F1B740BCFA57FF46E353000313B11B@nav-akl-exch-c.newton.navman.com> Try this: print word[::-1] -----Original Message----- From: tutor-bounces+hans.dushanthakumar=navman.com at python.org [mailto:tutor-bounces+hans.dushanthakumar=navman.com at python.org] On Behalf Of ryan luna Sent: Thursday, 19 January 2006 12:13 p.m. To: tutor at python.org Subject: [Tutor] Strings backwards Hello, what i need to do is get user input and then print the string backwards ^^ i have no idea how to do that, print "Enter a word and i well tell you how to say it backwards" word = raw_input("Your word: ") print word all that is simple enough im sure printing it out backwards is to, just dont know how ^^, thanks for any help. _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From adam.jtm30 at gmail.com Thu Jan 19 00:25:31 2006 From: adam.jtm30 at gmail.com (Adam) Date: Wed, 18 Jan 2006 23:25:31 +0000 Subject: [Tutor] Fwd: Strings backwards In-Reply-To: References: <20060118231253.78827.qmail@web80825.mail.yahoo.com> Message-ID: On 18/01/06, ryan luna wrote: > > Hello, what i need to do is get user input and then > print the string backwards ^^ i have no idea how to do > that, > > print "Enter a word and i well tell you how to say it > backwards" > > word = raw_input("Your word: ") > > print word > > all that is simple enough im sure printing it out > backwards is to, just dont know how ^^, thanks for any help. How's this for you? >>> l = list('string') >>> l ['s', 't', 'r', 'i', 'n', 'g'] >>> l.reverse() >>> l ['g', 'n', 'i', 'r', 't', 's'] >>> ''.join(l) 'gnirts' As you can see I converted the string to a list using the list() function and then applied the reverse method of the list to put it the other way round and finally used the string method join() to change it back to a string. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060118/3d35cc01/attachment.htm From bgailer at alum.rpi.edu Thu Jan 19 00:46:10 2006 From: bgailer at alum.rpi.edu (bob) Date: Wed, 18 Jan 2006 15:46:10 -0800 Subject: [Tutor] namespace confusion In-Reply-To: <20060118222520.39893.qmail@web51613.mail.yahoo.com> References: <20060118222520.39893.qmail@web51613.mail.yahoo.com> Message-ID: <7.0.0.16.0.20060118154441.0238d310@alum.rpi.edu> At 02:25 PM 1/18/2006, Christopher Spears wrote: >Let's say I have two classes: > > >>> class super: >... def hello(self): >... self.data1 = 'spam' >... > >>> class sub(super): >... def hola(self): >... self.data2 = 'eggs' >... > >Now let's look in the classes' namespaces using >__dict__: > > >>> sub.__dict__ >{'__module__': '__main__', '__doc__': None, 'hola': >} > > >>> super.__dict__ >{'__module__': '__main__', 'hello': 0x4039548c>, '__doc__': None} > >I was first confused why 'hello' did not appear in sub >as well. Then I read about dir(): > > >>> dir(sub) >['__doc__', '__module__', 'hello', 'hola'] > > >>> dir(super) >['__doc__', '__module__', 'hello'] > >The above result makes more sense to me. Why doesn't >__dict__ give the same response as dir()? How come I >don't see super in sub's namespace? From help under dir(): "With an argument, attempts to return a list of valid attributes for that object. This information is gleaned from the object's __dict__ attribute, if defined, and from the class or type object. The list is not necessarily complete. ... If the object is a type or class object, the list contains the names of its attributes, and recursively of the attributes of its bases.: -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060118/e633bd6d/attachment.html From adam.jtm30 at gmail.com Thu Jan 19 00:54:37 2006 From: adam.jtm30 at gmail.com (Adam) Date: Wed, 18 Jan 2006 23:54:37 +0000 Subject: [Tutor] Strings backwards In-Reply-To: <20060118234604.16892.qmail@web80807.mail.yahoo.com> References: <20060118234604.16892.qmail@web80807.mail.yahoo.com> Message-ID: On 18/01/06, ryan luna wrote: > > > > --- Adam wrote: > > > On 18/01/06, ryan luna > > wrote: > > > > > > Hello, what i need to do is get user input and > > then > > > print the string backwards ^^ i have no idea how > > to do > > > that, > > > > > > print "Enter a word and i well tell you how to say > > it > > > backwards" > > > > > > word = raw_input("Your word: ") > > > > > > print word > > > > > > all that is simple enough im sure printing it out > > > backwards is to, just dont know how ^^, thanks for > > any help. > > > > > > How's this for you? > > > > >>> l = list('string') > > >>> l > > ['s', 't', 'r', 'i', 'n', 'g'] > > >>> l.reverse() > > >>> l > > ['g', 'n', 'i', 'r', 't', 's'] > > >>> ''.join(l) > > 'gnirts' > > > > As you can see I converted the string to a list > > using the list() function > > and then applied the reverse method of the list to > > put it the other way > > round and finally used the string method join() to > > change it back to a > > string. > > > > Great! thanks, but the last part, for some reason, the > last part ''.join() isn't working it stays in list > forms, donno what im doin wrong, heres my code. > > print "Enter a word and i well tell you how to say it > backwards" > > word = raw_input("Your word: ") > word = list(word) > word.reverse() > ''.join(word) > > > > print word > > Oh sorry it probably wasn't clear you need to either directly print ''.join(word) or assign it to a variable which could be something like this: word = ''.join(word) if you want to use the same variable. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060118/908f14fd/attachment.htm From benvinger at yahoo.co.uk Thu Jan 19 01:02:35 2006 From: benvinger at yahoo.co.uk (Ben Vinger) Date: Thu, 19 Jan 2006 00:02:35 +0000 (GMT) Subject: [Tutor] a class knowing its self Message-ID: <20060119000235.37457.qmail@web25811.mail.ukl.yahoo.com> Hello I've been reading about how a class has access to its own 'self', so I tried the following, but it is not working as I would expect: class Skill: def __init__(self): self.history = [] def setName(self, skill): self.name = skill def getName(self): return self.name # Assigning data to my class: SkillNames = [r'python', r'apache', r'mysql'] #a.) python = Skill() python.setName('python') print python.getName() #b.) for s in SkillNames: s = Skill() s.setName(s) print s.getName() Why does a work and b not? b returns: <__main__.Skill instance at 0x401e260c> <__main__.Skill instance at 0x401e230c> <__main__.Skill instance at 0x401e23ec> why does b not return the names of the 3 instances of Skill? Thanks Ben ___________________________________________________________ To help you stay safe and secure online, we've developed the all new Yahoo! Security Centre. http://uk.security.yahoo.com From victor at grupocdm.com Thu Jan 19 01:15:50 2006 From: victor at grupocdm.com (Victor Bouffier) Date: Wed, 18 Jan 2006 18:15:50 -0600 Subject: [Tutor] References and list aliasing in Perl and Python [Was: Re: Dictionaries] In-Reply-To: References: Message-ID: <1137629750.21531.3.camel@elrond> On Tue, 2006-01-17 at 22:57 -0800, Danny Yoo wrote: > > > The terminology that the original poster uses ("references to another > > > object") sounds a lot like the original usage of symbolic "soft" > > > references in Perl. > > > (http://www.perl.com/doc/manual/html/pod/perlref.html) > > > > > > Perl programmers, for the most part, avoid them now because they're so > > > error prone. So if the original poster is thinking about symbolic > > > references, then we should encourage the poster to look into > > > dictionaries, since dictionaries are a fairly direct replacement for > > > that usage. > > > > > I did not know Perl programmers were moving away from references. That's > > new to me, and an interesting point. > > [Note: I'll write some Perl code below. Probably bad, nonidiomatic Perl > code. I also have a high chance of saying something wrong. If I do so, > someone please correct me. *grin* > > Also, whenever I say "Perl", I'll mean Perl 5 --- I understand that Perl 6 > has a model that's similar to Python now.] > > > Hi Victor, > > No, no, I'd better clarify this to try to avoid someone getting angry at > me. Maybe I'll dig myself into a deeper hole, but oh well. > > Perl has a distinction between "soft" symbolic references and "hard" > references. I think symbolic references may have been a language mistake; > I think good Perl style these days has been to phase them out of usage. > > Perl programmers seem to be perfectly happy with "hard" references: > (http://search.cpan.org/~nwclark/perl-5.8.7/pod/perlreftut.pod) > > > Python programmers like myself struggle a little when we talk about this > because, truthfully, we don't think about this much. In Python, we pass > references around without with abandon: we might not even realize it! > Values in Python are all references. For example: > > ### Python ### > >>> msg = list("hello world"); > >>> greeting = msg > >>> id(msg) > 466880 > >>> id(greeting) > 466880 > ############## > > In Python, both 'msg' and 'greeting' are names that refer to the same list > value. We see this because they have the same id(). And if we apply > mutation on the list value, we'll see this from both names: > > ### Python ### > >>> msg[1] = 'a' > >>> msg > ['h', 'a', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'] > >>> greeting > ['h', 'a', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'] > ############## > > > > Perl makes a distinction between values and references to those values, so > the following shows different results: > > ### Perl ######################### > mumak:~ dyoo$ cat > test.pl > my @msg = split //, "hello world"; > my @greeting = @msg; > print \@msg, "\n"; > print \@greeting, "\n"; > $msg[1] = 'a'; > print "@msg\n"; > print "@greeting\n"; > > mumak:~ dyoo$ perl -w test.pl > ARRAY(0x180b560) > ARRAY(0x180b5b4) > h a l l o w o r l d > h e l l o w o r l d > ################################## > > Here, we see that @msg and @greeting are really separate things in Perl: > the values are in different memory locations, and assignment copies the > data structures around. > > > To get the same aliasing effect as in Python, we'd have to explicitely ask > Perl to reference and dereference: > > ### Perl ########################### > my $msg = [split //, "hello world"]; > my $greeting = $msg; > print $msg, "\n"; > print $greeting, "\n"; > $msg->[1] = 'a'; > print "@$msg\n"; > print "@$greeting\n"; > ##################################### > > So Perl folks have a slightly more complex conceptual model: they make a > distinction bewteen values and references. Python just has references. > > There are tradeoffs here. On the one hand, Python folks get caught off > guard when they first encounter list aliasing. On the other, Perl folks > get caught off guard when they first try to make a hash whose values are > themselves lists. *grin* > WOW. Great explanation. Don't worry about a deeper hole. Your examples once again reminded me of one of reasons I started looking into Python instead of continuing with Perl. It is not the functionality, but the convoluted scripts can get. One can hardly understand the code. Thanks again. Victor > > Hope this helps! > > From shuying at gmail.com Thu Jan 19 01:16:31 2006 From: shuying at gmail.com (Shuying Wang) Date: Thu, 19 Jan 2006 11:16:31 +1100 Subject: [Tutor] a class knowing its self In-Reply-To: <20060119000235.37457.qmail@web25811.mail.ukl.yahoo.com> References: <20060119000235.37457.qmail@web25811.mail.ukl.yahoo.com> Message-ID: <75fa0c3a0601181616n60771be4xa2ebf3424f270c76@mail.gmail.com> Ben, If you change example #b to: for s in SkillNames: skill = Skill() skill.setName(s) print skill.getName() You will find that the results are the same as #a. In your #b example, you are giving setName() the skill instance instead of the string you intended. --Shuying On 1/19/06, Ben Vinger wrote: > I've been reading about how a class has access to its > own 'self', so I tried the following, but it is not > working as I would expect: > > class Skill: > def __init__(self): > self.history = [] > > def setName(self, skill): > self.name = skill > > def getName(self): > return self.name > > # Assigning data to my class: > > SkillNames = [r'python', r'apache', r'mysql'] > > #a.) > python = Skill() > python.setName('python') > print python.getName() > > #b.) > for s in SkillNames: > s = Skill() > s.setName(s) > print s.getName() > > Why does a work and b not? From ryan_gm at sbcglobal.net Thu Jan 19 01:17:12 2006 From: ryan_gm at sbcglobal.net (ryan luna) Date: Wed, 18 Jan 2006 16:17:12 -0800 (PST) Subject: [Tutor] Jumble Message-ID: <20060119001712.12193.qmail@web80832.mail.yahoo.com> Ok so what i have to do is make it so when a player ask for a hint the program display a hint, heres my loop, not whole script. guess = raw_input("\nYour guess: ") guess = guess.lower() while (guess != correct) and (guess != ""): print "Sorry, that's not it." print "If you need a hint enter help" if guess == hint: The problem is its passing up "Hint" altogether when the user input is hint it doesn't do anything, prolly makin a noob mistake here, Thank for any help From adam.jtm30 at gmail.com Thu Jan 19 01:35:55 2006 From: adam.jtm30 at gmail.com (Adam) Date: Thu, 19 Jan 2006 00:35:55 +0000 Subject: [Tutor] Jumble In-Reply-To: <20060119001712.12193.qmail@web80832.mail.yahoo.com> References: <20060119001712.12193.qmail@web80832.mail.yahoo.com> Message-ID: On 19/01/06, ryan luna wrote: > > Ok so what i have to do is make it so when a player > ask for a hint the program display a hint, heres my > loop, not whole script. > > guess = raw_input("\nYour guess: ") > guess = guess.lower() > while (guess != correct) and (guess != ""): > print "Sorry, that's not it." > print "If you need a hint enter help" > if guess == hint: raw_input converts any input to a string so if guess == "hint": should work or making the variable hint = "hint" -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060119/1cd72744/attachment.html From john at fouhy.net Thu Jan 19 02:13:02 2006 From: john at fouhy.net (John Fouhy) Date: Thu, 19 Jan 2006 14:13:02 +1300 Subject: [Tutor] copyright statement Message-ID: <5e58f2e40601181713o30daa06au@mail.gmail.com> Anyone know anything about the 'copyright' statement? help(copyright) is not ultra helpful, and I can't see anything in the docs (eg, http://python.org/doc/2.4.2/ref/simple.html doesn't list it). Is it ever intended to be used in normal code? -- John. From dyoo at hkn.eecs.berkeley.edu Thu Jan 19 02:34:10 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 18 Jan 2006 17:34:10 -0800 (PST) Subject: [Tutor] Strings backwards In-Reply-To: <5667508E43F1B740BCFA57FF46E353000313B11B@nav-akl-exch-c.newton.navman.com> Message-ID: On Thu, 19 Jan 2006, Hans Dushanthakumar wrote: > Try this: > > print word[::-1] Hi Hans and Adam, Just wanted to point out: next time, let's try to figure out why Ryan had problems with this, rather than directly give a working answer. For example, we can ask things like: what part did Ryan get stuck on? Was it unfamiliarity with the things we can do with slices, or something else? What did Ryan try? What did Ryan look at? Are there programs that Ryan has written that are similar to the one he's asking about? The reason for the caution is this: the reversal question he asked felt way too much like a homework exercise. I hate being pedantic, but it is something we should be thinking about. From carroll at tjc.com Thu Jan 19 02:38:03 2006 From: carroll at tjc.com (Terry Carroll) Date: Wed, 18 Jan 2006 17:38:03 -0800 (PST) Subject: [Tutor] copyright statement In-Reply-To: <5e58f2e40601181713o30daa06au@mail.gmail.com> Message-ID: On Thu, 19 Jan 2006, John Fouhy wrote: > Anyone know anything about the 'copyright' statement? help(copyright) > is not ultra helpful, and I can't see anything in the docs (eg, > http://python.org/doc/2.4.2/ref/simple.html doesn't list it). Is it > ever intended to be used in normal code? No, not really. copyright isn't a statement, it's just a variable: >>> type(copyright) >>> copyright.__doc__ 'interactive prompt objects for printing the license text, a list of\n contributors and the copyright notice.' >>> print copyright Copyright (c) 2000-2005 ActiveState Corp. Copyright (c) 2001-2005 Python Software Foundation. All Rights Reserved. Copyright (c) 2000 BeOpen.com. All Rights Reserved. Copyright (c) 1995-2001 Corporation for National Research Initiatives. All Rights Reserved. Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam. All Rights Reserved. It's a variable set up in site.py (go have a look), intended for use in the interactive session, so a user can just type in the variable name and get some copyright information. In the main() method in site.py, you'll see setcopyright() which just calls that method to initialize the copyright variable. Similarly setquit() sets up a variable named "quit" that contains instructions on how to quit; so that when a user types "quit" they see the value of the variable, which tells them how to quit. From dyoo at hkn.eecs.berkeley.edu Thu Jan 19 02:39:00 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 18 Jan 2006 17:39:00 -0800 (PST) Subject: [Tutor] Jumble In-Reply-To: <20060119001712.12193.qmail@web80832.mail.yahoo.com> Message-ID: On Wed, 18 Jan 2006, ryan luna wrote: > Ok so what i have to do is make it so when a player ask for a hint the > program display a hint, heres my loop, not whole script. > > guess = raw_input("\nYour guess: ") > guess = guess.lower() > while (guess != correct) and (guess != ""): > print "Sorry, that's not it." > print "If you need a hint enter help" > if guess == hint: > > The problem is its passing up "Hint" altogether Hi Ryan, I'm seeing something a little weird here, but it's not what you're describing. I'll probe a little more to see if we can figure out what's going on. Can you show us what you mean by 'passing up "Hint"'? Not sure I understand what you mean yet. A copy-and-paste of the session you're doing to test the program will be helpful, as well as some discussion on what you expected to see vs. what you're actually seeing. Good luck to you. From ryan_gm at sbcglobal.net Thu Jan 19 02:57:38 2006 From: ryan_gm at sbcglobal.net (ryan luna) Date: Wed, 18 Jan 2006 17:57:38 -0800 (PST) Subject: [Tutor] yeah Message-ID: <20060119015738.59884.qmail@web80807.mail.yahoo.com> Hi Hans and Adam, Just wanted to point out: next time, let's try to figure out why Ryan had problems with this, rather than directly give a working answer. For example, we can ask things like: what part did Ryan get stuck on? Was it unfamiliarity with the things we can do with slices, or something else? What did Ryan try? What did Ryan look at? Are there programs that Ryan has written that are similar to the one he's asking about? The reason for the caution is this: the reversal question he asked felt way too much like a homework exercise. I hate being pedantic, but it is something we should be thinking about. yeah, that was something i should know so i whent back and read the whole chapter of the book that told me to write such a program, the problem is i was out of it when i read that part that nothing stuck, ^^ From john at fouhy.net Thu Jan 19 02:59:37 2006 From: john at fouhy.net (John Fouhy) Date: Thu, 19 Jan 2006 14:59:37 +1300 Subject: [Tutor] copyright statement In-Reply-To: References: <5e58f2e40601181713o30daa06au@mail.gmail.com> Message-ID: <5e58f2e40601181759v37cc1effo@mail.gmail.com> On 19/01/06, Terry Carroll wrote: > copyright isn't a statement, it's just a variable: Oops! I was tricked by emacs giving it the same highlighting as statements like 'assert'. (although, come to think of it, emacs highlights 'self' and 'None' as well :-/ ) Open mouth, insert foot, echo internationally... -- John. From kent37 at tds.net Thu Jan 19 03:03:27 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 18 Jan 2006 21:03:27 -0500 Subject: [Tutor] namespace confusion In-Reply-To: <20060118222520.39893.qmail@web51613.mail.yahoo.com> References: <20060118222520.39893.qmail@web51613.mail.yahoo.com> Message-ID: <43CEF36F.2090702@tds.net> Christopher Spears wrote: > Let's say I have two classes: > > >>>>class super: > > ... def hello(self): > ... self.data1 = 'spam' > ... > >>>>class sub(super): > > ... def hola(self): > ... self.data2 = 'eggs' > ... > > Now let's look in the classes' namespaces using > __dict__: First a point of terminology - classes and objects don't have namespaces, they have attributes. Namespaces are where variables are looked up, not attributes. Names are looked up in the local namespace, any enclosing namespaces, the module (global) namespace and the built-in namespace. What you are talking about is attributes and attribute lookup. Attribute lookup can seem quite simple but in fact when you look under the hood there is a lot going on. Python in a Nutshell says, "Attribute references...have fairly rich semantics in Python". I think that is an understatement. So I'll oversimplify to start. When you ask Python for the value of foo.bar, first it looks up foo in the namespace hierarchy as described above. Then, given the value of foo, it looks for a bar attribute. The first place to look is in foo.__dict__. If it is not found there, then the class of foo is tried - foo.__class__.__dict__. Failing that, each of the base classes of foo.__class__ is searched, and their base classes up the inheritance chain. This search is performed dynamically every time you ask for foo.bar - it's quite possible that bar will be found in a different location on two different searches. In time-critical code it's common to optimize out this lookup by assigning a method to a local variable, for example. In your example, hola is an attribute of sub and appears in sub.__dict__. hello is an attribute of super and appears in super.__dict__. When you access sub.hola, it is found in sub.__dict__. When you access sub.hello, the lookup in sub.__dict__ fails so super.__dict__ is tried and hello is found there. dir() is a convenience function that attempts to show the some of the attributes that are accessible from the object you pass to it. As I said, the above is a gross oversimplification. It is mostly true for common cases. I don't want to attempt a complete correct explanation but I will say that attribute lookup is also affected by __getattr__, __getattribute__, __slots__, properties, and whether the attribute is a special name. Unfortunately I don't know of any single place where all of this is written down. Kent > > >>>>sub.__dict__ > > {'__module__': '__main__', '__doc__': None, 'hola': > } > > >>>>super.__dict__ > > {'__module__': '__main__', 'hello': 0x4039548c>, '__doc__': None} > > I was first confused why 'hello' did not appear in sub > as well. Then I read about dir(): > > >>>>dir(sub) > > ['__doc__', '__module__', 'hello', 'hola'] > > >>>>dir(super) > > ['__doc__', '__module__', 'hello'] > > The above result makes more sense to me. Why doesn't > __dict__ give the same response as dir()? How come I > don't see super in sub's namespace? > > -Chris > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From intercodes at gmail.com Thu Jan 19 03:49:07 2006 From: intercodes at gmail.com (Intercodes) Date: Thu, 19 Jan 2006 08:19:07 +0530 Subject: [Tutor] How does [::-1] work? Message-ID: <37e70e3b0601181849u38a212fcr1d3cd995c9cb24f8@mail.gmail.com> Hello Everyone, There was a query in this list regarding reversing a string and someone suggested that [::-1] does that. I tried that expression in my intepreter and various other combination but still can't comprehend how the expression works. I could understand[:] , [n:] or [:n] . But what meaning does it have in using two colons inside array index while slicing?. A concise explanation would suppress my curiosity. Thank You. -- Intercodes -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060119/60db53e5/attachment.htm From carroll at tjc.com Thu Jan 19 04:00:59 2006 From: carroll at tjc.com (Terry Carroll) Date: Wed, 18 Jan 2006 19:00:59 -0800 (PST) Subject: [Tutor] copyright statement In-Reply-To: <5e58f2e40601181759v37cc1effo@mail.gmail.com> Message-ID: On Thu, 19 Jan 2006, John Fouhy wrote: > Open mouth, insert foot, echo internationally... No, it wasn't a dumb question. I remember wondering about "quit" some time ago: if Python can see your "command" quit, why doesn't it just quit, instead of telling you how to quit with Ctrl-Z, Ctrl-D, or whatever? That got me looking into it, and I discovered that EOF is the Python exit; and adding a string variable named "quit" whose output would be displayed is essentially a "courtesy" to a new user (someone like me, at the time) stumbling around trying to quit the interpreter. So, I figured "copyright" was probably the same sort of thing, so I knew where to look. It's never a cause for embarassment to ask for an explanation of something you don't yet understand. It's often the only way you get to understand it. I've learned a lot by not caring if I look dumb. From john at fouhy.net Thu Jan 19 04:36:57 2006 From: john at fouhy.net (John Fouhy) Date: Thu, 19 Jan 2006 16:36:57 +1300 Subject: [Tutor] How does [::-1] work? In-Reply-To: <37e70e3b0601181849u38a212fcr1d3cd995c9cb24f8@mail.gmail.com> References: <37e70e3b0601181849u38a212fcr1d3cd995c9cb24f8@mail.gmail.com> Message-ID: <5e58f2e40601181936q795507f7x@mail.gmail.com> On 19/01/06, Intercodes wrote: > I tried that expression in my intepreter and various other combination but > still can't comprehend how the expression works. I could understand[:] , > [n:] or [:n] . But what meaning does it have in using two colons inside > array index while slicing?. A concise explanation would suppress my > curiosity. This is new in python 2.3 (?). Basically, the syntax is [start:stop:step]. For example: >>> import string >>> string.lowercase 'abcdefghijklmnopqrstuvwxyz' >>> string.lowercase[::2] # every second letter, starting with 0 'acegikmoqsuwy' >>> string.lowercase[1::2] # every second letter, starting with 1 'bdfhjlnprtvxz' If step is negative, you work backwards. eg: >>> string.lowercase[20:10:-2] # letters 20, 18, 16, 14, 12 'usqom' And if you omit the start or stop parameters, and step is negative, then start defaults to the end of the list and stop to the beginning. So string.lowercase[::-1] will step backwards, starting at the end and finishing at the start. HTH! -- John. From intercodes at gmail.com Thu Jan 19 06:36:31 2006 From: intercodes at gmail.com (Intercodes) Date: Thu, 19 Jan 2006 11:06:31 +0530 Subject: [Tutor] How does [::-1] work? Message-ID: <37e70e3b0601182136p2ecabaafkcee07f613066b70e@mail.gmail.com> John, >Basically, the syntax is [start:stop:step] I have read some 2 or 3 introductory tutorials on python and have never found this syntax or maybe I forgot to note this one. This one seems certainly useful in some cases. > HTH! yes, it does.! -- Intercodes -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060119/d7bc794d/attachment.html From andy.senoaji at gmail.com Thu Jan 19 06:49:34 2006 From: andy.senoaji at gmail.com (andy senoaji) Date: Wed, 18 Jan 2006 21:49:34 -0800 Subject: [Tutor] Open file error In-Reply-To: References: <85e10d320601172101r39c53ec4xb13e33fe19c96022@mail.gmail.com> Message-ID: <85e10d320601182149h188da704v7d533e54796bfcaa@mail.gmail.com> Thanks Danny & Alan, your print repr(os.listdir("C:/")) has embarrased myself :(. I found out the file name is Test.txt.txt in my c: drive. I guess I learn something here. Again Thanks Andy On 1/17/06, Danny Yoo wrote: > > > > On Tue, 17 Jan 2006, andy senoaji wrote: > > > I'm back to my home machine, and ran again the open method, just to test > > my sanity Here are the results: > > [cut] > > Hi Andy, > > Unfortunately, there are a few things that might be happening here. You > mentioned earlier that: > > > I know for sure that the file is there, I even put copies of the files > > here and there, just to guess how python does the file search, but it > > Do you mind trying the following? I want to double check that the > filename doesn't have anything silly in it like spaces. > > ####### > import os > print repr(os.listdir("C:/")) > ####### > > Can you copy-and-paste what you see from this? This will show us the > names of things in the toplevel directory, and should help to reveal why > we're having so much trouble opening up that darn file. *grin* > > Good luck to you! > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060118/500f0ce1/attachment.htm From dyoo at hkn.eecs.berkeley.edu Thu Jan 19 08:03:59 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 18 Jan 2006 23:03:59 -0800 (PST) Subject: [Tutor] References and list aliasing in Perl and Python [Was: Re: Dictionaries] In-Reply-To: <1137629750.21531.3.camel@elrond> Message-ID: > > There are tradeoffs here. On the one hand, Python folks get caught > > off guard when they first encounter list aliasing. On the other, Perl > > folks get caught off guard when they first try to make a hash whose > > values are themselves lists. *grin* > > > WOW. Great explanation. Don't worry about a deeper hole. > > Your examples once again reminded me of one of reasons I started looking > into Python instead of continuing with Perl. It is not the > functionality, but the convoluted scripts can get. One can hardly > understand the code. Hi Victor, That might be an unfair judgement. One can write really convoluted and ugly programs in any programming language. And although I do think that our choice in what programming language we us can affect a program's clarity, I also believe that people matter much more than the programming language. Otherwise, what would be the point of a mailing list like this? *grin* Best of wishes! From janos.juhasz at VELUX.com Thu Jan 19 08:26:14 2006 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Thu, 19 Jan 2006 08:26:14 +0100 Subject: [Tutor] [Re] Fwd: Strings backwards In-Reply-To: Message-ID: Hi Ryan, I just extended Adam's code with a speech-to-text recepi from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/114216. On 18/01/06, ryan luna wrote: > > Hello, what i need to do is get user input and then > print the string backwards ^^ i have no idea how to do > that, > > print "Enter a word and i well tell you how to say it > backwards" > > word = raw_input("Your word: ") > > print word > > all that is simple enough im sure printing it out > backwards is to, just dont know how ^^, thanks for any help. import sys from win32com.client import constants import win32com.client import string speaker = win32com.client.Dispatch("SAPI.SpVoice") print "Type word or phrase, then enter." print "Ctrl+Z then enter to exit." def backword(word): l = list(word) l.reverse() return ''.join(l) def backsentence(sentence): words = sentence.split(' ') words = [backword(word) for word in words] return ' '.join(words) while 1: try: s = raw_input() rev = backsentence(s) print 'I would say: ', rev speaker.Speak(rev) except: if sys.exc_type is EOFError: sys.exit() It works on my xp :) Yours sincerely, ______________________________ J?nos Juh?sz From jjk_saji at yahoo.com Thu Jan 19 11:26:23 2006 From: jjk_saji at yahoo.com (John Joseph) Date: Thu, 19 Jan 2006 10:26:23 +0000 (GMT) Subject: [Tutor] Links for programming using MySQL Message-ID: <20060119102623.62073.qmail@web34801.mail.mud.yahoo.com> Hi I wanted to try out python with MySQL databases , I would like to get info about the link to sites , which gives you examples on how to do python programming by using MySQL database Please guide Thanks Joseph John ___________________________________________________________ To help you stay safe and secure online, we've developed the all new Yahoo! Security Centre. http://uk.security.yahoo.com From kent37 at tds.net Thu Jan 19 11:56:53 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 19 Jan 2006 05:56:53 -0500 Subject: [Tutor] Open file error In-Reply-To: <85e10d320601182149h188da704v7d533e54796bfcaa@mail.gmail.com> References: <85e10d320601172101r39c53ec4xb13e33fe19c96022@mail.gmail.com> <85e10d320601182149h188da704v7d533e54796bfcaa@mail.gmail.com> Message-ID: <43CF7075.2090900@tds.net> andy senoaji wrote: > Thanks Danny & Alan, > > your print repr(os.listdir("C:/")) has embarrased myself :(. I found out > the file name is Test.txt.txt in my c: drive. I guess I learn something > here. If you tell Windows not to hide file extensions you won't make that mistake again. On my computer (Win2k) it is under Tools / Folder Options / View / Hide file extensions for known file types. Kent From kraus at hagen-partner.de Thu Jan 19 12:11:20 2006 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Thu, 19 Jan 2006 12:11:20 +0100 Subject: [Tutor] Links for programming using MySQL In-Reply-To: <20060119102623.62073.qmail@web34801.mail.mud.yahoo.com> References: <20060119102623.62073.qmail@web34801.mail.mud.yahoo.com> Message-ID: John Joseph wrote: > Hi I wanted to try out python with MySQL databases , I would like > to get info about the link to sites , which gives you examples on how > to do python programming by using MySQL database Please guide > Thanks Joseph John > > Try this one: http://sourceforge.net/docman/?group_id=22307 HTH, Wolfram From ewald.ertl at hartter.com Thu Jan 19 12:09:11 2006 From: ewald.ertl at hartter.com (Ewald Ertl) Date: Thu, 19 Jan 2006 12:09:11 +0100 Subject: [Tutor] a class knowing its self Message-ID: <43CF7357.6090009@hartter.com> Hi! Ben Vinger wrote: > Hello > > I've been reading about how a class has access to its > own 'self', so I tried the following, but it is not > working as I would expect: > > class Skill: > def __init__(self): > self.history = [] > > def setName(self, skill): > self.name = skill > > def getName(self): > return self.name > > # Assigning data to my class: > > SkillNames = [r'python', r'apache', r'mysql'] > > #a.) > python = Skill() > python.setName('python') > print python.getName() > > #b.) > for s in SkillNames: > s = Skill() > s.setName(s) > print s.getName() > Have a more precisely look at your code. s.getName() does just return, what you have put into the class with setName(). ( Reassignment of a variable to something different what you intended ). HTH Ewald > Why does a work and b not? > > b returns: > <__main__.Skill instance at 0x401e260c> > <__main__.Skill instance at 0x401e230c> > <__main__.Skill instance at 0x401e23ec> > > why does b not return the names of the 3 instances of > Skill? > > Thanks > Ben > > > > ___________________________________________________________ > To help you stay safe and secure online, we've developed the all new Yahoo! Security Centre. http://uk.security.yahoo.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From jjk_saji at yahoo.com Thu Jan 19 13:46:12 2006 From: jjk_saji at yahoo.com (John Joseph) Date: Thu, 19 Jan 2006 12:46:12 +0000 (GMT) Subject: [Tutor] Python + MySQL , my first simple program does not gives results Message-ID: <20060119124612.81099.qmail@web34803.mail.mud.yahoo.com> Hi I tried out my first Pyhton program with MySQL I was trying to get the some result , eg describe table, select * from table but my program does not give the expected results , nor it gives any error I am adding my code in this mail Please guide me , why I am not getting any results displayed Thanks Joseph John *******************************************************************************8 """ For learning for To connect to a database "learnpython" , with mysql user name "john" password "asdlkj" To describe a table "contact" To get result of SQL statement """ import MySQLdb class learnpython_db: def __init__(self): db = MySQLdb.connect(host="localhost",user = "john",password = "asdlkj", db = learnpython) cursor = db.cursor() cursor.execute(" describe contact" ) cursor.execute(" SELECT * from contact" ) ___________________________________________________________ Yahoo! Messenger - NEW crystal clear PC to PC calling worldwide with voicemail http://uk.messenger.yahoo.com From ajikoe at gmail.com Thu Jan 19 14:19:00 2006 From: ajikoe at gmail.com (Pujo Aji) Date: Thu, 19 Jan 2006 14:19:00 +0100 Subject: [Tutor] Python + MySQL , my first simple program does not gives results In-Reply-To: <20060119124612.81099.qmail@web34803.mail.mud.yahoo.com> References: <20060119124612.81099.qmail@web34803.mail.mud.yahoo.com> Message-ID: > > You should fetch the results. try: result = cursor.fetchall() print result Cheers, pujo import MySQLdb > class learnpython_db: > def __init__(self): > db = > MySQLdb.connect(host="localhost",user = > "john",password = "asdlkj", db = learnpython) > cursor = db.cursor() > cursor.execute(" describe contact" ) > cursor.execute(" SELECT * from > contact" ) > > > > > > > > > ___________________________________________________________ > Yahoo! Messenger - NEW crystal clear PC to PC calling worldwide with > voicemail http://uk.messenger.yahoo.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060119/04c9d606/attachment.htm From jonathan.r.moore at gmail.com Thu Jan 19 16:36:25 2006 From: jonathan.r.moore at gmail.com (Jon Moore) Date: Thu, 19 Jan 2006 15:36:25 +0000 Subject: [Tutor] Indexing in a series for a newbie Message-ID: Hello I need some help for a program I am writing as a newbie to Python. I have created a series: WORDS = ("python", "program", "code", "xylophone") and then assigned one of them randomly to the variable 'word': word = random.choice(WORDS) I know that if I do: print word The randomly chosen word will be displayed. I also know that if I type: print WORDS[x] I will get the corresponding word back. But how do I find 'programaticaly' the index number for the string that random.choice has chosen? The reason I ask is that I an writing a simple word jumble game and need to link the randomly chosen word to a hint should the user need one. -- Best Regards Jon Moore -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060119/3fa7878a/attachment.html From ajikoe at gmail.com Thu Jan 19 16:44:13 2006 From: ajikoe at gmail.com (Pujo Aji) Date: Thu, 19 Jan 2006 16:44:13 +0100 Subject: [Tutor] Indexing in a series for a newbie In-Reply-To: References: Message-ID: Hello Jon, Why don't use randint so you can record the index and the value Example: WORDS = ("python", "program", "code", "xylophone") Indword = random.randint(0,len(WORDS)-1) word = WORDS[Indword] print Indword print word Cheers, pujo On 1/19/06, Jon Moore wrote: > > Hello > > I need some help for a program I am writing as a newbie to Python. > > I have created a series: > > WORDS = ("python", "program", "code", "xylophone") > > and then assigned one of them randomly to the variable 'word': > > word = random.choice(WORDS) > > I know that if I do: > > print word > > The randomly chosen word will be displayed. I also know that if I type: > > print WORDS[x] > > I will get the corresponding word back. But how do I find 'programaticaly' > the index number for the string that random.choice has chosen? > > The reason I ask is that I an writing a simple word jumble game and need > to link the randomly chosen word to a hint should the user need one. > > -- > Best Regards > > Jon Moore > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060119/d0688a7a/attachment.htm From kraus at hagen-partner.de Thu Jan 19 17:13:48 2006 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Thu, 19 Jan 2006 17:13:48 +0100 Subject: [Tutor] Indexing in a series for a newbie In-Reply-To: References: Message-ID: Jon Moore wrote: > Hello > > I need some help for a program I am writing as a newbie to Python. > > I have created a series: > > WORDS = ("python", "program", "code", "xylophone") > > and then assigned one of them randomly to the variable 'word': > > word = random.choice(WORDS) > > I know that if I do: > > print word > > The randomly chosen word will be displayed. I also know that if I type: > > print WORDS[x] > > I will get the corresponding word back. But how do I find > 'programaticaly' the index number for the string that random.choice has > chosen? > > The reason I ask is that I an writing a simple word jumble game and need > to link the randomly chosen word to a hint should the user need one. > > -- > Best Regards > > Jon Moore You can convert your WORDS-tuple to a list and use the index() method: idx = list(WORDS).index(word) HTH, Wolfram From python-tutor at toddmaynard.com Thu Jan 19 17:28:33 2006 From: python-tutor at toddmaynard.com (Todd Maynard) Date: Thu, 19 Jan 2006 11:28:33 -0500 Subject: [Tutor] Indexing in a series for a newbie In-Reply-To: References: Message-ID: <200601191128.33624.python-tutor@toddmaynard.com> Another approach would be to change your data structure to include the words and hints together as tuples in the same tuple. ie... WORDS=( ("python","The python hint"),("program","The program hint"), ("code","The code hint") ) then you can do... word, hint = random.choice(WORDS) >>> WORDS=( ("python","The python hint"),("program","The program hint"), ("code","The code hint") ) >>> word, hint = random.choice(WORDS) >>> word 'code' >>> hint 'The code hint' >>> Happy coding, -- Todd Maynard On Thursday 19 January 2006 10:36, Jon Moore wrote: > Hello > > I need some help for a program I am writing as a newbie to Python. > > I have created a series: > > WORDS = ("python", "program", "code", "xylophone") > > and then assigned one of them randomly to the variable 'word': > > word = random.choice(WORDS) > > I know that if I do: > > print word > > The randomly chosen word will be displayed. I also know that if I type: > > print WORDS[x] > > I will get the corresponding word back. But how do I find 'programaticaly' > the index number for the string that random.choice has chosen? > > The reason I ask is that I an writing a simple word jumble game and need to > link the randomly chosen word to a hint should the user need one. > > -- > Best Regards > > Jon Moore From srini_iyyer_bio at yahoo.com Thu Jan 19 19:01:57 2006 From: srini_iyyer_bio at yahoo.com (Srinivas Iyyer) Date: Thu, 19 Jan 2006 10:01:57 -0800 (PST) Subject: [Tutor] how to do multiple searching against many lists In-Reply-To: Message-ID: <20060119180157.27156.qmail@web31608.mail.mud.yahoo.com> Hi Group, my Problem: I have soms list for variety of animals, birds, bacteria I have another list: search_list = ['cat','python','parrot','donkey','e.coli'] animals = ['cat','tiger','donkey','zebra','lemur'] birs = ['parrot','mina','oriole','blue jay'] bacteria = ['e.coli','bacillus','staphy','acetobacter'] my output should look like this: cat '\t' animal python '\t' animal parrot '\t' bird donkey '\t'animal e.coli '\t' bacteria Can I do this using dictionaries , so that to make it faster? Thanks Srini __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From ajikoe at gmail.com Thu Jan 19 19:14:30 2006 From: ajikoe at gmail.com (Pujo Aji) Date: Thu, 19 Jan 2006 19:14:30 +0100 Subject: [Tutor] how to do multiple searching against many lists In-Reply-To: <20060119180157.27156.qmail@web31608.mail.mud.yahoo.com> References: <20060119180157.27156.qmail@web31608.mail.mud.yahoo.com> Message-ID: Yes you can. you can make: search_list =['cat','python','parrot','donkey','e.coli'] animals = ['python','cat','tiger','donkey','zebra','lemur'] birds = ['parrot','mina','oriole','blue jay'] bacteria = ['e.coli','bacillus','staphy','acetobacter'] mydic = {} for animal in animals : mydic[animal] = 'animal' for bird in birds: mydic[bird] = 'bird' for bacteri in bacteria: mydic[bacteri] = 'bacteria' for x in search_list: print x, mydic[x] Don't forget to include 'python' in animals group. Cheers, pujo On 1/19/06, Srinivas Iyyer wrote: > > Hi Group, > > my Problem: > > I have soms list for variety of animals, birds, > bacteria > > > I have another list: > search_list = > ['cat','python','parrot','donkey','e.coli'] > > animals = ['cat','tiger','donkey','zebra','lemur'] > birs = ['parrot','mina','oriole','blue jay'] > bacteria = > ['e.coli','bacillus','staphy','acetobacter'] > > my output should look like this: > > cat '\t' animal > python '\t' animal > parrot '\t' bird > donkey '\t'animal > e.coli '\t' bacteria > > Can I do this using dictionaries , so that to make it > faster? > > Thanks > Srini > > __________________________________________________ > Do You Yahoo!? > Tired of spam? Yahoo! Mail has the best spam protection around > http://mail.yahoo.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060119/f1140311/attachment.htm From kent37 at tds.net Thu Jan 19 19:37:40 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 19 Jan 2006 13:37:40 -0500 Subject: [Tutor] how to do multiple searching against many lists In-Reply-To: <20060119180157.27156.qmail@web31608.mail.mud.yahoo.com> References: <20060119180157.27156.qmail@web31608.mail.mud.yahoo.com> Message-ID: <43CFDC74.5020905@tds.net> Srinivas Iyyer wrote: > Hi Group, > > my Problem: > > I have soms list for variety of animals, birds, > bacteria > > > I have another list: > search_list = > ['cat','python','parrot','donkey','e.coli'] > > animals = ['cat','tiger','donkey','zebra','lemur'] > birs = ['parrot','mina','oriole','blue jay'] > bacteria = > ['e.coli','bacillus','staphy','acetobacter'] > > my output should look like this: > > cat '\t' animal > python '\t' animal > parrot '\t' bird > donkey '\t'animal > e.coli '\t' bacteria > > Can I do this using dictionaries , so that to make it > faster? I would make animals, birds and bacteria into sets rather than dicts since the values don't map to anything. You could store the sets in a single dict to give you the name -> set mapping. For example: >>> animals = set(['cat','tiger','donkey','zebra','lemur']) >>> birds = set(['parrot','mina','oriole','blue jay']) >>> bacteria = set(['e.coli','bacillus','staphy','acetobacter']) >>> fauna = { 'animals' : animals, 'birds' : birds, 'bacteria' : bacteria } >>> for item in ['cat','python','parrot','donkey','e.coli']: ... for setName, setValue in fauna.iteritems(): ... if item in setValue: ... print '%s\t%s' % (item, setName) ... cat animals parrot birds donkey animals e.coli bacteria Or, if each critter can be in only one set, you could make one dict that maps the critter name to the set it is in, and just do one lookup: >>> fauna2 = {} >>> for animal in animals: fauna2[animal] = 'animal' ... >>> for bird in birds: fauna2[bird] = 'bird' ... >>> for bacterium in bacteria: fauna2[bacterium] = 'bacteria' ... >>> for item in ['cat','python','parrot','donkey','e.coli']: ... print '%s\t%s' % (item, fauna2.get(item, 'None')) ... cat animal python None parrot bird donkey animal e.coli bacteria Kent From dyoo at hkn.eecs.berkeley.edu Thu Jan 19 19:53:19 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 19 Jan 2006 10:53:19 -0800 (PST) Subject: [Tutor] Indexing in a series for a newbie In-Reply-To: Message-ID: On Thu, 19 Jan 2006, Jon Moore wrote: > I need some help for a program I am writing as a newbie to Python. > > I have created a series: > > WORDS = ("python", "program", "code", "xylophone") > > and then assigned one of them randomly to the variable 'word': > > word = random.choice(WORDS) > > I will get the corresponding word back. But how do I find 'programaticaly' > the index number for the string that random.choice has chosen? Hi Jon, If you need the index as well as the sequence element, then it may be more practical to select a random index rather than a random element. The reason is because it's easy to get a sequence element from its index, but not necessarily visa-versa. The random.randrange() function may be useful here. Good luck! From dyoo at hkn.eecs.berkeley.edu Thu Jan 19 19:50:14 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 19 Jan 2006 10:50:14 -0800 (PST) Subject: [Tutor] Python + MySQL , my first simple program does not gives results In-Reply-To: <20060119124612.81099.qmail@web34803.mail.mud.yahoo.com> Message-ID: On Thu, 19 Jan 2006, John Joseph wrote: > Hi > I tried out my first Pyhton program with MySQL > I was trying to get the some result , eg > describe table, select * from table Hi John, Unlike Java, Python doesn't force you to put everything in a class. You can try the simpler: ###### import MySQLdb db = MySQLdb.connect(host="localhost",user = "john",password = "asdlkj", db = learnpython) cursor = db.cursor() cursor.execute(" describe contact" ) cursor.execute(" SELECT * from contact" ) ###### from toplevel. > but my program does not give the expected results , What do you expect to see, and from where? A call to cursor.execute() sets the cursor up so that subsequent calls to cursor.fetchone() will give us result rows. See: http://www.amk.ca/python/writing/DB-API.html You need to add some code to print out the result set. The link above is a tutorial to the database interface that should help you get started. Good luck! From victor at grupocdm.com Thu Jan 19 19:51:41 2006 From: victor at grupocdm.com (Victor Bouffier) Date: Thu, 19 Jan 2006 12:51:41 -0600 Subject: [Tutor] [Re] Fwd: Strings backwards In-Reply-To: References: Message-ID: <1137696701.2845.20.camel@elrond> This was just posted by John Fouhy (snipped part of it): Basically, the syntax is [start:stop:step]. If step is negative, you work backwards. eg: >>> string.lowercase[20:10:-2] # letters 20, 18, 16, 14, 12 'usqom' And if you omit the start or stop parameters, and step is negative, then start defaults to the end of the list and stop to the beginning. So string.lowercase[::-1] will step backwards, starting at the end and finishing at the start. So to reverse a string, you would only need to do the following: >>> print 'hello world'[::-1] dlrow olleh I had to do the string-to-list-then-reverse-string-then-back-to-string process myself before knowing about this marvelous operand. It works on tuples (all immutable objects) too: >>> digits = (0,1,2,3,4,5,6,7,8,9) >>> print digits[::-1] (9, 8, 7, 6, 5, 4, 3, 2, 1, 0) Best of Luck Victor On Thu, 2006-01-19 at 08:26 +0100, J?nos Juh?sz wrote: > Hi Ryan, > > I just extended Adam's code with a speech-to-text recepi from > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/114216. > > On 18/01/06, ryan luna wrote: > > > > Hello, what i need to do is get user input and then > > print the string backwards ^^ i have no idea how to do > > that, > > > > print "Enter a word and i well tell you how to say it > > backwards" > > > > word = raw_input("Your word: ") > > > > print word > > > > all that is simple enough im sure printing it out > > backwards is to, just dont know how ^^, thanks for any help. > > import sys > from win32com.client import constants > import win32com.client > import string > > speaker = win32com.client.Dispatch("SAPI.SpVoice") > print "Type word or phrase, then enter." > print "Ctrl+Z then enter to exit." > > def backword(word): > l = list(word) > l.reverse() > return ''.join(l) > > def backsentence(sentence): > words = sentence.split(' ') > words = [backword(word) for word in words] > return ' '.join(words) > > while 1: > try: > s = raw_input() > rev = backsentence(s) > print 'I would say: ', rev > speaker.Speak(rev) > except: > if sys.exc_type is EOFError: > sys.exit() > > It works on my xp :) > > > Yours sincerely, > ______________________________ > J?nos Juh?sz > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From zenzee at xs4all.nl Thu Jan 19 20:20:22 2006 From: zenzee at xs4all.nl (Vincent Zee) Date: Thu, 19 Jan 2006 20:20:22 +0100 Subject: [Tutor] How to get terminal settings Message-ID: <20060119192022.GA55224@xs4all.nl> Hi, say you want to write a more-like program. How do you know how many lines the terminal window can display. /\ Vincent From alan.gauld at freenet.co.uk Thu Jan 19 20:29:36 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 19 Jan 2006 19:29:36 -0000 Subject: [Tutor] Links for programming using MySQL References: <20060119102623.62073.qmail@web34801.mail.mud.yahoo.com> Message-ID: <006601c61d2e$af277e60$0b01a8c0@xp> > I wanted to try out python with MySQL databases What do you need to know about? Do you already know about MySql and just want to know how to connect to a database and execute a SQL statement? Or do you need to know about databases too? If the latter you can try the database topic in my tutor. If its the former look at the Python DBI documentation and then the python MySql data base driver docs. Between them they should sort things out. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Thu Jan 19 20:36:41 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 19 Jan 2006 19:36:41 -0000 Subject: [Tutor] Python + MySQL , my first simple program does not gives results References: <20060119124612.81099.qmail@web34803.mail.mud.yahoo.com> Message-ID: <007c01c61d2f$ac26f320$0b01a8c0@xp> > I was trying to get the some result , eg > describe table, select * from table > but my program does not give the expected results , > nor it gives any error First of all you have only defined init() but not created an instance so it never actually gets called! But if you do call it(by creating an instance of learnpython_db)... You are fetching the results into the cursor but you never access them! So the second execute call will overwrite the first execute with the SELECT results. But then you exit the init() function so cursor (a local variable) is garbage collected and the results die with it.. > import MySQLdb > class learnpython_db: > def __init__(self): > db = > MySQLdb.connect(host="localhost",user = > "john",password = "asdlkj", db = learnpython) > cursor = db.cursor() > cursor.execute(" describe contact" ) > cursor.execute(" SELECT * from > contact" ) You probably want to make cursor (and maybe db too) an instance variable. Then you can access the results of the cursor in other methods of the object. You will see this illustrated in my tutorial topic albeit using SQLite but the cursor hjandling is nearly identical. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From w.damen at gmail.com Thu Jan 19 20:41:12 2006 From: w.damen at gmail.com (Rinzwind) Date: Thu, 19 Jan 2006 20:41:12 +0100 Subject: [Tutor] escaping spaces in a directoryname Message-ID: <4677730601191141g535af141ud6c8a9914562eaf2@mail.gmail.com> Hmm, a very newby question but I never had to deal with escaping spaces etc. I want to read a directory with spaces in it and it errors out (because of the space). I need to escape it with a \ I guess. I saw alot about that on some websites but they all talk about why and how you escape and not what function can do that. Is there one? Or do I have scan the string and add them myself. *goes back to searching on the web* If I find it before I get an answer I'll post it :=) Wim -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060119/d2585442/attachment.html From bill at celestial.net Thu Jan 19 20:29:29 2006 From: bill at celestial.net (Bill Campbell) Date: Thu, 19 Jan 2006 11:29:29 -0800 Subject: [Tutor] How to get terminal settings In-Reply-To: <20060119192022.GA55224@xs4all.nl> References: <20060119192022.GA55224@xs4all.nl> Message-ID: <20060119192929.GB84208@alexis.mi.celestial.com> On Thu, Jan 19, 2006, Vincent Zee wrote: >Hi, > >say you want to write a more-like program. >How do you know how many lines the terminal window >can display. Use the curses library, and it will take care of this for you. Bill -- INTERNET: bill at Celestial.COM Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 The most serious doubt that has been thrown on the authenticity of the biblical miracles is the fact that most of the witnesses in regard to them were fishermen. -- Arthur Binstead From zenzee at xs4all.nl Thu Jan 19 21:09:27 2006 From: zenzee at xs4all.nl (Vincent Zee) Date: Thu, 19 Jan 2006 21:09:27 +0100 Subject: [Tutor] How to get terminal settings In-Reply-To: <20060119192929.GB84208@alexis.mi.celestial.com> References: <20060119192022.GA55224@xs4all.nl> <20060119192929.GB84208@alexis.mi.celestial.com> Message-ID: <20060119200927.GB55224@xs4all.nl> On Thursday, 19 January 2006 at 11:29:29 -0800, Bill Campbell wrote: > On Thu, Jan 19, 2006, Vincent Zee wrote: > >Hi, > > > >say you want to write a more-like program. > >How do you know how many lines the terminal window > >can display. > > Use the curses library, and it will take care of this for you. > Hi Bill, thanks for your answer. Is there, except from using the curses library, any other method? I'm a bit afraid of using curses at the moment(;-)) /\ Vincent From victor at grupocdm.com Thu Jan 19 21:19:23 2006 From: victor at grupocdm.com (Victor Bouffier) Date: Thu, 19 Jan 2006 14:19:23 -0600 Subject: [Tutor] References and list aliasing in Perl and Python [Was: Re: Dictionaries] In-Reply-To: References: Message-ID: <1137701963.2845.25.camel@elrond> On Wed, 2006-01-18 at 23:03 -0800, Danny Yoo wrote: > > > There are tradeoffs here. On the one hand, Python folks get caught > > > off guard when they first encounter list aliasing. On the other, Perl > > > folks get caught off guard when they first try to make a hash whose > > > values are themselves lists. *grin* > > > > > WOW. Great explanation. Don't worry about a deeper hole. > > > > Your examples once again reminded me of one of reasons I started looking > > into Python instead of continuing with Perl. It is not the > > functionality, but the convoluted scripts can get. One can hardly > > understand the code. > > Hi Victor, > > That might be an unfair judgement. > > One can write really convoluted and ugly programs in any programming > language. And although I do think that our choice in what programming > language we us can affect a program's clarity, I also believe that people > matter much more than the programming language. > > Otherwise, what would be the point of a mailing list like this? *grin* > > > Best of wishes! > > Yes, it is true. Take care. Victor From dyoo at hkn.eecs.berkeley.edu Thu Jan 19 21:37:38 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 19 Jan 2006 12:37:38 -0800 (PST) Subject: [Tutor] How to get terminal settings In-Reply-To: <20060119192022.GA55224@xs4all.nl> Message-ID: On Thu, 19 Jan 2006, Vincent Zee wrote: > say you want to write a more-like program. How do you know how many > lines the terminal window can display. Hi Vincent, It's possible that this information might already be in your environment. If you're using the 'bash' shell, and if the 'checkwinsize' option is set in bash, then bash should keep track of the window size through LINES and COLUMNS. According to the "Art of Unix Programming": http://www.faqs.org/docs/artu/ch10s04.html those variables are fairly standard and lots of programs use them. But I don't know if other shells go out of their way to maintain consistancy with the current terminal size on terminal resizing. If you want to get at the environment variables, take a look at the 'os.environ' dictionary: http://www.python.org/doc/lib/os-procinfo.html#l2h-1508 Alternatively, if you're on Unix, the 'curses' module will get you the information you want. http://www.python.org/doc/lib/module-curses.html On Windows, it looks like you can use the following cookbook recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440694 From zenzee at xs4all.nl Thu Jan 19 22:05:27 2006 From: zenzee at xs4all.nl (Vincent Zee) Date: Thu, 19 Jan 2006 22:05:27 +0100 Subject: [Tutor] How to get terminal settings In-Reply-To: References: <20060119192022.GA55224@xs4all.nl> Message-ID: <20060119210527.GC55224@xs4all.nl> On Thursday, 19 January 2006 at 12:37:38 -0800, Danny Yoo wrote: > > > On Thu, 19 Jan 2006, Vincent Zee wrote: > > > say you want to write a more-like program. How do you know how many > > lines the terminal window can display. > > Hi Vincent, > > It's possible that this information might already be in your environment. > If you're using the 'bash' shell, and if the 'checkwinsize' option is set > in bash, then bash should keep track of the window size through LINES and > COLUMNS. According to the "Art of Unix Programming": > > http://www.faqs.org/docs/artu/ch10s04.html > > those variables are fairly standard and lots of programs use them. But I > don't know if other shells go out of their way to maintain consistancy > with the current terminal size on terminal resizing. > > If you want to get at the environment variables, take a look at the > 'os.environ' dictionary: > > http://www.python.org/doc/lib/os-procinfo.html#l2h-1508 > > > Alternatively, if you're on Unix, the 'curses' module will get you the > information you want. > > http://www.python.org/doc/lib/module-curses.html Hi Danny, thank you for your reply. I want the program to run on Freebsd and on MacOSX. On FreeBSD I use the tcsh and on Mac its bash or tcsh. I looked at the curses module and also to the cursus howto on python.org but I find it still a bit unclear on how to use it. There being curses, ncurses and a curses wrapper. I'm a little confused. The os.environ didn't give me any hints to screen size so maybe curses is the way to go. Any pointers to other curses howto's? /\ Vincent From bernd at prager.ws Thu Jan 19 22:42:50 2006 From: bernd at prager.ws (bernd) Date: Thu, 19 Jan 2006 16:42:50 -0500 Subject: [Tutor] Simple MS Windows Shell Extension? Message-ID: <20060119214243.GA6474@mail.prager.ws> Hi, I have a python script that I want my users to execute with a "Right-Mouse-Click" on a file under Windows XP. (If possible without changing the default "Open with ..." behavior from Windows.) Does anybody has a simple example on how to do that? Thanks, -- Bernd From singingxduck at gmail.com Thu Jan 19 22:49:50 2006 From: singingxduck at gmail.com (Orri Ganel) Date: Thu, 19 Jan 2006 16:49:50 -0500 Subject: [Tutor] [Re] Fwd: Strings backwards In-Reply-To: <1137696701.2845.20.camel@elrond> References: <1137696701.2845.20.camel@elrond> Message-ID: <43D0097E.3070609@gmail.com> Victor Bouffier wrote: >I had to do the string-to-list-then-reverse-string-then-back-to-string >process myself before knowing about this marvelous operand. >It works on tuples (all immutable objects) too: > [SNIP] Not all immutable objects, just those that define __getslice__ (basically, those that use indexes: sequences). Ints, for example, are immutable and don't work: >>> 12[::-1] Traceback (most recent call last): File "", line 1, in -toplevel- 12[::-1] TypeError: unsubscriptable object - Orri -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. From alan.gauld at freenet.co.uk Fri Jan 20 00:53:06 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 19 Jan 2006 23:53:06 -0000 Subject: [Tutor] How to get terminal settings References: <20060119192022.GA55224@xs4all.nl> Message-ID: <00a301c61d53$7ed77ba0$0b01a8c0@xp> Assuming you are on a Unix style OS/terminal you can read the output of stty. Look at the rows value Here are a couple of runs of rows at different terminal sizes: $ stty -a | grep rows speed 38400 baud; rows 41; columns 80; line = 0; $ stty -a | grep rows speed 38400 baud; rows 26; columns 80; line = 0; A call to Popen should get you what you want. An alternative technique, and the one useed by the real more/less programmes is to use curses to open a display window. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From carroll at tjc.com Fri Jan 20 01:03:16 2006 From: carroll at tjc.com (Terry Carroll) Date: Thu, 19 Jan 2006 16:03:16 -0800 (PST) Subject: [Tutor] How to get terminal settings In-Reply-To: <20060119210527.GC55224@xs4all.nl> Message-ID: On Thu, 19 Jan 2006, Vincent Zee wrote: > Any pointers to other curses howto's? There's http://heather.cs.ucdavis.edu/~matloff/Python/PyCurses.pdf ; but it's mostly a couple of example programs, without a lot of explanation. From ps_python3 at yahoo.co.in Fri Jan 20 01:10:59 2006 From: ps_python3 at yahoo.co.in (ps python) Date: Fri, 20 Jan 2006 00:10:59 +0000 (GMT) Subject: [Tutor] getting text within an element [attribute text] using elementtree In-Reply-To: Message-ID: <20060120001059.29886.qmail@web8406.mail.in.yahoo.com> Dear group, In my XML file some attributes have text within an element. I want to get that text. How can I do that. I looked into ElementTree -bits and pieces: and there is a small function. >>> def gettext(elem): ... text = elem.text or "" ... for e in elem: ... text += gettext(e) ... if e.tail: ... text += e.tail ... return text >>> for m in tree.findall('//{org:hprd:dtd:hprdr2}proteinInteractor'): ... k = gettext(m) ... print k ... >>> I got nothing out of it. I tried more preliminary way: >>> for m in tree.findall('//{org:hprd:dtd:hprdr2}proteinIn ... k = m.findtext('{org:hprd:dtd:hprdr2}secondaryRef' ... print k ... >>> for m in tree.findall('//{org:hprd:dtd:hprdr2}proteinIn ... print m ... >>> The part of the xml file is listd below. Could any one you help me please. I want to get : id value: Thanks w HPRD Human Protein Reference Database Histone H3 Human Homo sapiens Minichromosome maintenance protein 2 Mouse Mus musculus MCM3 Mouse Mus musculus MCM4 Mouse Mus musculus Send instant messages to your online friends http://in.messenger.yahoo.com From dyoo at hkn.eecs.berkeley.edu Fri Jan 20 01:48:53 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 19 Jan 2006 16:48:53 -0800 (PST) Subject: [Tutor] getting text within an element [attribute text] using elementtree In-Reply-To: <20060120001059.29886.qmail@web8406.mail.in.yahoo.com> Message-ID: On Fri, 20 Jan 2006, ps python wrote: > In my XML file some attributes have text within an element. I want to > get that text. How can I do that. Hello, The problems you have don't have to do with the calls to gettext, but to selecting namespaced nodes as with your previous questions. Let's look at some of the code: > >>> for m in > tree.findall('//{org:hprd:dtd:hprdr2}proteinInteractor'): > ... k = gettext(m) > ... print k > ... The XML that you show us appears to use a different namespace than 'org:hprd:dtd:hprdr2': ###################################### >> text = """ ... Hello world ... This has attributes ... """ >>> from elementtree import ElementTree >>> tree = ElementTree.fromstring(text) >>> tree >>> >>> for msg in tree: ... if msg.get('name'): ... print msg.get('name') ... print msg.text ... attr1 This has attributes ###### Good luck! From 3dbernard at gmail.com Fri Jan 20 02:14:21 2006 From: 3dbernard at gmail.com (Bernard Lebel) Date: Thu, 19 Jan 2006 17:14:21 -0800 Subject: [Tutor] glibc error while Python script runs - Solved Message-ID: <61d0e2b40601191714g17e3e59fq55132b3fa8508b14@mail.gmail.com> Hello, For the record, in case anyone would like to know what happened with this issue... It seems that the problem was related to the way I managed MySQL connections. There was the main thread that would query every 5 seconds the database to see if a someone wanted to abort the job running on the render node. However, the actual rendering was managed by a child thread, who would perform many MySQL transactions, depending on the output produced by the rendering software. So there were two separate threads doing MySQL queries. I noticed by reading my debug logs that some of these queries would become interlaced, that is, one query would try to update while another would try to select-fetch. In turned out that this would severe the connection with the database, and soon after Python would crash altogether. So the solution was to start some sort of queue server in a separate thread. This queue would consist of a list, and each time the program would want to perform a MySQL operation, it would add it to the queue. Then, the caller would enter a while loop that would wait for the server to carry the operation. The server would run a while loop, that check the queue once every iteration to see if there is something to do. When it finds something, it would carry the entire transaction, then put the result in a dictionary, using an ID number assigned when the transaction was submitted to the queue. The "submitter" would then pick up the result, and return it to the original caller. The result is that no two queries would take place at the same time. Once I did that, my program stopped crashing, and actually has been running very smooth since then. In fact my progam is now very very close to completion. Kent: I took your suggestion and changed the program design and splitted the code into separate modules. It was tricky to "re-wire" everything together (it took me at least 4 days), but past that, I'm glad I did it. Thanks everyone for the help, it has been a great learning experience! Bernard On 1/4/06, Bernard Lebel <3dbernard at gmail.com> wrote: > Hi Danny, > See [Bernard] below... > > On 1/4/06, Danny Yoo wrote: > > > > > rn200.bbfxa.com Wed Jan 4 16:23:36 2006 [jobid: 9]: Get status of all > > > local jobs for this job... > > > > > > *** glibc detected *** double free or corruption: 0x09484d58 *** > > > Aborted > > > > > > Hi Bernard, > > > > Ugh. I hate memory allocation bugs. > > > > Is it reproducable? Can you run this through a debugger like GDB to find > > out where we are when this happens? A stack trace will be invaluable > > because we need to know who to blame. > > [Bernard] I am quite unfamiliar with Linux in general and a lot more > with these tools. Where can I find information about GDB? > > > > *grin* We need to know if it's > > Python that's doing this, or if it's MySQLdb, or if it's something else > > entirely... > > > > Just checking up on this: what version of MySQLdb do you have on those > > systems? I do remember some ugly memory-leaking bugs that haunted ancient > > versions of MySQLdb, so I want to make sure we're not hitting those. > > [Bernard] I am using 1.2.0, with Python 2.3.4. > > > > > > Analyzing this might goes out of Tutor's scope, so you may want to bring > > this up on a more general forum like comp.lang.python instead. > > [Bernard] Okay thanks a lot. I'll check it out, but if you have any idea... :-) > > > Bernard > From kent37 at tds.net Fri Jan 20 02:44:16 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 19 Jan 2006 20:44:16 -0500 Subject: [Tutor] glibc error while Python script runs - Solved In-Reply-To: <61d0e2b40601191714g17e3e59fq55132b3fa8508b14@mail.gmail.com> References: <61d0e2b40601191714g17e3e59fq55132b3fa8508b14@mail.gmail.com> Message-ID: <43D04070.3040309@tds.net> Hi Bernard, I'm glad you got it working but kind of surprised at what you had to do. You shouldn't have to have a single thread to access the database. In your original desing were you sharing a connection between threads? That could cause trouble. But if each connection has its own thread and you are using transactions and isolation levels appropriately, they shouldn't stomp on each other. There are some good recipes for queuing up tasks and getting callbacks that might be simpler than your dictionary solution. For example see http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/435883 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/203871 You could also use a second queue to return results to the main thread. Kent Bernard Lebel wrote: > Hello, > > For the record, in case anyone would like to know what happened with > this issue... > > > It seems that the problem was related to the way I managed MySQL > connections. There was the main thread that would query every 5 > seconds the database to see if a someone wanted to abort the job > running on the render node. > > However, the actual rendering was managed by a child thread, who would > perform many MySQL transactions, depending on the output produced by > the rendering software. > > So there were two separate threads doing MySQL queries. I noticed by > reading my debug logs that some of these queries would become > interlaced, that is, one query would try to update while another would > try to select-fetch. In turned out that this would severe the > connection with the database, and soon after Python would crash > altogether. > > So the solution was to start some sort of queue server in a separate > thread. This queue would consist of a list, and each time the program > would want to perform a MySQL operation, it would add it to the queue. > Then, the caller would enter a while loop that would wait for the > server to carry the operation. > > The server would run a while loop, that check the queue once every > iteration to see if there is something to do. When it finds something, > it would carry the entire transaction, then put the result in a > dictionary, using an ID number assigned when the transaction was > submitted to the queue. > > The "submitter" would then pick up the result, and return it to the > original caller. > The result is that no two queries would take place at the same time. > > Once I did that, my program stopped crashing, and actually has been > running very smooth since then. In fact my progam is now very very > close to completion. > > > > Kent: I took your suggestion and changed the program design and > splitted the code into separate modules. It was tricky to "re-wire" > everything together (it took me at least 4 days), but past that, I'm > glad I did it. > > > Thanks everyone for the help, it has been a great learning experience! > > > Bernard From 3dbernard at gmail.com Fri Jan 20 03:04:55 2006 From: 3dbernard at gmail.com (Bernard Lebel) Date: Thu, 19 Jan 2006 18:04:55 -0800 Subject: [Tutor] glibc error while Python script runs - Solved In-Reply-To: <43D04070.3040309@tds.net> References: <61d0e2b40601191714g17e3e59fq55132b3fa8508b14@mail.gmail.com> <43D04070.3040309@tds.net> Message-ID: <61d0e2b40601191804yc3d569em35d60fb0c3be11c7@mail.gmail.com> On 1/19/06, Kent Johnson wrote: > Hi Bernard, > > I'm glad you got it working but kind of surprised at what you had to do. > You shouldn't have to have a single thread to access the database. In > your original desing were you sharing a connection between threads? That > could cause trouble. But if each connection has its own thread and you > are using transactions and isolation levels appropriately, they > shouldn't stomp on each other. I'm not sure what you mean by transaction and isolation levels. I get some sort of an idea, but could you elaborate on the idea? I have not considered having one connection per thread, and have not tested the idea. The way it works right now is that there is only one connection, as a class instance attribute. All transaction go through that connection. > > There are some good recipes for queuing up tasks and getting callbacks > that might be simpler than your dictionary solution. For example see > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/435883 > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/203871 > > You could also use a second queue to return results to the main thread. Thanks I'll check these out. Bernard > > Kent > > Bernard Lebel wrote: > > Hello, > > > > For the record, in case anyone would like to know what happened with > > this issue... > > > > > > It seems that the problem was related to the way I managed MySQL > > connections. There was the main thread that would query every 5 > > seconds the database to see if a someone wanted to abort the job > > running on the render node. > > > > However, the actual rendering was managed by a child thread, who would > > perform many MySQL transactions, depending on the output produced by > > the rendering software. > > > > So there were two separate threads doing MySQL queries. I noticed by > > reading my debug logs that some of these queries would become > > interlaced, that is, one query would try to update while another would > > try to select-fetch. In turned out that this would severe the > > connection with the database, and soon after Python would crash > > altogether. > > > > So the solution was to start some sort of queue server in a separate > > thread. This queue would consist of a list, and each time the program > > would want to perform a MySQL operation, it would add it to the queue. > > Then, the caller would enter a while loop that would wait for the > > server to carry the operation. > > > > The server would run a while loop, that check the queue once every > > iteration to see if there is something to do. When it finds something, > > it would carry the entire transaction, then put the result in a > > dictionary, using an ID number assigned when the transaction was > > submitted to the queue. > > > > The "submitter" would then pick up the result, and return it to the > > original caller. > > The result is that no two queries would take place at the same time. > > > > Once I did that, my program stopped crashing, and actually has been > > running very smooth since then. In fact my progam is now very very > > close to completion. > > > > > > > > Kent: I took your suggestion and changed the program design and > > splitted the code into separate modules. It was tricky to "re-wire" > > everything together (it took me at least 4 days), but past that, I'm > > glad I did it. > > > > > > Thanks everyone for the help, it has been a great learning experience! > > > > > > Bernard > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From dyoo at hkn.eecs.berkeley.edu Fri Jan 20 04:23:25 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 19 Jan 2006 19:23:25 -0800 (PST) Subject: [Tutor] glibc error while Python script runs - Solved In-Reply-To: <43D04070.3040309@tds.net> Message-ID: On Thu, 19 Jan 2006, Kent Johnson wrote: > In your original desing were you sharing a connection between threads? > That could cause trouble. But if each connection has its own thread and > you are using transactions and isolation levels appropriately, they > shouldn't stomp on each other. Hi Kent and Bernard, It's possible that MySQLdb was linked against the non-thread-safe mysqlclient (rather than mysqlclient_r) library; that would probably cause havoc. > > So the solution was to start some sort of queue server in a separate > > thread. This queue would consist of a list, and each time the program > > would want to perform a MySQL operation, it would add it to the queue. We may want to use the Queue module here instead of a list; the way the program is described now sounds like the server is busy-spinning when it looks for new things to do. The thing that makes busy-spinning slightly not-nice is that it consumes CPU regardless if the system's doing anything or not. But a more serious problem than busy-waiting is one of thread-safety: the object that's used to communicate between two threads --- a shared list --- might be unreliable if the list methods aren't thread-safe. And I'm not certain that all the list methods are thread-safe. That is, the problem with mutual exclusion may have just been pushed up the program's structure, from the MySQL queries up to the shared queue list access. *grin* The synchronized Queue described in: http://www.python.org/doc/lib/module-Queue.html is designed to be a reliable communication medium between threads, and I strongly recommend you look at it, especially because you've seen first-hand the weird things that can happen with threads. *grin* Here's a small example that shows what a different Queue can make: ############################################ from threading import Thread class Server: def __init__(self): self.queue = [] def acceptJob(self, query): self.queue.append((query,)) def shutdownOnIdle(self): self.queue.append("QUIT!") def jobLoop(self): while True: print "looping" if len(self.queue) > 0: nextJob = self.queue.pop(0) if nextJob == "QUIT!": return print "I should do", nextJob def startServer(self): Thread(target=self.jobLoop).start() if __name__ == '__main__': server = Server() server.startServer() server.acceptJob("a") server.acceptJob("b") server.acceptJob("c") server.shutdownOnIdle() ############################################ Running this will show just how much work a busy-waiting thread does. But if we change a few methods to use Queues instead of lists: ###### from threading import Thread from Queue import Queue class Server: def __init__(self): self.queue = Queue() def acceptJob(self, query): self.queue.put((query,)) def shutdownOnIdle(self): self.queue.put("QUIT!") def jobLoop(self): while True: print "looping" nextJob = self.queue.get() if nextJob == "QUIT!": return print "I should do", nextJob def startServer(self): Thread(target=self.jobLoop).start() if __name__ == '__main__': server = Server() server.startServer() server.acceptJob("a") server.acceptJob("b") server.acceptJob("c") server.shutdownOnIdle() ###### and compare the output of this to the original implementation, it should be clearer why Queues are cool. *grin* Does this make sense? I hope this helps! From 3dbernard at gmail.com Fri Jan 20 04:48:26 2006 From: 3dbernard at gmail.com (Bernard Lebel) Date: Thu, 19 Jan 2006 19:48:26 -0800 Subject: [Tutor] glibc error while Python script runs - Solved In-Reply-To: References: <43D04070.3040309@tds.net> Message-ID: <61d0e2b40601191948g18f17b24s896bffcb629da998@mail.gmail.com> Thanks a lot Danny, That certainly does make sense. I'll look into implementing the Queue approach in my program tomorrow. I remember you recommending me this module as well not long ago, although in a different discussion (where I suspected problem with file access from multiple thread, but I guess it's pretty much a similar problem, isn't it? :-) Thanks again Bernard On 1/19/06, Danny Yoo wrote: > > > On Thu, 19 Jan 2006, Kent Johnson wrote: > > > > In your original desing were you sharing a connection between threads? > > That could cause trouble. But if each connection has its own thread and > > you are using transactions and isolation levels appropriately, they > > shouldn't stomp on each other. > > Hi Kent and Bernard, > > It's possible that MySQLdb was linked against the non-thread-safe > mysqlclient (rather than mysqlclient_r) library; that would probably cause > havoc. > > > > > So the solution was to start some sort of queue server in a separate > > > thread. This queue would consist of a list, and each time the program > > > would want to perform a MySQL operation, it would add it to the queue. > > We may want to use the Queue module here instead of a list; the way the > program is described now sounds like the server is busy-spinning when it > looks for new things to do. The thing that makes busy-spinning slightly > not-nice is that it consumes CPU regardless if the system's doing anything > or not. > > But a more serious problem than busy-waiting is one of thread-safety: the > object that's used to communicate between two threads --- a shared list > --- might be unreliable if the list methods aren't thread-safe. And I'm > not certain that all the list methods are thread-safe. > > That is, the problem with mutual exclusion may have just been pushed up > the program's structure, from the MySQL queries up to the shared queue > list access. *grin* > > > The synchronized Queue described in: > > http://www.python.org/doc/lib/module-Queue.html > > is designed to be a reliable communication medium between threads, and I > strongly recommend you look at it, especially because you've seen > first-hand the weird things that can happen with threads. *grin* > > > Here's a small example that shows what a different Queue can make: > > ############################################ > from threading import Thread > > class Server: > def __init__(self): > self.queue = [] > > def acceptJob(self, query): > self.queue.append((query,)) > > def shutdownOnIdle(self): > self.queue.append("QUIT!") > > def jobLoop(self): > while True: > print "looping" > if len(self.queue) > 0: > nextJob = self.queue.pop(0) > if nextJob == "QUIT!": > return > print "I should do", nextJob > > def startServer(self): > Thread(target=self.jobLoop).start() > > if __name__ == '__main__': > server = Server() > server.startServer() > server.acceptJob("a") > server.acceptJob("b") > server.acceptJob("c") > server.shutdownOnIdle() > ############################################ > > > Running this will show just how much work a busy-waiting thread does. > > > But if we change a few methods to use Queues instead of lists: > > ###### > from threading import Thread > from Queue import Queue > > class Server: > def __init__(self): > self.queue = Queue() > > def acceptJob(self, query): > self.queue.put((query,)) > > def shutdownOnIdle(self): > self.queue.put("QUIT!") > > def jobLoop(self): > while True: > print "looping" > nextJob = self.queue.get() > if nextJob == "QUIT!": > return > print "I should do", nextJob > > def startServer(self): > Thread(target=self.jobLoop).start() > > if __name__ == '__main__': > server = Server() > server.startServer() > server.acceptJob("a") > server.acceptJob("b") > server.acceptJob("c") > server.shutdownOnIdle() > ###### > > and compare the output of this to the original implementation, it should > be clearer why Queues are cool. *grin* > > > Does this make sense? I hope this helps! > > From zenzee at xs4all.nl Fri Jan 20 09:21:53 2006 From: zenzee at xs4all.nl (Vincent Zee) Date: Fri, 20 Jan 2006 09:21:53 +0100 Subject: [Tutor] How to get terminal settings In-Reply-To: References: <20060119210527.GC55224@xs4all.nl> Message-ID: <20060120082153.GA99831@xs4all.nl> On Thursday, 19 January 2006 at 16:03:16 -0800, Terry Carroll wrote: > On Thu, 19 Jan 2006, Vincent Zee wrote: > > > Any pointers to other curses howto's? > > There's http://heather.cs.ucdavis.edu/~matloff/Python/PyCurses.pdf ; but > it's mostly a couple of example programs, without a lot of explanation. Hi Terry, thank you for the link, I'll have a look. /\ Vincent From kent37 at tds.net Fri Jan 20 03:34:27 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 19 Jan 2006 21:34:27 -0500 Subject: [Tutor] glibc error while Python script runs - Solved In-Reply-To: <61d0e2b40601191804yc3d569em35d60fb0c3be11c7@mail.gmail.com> References: <61d0e2b40601191714g17e3e59fq55132b3fa8508b14@mail.gmail.com> <43D04070.3040309@tds.net> <61d0e2b40601191804yc3d569em35d60fb0c3be11c7@mail.gmail.com> Message-ID: <43D04C33.7090909@tds.net> Bernard Lebel wrote: > On 1/19/06, Kent Johnson wrote: > >>Hi Bernard, >> >>I'm glad you got it working but kind of surprised at what you had to do. >>You shouldn't have to have a single thread to access the database. In >>your original desing were you sharing a connection between threads? That >>could cause trouble. But if each connection has its own thread and you >>are using transactions and isolation levels appropriately, they >>shouldn't stomp on each other. > > > I'm not sure what you mean by transaction and isolation levels. I get > some sort of an idea, but could you elaborate on the idea? Transactions are helpful in two ways. One is to make a sequence of operations atomic - they either all succeed or all fail. A classic example is a banking transaction where you have to debit one account and credit another. You wouldn't want one request to succeed and the other fail - that would be disastrous. By wrapping the two operations in a transaction, the database ensures that they succeed or fail together. The other thing is to isolate the intermediate steps from other database clients. You might not want a second client to see the database in the intermediate step. By setting the proper isolation level on the transaction the database will not make the changes visible to other clients until the transaction commits. http://en.wikipedia.org/wiki/Database_transaction http://en.wikipedia.org/wiki/ACID > > I have not considered having one connection per thread, and have not > tested the idea. The way it works right now is that there is only one > connection, as a class instance attribute. All transaction go through > that connection. So you *were* sharing one connection between several threads before? ouch. I'm not surprised that that broke badly... Kent From alan.gauld at freenet.co.uk Fri Jan 20 09:46:30 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 20 Jan 2006 08:46:30 -0000 Subject: [Tutor] Simple MS Windows Shell Extension? References: <20060119214243.GA6474@mail.prager.ws> Message-ID: <00ca01c61d9e$02b962e0$0b01a8c0@xp> > I have a python script that I want my users to execute with a > "Right-Mouse-Click" on a file under Windows XP. > > (If possible without changing the default "Open with ..." behavior from > Windows.) Use Windows explorer to edit the options on that file type. You can add new context menu items using the Tools->FolderOptions->FileTypes dialog tab. For instance I have several options for a Python sdcript including Edit (in IDLE), View (in Scite) in addition to the usual Open (run it), and Edit with Vim (guess!:-) that are always there. Alan G. From zenzee at xs4all.nl Fri Jan 20 10:05:49 2006 From: zenzee at xs4all.nl (Vincent Zee) Date: Fri, 20 Jan 2006 10:05:49 +0100 Subject: [Tutor] How to get terminal settings In-Reply-To: <00a301c61d53$7ed77ba0$0b01a8c0@xp> References: <20060119192022.GA55224@xs4all.nl> <00a301c61d53$7ed77ba0$0b01a8c0@xp> Message-ID: <20060120090548.GB99831@xs4all.nl> On Thursday, 19 January 2006 at 23:53:06 -0000, Alan Gauld wrote: > Assuming you are on a Unix style OS/terminal you can read the > output of stty. Look at the rows value > > Here are a couple of runs of rows at different terminal sizes: > > $ stty -a | grep rows > speed 38400 baud; rows 41; columns 80; line = 0; > > $ stty -a | grep rows > speed 38400 baud; rows 26; columns 80; line = 0; > > A call to Popen should get you what you want. > > An alternative technique, and the one useed by the real > more/less programmes is to use curses to open a display > window. > Hi Alan, this has helped me very much, thank you. I'll use the popen() before venturing into curses land. /\ Vincent From lemeia at bigpond.com Fri Jan 20 08:43:01 2006 From: lemeia at bigpond.com (lemeia) Date: Fri, 20 Jan 2006 18:43:01 +1100 Subject: [Tutor] unittest and private methods Message-ID: <12243725.1137742981414.JavaMail.root@web03sl> I currently have a class where I have quite a few private methods. One of these methods is a small general utility that extracts characters from provided text up until it reaches a delimiter. Something like extractTo(self, text, delimiter). It's not a relevant interface to the class, just a utility for the class' public methods, which is why I've made it private. That seems to be a logical decision to me. However, the public methods within the class that call it currently only do so to extract numeric events from the text. extractTo is a little more generalised than that and so I decided that I would use unittest to build test cases for the extractTo method and exercise it to its fullest in case the class requires its extended functionality in the future. You'll probably see what my problem is. I can't exercise this method directly from an external test case as the method is not part of the class' public interface. If I call a method in the interface that currently utilises this private method I'm not testing the method as fully as I would like. Now I can build arbitrary interfaces into my class just for testing this method but that sounds like a messy way to maintain a program. Additionally, I could make this method public, but that also seems like an unsatisfactory solution. The example isn't so important to my question, but I wanted to give some context before asking...... Is there a way to specifically target and unit test private methods in a class via unittest without testing them through the class' public interface? I hope I've made some sense there. Patrick From kent37 at tds.net Fri Jan 20 12:06:23 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 20 Jan 2006 06:06:23 -0500 Subject: [Tutor] unittest and private methods In-Reply-To: <12243725.1137742981414.JavaMail.root@web03sl> References: <12243725.1137742981414.JavaMail.root@web03sl> Message-ID: <43D0C42F.5040805@tds.net> lemeia wrote: > I currently have a class where I have quite a few private methods. > One of these methods is a small general utility that extracts characters from provided text up until it reaches a delimiter. Something like extractTo(self, text, delimiter). > > It's not a relevant interface to the class, just a utility for the class' public methods, which is why I've made it private. That seems to be a logical decision to me. Yes, that is good reasoning. When you say it is private, do you mean the name starts with two underscores? > > However, the public methods within the class that call it currently only do so to extract numeric events from the text. extractTo is a little more generalised than that and so I decided that I would use unittest to build test cases for the extractTo method and exercise it to its fullest in case the class requires its extended functionality in the future. > > You'll probably see what my problem is. I can't exercise this method directly from an external test case as the method is not part of the class' public interface. If I call a method in the interface that currently utilises this private method I'm not testing the method as fully as I would like. I'm not sure I understand this part. You mean the private methods have capabilities that can't currently be exercised through the public interface? That smells of "Speculative Generality" - writing code because you think you might need it later. If that is the case the best answer might be to rip it out and wait until you need it. > > Now I can build arbitrary interfaces into my class just for testing this method but that sounds like a messy way to maintain a program. Additionally, I could make this method public, but that also seems like an unsatisfactory solution. > > The example isn't so important to my question, but I wanted to give some context before asking...... > > Is there a way to specifically target and unit test private methods > in a class via unittest without testing them through the class' public interface? Python's notion of privacy is pretty weak. I would have no problem with a unit test that called single-underscore methods in the class under test. Unit test purists object to this, saying a class should only be tested through its public interface, but "practicality beats purity" in my mind. Rereading your mail another possibility comes to mind. It sounds like extractTo() is a general-purpose function that is used for a specific purpose by the module you are testing. Why not extract extractTo to a utility module? Then you can test it as much as you like in the unit tests for the utility and you can reuse it in other code if the need arises. Almost all of my projects have 'util' packages containing collections of miscellaneous useful stuff. The utils have their own unit tests and get included as needed in other modules and projects. Kent From 3dbernard at gmail.com Fri Jan 20 18:13:10 2006 From: 3dbernard at gmail.com (Bernard Lebel) Date: Fri, 20 Jan 2006 12:13:10 -0500 Subject: [Tutor] glibc error while Python script runs - Solved In-Reply-To: <61d0e2b40601191948g18f17b24s896bffcb629da998@mail.gmail.com> References: <43D04070.3040309@tds.net> <61d0e2b40601191948g18f17b24s896bffcb629da998@mail.gmail.com> Message-ID: <61d0e2b40601200913q6d3b3ff5s471a618dc895b82@mail.gmail.com> Hi Danny, So have written a little test script. The fact is that I want to be able to manage the same queue from separate threads. Below is an example of what my real program is doing: from threading import Thread from Queue import Queue import time class SQLServer: def __init__( self ): self.queueinput = Queue() self.queueoutput = Queue() def query( self, sInput ): # Puts an item to the input queue self.queueinput.put( sInput ) # Wait for input queue to output result while True: # Get output from output queue sOutput = self.queueoutput.get() # Return result to caller return sOutput def shutdownOnIdle( self ): self.queueinput.put( "QUIT!" ) # SERVER def serveSqlQueue( self ): while True: # Get a job from the input queue sQuery = self.queueinput.get() # Check if server has to quit if sQuery == "QUIT!": return print 'Server does %s' % sQuery self.queueoutput.put( sQuery ) # START THE SERVER def startServer( self ): Thread( target = self.serveSqlQueue ).start() def separateCaller(): i = 1000 while True: print '--Separate caller asks %i' % i oSeparateOutput = server.query( i ) print '--Separate caller got %s' % str(oSeparateOutput) i += 1 if i == 1004: break if __name__ == '__main__': # Instantiate the server class server = SQLServer() # Start the server server.startServer() # Start the separate thread Thread( target = separateCaller ).start() print 'Main thread asks %s' % 'a' oMainOutput = server.query( 'a' ) print 'Main thread got %s' % str(oMainOutput) print 'Main thread asks %s' % 'b' oMainOutput = server.query( 'b' ) print 'Main thread got %s' % str(oMainOutput) print 'Main thread asks %s' % 'c' oMainOutput = server.query( 'c' ) print 'Main thread got %s' % str(oMainOutput) server.shutdownOnIdle() When I run this, I get this output: Main thread asks a --Separate caller asks 1000 Server does 1000 --Separate caller got 1000 --Separate caller asks 1001 Server does a --Separate caller got a --Separate caller asks 1002 Server does 1001 --Separate caller got 1001 --Separate caller asks 1003 Server does 1002 --Separate caller got 1002 Server does 1003 Main thread got 1003 Main thread asks b Server does b Main thread got b Main thread asks c Server does c Main thread got c As you can see, the main thread and the separateCaller function have mixed results. How can I "synchronize" the queues? Thanks Bernard On 1/19/06, Bernard Lebel <3dbernard at gmail.com> wrote: > Thanks a lot Danny, > > That certainly does make sense. I'll look into implementing the Queue > approach in my program tomorrow. I remember you recommending me this > module as well not long ago, although in a different discussion (where > I suspected problem with file access from multiple thread, but I guess > it's pretty much a similar problem, isn't it? :-) > > > Thanks again > Bernard > > > > On 1/19/06, Danny Yoo wrote: > > > > > > On Thu, 19 Jan 2006, Kent Johnson wrote: > > > > > > > In your original desing were you sharing a connection between threads? > > > That could cause trouble. But if each connection has its own thread and > > > you are using transactions and isolation levels appropriately, they > > > shouldn't stomp on each other. > > > > Hi Kent and Bernard, > > > > It's possible that MySQLdb was linked against the non-thread-safe > > mysqlclient (rather than mysqlclient_r) library; that would probably cause > > havoc. > > > > > > > > So the solution was to start some sort of queue server in a separate > > > > thread. This queue would consist of a list, and each time the program > > > > would want to perform a MySQL operation, it would add it to the queue. > > > > We may want to use the Queue module here instead of a list; the way the > > program is described now sounds like the server is busy-spinning when it > > looks for new things to do. The thing that makes busy-spinning slightly > > not-nice is that it consumes CPU regardless if the system's doing anything > > or not. > > > > But a more serious problem than busy-waiting is one of thread-safety: the > > object that's used to communicate between two threads --- a shared list > > --- might be unreliable if the list methods aren't thread-safe. And I'm > > not certain that all the list methods are thread-safe. > > > > That is, the problem with mutual exclusion may have just been pushed up > > the program's structure, from the MySQL queries up to the shared queue > > list access. *grin* > > > > > > The synchronized Queue described in: > > > > http://www.python.org/doc/lib/module-Queue.html > > > > is designed to be a reliable communication medium between threads, and I > > strongly recommend you look at it, especially because you've seen > > first-hand the weird things that can happen with threads. *grin* > > > > > > Here's a small example that shows what a different Queue can make: > > > > ############################################ > > from threading import Thread > > > > class Server: > > def __init__(self): > > self.queue = [] > > > > def acceptJob(self, query): > > self.queue.append((query,)) > > > > def shutdownOnIdle(self): > > self.queue.append("QUIT!") > > > > def jobLoop(self): > > while True: > > print "looping" > > if len(self.queue) > 0: > > nextJob = self.queue.pop(0) > > if nextJob == "QUIT!": > > return > > print "I should do", nextJob > > > > def startServer(self): > > Thread(target=self.jobLoop).start() > > > > if __name__ == '__main__': > > server = Server() > > server.startServer() > > server.acceptJob("a") > > server.acceptJob("b") > > server.acceptJob("c") > > server.shutdownOnIdle() > > ############################################ > > > > > > Running this will show just how much work a busy-waiting thread does. > > > > > > But if we change a few methods to use Queues instead of lists: > > > > ###### > > from threading import Thread > > from Queue import Queue > > > > class Server: > > def __init__(self): > > self.queue = Queue() > > > > def acceptJob(self, query): > > self.queue.put((query,)) > > > > def shutdownOnIdle(self): > > self.queue.put("QUIT!") > > > > def jobLoop(self): > > while True: > > print "looping" > > nextJob = self.queue.get() > > if nextJob == "QUIT!": > > return > > print "I should do", nextJob > > > > def startServer(self): > > Thread(target=self.jobLoop).start() > > > > if __name__ == '__main__': > > server = Server() > > server.startServer() > > server.acceptJob("a") > > server.acceptJob("b") > > server.acceptJob("c") > > server.shutdownOnIdle() > > ###### > > > > and compare the output of this to the original implementation, it should > > be clearer why Queues are cool. *grin* > > > > > > Does this make sense? I hope this helps! > > > > > From marilyn at deliberate.com Fri Jan 20 20:02:54 2006 From: marilyn at deliberate.com (Marilyn Davis) Date: Fri, 20 Jan 2006 11:02:54 -0800 (PST) Subject: [Tutor] Quoting trouble Message-ID: Dear Tutors, I'm having a problem and going around in circles. I'm on Python 2.4.1. This odd address line comes in email: >>> line = '''"ma >> \"marilyn at maildance.com\"" ''' It makes sense to me, and to the MTA. I want to use it to create a variable: >>> exec('h_to = %s' % line) Traceback (most recent call last): File "", line 1, in ? File "", line 1 h_to = "ma >> "marilyn at maildance.com"" ^ SyntaxError: invalid syntax So, how do I keep the \" in there? I've tried a bunch of things but can't find anything that works. Heeeeeeeeeeelp. Please. Thank you. Marilyn Davis From dyoo at hkn.eecs.berkeley.edu Fri Jan 20 20:34:42 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 20 Jan 2006 11:34:42 -0800 (PST) Subject: [Tutor] Starbucks does not use two-phase commit In-Reply-To: <61d0e2b40601200913q6d3b3ff5s471a618dc895b82@mail.gmail.com> Message-ID: On Fri, 20 Jan 2006, Bernard Lebel wrote: > So have written a little test script. The fact is that I want to be able > to manage the same queue from separate threads. Below is an example of > what my real program is doing: Hi Bernard, One problem is that there's a single outputQueue being presented to get results back from the Server. A different approach is to use a lot of outputQueues. *grin* The idea is that when we send a job submission, we immediately get back a "ticket". We can then use this ticket to claim() our result. Each ticket is unique to a job submission, so we shouldn't see any bleeding going on between clients. Here's some code that implements this idea. It's a little complex, so you may want to read through it slowly: ################################################ from threading import Thread from Queue import Queue class Ticket: """A small token that we can use to claim our result.""" def __init__(self, q): self.q = q self.result = None self.done = False def claim(self): if not self.done: self.result = self.q.get() self.done = True return self.result class Server: _QUIT_JOB = ['Quit!'] def __init__(self): """A queue will contain 2-tuples of (job, outputQueue) elements.""" self.queue = Queue() def startServer(self): """Brings the server online.""" Thread(target=self._jobLoop).start() def schedule(self, job): """Schedules a job to be done and returns a ticket that the client can use later to claim the result of the job.""" outputQueue = Queue() self.queue.put((job, outputQueue)) return Ticket(outputQueue) def scheduleShutdown(self): """Add a 'job' that shuts the system down.""" self.queue.put((Server._QUIT_JOB, None)) def _jobLoop(self): """Continue looping through tasks.""" while True: print "Looping..." (nextJob, outputQueue) = self.queue.get() if nextJob is Server._QUIT_JOB: return returnValue = self._doJob(nextJob) outputQueue.put(returnValue) def _doJob(self, job): print "I'm doing", job return job + job ## something to show that we're doing something def separateCaller(server): for i in range(1000, 1004 + 1): print "--Separate caller asks %d" % i ticket = server.schedule(str(i)) print "--Separate caller got %s" % ticket.claim() if __name__ == '__main__': server = Server() server.startServer() Thread(target=separateCaller, args=(server,)).start() result1 = server.schedule("1") print "result1: %s" % result1.claim() result2 = server.schedule("2") print "result2: %s" % result2.claim() result3 = server.schedule("3") print "result3: %s" % result3.claim() server.scheduleShutdown() ############################################################# Play around with this a bit and see if it makes sense to you. You might also be interested in the amusing article "Starbucks Does Not Use Two-Phase Commit": http://www.eaipatterns.com/ramblings/18_starbucks.html as it touches on concepts in the code. If you have more questions, please feel free to ask! From kent37 at tds.net Fri Jan 20 20:45:11 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 20 Jan 2006 14:45:11 -0500 Subject: [Tutor] Quoting trouble In-Reply-To: References: Message-ID: <43D13DC7.9040602@tds.net> Marilyn Davis wrote: > Dear Tutors, > > I'm having a problem and going around in circles. I'm on Python 2.4.1. > > This odd address line comes in email: > > >>>>line = '''"ma >> \"marilyn at maildance.com\"" ''' > > > It makes sense to me, and to the MTA. I want to use it to create a > variable: > > >>>>exec('h_to = %s' % line) > > Traceback (most recent call last): > File "", line 1, in ? > File "", line 1 > h_to = "ma >> "marilyn at maildance.com"" > ^ > SyntaxError: invalid syntax > > So, how do I keep the \" in there? Why are you using exec? What's wrong with h_to = line ?? If you really need the exec then you need to put some quotes in there somewhere, either exec('h_to = '''%s''' ' % line) or exec('h_to = %s' % repr(line)) Kent From marilyn at deliberate.com Fri Jan 20 22:50:36 2006 From: marilyn at deliberate.com (Marilyn Davis) Date: Fri, 20 Jan 2006 13:50:36 -0800 (PST) Subject: [Tutor] Quoting trouble In-Reply-To: <43D13DC7.9040602@tds.net> Message-ID: On Fri, 20 Jan 2006, Kent Johnson wrote: Thank you so much Kent. This is *very* helpful. > Marilyn Davis wrote: > > Dear Tutors, > > > > I'm having a problem and going around in circles. I'm on Python 2.4.1. > > > > This odd address line comes in email: > > > > > >>>>line = '''"ma >> \"marilyn at maildance.com\"" ''' > > > > > > It makes sense to me, and to the MTA. I want to use it to create a > > variable: > > > > > >>>>exec('h_to = %s' % line) > > > > Traceback (most recent call last): > > File "", line 1, in ? > > File "", line 1 > > h_to = "ma >> "marilyn at maildance.com"" > > ^ > > SyntaxError: invalid syntax > > > > So, how do I keep the \" in there? > > Why are you using exec? What's wrong with > h_to = line > ?? Explanation below. > > If you really need the exec then you need to put some quotes in there > somewhere, either > exec('h_to = '''%s''' ' % line) >>> exec('h_to = '''%s''' % line ') ... It seems to want more. > or > exec('h_to = %s' % repr(line)) This one does! >>> exec('h_to = %s' % repr(line)) >>> h_to '"ma >> "marilyn at maildance.com"" ' Why I'm using exec: I'm using exec so that I have a flexible scheme for collecting headers. Maybe you have a better suggestion? I have a dictionary that starts: significant_headers = { 'Cc: ':None, 'CC: ':None, 'From: ':None, 'Return-path: ':None, 'Sender: ':None, 'Subject: ':None, 'To: ':None} and heads_to_find = significant_headers.keys() So I collect the header texts into the dictionary items: for each in heads_to_find: if not significant_headers[each] \ and text.startswith(each): significant_headers[each] = text[len(each):].strip().replace('"','\\"').replace('\n',' ') break And then later, I make variables that match the variables that exim, my MTA, uses. For each header in the message exim provides a $h_to, $h_from, etc. I like my variable names to match exim's as much as possible: for each in significant_headers.keys(): this = '''self.h_%s = "%s"''' % \ (each[:-2].lower().replace('-','_'), repr(significant_headers[each])) exec(this) If I decide that I need to collect another header, I can just add it to my dicitonary. And now, with your help, I don't get any exceptions ... so far. But, if there's another way to do this, I'd appreciate any improvement. Thank you so much. Marilyn > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- From python at venix.com Sat Jan 21 00:13:51 2006 From: python at venix.com (Python) Date: Fri, 20 Jan 2006 18:13:51 -0500 Subject: [Tutor] Quoting trouble In-Reply-To: References: Message-ID: <1137798831.15004.800.camel@www.venix.com> On Fri, 2006-01-20 at 13:50 -0800, Marilyn Davis wrote: > for each in significant_headers.keys(): > this = '''self.h_%s = "%s"''' % \ > (each[:-2].lower().replace('-','_'), > repr(significant_headers[each])) > exec(this) So you are using exec to process an assignment statement. The setattr builtin function will do what you want. http://docs.python.org/lib/built-in-funcs.html#l2h-64 so your code could wind up looking something like: setattr( self, 'h_' + each[:-2].lower().replace('-','_'), significant_headers[each] ) Looking at that code, you can pull the key and value from significant_headers in the for statement. That is: for key,val in significant_headers.items(): setattr( self, 'h_' + key[:-2].lower().replace('-','_'), val ) Now the line that actually determines the attribute name looks pretty ugly. I would recommend writing a function to replace that operation with an understandable function name (perhaps key2name). That would result in: setattr(self, key2name(key), val) Hope this helps. The ease with which Python allows you to attach names to values is one of the great features of the language. -- Lloyd Kvam Venix Corp From marilyn at deliberate.com Sat Jan 21 00:45:18 2006 From: marilyn at deliberate.com (Marilyn Davis) Date: Fri, 20 Jan 2006 15:45:18 -0800 (PST) Subject: [Tutor] Quoting trouble In-Reply-To: <1137798831.15004.800.camel@www.venix.com> Message-ID: On Fri, 20 Jan 2006, Python wrote: > On Fri, 2006-01-20 at 13:50 -0800, Marilyn Davis wrote: > > for each in significant_headers.keys(): > > this = '''self.h_%s = "%s"''' % \ > > (each[:-2].lower().replace('-','_'), > > repr(significant_headers[each])) > > exec(this) > > So you are using exec to process an assignment statement. The setattr > builtin function will do what you want. > > http://docs.python.org/lib/built-in-funcs.html#l2h-64 > > so your code could wind up looking something like: > > setattr( self, > 'h_' + each[:-2].lower().replace('-','_'), > significant_headers[each] > ) > > Looking at that code, you can pull the key and value from > significant_headers in the for statement. That is: > > for key,val in significant_headers.items(): > setattr( self, > 'h_' + key[:-2].lower().replace('-','_'), > val > ) > > Now the line that actually determines the attribute name looks pretty > ugly. I would recommend writing a function to replace that operation > with an understandable function name (perhaps key2name). That would > result in: > setattr(self, key2name(key), val) Very nice indeed! > > > Hope this helps. The ease with which Python allows you to attach names > to values is one of the great features of the language. Yes. Thank you so much. I'll fix it and I'm glad to have it in my bag of tricks. Marilyn > > -- From kent37 at tds.net Sat Jan 21 02:36:52 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 20 Jan 2006 20:36:52 -0500 Subject: [Tutor] Quoting trouble In-Reply-To: References: Message-ID: <43D19034.8040002@tds.net> Marilyn Davis wrote: > significant_headers[each] = text[len(each):].strip().replace('"','\\"').replace('\n',' ') This looks like you are trying to make an escaped string, with literal backslashes. You might prefer using the 'string_escape' codec: >>> '\n'.encode('string_escape') '\\n' Kent From edgar.antonio.rv at gmail.com Sat Jan 21 03:20:29 2006 From: edgar.antonio.rv at gmail.com (=?ISO-8859-1?Q?Edgar_Antonio_Rodr=EDguez_Velazco?=) Date: Fri, 20 Jan 2006 20:20:29 -0600 Subject: [Tutor] Doubt with classes Message-ID: <9378d12c0601201820nce4b1c0w1fad545f33976a82@mail.gmail.com> Hi everybody, I've been reading the chapter of classes of Byte of Python by Swaroop. There's an example with classes (11.4) that is below: ############################################# class Person: '''Represents a person.''' population = 0 def __init__(self, name): '''Initializes the person's data.''' self.name = name print '(Initializing %s)' % self.name # When this person is created, he/she # adds to the population Person.population += 1 def __del__(self): '''I am dying.''' print '%s says bye.' % self.name Person.population -= 1 if Person.population == 0: print 'I am the last one.' else: print 'There are still %d people left.' % Person.population def sayHi(self): '''Greeting by the person. Really, that's all it does.''' print 'Hi, my name is %s.' % self.name def howMany(self): '''Prints the current population.''' if Person.population == 1: print 'I am the only person here.' else: print 'We have %d persons here.' % Person.population swaroop = Person('Swaroop') swaroop.sayHi() swaroop.howMany() kalam = Person('Abdul Kalam') kalam.sayHi() kalam.howMany() swaroop.sayHi() swaroop.howMany() ################################# EXAMPLE'S OUTPUT (Output shown in the example) $ python objvar.py (Initializing Swaroop) Hi, my name is Swaroop. I am the only person here. (Initializing Abdul Kalam) Hi, my name is Abdul Kalam. We have 2 persons here. Hi, my name is Swaroop. We have 2 persons here. Abdul Kalam says bye. There are still 1 people left. Swaroop says bye. I am the last one. ############################## MY OUTPUT (Initializing Swaroop) Hi, my name is Swaroop. I am the only person here. (Initializing Abdul Kalam) Hi, my name is Abdul Kalam. We have 2 persons here. Hi, my name is Swaroop. We have 2 persons here. ################################## I have runned the script in both Linux and Windows and got the same result. Could you explain me what's wrong with this??? -- Edgar A. Rodriguez -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060120/c527657b/attachment.html From kent37 at tds.net Sat Jan 21 03:45:04 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 20 Jan 2006 21:45:04 -0500 Subject: [Tutor] Doubt with classes In-Reply-To: <9378d12c0601201820nce4b1c0w1fad545f33976a82@mail.gmail.com> References: <9378d12c0601201820nce4b1c0w1fad545f33976a82@mail.gmail.com> Message-ID: <43D1A030.9000506@tds.net> Edgar Antonio Rodr?guez Velazco wrote: > Hi everybody, > I've been reading the chapter of classes of Byte of Python by Swaroop. > There's an example with classes (11.4) that is below: The example is depending on Person.__del__() being called on swaroop and kalam when the intepreter exits. The Python Language Reference documentation on __del__() says, "It is not guaranteed that __del__() methods are called for objects that still exist when the interpreter exits." So this program is relying on behaviour that may change between different versions of Python. Try adding del swaroop del kalam to the end of the program, this should force the __del__() method to be called (at least in CPython, in Jython it still may not be called). Kent > > ############################################# > class Person: > '''Represents a person.''' > population = 0 > > def __init__(self, name): > '''Initializes the person's data.''' > self.name = name > print '(Initializing %s)' % self.name > > # When this person is created, he/she > # adds to the population > Person.population += 1 > > def __del__(self): > '''I am dying.''' > print '%s says bye.' % self.name > > Person.population -= 1 > > if Person.population == 0: > print 'I am the last one.' > else: > print 'There are still %d people left.' % Person.population > > def sayHi (self): > '''Greeting by the person. > > Really, that's all it does.''' > print 'Hi, my name is %s.' % self.name > > def howMany(self): > '''Prints the current population.''' > if Person.population == 1: > print 'I am the only person here.' > else: > print 'We have %d persons here.' % Person.population > > swaroop = Person('Swaroop') > swaroop.sayHi() > swaroop.howMany() > > kalam = Person('Abdul Kalam') > kalam.sayHi() > kalam.howMany() > > swaroop.sayHi() > swaroop.howMany() > > ################################# > EXAMPLE'S OUTPUT (Output shown in the example) > > $ python objvar.py > (Initializing Swaroop) > Hi, my name is Swaroop. > I am the only person here. > (Initializing Abdul Kalam) > Hi, my name is Abdul Kalam. > We have 2 persons here. > Hi, my name is Swaroop. > We have 2 persons here. > Abdul Kalam says bye. > There are still 1 people left. > Swaroop says bye. > I am the last one. > ############################## > MY OUTPUT > > (Initializing Swaroop) > Hi, my name is Swaroop. > I am the only person here. > (Initializing Abdul Kalam) > Hi, my name is Abdul Kalam. > We have 2 persons here. > Hi, my name is Swaroop. > We have 2 persons here. > ################################## > > I have runned the script in both Linux and Windows and got the same > result. Could you explain me what's wrong with this??? > > -- > Edgar A. Rodriguez > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From neal at bcn.boulder.co.us Sat Jan 21 05:01:03 2006 From: neal at bcn.boulder.co.us (Neal McBurnett) Date: Fri, 20 Jan 2006 21:01:03 -0700 (MST) Subject: [Tutor] python-based system programming and admin? Message-ID: <20060121040103.AD30C8EF5@lock.gotdns.org> I'm an experienced linux guy, with lots of python interest and some python experience. I'm helping a colleague develop software to run on our linux server. He has python skill, but doesn't know the shell or linux very well at all. I'd like to give him a secure, safe, flexible development environment on the serve, (which does audio streaming and other fun things). At the moment, he has an account and can connect from his mac via ssh, and copy files back and forth (ftp-like stuff - I forget which ssh client). But he doesn't want to log in to a bash shell and learn a whole new way to do things. But he does want to run programs. Editing python scripts spawned by cron is one of the goals. But developing them by waiting for cron to fire and send the output via email is pretty painful.... The server currently doesn't need to run a web server, and I'm reluctant to introduce new services that have much security risk associated with them, but something like that seems like a possibility. One idea that just popped in my brain is to give him a python login shell on linux - any advice on how to do that? Other possibilities, I guess: - An https-based web server with and mod-python, somehow configured so that his jobs run as him. - a pure-python server (via twisted?) running as him - moinmoin or the like - zope or plone (not sounding very simple any more, but I've done a bit of this ....) What would be the safest, simplest solution that was adequate for providing a reasonable development environment? Any ideas I haven't thought of yet? Cheers, Neal McBurnett http://bcn.boulder.co.us/~neal/ Signed and/or sealed mail encouraged. GPG/PGP Keyid: 2C9EBA60 From bradly.mcconnell at gmail.com Sat Jan 21 07:45:07 2006 From: bradly.mcconnell at gmail.com (Bradly McConnell) Date: Sat, 21 Jan 2006 01:45:07 -0500 Subject: [Tutor] Is this overkill? Message-ID: <80463c260601202245s149fd654w929cac0ab5f62b4@mail.gmail.com> Greetings all: I'm new to Python, and have come across and exercise that basically counts to 100. The idea is to accept user input for an initial number, and then let the user add additional numbers. I wanted to give feedback if a number selected would bring the total above 100, so the user would select a lower number. It looks like I have it working, but it doesn't seem very efficient. I would like any hints, help, or comments that you can provide. Below is what I have so far. number = input("Please enter a number: ") while number != 100: additional_number = input("Please enter an additional number: ") if additional_number + number > 100: lower_number = input("please enter a lower number: ") if lower_number + number > 100: lower_number = input("Lower!") else: number = lower_number + number elif additional_number + number < 100: number = additional_number + number else: continue print "Done", number Brad From lemeia at bigpond.com Sat Jan 21 07:46:41 2006 From: lemeia at bigpond.com (lemeia) Date: Sat, 21 Jan 2006 17:46:41 +1100 Subject: [Tutor] unittest and private methods Message-ID: <10374416.1137826001395.JavaMail.root@web01ps> kent wrote: > > I currently have a class where I have quite a few private methods. > > One > of these methods is a small general utility that extracts characters > from provided text up until it reaches a delimiter. Something like > extractTo(self, text, delimiter). > > > > It's not a relevant interface to the class, just a utility for the > class' public methods, which is why I've made it private. That seems to > be a logical decision to me. > > Yes, that is good reasoning. When you say it is private, do you mean the > name starts with two underscores? > Yes - it is __extractTo(self, text, delimiter) > > > However, the public methods within the class that call it currently > only do so to extract numeric events from the text. extractTo is a > little more generalised than that and so I decided that I would use > unittest to build test cases for the extractTo method and exercise it to > its fullest in case the class requires its extended functionality in the > future. > > > > You'll probably see what my problem is. I can't exercise this method > directly from an external test case as the method is not part of the > class' public interface. If I call a method in the interface that > currently utilises this private method I'm not testing the method as > fully as I would like. > > I'm not sure I understand this part. You mean the private methods have > capabilities that can't currently be exercised through the public > interface? That smells of "Speculative Generality" - writing code > because you think you might need it later. If that is the case the best > answer might be to rip it out and wait until you need it. > > > I like the term Speculative Generality - never heard that before. If the method was already extremely complicated I would agree that you should only alter when needed. However, this method is simpler in design and I don't see the harm in generalising in this particular case. Once I'd made the decision to generalise it I consequently saw several worthwhile refactoring possibilities in my class, which I shall probably exercise a little later. > Now I can build arbitrary interfaces into my class just for testing > this method but that sounds like a messy way to maintain a program. > Additionally, I could make this method public, but that also seems like > an unsatisfactory solution. > > > > The example isn't so important to my question, but I wanted to give > some context before asking...... > > > > Is there a way to specifically target and unit test private methods > > in > a class via unittest without testing them through the class' public > interface? > > Python's notion of privacy is pretty weak. I would have no problem with > a unit test that called single-underscore methods in the class under > test. Unit test purists object to this, saying a class should only be > tested through its public interface, but "practicality beats purity" in > my mind. > > Rereading your mail another possibility comes to mind. It sounds like > extractTo() is a general-purpose function that is used for a specific > purpose by the module you are testing. Why not extract extractTo to a > utility module? Then you can test it as much as you like in the unit > tests for the utility and you can reuse it in other code if the need > arises. Almost all of my projects have 'util' packages containing > collections of miscellaneous useful stuff. The utils have their own unit > tests and get included as needed in other modules and projects. > > This makes sense to me and I hadn't thought of that in all honesty. I get so involved in object orientated design, I sometimes forget about the convenience of a few general functions to "help out". Would I lose my OO membership card though? I think I might stick to the public interface testing wherever possible and I have done so with other private methods in my class. This particular one just seemed to benefit from direct testing. I'm really enjoying Python. I don't like the "sentence structure" quite as much as Smalltalk (ie I like anObject actOn: a untilYouSee: b), but there's something quite friendly about its syntax all the same. I find it much faster to do things in Python even over Visual Basic. I really like developing using OO and so far, Python has been the easiest to adopt (besides Smalltalk perhaps). For some reason I struggled with OO in C++ when I looked into it and Java always seemed to be a big red stop sign for me (not sure why). Patrick From alan.gauld at freenet.co.uk Sat Jan 21 10:21:36 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 21 Jan 2006 09:21:36 -0000 Subject: [Tutor] Doubt with classes References: <9378d12c0601201820nce4b1c0w1fad545f33976a82@mail.gmail.com> Message-ID: <004001c61e6c$142925a0$0b01a8c0@xp> swaroop = Person('Swaroop') swaroop.sayHi() swaroop.howMany() kalam = Person('Abdul Kalam') kalam.sayHi() kalam.howMany() swaroop.sayHi() swaroop.howMany() ################################# MY OUTPUT (Initializing Swaroop) Hi, my name is Swaroop. I am the only person here. (Initializing Abdul Kalam) Hi, my name is Abdul Kalam. We have 2 persons here. Hi, my name is Swaroop. We have 2 persons here. ################################## > I have runned the script in both Linux and Windows and got the same > result. > Could you explain me what's wrong with this??? The script never calls del() so it is relying on Garbage Collection to kill the objects. How are you running the script? From a command line in the OS or by importing it into a Python session? If you only import it then you will get the result you see. You will need to run the script by 1) Double clicking in a File broewsrer(like Windows explorer) or 2) From a console window typing "ython scripy.py" Alternarively, add del(swaroop) del(kalam) to the end of your script... HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Sat Jan 21 10:32:47 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 21 Jan 2006 09:32:47 -0000 Subject: [Tutor] Is this overkill? References: <80463c260601202245s149fd654w929cac0ab5f62b4@mail.gmail.com> Message-ID: <004801c61e6d$a4118d00$0b01a8c0@xp> number = input("Please enter a number: ") while number != 100: additional_number = input("Please enter an additional number: ") if additional_number + number > 100: lower_number = input("please enter a lower number: ") you can just 'continue' here since the while loop asks for a new number anyhow. It xchanges the behaviour salightly in that it never allows a number that sums to more than 100 whereas you allow only two attempts. if lower_number + number > 100: lower_number = input("Lower!") else: number = lower_number + number elif additional_number + number < 100: so the lines above become unnecessary. number = additional_number + number else: continue you don't need the last else/continue, thats pythons standard behaviour. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Sat Jan 21 10:37:54 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 21 Jan 2006 09:37:54 -0000 Subject: [Tutor] unittest and private methods References: <10374416.1137826001395.JavaMail.root@web01ps> Message-ID: <004c01c61e6e$5b347c40$0b01a8c0@xp> > I'm really enjoying Python. I don't like the "sentence structure" quite > as much as Smalltalk (ie I like anObject actOn: a untilYouSee: b), Have you looked at Objective C? It uses Smalltalk style messaging, but in a C language framework. > I find it much faster to do things in Python even over Visual Basic. For sure, other than GUI design. > some reason I struggled with OO in C++ when I looked into it C++ was fairly easy up until v2 but then the ISO process added so many twisted features that it just became unusable IMHO. > and Java always seemed to be a big red stop sign for me You are not alone! Java ranks alongside COBOL as one of my least favourite languages and unfortunately I have to work with both! (Fortunately not too often) Alan G From kent37 at tds.net Sat Jan 21 13:13:12 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 21 Jan 2006 07:13:12 -0500 Subject: [Tutor] unittest and private methods In-Reply-To: <10374416.1137826001395.JavaMail.root@web01ps> References: <10374416.1137826001395.JavaMail.root@web01ps> Message-ID: <43D22558.2070508@tds.net> lemeia wrote: > kent wrote: >>Rereading your mail another possibility comes to mind. It sounds like >>extractTo() is a general-purpose function that is used for a specific >>purpose by the module you are testing. Why not extract extractTo to a >>utility module? Then you can test it as much as you like in the unit >>tests for the utility and you can reuse it in other code if the need >>arises. Almost all of my projects have 'util' packages containing >>collections of miscellaneous useful stuff. The utils have their own unit >>tests and get included as needed in other modules and projects. >> >> This makes sense to me and I hadn't thought of that in all honesty. >> I get so involved in object orientated design, I sometimes forget about the convenience of a few general functions to "help out". Would I lose my OO membership card though? No, not at all, in fact you jeopardize your OO membership if you use it where it is not needed ;) But seriously, one of the strengths of Python is that I can write OO code where appropriate, I can write procedural code when I don't need the extra power of classes, and I can write straight-line code when my needs are very simple, I can write in a functional style too. I can even mix the four styles in a single module if I want to. So go ahead and make a utility module, or a public helper function at global scope in the same module as your class. Kent From bradly.mcconnell at gmail.com Sat Jan 21 16:09:42 2006 From: bradly.mcconnell at gmail.com (Bradly McConnell) Date: Sat, 21 Jan 2006 10:09:42 -0500 Subject: [Tutor] Is this overkill? In-Reply-To: <004801c61e6d$a4118d00$0b01a8c0@xp> References: <80463c260601202245s149fd654w929cac0ab5f62b4@mail.gmail.com> <004801c61e6d$a4118d00$0b01a8c0@xp> Message-ID: <80463c260601210709j23ec57c8s1afe9f9baa3c7c4c@mail.gmail.com> On 1/21/06, Alan Gauld wrote: > number = input("Please enter a number: ") > while number != 100: > additional_number = input("Please enter an additional number: ") > if additional_number + number > 100: > lower_number = input("please enter a lower number: ") > > you can just 'continue' here since the while loop asks for a new > number anyhow. It xchanges the behaviour salightly in that it never > allows a number that sums to more than 100 whereas you allow > only two attempts. Not sure where I went wrong, but at this point, I cannot get the count to reach 100 unless I use something like 60 and 40 for the number a additional_number inputs. It seems that my variables are being overwritten, but the "previous" additional number doesn't get added to number before it happens. This appears in both my original, and with the modifications that you (Alan) suggested. I think I worked on it a bit too much last night, and lost track of what I tried and didn't try so I think I'll take a look through the areas on loops and conditional statements again this evening and start over "fresh". Thanks for the help. Brad From benvinger at yahoo.co.uk Sat Jan 21 17:29:51 2006 From: benvinger at yahoo.co.uk (Ben Vinger) Date: Sat, 21 Jan 2006 16:29:51 +0000 (GMT) Subject: [Tutor] a class knowing its self In-Reply-To: <43CF7357.6090009@hartter.com> Message-ID: <20060121162951.75009.qmail@web25801.mail.ukl.yahoo.com> Yes, you are right, - Shuying Wang's suggestion fixed the immediate problem, but there is still someting wrong with my code - maybe I'll ask about it again later. --- Ewald Ertl wrote: > > > Have a more precisely look at your code. > s.getName() does just return, what you have put into > the class with setName(). ( Reassignment of a > variable to > something different what you intended ). ___________________________________________________________ NEW Yahoo! Cars - sell your car and browse thousands of new and used cars online! http://uk.cars.yahoo.com/ From benvinger at yahoo.co.uk Sat Jan 21 17:34:45 2006 From: benvinger at yahoo.co.uk (Ben Vinger) Date: Sat, 21 Jan 2006 16:34:45 +0000 (GMT) Subject: [Tutor] passwords in scripts Message-ID: <20060121163445.89638.qmail@web25807.mail.ukl.yahoo.com> Hello I've written a couple of scripts that check log files on our WIndows and Unix servers. These scripts have plain text passwords in them, so anyone who can access the filesystem of the Windows server that runs the scripts can discover the passwords of the servers. Is there a way to hide/encrypt these passwords? Or can the scripts be converted to compiled code in order for the passwords to be hidden? Thanks Ben ___________________________________________________________ Win a BlackBerry device from O2 with Yahoo!. Enter now. http://www.yahoo.co.uk/blackberry From python at venix.com Sat Jan 21 19:24:36 2006 From: python at venix.com (Python) Date: Sat, 21 Jan 2006 13:24:36 -0500 Subject: [Tutor] Is this overkill? In-Reply-To: <80463c260601210709j23ec57c8s1afe9f9baa3c7c4c@mail.gmail.com> References: <80463c260601202245s149fd654w929cac0ab5f62b4@mail.gmail.com> <004801c61e6d$a4118d00$0b01a8c0@xp> <80463c260601210709j23ec57c8s1afe9f9baa3c7c4c@mail.gmail.com> Message-ID: <1137867876.15004.819.camel@www.venix.com> On Sat, 2006-01-21 at 10:09 -0500, Bradly McConnell wrote: > On 1/21/06, Alan Gauld wrote: > > number = input("Please enter a number: ") > > while number != 100: > > additional_number = input("Please enter an additional number: ") > > if additional_number + number > 100: > > lower_number = input("please enter a lower number: ") > > > > you can just 'continue' here since the while loop asks for a new > > number anyhow. It xchanges the behaviour salightly in that it never > > allows a number that sums to more than 100 whereas you allow > > only two attempts. > > Not sure where I went wrong, but at this point, I cannot get the count > to reach 100 unless I use something like 60 and 40 for the number a > additional_number inputs. It seems that my variables are being > overwritten, but the "previous" additional number doesn't get added to > number before it happens. This appears in both my original, and with > the modifications that you (Alan) suggested. One approach that might help simplify things would be to use a variable for the input prompt. Changing as little as possible: prompt = "Please enter an additional number: " while number != 100: additional_number = input(prompt) This helps remove the need for additional input requests and should let you keep the while loop logic reasonably simple. Do this in conjunction with Alan's advice. I think we are both trying to push you in the same direction. > > I think I worked on it a bit too much last night, and lost track of > what I tried and didn't try so I think I'll take a look through the > areas on loops and conditional statements again this evening and start > over "fresh". > > Thanks for the help. > > Brad > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From python-tutor at toddmaynard.com Sat Jan 21 19:57:43 2006 From: python-tutor at toddmaynard.com (Todd Maynard) Date: Sat, 21 Jan 2006 13:57:43 -0500 Subject: [Tutor] Starbucks does not use two-phase commit In-Reply-To: References: Message-ID: <200601211357.43834.python-tutor@toddmaynard.com> Danny, I want to thank you for ruining my plans for a relaxing Saturday morning. As a thread newbie I killed several hours playing around with your code. One thing I noticed is that sometimes the program would hang, which I figured was the Queue code blocking in the Ticket claim function. I used exception handling to deal with that situation cleanly. I then decided that it wasn't very nice of Starbucks to close after accepting my order without giving me my Latte, so I changed that part of the code to: def schedule(self,job): """Schedules a job and returns a "ticket" the user can later use to get the result.""" if self.acceptNew == True: outputQueue=Queue() self.queue.put((job,outputQueue)) return Ticket(outputQueue) else: print "Server not accepting any new requests." return None def scheduleShutdown(self): """Add a job that shuts the system down.""" print "Telling server to shut down" self.queue.put((Server._QUIT_NICELY,None)) def _jobLoop(self): """Continue looping through tasks.""" while True: print "Looping ... " (nextJob, outputQueue) = self.queue.get() if nextJob is server._QUIT_NOW: return if nextJob is server._QUIT_NICELY: self.acceptNew = False self.queue.put((Server._QUIT_NOW,None)) else: returnValue=self._doJob(nextJob) outputQueue.put(returnValue) I am 99.44% sure that this is thread safe, reasoning being: setting the acceptNew to False and adding the QUIT_NOW happens in the same thread so it is impossible for another job to get scheduled after the QUIT_NOW - so no thread will end up hanging... However, I would sleep a little better if you could reassure me that I am right, and would sleep even better if you could give me a method to test this. This kinda stuff looks tricky to test with standard unittest methodology.... Thanks again for the enligntenment all you guys bring to this awesome language. My bastardized code is below for reference. --Todd Maynard < python-tutor at toddmaynard.com > [It is] best to confuse only one issue at a time. -- K&R ************************************** from threading import Thread from Queue import Queue,Empty class Ticket(object): """A small token we can use to claim our result.""" def __init__(self, q): self.q = q self.result = None self.done=False def claim(self): if not self.done: try: self.result=self.q.get(True,5) self.done=True except Empty: print "We lost the server!" self.result=None return self.result class Server(object): _QUIT_NOW=['Quit!'] _QUIT_NICELY=['Quit Nicely'] def __init__(self): """A queue will contain 2-tuples of (job, outputQueue) elements.""" self.queue=Queue() self.acceptNew=True def startServer(self): """Brings the server online.""" Thread(target=self._jobLoop).start() def schedule(self,job): """Schedules a job and returns a "ticket" the user can later use to get the result.""" if self.acceptNew == True: outputQueue=Queue() self.queue.put((job,outputQueue)) return Ticket(outputQueue) else: print "Server not accepting any new requests." return None def scheduleShutdown(self): """Add a job that shuts the system down.""" print "Telling server to shut down" self.queue.put((Server._QUIT_NICELY,None)) def _jobLoop(self): """Continue looping through tasks.""" while True: print "Looping ... " (nextJob, outputQueue) = self.queue.get() if nextJob is server._QUIT_NOW: return if nextJob is server._QUIT_NICELY: self.acceptNew = False self.queue.put((Server._QUIT_NOW,None)) else: returnValue=self._doJob(nextJob) outputQueue.put(returnValue) def _doJob(self,job): print "I'm doing " , job return job + job #Something to show that we are doing something def separateCaller(server): for i in range(1000,1004+1): print " -- separateCaller asks %d" % i ticket = server.schedule(str(i)) if ticket: print " -- separateCaller got %s" % ticket.claim() else: print " -- separateCaller couldn't get a ticket." if __name__=="__main__": server = Server() server.startServer() Thread(target=separateCaller, args=(server,)).start() result1=server.schedule("1") result2=server.schedule("2") result3=server.schedule("3") if result3: print "result3: %s" % result3.claim() else: print "result3: Couldn't get a ticket" if result2: print "result2: %s" % result2.claim() else: print "result2: Couldn't get a ticket" if result1: print "result1: %s" % result1.claim() else: print "result1: Couldn't get a ticket" server.scheduleShutdown() From victor at grupocdm.com Sun Jan 22 00:57:48 2006 From: victor at grupocdm.com (Victor Bouffier) Date: Sat, 21 Jan 2006 17:57:48 -0600 Subject: [Tutor] [Re] Fwd: Strings backwards In-Reply-To: <43D0097E.3070609@gmail.com> References: <1137696701.2845.20.camel@elrond> <43D0097E.3070609@gmail.com> Message-ID: <1137887868.4424.6.camel@elrond> On Thu, 2006-01-19 at 16:49 -0500, Orri Ganel wrote: > Victor Bouffier wrote: > > >I had to do the string-to-list-then-reverse-string-then-back-to-string > >process myself before knowing about this marvelous operand. > >It works on tuples (all immutable objects) too: > > > [SNIP] > > Not all immutable objects, just those that define __getslice__ > (basically, those that use indexes: sequences). Ints, for example, are > immutable and don't work: > > >>> 12[::-1] > > Traceback (most recent call last): > File "", line 1, in -toplevel- > 12[::-1] > TypeError: unsubscriptable object > > > - Orri > I see. Thanks for the correction Orri Victor From mail.roma1 at gmail.com Sun Jan 22 03:16:43 2006 From: mail.roma1 at gmail.com (Ivan Furone) Date: Sun, 22 Jan 2006 03:16:43 +0100 Subject: [Tutor] passwords in scripts In-Reply-To: <20060121163445.89638.qmail@web25807.mail.ukl.yahoo.com> References: <20060121163445.89638.qmail@web25807.mail.ukl.yahoo.com> Message-ID: <6122a57a0601211816t591d650ft@mail.gmail.com> 2006/1/21, Ben Vinger : > Hello > > I've written a couple of scripts that check log files > on our WIndows and Unix servers. These scripts have > plain text passwords in them, so anyone who can access > the filesystem of the Windows server that runs the > scripts can discover the passwords of the servers. > Is there a way to hide/encrypt these passwords? Or > can the scripts be converted to compiled code in order > for the passwords to be hidden? > > > Thanks > Ben > > Hello, Compiling a file in python is a big time loss,because there's not a built-in function for decompiling,but you can just use the 'dis'module for disassembling it and the result is always different from the original,because it uses Abstract Source Tree syntax in spite of Python language for translating the bytecode;on the other hand it wouldn't secure the file itself from being accessed but makes it useless IMHO.Thus,with a slight impact on complexity,a module with the crypted passwords would be imported, which would proceed for checking the passwords and exporting them in a StringIO object at runtime.For enhancing security,once used it could be removed and used again when needed,without removing the scripts themselves.You can check the 'crypt' module for this task. Cheers, Ivan From dyoo at hkn.eecs.berkeley.edu Sun Jan 22 08:19:09 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 21 Jan 2006 23:19:09 -0800 (PST) Subject: [Tutor] passwords in scripts In-Reply-To: <6122a57a0601211816t591d650ft@mail.gmail.com> Message-ID: > > I've written a couple of scripts that check log files on our WIndows > > and Unix servers. These scripts have plain text passwords in them, so > > anyone who can access the filesystem of the Windows server that runs > > the scripts can discover the passwords of the servers. Hello, I guess one question might be: why are the passwords there in the first place? *grin* It's usually a good idea to try avoiding hardcoding things in a program, and that goes for passwords too. If you're using passwords to connect to the Unix servers, you might want to consider looking at Keychain: http://www.gentoo.org/proj/en/keychain/ to avoid having to do manual password entry. Alternatively, 'ssh' can be used to run remote commands on a Unix server. There's a good example of this here: http://www.jdmz.net/ssh/ If you could tell us more details on why those passwords are there, we might have some better suggestions. Good luck! From dyoo at hkn.eecs.berkeley.edu Sun Jan 22 09:13:57 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 22 Jan 2006 00:13:57 -0800 (PST) Subject: [Tutor] Starbucks does not use two-phase commit In-Reply-To: <200601211357.43834.python-tutor@toddmaynard.com> Message-ID: On Sat, 21 Jan 2006, Todd Maynard wrote: > I want to thank you for ruining my plans for a relaxing Saturday > morning. As a thread newbie I killed several hours playing around with > your code. Hi Todd, Sorry about that. I hope you were relaxing in a cafe while playing with the code. > One thing I noticed is that sometimes the program would hang, which I > figured was the Queue code blocking in the Ticket claim function. I used > exception handling to deal with that situation cleanly. That's odd. There shouldn't be anything that blocks the code. Oh! Did you make changes to the test code, or did the hanging occur in the original code in: http://mail.python.org/pipermail/tutor/2006-January/044567.html I'm curious because nothing there should fundamentally block, assuming that _doJob() doesn't dies badly with an exception. If _doJob() dies, the server dies, and that's bad. *grin* Do you mind showing what the exception handling looks like in your code? > I then decided that it wasn't very nice of Starbucks to close after > accepting my order without giving me my Latte, so I changed that part of > the code to: [code cut] > I am 99.44% sure that this is thread safe, reasoning being: > setting the acceptNew to False and adding the QUIT_NOW happens in the same > thread so it is impossible for another job to get scheduled after the > QUIT_NOW - so no thread will end up hanging... Bad news: no. *grin* There's a "race condition". Let's go into some detail with this, since this is not obvious stuff. First, let's look at the code again --- I'll label three lines with (a), (b), and (c), to make it a little easier to see the race. ############################################################### def schedule(self,job): if self.acceptNew == True: ## (a) outputQueue=Queue() self.queue.put((job,outputQueue)) return Ticket(outputQueue) else: print "Server not accepting any new requests." return None def scheduleShutdown(self): ## (b) self.queue.put((Server._QUIT_NICELY,None)) def _jobLoop(self): while True: print "Looping ... " (nextJob, outputQueue) = self.queue.get() if nextJob is server._QUIT_NOW: return if nextJob is server._QUIT_NICELY: ## (c) self.acceptNew = False self.queue.put((Server._QUIT_NOW,None)) else: returnValue=self._doJob(nextJob) outputQueue.put(returnValue) ############################################################## Let's imagine three threads, which I'll name C1, C2, and S. C1 and C2 will be distinct client threads, and S will be the server thread that runs through _jobLoop(). Imagine the following scenario. The server's online, and its work queue is empty. 1. C1 calls schedule(), and reaches the line labeled (a). At this point, server.acceptNew is True, so it goes into the body of the if statement. But wait... 2. Now we context switch to C2. C2 calls scheduleShutdown() in its entirety. There is now a _QUIT_NICELY element in the queue. C2 is done for. 3. Now we context switch to the server thread S. It grabs the _QUIT_NICELY, and puts a _QUIT_NOW. Let's imagine that S continues and loops again. In the next loop through _jobLoop(), it sees _QUIT_NOW and exits. S is done for. Muhahaha. 4. Now we context switch back to C1 and continue with: outputQueue = Queue() self.queue.put((job,outputQueue)) return Ticket(outputQueue) In this scenario, poor C1 is left holding a ticket that will never cash out. One way to fix this problem is to make calling schedule() and scheduleShutdown() "atomic" in this sense: if we're calling schedule(), we shouldn't be able to context switch into a call to scheduleShutdown(), and visa-versa. Our troubles started at step 2 of the above scenario, where two clients jostled for attention. If we prevent that particular situation --- if we force all our clients to stand in line to get served --- then we'll be fine. So we might look into some synchronizing tool, like a Lock object: http://www.python.org/doc/lib/lock-objects.html Concretely, we can add an exclusive Lock object to the server's __init__: def __init__(self): self.clientLock = Lock() and make sure to acquire-and-release in any of our schedule* functions: def schedule*(self, job): self.clientLock.acquire() try: ... finally: self.clientLock.release() > However, I would sleep a little better if you could reassure me that I > am right, and would sleep even better if you could give me a method to > test this. I'm sorry; I can't provide either. That doesn't mean that such things don't exist, but only that I don't know about them. (The only formal training I've received on this, so far, has been a standard intro Operating Systems CS course.) So you might want to check with others. The way I caught the race condition above was by just by trying to be in a very foul mood while reading the code. > This kinda stuff looks tricky to test with standard unittest > methodology.... It might be hard. It's an active CS research topic to formally check for race conditions. There may be commercial tools to build unit tests to hammer for race conditions, but I don't know much about them. For example, associate Professor Cormac Flanagan does research on statically detecting race conditions: http://www.soe.ucsc.edu/~cormac/ And Google Scholar does show a heck of a lot of recent papers on this: http://scholar.google.com/scholar?hl=en&lr=&q=thread+race+condition&btnG=Search so this might not be a closed issue yet. Hmmm... hey, Flanagan's paper looks interesting! Ok, I'm printing it out now... now where's my coffee... Weekend reading for me. Well, thanks for ruining my weekend too. *grin* From jjk_saji at yahoo.com Sun Jan 22 13:43:22 2006 From: jjk_saji at yahoo.com (John Joseph) Date: Sun, 22 Jan 2006 12:43:22 +0000 (GMT) Subject: [Tutor] Searching for email id in MySQL giving wrong results Message-ID: <20060122124323.37411.qmail@web34806.mail.mud.yahoo.com> Hi Thanks to Allan,Danny,Pujo I did my simple python script for MySQL , the scripts add the data , and search for the data and display I have problem in searching email id ,ie If search for the something at some , I will not get any result , Guidance and advice needed for the reason for this behavior I had added my script in this mail Thanks Joseph John ********************************************************* """ This program is for to learn how to enter data to MySQL using python How to search not using OOP Have problem in searching email-id Why I do not get correct results when searching email id "@" string search containg "@" gives empty results """ import MySQLdb def selecter(): choice = None while choice != "0": print \ """ Data Base Entry for the Testing Env 0 - Quit 1 - Enter the Data 2 - Display The data 3 - Search The Company """ choice = raw_input("Choice :........") print if choice == "0": print "Good Bye ..." elif choice == "1": dataentry() elif choice == "2": datashow() elif choice == "3": datasearch() def dataentry(): name = raw_input("Enter the name of the company ") email_id = raw_input("\n Enter the email ID : ") phone_no = raw_input("Enter the Phone No : ") fax_no = raw_input("\n Enter the fax no : ") db = MySQLdb.connect(host="localhost",user = "john", passwd = "asdlkj", db = 'learnpython') entry = db.cursor() #entry.execute("""INSERT INTO contact """,(name,email_id,phone_no,fax_no,)) entry.execute("""INSERT INTO contact(name,email_id,phone_no,fax_no) VALUES (%s,%s,%s,%s)""",(name,email_id,phone_no,fax_no,)) print name , email_id , fax_no, phone_no def datashow(): db = MySQLdb.connect(host="localhost",user = "john", passwd = "asdlkj", db = 'learnpython') entry = db.cursor() entry.execute("SELECT * from contact") p = entry.fetchall() print p def datasearch(): print "Do U want to search by Name , email id , phone or fax " choice = None while choice != "0": print \ """ U want to search the contacts by 0 - Quit 1 - Name 2 - email_id 3 - phone 4 - fax """ choice = raw_input("Choice :........") print if choice == "0": print "Good Bye ..." elif choice == "1": searchbyname() elif choice == "2": searchbyemail() elif choice == "3": searchbyphone() elif choice == "4": searchbyfax() def searchbyname(): s_name = raw_input("Enter the name to be searched ") db = MySQLdb.connect(host="localhost",user = "john", passwd = "asdlkj", db = 'learnpython') entry = db.cursor() entry.execute("""SELECT * FROM contact WHERE name = %s""", (s_name,)) p = entry.fetchall() print p def searchbyemail(): s_email = raw_input("Enter the Email to be searched ") db = MySQLdb.connect(host="localhost",user = "john", passwd = "asdlkj", db = 'learnpython') entry = db.cursor() entry.execute("""SELECT * FROM contact WHERE email_id = %s""", (s_email,)) p = entry.fetchall() print p def searchbyphone(): s_phone= raw_input("Enter the Phone no to be searched ") db = MySQLdb.connect(host="localhost",user = "john", passwd = "asdlkj", db = 'learnpython') entry = db.cursor() entry.execute("""SELECT * FROM contact WHERE phone_no = %s""", (s_phone,)) p = entry.fetchall() print p def searchbyfax(): s_fax = raw_input("Enter the FAX no to be searched ") db = MySQLdb.connect(host="localhost",user = "john", passwd = "asdlkj", db = 'learnpython') entry = db.cursor() entry.execute("""SELECT * FROM contact WHERE fax_no = %s""", (s_fax,)) p = entry.fetchall() print p selecter() ___________________________________________________________ Yahoo! Photos ? NEW, now offering a quality print service from just 8p a photo http://uk.photos.yahoo.com From python-tutor at toddmaynard.com Sun Jan 22 15:52:23 2006 From: python-tutor at toddmaynard.com (Todd Maynard) Date: Sun, 22 Jan 2006 09:52:23 -0500 Subject: [Tutor] Starbucks does not use two-phase commit In-Reply-To: References: Message-ID: <200601220952.24600.python-tutor@toddmaynard.com> Well Danny, now I know how I am gonna spend my Sunday.... Thanks for the great explanation and the resources. Of course do you think I could manage to get the code to break - of course not.... Usually I have the opposite problem. Anyways I think that your explanation makes perfect sense. My problem with your original code is that _jobLoop could sometimes return when there where still jobs (from separateCaller) still left in the queue. When separateCaller tried to ticket.claim , the self.result = self.q.get() would block, causing the program to hang indefinitely. This is what I was trying to prevent by using the timeout in the get() call and then handling the possible Empty exception. I am now gonna play with this some more to see if I can build a robust/clean coffeeshop framework, with customers placing orders with a cashier , the cashier passing the orders to a barista and the barista processing the orders and delivering to the customers. The idea of course being that the customers, cashier, and baristas each run in different threads. Then to enhance with multiple cashiers and baristas.... but first I need to put another pot of coffee on. If you don't hear from me in a while, I've probably suffered a caffeine overdose. Thanks for the inspiration, Todd Maynard -- The tao that can be tar(1)ed is not the entire Tao. The path that can be specified is not the Full Path. We declare the names of all variables and functions. Yet the Tao has no type specifier. Dynamically binding, you realize the magic. Statically binding, you see only the hierarchy. Yet magic and hierarchy arise from the same source, and this source has a null pointer. Reference the NULL within NULL, it is the gateway to all wizardry. On Sunday 22 January 2006 03:13, Danny Yoo wrote: > On Sat, 21 Jan 2006, Todd Maynard wrote: > > I want to thank you for ruining my plans for a relaxing Saturday > > morning. As a thread newbie I killed several hours playing around with > > your code. > > Hi Todd, > > Sorry about that. I hope you were relaxing in a cafe while playing with > the code. > > > One thing I noticed is that sometimes the program would hang, which I > > figured was the Queue code blocking in the Ticket claim function. I used > > exception handling to deal with that situation cleanly. > > That's odd. There shouldn't be anything that blocks the code. Oh! Did > you make changes to the test code, or did the hanging occur in the > original code in: > > http://mail.python.org/pipermail/tutor/2006-January/044567.html > > I'm curious because nothing there should fundamentally block, assuming > that _doJob() doesn't dies badly with an exception. If _doJob() dies, the > server dies, and that's bad. *grin* > > Do you mind showing what the exception handling looks like in your code? > > > I then decided that it wasn't very nice of Starbucks to close after > > accepting my order without giving me my Latte, so I changed that part of > > the code to: > > [code cut] > > > I am 99.44% sure that this is thread safe, reasoning being: > > setting the acceptNew to False and adding the QUIT_NOW happens in the > > same thread so it is impossible for another job to get scheduled after > > the QUIT_NOW - so no thread will end up hanging... > > Bad news: no. *grin* > > There's a "race condition". Let's go into some detail with this, since > this is not obvious stuff. > > First, let's look at the code again --- I'll label three lines with (a), > (b), and (c), to make it a little easier to see the race. > > > ############################################################### > def schedule(self,job): > if self.acceptNew == True: ## (a) > outputQueue=Queue() > self.queue.put((job,outputQueue)) > return Ticket(outputQueue) > else: > print "Server not accepting any new requests." > return None > > def scheduleShutdown(self): ## (b) > self.queue.put((Server._QUIT_NICELY,None)) > > def _jobLoop(self): > while True: > print "Looping ... " > (nextJob, outputQueue) = self.queue.get() > if nextJob is server._QUIT_NOW: > return > if nextJob is server._QUIT_NICELY: ## (c) > self.acceptNew = False > self.queue.put((Server._QUIT_NOW,None)) > else: > returnValue=self._doJob(nextJob) > outputQueue.put(returnValue) > ############################################################## > > > Let's imagine three threads, which I'll name C1, C2, and S. C1 and C2 > will be distinct client threads, and S will be the server thread that runs > through _jobLoop(). > > Imagine the following scenario. The server's online, and its work queue > is empty. > > 1. C1 calls schedule(), and reaches the line labeled (a). At this > point, server.acceptNew is True, so it goes into the body of the > if statement. But wait... > > 2. Now we context switch to C2. C2 calls scheduleShutdown() > in its entirety. There is now a _QUIT_NICELY element in the > queue. C2 is done for. > > 3. Now we context switch to the server thread S. It grabs the > _QUIT_NICELY, and puts a _QUIT_NOW. Let's imagine that S > continues and loops again. In the next loop through _jobLoop(), > it sees _QUIT_NOW and exits. S is done for. Muhahaha. > > 4. Now we context switch back to C1 and continue with: > > outputQueue = Queue() > self.queue.put((job,outputQueue)) > return Ticket(outputQueue) > > In this scenario, poor C1 is left holding a ticket that will never cash > out. > > One way to fix this problem is to make calling schedule() and > scheduleShutdown() "atomic" in this sense: if we're calling schedule(), we > shouldn't be able to context switch into a call to scheduleShutdown(), and > visa-versa. > > Our troubles started at step 2 of the above scenario, where two clients > jostled for attention. If we prevent that particular situation --- if we > force all our clients to stand in line to get served --- then we'll be > fine. So we might look into some synchronizing tool, like a Lock object: > > http://www.python.org/doc/lib/lock-objects.html > > Concretely, we can add an exclusive Lock object to the server's __init__: > > def __init__(self): > self.clientLock = Lock() > > and make sure to acquire-and-release in any of our schedule* functions: > > def schedule*(self, job): > self.clientLock.acquire() > try: > ... > finally: > self.clientLock.release() > > > However, I would sleep a little better if you could reassure me that I > > am right, and would sleep even better if you could give me a method to > > test this. > > I'm sorry; I can't provide either. That doesn't mean that such things > don't exist, but only that I don't know about them. (The only formal > training I've received on this, so far, has been a standard intro > Operating Systems CS course.) > > So you might want to check with others. The way I caught the race > condition above was by just by trying to be in a very foul mood while > reading the code. > > > This kinda stuff looks tricky to test with standard unittest > > methodology.... > > It might be hard. It's an active CS research topic to formally check for > race conditions. There may be commercial tools to build unit tests to > hammer for race conditions, but I don't know much about them. > > For example, associate Professor Cormac Flanagan does research on > statically detecting race conditions: > > http://www.soe.ucsc.edu/~cormac/ > > And Google Scholar does show a heck of a lot of recent papers on this: > > http://scholar.google.com/scholar?hl=en&lr=&q=thread+race+condition&btnG=Se >arch > > so this might not be a closed issue yet. > > > Hmmm... hey, Flanagan's paper looks interesting! Ok, I'm printing it out > now... now where's my coffee... Weekend reading for me. > > Well, thanks for ruining my weekend too. *grin* From jwalker343 at yahoo.com Sun Jan 22 17:37:22 2006 From: jwalker343 at yahoo.com (johnny` walker) Date: Sun, 22 Jan 2006 08:37:22 -0800 (PST) Subject: [Tutor] webcam secrets? Message-ID: <20060122163722.1417.qmail@web32207.mail.mud.yahoo.com> i was wondering if there was a way to automatically take a picture from my webcam every oh say 5 minutes? is there anyway of doing this (im very new to programming languages.) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060122/9e96f8ff/attachment.htm From w.damen at gmail.com Sun Jan 22 17:19:42 2006 From: w.damen at gmail.com (Rinzwind) Date: Sun, 22 Jan 2006 17:19:42 +0100 Subject: [Tutor] [webbrowser] some help on an error running mozilla firefox Message-ID: <4677730601220819qdb0ee24k4004a439f85bd490@mail.gmail.com> Why does this: >>> import webbrowser >>> webbrowser.open('http://www.google.com") give me this: run-mozilla.sh: Cannot execute /opt/firefox/mozilla-firefox-bin. Is this bacause 'webbrowser' does not know about the identification of 1.5? (I do not want to do it like this: >>> import os >>> os.system ('firefox http://www.google.com') bacause not all of us use firefox :) ) Oh and can I, when I open a new browserwindow, force it to open in the same workspace as I am with my pythonprogram and not inside another workspace where I have a browser window open? Any enlightment would be appreciated :-) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060122/4ea8e549/attachment.html From w.damen at gmail.com Sun Jan 22 18:11:40 2006 From: w.damen at gmail.com (Rinzwind) Date: Sun, 22 Jan 2006 18:11:40 +0100 Subject: [Tutor] webcam secrets? In-Reply-To: <20060122163722.1417.qmail@web32207.mail.mud.yahoo.com> References: <20060122163722.1417.qmail@web32207.mail.mud.yahoo.com> Message-ID: <4677730601220911t55005e77j9cc9110cb52098c2@mail.gmail.com> That (mosttimes) is a setting in your webcamsoftware and doesn't require coding. Wim On 1/22/06, johnny` walker wrote: > > i was wondering if there was a way to automatically take a picture from my > webcam every oh say 5 minutes? > > is there anyway of doing this (im very new to programming languages.) > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060122/d3586109/attachment.htm From alan.gauld at freenet.co.uk Sun Jan 22 18:28:40 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 22 Jan 2006 17:28:40 -0000 Subject: [Tutor] Totorial announcement Message-ID: <00a501c61f79$49a63110$0b01a8c0@xp> I've just uploaded the completed tutoroial topic on OS access. It covers most of the common questions asked on this list about determining file access, launching programs (including use of the new subprocess module), accessing environment variables etc. It also has a short intro to bitmask manipulation and bitwise operators. I've also updated the zip, tgz and pdf files too. For those interested in printing out the PDF (someone asked me recently) it currently runs to 342 pages of A4 but the margins are set so it should work fine on US Letter paper too. Enjoy, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From zamb at saudi.net.sa Sun Jan 22 19:23:23 2006 From: zamb at saudi.net.sa (ZIYAD A. M. AL-BATLY) Date: Sun, 22 Jan 2006 21:23:23 +0300 Subject: [Tutor] Searching for email id in MySQL giving wrong results In-Reply-To: <20060122124323.37411.qmail@web34806.mail.mud.yahoo.com> References: <20060122124323.37411.qmail@web34806.mail.mud.yahoo.com> Message-ID: <1137954203.31434.8.camel@localhost.localdomain> On Sun, 2006-01-22 at 12:43 +0000, John Joseph wrote: > Hi Hi John... Most of your problems in your code seems to be caused by a single mistake. Compare the following two strings and you should figure out what's wrong by yourself: email_id = 'email at domain.tld' wrong_string = '''SELECT s FROM t WHERE id=%s''' , (email_id) right_string = '''SELECT s FROM t WHERE id=%s''' % (email_id) print "Wrong:", wrong_string print "Right:", right_string This is the output: Wrong: ('SELECT s FROM t WHERE id=%s', 'email at domain.tld') Right: SELECT s FROM t WHERE id=email at domain.tld Now, which one is the right one? And which one is the one you want? I suggest you study strings more, especially concatenation and '%'. If you need more help, just post to the mailing list again. Ziyad. From w.damen at gmail.com Sun Jan 22 19:29:38 2006 From: w.damen at gmail.com (Rinzwind) Date: Sun, 22 Jan 2006 19:29:38 +0100 Subject: [Tutor] Totorial announcement In-Reply-To: <00a501c61f79$49a63110$0b01a8c0@xp> References: <00a501c61f79$49a63110$0b01a8c0@xp> Message-ID: <4677730601221029vbc28d1fyc09c97aab7f33b04@mail.gmail.com> Excellent guide. I bookmarked it :-) because I plan to use it alot. Oh, how much work (in hours) did it take it to translate your website? Wim On 1/22/06, Alan Gauld wrote: > > I've just uploaded the completed tutoroial topic on OS access. > > It covers most of the common questions asked on this list about > determining > file access, launching programs (including use of the new subprocess > module), > accessing environment variables etc. It also has a short intro to bitmask > manipulation > and bitwise operators. > > I've also updated the zip, tgz and pdf files too. > > For those interested in printing out the PDF (someone asked me recently) > it > currently runs to 342 pages of A4 but the margins are set so it should > work fine on US Letter paper too. > > Enjoy, > > Alan G > Author of the learn to program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060122/dbdabc62/attachment.htm From kenneth.kalmer at gmail.com Sun Jan 22 20:41:53 2006 From: kenneth.kalmer at gmail.com (Kenneth Kalmer) Date: Sun, 22 Jan 2006 21:41:53 +0200 Subject: [Tutor] Framework recommendations for e-commerce Message-ID: Greetings list This is my first post to the list, please excuse me if I mess up... OK, I'm new to Python, but not new to programming. I have years of PHP behind me, and some C# & Java (to name the "bigger" names)... I'm asking this question here because I'm new, and it must have been discussed excessively in the python-list by now. I'm looking for suggestions on a framework for building an e-commerce solution. Must be relatively painless to extend with new features but provide a good strong base. The learning curve mustn't be too steep either :) I've seen with PHP & Java that there is no single great framework. I'm looking for the best mix of powerful and fast time to market, considering I'm a newbie... So far Zope looks great, and sticking Plone on top seems like a great idea. I can then only extend Plone and a lot of basics will be covered for me... Will I be shooting myself in the foot? Best -- Kenneth Kalmer kenneth.kalmer at gmail.com Folding at home stats http://fah-web.stanford.edu/cgi-bin/main.py?qtype=userpage&username=kenneth%2Ekalmer From hugonz-lists at h-lab.net Sun Jan 22 23:30:30 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Sun, 22 Jan 2006 16:30:30 -0600 Subject: [Tutor] webcam secrets? In-Reply-To: <20060122163722.1417.qmail@web32207.mail.mud.yahoo.com> References: <20060122163722.1417.qmail@web32207.mail.mud.yahoo.com> Message-ID: <43D40786.5080906@h-lab.net> Hi Johnny, As someone already said, it could be possible to do that without going into any code, but assuming you want to do it by means of Python... I assume you're using Windows, are you trying to control another application (the one that came with your webcam)? are you trying to write a program that accesses the driver for your webcam? In any case, whatever you're trying to accomplish will have a lot to do with what the operating system allows you. May I suggest you take another program or exercise more related to programming before you become complicated with so mucho weird operating system interfaces? I suppose webcams are accessed through the TWAIN infterface. There is (old) support for python, here: http://twainmodule.sourceforge.net/docs/ Hugo johnny` walker wrote: > i was wondering if there was a way to automatically take a picture from > my webcam every oh say 5 minutes? > > is there anyway of doing this (im very new to programming languages.) > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From zenzee at xs4all.nl Mon Jan 23 00:46:26 2006 From: zenzee at xs4all.nl (Vincent Zee) Date: Mon, 23 Jan 2006 00:46:26 +0100 Subject: [Tutor] I'm puzzled Message-ID: <20060122234626.GA73196@xs4all.nl> Hi all, I'm puzzled (:-)) Why will this little program crash when you enter the enter key? while True: a = raw_input('number? ') if a.isdigit(): print 'isdigit' elif a[0] == '-' and a[1:].isdigit(): print '- + isdigit' elif a == 'q': break else: print 'no digit' /\ Vincent From dyoo at hkn.eecs.berkeley.edu Mon Jan 23 00:54:06 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 22 Jan 2006 15:54:06 -0800 (PST) Subject: [Tutor] I'm puzzled In-Reply-To: <20060122234626.GA73196@xs4all.nl> Message-ID: > Why will this little program crash when you enter the enter key? [program cut] Hi Vincent, What do you mean by "crash"? Do you get an error message? If so, can you show us? It will also help to think to try playing the situation out without preconceptions. In the beginning of the loop, at: > a = raw_input('number? ') what does 'a' contain when you hit enter? From zenzee at xs4all.nl Mon Jan 23 00:59:40 2006 From: zenzee at xs4all.nl (Vincent Zee) Date: Mon, 23 Jan 2006 00:59:40 +0100 Subject: [Tutor] I'm puzzled In-Reply-To: References: <20060122234626.GA73196@xs4all.nl> Message-ID: <20060122235940.GB73196@xs4all.nl> On Sunday, 22 January 2006 at 15:54:06 -0800, Danny Yoo wrote: > > > Why will this little program crash when you enter the enter key? > > [program cut] > > Hi Vincent, > > What do you mean by "crash"? Do you get an error message? If so, can you > show us? > > > It will also help to think to try playing the situation out without > preconceptions. In the beginning of the loop, at: > > > a = raw_input('number? ') > > what does 'a' contain when you hit enter? > > Hi Danny, the program works with any input except when you just hit the enter key. vincent at zenzeebook:~/Desktop% python untitled.py number? Traceback (most recent call last): File "untitled.py", line 12, in ? elif a[0] == '-' and a[1:].isdigit(): IndexError: string index out of range /\ Vincent From shuying at gmail.com Mon Jan 23 00:59:24 2006 From: shuying at gmail.com (Shuying Wang) Date: Mon, 23 Jan 2006 10:59:24 +1100 Subject: [Tutor] I'm puzzled In-Reply-To: <20060122234626.GA73196@xs4all.nl> References: <20060122234626.GA73196@xs4all.nl> Message-ID: <75fa0c3a0601221559m72886b98m6c25940978a039ad@mail.gmail.com> I'm guessing when you did that, you got something like an IndexError. That's because you didn't check the length of "a" from raw_input and accessed a nonexistent array element (a string is an array of characters). So if you changed the line: elif a[0] == '-' and a[1:].isdigit(): to : elif len(a) > 1 and a[0] == '-' and a[1:].isdigit(): I expect you'll get what you want. --Shuying On 1/23/06, Vincent Zee wrote: > Hi all, > > I'm puzzled (:-)) > > Why will this little program crash when you enter the > enter key? > > while True: > a = raw_input('number? ') > if a.isdigit(): > print 'isdigit' > elif a[0] == '-' and a[1:].isdigit(): > print '- + isdigit' > elif a == 'q': > break > else: > print 'no digit' From bgailer at alum.rpi.edu Mon Jan 23 01:07:06 2006 From: bgailer at alum.rpi.edu (bob) Date: Sun, 22 Jan 2006 16:07:06 -0800 Subject: [Tutor] I'm puzzled In-Reply-To: <20060122234626.GA73196@xs4all.nl> References: <20060122234626.GA73196@xs4all.nl> Message-ID: <7.0.0.16.0.20060122160058.0240a8b8@alum.rpi.edu> At 03:46 PM 1/22/2006, Vincent Zee wrote: >Why will this little program crash when you enter the enter key? Thank you for including the "traceback" message in your 2nd post. Index error means you tried to reference an element of a sequence that is not there. a is the empty string when you just hit enter to the raw_input request. It therefore has no elements, so a[0] raises the exception. To avoid this test first for len(a) > 0. >while True: > a = raw_input('number? ') > if a.isdigit(): > print 'isdigit' > elif a[0] == '-' and a[1:].isdigit(): > print '- + isdigit' > elif a == 'q': > break > else: > print 'no digit' From hugonz-lists at h-lab.net Mon Jan 23 01:11:09 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Sun, 22 Jan 2006 18:11:09 -0600 Subject: [Tutor] I'm puzzled In-Reply-To: <20060122235940.GB73196@xs4all.nl> References: <20060122234626.GA73196@xs4all.nl> <20060122235940.GB73196@xs4all.nl> Message-ID: <43D41F1D.1030703@h-lab.net> Hi Vincent, > the program works with any input except when you just hit the enter key. To be able to understand why is the crash, take a look at what the interpreter tells you: > File "untitled.py", line 12, in ? > elif a[0] == '-' and a[1:].isdigit(): > IndexError: string index out of range IndexError is raised whan you try to access an element in a list or string, an element that does not exist. In the case where you only press enter, what is the content of a???? How many characters? (hint, you may try to print a before any evaluation... Hope that gets you going, Hugo From zenzee at xs4all.nl Mon Jan 23 01:18:53 2006 From: zenzee at xs4all.nl (Vincent Zee) Date: Mon, 23 Jan 2006 01:18:53 +0100 Subject: [Tutor] I'm puzzled In-Reply-To: <7.0.0.16.0.20060122160058.0240a8b8@alum.rpi.edu> References: <20060122234626.GA73196@xs4all.nl> <7.0.0.16.0.20060122160058.0240a8b8@alum.rpi.edu> Message-ID: <20060123001853.GA74847@xs4all.nl> On Sunday, 22 January 2006 at 16:07:06 -0800, bob wrote: > At 03:46 PM 1/22/2006, Vincent Zee wrote: > >Why will this little program crash when you enter the enter key? > > Thank you for including the "traceback" message in your 2nd post. > > Index error means you tried to reference an element of a sequence > that is not there. a is the empty string when you just hit enter to > the raw_input request. It therefore has no elements, so a[0] raises > the exception. > > To avoid this test first for len(a) > 0. > > >while True: > > a = raw_input('number? ') > > if a.isdigit(): > > print 'isdigit' > > elif a[0] == '-' and a[1:].isdigit(): > > print '- + isdigit' > > elif a == 'q': > > break > > else: > > print 'no digit' > Ah, thank you Bob for the explanation. I understand now. /\ Vincent From hugonz-lists at h-lab.net Mon Jan 23 01:19:55 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Sun, 22 Jan 2006 18:19:55 -0600 Subject: [Tutor] python-based system programming and admin? In-Reply-To: <20060121040103.AD30C8EF5@lock.gotdns.org> References: <20060121040103.AD30C8EF5@lock.gotdns.org> Message-ID: <43D4212B.70603@h-lab.net> MMM strange needs... I'm thinking that perhaps allowing him to run idle and exporting X display to the Mac could be an option? I used to do perl on linux until I found Python, I find it very easy to run quick scripts and system stuff without having to learn BASH, sed, awk, etc separately, taht way I can do regexp, listings, recursion on directories, batch jobs, etc. Hugo From zenzee at xs4all.nl Mon Jan 23 01:20:18 2006 From: zenzee at xs4all.nl (Vincent Zee) Date: Mon, 23 Jan 2006 01:20:18 +0100 Subject: [Tutor] I'm puzzled In-Reply-To: <75fa0c3a0601221559m72886b98m6c25940978a039ad@mail.gmail.com> References: <20060122234626.GA73196@xs4all.nl> <75fa0c3a0601221559m72886b98m6c25940978a039ad@mail.gmail.com> Message-ID: <20060123002018.GB74847@xs4all.nl> On Monday, 23 January 2006 at 10:59:24 +1100, Shuying Wang wrote: > I'm guessing when you did that, you got something like an IndexError. > That's because you didn't check the length of "a" from raw_input and > accessed a nonexistent array element (a string is an array of > characters). So if you changed the line: > elif a[0] == '-' and a[1:].isdigit(): > to : > elif len(a) > 1 and a[0] == '-' and a[1:].isdigit(): > > I expect you'll get what you want. > Hi Shuying, thank you for your solution. /\ Vincent From zenzee at xs4all.nl Mon Jan 23 01:24:56 2006 From: zenzee at xs4all.nl (Vincent Zee) Date: Mon, 23 Jan 2006 01:24:56 +0100 Subject: [Tutor] I'm puzzled In-Reply-To: <43D41F1D.1030703@h-lab.net> References: <20060122234626.GA73196@xs4all.nl> <20060122235940.GB73196@xs4all.nl> <43D41F1D.1030703@h-lab.net> Message-ID: <20060123002456.GC74847@xs4all.nl> On Sunday, 22 January 2006 at 18:11:09 -0600, Hugo Gonz?lez Monteverde wrote: > Hi Vincent, > > > the program works with any input except when you just hit the enter key. > > > To be able to understand why is the crash, take a look at what the > interpreter tells you: > > > File "untitled.py", line 12, in ? > > elif a[0] == '-' and a[1:].isdigit(): > > IndexError: string index out of range > > IndexError is raised whan you try to access an element in a list or > string, an element that does not exist. In the case where you only press > enter, what is the content of a???? How many characters? (hint, you may > try to > Hi Hugo, thank you for your reply. What confused me was the fact that the isdigit method didn't complain about the empty string, so I assumed that indexing an empty string wouldn't be a problem (:-)) But now I think of it that wouldn't be logical. Sometimes the 'intelligence' of python makes me lazy (;-)) /\ Vincent From neal at bcn.boulder.co.us Mon Jan 23 01:39:23 2006 From: neal at bcn.boulder.co.us (Neal McBurnett) Date: Sun, 22 Jan 2006 17:39:23 -0700 Subject: [Tutor] python-based system programming and admin? In-Reply-To: <43D4212B.70603@h-lab.net> References: <20060121040103.AD30C8EF5@lock.gotdns.org> <43D4212B.70603@h-lab.net> Message-ID: <20060123003923.GH25156@feynman> On Sun, Jan 22, 2006 at 06:19:55PM -0600, Hugo Gonz?lez Monteverde wrote: > I used to do perl on linux until I found Python, I find it very easy to > run quick scripts and system stuff without having to learn BASH, sed, > awk, etc separately, taht way I can do regexp, listings, recursion on > directories, batch jobs, etc. My question is exactly how to let someone do that securely on a remote machine. I've looked at ipython now, and I think it is ideal for the purpose - I just have to tell the user to ssh in and run 'ipython' to get a familiar and flexible environment. > I'm thinking that perhaps allowing him to run idle and exporting X > display to the Mac could be an option? The system is a server - doesn't even need X libraries, which are a significant source of security concerns. Thanks, Neal McBurnett http://bcn.boulder.co.us/~neal/ Signed and/or sealed mail encouraged. GPG/PGP Keyid: 2C9EBA60 From alan.gauld at freenet.co.uk Mon Jan 23 01:55:00 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 23 Jan 2006 00:55:00 -0000 Subject: [Tutor] Totorial announcement References: <00a501c61f79$49a63110$0b01a8c0@xp> <4677730601221029vbc28d1fyc09c97aab7f33b04@mail.gmail.com> Message-ID: <00df01c61fb7$a3855ba0$0b01a8c0@xp> > Excellent guide. I bookmarked it :-) because I plan to use it alot. Glad you like it, as you'll see I have a few more topics planned yet but each topic takes from 3-12 weeks to write... > Oh, how much work (in hours) did it take it to translate your website? To translate, I don't know, some translators seem to get through the whole thing in a few months, others take a year or more. I've been working on the English version since 1998 and the rewrite to Python 2.3 took over 6 months. Working about 5-10 hours per week I guess. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From list at ohtogo.com Mon Jan 23 07:33:11 2006 From: list at ohtogo.com (Michael) Date: Sun, 22 Jan 2006 23:33:11 -0700 Subject: [Tutor] processing a text file w/ OO? Message-ID: Hi. I'm processing a tab-delimited text file where I read in a file, perform a bunch of operations on the items, and then write them out again to a fixed-width text file. I've been doing this with a very functional approach: - loop over lines - read line into dictionary - process dictionary values ( format phone numbers and dates and amounts, etc.) - pad dictionary values with spaces - write dictionary values out to file Anyway, this all works fine. Not knowing much about OO, I'm wondering if there's a way to approach this from an object-oriented perspective. Is there anything to be gained? Or is this type of problem best tackled with a functional approach? TIA. From ajikoe at gmail.com Mon Jan 23 08:43:11 2006 From: ajikoe at gmail.com (Pujo Aji) Date: Mon, 23 Jan 2006 08:43:11 +0100 Subject: [Tutor] processing a text file w/ OO? In-Reply-To: References: Message-ID: you can use regex if you want. It gives you power to do text processing. OO will give you benefit because your program becomes clearer while it is developed Cheers, pujo On 1/23/06, Michael wrote: > > Hi. > > I'm processing a tab-delimited text file where I read in a file, > perform a bunch of operations on the items, and then write them out > again to a fixed-width text file. > > I've been doing this with a very functional approach: > > - loop over lines > - read line into dictionary > - process dictionary values ( format phone numbers and dates and > amounts, etc.) > - pad dictionary values with spaces > - write dictionary values out to file > > Anyway, this all works fine. Not knowing much about OO, I'm wondering > if there's a way to approach this from an object-oriented > perspective. Is there anything to be gained? Or is this type of > problem best tackled with a functional approach? > > TIA. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060123/fccca3c6/attachment.html From derroach at stu.usd376.com Thu Jan 19 03:46:57 2006 From: derroach at stu.usd376.com (derroach at stu.usd376.com) Date: Wed, 18 Jan 2006 20:46:57 -0600 Subject: [Tutor] Senior Project With Python Message-ID: <20060119024600.M5570@stu.usd376.com> Greetings! My name is Deric Roach, and I am a senior at Sterling High School in Sterling, Kansas. This year, the school is conducting senior projects. For my senior project, I have decided to learn the python programming language and design a simple (yet amusing) role-playing game. For the undertaking, I must find a "mentor" to assist my development, guide my progress, and prepare me for the final presentation of the finished product. This mentor is to put in around 10 hours of service from now until the end of April, at which point the projects will be completed. I would like to find somebody who would be willing to help me out and adopt the title of "mentor." You don't necessarily have to be fluent in Python, but you must be able to give me guidance in the way of programming and/or game development. If you live farther away than is of convenience, we could maintain an e-mail partnership. A thank you all, and to all a "thank you. Respectfully, Deric E. Roach From rymer at generativesystems.com Fri Jan 20 01:29:56 2006 From: rymer at generativesystems.com (Shane Rymer) Date: Thu, 19 Jan 2006 17:29:56 -0700 Subject: [Tutor] mac users Message-ID: <9416bca17c32163403c3e70254368cac@generativesystems.com> Dear Group, I am a macOSX user and I would like to simultaneously learn how to program and learn python. Does anyone know of a good book, or online tutorial that would be helpful? I got the book, "Learning to Program in Python for the absolute beginner". but... its was made for Windows users and the examples in the book dont work for me, for example, print "\a" does not make my macOSX system "beep" any guidance would be great! thanks, Shane From shalini.r at oneworld.net Mon Jan 23 07:24:28 2006 From: shalini.r at oneworld.net (Shalini R) Date: Mon, 23 Jan 2006 06:24:28 -0000 Subject: [Tutor] PLZ REPLY SOON Message-ID: <380-22006112362428973@oneworld.net> Hi sir, I'm new to python & postgres as I've created a form in html & a table in postgres. There is a field in form which will take multiple value the problem which i'm facing is i'm getting single value but when i want multiple values to be inserted to postgres table it is not happening the dtml script is
Eno
EmpName
Facility you want HRA
Travel
Food
Accomodation
State
-------------- python script import psycopg import sys def add(REQUEST): try: con=psycopg.connect("dbname=mission2007 user= postgres") cur=con.cursor() d=[] d.append(REQUEST.get("txtEmpName")) d.append(REQUEST.get("arrFacility")) d.append(REQUEST.get("txtState")) sql1="select max(eno) from empdetail" cur.execute(sql1) eno=cur.fetchone() sql="insert into empdetail (empname,facility,state) values('"+REQUEST.get("txtEmpName")+"','"+REQUEST.get("arrFacility")+" ','"+REQUEST.get("txtState")+"')" return sql cur.execute(sql) con.commit() cur.close() con.close() return "You had successfully entered data" From SChitti at manh.com Mon Jan 23 09:50:53 2006 From: SChitti at manh.com (Suri Chitti) Date: Mon, 23 Jan 2006 14:20:53 +0530 Subject: [Tutor] How can I clean the screen Message-ID: Dear group, If I am executing a python prog from the command line and need to clear the screen (like using the cls command at the windows cmd prompt) midway into the program, how do I do it?? Any inputs will be greatly appreciated. Thanks. From ajikoe at gmail.com Mon Jan 23 10:11:48 2006 From: ajikoe at gmail.com (Pujo Aji) Date: Mon, 23 Jan 2006 10:11:48 +0100 Subject: [Tutor] How can I clean the screen In-Reply-To: References: Message-ID: Try : import os os.system('cls') you will able to see the effect when you run in windows console. Cheers, pujo On 1/23/06, Suri Chitti wrote: > > > Dear group, > If I am executing a python prog from the command line and > need to clear the screen (like using the cls command at the windows cmd > prompt) midway into the program, how do I do it?? Any inputs will be > greatly appreciated. > Thanks. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060123/bb51d076/attachment.htm From alan.gauld at freenet.co.uk Mon Jan 23 10:53:35 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 23 Jan 2006 09:53:35 -0000 Subject: [Tutor] processing a text file w/ OO? References: Message-ID: <011101c62002$e3029ae0$0b01a8c0@xp> > I'm processing a tab-delimited text file where I read in a file, > perform a bunch of operations on the items, and then write them out > again to a fixed-width text file. > > I've been doing this with a very functional approach: > > Anyway, this all works fine. Not knowing much about OO, I'm wondering > if there's a way to approach this from an object-oriented > perspective. Is there anything to be gained? Or is this type of > problem best tackled with a functional approach? This is one of the types of problem where I personally don't try to use objects too much. Where objects might be helpful is if you have a number of similar but slightly different data records such that the processing consists of lots of if/elif chains. In that case identifying the type once and relying on polymorphism to deal with the differences is useful. But if the records all have similar processing then OOP will make the code bulkier, slower and not add too much IMHO. OTOH if you were to write a lot of these kinds of applications OOP might provide a higher level of code reuse between projects.... But remember that the cost of reuse means that you need to reuse code 3(*) or more times to make it economical! (*) Metrics suggest the actual figure varies between 3-10 times depending on language, object complexity and level of generality. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Mon Jan 23 10:59:44 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 23 Jan 2006 09:59:44 -0000 Subject: [Tutor] mac users References: <9416bca17c32163403c3e70254368cac@generativesystems.com> Message-ID: <011901c62003$bcb53220$0b01a8c0@xp> Hi Shane, > I am a macOSX user and I would like to simultaneously learn how to program > and learn python. Does anyone know of a good book, or online tutorial that > would be helpful? The Python web site lists lots of tutorials and they are all free so try them and see which suits your style. Tutorials tend to be very individual in nature, what suits one may not work for another. > Python for the absolute beginner". but... its was made for Windows users > and the examples in the book dont work for me, for example, > > print "\a" > > does not make my macOSX system "beep" Did you try it in the Terminal (Applications->Utilities) I don't think \a works in the IDE that comes with MacPython but the Terminal should work I think...(Where is my iBook when I need it?!) regards, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Mon Jan 23 11:07:09 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 23 Jan 2006 10:07:09 -0000 Subject: [Tutor] How can I clean the screen References: Message-ID: <011f01c62004$c5fa6fc0$0b01a8c0@xp> > If I am executing a python prog from the command line and > need to clear the screen (like using the cls command at the windows cmd Thus should be a FAQ somewhere... Clearing the screen is terminal specific so Python doesn't have a single way to do it. Since you mention Windows I'll assume thats what you are using and suggest you simply use the CLS command via an os.system() call: import os os.system('CLS') If you have Linux substitute 'clear' for CLS Or as a last resort write your own: def cls(rows=100): for row in rows: print If you use curses it has a couple of functions for clearing a window. HTH, Alan G. From lumbricus at gmx.net Mon Jan 23 11:31:16 2006 From: lumbricus at gmx.net (lumbricus at gmx.net) Date: Mon, 23 Jan 2006 11:31:16 +0100 (MET) Subject: [Tutor] python-based system programming and admin? Message-ID: <2962.1138012276@www037.gmx.net> > I just have to tell the user to ssh in and run 'ipython' to > get a familiar and flexible environment. Put a link on his Desktop which points to "ssh -X user at host ipython" man ssh > The system is a server - doesn't even need X libraries, which are a > significant source of security concerns. The security risk is running an X-Server, but the server doesn't need one. The _client_ needs to run X so ipython (running on the server) can draw its windows on the screen of the client machine. So this should not be a problem. HTH -- Freedom, Freedom, Freedom, Oi! -- Zoidberg Telefonieren Sie schon oder sparen Sie noch? NEU: GMX Phone_Flat http://www.gmx.net/de/go/telefonie From w.damen at gmail.com Mon Jan 23 11:34:40 2006 From: w.damen at gmail.com (Rinzwind) Date: Mon, 23 Jan 2006 11:34:40 +0100 Subject: [Tutor] Totorial announcement In-Reply-To: <00df01c61fb7$a3855ba0$0b01a8c0@xp> References: <00a501c61f79$49a63110$0b01a8c0@xp> <4677730601221029vbc28d1fyc09c97aab7f33b04@mail.gmail.com> <00df01c61fb7$a3855ba0$0b01a8c0@xp> Message-ID: <4677730601230234k73479d80k1c2acd13e1b5a1de@mail.gmail.com> Saves me ordering the book :-) I saw it on bol.com together with another of your books. Those hours is too much for me otherwise you'd have a Dutch version too :-) From SChitti at manh.com Mon Jan 23 12:30:07 2006 From: SChitti at manh.com (Suri Chitti) Date: Mon, 23 Jan 2006 17:00:07 +0530 Subject: [Tutor] How can I clean the screen Message-ID: I tried os.system('cls')...the screen seemed to hang. -----Original Message----- From: Alan Gauld [mailto:alan.gauld at freenet.co.uk] Sent: Monday, January 23, 2006 3:37 PM To: Suri Chitti; tutor at python.org Subject: Re: [Tutor] How can I clean the screen > If I am executing a python prog from the command line and > need to clear the screen (like using the cls command at the windows cmd Thus should be a FAQ somewhere... Clearing the screen is terminal specific so Python doesn't have a single way to do it. Since you mention Windows I'll assume thats what you are using and suggest you simply use the CLS command via an os.system() call: import os os.system('CLS') If you have Linux substitute 'clear' for CLS Or as a last resort write your own: def cls(rows=100): for row in rows: print If you use curses it has a couple of functions for clearing a window. HTH, Alan G. From alan.gauld at freenet.co.uk Mon Jan 23 12:32:54 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 23 Jan 2006 11:32:54 -0000 Subject: [Tutor] Totorial announcement References: <00a501c61f79$49a63110$0b01a8c0@xp><4677730601221029vbc28d1fyc09c97aab7f33b04@mail.gmail.com><00df01c61fb7$a3855ba0$0b01a8c0@xp> <4677730601230234k73479d80k1c2acd13e1b5a1de@mail.gmail.com> Message-ID: <013701c62010$c06d4530$0b01a8c0@xp> > Saves me ordering the book :-) > I saw it on bol.com together with another of your books. The book is slightly different and has some extra chapters but it is now quite out of date, I recommend the web version (which also has a lot of material not in the book, so swings and roundabouts there...). But I don't have any other books published (yet) the stuff about hypnotism and psychic stuff is another Alan Gauld based in Chicago USA - I get a lot of email for him! :-) Alan G. From jjk_saji at yahoo.com Mon Jan 23 12:41:57 2006 From: jjk_saji at yahoo.com (John Joseph) Date: Mon, 23 Jan 2006 11:41:57 +0000 (GMT) Subject: [Tutor] Searching for email id in MySQL giving wrong results [ Try out pattern Search ] In-Reply-To: <1137954203.31434.8.camel@localhost.localdomain> Message-ID: <20060123114157.19304.qmail@web34807.mail.mud.yahoo.com> Hi Thanks for the tip now I am trying to do pattern matching for MySQL , but I am not getting the result on MySQL , to select for all email starting with jos we do select * from contact where email_id like "jos%"; but I get confused how to use it , while executing it in python , how to call the pattern matching inside mysql query I had added my code Thanks Joseph John *********************************************************** import MySQLdb s_email= raw_input("Enter the some part of the Email to be searched ") db = MySQLdb.connect(host="localhost",user = "john", passwd = "asdlkj", db = 'learnpython') entry = db.cursor() #entry.execute('''SELECT * FROM contact WHERE email_id like %s''', (s_email,)) #s = entry.fetchall() #print s entry.execute('''SELECT * FROM contact WHERE email_id like %s''', (s_email,)) s = entry.fetchall() print s ~ ~ --- "ZIYAD A. M. AL-BATLY" wrote: > On Sun, 2006-01-22 at 12:43 +0000, John Joseph > wrote: > > Hi > Hi John... > > Most of your problems in your code seems to be > caused by a single > mistake. Compare the following two strings and you > should figure out > what's wrong by yourself: > > email_id = 'email at domain.tld' > > wrong_string = '''SELECT s FROM t WHERE > id=%s''' , (email_id) > right_string = '''SELECT s FROM t WHERE > id=%s''' % (email_id) > > print "Wrong:", wrong_string > print "Right:", right_string > > This is the output: > Wrong: ('SELECT s FROM t WHERE id=%s', > 'email at domain.tld') > Right: SELECT s FROM t WHERE > id=email at domain.tld > > Now, which one is the right one? And which one is > the one you want? > > > I suggest you study strings more, especially > concatenation and '%'. > > If you need more help, just post to the mailing list > again. > Ziyad. > > ___________________________________________________________ To help you stay safe and secure online, we've developed the all new Yahoo! Security Centre. http://uk.security.yahoo.com From w.damen at gmail.com Mon Jan 23 13:46:35 2006 From: w.damen at gmail.com (Rinzwind) Date: Mon, 23 Jan 2006 13:46:35 +0100 Subject: [Tutor] Totorial announcement In-Reply-To: <013701c62010$c06d4530$0b01a8c0@xp> References: <00a501c61f79$49a63110$0b01a8c0@xp> <4677730601221029vbc28d1fyc09c97aab7f33b04@mail.gmail.com> <00df01c61fb7$a3855ba0$0b01a8c0@xp> <4677730601230234k73479d80k1c2acd13e1b5a1de@mail.gmail.com> <013701c62010$c06d4530$0b01a8c0@xp> Message-ID: <4677730601230446p53d17d3dhd9b9a248b65a2258@mail.gmail.com> LOL! Did you know I actually thought "wtf and a book about coding and a book about hypnotism? WOW". :D :D :D Well I like books cuz it's easier to carry around inside trains and busses ;) Wim On 1/23/06, Alan Gauld wrote: > > Saves me ordering the book :-) > > I saw it on bol.com together with another of your books. > > The book is slightly different and has some extra chapters but it > is now quite out of date, I recommend the web version (which > also has a lot of material not in the book, so swings and > roundabouts there...). > > But I don't have any other books published (yet) the stuff about > hypnotism and psychic stuff is another Alan Gauld based in > Chicago USA - I get a lot of email for him! :-) > > Alan G. > From mail.roma1 at gmail.com Mon Jan 23 14:05:16 2006 From: mail.roma1 at gmail.com (Ivan Furone) Date: Mon, 23 Jan 2006 14:05:16 +0100 Subject: [Tutor] Totorial announcement Message-ID: <6122a57a0601230505r911f13bn@mail.gmail.com> Sorry to both A.Gauld and Rinzwind for my previous mistake in addressing. Great,Alan,I got pretty much help from your OS tutorial in my past hard times in learning Python. I'm glad you've completed it :) Cheers Ivan From mail.roma1 at gmail.com Mon Jan 23 14:17:07 2006 From: mail.roma1 at gmail.com (Ivan Furone) Date: Mon, 23 Jan 2006 14:17:07 +0100 Subject: [Tutor] How can I clean the screen In-Reply-To: References: Message-ID: <6122a57a0601230517p35d86a6bp@mail.gmail.com> 2006/1/23, Suri Chitti : > > Dear group, > If I am executing a python prog from the command line and > need to clear the screen (like using the cls command at the windows cmd > prompt) midway into the program, how do I do it?? Any inputs will be > greatly appreciated. > Thanks. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Hi there A nice neat trick which is: print '\n' * 100 Will print a hundred lines on the screen,thus shifting the cursor down so the screen will seem to have been cleaned. Or it's possible to implement these lines in a program: import os, platform def clear_screen(): if platform.system() == 'Linux': os.system('clear') if platform.system() == 'Windows': os.system('cls') clear_screen() (Both them are excerpt from the Python Tips and Tricks published from the Italian Python User Group). Cheers Ivan From alan.gauld at freenet.co.uk Mon Jan 23 14:45:46 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 23 Jan 2006 13:45:46 -0000 Subject: [Tutor] How can I clean the screen References: Message-ID: <013b01c62023$50914640$0b01a8c0@xp> > I tried os.system('cls')...the screen seemed to hang. Did you try hitting Enter after it? cls will just clear the screeen... Alan G. -----Original Message----- From: Alan Gauld [mailto:alan.gauld at freenet.co.uk] Sent: Monday, January 23, 2006 3:37 PM To: Suri Chitti; tutor at python.org Subject: Re: [Tutor] How can I clean the screen > If I am executing a python prog from the command line and > need to clear the screen (like using the cls command at the windows cmd Thus should be a FAQ somewhere... Clearing the screen is terminal specific so Python doesn't have a single way to do it. Since you mention Windows I'll assume thats what you are using and suggest you simply use the CLS command via an os.system() call: import os os.system('CLS') If you have Linux substitute 'clear' for CLS Or as a last resort write your own: def cls(rows=100): for row in rows: print If you use curses it has a couple of functions for clearing a window. HTH, Alan G. From edgar.antonio.rv at gmail.com Mon Jan 23 14:59:26 2006 From: edgar.antonio.rv at gmail.com (Edgar Antonio Rodriguez Velazco) Date: Mon, 23 Jan 2006 07:59:26 -0600 Subject: [Tutor] How can I clean the screen Message-ID: <9378d12c0601230559l764e35bclbfd816a96b2020a9@mail.gmail.com> You can use the function system() of the os module. os.system('clear') in Unix or in Windows os.system('clear') -- Edgar A. Rodriguez V. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060123/9210d182/attachment.html From python at venix.com Mon Jan 23 15:15:57 2006 From: python at venix.com (Python) Date: Mon, 23 Jan 2006 09:15:57 -0500 Subject: [Tutor] Searching for email id in MySQL giving wrong results In-Reply-To: <1137954203.31434.8.camel@localhost.localdomain> References: <20060122124323.37411.qmail@web34806.mail.mud.yahoo.com> <1137954203.31434.8.camel@localhost.localdomain> Message-ID: <1138025757.15004.837.camel@www.venix.com> On Sun, 2006-01-22 at 21:23 +0300, ZIYAD A. M. AL-BATLY wrote: > wrong_string = '''SELECT s FROM t WHERE id=%s''' , (email_id) The string is being used in a call to cursor.execute. The email_id is a second parameter getting passed to execute. That is the *correct* approach to use. That is no help in explaining why the SELECT command is failing to return the expected results. -- Lloyd Kvam Venix Corp From ronin_cpim at hotmail.com Mon Jan 23 15:28:50 2006 From: ronin_cpim at hotmail.com (CPIM Ronin) Date: Mon, 23 Jan 2006 09:28:50 -0500 Subject: [Tutor] Linux Python install? In-Reply-To: Message-ID: Sorry to bother the list with so simple a question but on moving to Linux from Windows XP, it's not clear to me how to accomplish a Python install on Linux. On XP it was mostly point and click on a ".msi" file (with msi standing for Microsoft install). I've loaded the latest Fedora/Redhat release on an old AMD machine. How do I install Python such that it shows up as a selection under the Programming task bar with EMACS? I assume I have to do this under root, right? Step by step please. Thanks. _________________________________________________________________ Don’t just search. Find. Check out the new MSN Search! http://search.msn.click-url.com/go/onm00200636ave/direct/01/ From bgailer at alum.rpi.edu Mon Jan 23 16:03:11 2006 From: bgailer at alum.rpi.edu (bob) Date: Mon, 23 Jan 2006 07:03:11 -0800 Subject: [Tutor] PLZ REPLY SOON In-Reply-To: <380-22006112362428973@oneworld.net> References: <380-22006112362428973@oneworld.net> Message-ID: <7.0.0.16.0.20060123065903.01cdc2c8@alum.rpi.edu> At 10:24 PM 1/22/2006, Shalini R wrote: >Hi sir, > I'm new to python & postgres as I've created a form in html & a >table in postgres. There is a field in form which will take multiple >value My guess is that each checkbox needs its own name, rather than all of them using arrFacility. Give that a try. >the problem which i'm facing is i'm getting single value but >when i want multiple values to be inserted to postgres table it is >not happening >the dtml script is > > >
> > > > > > > > > > >
Eno
EmpNamename="txtEmpName">
Facility you want >HRA
>Travel
>Food
>value="Accomodation">Accomodation
> >
State
> >
> > > >-------------- >python script > > >import psycopg >import sys >def add(REQUEST): > try: > con=psycopg.connect("dbname=mission2007 user= >postgres") > cur=con.cursor() > d=[] > d.append(REQUEST.get("txtEmpName")) > d.append(REQUEST.get("arrFacility")) > d.append(REQUEST.get("txtState")) > sql1="select max(eno) from empdetail" > cur.execute(sql1) > eno=cur.fetchone() > sql="insert into empdetail (empname,facility,state) >values('"+REQUEST.get("txtEmpName")+"','"+REQUEST.get("arrFacility")+" >','"+REQUEST.get("txtState")+"')" > return sql > cur.execute(sql) > con.commit() > cur.close() > con.close() > return "You had successfully entered data" > > > > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor From python at venix.com Mon Jan 23 16:06:24 2006 From: python at venix.com (Python) Date: Mon, 23 Jan 2006 10:06:24 -0500 Subject: [Tutor] Linux Python install? In-Reply-To: References: Message-ID: <1138028784.15004.851.camel@www.venix.com> On Mon, 2006-01-23 at 09:28 -0500, CPIM Ronin wrote: > Sorry to bother the list with so simple a question but on moving to Linux > from Windows XP, it's not clear to me how to accomplish a Python install on > Linux. On XP it was mostly point and click on a ".msi" file (with msi > standing for Microsoft install). I've loaded the latest Fedora/Redhat > release on an old AMD machine. How do I install Python such that it shows up > as a selection under the Programming task bar with EMACS? I assume you are using yum for package management. It should have been installed by default. As root, you can issue the command yum install python python-docs python-devel python-tools The package yumex provides a GUI interface to the yum package manager. You can think of yumex as the Windows "Add/Remove Programs" application on steroids. yum install yumex The yumex install view with a filter of python will provide an extensive list of additional python packages. Finally, I do not know if this includes the best python integration with EMACS. > I assume I have to do this under root, right? > > Step by step please. > > Thanks. > > _________________________________________________________________ > Dont just search. Find. Check out the new MSN Search! > http://search.msn.click-url.com/go/onm00200636ave/direct/01/ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From 3dbernard at gmail.com Mon Jan 23 16:15:56 2006 From: 3dbernard at gmail.com (Bernard Lebel) Date: Mon, 23 Jan 2006 10:15:56 -0500 Subject: [Tutor] Starbucks does not use two-phase commit In-Reply-To: <61d0e2b40601201428g469dbfd1v4b772fcfdbc759d0@mail.gmail.com> References: <61d0e2b40601200913q6d3b3ff5s471a618dc895b82@mail.gmail.com> <61d0e2b40601201428g469dbfd1v4b772fcfdbc759d0@mail.gmail.com> Message-ID: <61d0e2b40601230715p74450d03m4045321eed099c31@mail.gmail.com> Hi Danny, Just to report something regarding the code you have provided. I noticed that when I do a keyboard interrupt, I get the keyboard interrupt exception messages, but after that it keeps hangning and never returns to the command line input mode. I have to close the shell to really end the program afaics. After reading Todd's emails, I wondered if it had something to do with how the threaded queue is started. In your example, you use: Thread( target = ).start() While I have been using the thread module, using: thread.start_new( , ( , ) ) When I implemented your example in my program, I also used your approach, and started having the hanging behavior. I reconverted the thread spawn to my own approch, just to see if it would make a difference. And with my approach, the keyboard interrupts really aborts the program, the shell returns to command line input mode. Any idea why those two methods of starting threads can behave so differently? Thanks Bernard On 1/20/06, Bernard Lebel <3dbernard at gmail.com> wrote: > Ultra-nice Danny, it works (ie: I have implemented your example in my > code and it runs as it should). > > I have to admit that I'm a little bit puzzled by this chain of > instantiation and argument passing, however I intend to decipher it > properly. > > > Thanks again! > Bernard > > > > > On 1/20/06, Danny Yoo wrote: > > > > > > On Fri, 20 Jan 2006, Bernard Lebel wrote: > > > > > So have written a little test script. The fact is that I want to be able > > > to manage the same queue from separate threads. Below is an example of > > > what my real program is doing: > > > > > > Hi Bernard, > > > > One problem is that there's a single outputQueue being presented to get > > results back from the Server. > > > > A different approach is to use a lot of outputQueues. *grin* > > > > The idea is that when we send a job submission, we immediately get back a > > "ticket". We can then use this ticket to claim() our result. Each ticket > > is unique to a job submission, so we shouldn't see any bleeding going on > > between clients. > > > > > > Here's some code that implements this idea. It's a little complex, so you > > may want to read through it slowly: > > > > > > ################################################ > > from threading import Thread > > from Queue import Queue > > > > > > class Ticket: > > """A small token that we can use to claim our result.""" > > def __init__(self, q): > > self.q = q > > self.result = None > > self.done = False > > > > def claim(self): > > if not self.done: > > self.result = self.q.get() > > self.done = True > > return self.result > > > > > > class Server: > > _QUIT_JOB = ['Quit!'] > > > > def __init__(self): > > """A queue will contain 2-tuples of (job, outputQueue) > > elements.""" > > self.queue = Queue() > > > > > > def startServer(self): > > """Brings the server online.""" > > Thread(target=self._jobLoop).start() > > > > > > def schedule(self, job): > > """Schedules a job to be done and returns a ticket that the > > client can use later to claim the result of the job.""" > > outputQueue = Queue() > > self.queue.put((job, outputQueue)) > > return Ticket(outputQueue) > > > > > > def scheduleShutdown(self): > > """Add a 'job' that shuts the system down.""" > > self.queue.put((Server._QUIT_JOB, None)) > > > > > > def _jobLoop(self): > > """Continue looping through tasks.""" > > while True: > > print "Looping..." > > (nextJob, outputQueue) = self.queue.get() > > if nextJob is Server._QUIT_JOB: > > return > > returnValue = self._doJob(nextJob) > > outputQueue.put(returnValue) > > > > > > def _doJob(self, job): > > print "I'm doing", job > > return job + job ## something to show that we're doing something > > > > > > > > def separateCaller(server): > > for i in range(1000, 1004 + 1): > > print "--Separate caller asks %d" % i > > ticket = server.schedule(str(i)) > > print "--Separate caller got %s" % ticket.claim() > > > > > > if __name__ == '__main__': > > server = Server() > > server.startServer() > > Thread(target=separateCaller, args=(server,)).start() > > > > result1 = server.schedule("1") > > print "result1: %s" % result1.claim() > > result2 = server.schedule("2") > > print "result2: %s" % result2.claim() > > result3 = server.schedule("3") > > print "result3: %s" % result3.claim() > > server.scheduleShutdown() > > ############################################################# > > > > > > Play around with this a bit and see if it makes sense to you. You might > > also be interested in the amusing article "Starbucks Does Not Use > > Two-Phase Commit": > > > > http://www.eaipatterns.com/ramblings/18_starbucks.html > > > > as it touches on concepts in the code. > > > > > > If you have more questions, please feel free to ask! > > > > > From mhansen at cso.atmel.com Mon Jan 23 17:14:44 2006 From: mhansen at cso.atmel.com (Mike Hansen) Date: Mon, 23 Jan 2006 09:14:44 -0700 Subject: [Tutor] python-based system programming and admin? In-Reply-To: References: Message-ID: <43D500F4.8090605@cso.atmel.com> > ------------------------------------------------------------------------ > > Subject: > [Tutor] python-based system programming and admin? > From: > Neal McBurnett > Date: > Fri, 20 Jan 2006 21:01:03 -0700 (MST) > To: > tutor > > To: > tutor > > > I'm an experienced linux guy, with lots of python interest and some > python experience. > > I'm helping a colleague develop software to run on our linux server. > He has python skill, but doesn't know the shell or linux very well at > all. > > I'd like to give him a secure, safe, flexible development environment > on the serve, (which does audio streaming and other fun things). > > At the moment, he has an account and can connect from his mac via ssh, > and copy files back and forth (ftp-like stuff - I forget which ssh > client). But he doesn't want to log in to a bash shell and learn a > whole new way to do things. But he does want to run programs. > > Editing python scripts spawned by cron is one of the goals. > But developing them by waiting for cron to fire and send the output > via email is pretty painful.... > > The server currently doesn't need to run a web server, and I'm > reluctant to introduce new services that have much security risk > associated with them, but something like that seems like a > possibility. > > One idea that just popped in my brain is to give him a python login > shell on linux - any advice on how to do that? > > Other possibilities, I guess: > > - An https-based web server with and mod-python, somehow configured > so that his jobs run as him. > > - a pure-python server (via twisted?) running as him > > - moinmoin or the like > > - zope or plone (not sounding very simple any more, but I've done a > bit of this ....) > > What would be the safest, simplest solution that was adequate for > providing a reasonable development environment? > > Any ideas I haven't thought of yet? > > Cheers, > > Neal McBurnett http://bcn.boulder.co.us/~neal/ Sorry to pop in late on this discussion. I get the digest and it's sent to my work, so I got all weekend's digests to catch up on. Rather than having you bend over backwards setting up a weird environment, I think your colleague should learn some basic unix commands. Since he's running a Mac(I'm assuming OS X), the basic commands will help him with Darwin OS which is underneath the Mac GUI. Darwin is a flavor of BSD, and BSD is a flavor of unix. There's not a lot to learn. Basic file management(copy, delete, move, rename), setting the permissions(chmod, chown), navigating the directory structure(cd, ls), and finally running a python program. Some editors have FTP built into them, so he could write the code on his mac and have the editor FTP the file to his account on the server. He could then telnet to the server and run the script. Mike From alan.gauld at freenet.co.uk Mon Jan 23 19:17:26 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 23 Jan 2006 18:17:26 -0000 Subject: [Tutor] Searching for email id in MySQL giving wrong results References: <20060122124323.37411.qmail@web34806.mail.mud.yahoo.com><1137954203.31434.8.camel@localhost.localdomain> <1138025757.15004.837.camel@www.venix.com> Message-ID: <016601c62049$438cf310$0b01a8c0@xp> > On Sun, 2006-01-22 at 21:23 +0300, ZIYAD A. M. AL-BATLY wrote: >> wrong_string = '''SELECT s FROM t WHERE id=%s''' , (email_id) > > The string is being used in a call to cursor.execute. The email_id is a > second parameter getting passed to execute. That is the *correct* > approach to use. Nope, sorry. This sends the string SELECT ..... id=%s something at somewhere.whatever ie the %s is kept in the string, not what is wanted. The OP must replace the comma with a % character for the string substitution to take place. > That is no help in explaining why the SELECT command is failing to > return the expected results. The rogue %s in the select string will mess things up. Alan G. From alan.gauld at freenet.co.uk Mon Jan 23 19:23:51 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 23 Jan 2006 18:23:51 -0000 Subject: [Tutor] Linux Python install? References: Message-ID: <016a01c6204a$29639a60$0b01a8c0@xp> > from Windows XP, it's not clear to me how to accomplish a Python install > on Linux. That depends on your distro. Each distribution has its own package management tool. eg. On RedHat its rpm(and there is a GUI tool too), on Debian its getappt or somesuch... Python should already be installed on most distros, but of course you may want a more recent version. > standing for Microsoft install). I've loaded the latest Fedora/Redhat > release on an old AMD machine. How do I install Python such that it shows > up as a selection under the Programming task bar with EMACS? No idea how to put it into Emacs automatically. I suspect that needs some editing of the .emacs file or somesuch. Some packages may do that for you but its beyond my outdated knowledge of Linux... I just run Linux, I don't tweak it very much. > I assume I have to do this under root, right? Not necessarily, but if you use another user you will sometimes find that you don't have access to the default fiolder locations. And even ifg you do only that user will be able to run the application. So root is usually best. HTH, Alan G From python at venix.com Mon Jan 23 19:48:56 2006 From: python at venix.com (Python) Date: Mon, 23 Jan 2006 13:48:56 -0500 Subject: [Tutor] Searching for email id in MySQL giving wrong results In-Reply-To: <016601c62049$438cf310$0b01a8c0@xp> References: <20060122124323.37411.qmail@web34806.mail.mud.yahoo.com> <1137954203.31434.8.camel@localhost.localdomain> <1138025757.15004.837.camel@www.venix.com> <016601c62049$438cf310$0b01a8c0@xp> Message-ID: <1138042136.15004.875.camel@www.venix.com> On Mon, 2006-01-23 at 18:17 +0000, Alan Gauld wrote: > > On Sun, 2006-01-22 at 21:23 +0300, ZIYAD A. M. AL-BATLY wrote: > >> wrong_string = '''SELECT s FROM t WHERE id=%s''' , (email_id) > > > > The string is being used in a call to cursor.execute. The email_id is a > > second parameter getting passed to execute. That is the *correct* > > approach to use. > > Nope, sorry. > This sends the string > > SELECT ..... id=%s something at somewhere.whatever > > ie the %s is kept in the string, not what is wanted. > > The OP must replace the comma with a % character for the string > substitution to take place. > > > That is no help in explaining why the SELECT command is failing to > > return the expected results. > > The rogue %s in the select string will mess things up. > > Alan G. -- Lloyd Kvam Venix Corp From dyoo at hkn.eecs.berkeley.edu Mon Jan 23 19:56:06 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 23 Jan 2006 10:56:06 -0800 (PST) Subject: [Tutor] Starbucks does not use two-phase commit In-Reply-To: <61d0e2b40601230715p74450d03m4045321eed099c31@mail.gmail.com> Message-ID: > I noticed that when I do a keyboard interrupt, I get the keyboard > interrupt exception messages, but after that it keeps hangning and never > returns to the command line input mode. I have to close the shell to > really end the program afaics. Hi Bernard, When we're using the high-level 'threading' interface, the server thread --- which runs independently of the main thread --- will continue to run until it's shut down. But we can call setDaemon() on the server's thread to allow Python to exit. Look at the bottom of: http://www.python.org/doc/lib/thread-objects.html So we can modify server.startServer() to flag the server thread as a daemon: def startServer(self): t = Thread(thread=self._jobLoop) t.setDaemon(True) t.start() > While I have been using the thread module, using: > > thread.start_new( , ( , ) ) > > When I implemented your example in my program, I also used your > approach, and started having the hanging behavior. I reconverted the > thread spawn to my own approch, just to see if it would make a > difference. The low level 'thread' library is a bit more platform specific. Here's what the documentation says: (http://www.python.org/doc/lib/module-thread.html) """When the main thread exits, it is system defined whether the other threads survive. On SGI IRIX using the native thread implementation, they survive. On most other systems, they are killed without executing try ... finally clauses or executing object destructors.""" Does this make sense? From python at venix.com Mon Jan 23 20:00:52 2006 From: python at venix.com (Python) Date: Mon, 23 Jan 2006 14:00:52 -0500 Subject: [Tutor] Searching for email id in MySQL giving wrong results In-Reply-To: <016601c62049$438cf310$0b01a8c0@xp> References: <20060122124323.37411.qmail@web34806.mail.mud.yahoo.com> <1137954203.31434.8.camel@localhost.localdomain> <1138025757.15004.837.camel@www.venix.com> <016601c62049$438cf310$0b01a8c0@xp> Message-ID: <1138042852.15004.887.camel@www.venix.com> On Mon, 2006-01-23 at 18:17 +0000, Alan Gauld wrote: > > On Sun, 2006-01-22 at 21:23 +0300, ZIYAD A. M. AL-BATLY wrote: > >> wrong_string = '''SELECT s FROM t WHERE id=%s''' , (email_id) > > > > The string is being used in a call to cursor.execute. The email_id is a > > second parameter getting passed to execute. That is the *correct* > > approach to use. > > Nope, sorry. > This sends the string > > SELECT ..... id=%s something at somewhere.whatever > > ie the %s is kept in the string, not what is wanted. > > The OP must replace the comma with a % character for the string > substitution to take place. The wrong_string line was lifted from the following code in the OP. entry = db.cursor() entry.execute("""SELECT * FROM contact WHERE email_id = %s""", (s_email,)) The execute method will handle the string substitution. This is better than doing it yourself, because execute will deal with any quoting issues for feeding the data to the database. I should have included the original code as I did here. Sorry if I created any confusion as related to regular Python string substitution. It is a very common mistake for people to do the SQL string interpolation themselves as opposed to leaving it for the execute method. > > > That is no help in explaining why the SELECT command is failing to > > return the expected results. > > The rogue %s in the select string will mess things up. > > Alan G. -- Lloyd Kvam Venix Corp From rondosxx at yahoo.com Mon Jan 23 20:19:59 2006 From: rondosxx at yahoo.com (ron) Date: Mon, 23 Jan 2006 11:19:59 -0800 (PST) Subject: [Tutor] Python install on Linux Message-ID: <20060123191959.15719.qmail@web50810.mail.yahoo.com> A simple way to migrate to Linux and get a recent version of Python by default would be to download a copy of Ubuntu Linux. You can burn it onto a CD, then pop it ino the cd drive and boot it on your Windows machine. It runs in a virtual machine, so you are assured that your Windows installation will never become corrupted by Linux. Or you can load it directly onto your hard drive in place of Windows. Python is loaded by default. Ubuntu is designed to ease your migration to Linux, You should be fairly comfortably up and running within two hours. I have it on my laptop, and it boots up in just over a minute. http://www.ubuntulinux.org/ __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From alan.gauld at freenet.co.uk Mon Jan 23 20:46:29 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 23 Jan 2006 19:46:29 -0000 Subject: [Tutor] Searching for email id in MySQL giving wrong results References: <20060122124323.37411.qmail@web34806.mail.mud.yahoo.com> <1137954203.31434.8.camel@localhost.localdomain> <1138025757.15004.837.camel@www.venix.com> <016601c62049$438cf310$0b01a8c0@xp> <1138042852.15004.887.camel@www.venix.com> Message-ID: <017c01c62055$b4b7c810$0b01a8c0@xp> >> >> wrong_string = '''SELECT s FROM t WHERE id=%s''' , (email_id) >> > >> The OP must replace the comma with a % character for the string >> substitution to take place. > > The wrong_string line was lifted from the following code in the OP. > > entry = db.cursor() > entry.execute("""SELECT * FROM contact WHERE email_id = %s""", > (s_email,)) > Ah I see. Yes that's a different proposition entirely! I really should read the whole thread before jumping in... :-( Alan G. From 3dbernard at gmail.com Mon Jan 23 20:55:37 2006 From: 3dbernard at gmail.com (Bernard Lebel) Date: Mon, 23 Jan 2006 14:55:37 -0500 Subject: [Tutor] Starbucks does not use two-phase commit In-Reply-To: References: <61d0e2b40601230715p74450d03m4045321eed099c31@mail.gmail.com> Message-ID: <61d0e2b40601231155y7b955053gfbf1c10c8c85d280@mail.gmail.com> Hi Danny, Yes that makes sense, but...... what is a "daemon"? Sorry if this is super basic question. Thanks Bernard On 1/23/06, Danny Yoo wrote: > > > > I noticed that when I do a keyboard interrupt, I get the keyboard > > interrupt exception messages, but after that it keeps hangning and never > > returns to the command line input mode. I have to close the shell to > > really end the program afaics. > > Hi Bernard, > > When we're using the high-level 'threading' interface, the server thread > --- which runs independently of the main thread --- will continue to run > until it's shut down. But we can call setDaemon() on the server's thread > to allow Python to exit. Look at the bottom of: > > http://www.python.org/doc/lib/thread-objects.html > > So we can modify server.startServer() to flag the server thread as a > daemon: > > def startServer(self): > t = Thread(thread=self._jobLoop) > t.setDaemon(True) > t.start() > > > > > While I have been using the thread module, using: > > > > thread.start_new( , ( , ) ) > > > > When I implemented your example in my program, I also used your > > approach, and started having the hanging behavior. I reconverted the > > thread spawn to my own approch, just to see if it would make a > > difference. > > The low level 'thread' library is a bit more platform specific. Here's > what the documentation says: > > (http://www.python.org/doc/lib/module-thread.html) > > """When the main thread exits, it is system defined whether the other > threads survive. On SGI IRIX using the native thread implementation, > they survive. On most other systems, they are killed without > executing try ... finally clauses or executing object destructors.""" > > > Does this make sense? > > From python at venix.com Mon Jan 23 21:16:08 2006 From: python at venix.com (Python) Date: Mon, 23 Jan 2006 15:16:08 -0500 Subject: [Tutor] Searching for email id in MySQL giving wrong results In-Reply-To: <017c01c62055$b4b7c810$0b01a8c0@xp> References: <20060122124323.37411.qmail@web34806.mail.mud.yahoo.com> <1137954203.31434.8.camel@localhost.localdomain> <1138025757.15004.837.camel@www.venix.com> <016601c62049$438cf310$0b01a8c0@xp> <1138042852.15004.887.camel@www.venix.com> <017c01c62055$b4b7c810$0b01a8c0@xp> Message-ID: <1138047368.15004.904.camel@www.venix.com> On Mon, 2006-01-23 at 19:46 +0000, Alan Gauld wrote: > >> >> wrong_string = '''SELECT s FROM t WHERE id=%s''' , (email_id) > >> > > >> The OP must replace the comma with a % character for the string > >> substitution to take place. > > > > The wrong_string line was lifted from the following code in the OP. > > > > entry = db.cursor() > > entry.execute("""SELECT * FROM contact WHERE email_id = %s""", > > (s_email,)) > > > > Ah I see. Yes that's a different proposition entirely! > I really should read the whole thread before jumping in... :-( > > Alan G. > Well I created the trap by not pasting in the execute call and posting what was on its face an invalid piece of Python coding. -- Lloyd Kvam Venix Corp From cspears2002 at yahoo.com Mon Jan 23 21:41:23 2006 From: cspears2002 at yahoo.com (Christopher Spears) Date: Mon, 23 Jan 2006 12:41:23 -0800 (PST) Subject: [Tutor] Why doesn't this work? Message-ID: <20060123204124.39593.qmail@web51609.mail.yahoo.com> I copied this code from Learning Python while learning about extending types by subclassing: class Set(list): def __init__(self, value=[]): list.__init__([]) self.concat(value) def intersect(self, other): res = [] for x in self: if x in other: res.append(x) return Set(res) def union(self, other): res = Set(self) res.concat(other) return res def concat(self, value): for x in value: if not x in self: self.append(x) def __and__(self, other): return self.intersect(other) def __or__(self, other): return self.union(other) def __repr__(self): return 'Set:' + list.__repr__(self) if __name__ == '__main__': x = Set([1,3,5,7]) y = Set([2,1,4,5,6]) print x, y, len(x) print x.intersect(y), y.union(x) print x & y, x | y x.reverse(); print x Here is the result: cspears at iaws09:/imports/home/cspears/Documents/Python/chap23> python setsubclass.py [1, 3, 5, 7] [2, 1, 4, 5, 6] 4 [1, 5] [2, 1, 4, 5, 6, 3, 7] Traceback (most recent call last): File "setsubclass.py", line 32, in ? print x & y, x | y TypeError: unsupported operand type(s) for &: 'Set' and 'Set' According to the book, here is what I should get: Set:[1, 3, 5, 7] Set:[2, 1, 4, 5, 6] 4 Set:[1, 5] Set:[2, 1, 4, 5, 6, 3, 7] Set:[1, 5] Set:[1, 3, 5, 7, 2, 4, 6] Set:[7, 5, 3, 1] Problem 1: Why isn't "Set:" being printed? I thought def __repr__(self): return 'Set:' + list.__repr__(self) would facilitate that. Problem 2: What is causing the TypeError? I'm pretty sure I copied this exactly from the book, so I'm not sure what is not working. From jason.massey at gmail.com Mon Jan 23 21:53:48 2006 From: jason.massey at gmail.com (Jason Massey) Date: Mon, 23 Jan 2006 14:53:48 -0600 Subject: [Tutor] Why doesn't this work? In-Reply-To: <20060123204124.39593.qmail@web51609.mail.yahoo.com> References: <20060123204124.39593.qmail@web51609.mail.yahoo.com> Message-ID: <7e3eab2c0601231253i5d94c9f6r2a117a074e48c457@mail.gmail.com> Christopher, I copied and pasted your code and it worked only a few modifications. The thing I had to change was the indention level of the: def __and__(self, other): return self.intersect(other) def __or__(self, other): return self.union(other) def __repr__(self): return 'Set:' + list.__repr__(self) statements. These statements need to be on the same indention level as your __init__, intersection and union satements. Here's what I got: class Set(list): def __init__(self, value=[]): list.__init__([]) self.concat(value) def intersect(self, other): res = [] for x in self: if x in other: res.append(x) return Set(res) def union(self, other): res = Set(self) res.concat(other) return res def concat(self, value): for x in value: if not x in self: self.append(x) def __and__(self, other): return self.intersect(other) def __or__(self, other): return self.union(other) def __repr__(self): return 'Set:' + list.__repr__(self) if __name__ == '__main__': x = Set([1,3,5,7]) y = Set([2,1,4,5,6]) print x, y, len(x) print x.intersect(y), y.union(x) print x & y, x | y x.reverse(); print x On 1/23/06, Christopher Spears wrote: > > I copied this code from Learning Python while learning > about extending types by subclassing: > > class Set(list): > def __init__(self, value=[]): > list.__init__([]) > self.concat(value) > > def intersect(self, other): > res = [] > for x in self: > if x in other: > res.append(x) > return Set(res) > > def union(self, other): > res = Set(self) > res.concat(other) > return res > > def concat(self, value): > for x in value: > if not x in self: > self.append(x) > > def __and__(self, other): return self.intersect(other) > def __or__(self, other): return self.union(other) > def __repr__(self): return 'Set:' + > list.__repr__(self) > > if __name__ == '__main__': > x = Set([1,3,5,7]) > y = Set([2,1,4,5,6]) > print x, y, len(x) > print x.intersect(y), y.union(x) > print x & y, x | y > x.reverse(); print x > > Here is the result: > > cspears at iaws09:/imports/home/cspears/Documents/Python/chap23> > python setsubclass.py > [1, 3, 5, 7] [2, 1, 4, 5, 6] 4 > [1, 5] [2, 1, 4, 5, 6, 3, 7] > Traceback (most recent call last): > File "setsubclass.py", line 32, in ? > print x & y, x | y > TypeError: unsupported operand type(s) for &: 'Set' > and 'Set' > > According to the book, here is what I should get: > > Set:[1, 3, 5, 7] Set:[2, 1, 4, 5, 6] 4 > Set:[1, 5] Set:[2, 1, 4, 5, 6, 3, 7] > Set:[1, 5] Set:[1, 3, 5, 7, 2, 4, 6] > Set:[7, 5, 3, 1] > > Problem 1: Why isn't "Set:" being printed? I thought > > > def __repr__(self): return 'Set:' + > list.__repr__(self) > > would facilitate that. > > Problem 2: What is causing the TypeError? > > I'm pretty sure I copied this exactly from the book, > so I'm not sure what is not working. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060123/2e896968/attachment.html From dyoo at hkn.eecs.berkeley.edu Mon Jan 23 22:05:43 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 23 Jan 2006 13:05:43 -0800 (PST) Subject: [Tutor] Starbucks does not use two-phase commit In-Reply-To: <61d0e2b40601231155y7b955053gfbf1c10c8c85d280@mail.gmail.com> Message-ID: On Mon, 23 Jan 2006, Bernard Lebel wrote: > Yes that makes sense, but...... what is a "daemon"? Sorry if this is > super basic question. According to: http://docs.python.org/lib/thread-objects.html """A thread can be flagged as a ``daemon thread''. The significance of this flag is that the entire Python program exits when only daemon threads are left. The initial value is inherited from the creating thread. The flag can be set with the setDaemon() method and retrieved with the isDaemon() method.""" So that's what "daemon" technically does when we apply that term it to a thread. But what it means to us humans is up to interpretation: I think of daemon threads as being more "ephemeral" than other threads. Not sure if that makes any sense to anyone besides myself, though. *grin* There's a traditional use of the word "daemon" that deals with programs that run in the background: http://en.wikipedia.org/wiki/Daemon_(computer_software) so the word "daemon" is, like most words, a bit overloaded. *grin* From carroll at tjc.com Mon Jan 23 22:15:21 2006 From: carroll at tjc.com (Terry Carroll) Date: Mon, 23 Jan 2006 13:15:21 -0800 (PST) Subject: [Tutor] Totorial announcement In-Reply-To: <013701c62010$c06d4530$0b01a8c0@xp> Message-ID: On Mon, 23 Jan 2006, Alan Gauld wrote: > But I don't have any other books published (yet) the stuff about > hypnotism and psychic stuff is another Alan Gauld based in > Chicago USA - I get a lot of email for him! :-) A friend of mine is the author of "Just Java," "Not Just Java," "Expert C Programming," and "Peter van der Linden's Guide to Linux." When looking up his books on Amazon, I found "Great Lakes Ships We Remember" and "Forest and Shade Trees of Iowa" by an entirely different Peter van der Linden. "The Official Handbook of Practical Jokes" is his, though. (BTW, each of Peter's technical books is highly recommended, if you're in the market for a book covering that subject matter.) From cspears2002 at yahoo.com Mon Jan 23 22:29:28 2006 From: cspears2002 at yahoo.com (Christopher Spears) Date: Mon, 23 Jan 2006 13:29:28 -0800 (PST) Subject: [Tutor] Why doesn't this work? In-Reply-To: <7e3eab2c0601231253i5d94c9f6r2a117a074e48c457@mail.gmail.com> Message-ID: <20060123212928.49715.qmail@web51604.mail.yahoo.com> Thanks! Is there a name for the type of myopia that develops after staring at the computer screen too long? -Chris --- Jason Massey wrote: > Christopher, > > I copied and pasted your code and it worked only a > few modifications. The > thing I had to change was the indention level of > the: > > def __and__(self, other): return > self.intersect(other) > def __or__(self, other): return self.union(other) > def __repr__(self): return 'Set:' + > list.__repr__(self) > > statements. These statements need to be on the same > indention level as your > __init__, intersection and union satements. > > Here's what I got: > > class Set(list): > def __init__(self, value=[]): > list.__init__([]) > self.concat(value) > > def intersect(self, other): > res = [] > for x in self: > if x in other: > res.append(x) > return Set(res) > > def union(self, other): > res = Set(self) > res.concat(other) > return res > > def concat(self, value): > for x in value: > if not x in self: > self.append(x) > > def __and__(self, other): return > self.intersect(other) > def __or__(self, other): return > self.union(other) > def __repr__(self): return 'Set:' + > list.__repr__(self) > > if __name__ == '__main__': > x = Set([1,3,5,7]) > y = Set([2,1,4,5,6]) > print x, y, len(x) > print x.intersect(y), y.union(x) > print x & y, x | y > x.reverse(); > print x > > On 1/23/06, Christopher Spears > wrote: > > > > I copied this code from Learning Python while > learning > > about extending types by subclassing: > > > > class Set(list): > > def __init__(self, value=[]): > > list.__init__([]) > > self.concat(value) > > > > def intersect(self, other): > > res = [] > > for x in self: > > if x in other: > > res.append(x) > > return Set(res) > > > > def union(self, other): > > res = Set(self) > > res.concat(other) > > return res > > > > def concat(self, value): > > for x in value: > > if not x in self: > > self.append(x) > > > > def __and__(self, other): return > self.intersect(other) > > def __or__(self, other): return self.union(other) > > def __repr__(self): return 'Set:' + > > list.__repr__(self) > > > > if __name__ == '__main__': > > x = Set([1,3,5,7]) > > y = Set([2,1,4,5,6]) > > print x, y, len(x) > > print x.intersect(y), y.union(x) > > print x & y, x | y > > x.reverse(); print x > > > > Here is the result: > > > > > cspears at iaws09:/imports/home/cspears/Documents/Python/chap23> > > python setsubclass.py > > [1, 3, 5, 7] [2, 1, 4, 5, 6] 4 > > [1, 5] [2, 1, 4, 5, 6, 3, 7] > > Traceback (most recent call last): > > File "setsubclass.py", line 32, in ? > > print x & y, x | y > > TypeError: unsupported operand type(s) for &: > 'Set' > > and 'Set' > > > > According to the book, here is what I should get: > > > > Set:[1, 3, 5, 7] Set:[2, 1, 4, 5, 6] 4 > > Set:[1, 5] Set:[2, 1, 4, 5, 6, 3, 7] > > Set:[1, 5] Set:[1, 3, 5, 7, 2, 4, 6] > > Set:[7, 5, 3, 1] > > > > Problem 1: Why isn't "Set:" being printed? I > thought > > > > > > def __repr__(self): return 'Set:' + > > list.__repr__(self) > > > > would facilitate that. > > > > Problem 2: What is causing the TypeError? > > > > I'm pretty sure I copied this exactly from the > book, > > so I'm not sure what is not working. > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > "I'm the last person to pretend that I'm a radio. I'd rather go out and be a color television set." -David Bowie "Who dares wins" -British military motto "I generally know what I'm doing." -Buster Keaton From 3dbernard at gmail.com Mon Jan 23 23:21:07 2006 From: 3dbernard at gmail.com (Bernard Lebel) Date: Mon, 23 Jan 2006 17:21:07 -0500 Subject: [Tutor] Starbucks does not use two-phase commit In-Reply-To: References: <61d0e2b40601231155y7b955053gfbf1c10c8c85d280@mail.gmail.com> Message-ID: <61d0e2b40601231421q1cbddbdch9e2cc6764fab391b@mail.gmail.com> Thanks a lot Danny. Bernard On 1/23/06, Danny Yoo wrote: > > > On Mon, 23 Jan 2006, Bernard Lebel wrote: > > > Yes that makes sense, but...... what is a "daemon"? Sorry if this is > > super basic question. > > According to: > > http://docs.python.org/lib/thread-objects.html > > """A thread can be flagged as a ``daemon thread''. The significance of > this flag is that the entire Python program exits when only daemon > threads are left. The initial value is inherited from the creating > thread. The flag can be set with the setDaemon() method and retrieved > with the isDaemon() method.""" > > So that's what "daemon" technically does when we apply that term it to a > thread. > > > But what it means to us humans is up to interpretation: I think of daemon > threads as being more "ephemeral" than other threads. Not sure if that > makes any sense to anyone besides myself, though. *grin* > > There's a traditional use of the word "daemon" that deals with programs > that run in the background: > > http://en.wikipedia.org/wiki/Daemon_(computer_software) > > so the word "daemon" is, like most words, a bit overloaded. *grin* > > From benvinger at yahoo.co.uk Mon Jan 23 23:29:11 2006 From: benvinger at yahoo.co.uk (Ben Vinger) Date: Mon, 23 Jan 2006 22:29:11 +0000 (GMT) Subject: [Tutor] passwords in scripts In-Reply-To: <6122a57a0601211816t591d650ft@mail.gmail.com> Message-ID: <20060123222911.65191.qmail@web25805.mail.ukl.yahoo.com> Hi Ivan I'm not sure I understand what you are saying here. Surely if the file is compiled it can just run (and will only need to be RE-compiled when I have to change the code (such as when one of the servers has their password changed). I would never need to de-compile, because I'll just keep a copy of the file on a memory stick, edit it there, compile it and replace the current compiled file with the newly compiled file. Not that I know anything about compiling Python programs, I just want to know if this is a possibility Thanks Ben --- Ivan Furone wrote: > 2006/1/21, Ben Vinger : > > Hello > > > > I've written a couple of scripts that check log > files > > on our WIndows and Unix servers. These scripts > have > > plain text passwords in them, so anyone who can > access > > the filesystem of the Windows server that runs the > > scripts can discover the passwords of the servers. > > Is there a way to hide/encrypt these passwords? > Or > > can the scripts be converted to compiled code in > order > > for the passwords to be hidden? > > > > > > Thanks > > Ben > > > > > > Hello, > Compiling a file in python is a big time > loss,because there's not a > built-in function for decompiling,but you can just > use the 'dis'module > for disassembling it and the result is always > different from the > original,because it uses Abstract Source Tree syntax > in spite of > Python language for translating the bytecode;on the > other hand it > wouldn't secure the file itself from being accessed > but makes it > useless IMHO.Thus,with a slight impact on > complexity,a module with the > crypted passwords would be imported, which would > proceed for checking > the passwords and exporting them in a StringIO > object at runtime.For > enhancing security,once used it could be removed and > used again when > needed,without removing the scripts themselves.You > can check the > 'crypt' module for this task. > Cheers, > Ivan > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > ___________________________________________________________ Win a BlackBerry device from O2 with Yahoo!. Enter now. http://www.yahoo.co.uk/blackberry From zamb at saudi.net.sa Mon Jan 23 23:38:57 2006 From: zamb at saudi.net.sa (ZIYAD A. M. AL-BATLY) Date: Tue, 24 Jan 2006 01:38:57 +0300 Subject: [Tutor] Searching for email id in MySQL giving wrong results In-Reply-To: <1138042852.15004.887.camel@www.venix.com> References: <20060122124323.37411.qmail@web34806.mail.mud.yahoo.com> <1137954203.31434.8.camel@localhost.localdomain> <1138025757.15004.837.camel@www.venix.com> <016601c62049$438cf310$0b01a8c0@xp> <1138042852.15004.887.camel@www.venix.com> Message-ID: <1138055937.13603.22.camel@localhost.localdomain> On Mon, 2006-01-23 at 14:00 -0500, Python wrote: > The wrong_string line was lifted from the following code in the OP. > > entry = db.cursor() > entry.execute("""SELECT * FROM contact WHERE email_id = %s""", (s_email,)) > > The execute method will handle the string substitution. This is better > than doing it yourself, because execute will deal with any quoting > issues for feeding the data to the database. > > I should have included the original code as I did here. Sorry if I > created any confusion as related to regular Python string substitution. > > It is a very common mistake for people to do the SQL string > interpolation themselves as opposed to leaving it for the execute > method. > Okay, here's a quote from the definition of "execute()": def execute(self, query, args=None): """Execute a query. query -- string, query to execute on server args -- optional sequence or mapping, parameters to use with query. Note: If args is a sequence, then %s must be used as the parameter placeholder in the query. If a mapping is used, %(key)s must be used as the placeholder. Returns long integer rows affected, if any""" So, my answer is correct. And it seems there are other solutions (using sequences and "%s" (just like Lloyd Kvam said) or "%(key1)s" in case of passing a mapping sequence (which, I think, is just a dictionary)). Why it didn't work for him in the first place? I really don't know. DISCLAIMER: I *NEVER* used "MySQLdb". I just wanted to help. The sentence: """%s""", (email_id) seemed awfully wrong to me, and since nobody replied to him for more than a day, I suggested (what seemed to me) the right answer. That's a wrong thing to do since I don't know anything about "MySQLdb". So, I apologise to all of you. Ziyad. From benvinger at yahoo.co.uk Tue Jan 24 00:02:42 2006 From: benvinger at yahoo.co.uk (Ben Vinger) Date: Mon, 23 Jan 2006 23:02:42 +0000 (GMT) Subject: [Tutor] passwords in scripts In-Reply-To: Message-ID: <20060123230242.91348.qmail@web25807.mail.ukl.yahoo.com> Hi Danny The Unix servers are ancient HP-UX ones. I doubt if an SSH implementation for them exists, but it is not worth my while trying to find out, because I will not be allowed to install anything on them (or even suggest it). So I access them using telnetlib: host = 'hpserver' user = 'backupuser\r' password = 'backuppassword\r' telnetConnection = telnetlib.Telnet(host) telnetConnection.read_until('login: ') telnetConnection.read_until('Password: ') telnetConnection.write(password) menu = telnetConnection.read_until('Please Enter choice :') etc - doing the things programatically what I would have done if I opened a regular telnet session On the Windows servers the scheduled task I use runs with my domain logon credentials. This is fine for the majority of the servers, but some are in other domains where my credentials don't do the job. For them, I just open a connection to the ipc$ share in advance, like so: os.system(r'net use \\farserver\ipc$ /u:fardomain\administrator farpassword') The information about all the backup results is finally served as a single web page, so anyone can see at a glance whether the backups worked. This can also easily be emailed out, or warnings can be sent. But surely my problem is a very common one. Every web-app must supply a username and password to make a connection to its backend database, for example. Thanks Ben --- Danny Yoo wrote: > I guess one question might be: why are the passwords > there in the first > place? *grin* > > > It's usually a good idea to try avoiding hardcoding > things in a program, > and that goes for passwords too. If you're using > passwords to connect to > the Unix servers, you might want to consider looking > at Keychain: > > http://www.gentoo.org/proj/en/keychain/ > > to avoid having to do manual password entry. > Alternatively, 'ssh' can > be used to run remote commands on a Unix server. > There's a good example > of this here: > > http://www.jdmz.net/ssh/ > > > If you could tell us more details on why those > passwords are there, we > might have some better suggestions. > > > Good luck! > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > ___________________________________________________________ Yahoo! Messenger - NEW crystal clear PC to PC calling worldwide with voicemail http://uk.messenger.yahoo.com From alan.gauld at freenet.co.uk Tue Jan 24 00:38:29 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 23 Jan 2006 23:38:29 -0000 Subject: [Tutor] Searching for email id in MySQL giving wrong results References: <20060122124323.37411.qmail@web34806.mail.mud.yahoo.com> <1137954203.31434.8.camel@localhost.localdomain> <1138025757.15004.837.camel@www.venix.com> <016601c62049$438cf310$0b01a8c0@xp> <1138042852.15004.887.camel@www.venix.com> <1138055937.13603.22.camel@localhost.localdomain> Message-ID: <019301c62076$1de73800$0b01a8c0@xp> Hi Ziyad, Don't beat yourself up over this, you were trying to be helpful and that's a good thing. The original syntax looked weird to me too, but mainly because the variable was inside a pair of parens, but because I didn't know MySql I didn't say anything at the time. But your answer seemed reasonable enough. >> entry.execute("""SELECT * FROM contact WHERE email_id = %s""", >> (s_email,)) >> >> The execute method will handle the string substitution. This is better >> than doing it yourself, because execute will deal with any quoting >> issues for feeding the data to the database. Personally I never use this feature of execute because I then can't print out the SQL statement sent to the database if anything unexpected happens. I'd rather take responsibility for awkward escape strings than have a string I can't debug being sent to the database, but I'm aware that others take the opposite view and have more confidence in Python's libraries than I do! > Okay, here's a quote from the definition of "execute()": > def execute(self, query, args=None): > """Execute a query. > > query -- string, query to execute on server > args -- optional sequence or mapping, parameters to use > with query. Actually this might still be the issue since the OP used a single variable not a sequence but I suspect Python is smart enough to deal with that. > So, my answer is correct. And it seems there are other solutions (using > sequences and "%s" (just like Lloyd Kvam said) or "%(key1)s" in case of > passing a mapping sequence (which, I think, is just a dictionary)). You would have been correct if he had been building the query outside of execute(). > Why it didn't work for him in the first place? I really don't know. Me neither! :-) > I *NEVER* used "MySQLdb". I just wanted to help. The sentence: > """%s""", (email_id) Maybe he just needs a comma after email_id to force the second arg to be a tuple - who knows, I certainly don't. > more than a day, I suggested (what seemed to me) the right > answer. > > That's a wrong thing to do since I don't know anything about > "MySQLdb". So, I apologise to all of you. No apology is necessary, you were trying to help. Without your wrong answer Lloyd may not have posted the correction and we might not have had a discussion about the options available in cursor.execute() Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From dyoo at hkn.eecs.berkeley.edu Tue Jan 24 01:58:17 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 23 Jan 2006 16:58:17 -0800 (PST) Subject: [Tutor] passwords in scripts In-Reply-To: <20060123230242.91348.qmail@web25807.mail.ukl.yahoo.com> Message-ID: Hi Ben, Jon Libes of the National Institute of Standards and Technology (NIST) has written a guide on how to handle passwords in backgrounded processes: http://expect.nist.gov/doc/bgpasswd.pdf It has more suggestions on how to handle passwords securely. As you might expect, it doesn't have a single definitive answer to your question either. There are many ways to handle passwords with varying levels of convenience and security in mind. [comments about telnet] The use of telnet is already problematic in terms of security. Telnet passwords are sent in the clear. (So, although this is unrelated to your particular problem, I think you should encourage your system administrators to look into ssh in the long term. HP appears to support it: http://h20293.www2.hp.com/portal/swdepot/displayProductInfo.do?productNumber=T1471AA) > But surely my problem is a very common one. Every web-app must supply a > username and password to make a connection to its backend database, for > example. One approach that's often used in these kinds of applications is to keep a separate configuration file with those usernames and passwords. Then we can use the operating system's mechanisms (like file permissions) to keep that file mostly safe from prying eyes. This is mentioned in the "Handing Passwords with Security and Reliability in Background Processes" link above. One problem, though, is that anyone who has privileges to execute the password-reading program will probably have the same power to read that configuration file directly. I can see encrypting the configuration file as a way of making it a bit more difficult for people to accidently run across the passwords, and perhaps that's enough security for your purposes. Best of wishes! From dyoo at hkn.eecs.berkeley.edu Tue Jan 24 02:00:45 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 23 Jan 2006 17:00:45 -0800 (PST) Subject: [Tutor] passwords in scripts In-Reply-To: Message-ID: On Mon, 23 Jan 2006, Danny Yoo wrote: > Jon Libes of the National Institute of Standards and Technology (NIST) ^^^ Gaah. I'm sorry, that should be "Don", not "Jon". My muscle memory slipped. *grin* From h.finucane at gmail.com Tue Jan 24 05:29:29 2006 From: h.finucane at gmail.com (Henry Finucane) Date: Mon, 23 Jan 2006 20:29:29 -0800 Subject: [Tutor] [webbrowser] some help on an error running mozilla firefox In-Reply-To: <4677730601220819qdb0ee24k4004a439f85bd490@mail.gmail.com> References: <4677730601220819qdb0ee24k4004a439f85bd490@mail.gmail.com> Message-ID: On 1/22/06, Rinzwind wrote: > Why does this: > > >>> import webbrowser > >>> webbrowser.open('http://www.google.com") > > give me this: > > run-mozilla.sh: Cannot execute > /opt/firefox/mozilla-firefox-bin. > I would assume it's a permissions error. Can you execute /opt/firefox/mozilla-firefox-bin? Is python running as a different user? -- --H.F. My penguin is bigger than yours, mister... From list at ohtogo.com Tue Jan 24 06:11:53 2006 From: list at ohtogo.com (Michael) Date: Mon, 23 Jan 2006 22:11:53 -0700 Subject: [Tutor] processing a text file w/ OO? In-Reply-To: <011101c62002$e3029ae0$0b01a8c0@xp> References: <011101c62002$e3029ae0$0b01a8c0@xp> Message-ID: <3FC02F9D-D58F-4BBB-8FC1-D93898439A20@ohtogo.com> Thanks, Alan. That's exactly the kind of explanation I was looking for. As this is pretty much a one-off project and the data transformations are pretty different for each field, I'll stick with the functional approach. The rule of thumb you mention is useful, too. I hadn't heard that before. On Jan 23, 2006, at 2:53 AM, Alan Gauld wrote: >> I'm processing a tab-delimited text file where I read in a file, >> perform a bunch of operations on the items, and then write them >> out again to a fixed-width text file. >> I've been doing this with a very functional approach: >> Anyway, this all works fine. Not knowing much about OO, I'm >> wondering if there's a way to approach this from an object- >> oriented perspective. Is there anything to be gained? Or is this >> type of problem best tackled with a functional approach? > > This is one of the types of problem where I personally don't try to > use objects too much. Where objects might be helpful is if you have > a number of similar but slightly different data records such that > the processing consists of lots of if/elif chains. In that case > identifying the type once and relying on polymorphism to deal with > the differences is useful. But if the records all have similar > processing then OOP will make the code bulkier, slower and not add > too much IMHO. > > OTOH if you were to write a lot of these kinds of applications OOP > might provide a higher level of code reuse between projects.... But > remember that the cost of reuse means that you need to reuse code 3 > (*) or more times to make it economical! > > (*) Metrics suggest the actual figure varies between 3-10 times > depending on language, object complexity and level of generality. > > HTH, > > Alan G > Author of the learn to program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld > > From victor at grupocdm.com Tue Jan 24 03:38:04 2006 From: victor at grupocdm.com (Victor Bouffier) Date: Mon, 23 Jan 2006 20:38:04 -0600 Subject: [Tutor] Linux Python install? In-Reply-To: <1138028784.15004.851.camel@www.venix.com> References: <1138028784.15004.851.camel@www.venix.com> Message-ID: <1138070284.2708.21.camel@elrond> I highly recommend you have a look into ipython. It is a breeze to work with. I usually have a couple of terminal screens open, one with the ipython interpreter, which helps me a lot when testing code snipplets. You can install it using yumex, or just run 'yum install ipython' from the root command line. If you just started with Fedora, go into this site and follow the tips provided. It really improves your working environment. It will also provide you with extra repositories which allow you the installation of ipython among other packages. Fedora Core 4 Tips and Tricks http://home.gagme.com/greg/linux/fc4-tips.php On Mon, 2006-01-23 at 10:06 -0500, Python wrote: > On Mon, 2006-01-23 at 09:28 -0500, CPIM Ronin wrote: > > Sorry to bother the list with so simple a question but on moving to Linux > > from Windows XP, it's not clear to me how to accomplish a Python install on > > Linux. On XP it was mostly point and click on a ".msi" file (with msi > > standing for Microsoft install). I've loaded the latest Fedora/Redhat > > release on an old AMD machine. How do I install Python such that it shows up > > as a selection under the Programming task bar with EMACS? > > I assume you are using yum for package management. It should have been > installed by default. As root, you can issue the command > yum install python python-docs python-devel python-tools > > The package yumex provides a GUI interface to the yum package manager. > You can think of yumex as the Windows "Add/Remove Programs" application > on steroids. > yum install yumex > > The yumex install view with a filter of > python > will provide an extensive list of additional python packages. > > Finally, I do not know if this includes the best python integration with > EMACS. > > > I assume I have to do this under root, right? > > > > Step by step please. > > > > Thanks. > > > > _________________________________________________________________ > > Dont just search. Find. Check out the new MSN Search! > > http://search.msn.click-url.com/go/onm00200636ave/direct/01/ > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor From alan.gauld at freenet.co.uk Tue Jan 24 10:31:11 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 24 Jan 2006 09:31:11 -0000 Subject: [Tutor] passwords in scripts References: <20060123230242.91348.qmail@web25807.mail.ukl.yahoo.com> Message-ID: <01ce01c620c8$effa3ca0$0b01a8c0@xp> > an SSH implementation for them exists, but it is not > worth my while trying to find out, because I will not > be allowed to install anything on them (or even > suggest it). So I access them using telnetlib: Hmm, they won;t lket you install a secure access tool but are happy to let you in with a known security horror in the shapoe of telnet.... An interesting approach to sys admin... > But surely my problem is a very common one. Every > web-app must supply a username and password to make a > connection to its backend database, for example. command line arguments? $ startapp -d mydb -l user/password & That way they are 1) kept secret(especially if you turn shell history off ;-) and 2) can be changed every time you restart the server app and 3) you can have production and test databases running simultaneously... Alan G From kent37 at tds.net Tue Jan 24 12:08:50 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 24 Jan 2006 06:08:50 -0500 Subject: [Tutor] Searching for email id in MySQL giving wrong results In-Reply-To: <20060122124323.37411.qmail@web34806.mail.mud.yahoo.com> References: <20060122124323.37411.qmail@web34806.mail.mud.yahoo.com> Message-ID: <43D60AC2.60602@tds.net> John Joseph wrote: > Hi > Thanks to Allan,Danny,Pujo > I did my simple python script for MySQL , the > scripts add the data , and search for the data and > display > I have problem in searching email id ,ie > If search for the something at some , I will not get any > result , Guidance and advice needed for the reason > for this behavior Does it work when you search for other data such as name or phone? Can you show the output from a short run where you add a contact, display the data and search for an email? Kent > I had added my script in this mail > Thanks > Joseph John > > ********************************************************* > > """ This program is for to learn > how to enter data to MySQL using python > How to search > not using OOP > > Have problem in searching email-id > Why I do not get correct results when > searching email id > "@" string search containg "@" gives empty > results > > """ > > > > import MySQLdb > > def selecter(): > choice = None > while choice != "0": > print \ > """ > Data Base Entry for the Testing Env > 0 - Quit > 1 - Enter the Data > 2 - Display The data > 3 - Search The Company > """ > choice = raw_input("Choice :........") > print > > if choice == "0": > print "Good Bye ..." > elif choice == "1": > dataentry() > > elif choice == "2": > datashow() > elif choice == "3": > datasearch() > > > > def dataentry(): > name = raw_input("Enter the name of the company ") > email_id = raw_input("\n Enter the email ID : ") > phone_no = raw_input("Enter the Phone No : ") > fax_no = raw_input("\n Enter the fax no : ") > > db = MySQLdb.connect(host="localhost",user = "john", > passwd = "asdlkj", db = 'learnpython') > entry = db.cursor() > #entry.execute("""INSERT INTO contact > """,(name,email_id,phone_no,fax_no,)) > entry.execute("""INSERT INTO > contact(name,email_id,phone_no,fax_no) VALUES > (%s,%s,%s,%s)""",(name,email_id,phone_no,fax_no,)) > print name , email_id , fax_no, phone_no > > > > > def datashow(): > db = MySQLdb.connect(host="localhost",user = "john", > passwd = "asdlkj", db = 'learnpython') > entry = db.cursor() > entry.execute("SELECT * from contact") > p = entry.fetchall() > print p > > def datasearch(): > print "Do U want to search by Name , email id , phone > or fax " > choice = None > while choice != "0": > print \ > """ > U want to search the contacts by > 0 - Quit > 1 - Name > 2 - email_id > 3 - phone > 4 - fax > """ > choice = raw_input("Choice :........") > print > > if choice == "0": > print "Good Bye ..." > elif choice == "1": > searchbyname() > > elif choice == "2": > searchbyemail() > > elif choice == "3": > searchbyphone() > elif choice == "4": > searchbyfax() > > def searchbyname(): > s_name = raw_input("Enter the name to be searched ") > db = MySQLdb.connect(host="localhost",user = "john", > passwd = "asdlkj", db = 'learnpython') > entry = db.cursor() > entry.execute("""SELECT * FROM contact WHERE name = > %s""", (s_name,)) > p = entry.fetchall() > print p > > def searchbyemail(): > s_email = raw_input("Enter the Email to be searched > ") > db = MySQLdb.connect(host="localhost",user = "john", > passwd = "asdlkj", db = 'learnpython') > entry = db.cursor() > entry.execute("""SELECT * FROM contact WHERE email_id > = %s""", (s_email,)) > p = entry.fetchall() > print p > > > def searchbyphone(): > s_phone= raw_input("Enter the Phone no to be > searched ") > db = MySQLdb.connect(host="localhost",user = "john", > passwd = "asdlkj", db = 'learnpython') > entry = db.cursor() > entry.execute("""SELECT * FROM contact WHERE phone_no > = %s""", (s_phone,)) > p = entry.fetchall() > print p > > > > def searchbyfax(): > s_fax = raw_input("Enter the FAX no to be searched > ") > db = MySQLdb.connect(host="localhost",user = "john", > passwd = "asdlkj", db = 'learnpython') > entry = db.cursor() > entry.execute("""SELECT * FROM contact WHERE fax_no = > %s""", (s_fax,)) > p = entry.fetchall() > print p > > selecter() > > > > > > ___________________________________________________________ > Yahoo! Photos ? NEW, now offering a quality print service from just 8p a photo http://uk.photos.yahoo.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From matthew.williams at cancer.org.uk Tue Jan 24 11:57:23 2006 From: matthew.williams at cancer.org.uk (Matt Williams) Date: Tue, 24 Jan 2006 10:57:23 +0000 Subject: [Tutor] Python on Fedora In-Reply-To: References: Message-ID: <1138100243.4415.6.camel@localhost.localdomain> FC4 (the latest finished one) has python 2.4.1 as part of the distro (I think RedHat actually use python for some of their scripts). Just pull up a terminal and type 'python' and you should get the prompt... If you _are_ running FC4 and have more probs, feel free to drop me a line. at matt at mwilliams.org and I can try and help (since I am sat in front of an FC4 machine). WRT EMACS, I've never tried to get it going.... I use Eclipse and PyDev, or else SPE is worth a look. HTH, Matt From mail.roma1 at gmail.com Tue Jan 24 14:41:48 2006 From: mail.roma1 at gmail.com (Ivan Furone) Date: Tue, 24 Jan 2006 14:41:48 +0100 Subject: [Tutor] passwords in scripts In-Reply-To: <01ce01c620c8$effa3ca0$0b01a8c0@xp> References: <20060123230242.91348.qmail@web25807.mail.ukl.yahoo.com> <01ce01c620c8$effa3ca0$0b01a8c0@xp> Message-ID: <6122a57a0601240541i54869294l@mail.gmail.com> Hi Ivan I'm not sure I understand what you are saying here. Surely if the file is compiled it can just run (and will only need to be RE-compiled when I have to change the code (such as when one of the servers has their password changed). I would never need to de-compile, because I'll just keep a copy of the file on a memory stick, edit it there, compile it and replace the current compiled file with the newly compiled file. Not that I know anything about compiling Python programs, I just want to know if this is a possibility Thanks Ben Hi Ben, Perhaps I've been too much long-winded talking about the compiling issue,and too rash elsewhere.What I would say,essentially,it's possible to split the script in two modules,the first containing the passwords and a crypting/decrypting routine,and the second which could perform the checking operations on the logs.The second should need the passwords stored in the first to check them,so in module2,for example,you would import module1.This would allow the module with the passwords to be attached just at the needed moment then to be removed. Otherwise it applies the same if it's preferred.to backup and replace just a part of the script instead of everything,so it's possibile to modify the passwords or the script itself separately.It all depends by how you like to work with it. However I must establish that the access via telnet is the main security concern,and I agree to what Danny previously said about.The problem here is much matter of dealing with admins. Cheers, Ivan From wescpy at gmail.com Tue Jan 24 19:54:32 2006 From: wescpy at gmail.com (w chun) Date: Tue, 24 Jan 2006 10:54:32 -0800 Subject: [Tutor] Why doesn't this work? In-Reply-To: <20060123204124.39593.qmail@web51609.mail.yahoo.com> References: <20060123204124.39593.qmail@web51609.mail.yahoo.com> Message-ID: <78b3a9580601241054t5970d549r69fa8b29f2c9e28f@mail.gmail.com> on a barely related note, sets (mutable [set] and immutable [frozenset]) were added to Python beginning in version 2.3... so don't work too hard on your class! you may want to try something more interesting like: write a class which let's you keep track of time and does base 60 (sexagesimal / hexasegimal) math: >>> import myTime >>> c = myTime.myTime(10,30) >>> print c 10:30 >>> d = myTime.myTime(8,45) >>> print c + d 19:15 even better, also allow the constructor to take a string '10:30' in addition to the integers, and validate the parameters as necessary. (this is one of the exercises for "Core Python".) enjoy! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2006,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From dyoo at hkn.eecs.berkeley.edu Tue Jan 24 20:02:33 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 24 Jan 2006 11:02:33 -0800 (PST) Subject: [Tutor] passwords in scripts In-Reply-To: <6122a57a0601240541i54869294l@mail.gmail.com> Message-ID: On Tue, 24 Jan 2006, Ivan Furone wrote: > I'm not sure I understand what you are saying here. Surely if the file > is compiled it can just run (and will only need to be RE-compiled when I > have to change the code (such as when one of the servers has their > password changed). Hi Ivan, But the issue is that hardcoding passwords in a program doesn't really protect that password from exposure. For example: ###### bash-3.00$ cat test.py message = "hello, this is a test" bash-3.00$ python Python 2.3.3 (#1, Nov 7 2005, 22:36:37) [C] on sunos5 Type "help", "copyright", "credits" or "license" for more information. >>> import test >>> ^D ####### Doing the import will cause test.py to be compiled to 'test.pyc': ###### bash-3.00$ ls -l test.pyc -rw-r--r-- 1 dyoo other 143 Jan 24 10:55 test.pyc ###### But watch what happens here: ###### bash-3.00$ strings test.pyc hello, this is a testN( message( message( test.pys ###### Our secret string shows right up! This works even if we're talking about C code: /******/ bash-3.00$ cat test.c #include int main(int argc, char** argv) { char *msg = "hello"; } bash-3.00$ gcc test.c bash-3.00$ strings a.out hello /******/ So the fact that we're "compiling" code doesn't do anything significant to add security: those string literals are ripe for the taking for anyone competent enough to use the 'strings' command. So that's what we're trying to warn you about. Compiling code is not a magic wand to obscure secrets. Hope this helps! From Barry.Carroll at psc.com Tue Jan 24 20:04:29 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Tue, 24 Jan 2006 11:04:29 -0800 Subject: [Tutor] More Doubt with classes Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C35D2@eugsrv400.psc.pscnet.com> Greetings: I took Edgar's script and added some more people. Here is the script as I ran it. ======================================== class Person: '''Represents a person.''' population = 0 def __init__(self, name): '''Initializes the person's data.''' self.name = name print '(Initializing %s)' % self.name # When this person is created, he/she # adds to the population Person.population += 1 def __del__(self): '''I am dying.''' print '%s says bye.' % self.name Person.population -= 1 if Person.population == 0: print 'I am the last one.' else: print 'There are still %d people left.' % Person.population def sayHi(self): '''Greeting by the person. Really, that's all it does.''' print 'Hi, my name is %s.' % self.name def howMany(self): '''Prints the current population.''' print self.name + ' says: ', if Person.population == 1: print 'I am the only person here.' else: print 'We have %d persons here.' % Person.population swaroop = Person('Swaroop') swaroop.sayHi() swaroop.howMany() kalam = Person('Abdul Kalam') kalam.sayHi() kalam.howMany() butch = Person('Butch Cassidy') butch.sayHi() butch.howMany() gerald = Person('Gerald McBoingBoing') gerald.sayHi() gerald.howMany() tony = Person('Tony Danza') tony.sayHi() tony.howMany() swaroop.howMany() kalam.howMany() butch.howMany() gerald.howMany() tony.howMany() ======================================== When I ran it on my system (Windows XP Professional), I got an error as the script was cleaning up. Here is the output. >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> (Initializing Swaroop) Hi, my name is Swaroop. Swaroop says: I am the only person here. (Initializing Abdul Kalam) Hi, my name is Abdul Kalam. Abdul Kalam says: We have 2 persons here. (Initializing Butch Cassidy) Hi, my name is Butch Cassidy. Butch Cassidy says: We have 3 persons here. (Initializing Gerald McBoingBoing) Hi, my name is Gerald McBoingBoing. Gerald McBoingBoing says: We have 4 persons here. (Initializing Tony Danza) Hi, my name is Tony Danza. Tony Danza says: We have 5 persons here. Swaroop says: We have 5 persons here. Abdul Kalam says: We have 5 persons here. Butch Cassidy says: We have 5 persons here. Gerald McBoingBoing says: We have 5 persons here. Tony Danza says: We have 5 persons here. Butch Cassidy says bye. There are still 4 people left. Abdul Kalam says bye. There are still 3 people left. Gerald McBoingBoing says bye. There are still 2 people left. Swaroop says bye. There are still 1 people left. Tony Danza says bye. Exception exceptions.AttributeError: "'NoneType' object has no attribute 'population'" in > ignored >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Surprisingly, when I comment out the statements referencing the 'tony' instance, the error goes away. >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> (Initializing Swaroop) Hi, my name is Swaroop. Swaroop says: I am the only person here. (Initializing Abdul Kalam) Hi, my name is Abdul Kalam. Abdul Kalam says: We have 2 persons here. (Initializing Butch Cassidy) Hi, my name is Butch Cassidy. Butch Cassidy says: We have 3 persons here. (Initializing Gerald McBoingBoing) Hi, my name is Gerald McBoingBoing. Gerald McBoingBoing says: We have 4 persons here. Swaroop says: We have 4 persons here. Abdul Kalam says: We have 4 persons here. Butch Cassidy says: We have 4 persons here. Gerald McBoingBoing says: We have 4 persons here. Butch Cassidy says bye. There are still 3 people left. Abdul Kalam says bye. There are still 2 people left. Gerald McBoingBoing says bye. There are still 1 people left. Swaroop says bye. I am the last one. >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> I can't figure out what the difference is. Does anyone have an idea? Regards, Barry PS Sorry for the long post. I didn't want to leave anything out that might contain a clue. BGC > -----Original Message----- > Date: Fri, 20 Jan 2006 20:20:29 -0600 > From: Edgar Antonio Rodr?guez Velazco > Subject: [Tutor] Doubt with classes > To: tutor at python.org > Message-ID: > <9378d12c0601201820nce4b1c0w1fad545f33976a82 at mail.gmail.com> > Content-Type: text/plain; charset="iso-8859-1" > > Hi everybody, > I've been reading the chapter of classes of Byte of Python by Swaroop. > There's an example with classes (11.4) that is below: > > ############################################# > > ################################## > > I have runned the script in both Linux and Windows and got the same > result. > Could you explain me what's wrong with this??? > > -- > Edgar A. Rodriguez > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > http://mail.python.org/pipermail/tutor/attachments/20060120/c527657b/att ac > hment.htm From benvinger at yahoo.co.uk Tue Jan 24 20:51:53 2006 From: benvinger at yahoo.co.uk (Ben Vinger) Date: Tue, 24 Jan 2006 19:51:53 +0000 (GMT) Subject: [Tutor] passwords in scripts In-Reply-To: <01ce01c620c8$effa3ca0$0b01a8c0@xp> Message-ID: <20060124195154.46221.qmail@web25809.mail.ukl.yahoo.com> --- Alan Gauld wrote: > command line arguments? > > $ startapp -d mydb -l user/password & > > That way they are > 1) kept secret(especially if you turn shell history > off ;-) and > 2) can be changed every time you restart the server > app and > 3) you can have production and test databases > running simultaneously... These are good points, but what if the server is bounced when I'm on holiday (or everyone who might enter the password is asleep). My own little app isn't critical, but I can't see this do the trick for high profile web sites and similar. ___________________________________________________________ Yahoo! Messenger - NEW crystal clear PC to PC calling worldwide with voicemail http://uk.messenger.yahoo.com From benvinger at yahoo.co.uk Tue Jan 24 21:18:18 2006 From: benvinger at yahoo.co.uk (Ben Vinger) Date: Tue, 24 Jan 2006 20:18:18 +0000 (GMT) Subject: [Tutor] passwords in scripts In-Reply-To: Message-ID: <20060124201819.34036.qmail@web25804.mail.ukl.yahoo.com> Compiling is certainly helpful in my case, and I did not realise how simple it was until you explained it. I estimate that most of our MCSEs will not know about the strings command or attempt to look inside something like test.pyc for a password. As for users, I'll be amazed if they tried it. And real crackers - I think our network/firewall people know what they are doing, so I assume crackers are kept out. So, yes, I will use this until I've done something with crypt and/or expect. Finally, regarding changing the policy about telnet - it looks to me like the network where I am (I'm very new), is secure on the networking side however lax it might be on the server side. It is 100% switched, which means that only by controlling a switch can cleartext stuff be seen, and the switches are well-protected (also physically). So while I might agree with everyone who mentioned it, I will leave the Unix security to whoever in our large organisation's concern it is. I just want to avoid endangering it myself. Thanks Ben --- Danny Yoo wrote: > > > On Tue, 24 Jan 2006, Ivan Furone wrote: > > > I'm not sure I understand what you are saying > here. Surely if the file > > is compiled it can just run (and will only need to > be RE-compiled when I > > have to change the code (such as when one of the > servers has their > > password changed). > > Hi Ivan, > > But the issue is that hardcoding passwords in a > program doesn't really > protect that password from exposure. For example: > > ###### > bash-3.00$ cat test.py > message = "hello, this is a test" > bash-3.00$ python > Python 2.3.3 (#1, Nov 7 2005, 22:36:37) [C] on > sunos5 > Type "help", "copyright", "credits" or "license" for > more information. > >>> import test > >>> ^D > ####### > > > Doing the import will cause test.py to be compiled > to 'test.pyc': > > ###### > bash-3.00$ ls -l test.pyc > -rw-r--r-- 1 dyoo other 143 Jan 24 > 10:55 test.pyc > ###### > > > But watch what happens here: > > ###### > bash-3.00$ strings test.pyc > hello, this is a testN( > message( > message( > test.pys > ###### > > Our secret string shows right up! > > > > This works even if we're talking about C code: > > /******/ > bash-3.00$ cat test.c > #include > int main(int argc, char** argv) { > char *msg = "hello"; > } > bash-3.00$ gcc test.c > bash-3.00$ strings a.out > hello > /******/ > > > So the fact that we're "compiling" code doesn't do > anything significant to > add security: those string literals are ripe for the > taking for anyone > competent enough to use the 'strings' command. So > that's what we're > trying to warn you about. Compiling code is not a > magic wand to obscure > secrets. > > > Hope this helps! > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > ___________________________________________________________ Yahoo! Messenger - NEW crystal clear PC to PC calling worldwide with voicemail http://uk.messenger.yahoo.com From alan.gauld at freenet.co.uk Tue Jan 24 21:46:38 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 24 Jan 2006 20:46:38 -0000 Subject: [Tutor] passwords in scripts References: <20060124201819.34036.qmail@web25804.mail.ukl.yahoo.com> Message-ID: <021201c62127$4614d790$0b01a8c0@xp> > Compiling is certainly helpful in my case, and I did > not realise how simple it was until you explained it. Remember that only *imported* modules are compiled. Your main program will not be compiled. You can fix that by having your main program look like this: ####### dummy mainprog.py ######## import realprog realprog.main() ################################ So the real code lives in realprog whjich will be compiled. You can then remove all .py files except mainprog.py. > I estimate that most of our MCSEs will not know about > the strings command or attempt to look inside > something like test.pyc for a password. > As for users, I'll be amazed if they tried it. It depends on their Unix experience. In the old days of Unix (around 1988-1998 - ie pre Y2K issues...) using strings was a standard user trick to find out how to use a program for which man pages had not been installed - the usage instructions were usually to be found using strings. And since X windows became popular as a Unix GUI strings is still a popular way to find out what X resources can be set to customise an applications behaviour/appearance - the resources are often badly documented.... Speaking personally one of the first things I do after adding a new app on Unix is run strings on it! And I know I'm not alone. So if your users have had access to Unix in the past there is a high likeliehood of them knowing about strings. (other commands that users use to derive personaisation settings include truss/strace to monitor the inter process calls.) Alan G. From carroll at tjc.com Wed Jan 25 03:01:16 2006 From: carroll at tjc.com (Terry Carroll) Date: Tue, 24 Jan 2006 18:01:16 -0800 (PST) Subject: [Tutor] More Doubt with classes In-Reply-To: <2BBAEE949D384D40A2B851287ADB6A432C35D2@eugsrv400.psc.pscnet.com> Message-ID: On Tue, 24 Jan 2006, my long-lost cousin Barry wrote: > class Person: ... > def __del__(self): > '''I am dying.''' > print '%s says bye.' % self.name > Person.population -= 1 > > if Person.population == 0: > print 'I am the last one.' > else: > print 'There are still %d people left.' % Person.population > ======================================== > > When I ran it on my system (Windows XP Professional), I got an error as > the script was cleaning up. Here is the output. . . . > Tony Danza says bye. > Exception exceptions.AttributeError: "'NoneType' object has no attribute > 'population'" in instance at 0x00909BC0>> ignored > >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> I'm thinking that what's going on here is that the instances are being deleted as your program ends, which results in the __del__ method being invoked for each instance. But as the last instance (Danza) is deleted, there are no references left to the Person class any longer, either; and so the class itself is deleted, and that's happening before the deletion of Danza has completed. Once the Person class is deleted, there is no longer any Person.population variable. You therefore get an AttributeError, because the attribute "population" no longer exists; and since the person class is gone, there isn't even the Person class to reference any longer, hence the NoneType. I think this is what's meant in the docs on __del__: Also, when __del__() is invoked in response to a module being deleted (e.g., when execution of the program is done), other globals referenced by the __del__() method may already have been deleted. http://www.python.org/doc/2.4.2/ref/customization.html In your case, Person.population is one such "other global." If you really wanted to count on that code being executed in a timely way, the best way to do it is with an explicit call to a method to clean up the object. On the other hand, I'm talking just a little bit over my own head here, so I might be completely wrong. But I figure it's as good a way as any to get a conversation started where I might learn something. From singingxduck at gmail.com Wed Jan 25 07:59:45 2006 From: singingxduck at gmail.com (Orri Ganel) Date: Wed, 25 Jan 2006 01:59:45 -0500 Subject: [Tutor] : unexpected behavior with assignment in __init__ Message-ID: <43D721E1.5060504@gmail.com> Hello all, I was just messing around with a suggestion w chun (wescpy at gmail dot com) gave (to make a class that handles time, ie: > >> import myTime > >> c = myTime.myTime(10,30) > >> print c 10:30 > >> d = myTime.myTime(8,45) > >> print c + d 19:15 etc), and I was trying to make it like the str class in that, by default, when you str() a string, it returns the same object. I tried to do this with the following (irrelevant code removed), but it didn't work, despite original indications to the contrary, and I'm not sure I understand why: >>> class stime: def __init__(self, minutes, seconds=None): if seconds is None: if minutes.__class__ is stime: print minutes, type(minutes), minutes.__class__, id(minutes) self = minutes print self, type(self), self.__class__, id(self) def __repr__(self): return str(self) def __str__(self): return "%02d:%02d" % (self.minutes, self.seconds) >>> a = stime(10,3) >>> b = stime(a) 10:03 __main__.stime 12858832 10:03 __main__.stime 12858832 >>> # so, it appears to work, because it prints the same id both times. however, # . . . >>> id(a) 12858832 >>> id(b) 12858792 >>> # they're not the same anymore! and that's not all: >>> a 10:03 >>> b Traceback (most recent call last): File "", line 1, in -toplevel- b File "C:/Documents and Settings/Cookie/Desktop/stime.py", line 20, in __repr__ return str(self) File "C:/Documents and Settings/Cookie/Desktop/stime.py", line 22, in __str__ return "%02d:%02d" % (self.minutes, self.seconds) AttributeError: stime instance has no attribute 'minutes' So, not only do the two variables not refer to the same object after exiting __init__, but b is now a broken stime instance. Anyone know what's going on? Thanks in advance, Orri -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060125/00cad0bf/attachment.htm From broek at cc.umanitoba.ca Wed Jan 25 09:55:12 2006 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Wed, 25 Jan 2006 02:55:12 -0600 Subject: [Tutor] Why doesn't this work? In-Reply-To: <20060123204124.39593.qmail@web51609.mail.yahoo.com> References: <20060123204124.39593.qmail@web51609.mail.yahoo.com> Message-ID: <43D73CF0.5060703@cc.umanitoba.ca> Christopher Spears said unto the world upon 23/01/06 02:41 PM: > I copied this code from Learning Python while learning > about extending types by subclassing: > I'm pretty sure I copied this exactly from the book, > so I'm not sure what is not working. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > You can download the code to remove the retyping uncertainty. Best, Brian vdB From kent37 at tds.net Wed Jan 25 12:07:46 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 25 Jan 2006 06:07:46 -0500 Subject: [Tutor] : unexpected behavior with assignment in __init__ In-Reply-To: <43D721E1.5060504@gmail.com> References: <43D721E1.5060504@gmail.com> Message-ID: <43D75C02.3090801@tds.net> Orri Ganel wrote: > Hello all, > I was just messing around with a suggestion w chun (wescpy at gmail > dot com) gave (to make a class that handles time, ie: > >> >> import myTime >> >> c = myTime.myTime(10,30) >> >> print c > 10:30 >> >> d = myTime.myTime(8,45) >> >> print c + d > 19:15 > > etc), and I was trying to make it like the str class in that, by > default, when you str() a string, it returns the same object. I tried > to do this with the following (irrelevant code removed), but it didn't > work, despite original indications to the contrary, and I'm not sure I > understand why: > > >>> class stime: > def __init__(self, minutes, seconds=None): > if seconds is None: > if minutes.__class__ is stime: > print minutes, type(minutes), minutes.__class__, id(minutes) > self = minutes > print self, type(self), self.__class__, id(self) > def __repr__(self): > return str(self) > def __str__(self): > return "%02d:%02d" % (self.minutes, self.seconds) Assigning to self in __init__() just changes the value of the local variable, it has no effect outside the method; inside a method, self is just a method parameter, nothing more. There is some magic that gives self its value for the call. When __init__() is called the new instance has already been created, you are just initializing its state, not creating the object. You can do what you want by defining stime.__new__(). __new__() is responsible for actually creating a new object. You still have to check for an stime instance in __init__() because __init__() will be called even when __new__() returns an existing instance. Here is a simplified example: >>> class stime(object): ... def __new__(cls, value): ... if isinstance(value, cls): ... return value ... return object.__new__(cls, value) ... def __init__(self, value): ... print 'stime.__init__', value ... if isinstance(value, stime): ... return ... self.value = value ... >>> a=stime(3) stime.__init__ 3 >>> a <__main__.stime object at 0x00A32E90> >>> b=stime(a) stime.__init__ <__main__.stime object at 0x00A32E90> >>> b <__main__.stime object at 0x00A32E90> >>> a.value 3 >>> b.value 3 >>> a is b True Kent > > >>> a = stime(10,3) > >>> b = stime(a) > 10:03 __main__.stime 12858832 > 10:03 __main__.stime 12858832 > >>> # so, it appears to work, because it prints the same id both times. > however, > # . . . > >>> id(a) > 12858832 > >>> id(b) > 12858792 > >>> # they're not the same anymore! and that's not all: > >>> a > 10:03 > >>> b > > Traceback (most recent call last): > File "", line 1, in -toplevel- > b > File "C:/Documents and Settings/Cookie/Desktop/stime.py", line 20, in > __repr__ > return str(self) > File "C:/Documents and Settings/Cookie/Desktop/stime.py", line 22, in > __str__ > return "%02d:%02d" % (self.minutes, self.seconds) > AttributeError: stime instance has no attribute 'minutes' > > So, not only do the two variables not refer to the same object after > exiting __init__, but b is now a broken stime instance. Anyone know > what's going on? > > Thanks in advance, > Orri > > -- > Email: singingxduck AT gmail DOT com > AIM: singingxduck > Programming Python for the fun of it. > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From singingxduck at gmail.com Wed Jan 25 12:35:15 2006 From: singingxduck at gmail.com (Orri Ganel) Date: Wed, 25 Jan 2006 06:35:15 -0500 Subject: [Tutor] : unexpected behavior with assignment in __init__ In-Reply-To: <43D75C02.3090801@tds.net> References: <43D721E1.5060504@gmail.com> <43D75C02.3090801@tds.net> Message-ID: <43D76273.3030802@gmail.com> Kent Johnson wrote: >variable, it has no effect outside the method; inside a method, self is >just a method parameter, nothing more. There is some magic that gives >self its value for the call. > >When __init__() is called the new instance has already been created, you >are just initializing its state, not creating the object. You can do >what you want by defining stime.__new__(). __new__() is responsible for >actually creating a new object. You still have to check for an stime >instance in __init__() because __init__() will be called even when >__new__() returns an existing instance. > >Here is a simplified example: > > >>> class stime(object): > ... def __new__(cls, value): > ... if isinstance(value, cls): > ... return value > ... return object.__new__(cls, value) > ... def __init__(self, value): > ... print 'stime.__init__', value > ... if isinstance(value, stime): > ... return > ... self.value = value > ... > >>> a=stime(3) >stime.__init__ 3 > >>> a ><__main__.stime object at 0x00A32E90> > >>> b=stime(a) >stime.__init__ <__main__.stime object at 0x00A32E90> > >>> b ><__main__.stime object at 0x00A32E90> > >>> a.value >3 > >>> b.value >3 > >>> a is b >True > >Kent > > > Assigning to self in __init__() just changes the value of the local Thanks. I think I've run into this sort of behavior before, but didn't remember the details well enough to remember the solution (if I've ever known it). Hopefully this'll be the last of me emails to the Tutor mailing list on this particular problem. ;-) Thanks again, Orri -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060125/4bdbfe44/attachment.html From ml.cyresse at gmail.com Wed Jan 25 14:18:46 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Thu, 26 Jan 2006 02:18:46 +1300 Subject: [Tutor] strings & splitting Message-ID: Hi all, I have a large string which I'm attempting to manipulate, which I find very convenient to call large_string.split(" ") on to conveniently tokenise. Except, however for the double quoted strings within my string, which contain spaces. At the moment I'm doing a split by \n, and then looping line by line, splitting by spaces and then reuniting double quoted strings by iterating over the split line, looking for mismatched quotation marks, storing the indexes of each matching pair and then: for (l,r) in pairs: . sub_string = q[l:r+1] #Up to r and including it. . rejoined_string = " ".join(sub_string) . indices = range(l,r+1) . indices.reverse() . for i in indices: q.pop(i) . q.insert(l, rejoined_string) I'm doing it split line by split line, extending the resulting line into a big flat list as I found out that Python doesn't cope overly well with stuff like the above when it's a 800,000 item list, I think it was the insert mainly. My question is, is there a more Pythonic solution to this? I was thinking of using a regex to pluck qualifying quoted-space-including sentences out, and then trying to remember where they went based on context, but that sounds prone to error; so I thought of perhaps the same thing with a unique token of my own that I can find once the list is created and then sub the original string back in, but I wonder if calling index() repeatedly would be any faster. I've got it down to 3 seconds now, but I'm trying to get... a stable solution, if possible an elegant solution.The current one is prone to breaking based on funny whitespace and is just ugly and prickly looking. Regards, Liam Clarke From kent37 at tds.net Wed Jan 25 14:38:03 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 25 Jan 2006 08:38:03 -0500 Subject: [Tutor] strings & splitting In-Reply-To: References: Message-ID: <43D77F3B.9010400@tds.net> Liam Clarke wrote: > Hi all, > > I have a large string which I'm attempting to manipulate, which I find > very convenient to call > large_string.split(" ") on to conveniently tokenise. > > Except, however for the double quoted strings within my string, which > contain spaces. > > At the moment I'm doing a split by \n, and then looping line by line, > splitting by spaces and then reuniting double quoted strings by > iterating over the split line, looking for mismatched quotation marks, > storing the indexes of each matching pair and then: I'm pretty sure you can do this with the csv module. You can configure the field delimiter to be a space and I think it will do what you want line-by-line, then you just have to join the lines together. Pyparsing also has built-in support for quoted strings, you could use it. > > for (l,r) in pairs: > . sub_string = q[l:r+1] #Up to r and including it. > . rejoined_string = " ".join(sub_string) > . indices = range(l,r+1) > . indices.reverse() > . for i in indices: q.pop(i) > . q.insert(l, rejoined_string) > > I'm doing it split line by split line, extending the resulting line > into a big flat list as I found out that Python doesn't cope overly > well with stuff like the above when it's a 800,000 item list, I think > it was the insert mainly. The pops and the inserts will get expensive as the list grows. You could do them all in one operation with something like this: q[l:r+1] = [rejoined_string] That should speed it up a bit. A list is implemented as an array of references. Each time you pop or insert, the elements of the list after the point of change have to be copied to add or remove a space in the array. Doing it in one operation reduces this to a single copy per iteration, instead of two or more. Kent > > My question is, is there a more Pythonic solution to this? > > I was thinking of using a regex to pluck qualifying > quoted-space-including sentences out, and then trying to remember > where they went based on context, but that sounds prone to error; so I > thought of perhaps the same thing with a unique token of my own that I > can find once the list is created and then sub the original string > back in, but I wonder if calling index() repeatedly would be any > faster. > > I've got it down to 3 seconds now, but I'm trying to get... a stable > solution, if possible an elegant solution.The current one is prone to > breaking based on funny whitespace and is just ugly and prickly > looking. > > Regards, > > Liam Clarke > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From jonathan.r.moore at gmail.com Wed Jan 25 17:44:26 2006 From: jonathan.r.moore at gmail.com (Jon Moore) Date: Wed, 25 Jan 2006 16:44:26 +0000 Subject: [Tutor] Controling my loops and redundant code?!? Message-ID: Hi, I have written the program below as an exercise from a book I am working my way through. Objective from book: Write a character creator program for a role-playing-game. The player should be given a pool of 30 points to spend on four attributes: strength, health, wisdom and dexterity. The player should be able to spend points from the pool on any attribute and should be also be able to take points from an attribute and put them back in the pool. Although the program meets the aim of the exercise set out in the book , there are a couple of things I am not happy with! 1. I am sure I have written far more code than required. Where could I have made some shorcuts? 2. Should the user enter a value greater than what is available, the program kicks the user all the way back to the main menu. How could I tidy this up to just loop round to ask the user to try a new value? choice = None # Set max number of available points POINTS_POOL = 30 # store attribute values attributes = [["Strength", 0], ["Health", 0], ["Wisdom", 0], ["Dexterity", 0]] strength = attributes[0] health = attributes[1] wisdom = attributes[2] dexterity = attributes[3] available_points = 30 used_points = 0 attribute_value = "" while choice != "0": print \ """ ----------------- Character Creator ----------------- 0 - Exit 1 - Show Character Attributes 2 - Set Character Attributes 3 - Reset Character Attributes """ choice = raw_input("Choice: ") print # exit option if choice == "0": print "Good bye." # show attributes option elif choice == "1": print "Your attributes are as follows:\n" print "\t",strength[0], strength[1] print "\t",health[0], health[1] print "\t",wisdom[0], wisdom[1] print "\t",dexterity[0], dexterity[1] print "\nYou have",available_points,"points available." # edit attributes option elif choice == "2": # set strength attribute print "\nYou have",strength[1] + available_points,"points available." attribute_value = int(raw_input("How much would you like to assign to strength?: ")) if attribute_value > (strength[1] + available_points): print "Error - You do not have that many points available!\n" print "Please reset the character or assign a value equal\nto or lower than the avaialble points." continue strength[1] = attribute_value used_points = strength[1] + health[1] + wisdom[1] + dexterity[1] available_points = POINTS_POOL - used_points # set health attribute print "\nYou have",health[1] + available_points,"points available." attribute_value = int(raw_input("How much would you like to assign to health?: ")) if attribute_value > (health[1] + available_points): print "Error - You do not have that many points available!\n" print "Please reset the character or assign a value equal\nto or lower than the avaialble points." continue health[1] = attribute_value used_points = strength[1] + health[1] + wisdom[1] + dexterity[1] available_points = POINTS_POOL - used_points # set wisdom attribute print "\nYou have",wisdom[1] + available_points,"points available." attribute_value = int(raw_input("How much would you like to assign to wisdom?: ")) if attribute_value > (wisdom[1] + available_points): print "Error - You do not have that many points available!\n" print "Please reset the character or assign a value equal\nto or lower than the avaialble points." continue wisdom[1] = attribute_value used_points = strength[1] + health[1] + wisdom[1] + dexterity[1] available_points = POINTS_POOL - used_points # set dexterity attribute print "\nYou have",dexterity[1] + available_points,"points available." attribute_value = int(raw_input("How much would you like to assign to dexterity?: ")) if attribute_value > (dexterity[1] + available_points): print "Error - You do not have that many points available!\n" print "Please reset the character or assign a value equal\nto or lower than the avaialble points." continue dexterity[1] = attribute_value used_points = strength[1] + health[1] + wisdom[1] + dexterity[1] available_points = POINTS_POOL - used_points # print amount of unused points print "\nYou have",available_points,"unused points." # reset attributes option elif choice == "3": strength[1] = 0 health[1] = 0 wisdom[1] = 0 dexterity[1] = 0 used_points = strength[1] + health[1] + wisdom[1] + dexterity[1] available_points = POINTS_POOL - used_points print "Attributes have been reset." # some unknown choice else: print "Sorry, but" ,choice, "is not a valid choice." -- Best Regards Jon Moore -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060125/77422c42/attachment-0001.htm From alan.gauld at freenet.co.uk Wed Jan 25 19:28:28 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 25 Jan 2006 18:28:28 -0000 Subject: [Tutor] strings & splitting References: Message-ID: <024001c621dd$233b3690$0b01a8c0@xp> Hi Liam, I'm not sure I really understand what you are trying to get to here. Can you provide a short sample of before/after data so we can see what we are trying to achieve? Alan G ----- Original Message ----- From: "Liam Clarke" To: "Python Tutor" Sent: Wednesday, January 25, 2006 1:18 PM Subject: [Tutor] strings & splitting Hi all, I have a large string which I'm attempting to manipulate, which I find very convenient to call large_string.split(" ") on to conveniently tokenise. Except, however for the double quoted strings within my string, which contain spaces. At the moment I'm doing a split by \n, and then looping line by line, splitting by spaces and then reuniting double quoted strings by iterating over the split line, looking for mismatched quotation marks, storing the indexes of each matching pair and then: for (l,r) in pairs: . sub_string = q[l:r+1] #Up to r and including it. . rejoined_string = " ".join(sub_string) . indices = range(l,r+1) . indices.reverse() . for i in indices: q.pop(i) . q.insert(l, rejoined_string) I'm doing it split line by split line, extending the resulting line into a big flat list as I found out that Python doesn't cope overly well with stuff like the above when it's a 800,000 item list, I think it was the insert mainly. My question is, is there a more Pythonic solution to this? I was thinking of using a regex to pluck qualifying quoted-space-including sentences out, and then trying to remember where they went based on context, but that sounds prone to error; so I thought of perhaps the same thing with a unique token of my own that I can find once the list is created and then sub the original string back in, but I wonder if calling index() repeatedly would be any faster. I've got it down to 3 seconds now, but I'm trying to get... a stable solution, if possible an elegant solution.The current one is prone to breaking based on funny whitespace and is just ugly and prickly looking. Regards, Liam Clarke From alan.gauld at freenet.co.uk Wed Jan 25 19:53:12 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 25 Jan 2006 18:53:12 -0000 Subject: [Tutor] Controling my loops and redundant code?!? References: Message-ID: <024801c621e0$978d5250$0b01a8c0@xp> Hi Jon, > 1. I am sure I have written far more code than required. > Where could I have made some shorcuts? Probably but shortcuts are not necesasarily a good thing if they obscure readability... However one area that would clean it up a bit is if you were to use a dictionary rather than lists for the attributes(see below): > # Set max number of available points > POINTS_POOL = 30 Thus duplicates available_points below. You only really need it once... although I see that you modify avail... Might be better to do it by assigning this constant as the initial value of available_points: available_points = POINTS_POOL > # store attribute values > attributes = [["Strength", 0], ["Health", 0], > ["Wisdom", 0], ["Dexterity",0]] Use a dictionary here instead: attributes = {'Strength': 0, 'Health':0, 'Wisdom':0, Dexterity:0} >strength = attributes[0] >health = attributes[1] >wisdom = attributes[2] >dexterity = attributes[3] and you shouldn't need these now.... available_points = 30 used_points = 0 attribute_value = "" choice = None while choice != "0": print """ ----------------- """ choice = raw_input("Choice: ") # show attributes option > elif choice == "1": > print "Your attributes are as follows:\n" > print "\t",strength[0], strength[1] print '\t Strength', attributes['Strength'] is easier to read I think. # edit attributes option > elif choice == "2": > # set strength attribute > print "\nYou have",strength[1] + available_points,"points > available." print '\n You have', attributes['Strength'] + available_points,'points' Although I personally prefer to use string formatting: print '\n You have %d points', (attributes['Strength'] + available_points) > if attribute_value > (strength[1] + available_points): Since you do the sum twice I'd store the value up top avail_strength = attributes['Strength'] + available_points And use avail_strength in both the print and comparison. > strength[1] = attribute_value > used_points = strength[1] + health[1] + wisdom[1] + dexterity[1] You can use the sum() function here: used_points = sum(attributes.values()) Also since you are repeating almost exactly the same code for each attribute you coiuld create a function that takes the attribute name as a parameter. Have you come across functions yet? If not don't worry this approach works it just means more typing and multiple changes to fix things. Hope those points help a little. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From intercodes at gmail.com Wed Jan 25 19:59:00 2006 From: intercodes at gmail.com (Intercodes) Date: Thu, 26 Jan 2006 00:29:00 +0530 Subject: [Tutor] mod_python and other web frameworks Message-ID: <37e70e3b0601251059h4c2e8d69i527b79062a050ea2@mail.gmail.com> Hello everyone, Disclaimer: Beginner. I have an idea of coding a web application and decided to do it entirely with python (reddit style). I started looking for web programming in python and somehow I saw mod_python first. Iam perusing the help document now. Few minutes of browsing confused my mind entirely , since it seems there are about 20 different web frameworks available for python. I am left clueless as to pick which one. I have an soft side towards the one I picked first. Considering yourself as a beginner to python ,do you prefer mod_python over all other framework?. Say if you want to create a blog , will mod_python suffice? And is mod_python and cgi (the python lib) different? -- Intercodes -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060126/f203565b/attachment.html From ml.cyresse at gmail.com Wed Jan 25 21:18:26 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Thu, 26 Jan 2006 09:18:26 +1300 Subject: [Tutor] mod_python and other web frameworks In-Reply-To: <37e70e3b0601251059h4c2e8d69i527b79062a050ea2@mail.gmail.com> References: <37e70e3b0601251059h4c2e8d69i527b79062a050ea2@mail.gmail.com> Message-ID: Hi, I recommend checking out the Turbogears 20 minute Wiki tutorial, although I'd hold off using it until the 0.9 release comes out with some useful changes. When you use it, it sits behind mod_python and responds to requests made. You can see a Turbogears error message here - :D http://digitalsouth.net.nz/~cyresse/index.htm that I've been playing with. Normally it works. ;) Django is also worth having a look at, but it's a bit sharper to learn The Turbogears Google group is really supportive, by the way. Regards, Liam Clarke On 1/26/06, Intercodes wrote: > Hello everyone, > > Disclaimer: Beginner. > > I have an idea of coding a web application and decided to do it entirely > with python (reddit style). I started looking for web programming in python > and somehow I saw mod_python first. Iam perusing the help document now. > > Few minutes of browsing confused my mind entirely , since it seems there are > about 20 different web frameworks available for python. I am left clueless > as to pick which one. I have an soft side towards the one I picked first. > > Considering yourself as a beginner to python ,do you prefer mod_python over > all other framework?. Say if you want to create a blog , will mod_python > suffice? And is mod_python and cgi (the python lib) different? > > > -- > Intercodes > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From intercodes at gmail.com Wed Jan 25 21:37:43 2006 From: intercodes at gmail.com (Intercodes) Date: Thu, 26 Jan 2006 02:07:43 +0530 Subject: [Tutor] mod_python and other web frameworks In-Reply-To: <20060125200721.52012.qmail@web27003.mail.ukl.yahoo.com> References: <37e70e3b0601251059h4c2e8d69i527b79062a050ea2@mail.gmail.com> <20060125200721.52012.qmail@web27003.mail.ukl.yahoo.com> Message-ID: <37e70e3b0601251237n217d7f32w6e4c2ec75074e28b@mail.gmail.com> Lolo, Thanks for the boost up. I am looking at PSP now and it seems promising. 3 days is impossible for me :) ...maybe a week or more. I will certainly have a look at 'mighty' once I am familiar with mod_python. List: I am still open to suggestions. Thank You. Intercodes ------------------------------------------ On 1/26/06, Lolo wrote: > > Hi guys, > > I'm using PSP module from mod_python for professional > stuff. > It's quick and easy to use, so it will be easy to > create your blog > in 3 or 4 days. > You can put directly your python code in an html web > page. > > But currently i take a look at migthy > (http://www.myghty.org/index.myt), it's a very cool > templating framework. And you can use it with > mod_python. > > Have a nice day ... > > > -- Intercodes -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060126/b3b4578b/attachment.html From ml.cyresse at gmail.com Wed Jan 25 21:42:54 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Thu, 26 Jan 2006 09:42:54 +1300 Subject: [Tutor] strings & splitting In-Reply-To: <024001c621dd$233b3690$0b01a8c0@xp> References: <024001c621dd$233b3690$0b01a8c0@xp> Message-ID: Hi, Thanks Kent, I'll check out the CSV module. I had a go with Pyparsing awhile ago, and it's clocking in at the 3 minute mark also. Alan - the data is of the form - a = { b = 1 c = 2 d = { e = { f = 4 g = "Ultimate Showdown of Ultimate Destiny" } h = { i j k } } } Everything is whitespace delimited. I'd like to turn it into ["a", "=", "{", "b", "=", "1", "c", "=", "2", "d", "=", "{", "e", "=", "{", "f", "=", "4", "g", "=", "\"Ultimate Showdown of Ultimate Destiny\"", "}", "h", "=", "{", "i", "j", "k", "}", "}"] Regards, Liam Clarke On 1/26/06, Alan Gauld wrote: > Hi Liam, > > I'm not sure I really understand what you are trying > to get to here. > > Can you provide a short sample of before/after data > so we can see what we are trying to achieve? > > Alan G > > ----- Original Message ----- > From: "Liam Clarke" > To: "Python Tutor" > Sent: Wednesday, January 25, 2006 1:18 PM > Subject: [Tutor] strings & splitting > > > Hi all, > > I have a large string which I'm attempting to manipulate, which I find > very convenient to call > large_string.split(" ") on to conveniently tokenise. > > Except, however for the double quoted strings within my string, which > contain spaces. > > At the moment I'm doing a split by \n, and then looping line by line, > splitting by spaces and then reuniting double quoted strings by > iterating over the split line, looking for mismatched quotation marks, > storing the indexes of each matching pair and then: > > for (l,r) in pairs: > . sub_string = q[l:r+1] #Up to r and including it. > . rejoined_string = " ".join(sub_string) > . indices = range(l,r+1) > . indices.reverse() > . for i in indices: q.pop(i) > . q.insert(l, rejoined_string) > > I'm doing it split line by split line, extending the resulting line > into a big flat list as I found out that Python doesn't cope overly > well with stuff like the above when it's a 800,000 item list, I think > it was the insert mainly. > > My question is, is there a more Pythonic solution to this? > > I was thinking of using a regex to pluck qualifying > quoted-space-including sentences out, and then trying to remember > where they went based on context, but that sounds prone to error; so I > thought of perhaps the same thing with a unique token of my own that I > can find once the list is created and then sub the original string > back in, but I wonder if calling index() repeatedly would be any > faster. > > I've got it down to 3 seconds now, but I'm trying to get... a stable > solution, if possible an elegant solution.The current one is prone to > breaking based on funny whitespace and is just ugly and prickly > looking. > > Regards, > > Liam Clarke > > > From ml.cyresse at gmail.com Wed Jan 25 21:57:51 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Thu, 26 Jan 2006 09:57:51 +1300 Subject: [Tutor] mod_python and other web frameworks In-Reply-To: <37e70e3b0601251245q3fc918beo6cc35774fea5739b@mail.gmail.com> References: <37e70e3b0601251059h4c2e8d69i527b79062a050ea2@mail.gmail.com> <37e70e3b0601251245q3fc918beo6cc35774fea5739b@mail.gmail.com> Message-ID: On 1/26/06, Intercodes wrote: > Liam, > > I checked the wiki video sometime back. If my memory wont fail me, the guy > there never used a single line of python code ;) (I may be wrong) It seemed > a totally new language that he used to create that wiki. > > Iam more inclined to code a lot rather than deal with such high abstraction, > as I would like to improve my programming skills and get good python > knowledge. I think ill give these two a try once I have some website running > under something that uses more python code. I'd say you're referring to the Kid templating. ${title} etc. As the main handlers uses Cherrypy, which is very much Pythonic, and the object-relational mapper uses SQLObject which is also very Pythonic. For your reference if needed http://www.turbogears.org/docs/wiki20/ Anyhoo, your choice in the end, good luck with the deep end approach. Regards, Liam Clarke From intercodes at gmail.com Wed Jan 25 21:45:34 2006 From: intercodes at gmail.com (Intercodes) Date: Thu, 26 Jan 2006 02:15:34 +0530 Subject: [Tutor] mod_python and other web frameworks In-Reply-To: References: <37e70e3b0601251059h4c2e8d69i527b79062a050ea2@mail.gmail.com> Message-ID: <37e70e3b0601251245q3fc918beo6cc35774fea5739b@mail.gmail.com> Liam, I checked the wiki video sometime back. If my memory wont fail me, the guy there never used a single line of python code ;) (I may be wrong) It seemed a totally new language that he used to create that wiki. Iam more inclined to code a lot rather than deal with such high abstraction, as I would like to improve my programming skills and get good python knowledge. I think ill give these two a try once I have some website running under something that uses more python code. Thanks for your time. Thank You, Intercodes On 1/26/06, Liam Clarke wrote: > > Hi, > > I recommend checking out the Turbogears 20 minute Wiki tutorial, > although I'd hold off using it until the 0.9 release comes out with > some useful changes. > > When you use it, it sits behind mod_python and responds to requests made. > You can see a Turbogears error message here - :D > http://digitalsouth.net.nz/~cyresse/index.htm that I've been playing > with. Normally it works. ;) > > Django is also worth having a look at, but it's a bit sharper to learn > The Turbogears Google group is really supportive, by the way. > > -- Intercodes -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060126/a022a7df/attachment-0001.htm From alan.gauld at freenet.co.uk Wed Jan 25 23:44:07 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 25 Jan 2006 22:44:07 -0000 Subject: [Tutor] strings & splitting References: <024001c621dd$233b3690$0b01a8c0@xp> Message-ID: <026401c62200$d9eba000$0b01a8c0@xp> Liam wrote: ------------------------ Alan - the data is of the form - a = { b = 1 c = 2 d = { e = { f = 4 g = "Ultimate Showdown of Ultimate Destiny" } h = { i j k } } } Everything is whitespace delimited. I'd like to turn it into ["a", "=", "{", "b", "=", "1", "c", "=", "2", "d", "=", "{", "e", "=", "{", "f", "=", "4", "g", "=", "\"Ultimate Showdown of Ultimate Destiny\"", "}", "h", "=", "{", "i", "j", "k", "}", "}"] ----------------------- Liam, I'd probably tackle this on a character by character basis using traditional tokenising code. ie build a state machine to determine what kind of token I'm in and keep reading chars until the token completes. most tokens are single-char tokens, others are quote-tokens. Set token-type appropriately and read till end-of-token. I might even use some classes to define the token types, but I'd keep them as simple as possible. Rough pseudo code: for char in tokenString: if token.type == quoted: token.append(char) if char == ": token.type =None continue elif token.type = simple tokens.append(char) token.type = None else: # not in a token if char in '\n\t ,.': # other non token chars continue elif char == '"': token.type = quoted token.append(char) continue else: token.type = simple token.append(char) You can tidy that up with functions and a proper state jump table but it might be faster than trying to build complex pattern matches and doing lots of insertions into lists etc. But it does rely on the data being as simple as your sample in the variety of token types. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From gsf at panix.com Wed Jan 25 23:48:38 2006 From: gsf at panix.com (Gabriel S Farrell) Date: Wed, 25 Jan 2006 17:48:38 -0500 Subject: [Tutor] mod_python and other web frameworks In-Reply-To: <37e70e3b0601251237n217d7f32w6e4c2ec75074e28b@mail.gmail.com> References: <37e70e3b0601251059h4c2e8d69i527b79062a050ea2@mail.gmail.com> <20060125200721.52012.qmail@web27003.mail.ukl.yahoo.com> <37e70e3b0601251237n217d7f32w6e4c2ec75074e28b@mail.gmail.com> Message-ID: <20060125224838.GD6223@panix.com> On Thu, Jan 26, 2006 at 02:07:43AM +0530, Intercodes wrote: > Lolo, > > Thanks for the boost up. I am looking at PSP now and it seems promising. 3 > days is impossible for me :) ...maybe a week or more. I will certainly have > a look at 'mighty' once I am familiar with mod_python. > > List: I am still open to suggestions. If you're looking to do some Python coding to put your site together, you might take a gander at Quixote (http://www.mems-exchange.org/software/quixote/). From what I've seen, it's the closest thing to coding a web site in Python. It works best with SCGI, but also with regular CGI and mod_python. gsf From jonathan.r.moore at gmail.com Thu Jan 26 00:17:49 2006 From: jonathan.r.moore at gmail.com (Jon Moore) Date: Wed, 25 Jan 2006 23:17:49 +0000 Subject: [Tutor] Controling my loops and redundant code?!? In-Reply-To: <024801c621e0$978d5250$0b01a8c0@xp> References: <024801c621e0$978d5250$0b01a8c0@xp> Message-ID: Alan Many thanks, that is really useful. I will go through this a bit at a time over the next few days to ensure I understand what I am doing! I think functions come in the next chapter! Jon On 25/01/06, Alan Gauld wrote: > > Hi Jon, > > > 1. I am sure I have written far more code than required. > > Where could I have made some shorcuts? > > Probably but shortcuts are not necesasarily a good thing > if they obscure readability... > > However one area that would clean it up a bit is if you were to > use a dictionary rather than lists for the attributes(see below): > > > # Set max number of available points > > POINTS_POOL = 30 > > Thus duplicates available_points below. You only really need it once... > although I see that you modify avail... Might be better to do it by > assigning this constant as the initial value of available_points: > > available_points = POINTS_POOL > > > # store attribute values > > attributes = [["Strength", 0], ["Health", 0], > > ["Wisdom", 0], ["Dexterity",0]] > > Use a dictionary here instead: > > attributes = {'Strength': 0, 'Health':0, 'Wisdom':0, Dexterity:0} > > >strength = attributes[0] > >health = attributes[1] > >wisdom = attributes[2] > >dexterity = attributes[3] > > and you shouldn't need these now.... > > > available_points = 30 > used_points = 0 > attribute_value = "" > > choice = None > while choice != "0": > print """ > ----------------- > """ > choice = raw_input("Choice: ") > > # show attributes option > > elif choice == "1": > > print "Your attributes are as follows:\n" > > print "\t",strength[0], strength[1] > > print '\t Strength', attributes['Strength'] > > is easier to read I think. > > # edit attributes option > > elif choice == "2": > > # set strength attribute > > print "\nYou have",strength[1] + available_points,"points > > available." > > print '\n You have', attributes['Strength'] + available_points,'points' > > Although I personally prefer to use string formatting: > > print '\n You have %d points', (attributes['Strength'] + available_points) > > > if attribute_value > (strength[1] + available_points): > > Since you do the sum twice I'd store the value up top > > avail_strength = attributes['Strength'] + available_points > > And use avail_strength in both the print and comparison. > > > strength[1] = attribute_value > > used_points = strength[1] + health[1] + wisdom[1] + dexterity[1] > > You can use the sum() function here: > > used_points = sum(attributes.values()) > > > Also since you are repeating almost exactly the same > code for each attribute you coiuld create a function that > takes the attribute name as a parameter. > Have you come across functions yet? If not don't worry > this approach works it just means more typing and > multiple changes to fix things. > > Hope those points help a little. > > Alan G > Author of the learn to program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld > > > -- Best Regards Jon Moore -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060125/c4c839cd/attachment.htm From jonathan.r.moore at gmail.com Thu Jan 26 00:23:06 2006 From: jonathan.r.moore at gmail.com (Jon Moore) Date: Wed, 25 Jan 2006 23:23:06 +0000 Subject: [Tutor] Dictionaries Message-ID: Hi Is there anyway to print informtation from dictionaries better than this?: >>> pairs = {"Jon Moore": "Tony Moore", "Simon Nightingale": "John Nightingale", "David Willett": "Bernard Willet", "John Jackson": "Stuart Jackson", "James Southey": "Richard Southey", "William Forsythe": "Shaun Forsythe"} >>> print pairs.keys() ['David Willett', 'Jon Moore', 'John Jackson', 'Simon Nightingale', 'James Southey', 'William Forsythe'] >>> Is there no way to make it a nice list as I want to print the keys and values next to each other in a list such as: Jon Moore Tony Moore Simon Nightingale John Nightingale David Willett Bernard Willet John Jackson Stuart Jackson James Southey Richard Southey William Forsythe Shaun Forsythe For anyone who is wondering, it is to show father/son pairs. Next is to add grandfathers *eek*. -- Best Regards Jon Moore -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060125/3faa6605/attachment.html From intercodes at gmail.com Thu Jan 26 00:36:07 2006 From: intercodes at gmail.com (Intercodes) Date: Thu, 26 Jan 2006 05:06:07 +0530 Subject: [Tutor] mod_python and other web frameworks In-Reply-To: References: <37e70e3b0601251059h4c2e8d69i527b79062a050ea2@mail.gmail.com> <37e70e3b0601251245q3fc918beo6cc35774fea5739b@mail.gmail.com> Message-ID: <37e70e3b0601251536v36d37fcfxf428a5bcb99cb3c2@mail.gmail.com> Thanks for the input guys. I think ill go with - Quixote - mod_python - postgres - XHTML Ill let you know if I have done something useful with the above four :D TY Intercodes >If you're looking to do some Python coding to put your site together, >you might take a gander at Quixote >(http://www.mems-exchange.org/software/quixote/). From what I've >seen, it's the closest thing to coding a web site in Python. It works >best with SCGI, but also with regular CGI and mod_python. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060126/ebd367e6/attachment.htm From benvinger at yahoo.co.uk Thu Jan 26 00:44:07 2006 From: benvinger at yahoo.co.uk (Ben Vinger) Date: Wed, 25 Jan 2006 23:44:07 +0000 (GMT) Subject: [Tutor] mod_python and other web frameworks In-Reply-To: <37e70e3b0601251237n217d7f32w6e4c2ec75074e28b@mail.gmail.com> Message-ID: <20060125234407.62860.qmail@web25805.mail.ukl.yahoo.com> --- Intercodes wrote: > List: I am still open to suggestions. Being also keen to write better web apps in Python, I've spent a considerable amount of time reading about this (and it is indeed confusing), I've opted to try out something like Pylons or Turbogears. One thing I will say though, is that most of the frameworks you've read about can be run on top of mod_python. So mod_python is not one of the lot - it is essential on Apache unless you opt to use CGI or FCGI. But as I understand it, you would always opt for mod_python over CGI or FCGI on a high-traffic website, though CGI or FCGI is of course fine for smaller things. But mod_python is not so easy to work with and it will only work on Apache. So it seems best to choose something else and run that through mod_python when you're on Apache. ___________________________________________________________ Yahoo! Messenger - NEW crystal clear PC to PC calling worldwide with voicemail http://uk.messenger.yahoo.com From john at fouhy.net Thu Jan 26 02:00:28 2006 From: john at fouhy.net (John Fouhy) Date: Thu, 26 Jan 2006 14:00:28 +1300 Subject: [Tutor] Dictionaries In-Reply-To: References: Message-ID: <5e58f2e40601251700x218b0834t@mail.gmail.com> On 26/01/06, Jon Moore wrote: > Hi > > Is there anyway to print informtation from dictionaries better than this?: Well, you can print the value too if you want :-) eg: >>> pairs = {"Jon Moore": "Tony Moore", ... "Simon Nightingale": "John Nightingale", ... "David Willett": "Bernard Willet", ... "John Jackson": "Stuart Jackson", ... "James Southey": "Richard Southey", ... "William Forsythe": "Shaun Forsythe"} >>> for name in pairs: ... print name, pairs[name] ... David Willett Bernard Willet Jon Moore Tony Moore John Jackson Stuart Jackson Simon Nightingale John Nightingale James Southey Richard Southey William Forsythe Shaun Forsythe That is a bit ugly. We could at least put something between the names so we know where one name ends and the next begins! >>> for name in pairs: ... print name, '::', pairs[name] ... David Willett :: Bernard Willet Jon Moore :: Tony Moore John Jackson :: Stuart Jackson Simon Nightingale :: John Nightingale James Southey :: Richard Southey William Forsythe :: Shaun Forsythe We could have achieved the same thing by using string formatting operations --- see http://python.org/doc/2.4.2/lib/typesseq-strings.html for details. You'll want to have at least some familiarity with them if you are doing any kind of string building! In this case, the example looks like this: >>> for name in pairs: ... print '%s :: %s' % (name, pairs[name]) ... David Willett :: Bernard Willet Jon Moore :: Tony Moore John Jackson :: Stuart Jackson Simon Nightingale :: John Nightingale James Southey :: Richard Southey William Forsythe :: Shaun Forsythe Of course, that doesn't line up the two columns. If you want to do that, the first thing you'll need to do is figure out how wide the columns need to be --- which means looking through all the key/value pairs and seeing how long each one is. We could do that like this: >>> maxKey, maxValue = 0, 0 >>> for name in pairs: ... if len(name) > maxKey: ... maxKey = len(name) ... if len(pairs[name]) > maxValue: ... maxValue = len(pairs[name]) ... >>> maxKey, maxValue (17, 16) (you could also do it in one line with a clever list comprehension, but that's a bit more opaque [1]) Once we've got those, we can work out how much padding we need for each name. So, we could do this: >>> for name in pairs: ... print name, ' '*(maxKey-len(name)), pairs[name], ' '*(maxValue-len(pairs[name])) ... David Willett Bernard Willet Jon Moore Tony Moore John Jackson Stuart Jackson Simon Nightingale John Nightingale James Southey Richard Southey William Forsythe Shaun Forsythe (did you know that you can multiply strings? '.'*5 == '.....') Using a comma in a print statement adds an extra space, so it might be a bit tricky getting your formatting right. If we use string formatting operations, it's a lot easier: >>> for name in pairs: ... print '%*s --> %*s' % (maxKey, name, maxValue, pairs[name]) ... David Willett --> Bernard Willet Jon Moore --> Tony Moore John Jackson --> Stuart Jackson Simon Nightingale --> John Nightingale James Southey --> Richard Southey William Forsythe --> Shaun Forsythe Hmm, everything's right-justified. We can left-justify by adding a '-' to the length field in the string. >>> for name in pairs: ... print '%*s --> %-*s' % (maxKey, name, maxValue, pairs[name]) ... David Willett --> Bernard Willet Jon Moore --> Tony Moore John Jackson --> Stuart Jackson Simon Nightingale --> John Nightingale James Southey --> Richard Southey William Forsythe --> Shaun Forsythe HTH! -- John. [1] Ok, I couldn't resist. Here it is: >>> mK, mV = [max(x) for x in zip(*[(len(a), len(b)) for a, b in pairs.items()])] >>> mK, mV (17, 16) I guess that's technically two list comprehensions, but it does only iterate through pairs once. From kent37 at tds.net Thu Jan 26 02:15:08 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 25 Jan 2006 20:15:08 -0500 Subject: [Tutor] strings & splitting In-Reply-To: References: <024001c621dd$233b3690$0b01a8c0@xp> Message-ID: <43D8229C.4030900@tds.net> Liam Clarke wrote: > Hi, > > Thanks Kent, I'll check out the CSV module. I had a go with Pyparsing > awhile ago, and it's clocking in at the 3 minute mark also. > > Alan - the data is of the form - > > a = { > b = 1 > c = 2 > d = { e = { f = 4 g = "Ultimate Showdown of Ultimate Destiny" } h = > { i j k } } > } > > Everything is whitespace delimited. I'd like to turn it into > > ["a", "=", "{", "b", "=", "1", > "c", "=", "2", "d", "=", "{", > "e", "=", "{", "f", "=", "4", "g", "=", > "\"Ultimate Showdown of Ultimate Destiny\"", > "}", "h", "=", "{", "i", "j", "k", "}", "}"] > This is close - it strips the quotes from the quoted string and doubled spaces show up as an empty field. The empty field is easy to strip. You could add quotes back to any field that contains spaces. data = '''a = { b = 1 c = 2 d = { e = { f = 4 g = "Ultimate Showdown of Ultimate Destiny" } h = { i j k } } }'''.splitlines() import csv tokens = [] for line in csv.reader(data, delimiter=' '): tokens.extend(line) print tokens #### prints ['a', '=', '{', 'b', '=', '1', 'c', '=', '2', 'd', '=', '{', 'e', '=', '', '{', 'f', '', '=', '4', 'g', '=', 'Ultimate Showdown of Ultimate Destiny', '}', 'h', '=', '{', 'i', 'j', 'k', '}', '}', '}'] Kent From kent37 at tds.net Thu Jan 26 02:23:04 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 25 Jan 2006 20:23:04 -0500 Subject: [Tutor] Dictionaries In-Reply-To: References: Message-ID: <43D82478.7090703@tds.net> Jon Moore wrote: > Hi > > Is there anyway to print informtation from dictionaries better than this?: > > >>> pairs = {"Jon Moore": "Tony Moore", > "Simon Nightingale": "John Nightingale", > "David Willett": "Bernard Willet", > "John Jackson": "Stuart Jackson", > "James Southey": "Richard Southey", > "William Forsythe": "Shaun Forsythe"} > >>> print pairs.keys() > ['David Willett', 'Jon Moore', 'John Jackson', 'Simon Nightingale', > 'James Southey', 'William Forsythe'] > >>> > > Is there no way to make it a nice list as I want to print the keys and > values next to each other in a list such as: Of course there is :-) >>> for father, son in pairs.iteritems(): ... print '%-20s %s' % (father, son) ... David Willett Bernard Willet Jon Moore Tony Moore John Jackson Stuart Jackson Simon Nightingale John Nightingale James Southey Richard Southey William Forsythe Shaun Forsythe pairs.iteritems() iterates over key, value pairs. The string formatting operations are very handy for formatted output. http://docs.python.org/lib/typesseq-strings.html Kent > > Jon Moore Tony Moore > Simon Nightingale John Nightingale > David Willett Bernard Willet > John Jackson Stuart Jackson > James Southey Richard Southey > William Forsythe Shaun Forsythe > > For anyone who is wondering, it is to show father/son pairs. Next is to > add grandfathers *eek*. > -- > Best Regards > > Jon Moore > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From alan.gauld at freenet.co.uk Thu Jan 26 09:05:38 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 26 Jan 2006 08:05:38 -0000 Subject: [Tutor] Dictionaries References: Message-ID: <027f01c6224f$4b2fea70$0b01a8c0@xp> > Is there anyway to print informtation from dictionaries better than this?: For formatted printing look at the print format operator '%' You can specify field sizes, justification etc thus : >>> pairs = {"Jon Moore": "Tony Moore", "Simon Nightingale": "John Nightingale", "David Willett": "Bernard Willet", "John Jackson": "Stuart Jackson", "James Southey": "Richard Southey", "William Forsythe": "Shaun Forsythe"} >>> print pairs.keys() ['David Willett', 'Jon Moore', 'John Jackson', 'Simon Nightingale', 'James Southey', 'William Forsythe'] >>> for father,son in pairs.items: ... print "%20s\t%20s" % (father,son) Which will print father and son each in a field 20 characters wide with a tab between them. The docs on the format operator are here: http://docs.python.org/lib/typesseq-strings.html HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From jonathan.r.moore at gmail.com Thu Jan 26 10:03:07 2006 From: jonathan.r.moore at gmail.com (Jon Moore) Date: Thu, 26 Jan 2006 09:03:07 +0000 Subject: [Tutor] Dictionaries In-Reply-To: <43D82478.7090703@tds.net> References: <43D82478.7090703@tds.net> Message-ID: Kent Thanks! I have not come accross string formatting yet, but I can see how the for statement works. How would I modify this to just print either the values or keys? Jon On 26/01/06, Kent Johnson wrote: > > Jon Moore wrote: > > Hi > > > > Is there anyway to print informtation from dictionaries better than > this?: > > > > >>> pairs = {"Jon Moore": "Tony Moore", > > "Simon Nightingale": "John Nightingale", > > "David Willett": "Bernard Willet", > > "John Jackson": "Stuart Jackson", > > "James Southey": "Richard Southey", > > "William Forsythe": "Shaun Forsythe"} > > >>> print pairs.keys() > > ['David Willett', 'Jon Moore', 'John Jackson', 'Simon Nightingale', > > 'James Southey', 'William Forsythe'] > > >>> > > > > Is there no way to make it a nice list as I want to print the keys and > > values next to each other in a list such as: > > Of course there is :-) > >>> for father, son in pairs.iteritems(): > ... print '%-20s %s' % (father, son) > ... > David Willett Bernard Willet > Jon Moore Tony Moore > John Jackson Stuart Jackson > Simon Nightingale John Nightingale > James Southey Richard Southey > William Forsythe Shaun Forsythe > > pairs.iteritems() iterates over key, value pairs. The string formatting > operations are very handy for formatted output. > http://docs.python.org/lib/typesseq-strings.html > > Kent > > > > > Jon Moore Tony Moore > > Simon Nightingale John Nightingale > > David Willett Bernard Willet > > John Jackson Stuart Jackson > > James Southey Richard Southey > > William Forsythe Shaun Forsythe > > > > For anyone who is wondering, it is to show father/son pairs. Next is to > > add grandfathers *eek*. > > -- > > Best Regards > > > > Jon Moore > > > > > > ------------------------------------------------------------------------ > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Best Regards Jon Moore -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060126/eb87db34/attachment.htm From jonathan.r.moore at gmail.com Thu Jan 26 12:19:54 2006 From: jonathan.r.moore at gmail.com (Jon Moore) Date: Thu, 26 Jan 2006 11:19:54 +0000 Subject: [Tutor] Adding items to dictionaries Message-ID: Hi, I have the following dictionary: pairs = {"Jon Moore": ["Tony Moore", "Stanley Moore"], "Simon Nightingale": ["John Nightingale", "Alan Nightingale"], "David Willett": ["Bernard Willet", "Robert Willet"], "John Jackson": ["John Jackson", "Peter Jackson"], "James Southey": ["Richard Southey", "Paul Southey"], "Shaun Forsythe": ["William Forsythe", "Angus Forsythe"], "Daniel Geach": ["Mike Geach", "Andy Geach"]} Where the names represent a son, father and grandfather. I am trying to add a new term and related definitions to the dictionary, but my code does not seem to work: son = raw_input("Please enter the name of the Son: ") if son not in pairs: father = raw_input("Who is the Father?: ") grandfather = raw_input("What is the Grand Father?: ") pairs[son][0] = father pairs[son][1] = grandfather print "\n", son, ",", father, "and" ,grandfather, "have been added." else: print "\nThat Son already exists!" The error I get is: Please enter the name of the Son: Steven Bates Who is the Father?: Alan Bates What is the Grand Father?: Master Bates Traceback (most recent call last): File "C:\Documents and Settings\Administrator\Desktop\FOO\transfer\whos_your_daddy_and_grandaddy.py", line 65, in ? pairs[son][0] = father KeyError: 'Steven Bates' >>> Where am I going wrong? -- Best Regards Jon Moore -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060126/98b7144f/attachment.html From kent37 at tds.net Thu Jan 26 12:31:41 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 26 Jan 2006 06:31:41 -0500 Subject: [Tutor] Dictionaries In-Reply-To: References: <43D82478.7090703@tds.net> Message-ID: <43D8B31D.4010904@tds.net> Jon Moore wrote: > Kent > > Thanks! I have not come accross string formatting yet, but I can see how > the for statement works. > > How would I modify this to just print either the values or keys? Use for key in pairs.iterkeys(): or for value in pairs.itervalues(): and change the print statement appropriately. This page shows the operations available on a dict: http://docs.python.org/lib/typesmapping.html Kent > > Jon > > On 26/01/06, *Kent Johnson* > wrote: > > Jon Moore wrote: > > Hi > > > > Is there anyway to print informtation from dictionaries better > than this?: > > > > >>> pairs = {"Jon Moore": "Tony Moore", > > "Simon Nightingale": "John Nightingale", > > "David Willett": "Bernard Willet", > > "John Jackson": "Stuart Jackson", > > "James Southey": "Richard Southey", > > "William Forsythe": "Shaun Forsythe"} > > >>> print pairs.keys() > > ['David Willett', 'Jon Moore', 'John Jackson', 'Simon Nightingale', > > 'James Southey', 'William Forsythe'] > > >>> > > > > Is there no way to make it a nice list as I want to print the > keys and > > values next to each other in a list such as: > > Of course there is :-) > >>> for father, son in pairs.iteritems(): > ... print '%-20s %s' % (father, son) > ... > David Willett Bernard Willet > Jon Moore Tony Moore > John Jackson Stuart Jackson > Simon Nightingale John Nightingale > James Southey Richard Southey > William Forsythe Shaun Forsythe > > pairs.iteritems() iterates over key, value pairs. The string formatting > operations are very handy for formatted output. > http://docs.python.org/lib/typesseq-strings.html > > Kent > > > > > Jon Moore Tony Moore > > Simon Nightingale John Nightingale > > David Willett Bernard Willet > > John Jackson Stuart Jackson > > James Southey Richard Southey > > William Forsythe Shaun Forsythe > > > > For anyone who is wondering, it is to show father/son pairs. Next > is to > > add grandfathers *eek*. > > -- > > Best Regards > > > > Jon Moore > > > > > > > ------------------------------------------------------------------------ > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > > > > -- > Best Regards > > Jon Moore From wkranec at gmail.com Thu Jan 26 12:45:38 2006 From: wkranec at gmail.com (wkranec at gmail.com) Date: Thu, 26 Jan 2006 06:45:38 -0500 Subject: [Tutor] mod_python and other web frameworks In-Reply-To: <20060125234407.62860.qmail@web25805.mail.ukl.yahoo.com> References: <37e70e3b0601251237n217d7f32w6e4c2ec75074e28b@mail.gmail.com> <20060125234407.62860.qmail@web25805.mail.ukl.yahoo.com> Message-ID: <32b77d5a0601260345u40abf5c5td9c5a8c31c51b52f@mail.gmail.com> There seems to be a discussion about this sort of thing every other week or so, and I'm always surprised that no one mentions Cheetah Templates (www.cheetahtemplate.org). It's useful for both web and non-Web applications, and has a straightforward syntax that pretty much *is* Python. For web programming, it can be used for straight up CGI, or in a mod_python type setup. I have used it several times and really enjoyed it. There's alot of work being done right now in preparation for a 2.0 release, so the web site should be very up to date, as well as the tutorial / user's guide. Check it out! Bill On 1/25/06, Ben Vinger wrote: > > --- Intercodes wrote: > > > List: I am still open to suggestions. > > Being also keen to write better web apps in Python, > I've spent a considerable amount of time reading about > this (and it is indeed confusing), I've opted to try > out something like Pylons or Turbogears. > One thing I will say though, is that most of the > frameworks you've read about can be run on top of > mod_python. So mod_python is not one of the lot - it > is essential on Apache unless you opt to use CGI or > FCGI. But as I understand it, you would always opt for > mod_python over CGI or FCGI on a high-traffic website, > though CGI or FCGI is of course fine for smaller > things. > But mod_python is not so easy to work with and it will > only work on Apache. So it seems best to choose > something else and run that through mod_python when > you're on Apache. > > > > > > > ___________________________________________________________ > Yahoo! Messenger - NEW crystal clear PC to PC calling worldwide with voicemail http://uk.messenger.yahoo.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Thu Jan 26 14:07:10 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 26 Jan 2006 08:07:10 -0500 Subject: [Tutor] Adding items to dictionaries In-Reply-To: References: Message-ID: <43D8C97E.7010809@tds.net> Jon Moore wrote: > Hi, > > I have the following dictionary: > > pairs = {"Jon Moore": ["Tony Moore", "Stanley Moore"], > "Simon Nightingale": ["John Nightingale", "Alan Nightingale"], > "David Willett": ["Bernard Willet", "Robert Willet"], > "John Jackson": ["John Jackson", "Peter Jackson"], > "James Southey": ["Richard Southey", "Paul Southey"], > "Shaun Forsythe": ["William Forsythe", "Angus Forsythe"], > "Daniel Geach": ["Mike Geach", "Andy Geach"]} > > Where the names represent a son, father and grandfather. > > I am trying to add a new term and related definitions to the dictionary, > but my code does not seem to work: > > son = raw_input("Please enter the name of the Son: ") > if son not in pairs: > father = raw_input("Who is the Father?: ") > grandfather = raw_input("What is the Grand Father?: ") > pairs[son][0] = father > pairs[son][1] = grandfather > print "\n", son, ",", father, "and" ,grandfather, "have been > added." > else: > print "\nThat Son already exists!" > > The error I get is: > > pairs[son][0] = father > KeyError: 'Steven Bates' > >>> > > Where am I going wrong? The problem is, when you say pairs[son][0] = father pairs[son] does not yet exist. This is on the left side of an assignment, but it is really an access to pair[son]. It is as if you had written temp = pairs[son] temp[0] = father You get a KeyError accessing pairs[son]. The solution is to create a new list for the (father, grandfather) pair, and assign that to pairs[son]: ancestors = [father, grandfather] pairs[son] = ancestors You might want to rethink how you are storing the data. (father, grandfather) is actually a (son, father) pair so you might want to store them as another entry in the dictionary. Also two sons could have the same father and grandfather; with your scheme you will store the (father, grandfather) pair twice. In general this kind of duplication of data is better avoided. You might also want to Google 'python genealogy'. Kent From epost2 at gmail.com Thu Jan 26 14:07:50 2006 From: epost2 at gmail.com (Elderely Geek) Date: Thu, 26 Jan 2006 14:07:50 +0100 Subject: [Tutor] smarter way of looping Message-ID: Hi, I`m a python newbie and could use some help. I often do a loop over arbitrary number of sequences. I do it like this: for elem1 in seq1: for elem2 in seq2: do whatever seq1,seq2 this isn`t nice I think. Is there some way I can say myiterator=geniousfunction(seq1,seq2,seq3) and then myiterator.next() and have it return the corresponding elemnts from all sequences like if seq1 = ['a','b'] seq2 = [1,2] I could get a 1 a 2 b 1 b 2 also, how do you loop over all the elements that can be returned by myiterator? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060126/1db985d6/attachment.htm From alan.gauld at freenet.co.uk Thu Jan 26 14:40:45 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 26 Jan 2006 13:40:45 -0000 Subject: [Tutor] Dictionaries References: <027f01c6224f$4b2fea70$0b01a8c0@xp> Message-ID: <029501c6227e$1c547ac0$0b01a8c0@xp> >>>> for father,son in pairs.items: > ... print "%20s\t%20s" % (father,son) Oops! Should have been for father,son in pairs.items(): Sorry, Alan G. From alan.gauld at freenet.co.uk Thu Jan 26 14:43:22 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 26 Jan 2006 13:43:22 -0000 Subject: [Tutor] Dictionaries References: <43D82478.7090703@tds.net> Message-ID: <029b01c6227e$79eb3840$0b01a8c0@xp> > How would I modify this to just print either the values or keys? Just ask for the values or the keys! for value in pairs.values() print value for key in pairs.keys() print key for key,value in pairs.items() print key print value Dictionaries are extremely powerful data containers. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Thu Jan 26 14:48:51 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 26 Jan 2006 08:48:51 -0500 Subject: [Tutor] smarter way of looping In-Reply-To: References: Message-ID: <43D8D343.6090909@tds.net> Elderely Geek wrote: > Hi, > I`m a python newbie and could use some help. > > I often do a loop over arbitrary number of sequences. I do it like this: > > for elem1 in seq1: > for elem2 in seq2: > do whatever seq1,seq2 > > this isn`t nice I think. Is there some way I can say > myiterator=geniousfunction(seq1,seq2,seq3) > > and then myiterator.next() and have it return the corresponding elemnts > from all sequences like if > > seq1 = ['a','b'] > seq2 = [1,2] > > I could get > > a 1 > a 2 > b 1 > b 2 This is a perennial topic on comp.lang.python and there are many clever ways to do it. The most straightforward way is to use a recursive generator. The idea is, at each step, combine each element of the first sequence with each sequence generated from the remaining sequences. Here is one way to do it: def combine(*seqs): if not seqs: yield [] else: for item in seqs[0]: for subitem in combine(*seqs[1:]): yield [item] + subitem seq1 = ['a','b'] seq2 = [1,2] for seq in combine(seq1, seq2): print seq print list(combine(seq1, seq2)) This uses some fairly advanced bits of Python: arbitrary argument lists (I can't find a good doc for this) generators: http://www.python.org/doc/2.3.5/whatsnew/section-generators.html and recursion. > > also, how do you loop over all the elements that can be returned by > myiterator? As in the example above, you can iterate it with a for loop, or convert to a list. Kent > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From Christian.Wyglendowski at greenville.edu Thu Jan 26 14:37:08 2006 From: Christian.Wyglendowski at greenville.edu (Christian Wyglendowski) Date: Thu, 26 Jan 2006 07:37:08 -0600 Subject: [Tutor] mod_python and other web frameworks Message-ID: Some others have already mentioned TurboGears, but since it sounds like you want more control perhaps, I would recommend going with CherryPy (http://www.cherrypy.org). You basically write python code and then expose it to the web (or intranet or whatever). # simple example import cherrypy import time class MySection(object): @cherrypy.expose def index(self): yield "

Hello, world!

" yield "
Check the time" # if you are using Python 2.3, you do the following to expose a method # index.exposed = True @cherrypy.expose def time(self): return "

The current time is %s

" % self.get_time() # this method is not exposed and thus not accessible from the web def get_time(self): return time.ctime() # mount the class at the server root cherrypy.root = MySection() cherrypy.server.start() # end of example You can then run that script and visit http://localhost:8080/. That will call the "index" method of the MySection object mounted at the server root. You can also visit http://localhost:8080/time. However, http://localhost:8080/get_time is _not_ available to the web, because it is not "exposed". Anyhow, CherryPy is very pythonic and flexible. Use whatever DB you want (or flat files or ...). Use whatever templating language you want (or just return html from your methods. Anyhow, that's probably more info than you wanted. Good luck! Christian http://www.dowski.com ps And "as a beginner", I would _not_ start with something like mod_python ;-) -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Intercodes Sent: Wednesday, January 25, 2006 12:59 PM To: tutor at python.org Subject: [Tutor] mod_python and other web frameworks Hello everyone, Disclaimer: Beginner. I have an idea of coding a web application and decided to do it entirely with python (reddit style). I started looking for web programming in python and somehow I saw mod_python first. Iam perusing the help document now. Few minutes of browsing confused my mind entirely , since it seems there are about 20 different web frameworks available for python. I am left clueless as to pick which one. I have an soft side towards the one I picked first. Considering yourself as a beginner to python ,do you prefer mod_python over all other framework?. Say if you want to create a blog , will mod_python suffice? And is mod_python and cgi (the python lib) different? -- Intercodes From jonathan.r.moore at gmail.com Thu Jan 26 14:53:02 2006 From: jonathan.r.moore at gmail.com (Jon Moore) Date: Thu, 26 Jan 2006 13:53:02 +0000 Subject: [Tutor] Adding items to dictionaries In-Reply-To: <43D8C97E.7010809@tds.net> References: <43D8C97E.7010809@tds.net> Message-ID: Kent Thanks again. I have a question (see below). On 26/01/06, Kent Johnson wrote: > > Jon Moore wrote: > > Hi, > > > > I have the following dictionary: > > > > pairs = {"Jon Moore": ["Tony Moore", "Stanley Moore"], > > "Simon Nightingale": ["John Nightingale", "Alan Nightingale"], > > "David Willett": ["Bernard Willet", "Robert Willet"], > > "John Jackson": ["John Jackson", "Peter Jackson"], > > "James Southey": ["Richard Southey", "Paul Southey"], > > "Shaun Forsythe": ["William Forsythe", "Angus Forsythe"], > > "Daniel Geach": ["Mike Geach", "Andy Geach"]} > > > > Where the names represent a son, father and grandfather. > > > > I am trying to add a new term and related definitions to the dictionary, > > but my code does not seem to work: > > > > son = raw_input("Please enter the name of the Son: ") > > if son not in pairs: > > father = raw_input("Who is the Father?: ") > > grandfather = raw_input("What is the Grand Father?: ") > > pairs[son][0] = father > > pairs[son][1] = grandfather > > print "\n", son, ",", father, "and" ,grandfather, "have been > > added." > > else: > > print "\nThat Son already exists!" > > > > The error I get is: > > > > pairs[son][0] = father > > KeyError: 'Steven Bates' > > >>> > > > > Where am I going wrong? > > The problem is, when you say > pairs[son][0] = father > > pairs[son] does not yet exist. This is on the left side of an > assignment, but it is really an access to pair[son]. It is as if you had > written > temp = pairs[son] > temp[0] = father > > You get a KeyError accessing pairs[son]. > > The solution is to create a new list for the (father, grandfather) pair, > and assign that to pairs[son]: > > ancestors = [father, grandfather] > pairs[son] = ancestors > > You might want to rethink how you are storing the data. (father, > grandfather) is actually a (son, father) pair so you might want to store > them as another entry in the dictionary. Also two sons could have the > same father and grandfather; with your scheme you will store the > (father, grandfather) pair twice. In general this kind of duplication of > data is better avoided. Good point, but I have no idea how to do this! Could you show me? You might also want to Google 'python genealogy'. > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Best Regards Jon Moore -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060126/f5eb27ee/attachment.html From intercodes at gmail.com Thu Jan 26 15:03:34 2006 From: intercodes at gmail.com (Intercodes) Date: Thu, 26 Jan 2006 19:33:34 +0530 Subject: [Tutor] mod_python and other web frameworks In-Reply-To: References: Message-ID: <37e70e3b0601260603y2e89ec1fh8984d10b8c055735@mail.gmail.com> Christian, You are certainly right. I couldn't get anything apart from "Hello world" coding in mod_python. The mod_python manual is also bit vague, not for beginners. I wonder why there aren't any good tutorials on mod_python. I am having a look at quixote as a developer in this list suggested. I would take a look at cherrypy if quixote is too deep for me. Thanks for your time and the example. I believe your website is written completely in cherrypy. Working on so many projects ,nice work. Intercodes # simple example > import cherrypy > import time > > class MySection(object): > @cherrypy.expose > def index(self): > yield "

Hello, world!

" > yield "Check the time" > # if you are using Python 2.3, you do the following to expose a method > # index.exposed = True > > @cherrypy.expose > def time(self): > return "

The current time is %s

" % self.get_time() > > # this method is not exposed and thus not accessible from the web > def get_time(self): > return time.ctime() > > # mount the class at the server root > cherrypy.root = MySection() > > cherrypy.server.start() > # end of example > > You can then run that script and visit http://localhost:8080/. That > will call the "index" method of the MySection object mounted at the > server root. You can also visit http://localhost:8080/time. However, > http://localhost:8080/get_time is _not_ available to the web, because it > is not "exposed". > > Anyhow, CherryPy is very pythonic and flexible. Use whatever DB you > want (or flat files or ...). Use whatever templating language you want > (or just return html from your methods. > > Anyhow, that's probably more info than you wanted. Good luck! > > Christian > http://www.dowski.com > > ps And "as a beginner", I would _not_ start with something like > mod_python ;-) > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060126/f9e2831c/attachment.htm From alan.gauld at freenet.co.uk Thu Jan 26 15:09:52 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 26 Jan 2006 14:09:52 -0000 Subject: [Tutor] Adding items to dictionaries References: Message-ID: <02b101c62282$2ff6e3c0$0b01a8c0@xp> > pairs[son][0] = father > KeyError: 'Steven Bates' > Where am I going wrong? A KeyError means you are trying to access an object that does not exist in the dictionary. And this is true, you haven't added anything for Steven Bates yet, but you are trying to access his parents list. You need to create an associated list which you can then edit. pairs[son] = [0,0] # need to put dummy data in pairs[son][0] = father pairs[son][1] = grandfather HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Thu Jan 26 15:18:25 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 26 Jan 2006 14:18:25 -0000 Subject: [Tutor] smarter way of looping References: Message-ID: <02b701c62283$5f35a850$0b01a8c0@xp> > I often do a loop over arbitrary number of sequences. I do it like this: > >for elem1 in seq1: > for elem2 in seq2: > do whatever seq1,seq2 > > this isn`t nice I think. Actually its pretty common and not that ugly. But... > myiterator=geniousfunction(seq1,seq2,seq3) > > and then myiterator.next() and have it return the corresponding elemnts > from all sequences The problem is that there are so many different ways you can do that. Python offers several options but none of them solve all the cases. Look at the documentation for List Comprehensions zip() map() filter() reduce() > seq1 = ['a','b'] > seq2 = [1,2] > a 1 > a 2 > b 1 > b 2 [a,b for a in seq1 for b in seq2] > how do you loop over all the elements that can be returned by > myiterator? return the options as a list of tuples and then use the usual list iteration techniques. for elem in [a,b for a in seq1 for b in seq2]: # use elem here HTH Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From epost2 at gmail.com Thu Jan 26 16:00:13 2006 From: epost2 at gmail.com (Elderly Geek) Date: Thu, 26 Jan 2006 16:00:13 +0100 Subject: [Tutor] smarter way of looping In-Reply-To: <02b701c62283$5f35a850$0b01a8c0@xp> References: <02b701c62283$5f35a850$0b01a8c0@xp> Message-ID: On 1/26/06, Alan Gauld wrote: > > I often do a loop over arbitrary number of sequences. I do it like this: > > > >for elem1 in seq1: > > for elem2 in seq2: > > do whatever seq1,seq2 > > this isn`t nice I think. > > Actually its pretty common and not that ugly. > But... Ok, I see. I was trying to show that I`m (was) unable to pass in an arbitrary number of secuences, but the generator in one of the other posts in thread solves this, right? quite impressive that one I think > > myiterator=geniousfunction(seq1,seq2,seq3) > > > > and then myiterator.next() and have it return the corresponding elemnts > > from all sequences > > The problem is that there are so many different ways you can do that. > Python offers several options but none of them solve all the cases. > > Look at the documentation for > > List Comprehensions > zip() > map() > filter() > reduce() I will. Thanks. > > > seq1 = ['a','b'] > > seq2 = [1,2] > > a 1 > > a 2 > > b 1 > > b 2 > > [a,b for a in seq1 for b in seq2] > > > how do you loop over all the elements that can be returned by > > myiterator? > > return the options as a list of tuples and then use the usual list iteration > techniques. > > for elem in [a,b for a in seq1 for b in seq2]: > # use elem here > that`s nice. Thanks for the replies From bgailer at gmail.com Thu Jan 26 18:52:22 2006 From: bgailer at gmail.com (Bob Gailer) Date: Thu, 26 Jan 2006 09:52:22 -0800 Subject: [Tutor] Controling my loops and redundant code?!? Message-ID: <23d7abd0601260952k734be1e8pb2d61f9251de097b@mail.gmail.com> At 08:44 AM 1/25/2006, Jon Moore wrote: Hi, I have written the program below as an exercise from a book I am working my way through. Objective from book: Write a character creator program for a role-playing-game. The player should be given a pool of 30 points to spend on four attributes: strength, health, wisdom and dexterity. The player should be able to spend points from the pool on any attribute and should be also be able to take points from an attribute and put them back in the pool. Although the program meets the aim of the exercise set out in the book , there are a couple of things I am not happy with! 1. I am sure I have written far more code than required. Where could I have made some shorcuts? 2. Should the user enter a value greater than what is available, the program kicks the user all the way back to the main menu. How could I tidy this up to just loop round to ask the user to try a new value? choice = None # Set max number of available points POINTS_POOL = 30 # store attribute values attributes = [["Strength", 0], ["Health", 0], ["Wisdom", 0], ["Dexterity", 0]] Some ideas to chew on as you develop skills and understanding of programming. Separate the "essential data" from the code. The essential data are attributes, associated points and max_points. So attributes = ["Strength", "Health", "Wisdom", "Dexterity"] points = [0, 0, 0, 0] MAX_POINTS = 30 In this model the relationship between attributes and points is by position. Later you will study and use classes; then the points list will be replaced by a list of class instances, one per attribute. Develop code that operates on these lists to accomplish the various objectives. The code itself will never refer to any attribute by name! For example - to list the attributes with their points: for x in range(len(attributes)): print "\t",attributes[x], points[x] To assign values. Note I separated getting input from converting it to integer so we can see if the user's entry is convertible.: available_points = MAX_POINTS - sum(points) print "You have " + available_points + " available." for x in range(len(attributes)): cvalue = raw_input("How much would you like to assign to " + attributes[x] + " ?: ")) if cvalue.isdigit(): value = int(cvalue) else: print "Number expected" [snip] -- Bob Gailer 510-978-4454 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060126/38497fad/attachment.html From etrade.griffiths at dsl.pipex.com Thu Jan 26 19:20:48 2006 From: etrade.griffiths at dsl.pipex.com (etrade.griffiths at dsl.pipex.com) Date: Thu, 26 Jan 2006 18:20:48 +0000 Subject: [Tutor] First steps with Tkinter Message-ID: <1138299648.43d9130033149@netmail.pipex.net> Hi! Just started trying to get to grips with Python and Tkinter. Have Frederick Lundh's tutorial and am on program hello2.py which looks like this # 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() I am running from inside Pythonwin 2.4 IDE under XP Pro and every time I run hello2.py it freezes when I press "QUIT". The only way to kill it is through Alt-Ctrl-Del but this crashes Pythonwin. Any workaround for this so that I can use Tkinter from inside the IDE? BTW the same thing happend with IDLE Thanks in advance Alun Griffiths From pkraus at pelsupply.com Thu Jan 26 19:49:31 2006 From: pkraus at pelsupply.com (Paul Kraus) Date: Thu, 26 Jan 2006 13:49:31 -0500 Subject: [Tutor] Controling my loops and redundant code?!? In-Reply-To: <23d7abd0601260952k734be1e8pb2d61f9251de097b@mail.gmail.com> References: <23d7abd0601260952k734be1e8pb2d61f9251de097b@mail.gmail.com> Message-ID: <200601261349.32326.pkraus@pelsupply.com> What book are you working through? That is a pretty interesting exercise. Paul On Thursday 26 January 2006 12:52 pm, Bob Gailer wrote: > At 08:44 AM 1/25/2006, Jon Moore wrote: > > Hi, > > I have written the program below as an exercise from a book I am working my > way through. > > Objective from book: > Write a character creator program for a role-playing-game. The player > should be given a pool of 30 points to spend on four attributes: strength, > health, wisdom and dexterity. The player should be able to spend points > from the pool on any attribute and should be also be able to take points > from an attribute and put them back in the pool. > > Although the program meets the aim of the exercise set out in the book , > there are a couple of things I am not happy with! > > 1. I am sure I have written far more code than required. Where could I have > made some shorcuts? > > 2. Should the user enter a value greater than what is available, the > program kicks the user all the way back to the main menu. How could I tidy > this up to just loop round to ask the user to try a new value? > > choice = None > > # Set max number of available points > POINTS_POOL = 30 > > # store attribute values > attributes = [["Strength", 0], ["Health", 0], ["Wisdom", 0], ["Dexterity", > 0]] > > > Some ideas to chew on as you develop skills and understanding of > programming. > Separate the "essential data" from the code. The essential data are > attributes, associated points and max_points. So > > attributes = ["Strength", "Health", "Wisdom", "Dexterity"] > points = [0, 0, 0, 0] > MAX_POINTS = 30 > > In this model the relationship between attributes and points is by > position. Later you will study and use classes; then the points list will > be replaced by a list of class instances, one per attribute. > > Develop code that operates on these lists to accomplish the various > objectives. The code itself will never refer to any attribute by name! > > For example - to list the attributes with their points: > > for x in range(len(attributes)): > print "\t",attributes[x], points[x] > > To assign values. Note I separated getting input from converting it to > integer so we can see if the user's entry is convertible.: > > available_points = MAX_POINTS - sum(points) > print "You have " + available_points + " available." > for x in range(len(attributes)): > cvalue = raw_input("How much would you like to assign to " + attributes[x] > + " ?: ")) > if cvalue.isdigit(): > value = int(cvalue) > else: > print "Number expected" > > [snip] > -- > Bob Gailer > 510-978-4454 -- Paul Kraus =-=-=-=-=-=-=-=-=-=-= PEL Supply Company Network Administrator 216.267.5775 Voice 216.267.6176 Fax www.pelsupply.com =-=-=-=-=-=-=-=-=-=-= From klappnase at freenet.de Thu Jan 26 20:50:01 2006 From: klappnase at freenet.de (Michael Lange) Date: Thu, 26 Jan 2006 20:50:01 +0100 Subject: [Tutor] First steps with Tkinter In-Reply-To: <1138299648.43d9130033149@netmail.pipex.net> References: <1138299648.43d9130033149@netmail.pipex.net> Message-ID: <20060126205001.7ddd571a.klappnase@freenet.de> On Thu, 26 Jan 2006 18:20:48 +0000 etrade.griffiths at dsl.pipex.com wrote: > > root.mainloop() > > I am running from inside Pythonwin 2.4 IDE under XP Pro and every time I run > hello2.py it freezes when I press "QUIT". The only way to kill it is through > Alt-Ctrl-Del but this crashes Pythonwin. Any workaround for this so that I > can use Tkinter from inside the IDE? BTW the same thing happend with IDLE > Hi, when running Tkinter apps from IDLE or Pythonwin, you need to comment out the call to mainloop() . This is because the IDE itself runs a Tkinter mainloop() and two of these cannot coexist in one process. I hope this helps Michael From bgailer at alum.rpi.edu Thu Jan 26 20:49:24 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu, 26 Jan 2006 11:49:24 -0800 Subject: [Tutor] Controling my loops and redundant code?!? Message-ID: <43D927C4.5040407@alum.rpi.edu> At 08:44 AM 1/25/2006, Jon Moore wrote: > Hi, > > I have written the program below as an exercise from a book I am > working my way through. > > Objective from book: > Write a character creator program for a role-playing-game. The player > should be given a pool of 30 points to spend on four attributes: > strength, health, wisdom and dexterity. The player should be able to > spend points from the pool on any attribute and should be also be able > to take points from an attribute and put them back in the pool. > > Although the program meets the aim of the exercise set out in the book > , there are a couple of things I am not happy with! > > 1. I am sure I have written far more code than required. Where could I > have made some shorcuts? > > 2. Should the user enter a value greater than what is available, the > program kicks the user all the way back to the main menu. How could I > tidy this up to just loop round to ask the user to try a new value? > > choice = None > > # Set max number of available points > POINTS_POOL = 30 > > # store attribute values > attributes = [["Strength", 0], ["Health", 0], ["Wisdom", 0], > ["Dexterity", 0]] Some ideas to chew on as you develop skills and understanding of programming. Separate the "essential data" from the code. The essential data are attributes, associated points and max_points. So attributes = ["Strength", "Health", "Wisdom", "Dexterity"] points = [0, 0, 0, 0] MAX_POINTS = 30 In this model the relationship between attributes and points is by position. Later you will study and use classes; then the points list will be replaced by a list of class instances, one per attribute. Develop code that operates on these lists to accomplish the various objectives. The code itself will never refer to any attribute by name! For example - to list the attributes with their points: for x in range(len(attributes)): print "\t",attributes[x], points[x] To assign values. Note I separated getting input from converting it to integer so we can see if the user's entry is convertible.: available_points = MAX_POINTS - sum(points) print "You have " + available_points + " available." for x in range(len(attributes)): cvalue = raw_input("How much would you like to assign to " + attributes[x] + " ?: ")) if cvalue.isdigit(): value = int(cvalue) else: print "Number expected" [snip] -- Bob Gailer 510-978-4454 From w.damen at gmail.com Thu Jan 26 20:52:57 2006 From: w.damen at gmail.com (Rinzwind) Date: Thu, 26 Jan 2006 20:52:57 +0100 Subject: [Tutor] [newbie alert] why can't I find a function that gives me the sign of an integer? Message-ID: <4677730601261152j4fc1a30dy533a8e80e76c35b7@mail.gmail.com> In basic I can use SGN to get back -1, 0, +1 if a number is <0, 0, >0. I searched on the web for a bit but sgn and sign give me way too many discussions about Decimals. python.org with numbers/digits doesn't tell about a function. Maybe Python uses a different name for it so I am not looking for the correct wording :( Sucks not knowing syntax from my memory and having to look them up alot). Wim -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060126/261eed63/attachment.html From singingxduck at gmail.com Thu Jan 26 20:57:50 2006 From: singingxduck at gmail.com (Orri Ganel) Date: Thu, 26 Jan 2006 14:57:50 -0500 Subject: [Tutor] [newbie alert] why can't I find a function that gives me the sign of an integer? In-Reply-To: <4677730601261152j4fc1a30dy533a8e80e76c35b7@mail.gmail.com> References: <4677730601261152j4fc1a30dy533a8e80e76c35b7@mail.gmail.com> Message-ID: <43D929BE.6080407@gmail.com> Rinzwind wrote: > In basic I can use SGN to get back -1, 0, +1 if a number is <0, 0, >0. > I searched on the web for a bit but sgn and sign give me way too many > discussions about Decimals. python.org with > numbers/digits doesn't tell about a function. > > Maybe Python uses a different name for it so I am not looking for the > correct wording :( Sucks not knowing syntax from my memory and having > to look them up alot). > > Wim > > >------------------------------------------------------------------------ > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > Well, the cmp() function does this if you compare the number to 0: >>> cmp(-34,0) -1 >>> cmp(0,0) 0 >>> cmp(23,0) 1 Of course, that's not all cmp() is good for, but it would work in this case. HTH, Orri -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060126/f0939b48/attachment.htm From w.damen at gmail.com Thu Jan 26 21:00:03 2006 From: w.damen at gmail.com (Rinzwind) Date: Thu, 26 Jan 2006 21:00:03 +0100 Subject: [Tutor] [newbie alert] why can't I find a function that gives me the sign of an integer? In-Reply-To: <43D929BE.6080407@gmail.com> References: <4677730601261152j4fc1a30dy533a8e80e76c35b7@mail.gmail.com> <43D929BE.6080407@gmail.com> Message-ID: <4677730601261200y3f3e5190wf5e0c3df9cd5e90c@mail.gmail.com> Thank you! *opens manual again* Wim On 1/26/06, Orri Ganel wrote: > > Rinzwind wrote: > > In basic I can use SGN to get back -1, 0, +1 if a number is <0, 0, >0. > I searched on the web for a bit but sgn and sign give me way too many > discussions about Decimals. python.org with numbers/digits doesn't tell > about a function. > > Maybe Python uses a different name for it so I am not looking for the > correct wording :( Sucks not knowing syntax from my memory and having to > look them up alot). > > Wim > > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.orghttp://mail.python.org/mailman/listinfo/tutor > > > Well, the cmp() function does this if you compare the number to 0: > > >>> cmp(-34,0) > -1 > >>> cmp(0,0) > 0 > >>> cmp(23,0) > 1 > > Of course, that's not all cmp() is good for, but it would work in this > case. > > HTH, > Orri > > -- > Email: singingxduck AT gmail DOT com > AIM: singingxduck > Programming Python for the fun of it. > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060126/c9309862/attachment.html From singingxduck at gmail.com Thu Jan 26 21:15:27 2006 From: singingxduck at gmail.com (Orri Ganel) Date: Thu, 26 Jan 2006 15:15:27 -0500 Subject: [Tutor] [newbie alert] why can't I find a function that gives me the sign of an integer? In-Reply-To: <4677730601261200y3f3e5190wf5e0c3df9cd5e90c@mail.gmail.com> References: <4677730601261152j4fc1a30dy533a8e80e76c35b7@mail.gmail.com> <43D929BE.6080407@gmail.com> <4677730601261200y3f3e5190wf5e0c3df9cd5e90c@mail.gmail.com> Message-ID: <43D92DDF.5020204@gmail.com> No problem. As for the main use of cmp(), btw, afaik, it's used to define custom sorting, as in the following: >>> import random >>> temp = [] >>> for i in range(10): temp.append((random.randint(0,100),random.randint(0,100),random.randint(0,100))) >>> temp [(16, 70, 87), (57, 80, 33), (14, 22, 2), (21, 92, 69), (40, 18, 90), (60, 78, 35), (3, 98, 7), (32, 21, 39), (15, 67, 15), (70, 95, 39)] >>> temp.sort(cmp=lambda x, y: cmp(x[0],y[0])) >>> temp [(3, 98, 7), (14, 22, 2), (15, 67, 15), (16, 70, 87), (21, 92, 69), (32, 21, 39), (40, 18, 90), (57, 80, 33), (60, 78, 35), (70, 95, 39)] >>> temp.sort(cmp=lambda x, y: cmp(x[1],y[1])) >>> temp [(40, 18, 90), (32, 21, 39), (14, 22, 2), (15, 67, 15), (16, 70, 87), (60, 78, 35), (57, 80, 33), (21, 92, 69), (70, 95, 39), (3, 98, 7)] >>> temp.sort(cmp=lambda x, y: cmp(x[2],y[2])) >>> temp [(14, 22, 2), (3, 98, 7), (15, 67, 15), (57, 80, 33), (60, 78, 35), (32, 21, 39), (70, 95, 39), (21, 92, 69), (16, 70, 87), (40, 18, 90)] or, without lambdas: >>> def sort(x,y): return cmp(x[0],y[0]) >>> def sort1(x,y): return cmp(x[1],y[1]) >>> def sort2(x,y): return cmp(x[2],y[2]) >>> temp.sort(cmp=sort) >>> temp [(3, 98, 7), (14, 22, 2), (15, 67, 15), (16, 70, 87), (21, 92, 69), (32, 21, 39), (40, 18, 90), (57, 80, 33), (60, 78, 35), (70, 95, 39)] >>> temp.sort(cmp=sort1) >>> temp [(40, 18, 90), (32, 21, 39), (14, 22, 2), (15, 67, 15), (16, 70, 87), (60, 78, 35), (57, 80, 33), (21, 92, 69), (70, 95, 39), (3, 98, 7)] >>> temp.sort(cmp=sort2) >>> temp [(14, 22, 2), (3, 98, 7), (15, 67, 15), (57, 80, 33), (60, 78, 35), (32, 21, 39), (70, 95, 39), (21, 92, 69), (16, 70, 87), (40, 18, 90)] Rinzwind wrote: > Thank you! > *opens manual again* > > Wim > > On 1/26/06, *Orri Ganel* > wrote: > > Well, the cmp() function does this if you compare the number to 0: > > >>> cmp(-34,0) > -1 > >>> cmp(0,0) > 0 > >>> cmp(23,0) > 1 > > Of course, that's not all cmp() is good for, but it would work in > this case. > > HTH, > Orri > >-- >Email: singingxduck AT gmail DOT com >AIM: singingxduck >Programming Python for the fun of it. > > >------------------------------------------------------------------------ > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060126/271269ce/attachment-0001.html From cspears2002 at yahoo.com Thu Jan 26 21:29:30 2006 From: cspears2002 at yahoo.com (Christopher Spears) Date: Thu, 26 Jan 2006 12:29:30 -0800 (PST) Subject: [Tutor] list.__init__() Message-ID: <20060126202930.20082.qmail@web51610.mail.yahoo.com> What purpose does list.__init__() play in the piece of code below? class Mylist(list): def __init__(self, value = []): list.__init__([]) self.concat(value) def concat(self, value): for x in value: if not x in self: self.append(x) From kent37 at tds.net Thu Jan 26 21:30:04 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 26 Jan 2006 15:30:04 -0500 Subject: [Tutor] [newbie alert] why can't I find a function that gives me the sign of an integer? In-Reply-To: <43D929BE.6080407@gmail.com> References: <4677730601261152j4fc1a30dy533a8e80e76c35b7@mail.gmail.com> <43D929BE.6080407@gmail.com> Message-ID: <43D9314C.2060308@tds.net> Orri Ganel wrote: > Rinzwind wrote: > >> In basic I can use SGN to get back -1, 0, +1 if a number is <0, 0, >0. > Well, the cmp() function does this if you compare the number to 0: > > >>> cmp(-34,0) > -1 > >>> cmp(0,0) > 0 > >>> cmp(23,0) One caution: this behaviour doesn't seem to be required, the docs allow any positive or negative integer: cmp( x, y) Compare the two objects x and y and return an integer according to the outcome. The return value is negative if x < y, zero if x == y and strictly positive if x > y. So this behaviour might differ between Python versions. Kent From kent37 at tds.net Thu Jan 26 21:38:51 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 26 Jan 2006 15:38:51 -0500 Subject: [Tutor] list.__init__() In-Reply-To: <20060126202930.20082.qmail@web51610.mail.yahoo.com> References: <20060126202930.20082.qmail@web51610.mail.yahoo.com> Message-ID: <43D9335B.9050103@tds.net> Christopher Spears wrote: > What purpose does list.__init__() play in the piece of > code below? It's an incorrect call to the base class __init__() function. This does base class initialization on the current list. The correct call is list.__init__(self) By the way this list seems to be doing the work of a set. Since Python 2.3 set types have been standard in Python (in module sets in 2.3 and the builtin type set in 2.4). Before 2.3 a dict is a better choice for rolling your own because it supports fast lookup. Kent > > class Mylist(list): > def __init__(self, value = []): > list.__init__([]) > self.concat(value) > def concat(self, value): > for x in value: > if not x in self: > self.append(x) > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From cspears2002 at yahoo.com Thu Jan 26 22:12:54 2006 From: cspears2002 at yahoo.com (Christopher Spears) Date: Thu, 26 Jan 2006 13:12:54 -0800 (PST) Subject: [Tutor] designing a class Message-ID: <20060126211254.77716.qmail@web51613.mail.yahoo.com> Here is an exercise out of Learning Python: Write a class called Mylist that shadows ("wraps") a Python list: it should overload most list operators and operations including +, indexing, iteration, slicing, and list methods such as append and sort. See the Python reference manual for a list of possible methods to support. Also, provide a constructor for your class that takes an existing list (or a Mylist instance) and copies it components inro an instance member. When I read this, I feel like a deer caught in the headlights. Where should I begin? How do I go about designing a new class? From alan.gauld at freenet.co.uk Thu Jan 26 22:53:56 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 26 Jan 2006 21:53:56 -0000 Subject: [Tutor] [newbie alert] why can't I find a function that givesme the sign of an integer? References: <4677730601261152j4fc1a30dy533a8e80e76c35b7@mail.gmail.com> <43D929BE.6080407@gmail.com> Message-ID: <02f701c622c3$01b39030$0b01a8c0@xp> >> In basic I can use SGN to get back -1, 0, +1 if a number is <0, 0, >0. > Well, the cmp() function does this if you compare the number to 0: Neat trick Orri, I'd never have thought of that one :-) Alan G. From catherine.curley at gmail.com Thu Jan 26 23:33:41 2006 From: catherine.curley at gmail.com (catherine curley) Date: Thu, 26 Jan 2006 22:33:41 +0000 Subject: [Tutor] Is this overkill? In-Reply-To: <80463c260601202245s149fd654w929cac0ab5f62b4@mail.gmail.com> References: <80463c260601202245s149fd654w929cac0ab5f62b4@mail.gmail.com> Message-ID: Bradly I'm new to python also. Have you come across any good exercises that a beginner try. I've spend some time going throught the many available turorials, but find it hard to get good exercises to try out what you learn. Catherine On 1/21/06, Bradly McConnell wrote: > > Greetings all: > > I'm new to Python, and have come across and exercise that basically > counts to 100. The idea is to accept user input for an initial > number, and then let the user add additional numbers. I wanted to > give feedback if a number selected would bring the total above 100, so > the user would select a lower number. It looks like I have it > working, but it doesn't seem very efficient. I would like any hints, > help, or comments that you can provide. Below is what I have so far. > > number = input("Please enter a number: ") > while number != 100: > additional_number = input("Please enter an additional number: ") > if additional_number + number > 100: > lower_number = input("please enter a lower number: ") > if lower_number + number > 100: > lower_number = input("Lower!") > else: > number = lower_number + number > elif additional_number + number < 100: > number = additional_number + number > else: > continue > > print "Done", number > > > Brad > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060126/4e59c89a/attachment.htm From catherine.curley at gmail.com Thu Jan 26 23:41:50 2006 From: catherine.curley at gmail.com (catherine curley) Date: Thu, 26 Jan 2006 22:41:50 +0000 Subject: [Tutor] First steps with Tkinter In-Reply-To: <1138299648.43d9130033149@netmail.pipex.net> References: <1138299648.43d9130033149@netmail.pipex.net> Message-ID: Alan As a matter of interest, did you have much knowledge of Python before you tried TKinter? I'm only a python beginner at present. Catherine On 1/26/06, etrade.griffiths at dsl.pipex.com wrote: > > Hi! > > Just started trying to get to grips with Python and Tkinter. Have > Frederick > Lundh's tutorial and am on program hello2.py which looks like this > > # 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() > > I am running from inside Pythonwin 2.4 IDE under XP Pro and every time I > run > hello2.py it freezes when I press "QUIT". The only way to kill it is > through > Alt-Ctrl-Del but this crashes Pythonwin. Any workaround for this so that > I > can use Tkinter from inside the IDE? BTW the same thing happend with IDLE > > Thanks in advance > > Alun Griffiths > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060126/fc14a99f/attachment.html From carroll at tjc.com Fri Jan 27 01:02:37 2006 From: carroll at tjc.com (Terry Carroll) Date: Thu, 26 Jan 2006 16:02:37 -0800 (PST) Subject: [Tutor] designing a class In-Reply-To: <20060126211254.77716.qmail@web51613.mail.yahoo.com> Message-ID: On Thu, 26 Jan 2006, Christopher Spears wrote: > Here is an exercise out of Learning Python: Which edition? If I recall, the second edition covers through a release of Python (2.2?) that permits direct subclassing of lists; while the earlier one came out prior to Python 2.2, and would expect you to fake it out a bit by subclassing USerList. > Write a class called Mylist that shadows ("wraps") a > Python list: Okay; what this means is that you're defining a class by subclassing the list type (or UserList type, for pre-2.2). > it should overload most list operators > and operations including... This meens you need to write a bunch of methods name __x__ where "x" is some specific name that is related to the task listed in the problem. You'll find most of these, I think, in section 3.3 of the reference Manual; see http://docs.python.org/ref/specialnames.html and the pages that follow. For some examples, > +, That would be __add__ ; see http://docs.python.org/ref/numeric-types.html > indexing, iteration, > slicing, and list methods such as append and sort. Most of these are discussed at http://docs.python.org/ref/sequence-methods.html There seem to be quite a lot of them! I'm wondering if you can skip most of them; one advantage of subclassing is to be able to rely on the superclasses implementations. > Also, provide a constructor for > your class that takes an existing list (or a Mylist > instance) and copies it components inro an instance > member. That's __init__. > > When I read this, I feel like a deer caught in the > headlights. Where should I begin? How do I go about > designing a new class? I would suggest you first just successfully subclass the list builtin. (Even if you're using the First Edition of LP, I'd go with subclassing list directly, rather than using UserList. If you're on a sufficiently old version of Python that you can't do that, enough has changed that it's worth upgrading.) Play with that, adding and printing list members. Once you have that down, add your __init__ to support initialization by making a copy. Then add the other pieces. Small steps, get some confidence, then work forwards. From hinkle.bob at gmail.com Fri Jan 27 02:42:23 2006 From: hinkle.bob at gmail.com (Bob Hinkle) Date: Thu, 26 Jan 2006 20:42:23 -0500 Subject: [Tutor] AttributeError - ChatServer Message-ID: <3237302f0601261742y18e114e1sdae62634d7bc3769@mail.gmail.com> While following a tutorial on how to create a simple chat server I stumbled upon this problem: AttributeError: ChatServer instance has no attribute 'decriptors' here is my code: #................................................................................... import socket import select class ChatServer: def __init__(self,port): self.port = port; self.srvsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.srvsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.srvsock.bind(("", port)) self.srvsock.listen(5) self.descriptors = [self.srvsock] print 'Chat Server started on port %s' % port def run ( self ): while 1: #Await even on a readable socket descriptor (sread, swrite, sexc) = select.select(self.descriptors, [], []) #Iterate through the tagged read descriptors for sock in sread: #check if received a connect to the server if sock == self.srvsock: self.accept_new_connection() else: # received something on a client socket str = sock.recv(100) # check and see if the peer closed socket if str == '': host,port = sock.getpeername() str = 'Client left %s:%s\r\n' % (host, port) self.broadcast_string(str,sock) sock.close self.descriptors.remose(sock) else: host,port = sock.getpeername() newstr = '[%s:%s] %s' % (host, port, str) self.broadcast_string(newstr,sock) def broadcast_string(self, str, omit_sock): for sock in self.decriptors: if sock != self.srvsock and sock != omit_sock: sock.send(str) print str, def accept_new_connection( self ): newsock, (remhost, remport) = self.srvsock.accept() self.descriptors.append( newsock ) newsock.send("You're connected to Chat Server!\r\n") str = "Client joined %s:%s\r\n" % (remhost, remport) self.broadcast_string( str, newsock ) myserver = ChatServer( 23000 ) myserver.run() #....................................................................... It starts fine but when someone connects, I get the error. [saiph]$ python telnetserver2.py Chat Server started on port 23000 Traceback (most recent call last): File "telnetserver2.py", line 74, in ? myserver.run() File "telnetserver2.py", line 32, in run self.accept_new_connection() File "telnetserver2.py", line 69, in accept_new_connection self.broadcast_string( str, newsock ) File "telnetserver2.py", line 53, in broadcast_string for sock in self.decriptors: AttributeError: ChatServer instance has no attribute 'decriptors' Any help would be appreciated! TIA -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060126/2210db64/attachment.htm From john at fouhy.net Fri Jan 27 03:02:54 2006 From: john at fouhy.net (John Fouhy) Date: Fri, 27 Jan 2006 15:02:54 +1300 Subject: [Tutor] AttributeError - ChatServer In-Reply-To: <3237302f0601261742y18e114e1sdae62634d7bc3769@mail.gmail.com> References: <3237302f0601261742y18e114e1sdae62634d7bc3769@mail.gmail.com> Message-ID: <5e58f2e40601261802l1cfe15b3s@mail.gmail.com> On 27/01/06, Bob Hinkle wrote: > While following a tutorial on how to create a simple chat server I stumbled > upon this problem: > AttributeError: ChatServer instance has no attribute 'decriptors' Hi Bob, Attributes are things like methods or variables that are "attached" to a class instance. For example, instances of your CharServer class have attributes like .port or .srvsock. When you get an AttributeError, it means that you tried to access an attribute and python couldn't find the attribute you wanted. In this particular case, the error message says that on line 53, you tried to access "self.decriptors", and "self" (which is your ChatServer) didn't have a "decriptors" attribute. Looking through your code, I can see that you assign to "self.descriptors" in your __init__ method. So I guess this is just a typo --- if you change "self.decriptors" to "self.descriptors", you might have more luck :-) -- John. From ben3941 at yahoo.com Fri Jan 27 05:49:35 2006 From: ben3941 at yahoo.com (Ben Markwell) Date: Thu, 26 Jan 2006 20:49:35 -0800 (PST) Subject: [Tutor] Trying to enter text from a file to a Dictionary Message-ID: <20060127044935.42608.qmail@web35612.mail.mud.yahoo.com> Being new to programming, I made a text file that contains terms with their definitions that I have come across in my studying. As an exercise, I thought I would make a glossary using a dictionary so I can look up words, add new words, view all entries, etc. I want to enter the words and definitions from the text file into the dict. The way the text file is set up is that one line is the word and the next line is the definition. For example: Word Definition of the word. Second Word Definition of the second word. Etc.... I thought this would be rather simple (maybe it really is), but I'm stuck. I can't figure out how to tell Python to read the line with the word, add the word to the Key of the dict, then read the next line and add that line to the Value of the dict, then do it all again 'til the end of the file. I tried using a for loop like this f = open('glossary.txt','r') gloss = {} for line in f: gloss[line] = line When I tried to print this, a huge list of key/values printed out. With many copies of the same key/value pair. And the key and the value were the same. (not word followed by definition) , which afterword made sense, because, I told it that gloss[line] = line I tried : for line in f: gloss[line] = f.readline() That got me nowhere. Sorry for being so dense. I understand what needs to happen, but am having trouble implementing it. Thanks for your help and understanding. --------------------------------- Bring words and photos together (easily) with PhotoMail - it's free and works with Yahoo! Mail. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060126/f52cfe5b/attachment.html From dyoo at hkn.eecs.berkeley.edu Fri Jan 27 06:30:03 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 26 Jan 2006 21:30:03 -0800 (PST) Subject: [Tutor] Trying to enter text from a file to a Dictionary In-Reply-To: <20060127044935.42608.qmail@web35612.mail.mud.yahoo.com> Message-ID: > I tried : > > for line in f: > gloss[line] = f.readline() > This should have worked, but there's one problem. Whenever we're doing something like: for line in f: ... there can be some interference between the iteration and any readline() in the body of the loop. For efficiency reasons, the iterator's allowed to march through the file ahead several lines at with an internal buffer. This means our position in the file might be further along than we might realize, and that means that readline() will give nonsensical results. So we're getting caught by a low-level detail. We should try to avoid using both the for loop and readline() on the same file. Here's one way we can avoid the problem: while True: word = f.readline() defn = f.readline() if not word or not defn: break ... Does this make sense? From w.damen at gmail.com Fri Jan 27 07:40:17 2006 From: w.damen at gmail.com (Rinzwind) Date: Fri, 27 Jan 2006 07:40:17 +0100 Subject: [Tutor] why can't I find a function that givesme the sign of an integer? In-Reply-To: <02f701c622c3$01b39030$0b01a8c0@xp> References: <4677730601261152j4fc1a30dy533a8e80e76c35b7@mail.gmail.com> <43D929BE.6080407@gmail.com> <02f701c622c3$01b39030$0b01a8c0@xp> Message-ID: <4677730601262240n3ce12257kc9a0444bbda4fcce@mail.gmail.com> > On 1/26/06, Alan Gauld wrote: > >> In basic I can use SGN to get back -1, 0, +1 if a number is <0, 0, >0. > > Well, the cmp() function does this if you compare the number to 0: > > Neat trick Orri, I'd never have thought of that one :-) > > Alan G. Glad I could help :=) On 1/26/06, Kent Johnson wrote: > Orri Ganel wrote: > > Rinzwind wrote: > > > >> In basic I can use SGN to get back -1, 0, +1 if a number is <0, 0, >0. > > Well, the cmp() function does this if you compare the number to 0: > > > > >>> cmp(-34,0) > > -1 > > >>> cmp(0,0) > > 0 > > >>> cmp(23,0) > > One caution: this behaviour doesn't seem to be required, the docs allow > any positive or negative integer: > cmp( x, y) > Compare the two objects x and y and return an integer according to > the outcome. The return value is negative if x < y, zero if x == y and > strictly positive if x > y. > > So this behaviour might differ between Python versions. > > Kent Now you lost me. Eh you mean to say that in next Python versions someone could decide to change cmp(x,0) to another meaning? I bet my countryman (I'm from Holland too ;-) ) will veto that! Or else I'll pay him a visit :D From python.pan at gmail.com Fri Jan 27 07:59:48 2006 From: python.pan at gmail.com (Runsun Pan) Date: Fri, 27 Jan 2006 00:59:48 -0600 Subject: [Tutor] designing a class In-Reply-To: <20060126211254.77716.qmail@web51613.mail.yahoo.com> References: <20060126211254.77716.qmail@web51613.mail.yahoo.com> Message-ID: <5af1b8bc0601262259g498979f0o6762d9fce7a189ba@mail.gmail.com> On 1/26/06, Christopher Spears wrote: > headlights. Where should I begin? How do I go about > designing a new class? Some starter 101: First, recognize that a class is a compound type that is not only a type but binds other variables and methods with it. #----------------------------------- class definition class People(object): lastname = 'Spears' firstname = Chris object is the parent of People from where People inherits all of its definitions and behavior (functions). It's also called "subclassing" -- subclassing object to get People. #----------------------------------- instantiation p = People( ) p is called "an instance of class People" >>> p.lastname Spears >>> p.firstname Chris >>> p.firstname = 'runsun' >>> p.firstname runsun ~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~ Runsun Pan, PhD python.pan at gmail.com Nat'l Center for Macromolecular Imaging http://ncmi.bcm.tmc.edu/ncmi/ ~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~ From python.pan at gmail.com Fri Jan 27 08:10:54 2006 From: python.pan at gmail.com (Runsun Pan) Date: Fri, 27 Jan 2006 01:10:54 -0600 Subject: [Tutor] designing a class In-Reply-To: <5af1b8bc0601262259g498979f0o6762d9fce7a189ba@mail.gmail.com> References: <20060126211254.77716.qmail@web51613.mail.yahoo.com> <5af1b8bc0601262259g498979f0o6762d9fce7a189ba@mail.gmail.com> Message-ID: <5af1b8bc0601262310p28fee29cre0c8262cd2cf74f0@mail.gmail.com> #------------------------------------ initialization of class If you want to be able to give initial values to the class when it is instantialized, you do it in the __init__ function that Terry mentioned: class People(object): def __init__(self, firstname='Chris', lastname='Spears'): self.firstname = firstname self.lastname = lastname That is, instead of putting lastname = 'Spears' firstname = Chris right under "class People(object)", you put them inside the __init__. This will allow some user values be entered during the instantiation: p = People( firstname = 'Christopher') On 1/27/06, Runsun Pan wrote: > On 1/26/06, Christopher Spears wrote: > > > headlights. Where should I begin? How do I go about > > designing a new class? > > Some starter 101: > > First, recognize that a class is a compound type that is not only a type > but binds other variables and methods with it. > > #----------------------------------- class definition > class People(object): > lastname = 'Spears' > firstname = Chris > > object is the parent of People from where People inherits all of its > definitions and behavior (functions). It's also called "subclassing" -- > subclassing object to get People. > > #----------------------------------- instantiation > p = People( ) > > p is called "an instance of class People" > > >>> p.lastname > Spears > >>> p.firstname > Chris > >>> p.firstname = 'runsun' > >>> p.firstname > runsun > > > ~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~ > Runsun Pan, PhD > python.pan at gmail.com > Nat'l Center for Macromolecular Imaging > http://ncmi.bcm.tmc.edu/ncmi/ > ~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~ > -- ~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~ Runsun Pan, PhD python.pan at gmail.com Nat'l Center for Macromolecular Imaging http://ncmi.bcm.tmc.edu/ncmi/ ~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~ From alan.gauld at freenet.co.uk Fri Jan 27 09:14:38 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 27 Jan 2006 08:14:38 -0000 Subject: [Tutor] designing a class References: <20060126211254.77716.qmail@web51613.mail.yahoo.com> Message-ID: <031001c62319$b7e599b0$0b01a8c0@xp> > Write a class called Mylist that shadows ("wraps") a > Python list: it should overload most list operators > ... > When I read this, I feel like a deer caught in the > headlights. Where should I begin? How do I go about > designing a new class? Well, to quote an old joke, I wouldn't start from here.... Defining a new type based on a builtin type and overloading all the operators is a relatively hard thing to do (correctly). Personally I'd advise defining something easier and less useful. Something that doesn't require operators at all initially just plain methods. Once you've defined a few of those you will find the exercise above more straightforward. Try wrioting a program that you are interested in that uses objects - like say a DVD database, or a menu management system. Think about how you might build DVD or menu classes. What kind of things would you do to these objects if you had them(their methods). What kind of information would those methods need to work? Build the objects method by method and test them. Just some ideas. The one advantage of starting with a builtin type is that most of your code just calls the existing class's methods but I still think the advantage of that is outweighed by the added complexity of jumping straight into overloading operators! HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Fri Jan 27 09:24:00 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 27 Jan 2006 08:24:00 -0000 Subject: [Tutor] Is this overkill? References: <80463c260601202245s149fd654w929cac0ab5f62b4@mail.gmail.com> Message-ID: <031601c6231b$06be1ed0$0b01a8c0@xp> Catherine > I've spend some time going throught the many available turorials, but find > it hard to get good exercises to try out what you learn. Most tutorials do have a few suggested exercises but the best way is to take the examples they give and modify them to see what happens. The reason for that is you are starting with a working outline which is much easier than starting with nothing. However one source of small project ideas is "Useless Python". Have you seen that web site? It includes all sorts of little programs that people have written plus lots of projects that have been suggested, some very small others quite ambitious. So far as I know Useless Python is a unique concept in programming languages, but I think its great for beginners! (And don't forget to visit the 'old site' because it has more content than the new - but less well organised!) HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld On 1/21/06, Bradly McConnell wrote: > > Greetings all: > > I'm new to Python, and have come across and exercise that basically > counts to 100. The idea is to accept user input for an initial > number, and then let the user add additional numbers. I wanted to > give feedback if a number selected would bring the total above 100, so > the user would select a lower number. It looks like I have it > working, but it doesn't seem very efficient. I would like any hints, > help, or comments that you can provide. Below is what I have so far. > > number = input("Please enter a number: ") > while number != 100: > additional_number = input("Please enter an additional number: ") > if additional_number + number > 100: > lower_number = input("please enter a lower number: ") > if lower_number + number > 100: > lower_number = input("Lower!") > else: > number = lower_number + number > elif additional_number + number < 100: > number = additional_number + number > else: > continue > > print "Done", number > > > Brad > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at freenet.co.uk Fri Jan 27 09:26:26 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 27 Jan 2006 08:26:26 -0000 Subject: [Tutor] AttributeError - ChatServer References: <3237302f0601261742y18e114e1sdae62634d7bc3769@mail.gmail.com> Message-ID: <032001c6231b$5d8b57a0$0b01a8c0@xp> > AttributeError: ChatServer instance has no attribute 'decriptors' Read the error carefully - a typo maybe? Alan G. From etrade.griffiths at dsl.pipex.com Fri Jan 27 09:36:53 2006 From: etrade.griffiths at dsl.pipex.com (Etrade Griffiths) Date: Fri, 27 Jan 2006 08:36:53 +0000 Subject: [Tutor] First steps with Tkinter In-Reply-To: References: <1138299648.43d9130033149@netmail.pipex.net> Message-ID: <6.1.2.0.2.20060127083534.03ad7d70@pop.dsl.pipex.com> Catherine I'm a Python newbie too but have done some programming with C++ Builder so have a little knowledge of GUIs etc Best regards Alun At 22:41 26/01/2006, catherine curley wrote: >Alan > >As a matter of interest, did you have much knowledge of Python before you >tried TKinter? I'm only a python beginner at present. > >Catherine > > >On 1/26/06, >etrade.griffiths at dsl.pipex.com ><etrade.griffiths at dsl.pipex.com > >wrote: >Hi! > >Just started trying to get to grips with Python and Tkinter. Have Frederick >Lundh's tutorial and am on program hello2.py which looks like this > ># 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() > >I am running from inside Pythonwin 2.4 IDE under XP Pro and every time I run >hello2.py it freezes when I press "QUIT". The only way to kill it is through >Alt-Ctrl-Del but this crashes Pythonwin. Any workaround for this so that I >can use Tkinter from inside the IDE? BTW the same thing happend with IDLE > >Thanks in advance > >Alun Griffiths >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060127/d00e13ed/attachment.html From jonathan.r.moore at gmail.com Fri Jan 27 09:53:43 2006 From: jonathan.r.moore at gmail.com (Jon Moore) Date: Fri, 27 Jan 2006 08:53:43 +0000 Subject: [Tutor] Controling my loops and redundant code?!? In-Reply-To: <200601261349.32326.pkraus@pelsupply.com> References: <23d7abd0601260952k734be1e8pb2d61f9251de097b@mail.gmail.com> <200601261349.32326.pkraus@pelsupply.com> Message-ID: Paul The book is called 'Python Programming for the absolute beginner'. It is written by Michael Dawson and published by Premier Press. I have to say that as someone that has no experience in programming what so ever, I am hooked! I need to learn Python for a job I am starting next month and to say I felt a little worried at the idea is an understatement. Since going through the first few chapters of this book (and having the support of this group) I can not wait to learn more! Jon On 26/01/06, Paul Kraus wrote: > > What book are you working through? That is a pretty interesting exercise. > > Paul > On Thursday 26 January 2006 12:52 pm, Bob Gailer wrote: > > At 08:44 AM 1/25/2006, Jon Moore wrote: > > > > Hi, > > > > I have written the program below as an exercise from a book I am working > my > > way through. > > > > Objective from book: > > Write a character creator program for a role-playing-game. The player > > should be given a pool of 30 points to spend on four attributes: > strength, > > health, wisdom and dexterity. The player should be able to spend points > > from the pool on any attribute and should be also be able to take points > > from an attribute and put them back in the pool. > > > > Although the program meets the aim of the exercise set out in the book , > > there are a couple of things I am not happy with! > > > > 1. I am sure I have written far more code than required. Where could I > have > > made some shorcuts? > > > > 2. Should the user enter a value greater than what is available, the > > program kicks the user all the way back to the main menu. How could I > tidy > > this up to just loop round to ask the user to try a new value? > > > > choice = None > > > > # Set max number of available points > > POINTS_POOL = 30 > > > > # store attribute values > > attributes = [["Strength", 0], ["Health", 0], ["Wisdom", 0], > ["Dexterity", > > 0]] > > > > > > Some ideas to chew on as you develop skills and understanding of > > programming. > > Separate the "essential data" from the code. The essential data are > > attributes, associated points and max_points. So > > > > attributes = ["Strength", "Health", "Wisdom", "Dexterity"] > > points = [0, 0, 0, 0] > > MAX_POINTS = 30 > > > > In this model the relationship between attributes and points is by > > position. Later you will study and use classes; then the points list > will > > be replaced by a list of class instances, one per attribute. > > > > Develop code that operates on these lists to accomplish the various > > objectives. The code itself will never refer to any attribute by name! > > > > For example - to list the attributes with their points: > > > > for x in range(len(attributes)): > > print "\t",attributes[x], points[x] > > > > To assign values. Note I separated getting input from converting it to > > integer so we can see if the user's entry is convertible.: > > > > available_points = MAX_POINTS - sum(points) > > print "You have " + available_points + " available." > > for x in range(len(attributes)): > > cvalue = raw_input("How much would you like to assign to " + > attributes[x] > > + " ?: ")) > > if cvalue.isdigit(): > > value = int(cvalue) > > else: > > print "Number expected" > > > > [snip] > > -- > > Bob Gailer > > 510-978-4454 > > -- > Paul Kraus > =-=-=-=-=-=-=-=-=-=-= > PEL Supply Company > Network Administrator > 216.267.5775 Voice > 216.267.6176 Fax > www.pelsupply.com > =-=-=-=-=-=-=-=-=-=-= > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Best Regards Jon Moore -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060127/73d27730/attachment.htm From alan.gauld at freenet.co.uk Fri Jan 27 11:01:19 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 27 Jan 2006 10:01:19 -0000 Subject: [Tutor] Trying to enter text from a file to a Dictionary References: <20060127044935.42608.qmail@web35612.mail.mud.yahoo.com> Message-ID: <033501c62328$9f007870$0b01a8c0@xp> Hi Ben, > I want to enter the words and definitions from the text file into the > dict. > The way the text file is set up is that one line is the word and the > next line is the definition. > I tried using a for loop like this > > f = open('glossary.txt','r') > gloss = {} > > for line in f: > gloss[line] = line The problem that you have is that you really need to read two lines at a time. (Assuming that the definitions are all on one line which may not be true!) A while loop may be easier in this case. A for loop will read each line individually. You then need to set a definition flag to tell the loop body whether you are reading a definition or a key. Either type of loop is possible. Since you started with a for loop lets stick with it... definition = False currentKey = None for line in f: if isDefinition: gloss[currentKey] = line currentKey = None isDefinition = False else: currentKey = line isDefinition = True If the definitions take up more than one line each then you will need to think about how to identify the end of a definition - a blank line maybe? You will need to append the lines to the glossary entry (rather than just assign them) until the end of the definition. And you will need to update the isDefinition flag at the appropriate times. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Fri Jan 27 11:06:55 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 27 Jan 2006 10:06:55 -0000 Subject: [Tutor] why can't I find a function that givesme the sign of aninteger? References: <4677730601261152j4fc1a30dy533a8e80e76c35b7@mail.gmail.com><43D929BE.6080407@gmail.com> <02f701c622c3$01b39030$0b01a8c0@xp> <4677730601262240n3ce12257kc9a0444bbda4fcce@mail.gmail.com> Message-ID: <033b01c62329$678b46d0$0b01a8c0@xp> Orri, > Eh you mean to say that in next Python versions someone could decide > to change cmp(x,0) to another meaning? I bet my countryman (I'm from > Holland too ;-) ) will veto that! Or else I'll pay him a visit :D Its not another meaning, its the current meaning. Kent is just pointing out that while the default cmp currently returns -1,0,1 there is nothing to stop a user defined cmp fom returning any negative or positive number instead of -1,1. And cmp() calls any user defined cmp under the hood. In theory the standard cmp could be changed in future although its unlikely.. So while it is a nice trick it cannot be relied upon since it depends on a detail of implementation. In practice I suspect you are fairly safe :-) Alan G From w.damen at gmail.com Fri Jan 27 11:36:29 2006 From: w.damen at gmail.com (Rinzwind) Date: Fri, 27 Jan 2006 11:36:29 +0100 Subject: [Tutor] why can't I find a function that givesme the sign of aninteger? In-Reply-To: <033b01c62329$678b46d0$0b01a8c0@xp> References: <4677730601261152j4fc1a30dy533a8e80e76c35b7@mail.gmail.com> <43D929BE.6080407@gmail.com> <02f701c622c3$01b39030$0b01a8c0@xp> <4677730601262240n3ce12257kc9a0444bbda4fcce@mail.gmail.com> <033b01c62329$678b46d0$0b01a8c0@xp> Message-ID: <4677730601270236k26568859uada2dd16bbe84257@mail.gmail.com> On 1/27/06, Alan Gauld wrote: > Orri, > > > Eh you mean to say that in next Python versions someone could decide > > to change cmp(x,0) to another meaning? I bet my countryman (I'm from > > Holland too ;-) ) will veto that! Or else I'll pay him a visit :D > > Its not another meaning, its the current meaning. > Kent is just pointing out that while the default cmp currently > returns -1,0,1 > there is nothing to stop a user defined cmp fom returning any negative or > positive number instead of -1,1. And cmp() calls any user defined cmp > under the hood. > > In theory the standard cmp could be changed in future although its > unlikely.. > So while it is a nice trick it cannot be relied upon since it depends on a > detail of implementation. In practice I suspect you are fairly safe :-) > > Alan G > > Ok. Well I needed it to reflect -, 0 or + anyways so I should be safe. I needed it to find out the direction of a chessmove so pawns could not walk back and with that and the MIN and the MAX function I could do with 1 for+while loops per direction (hor, vert or diag). Oh, I am now on 32 hours of coding and started with 0 knowledge of Python, PIL and/or Pygame and the 1st release should be out soon :-) Just need to fix castling, promotion and en passant and I'm done! I LOVE PYTHON. From le.dahut at laposte.net Fri Jan 27 11:08:41 2006 From: le.dahut at laposte.net (le dahut) Date: Fri, 27 Jan 2006 11:08:41 +0100 Subject: [Tutor] socket and lost data Message-ID: <43D9F129.3080700@laposte.net> Hi, I try to send some data across a network (between 400KB and 10MB) like this : def envoyer(conn, mysize): print mysize,' KB sent' data = '1'*1024 data_end = data[:-5]+'#####' data = data*(mysize-1) begining = time.time() conn.send(data) conn.send(data_end) passed = time.time() - begining return passed, size and receive it like this : def recevoir(conn): data='' while 1: tmpdata = conn.recv(8192) data += tmpdata if '#####' in data: print 'END OF DATA' break print len(data)/1024, ' KB received' return passed, int(data[-15:-5])/1024 But I don't receive as much data that I sent ... does someone know why ? If I want to send the same data back to the client, do I have to destroy and recreate the socket ? From kent37 at tds.net Fri Jan 27 12:01:10 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 27 Jan 2006 06:01:10 -0500 Subject: [Tutor] why can't I find a function that givesme the sign of aninteger? In-Reply-To: <033b01c62329$678b46d0$0b01a8c0@xp> References: <4677730601261152j4fc1a30dy533a8e80e76c35b7@mail.gmail.com><43D929BE.6080407@gmail.com> <02f701c622c3$01b39030$0b01a8c0@xp> <4677730601262240n3ce12257kc9a0444bbda4fcce@mail.gmail.com> <033b01c62329$678b46d0$0b01a8c0@xp> Message-ID: <43D9FD76.2050701@tds.net> Alan Gauld wrote: > Orri, > > >>Eh you mean to say that in next Python versions someone could decide >>to change cmp(x,0) to another meaning? I bet my countryman (I'm from >>Holland too ;-) ) will veto that! Or else I'll pay him a visit :D > > > Its not another meaning, its the current meaning. > Kent is just pointing out that while the default cmp currently > returns -1,0,1 > there is nothing to stop a user defined cmp fom returning any negative or > positive number instead of -1,1. And cmp() calls any user defined cmp > under the hood. > > In theory the standard cmp could be changed in future although its > unlikely.. > So while it is a nice trick it cannot be relied upon since it depends on a > detail of implementation. In practice I suspect you are fairly safe :-) The test suite does specifically test for -1, 0 and 1 as the result of cmp(int, int): self.assertEqual(cmp(-1, 1), -1) self.assertEqual(cmp(1, -1), 1) self.assertEqual(cmp(1, 1), 0) so this behaviour will probably be consistent in different Python versions. Jython for example tries to pass the standard tests and I imagine IronPython does as well, and of course (C)Python. Kent From kent37 at tds.net Fri Jan 27 12:08:17 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 27 Jan 2006 06:08:17 -0500 Subject: [Tutor] socket and lost data In-Reply-To: <43D9F129.3080700@laposte.net> References: <43D9F129.3080700@laposte.net> Message-ID: <43D9FF21.5070000@tds.net> le dahut wrote: > Hi, > I try to send some data across a network (between 400KB and 10MB) like > this : > def envoyer(conn, mysize): > print mysize,' KB sent' > data = '1'*1024 > data_end = data[:-5]+'#####' > data = data*(mysize-1) > begining = time.time() > conn.send(data) > conn.send(data_end) > passed = time.time() - begining > return passed, size > socket.send() may not send all the data - it returns a count telling you what it actually did. Use socket.sendall() or put your call to send() in a loop. > and receive it like this : > > def recevoir(conn): > data='' > while 1: > tmpdata = conn.recv(8192) > data += tmpdata > if '#####' in data: > print 'END OF DATA' > break > print len(data)/1024, ' KB received' > return passed, int(data[-15:-5])/1024 socket.recv() will return an empty string when there is no more data - I would look for that instead of your marker, it is more general. Instead of if '#####' in data: you can say if data == '': or just if not data: > > But I don't receive as much data that I sent ... does someone know why ? > If I want to send the same data back to the client, do I have to destroy > and recreate the socket ? If this doesn't fix it, maybe an example of the lost data would help. Kent From kraus at hagen-partner.de Fri Jan 27 12:19:45 2006 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Fri, 27 Jan 2006 12:19:45 +0100 Subject: [Tutor] [newbie alert] why can't I find a function that gives me the sign of an integer? In-Reply-To: <4677730601261152j4fc1a30dy533a8e80e76c35b7@mail.gmail.com> References: <4677730601261152j4fc1a30dy533a8e80e76c35b7@mail.gmail.com> Message-ID: Rinzwind wrote: > In basic I can use SGN to get back -1, 0, +1 if a number is <0, 0, >0. > I searched on the web for a bit but sgn and sign give me way too many > discussions about Decimals. python.org with > numbers/digits doesn't tell about a function. > > Maybe Python uses a different name for it so I am not looking for the > correct wording :( Sucks not knowing syntax from my memory and having to > look them up alot). > > Wim > > If you can accept False,0,True instead of -1,0,1 you can use: x and x == abs(x) HTH, Wolfram From kraus at hagen-partner.de Fri Jan 27 12:22:40 2006 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Fri, 27 Jan 2006 12:22:40 +0100 Subject: [Tutor] [newbie alert] why can't I find a function that gives me the sign of an integer? In-Reply-To: <4677730601261152j4fc1a30dy533a8e80e76c35b7@mail.gmail.com> References: <4677730601261152j4fc1a30dy533a8e80e76c35b7@mail.gmail.com> Message-ID: Rinzwind wrote: > In basic I can use SGN to get back -1, 0, +1 if a number is <0, 0, >0. > I searched on the web for a bit but sgn and sign give me way too many > discussions about Decimals. python.org with > numbers/digits doesn't tell about a function. > > Maybe Python uses a different name for it so I am not looking for the > correct wording :( Sucks not knowing syntax from my memory and having to > look them up alot). > > Wim > > > D'Oh! It works with -1/0/1, too: x and x/abs(x) >>> x = -2 >>> x and x/abs(x) -1 >>> x = 2 >>> x and x/abs(x) 1 >>> x = 0 >>> x and x/abs(x) 0 HTH, Wolfram From w.damen at gmail.com Fri Jan 27 13:22:01 2006 From: w.damen at gmail.com (Rinzwind) Date: Fri, 27 Jan 2006 13:22:01 +0100 Subject: [Tutor] why can't I find a function that gives me the sign of an integer? In-Reply-To: References: <4677730601261152j4fc1a30dy533a8e80e76c35b7@mail.gmail.com> Message-ID: <4677730601270422v63bd11fgcccc7d720c7bc76a@mail.gmail.com> On 1/27/06, Wolfram Kraus wrote: > Rinzwind wrote: > > In basic I can use SGN to get back -1, 0, +1 if a number is <0, 0, >0. > > I searched on the web for a bit but sgn and sign give me way too many > > discussions about Decimals. python.org with > > numbers/digits doesn't tell about a function. > > > > Maybe Python uses a different name for it so I am not looking for the > > correct wording :( Sucks not knowing syntax from my memory and having to > > look them up alot). > > > > Wim > > > > > > > D'Oh! > > It works with -1/0/1, too: > x and x/abs(x) > > >>> x = -2 > >>> x and x/abs(x) > -1 > >>> x = 2 > >>> x and x/abs(x) > 1 > >>> x = 0 > >>> x and x/abs(x) > 0 > > HTH, > Wolfram No, I needed the -1 0 and 1 :-) That way whatever you move (like Qd2-d6 or Qd6-d2) I could find the places in between the 2. Same goes for Rd1-Rd8 or Rd8-Rd1). I needed it to multiply with -1, 0, 1 according to what move it was :-) Oh and I allready got it working so I'm all :-) :-) :-) about it. From mi.janssen at gmail.com Fri Jan 27 15:05:20 2006 From: mi.janssen at gmail.com (Michael Janssen) Date: Fri, 27 Jan 2006 15:05:20 +0100 Subject: [Tutor] Dictionaries In-Reply-To: <5e58f2e40601251700x218b0834t@mail.gmail.com> References: <5e58f2e40601251700x218b0834t@mail.gmail.com> Message-ID: <1ff2dfbf0601270605r34416a9ei24557532dc17840a@mail.gmail.com> On 1/26/06, John Fouhy wrote: > >>> for name in pairs: > ... print '%*s --> %*s' % (maxKey, name, maxValue, pairs[name]) thanks for pointing out the '*' syntax. Ignorant as I am I have had to write things like print '%%%ss --> %%%ss' % (maxKey, maxValue) % (name, pairs[name]) for years. Thanks :-) Michael From kent37 at tds.net Fri Jan 27 15:52:58 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 27 Jan 2006 09:52:58 -0500 Subject: [Tutor] Dictionaries In-Reply-To: References: Message-ID: <43DA33CA.7000804@tds.net> Jon Moore wrote: > Hi > > Is there anyway to print informtation from dictionaries better than this?: > > >>> pairs = {"Jon Moore": "Tony Moore", > "Simon Nightingale": "John Nightingale", > "David Willett": "Bernard Willet", > "John Jackson": "Stuart Jackson", > "James Southey": "Richard Southey", > "William Forsythe": "Shaun Forsythe"} > >>> print pairs.keys() > ['David Willett', 'Jon Moore', 'John Jackson', 'Simon Nightingale', > 'James Southey', 'William Forsythe'] > >>> There is a very nice table formatting recipe here: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/267662 Kent From alan.gauld at freenet.co.uk Fri Jan 27 16:09:22 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 27 Jan 2006 15:09:22 -0000 Subject: [Tutor] socket and lost data References: <43D9F129.3080700@laposte.net> Message-ID: <036301c62353$a80363d0$0b01a8c0@xp> I'm a wee bit confused. > def envoyer(conn, mysize): > print mysize,' KB sent This doesn't seem to be true from the code. > data = '1'*1024 > data_end = data[:-5]+'#####' > data = data*(mysize-1) So data is mysize-1 KB, but you printed mysize KB? > begining = time.time() > conn.send(data) > conn.send(data_end) > passed = time.time() - begining it migfht be more useful to print the siuze here and work out what you really sent: print 'sent: ',len(data) + len(data_end), 'bytes' > return passed, size where is size defined? > and receive it like this : > > def recevoir(conn): > data='' > while 1: > tmpdata = conn.recv(8192) > data += tmpdata > if '#####' in data: > print 'END OF DATA' > break > print len(data)/1024, ' KB received' > return passed, int(data[-15:-5])/1024 > > But I don't receive as much data that I sent ... does someone know why ? if you are going by your print statements they will not match. > If I want to send the same data back to the client, do I have to destroy > and recreate the socket ? There is nothing to stop you having two sockets, one in each direction. Alan G From mhansen at cso.atmel.com Fri Jan 27 16:17:41 2006 From: mhansen at cso.atmel.com (Mike Hansen) Date: Fri, 27 Jan 2006 08:17:41 -0700 Subject: [Tutor] templates Message-ID: <43DA3995.8020602@cso.atmel.com> For some of the web programming I've done in Python, I've used htmltmpl. I had some experience with it in Perl, and found a Python version. http://htmltmpl.sourceforge.net/ I like that there's nearly a complete separation between the presentation and the code. This is great when one person is designing the pages and another is writing the code to drive those pages. However, that's usually not the case for me. I'm usually doing both, and I'm thinking there's got to be something possibly better out there. I'm curious about other templating systems. I wouldn't be opposed to a little bit of code in the template. I just don't want to go the other extreme of something like PHP or ASP. i.e. all code in the template. What web templating systems do you use and why? Mike From cspears2002 at yahoo.com Fri Jan 27 17:39:16 2006 From: cspears2002 at yahoo.com (Christopher Spears) Date: Fri, 27 Jan 2006 08:39:16 -0800 (PST) Subject: [Tutor] designing a class In-Reply-To: <43D954D1.3040902@tds.net> Message-ID: <20060127163916.45054.qmail@web51609.mail.yahoo.com> > class MyList: > def __init__(self, aList=None): > if aList is None: > self._list = [] > else: > self._list = aList[:] > This code certainly looks like it will do the trick. I'm just not sure what the _ in front of list (i.e. _list) denotes. "I'm the last person to pretend that I'm a radio. I'd rather go out and be a color television set." -David Bowie "Who dares wins" -British military motto "I generally know what I'm doing." -Buster Keaton From kent37 at tds.net Fri Jan 27 17:49:00 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 27 Jan 2006 11:49:00 -0500 Subject: [Tutor] designing a class In-Reply-To: <20060127163916.45054.qmail@web51609.mail.yahoo.com> References: <20060127163916.45054.qmail@web51609.mail.yahoo.com> Message-ID: <43DA4EFC.5080208@tds.net> Christopher Spears wrote: >>class MyList: >> def __init__(self, aList=None): >> if aList is None: >> self._list = [] >> else: >> self._list = aList[:] >> > > > This code certainly looks like it will do the trick. > I'm just not sure what the _ in front of list (i.e. > _list) denotes. It's a convention that indicates a private attribute. Think of it as telling clients, "This is for my private use, it may change at any time." In this case it was also a way to avoid using 'list' as the name of the attribute. 'list' is the name of a built-in - it shouldn't be used as a variable name because it will shadow the built-in. In the case of an attribute it doesn't really matter but I have a strong habit of not using 'list' as a name. Kent From cspears2002 at yahoo.com Fri Jan 27 18:12:58 2006 From: cspears2002 at yahoo.com (Christopher Spears) Date: Fri, 27 Jan 2006 09:12:58 -0800 (PST) Subject: [Tutor] the chicken and the egg Message-ID: <20060127171258.7124.qmail@web51612.mail.yahoo.com> Thanks to all of the tutors on this mailing list! I'm finally making some headway! I originally decided to tackle my problem one operator at a time: class MyList: def __init__(self, aList=None): if aList is None: self.mylist = [] else: self.mylist = aList[:] def __getitem__(self, index): return self.mylist[index] However, I got the following error: >>> from MyList import * >>> x = MyList([1,2,3]) >>> x[0] Traceback (most recent call last): File "", line 1, in ? File "MyList.py", line 8, in __getitem__ self.mylist[index] AttributeError: MyList instance has no attribute '__setitem__' >>> x.mylist[0] 1 I did the obvious and created __setitem__. class MyList: def __init__(self, aList=None): if aList is None: self.mylist = [] else: self.mylist = aList[:] def __getitem__(self, index): return self.mylist[index] def __setitem__(self, index, value): self.mylist[index] = value Why does __getitem require __setitem__? Don't they do different things? From victor at grupocdm.com Fri Jan 27 18:22:33 2006 From: victor at grupocdm.com (Victor Bouffier) Date: Fri, 27 Jan 2006 11:22:33 -0600 Subject: [Tutor] Dictionaries In-Reply-To: <029b01c6227e$79eb3840$0b01a8c0@xp> References: <43D82478.7090703@tds.net> <029b01c6227e$79eb3840$0b01a8c0@xp> Message-ID: <1138382553.16040.9.camel@elrond> Hi Alan and Ken, I think know the difference between using items() vs. iteritems() and their equivalent for keys and values. I notice Ken suggests iteritems(), while Alan suggests items() only. Does one approach have an advantage over the other? Should we use only one of them favorably? Thanks. Victor On Thu, 2006-01-26 at 13:43 +0000, Alan Gauld wrote: > > How would I modify this to just print either the values or keys? > > Just ask for the values or the keys! > > for value in pairs.values() > print value > > for key in pairs.keys() > print key > > for key,value in pairs.items() > print key > print value > From bgailer at alum.rpi.edu Fri Jan 27 18:42:42 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri, 27 Jan 2006 09:42:42 -0800 Subject: [Tutor] Trying to enter text from a file to a Dictionary In-Reply-To: <033501c62328$9f007870$0b01a8c0@xp> References: <20060127044935.42608.qmail@web35612.mail.mud.yahoo.com> <033501c62328$9f007870$0b01a8c0@xp> Message-ID: <43DA5B92.7010709@alum.rpi.edu> Alan Gauld wrote: > Hi Ben, > > >> I want to enter the words and definitions from the text file into the >> dict. >> The way the text file is set up is that one line is the word and the >> next line is the definition. >> > > >> I tried using a for loop like this >> >> f = open('glossary.txt','r') >> gloss = {} >> >> for line in f: >> gloss[line] = line >> > > The problem that you have is that you really need to read two lines at a > time. > (Assuming that the definitions are all on one line which may not be true!) > A while loop may be easier in this case. > > A for loop will read each line individually. You then need to set a > definition > flag to tell the loop body whether you are reading a definition or a key. > > Either type of loop is possible. Since you started with a for loop lets > stick with it... > > definition = False > currentKey = None > > for line in f: > if isDefinition: > gloss[currentKey] = line > currentKey = None > isDefinition = False > else: > currentKey = line > isDefinition = True > Or you can use next(): for line in f: gloss[line] = f.next() > If the definitions take up more than one line each then you will need to > think > about how to identify the end of a definition - a blank line maybe? You will > need to append the lines to the glossary entry (rather than just assign > them) > until the end of the definition. And you will need to update the > isDefinition > flag at the appropriate times. > > HTH, > > Alan G > Author of the learn to program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From alan.gauld at freenet.co.uk Fri Jan 27 18:50:30 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 27 Jan 2006 17:50:30 -0000 Subject: [Tutor] Dictionaries References: <5e58f2e40601251700x218b0834t@mail.gmail.com> <1ff2dfbf0601270605r34416a9ei24557532dc17840a@mail.gmail.com> Message-ID: <039d01c6236a$2a86a310$0b01a8c0@xp> > ... print '%*s --> %*s' % (maxKey, name, maxValue, pairs[name]) > > thanks for pointing out the '*' syntax. Ignorant as I am I have > had to write things like > > print '%%%ss --> %%%ss' % (maxKey, maxValue) % (name, pairs[name]) I didn't even try that, I've always done it on two lines fmt = "%%%ds --> %%%ds' % (width1,width2) print fmt % (value1,value2) '%*s' is a neat trick, albeit a tad obscure in the readability stakes. But is %%%ds any better?! Alan G. From kent37 at tds.net Fri Jan 27 19:14:20 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 27 Jan 2006 13:14:20 -0500 Subject: [Tutor] the chicken and the egg In-Reply-To: <20060127171258.7124.qmail@web51612.mail.yahoo.com> References: <20060127171258.7124.qmail@web51612.mail.yahoo.com> Message-ID: <43DA62FC.50607@tds.net> Christopher Spears wrote: > Thanks to all of the tutors on this mailing list! I'm > finally making some headway! I originally decided to > tackle my problem one operator at a time: > > class MyList: > def __init__(self, aList=None): > if aList is None: > self.mylist = [] > else: > self.mylist = aList[:] > def __getitem__(self, index): > return self.mylist[index] > > However, I got the following error: > > >>>>from MyList import * >>>>x = MyList([1,2,3]) >>>>x[0] > > Traceback (most recent call last): > File "", line 1, in ? > File "MyList.py", line 8, in __getitem__ > self.mylist[index] > AttributeError: MyList instance has no attribute > '__setitem__' Strange. It works for me. Are you sure there is nothing else in MyList.py? D:\>type MyList.py class MyList: def __init__(self, aList=None): if aList is None: self.mylist = [] else: self.mylist = aList[:] def __getitem__(self, index): return self.mylist[index] D:\>python Python 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from MyList import * >>> m=MyList([0,1,2]) >>> m[0] 0 >>> m[1] 1 Kent From kent37 at tds.net Fri Jan 27 19:20:52 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 27 Jan 2006 13:20:52 -0500 Subject: [Tutor] Dictionaries In-Reply-To: <1138382553.16040.9.camel@elrond> References: <43D82478.7090703@tds.net> <029b01c6227e$79eb3840$0b01a8c0@xp> <1138382553.16040.9.camel@elrond> Message-ID: <43DA6484.1080007@tds.net> Victor Bouffier wrote: > Hi Alan and Ken, > > I think know the difference between using items() vs. iteritems() and > their equivalent for keys and values. I notice Ken suggests iteritems(), > while Alan suggests items() only. > > Does one approach have an advantage over the other? > Should we use only one of them favorably? It doesn't make much difference for small dictionaries. keys(), values() and items() create new lists with the specified elements. iterkeys(), itervalues() and iteritems() create iterators that return the specified elements in sequence. So for the common case of iterating over dict elements with a for loop, the 'iter' variants conserve memory and may be faster (but always check!) because of the cost of creating the list. The iter variants are relatively new (since Python 2.2). I used to use the older variants in examples here so I wouldn't have to explain the difference :-) but ISTM that modern usage is heading to prefer the iter versions and I am starting to use them myself. But I guess you will not notice any difference in performance until you have dicts with many thousands of elements. Kent From bgailer at alum.rpi.edu Fri Jan 27 19:22:39 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri, 27 Jan 2006 10:22:39 -0800 Subject: [Tutor] Trying to enter text from a file to a Dictionary In-Reply-To: <43DA5B92.7010709@alum.rpi.edu> References: <20060127044935.42608.qmail@web35612.mail.mud.yahoo.com> <033501c62328$9f007870$0b01a8c0@xp> <43DA5B92.7010709@alum.rpi.edu> Message-ID: <43DA64EF.9060908@alum.rpi.edu> Bob Gailer wrote: > Alan Gauld wrote: > >> Hi Ben, >> >> >> >>> I want to enter the words and definitions from the text file into the >>> dict. >>> The way the text file is set up is that one line is the word and the >>> next line is the definition. >>> >>> >> >> >>> I tried using a for loop like this >>> >>> f = open('glossary.txt','r') >>> gloss = {} >>> >>> for line in f: >>> gloss[line] = line >>> >>> >> The problem that you have is that you really need to read two lines at a >> time. >> (Assuming that the definitions are all on one line which may not be true!) >> A while loop may be easier in this case. >> >> A for loop will read each line individually. You then need to set a >> definition >> flag to tell the loop body whether you are reading a definition or a key. >> >> Either type of loop is possible. Since you started with a for loop lets >> stick with it... >> >> definition = False >> currentKey = None >> >> for line in f: >> if isDefinition: >> gloss[currentKey] = line >> currentKey = None >> isDefinition = False >> else: >> currentKey = line >> isDefinition = True >> >> > Or you can use next(): > > for line in f: > gloss[line] = f.next() > Or even: [gloss.setdefault(l,f.next()) for l in f] >> If the definitions take up more than one line each then you will need to >> think >> about how to identify the end of a definition - a blank line maybe? You will >> need to append the lines to the glossary entry (rather than just assign >> them) >> until the end of the definition. And you will need to update the >> isDefinition >> flag at the appropriate times. >> >> HTH, >> >> Alan G >> Author of the learn to program web tutor >> http://www.freenetpages.co.uk/hp/alan.gauld >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> >> >> > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From alan.gauld at freenet.co.uk Fri Jan 27 19:36:27 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 27 Jan 2006 18:36:27 -0000 Subject: [Tutor] Trying to enter text from a file to a Dictionary References: <20060127044935.42608.qmail@web35612.mail.mud.yahoo.com> <033501c62328$9f007870$0b01a8c0@xp> <43DA5B92.7010709@alum.rpi.edu> Message-ID: <03a701c62370$9590c540$0b01a8c0@xp> >> for line in f: >> if isDefinition: >> gloss[currentKey] = line >> currentKey = None >> isDefinition = False >> else: >> currentKey = line >> isDefinition = True >> > Or you can use next(): > > for line in f: > gloss[line] = f.next() Ah! Indeed you can. I'd forgotten about that neat feature of iterators. No longer are for loops broken when you mess around with the iterated item. Good catch Bob. Alan G. From benmarkwell at gmail.com Fri Jan 27 21:27:27 2006 From: benmarkwell at gmail.com (Ben Markwell) Date: Fri, 27 Jan 2006 15:27:27 -0500 Subject: [Tutor] Fwd: Trying to enter text from a file to a Dictionary In-Reply-To: References: <20060127044935.42608.qmail@web35612.mail.mud.yahoo.com> Message-ID: Hello Danny Thanks for replying to my post. > I tried : > > for line in f:Thanks for your reply to my post. > gloss[line] = f.readline() > This should have worked, but there's one problem. Whenever we're doing something like: for line in f: ... there can be some interference between the iteration and any readline() in the body of the loop. For efficiency reasons, the iterator's allowed to march through the file ahead several lines at with an internal buffer. This means our position in the file might be further along than we might realize, and that means that readline() will give nonsensical results. So we're getting caught by a low-level detail. We should try to avoid using both the for loop and readline() on the same file. Here's one way we can avoid the problem: while True: word = f.readline() defn = f.readline() if not word or not defn: break ... Does this make sense? It does mostly...I don't see why you need the: if not word or not defn: break If this is so that when python iterates to the end of the file, it knows to stop, and if that is so, then why doesn't python know it has gotten to the end of the file without it being told? _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060127/599d1091/attachment-0001.html From dyoo at hkn.eecs.berkeley.edu Fri Jan 27 22:21:11 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 27 Jan 2006 13:21:11 -0800 (PST) Subject: [Tutor] Fwd: Trying to enter text from a file to a Dictionary In-Reply-To: Message-ID: > Here's one way we can avoid the problem: > > while True: > word = f.readline() > defn = f.readline() > if not word or not defn: > break > ... > > Does this make sense? > > It does mostly...I don't see why you need the: > > if not word or not defn: > break > > If this is so that when python iterates to the end of the file, it knows > to stop, and if that is so, then why doesn't python know it has gotten > to the end of the file without it being told? Hi Ben, Yes, that's the point: Python doesn't know when to stop. *grin* The way we've rewritten the loop: while True: ... is an "infinite" loop that doesn't stop unless something in the loop's body does something extraordinary, like "breaking" out of the loop. Python is much dumber than we might expect. In more detail: Python's readline() method doesn't fail when we reach the end of a file: we actually start hitting the empty string. For example: ###### >>> import StringIO >>> sampleTextFile = StringIO.StringIO("""This is ... a sample ... text file ... """) >>> sampleTextFile.readline() 'This is\n' >>> sampleTextFile.readline() 'a sample\n' >>> sampleTextFile.readline() 'text file\n' >>> sampleTextFile.readline() '' >>> sampleTextFile.readline() '' ###### Notice that when we hit the end of the file, readline() still continues to run and give us empty string values. That's why the loop above needs to make sure it breaks out in this particular situation. Does this make sense? Please feel free to ask questions about this. From alan.gauld at freenet.co.uk Sat Jan 28 01:48:45 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 28 Jan 2006 00:48:45 -0000 Subject: [Tutor] Dictionaries References: <43D82478.7090703@tds.net> <029b01c6227e$79eb3840$0b01a8c0@xp> <1138382553.16040.9.camel@elrond> Message-ID: <03d301c623a4$98104690$0b01a8c0@xp> > their equivalent for keys and values. I notice Ken suggests iteritems(), > while Alan suggests items() only. I'm old fashioned and rarely use new language features until I really have to. Kent uses the more modern idioms. I think iteritems is the preferred usage nowadays, but its longer to type and for most jobs has no real advantage. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From benmarkwell at gmail.com Sat Jan 28 04:27:49 2006 From: benmarkwell at gmail.com (Ben Markwell) Date: Fri, 27 Jan 2006 22:27:49 -0500 Subject: [Tutor] Fwd: Trying to enter text from a file to a Dictionary In-Reply-To: References: Message-ID: > > > Hi Ben, > > Yes, that's the point: Python doesn't know when to stop. *grin* > > The way we've rewritten the loop: > > while True: > ... > > is an "infinite" loop that doesn't stop unless something in the loop's > body does something extraordinary, like "breaking" out of the loop. > Python is much dumber than we might expect. > > > In more detail: Python's readline() method doesn't fail when we reach the > end of a file: we actually start hitting the empty string. For example: > > ###### > >>> import StringIO > >>> sampleTextFile = StringIO.StringIO("""This is > ... a sample > ... text file > ... """) > >>> sampleTextFile.readline() > 'This is\n' > >>> sampleTextFile.readline() > 'a sample\n' > >>> sampleTextFile.readline() > 'text file\n' > >>> sampleTextFile.readline() > '' > >>> sampleTextFile.readline() > '' > ###### > > Notice that when we hit the end of the file, readline() still continues to > run and give us empty string values. That's why the loop above needs to > make sure it breaks out in this particular situation. > > > Does this make sense? Please feel free to ask questions about this. > > Yes The -- while true loop -- needs something to be false or it needs to be told when to stop. If that is correct, then it makes sense. Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060127/bc774be2/attachment.htm From benmarkwell at gmail.com Sat Jan 28 04:33:27 2006 From: benmarkwell at gmail.com (Ben Markwell) Date: Fri, 27 Jan 2006 22:33:27 -0500 Subject: [Tutor] Trying to enter text from a file to a Dictionary In-Reply-To: <43DA64EF.9060908@alum.rpi.edu> References: <20060127044935.42608.qmail@web35612.mail.mud.yahoo.com> <033501c62328$9f007870$0b01a8c0@xp> <43DA5B92.7010709@alum.rpi.edu> <43DA64EF.9060908@alum.rpi.edu> Message-ID: On 1/27/06, Bob Gailer wrote: > > Bob Gailer wrote: > > Alan Gauld wrote: > > > >> Hi Ben, > >> > >> > >> > >>> I want to enter the words and definitions from the text file into the > >>> dict. > >>> The way the text file is set up is that one line is the word and the > >>> next line is the definition. > >>> > >>> > >> > >> > >>> I tried using a for loop like this > >>> > >>> f = open('glossary.txt','r') > >>> gloss = {} > >>> > >>> for line in f: > >>> gloss[line] = line > >>> > >>> > >> The problem that you have is that you really need to read two lines at > a > >> time. > >> (Assuming that the definitions are all on one line which may not be > true!) > >> A while loop may be easier in this case. > >> > >> A for loop will read each line individually. You then need to set a > >> definition > >> flag to tell the loop body whether you are reading a definition or a > key. > >> > >> Either type of loop is possible. Since you started with a for loop lets > >> stick with it... > >> > >> definition = False > >> currentKey = None > >> > >> for line in f: > >> if isDefinition: > >> gloss[currentKey] = line > >> currentKey = None > >> isDefinition = False > >> else: > >> currentKey = line > >> isDefinition = True > >> > >> > > Or you can use next(): > > > > for line in f: > > gloss[line] = f.next() > > > Or even: > [gloss.setdefault(l,f.next()) for l in f] Hello Bob I understand f.next(), but [gloss.setdefault(l,f.next()) for l in f] is beyond me at this point. Thanks for your input. Ben -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060127/81adc646/attachment.html From bgailer at alum.rpi.edu Sat Jan 28 05:17:55 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri, 27 Jan 2006 20:17:55 -0800 Subject: [Tutor] Trying to enter text from a file to a Dictionary In-Reply-To: References: <20060127044935.42608.qmail@web35612.mail.mud.yahoo.com> <033501c62328$9f007870$0b01a8c0@xp> <43DA5B92.7010709@alum.rpi.edu> <43DA64EF.9060908@alum.rpi.edu> Message-ID: <43DAF073.2050106@alum.rpi.edu> Ben Markwell wrote: > > > On 1/27/06, *Bob Gailer* > wrote: > > Bob Gailer wrote: > > Alan Gauld wrote: > > > >> Hi Ben, > >> > >> > >> > >>> I want to enter the words and definitions from the text file > into the > >>> dict. > >>> The way the text file is set up is that one line is the word > and the > >>> next line is the definition. > >>> > >>> > >> > >> > >>> I tried using a for loop like this > >>> > >>> f = open('glossary.txt','r') > >>> gloss = {} > >>> > >>> for line in f: > >>> gloss[line] = line > >>> > >>> > >> The problem that you have is that you really need to read two > lines at a > >> time. > >> (Assuming that the definitions are all on one line which may > not be true!) > >> A while loop may be easier in this case. > >> > >> A for loop will read each line individually. You then need to > set a > >> definition > >> flag to tell the loop body whether you are reading a definition > or a key. > >> > >> Either type of loop is possible. Since you started with a for > loop lets > >> stick with it... > >> > >> definition = False > >> currentKey = None > >> > >> for line in f: > >> if isDefinition: > >> gloss[currentKey] = line > >> currentKey = None > >> isDefinition = False > >> else: > >> currentKey = line > >> isDefinition = True > >> > >> > > Or you can use next(): > > > > for line in f: > > gloss[line] = f.next() > > > Or even: > [gloss.setdefault(l,f.next()) for l in f] > > > Hello Bob > > I understand f.next(), but [gloss.setdefault(l,f.next()) for l in f] > is beyond me at this point. [expr for l in f] is a "list comprehension". expr is an expression that may involve l. result = [expr for l in f] # is equivalent to: result = [] for l in f: result.append(expr) "list comprehension" (once understood) is often easier to read and more efficient than the for loop. result = xxx.setdefault(key, newvalue) is a dictionary method that tries to get an item from the dictionary xxx using key. If the key is not in the dictionary it adds the item assigning it newvalue. Equivalent to: if key not in xxx: xxx[key] = newvalue result = xxx[key] Note that list comprehension and setdefault both return something. In my code the returned values are ignored. The outcome (populating a dictionary via a loop) is a "side effect". From benmarkwell at gmail.com Sat Jan 28 06:47:25 2006 From: benmarkwell at gmail.com (Ben Markwell) Date: Sat, 28 Jan 2006 00:47:25 -0500 Subject: [Tutor] Trying to enter text from a file to a Dictionary In-Reply-To: <43DAF073.2050106@alum.rpi.edu> References: <20060127044935.42608.qmail@web35612.mail.mud.yahoo.com> <033501c62328$9f007870$0b01a8c0@xp> <43DA5B92.7010709@alum.rpi.edu> <43DA64EF.9060908@alum.rpi.edu> <43DAF073.2050106@alum.rpi.edu> Message-ID: > > > > I understand f.next(), but [gloss.setdefault(l,f.next()) for l in f] > > is beyond me at this point. > [expr for l in f] is a "list comprehension". expr is an expression that > may involve l. > > result = [expr for l in f] # is equivalent to: > > result = [] > for l in f: > result.append(expr) > > "list comprehension" (once understood) is often easier to read and more > efficient than the for loop. > > result = xxx.setdefault(key, newvalue) is a dictionary method that tries > to get an item from the dictionary xxx using key. If the key is not in > the dictionary it adds the item assigning it newvalue. Equivalent to: > > if key not in xxx: > xxx[key] = newvalue > result = xxx[key] > > Note that list comprehension and setdefault both return something. In my > code the returned values are ignored. The outcome (populating a > dictionary via a loop) is a "side effect". > Thank you Bob. This is much to think about. I very much appreciate your concise explanation. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060128/9406a5ca/attachment.html From alan.gauld at freenet.co.uk Sat Jan 28 13:06:43 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 28 Jan 2006 12:06:43 -0000 Subject: [Tutor] Trying to enter text from a file to a Dictionary References: <20060127044935.42608.qmail@web35612.mail.mud.yahoo.com> <033501c62328$9f007870$0b01a8c0@xp><43DA5B92.7010709@alum.rpi.edu> <43DA64EF.9060908@alum.rpi.edu> <43DAF073.2050106@alum.rpi.edu> Message-ID: <03f601c62403$4e2d20c0$0b01a8c0@xp> Hi Bob, > "list comprehension" (once understood) is often easier to read and more > efficient than the for loop. They are often more efficient but I don't know if I'd ever claim they were easier to read than an explicit for loop. Perhaps the most trivial cases like z = [x*2 for x in L] and even then I'm not sure that is easier to read than z = [] for x in L: z.append(x*2) And personally I still find map() easier for those cases z = map(lambda x: x*2, L) But you do need to be comfortable with lambda for that, and lambda is just as hard to grok as list comprehensions! :-) Alan G. From kent37 at tds.net Sat Jan 28 13:57:30 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 28 Jan 2006 07:57:30 -0500 Subject: [Tutor] Trying to enter text from a file to a Dictionary In-Reply-To: <03f601c62403$4e2d20c0$0b01a8c0@xp> References: <20060127044935.42608.qmail@web35612.mail.mud.yahoo.com> <033501c62328$9f007870$0b01a8c0@xp><43DA5B92.7010709@alum.rpi.edu> <43DA64EF.9060908@alum.rpi.edu> <43DAF073.2050106@alum.rpi.edu> <03f601c62403$4e2d20c0$0b01a8c0@xp> Message-ID: <43DB6A3A.8060405@tds.net> Alan Gauld wrote: > Hi Bob, > > >>"list comprehension" (once understood) is often easier to read and more >>efficient than the for loop. > > > They are often more efficient but I don't know if I'd ever claim they were > easier to read than an explicit for loop. Perhaps the most trivial cases > like > > z = [x*2 for x in L] > > and even then I'm not sure that is easier to read than > > z = [] > for x in L: z.append(x*2) I find simple list comps far easier to read and write than the equivalent for loop, and they fit the way I think about problems - I will think, "I need a list of the squares of everything in L." This matches exactly the order of elements in a list comp. Personally I avoid using list comps purely for the side effects, to me that breaks the conceptual "I need a list...". I admit that some of the most unreadable one-liners on comp.lang.python use list comps in creative ways...I write out the loop rather than going to contortions to make an expression I can use in a list comp. I don't see the point in twistng the code to fit it into a list comp. Kent From kristi_holsinger at hotmail.com Sat Jan 28 19:46:00 2006 From: kristi_holsinger at hotmail.com (kristi holsinger) Date: Sat, 28 Jan 2006 18:46:00 +0000 Subject: [Tutor] remove from mailing list Message-ID: An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060128/91d077b5/attachment.html From membranplastik at hotmail.com Sat Jan 28 20:11:37 2006 From: membranplastik at hotmail.com (tony) Date: Sun, 29 Jan 2006 02:11:37 +0700 Subject: [Tutor] Iam beginner Message-ID: Hallo my name is tony iam from indonesia, Iam beginer iam try use python for my music program via athenaCL. what should I so, to understhand python langguage -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060129/55e93579/attachment.htm From membranplastik at hotmail.com Sat Jan 28 20:13:23 2006 From: membranplastik at hotmail.com (tony) Date: Sun, 29 Jan 2006 02:13:23 +0700 Subject: [Tutor] beginner Message-ID: iam beginner, Iam try to use pyhon What should I do to understhand python langguage, thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060129/8b86a781/attachment.html From tim.peters at gmail.com Sat Jan 28 20:39:27 2006 From: tim.peters at gmail.com (Tim Peters) Date: Sat, 28 Jan 2006 14:39:27 -0500 Subject: [Tutor] remove from mailing list In-Reply-To: References: Message-ID: <1f7befae0601281139q766c4266p4e953ee530ef155e@mail.gmail.com> [kristi holsinger] > please remove kristi_holsinger at hotmail.com from the mailing list! thank you This is self-service. You need to go to http://mail.python.org/mailman/listinfo/tutor and unsubscribe youself (look for the "Unsubscribe or edit options" button near the bottom of the page). From carroll at tjc.com Sat Jan 28 21:55:06 2006 From: carroll at tjc.com (Terry Carroll) Date: Sat, 28 Jan 2006 12:55:06 -0800 (PST) Subject: [Tutor] Trying to enter text from a file to a Dictionary In-Reply-To: <43DB6A3A.8060405@tds.net> Message-ID: On Sat, 28 Jan 2006, Kent Johnson wrote: > I find simple list comps far easier to read and write than the > equivalent for loop, and they fit the way I think about problems... I don't know if my experience is typical, but I found list comprehensions difficult to get. There's something, maybe about the syntax, that my intuition resists. Once I got it, though -- after maybe three attempts -- it stuck very well, and I like them better than their equivalent for-loops. From kent37 at tds.net Sat Jan 28 21:58:45 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 28 Jan 2006 15:58:45 -0500 Subject: [Tutor] beginner In-Reply-To: References: Message-ID: <43DBDB05.9020603@tds.net> tony wrote: > iam beginner, Iam try to use pyhon What should I do to understhand > python langguage, thanks The Beginners Guide has some suggestions: http://wiki.python.org/moin/BeginnersGuide Kent From andre.roberge at gmail.com Fri Jan 27 16:57:52 2006 From: andre.roberge at gmail.com (Andre Roberge) Date: Fri, 27 Jan 2006 11:57:52 -0400 Subject: [Tutor] Off-topic query for rur-ple users Message-ID: <7528bcdd0601270757y565639dcif51bdde8a9ed4d28@mail.gmail.com> Please, accept my apologies to bring this slightly off-topic question. This is the only way I know to reach RUR-PLE users. How important is it to have a browser included within rur-ple itself? Would there be any objections in eliminating the browser, and using your favourite browser (firefox, etc.) to read the lessons in a separate window? You may want to send your reply directly to me (return address should be part of the message; if not: andre dot roberge at gmail dot com) so as to not "pollute" induly this list. Thanks, Andr? ==== P.S. Just a note about the fact that this is not *completely* off-topic for this list: the PLE in RUR-PLE stands for Python Learning Environment. It is designed for learning Python for people that don't know anything about programming (hence the post to the python-tutor list). It has been used by some teachers in a classroom environment (hence the post to the edu-sig list). It has been very strongly inspired by Guido van Robot (hence the post to the gvr-devel list) and has served as the basis of the world-builder module now included with GvR. From jndomain at yahoo.com Sat Jan 28 06:17:27 2006 From: jndomain at yahoo.com (jan.n) Date: Sat, 28 Jan 2006 00:17:27 -0500 (EST) Subject: [Tutor] email-sending.. Message-ID: <20060128051727.53227.qmail@web51615.mail.yahoo.com> Hello, i am trying to send emails through a python script , but it complains that socket error 10061 conection refused.. any help with this would be great... import smtplib smtpserver = 'mailserver' AUTHREQUIRED = 1 # if you need to use SMTP AUTH set to 1 smtpuser = '#####' # for SMTP AUTH, set SMTP username here smtppass = '#####' # for SMTP AUTH, set SMTP password here flname = 'c:\\Python24\\mssg.txt' #c:\\tst.txt RECIPIENTS = ['someaddress at yahoo.com'] SENDER = 'someaddress at yahoo.co.in' mssg = open(flname , 'r').read() session = smtplib.SMTP(smtpserver) if AUTHREQUIRED: session.login(smtpuser, smtppass) smtpresult = session.sendmail(SENDER, RECIPIENTS, mssg) if smtpresult: errstr = "" for recip in smtpresult.keys(): errstr = """Could not delivery mail to: %s Server said: %s %s %s""" % (recip, smtpresult[recip][0], smtpresult[recip][1], errstr) raise smtplib.SMTPException, errstr --------------------------------- Find your next car at Yahoo! Canada Autos -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060128/c8e90f07/attachment.html From dyoo at hkn.eecs.berkeley.edu Sun Jan 29 07:43:19 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 28 Jan 2006 22:43:19 -0800 (PST) Subject: [Tutor] email-sending.. In-Reply-To: <20060128051727.53227.qmail@web51615.mail.yahoo.com> Message-ID: Hi Jan, Side question: how much Python do you know already? It really seems like you've just picked up an introductory example, so I'm not exactly sure I see where you might be getting stuck or what things you've tried already. Anyway, when you mention: > i am trying to send emails through a python script , but it complains that > > socket error 10061 conection refused.. although this is useful, you should also copy-and-paste the exact error message. I know that you have to be paraphrasing somewhere because the word "connection" is misspelled above. Copying-and-pasting error messages is perfectly fine: they provide information in even their most trivial-looking details, which is why we really want to see that information in its fullness. It will also help to see at one line things start going wrong. Do you remember seeing any kind of stack trace that pointed out which line of the program wasn't going so well? On quick question about the program you're showing us: > smtpserver = 'mailserver' ^^^^^^^^^^ Is this the real name of your SMTP mail server? From jjk_saji at yahoo.com Sun Jan 29 08:49:54 2006 From: jjk_saji at yahoo.com (John Joseph) Date: Sun, 29 Jan 2006 07:49:54 +0000 (GMT) Subject: [Tutor] Searching for email id in MySQL giving wrong results In-Reply-To: <43D60AC2.60602@tds.net> Message-ID: <20060129074954.4767.qmail@web34812.mail.mud.yahoo.com> Hi I am sending the code of the function "searchbyemail" and the output of the program when I run I am trying to search and display the results , even if we give a part of the email_id thanks Joseph John **************** SEARCH by email _id function ******************************** ################################################################################ def searchbyemail(): s_email = raw_input("Enter the Email to be searched ") db = MySQLdb.connect(host="localhost",user = "john", passwd = "asdlkj", db = 'learnpython') entry = db.cursor() entry.execute("""SELECT * FROM contact WHERE email_id = %s """, (s_email,)) p = entry.fetchall() print p ####################################################################### *** Output of the short run ********* [john at john experiement]$ python mysqlentry.py Data Base Entry for the Testing Env 0 - Quit 1 - Enter the Data 2 - Display The data 3 - Search The Company 4 - Delete Some info Choice :........2 (('Joseph', 'joseph at asd.com', '1234', '4321'), ('John', 'john at qwe.com', '4567', '7654'), ('CityBank', 'bank at money.com', '987', '789'), ('ABN amro', 'loan at money.com', '456', '654')) Data Base Entry for the Testing Env 0 - Quit 1 - Enter the Data 2 - Display The data 3 - Search The Company 4 - Delete Some info Choice :........3 Do U want to search by Name , email id , phone or fax U want to search the contacts by 0 - Quit 1 - Name 2 - email_id 3 - phone 4 - fax Choice :........2 Enter the Email to be searched loan at money.com (('ABN amro', 'loan at money.com', '456', '654'),) U want to search the contacts by 0 - Quit 1 - Name 2 - email_id 3 - phone 4 - fax Choice :........2 Enter the Email to be searched loan () U want to search the contacts by 0 - Quit 1 - Name 2 - email_id 3 - phone 4 - fax Choice :........ --- Kent Johnson wrote: > John Joseph wrote: > > Hi > > Thanks to Allan,Danny,Pujo > > I did my simple python script for MySQL , > the > > scripts add the data , and search for the data and > > display > > I have problem in searching email id > ,ie > > If search for the something at some , I will not get > any > > result , Guidance and advice needed for the > reason > > for this behavior > > Does it work when you search for other data such as > name or phone? > > Can you show the output from a short run where you > add a contact, > display the data and search for an email? > > Kent > > > I had added my script in this mail > > Thanks > > Joseph John > > > > > ********************************************************* > > > > """ This program is for to learn > > how to enter data to MySQL using python > > How to search > > not using OOP > > > > Have problem in searching email-id > > Why I do not get correct results when > > searching email id > > "@" string search containg "@" gives empty > > results > > > > """ > > > > > > > > import MySQLdb > > > > def selecter(): > > choice = None > > while choice != "0": > > print \ > > """ > > Data Base Entry for the Testing Env > > 0 - Quit > > 1 - Enter the Data > > 2 - Display The data > > 3 - Search The Company > > """ > > choice = raw_input("Choice :........") > > print > > > > if choice == "0": > > print "Good Bye ..." > > elif choice == "1": > > dataentry() > > > > elif choice == "2": > > datashow() > > elif choice == "3": > > datasearch() > > > > > > > > def dataentry(): > > name = raw_input("Enter the name of the company > ") > > email_id = raw_input("\n Enter the email ID : ") > > phone_no = raw_input("Enter the Phone No : ") > > fax_no = raw_input("\n Enter the fax no : ") > > > > db = MySQLdb.connect(host="localhost",user = > "john", > > passwd = "asdlkj", db = 'learnpython') > > entry = db.cursor() > > #entry.execute("""INSERT INTO contact > > """,(name,email_id,phone_no,fax_no,)) > > entry.execute("""INSERT INTO > > contact(name,email_id,phone_no,fax_no) VALUES > > (%s,%s,%s,%s)""",(name,email_id,phone_no,fax_no,)) > > print name , email_id , fax_no, phone_no > > > > > > > > > > def datashow(): > > db = MySQLdb.connect(host="localhost",user = > "john", > > passwd = "asdlkj", db = 'learnpython') > > entry = db.cursor() > > entry.execute("SELECT * from contact") > > p = entry.fetchall() > > print p > > > > def datasearch(): > > print "Do U want to search by Name , email id , > phone > > or fax " > > choice = None > > while choice != "0": > > print \ > > """ > > U want to search the contacts by > > 0 - Quit > > 1 - Name > > 2 - email_id > > 3 - phone > > 4 - fax > > """ > > choice = raw_input("Choice :........") > > print > > > > if choice == "0": > > print "Good Bye ..." > > elif choice == "1": > > searchbyname() > > > > elif choice == "2": > > searchbyemail() > > > > elif choice == "3": > > searchbyphone() > > elif choice == "4": > > searchbyfax() > > > > def searchbyname(): > > s_name = raw_input("Enter the name to be searched > ") > > db = MySQLdb.connect(host="localhost",user = > "john", > > passwd = "asdlkj", db = 'learnpython') > > entry = db.cursor() > > entry.execute("""SELECT * FROM contact WHERE name > = > > %s""", (s_name,)) > > p = entry.fetchall() > > print p > > > > def searchbyemail(): > > s_email = raw_input("Enter the Email to be > searched > > ") > > db = MySQLdb.connect(host="localhost",user = > "john", > > passwd = "asdlkj", db = 'learnpython') > > entry = db.cursor() > > entry.execute("""SELECT * FROM contact WHERE > email_id > > = %s""", (s_email,)) > > p = entry.fetchall() > > print p > > > > > > def searchbyphone(): > > s_phone= raw_input("Enter the Phone no to be > > searched ") > > db = MySQLdb.connect(host="localhost",user = > "john", > > passwd = "asdlkj", db = 'learnpython') > > entry = db.cursor() > > entry.execute("""SELECT * FROM contact WHERE > phone_no > > = %s""", (s_phone,)) > > p = entry.fetchall() > > print p > > > > > > > > def searchbyfax(): > > s_fax = raw_input("Enter the FAX no to be > searched > > ") > > db = MySQLdb.connect(host="localhost",user = > "john", > > passwd = "asdlkj", db = 'learnpython') > > entry = db.cursor() > > entry.execute("""SELECT * FROM contact WHERE > fax_no = > > %s""", (s_fax,)) > > p = entry.fetchall() > > print p > > > > selecter() > > > > > > > > > > > > > ___________________________________________________________ > > === message truncated === ___________________________________________________________ To help you stay safe and secure online, we've developed the all new Yahoo! Security Centre. http://uk.security.yahoo.com From dyoo at hkn.eecs.berkeley.edu Sun Jan 29 09:59:44 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 29 Jan 2006 00:59:44 -0800 (PST) Subject: [Tutor] Searching for email id in MySQL giving wrong results In-Reply-To: <20060129074954.4767.qmail@web34812.mail.mud.yahoo.com> Message-ID: On Sun, 29 Jan 2006, John Joseph wrote: > I am sending the code of the function "searchbyemail" and the output > of the program when I run I am trying to search and display the > results , even if we give a part of the email_id Hi John, Ok; because the question you're asking looks a little homework-y, we have to be a little bit more cautious in our answers. What part are you getting stuck on? Do you understand how SQL wildcards work? There's a good number of SQL tutorials on the web. For example, we can take a look at the queries section on Phil Greenspuns "SQL for Web Nerds" page: http://philip.greenspun.com/sql/queries.html (In fact, the examples he uses to talk about wildcards there seems very pertinant to your question!) Or are you getting stuck about constructing such a query using string operations? If so, you might find something like: http://diveintopython.org/native_data_types/formatting_strings.html useful. If you can give us more details on where you're having difficulty, we'll try to point you in a good direction. One suggestion about the code: you may also want to look into making the helper functions that use parameters, so you can more easily test it out on different examples. For example, if we have a program like: ###################################### def howTallProgram(): n = raw_input("how tall are you?") if n < 3: print "small" elif n < 6: print "medium" else: print "tall" ###################################### then this can be broken out into a helper function to take a height get a description of that height: ###################################### def describeHeight(n): if n < 3: return "small" elif n < 6: return "medium" else: return "tall" ###################################### which is fairly easy to test from the interactive interpreter. The programs that you've shown us so far seem to emphasize direct printing and interacting with the user. You may find functions more useful by making them take inputs and returning outputs. Best of wishes to you! From jjk_saji at yahoo.com Sun Jan 29 12:05:08 2006 From: jjk_saji at yahoo.com (John Joseph) Date: Sun, 29 Jan 2006 11:05:08 +0000 (GMT) Subject: [Tutor] Searching for email id in MySQL giving wrong results In-Reply-To: Message-ID: <20060129110508.69540.qmail@web34814.mail.mud.yahoo.com> --- Danny Yoo wrote: > > Hi John, > > Ok; because the question you're asking looks a > little homework-y, we have > to be a little bit more cautious in our answers. > What part are you > getting stuck on? > > > Do you understand how SQL wildcards work? There's a > good number of SQL > tutorials on the web. For example, we can take a > look at the queries > section on Phil Greenspuns "SQL for Web Nerds" page: > > http://philip.greenspun.com/sql/queries.html > > (In fact, the examples he uses to talk about > wildcards there seems very > pertinant to your question!) > > > Or are you getting stuck about constructing such a > query using string > operations? If so, you might find something like: > > > http://diveintopython.org/native_data_types/formatting_strings.html > > useful. > > > If you can give us more details on where you're > having difficulty, we'll > try to point you in a good direction. > > Hi Danny Thanks for the link , I understood strings formating and use of “%s” Also I read the link for basic SQL statements Now after this , I am getting lost when I do the python program let me try to explain my experience 1>From MySQL command mode , the command to check all the email id which starts with “j” is select * from contact where email_id like 'j%'; 2>Now when I want to select command in python I get confused , since I want to use SELECT statement to display the contacts which email id begins or contains the searched strings My script I am adding , Guidance requested Thanks Joseph John ************************************************************************************* import MySQLdb s_email = raw_input("Enter the Email to be searched ") db = MySQLdb.connect(host="localhost",user = "john", passwd = "asdlkj", db = 'learnpython') entry = db.cursor() """ I get confused here , in the SQL statement we use %s for the searched string , here I also need to use another % for pattern matching , I get lost over here """ entry.execute("""SELECT * FROM contact WHERE email_id = %s """, (s_email,)) #entry.execute("""SELECT * FROM contact WHERE email_id like %s% """, (s_email,)) p = entry.fetchall() print p ___________________________________________________________ Yahoo! Photos ? NEW, now offering a quality print service from just 8p a photo http://uk.photos.yahoo.com From dyoo at hkn.eecs.berkeley.edu Sun Jan 29 12:12:27 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 29 Jan 2006 03:12:27 -0800 (PST) Subject: [Tutor] Searching for email id in MySQL giving wrong results In-Reply-To: <20060129110508.69540.qmail@web34814.mail.mud.yahoo.com> Message-ID: > the email id which starts with “j” is > select * from contact where email_id like 'j%'; Hi John, Ok, looks good so far. So in a Python program, we might try something like this: ############################################################## ## assuming cursor is set up properly: cursor.execute("select * from coutact where email_id like %s", ("j%",)) print cursor.fetchone() ############################################################## Try an example off the interactive interpreter prompt. Do you get the results you expect? Best of wishes to you! From jjk_saji at yahoo.com Sun Jan 29 13:08:37 2006 From: jjk_saji at yahoo.com (John Joseph) Date: Sun, 29 Jan 2006 12:08:37 +0000 (GMT) Subject: [Tutor] Searching for email id in MySQL giving wrong results In-Reply-To: Message-ID: <20060129120837.50454.qmail@web34802.mail.mud.yahoo.com> --- Danny Yoo wrote: > > the email id which starts with ?j? is > > select * from contact where email_id like 'j%'; > > Hi John, > > Ok, looks good so far. So in a Python program, we > might try something > like this: > > ############################################################## > ## assuming cursor is set up > properly: > cursor.execute("select * from coutact where email_id > like %s", > ("j%",)) > print cursor.fetchone() > ############################################################## > > Try an example off the interactive interpreter > prompt. Do you get the > results you expect? > Hi It gives me the correct result , but I have problem in running a program in which it ask for which email to be searched , I am lost and confused there , I had marked it in my code *** import MySQLdb s_email = raw_input("Enter the Email to be searched ") db = MySQLdb.connect(host="localhost",user = "john", passwd = "asdlkj", db = 'learnpython') entry = db.cursor() """ I get confused here , in the SQL statement we use %s for the searched string , here I also need to use another % for pattern matching , I get lost over here """ entry.execute("""SELECT * FROM contact WHERE email_id = %s """, (s_email,)) #entry.execute("""SELECT * FROM contact WHERE email_id like %s% """, (s_email,)) p = entry.fetchall() print p > > Best of wishes to you! > > ___________________________________________________________ To help you stay safe and secure online, we've developed the all new Yahoo! Security Centre. http://uk.security.yahoo.com From alan.gauld at freenet.co.uk Sun Jan 29 16:27:53 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 29 Jan 2006 15:27:53 -0000 Subject: [Tutor] Searching for email id in MySQL giving wrong results References: <20060129074954.4767.qmail@web34812.mail.mud.yahoo.com> Message-ID: <045e01c624e8$92a223f0$0b01a8c0@xp> > I am trying to search and display the results , even > if we give a part of the email_id > entry.execute("""SELECT * FROM contact WHERE > email_id = %s """, (s_email,)) If you want to do partial matches you will need to use LIKE ''' SELECT * FROM contact WHERE email_id LIKE %s ''' Using = will only check for an exact match, and as you show that works OK. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From dyoo at hkn.eecs.berkeley.edu Sun Jan 29 19:09:17 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 29 Jan 2006 10:09:17 -0800 (PST) Subject: [Tutor] email-sending.. (fwd) Message-ID: ---------- Forwarded message ---------- Date: Sun, 29 Jan 2006 10:28:09 -0500 (EST) From: jan.n To: Danny Yoo Subject: Re: [Tutor] email-sending.. Hi Danny, i have crossed that point where it complains of socket error.., but now i am stuck with another issue, where it says that it has sent the mail, but i dont recive any in my yahoo mail.,i have even unbloked my spam filter in my yahoo.. i am a begginer in python scripting,i will paste the scipt i am usinh now.. this the code that i run... this is a command line code though, i need a script that launches from a shell, with a command, any help would be appritiated. ###################################################### # use the Python SMTP mail interface module to send # email messages; this is just a simple one-shot # send script--see pymail, PyMailGui, and PyMailCgi # for clients with more user interaction features, # and popmail.py for a script which retrieves mail; ###################################################### import smtplib, string, sys, time, mailconfig mailserver = mailconfig.smtpservername # ex: starship.python.net >From = string.strip(raw_input('From? ')) # ex: lutz at rmi.net To = string.strip(raw_input('To? ')) # ex: python-list at python.org To = string.split(To, ';') # allow a list of recipients Subj = string.strip(raw_input('Subj? ')) # prepend standard headers date = time.ctime(time.time()) text = ('From: %s\nTo: %s\nDate: %s\nSubject: %s\n' % (From, string.join(To, ';'), date, Subj)) print 'Type message text, end with line=(ctrl + D or Z)' while 1: line = sys.stdin.readline() if not line: break # exit on ctrl-d/z # if line[:4] == 'From': # line = '>' + line # servers escape for us text = text + line if sys.platform[:3] == 'win': print print 'Connecting...' server = smtplib.SMTP(mailserver) # connect, no login step failed = server.sendmail(From, To, text) server.quit() if failed: # smtplib may raise exceptions print 'Failed recipients:', failed # too, but let them pass here else: print 'No errors.' print 'Bye.' and this is the code for mailconfig.... ############################################ # email scripts get server names from here: # change to reflect your machine/user names; # could get these in command line instead ############################################ # SMTP email server machine (send) smtpservername = 'localhost' # or starship.python.net, 'localhost' # POP3 email server machine, user (retrieve) popservername = 'localhost' # or starship.python.net, 'localhost' popusername = 'username' # password is requested when run poppassword = 'mypassword' # local file where pymail (not PyMailGui) saves pop mail savemailfile = r'c:\Temp\savemail.txt' # personal info used by PyMailGui to fill in forms; # sig-- can be a triple-quoted block, ignored if empty string; # addr--used for initial value of "From" field if not empty, # else tries to guess From for replies, with varying success; myaddress = 'jndomain at yahoo.com' mysignature = 'jan (http://jandomain3d.com) [PyMailCgi 1.0]' Jan. Danny Yoo wrote: Hi Jan, Side question: how much Python do you know already? It really seems like you've just picked up an introductory example, so I'm not exactly sure I see where you might be getting stuck or what things you've tried already. Anyway, when you mention: > i am trying to send emails through a python script , but it complains that > > socket error 10061 conection refused.. although this is useful, you should also copy-and-paste the exact error message. I know that you have to be paraphrasing somewhere because the word "connection" is misspelled above. Copying-and-pasting error messages is perfectly fine: they provide information in even their most trivial-looking details, which is why we really want to see that information in its fullness. It will also help to see at one line things start going wrong. Do you remember seeing any kind of stack trace that pointed out which line of the program wasn't going so well? On quick question about the program you're showing us: > smtpserver = 'mailserver' ^^^^^^^^^^ Is this the real name of your SMTP mail server? --------------------------------- Find your next car at Yahoo! Canada Autos From victor at grupocdm.com Sun Jan 29 20:31:46 2006 From: victor at grupocdm.com (Victor Bouffier) Date: Sun, 29 Jan 2006 13:31:46 -0600 Subject: [Tutor] Dictionaries In-Reply-To: <43DA6484.1080007@tds.net> References: <43D82478.7090703@tds.net> <029b01c6227e$79eb3840$0b01a8c0@xp> <1138382553.16040.9.camel@elrond> <43DA6484.1080007@tds.net> Message-ID: <1138563106.9832.13.camel@elrond> On Fri, 2006-01-27 at 13:20 -0500, Kent Johnson wrote: > It doesn't make much difference for small dictionaries. keys(), values() > and items() create new lists with the specified elements. iterkeys(), > itervalues() and iteritems() create iterators that return the specified > elements in sequence. So for the common case of iterating over dict > elements with a for loop, the 'iter' variants conserve memory and may be > faster (but always check!) because of the cost of creating the list. > > The iter variants are relatively new (since Python 2.2). I used to use > the older variants in examples here so I wouldn't have to explain the > difference :-) but ISTM that modern usage is heading to prefer the iter > versions and I am starting to use them myself. > > But I guess you will not notice any difference in performance until you > have dicts with many thousands of elements. > > Kent > Hi Kent and Alan, Thanks to both for your response. Victor From andre.roberge at gmail.com Mon Jan 30 00:42:26 2006 From: andre.roberge at gmail.com (Andre Roberge) Date: Sun, 29 Jan 2006 19:42:26 -0400 Subject: [Tutor] ANN: Rur-ple lessons 0.36 Message-ID: <7528bcdd0601291542g16fc57ddjbc05d8c2f11d56a7@mail.gmail.com> Announcing RUR-PLE lessons 0.36 RUR-PLE stands for Roberge's Used Robot: a Python Learning Environment. This is the first official release of the lessons, separately from the application. The lessons are intended as a somewhat non-typical introduction to programming using Python, that has been used for other languages (just google "Karel Robot" for some examples). The version number (0.36) indicates that 36 complete lessons (plus a few more incomplete ones) are included. The complete introduction to Python (version 1.0) will probably include 50 lessons in total. This version contains more than 50% more material than what is included in the latest rur-ple release on sourceforge. A link to the download page can be found at http://rur-ple.sourceforge.net ===== In 1981, Richard Pattis introduced "Karel the Robot" as a tool to teach computer programming. Reeborg is a robot built on the 1981 Pattis' model... and it is starting to show its age. It has an oil leak, which allows us to follow its trail. Its compass is broken; it only knows if it is facing north or not, unlike Karel who could determine its orientation with respect to all four cardinal points. Pattis' Karel the Robot was named after the author Karel Capek, who popularized the word robot in his play Rossum's Universal Robots (RUR). While RUR-PLE shares the basic RUR acronym, in this case it stands for Roberge's Used Robot. However, through the magic of Guido van Rossum's Python, you can learn how to fix it and design a better one, worthy of the name Rossum's Universal Robot. From shuying at gmail.com Mon Jan 30 00:52:48 2006 From: shuying at gmail.com (Shuying Wang) Date: Mon, 30 Jan 2006 10:52:48 +1100 Subject: [Tutor] putting instance variables into a dict Message-ID: <75fa0c3a0601291552w46850ca0x76091e0348e702b4@mail.gmail.com> Hi, So I've got a class X with instance variables a, b, c. Is there any way of creating a dictionary of these instance variables besides the no-brainer way of doing dictionary = {'a' : X.a, 'b' : X.b, 'c' : X.c} ? --Shuying From dyoo at hkn.eecs.berkeley.edu Mon Jan 30 01:00:28 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 29 Jan 2006 16:00:28 -0800 (PST) Subject: [Tutor] putting instance variables into a dict In-Reply-To: <75fa0c3a0601291552w46850ca0x76091e0348e702b4@mail.gmail.com> Message-ID: On Mon, 30 Jan 2006, Shuying Wang wrote: > So I've got a class X with instance variables a, b, c. Is there any way > of creating a dictionary of these instance variables besides the > no-brainer way of doing dictionary = {'a' : X.a, 'b' : X.b, 'c' : X.c} ? Hi Shuying, It's an somewhat low-level detail that the attributes of a class instance can be accessed through a special __dict__ object: ###### >>> class SomeClass: ... def __init__(self, n): ... self.n = n ... def add(self, x): ... return self.n + x ... >>> s = SomeClass(5) >>> s.__dict__ {'n': 5} ###### Does this apply to your question? Classes can also be extended so that, to the untrained eye, they look very much like dictionaries. See: http://www.python.org/doc/ref/sequence-types.html for some details about having objects implement Python's container protocol. Best of wishes! From kirby.urner at gmail.com Mon Jan 30 01:36:20 2006 From: kirby.urner at gmail.com (kirby urner) Date: Sun, 29 Jan 2006 16:36:20 -0800 Subject: [Tutor] [Edu-sig] ANN: Rur-ple lessons 0.36 In-Reply-To: <7528bcdd0601291542g16fc57ddjbc05d8c2f11d56a7@mail.gmail.com> References: <7528bcdd0601291542g16fc57ddjbc05d8c2f11d56a7@mail.gmail.com> Message-ID: Hi Andre -- I'm going through this first lesson 0.36, not having installed the full wx in this particular Windows machine. I'm very impressed by the quality of these materials, in terms of their graphical sophistication. I also like the multi-lingual approach. That's something missing from most USA-based curricula: any attempt to blend in more than one language (it's either all English, or all something else, but rarely a blend). Kirby On 1/29/06, Andre Roberge wrote: > > Announcing RUR-PLE lessons 0.36 > > RUR-PLE stands for Roberge's Used Robot: a Python Learning Environment. > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060129/1a408dc9/attachment.htm From tvbare at socket.net Mon Jan 30 07:47:38 2006 From: tvbare at socket.net (->Terry<-) Date: Mon, 30 Jan 2006 00:47:38 -0600 (CST) Subject: [Tutor] A row of cards, but they're all red Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Slackware 10.1 Python 2.4.1 Pygame 1.6 The images (if needed) can be found at: Could someone help me understand the output I'm getting from the snippet below? I thought I would get a nice row of cards, 13 reds, 13 blues, etc. But what I get is a row of all red cards. The rank is correct on the cards, but they are all red. If the commented out lines near the bottom are uncommented and the preceding 3 lines are commented out, the output is correct. This tells me 'images' is ok, the right images are being loaded. The problem occurs when 'cards' is built. Can the image objects not be assembled in a list? Apologies if this is off-topic for tutor and would be better directed to a Pygame-specific list. Here's the code: - -------------------------- #!/usr/bin/env python import pygame pygame.init() # Initialize pygame screen = pygame.display.set_mode((640, 140)) suits = ["red ", "blue", "green", "yellow"] ranks = ["ace", "two", "three", "four", "five", "six", "seven", "EIGHT", "nine", "ten", "jack", "queen", "king"] value = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] images = [] cards = [] for z in range(52): fname = "images/" + str(z) + ".png" print("loading %s" % fname) img = pygame.image.load(fname).convert() images.append(img) for suit in suits: for x, rank in enumerate(ranks): cards.append([suit, rank, value[x], images[x]]) x = 10 y = 10 for crd in cards: screen.blit(crd[3], (x, y)) print("Should be a %s %s" % (crd[0], crd[1])) #for image in images: # screen.blit(image, (x, y)) pygame.display.update() pygame.time.wait(250) x += 10 - --------------------------- End of code. Thanks much, - -- Terry ,-~~-.___. Terry Randall / | ' \ http://members.socket.net/~tvbare/index.html < ) 0 \_/, ,-----' ==== // Linux Counter Project User# 98233 / \-'~; /~~~(0) / __/~| / | If only Snoopy had Slackware! =( ______| (________| "He is your friend, your partner, your defender, your dog. You are his life, his love, his leader. He will be yours, faithful and true, to the last beat of his heart. You owe it to him to be worthy of such devotion." -- Unknown -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.7 (GNU/Linux) iD8DBQFD3baOQvSnsfFzkV0RAhfUAJ4qrjQSty9iFLH8yFc8zw+qOfO5RACfbetI wgXLuy5wYkL598gH2ZlXQqA= =2T6i -----END PGP SIGNATURE----- From dyoo at hkn.eecs.berkeley.edu Mon Jan 30 08:18:16 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 29 Jan 2006 23:18:16 -0800 (PST) Subject: [Tutor] A row of cards, but they're all red In-Reply-To: Message-ID: > Could someone help me understand the output I'm getting from the snippet > below? I thought I would get a nice row of cards, 13 reds, 13 blues, > etc. But what I get is a row of all red cards. The rank is correct on > the cards, but they are all red. Hi Terry, There is an issue with the loop here: > for suit in suits: > for x, rank in enumerate(ranks): > cards.append([suit, rank, value[x], images[x]]) Let's assume for the moment that everything else is ok, and that images is a list of fifty-two elements. The loop above tries to associate each individual image with a unique card. Think about what values 'x' goes over in the loop, and you should see a problem. Again, try matching up the experience you're seeing --- all red cards --- and try doing a "what if?" on the situation here. Side note: you might find a funky operator called the "modulo" operator very useful. Here's what it looks like: ###### >>> for hour in range(24): ... print hour, hour % 12 ... 0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10 10 11 11 12 0 13 1 14 2 15 3 16 4 17 5 18 6 19 7 20 8 21 9 22 10 23 11 ###### That is, "modulo" makes numbers "wrap" around. More formally, m % n ends up being the remainder if we divide m by n. Believe it or not, this can be very handy at times. (Otherwise, why would I mention it here? *grin*) We can talk about this in more detail if you'd like. Good luck to you! From andre.roberge at gmail.com Mon Jan 30 12:21:35 2006 From: andre.roberge at gmail.com (Andre Roberge) Date: Mon, 30 Jan 2006 07:21:35 -0400 Subject: [Tutor] A row of cards, but they're all red In-Reply-To: References: Message-ID: <7528bcdd0601300321x4ab8bebgb46e2bb1063fa6e1@mail.gmail.com> On 1/30/06, ->Terry<- wrote: > -----BEGIN PGP SIGNED MESSAGE----- [snip] Try reducing your code to only the following: > > Here's the code: > - -------------------------- > #!/usr/bin/env python > suits = ["red ", "blue", "green", "yellow"] > ranks = ["ace", "two", "three", "four", "five", "six", "seven", > "EIGHT", "nine", "ten", "jack", "queen", "king"] > value = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] > > for suit in suits: > for x, rank in enumerate(ranks): > cards.append([suit, rank, value[x], images[x]]) > And replace the last line by: print [suit, rank, value[x], x] You will see that "x" is not doing what you want it to inside images... As a hint, I'd suggest looking at writing for y, suit in enumerate(suits) and changing the index of images[x]. Good luck! Andr? From python at kapitalisten.no Mon Jan 30 13:08:10 2006 From: python at kapitalisten.no (=?iso-8859-1?Q?=D8yvind?=) Date: Mon, 30 Jan 2006 13:08:10 +0100 (CET) Subject: [Tutor] wxPython Message-ID: <25794.193.71.38.142.1138622890.squirrel@mail.sporck.net> Hello. I have made some programs using wxPython (PythonCard). They all seem to have one common nominator. When the program are doing something unrelated unrelated to the graphics (for example, ftp's, works with a document or a file), the graphics freezes. It does unfreeze afterwards, but since the working with the other files might take a few minutes, the user assumes my program has crashed. How can I avoid that the graphics freeze. Thanks in advance.... -- This email has been scanned for viruses & spam by Decna as - www.decna.no Denne e-posten er sjekket for virus & spam av Decna as - www.decna.no From kent37 at tds.net Mon Jan 30 14:51:31 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 30 Jan 2006 08:51:31 -0500 Subject: [Tutor] wxPython In-Reply-To: <25794.193.71.38.142.1138622890.squirrel@mail.sporck.net> References: <25794.193.71.38.142.1138622890.squirrel@mail.sporck.net> Message-ID: <43DE19E3.2060006@tds.net> ?yvind wrote: > Hello. > > I have made some programs using wxPython (PythonCard). They all seem to > have one common nominator. When the program are doing something unrelated > unrelated to the graphics (for example, ftp's, works with a document or a > file), the graphics freezes. It does unfreeze afterwards, but since the > working with the other files might take a few minutes, the user assumes my > program has crashed. How can I avoid that the graphics freeze. The problem is that your long-running task is not yielding any time to the GUI to respond to events or update the screen. See this page for a detailed discussion of your options: http://wiki.wxpython.org/index.cgi/LongRunningTasks Kent From davholla2002 at yahoo.co.uk Mon Jan 30 15:28:55 2006 From: davholla2002 at yahoo.co.uk (David Holland) Date: Mon, 30 Jan 2006 14:28:55 +0000 (GMT) Subject: [Tutor] Copy files Message-ID: <20060130142855.72363.qmail@web25907.mail.ukl.yahoo.com> I wrote a small program that compares files test1 and test2 to test3. If the files are different then it copies either test1 to test3 or the reverse. The problem is that the although the shutil.copy2 in thefunction change_files works without error it does not copy. Can anyone see what is wrong :- def compare_files(file_name1, file_name2): x = cmp (file_name1, file_name2) return x def open_files(file_name): file_is = open(file_name,'r') file_conts = file_is.read() return file_conts def change_files(file_1, file_2): yesorno = raw_input("Do you want them to be the same Y or N ") yesorno = string.upper(yesorno) if yesorno == 'Y': try: shutil.copy2(file_1, file_2) print "copy has been done " except: print "it did not work" #main file_name1 = open_files("test1.txt") file_name2 = open_files("test2.txt") file_name3 = open_files("test3.txt") import shutil import string x = compare_files(file_name3, file_name1) if x != 0: print "test1 and test3 are different" change_files("test1.txt", "text3.txt", file_name1) else: file_name1 = "test2.txt" print file_name1 x = compare_files(file_name3, file_name2) # print "x is " + str(x) if x != 0: print "test2 and test3 are different" change_files("test2.txt", "text3.txt") print "program finished" -------------------------------------------------------------------------------------------------------------------------------------- "Then you will know the truth, and the truth will set you free." John 8:32 " As Pastor Niem?ller said, first they came for Piglet and I did not speak out because I was not a Disney character." http://www.telegraph.co.uk/opinion/main.jhtml?xml=/opinion/2005/10/04/do0402.xml "When the facts change, I change my opinions, what do you do sir ?" John Keynes. --------------------------------- To help you stay safe and secure online, we've developed the all new Yahoo! Security Centre. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060130/6f00147e/attachment.html From python at venix.com Mon Jan 30 16:48:35 2006 From: python at venix.com (Python) Date: Mon, 30 Jan 2006 10:48:35 -0500 Subject: [Tutor] email-sending.. (fwd) In-Reply-To: References: Message-ID: <1138636115.31751.168.camel@www.venix.com> On Sun, 2006-01-29 at 10:09 -0800, Danny Yoo wrote (forwarding a direct reply to the list): > Hi Danny, > > i have crossed that point where it complains of socket error.., but > now i am stuck with another issue, where it says that it has sent the > mail, but i dont recive any in my yahoo mail.,i have even unbloked my > spam filter in my yahoo.. You will find testing this kind of script much easier if you have access to the mail server logs. If you do not have a friend with a mail server and do not know how to run a mail server yourself, a local Linux user group may be able to provide some assistance. Your ISP, especially a smaller locally focused operation, would be another possibility. The big ISP's will now discard email without any notification. This is largely due to the overwhelming spam load they have to deal with. Your email could be getting discarded for any number of reasons. Chances are your script is working. -- Lloyd Kvam Venix Corp From shuying at gmail.com Mon Jan 30 23:00:58 2006 From: shuying at gmail.com (Shuying Wang) Date: Tue, 31 Jan 2006 09:00:58 +1100 Subject: [Tutor] putting instance variables into a dict In-Reply-To: References: <75fa0c3a0601291552w46850ca0x76091e0348e702b4@mail.gmail.com> Message-ID: <75fa0c3a0601301400h40e58fe3t47165779bc1e3355@mail.gmail.com> Hi, That's more or less what I want. Thanks! Now I just need to figure out metaclasses and poke around python's innards. :D --Shuying On 1/30/06, Danny Yoo wrote: > It's an somewhat low-level detail that the attributes of a class instance > can be accessed through a special __dict__ object: > ###### > >>> s = SomeClass(5) > >>> s.__dict__ > {'n': 5} > ###### From fant at pobox.com Mon Jan 30 21:16:52 2006 From: fant at pobox.com (Andrew D. Fant) Date: Mon, 30 Jan 2006 15:16:52 -0500 Subject: [Tutor] getting around ValueError in os.walk Message-ID: <43DE7434.60502@pobox.com> I'm working on a program to do some processing on a directory tree. If I had been doing it in a shell script, the core of the processing would have been in a "find $ROOT -type f -name FOO -print" command" On the web, I found a snippet of code that demonstrated the os.walk module and I created a simple test program to work on my tree that looked like this: #!/usr/bin/python import os for (dirpath. subdirs, filenames) in os.walk("/foo/bar"): for file in filenames: if file.endswith(".baz"): print os.path.join(dirpath,f) when I try to run it, I get a "ValueError: too many values to unpack" which I think comes from the fact that there is a subdirectory of /foo/bar which has over 2500 files in it. The tree can't be easily restructured for legacy reasons. Can anyone suggest the best way to get around this in code? Thanks, Andy -- Andrew Fant | And when the night is cloudy | This space to let Molecular Geek | There is still a light |---------------------- fant at pobox.com | That shines on me | Disclaimer: I don't Boston, MA | Shine until tomorrow, Let it be | even speak for myself From jason.massey at gmail.com Mon Jan 30 23:34:53 2006 From: jason.massey at gmail.com (Jason Massey) Date: Mon, 30 Jan 2006 16:34:53 -0600 Subject: [Tutor] getting around ValueError in os.walk In-Reply-To: <43DE7434.60502@pobox.com> References: <43DE7434.60502@pobox.com> Message-ID: <7e3eab2c0601301434g79f61c8bgcc5e38562645dac1@mail.gmail.com> Andrew, I put in your code, exactly as you have it, with only three changes: #!/usr/bin/python import os for (dirpath, subdirs, filenames) in os.walk("/python24"): # a comma instead of a period after dirpath for file in filenames: if file.endswith(".py"): # py instead of baz, just for my machine print os.path.join(dirpath,file) # file instead of f This walks the directories and prints out the path and filename. On a side note I've never had a problem throwing several thousand files or lines at python. On 1/30/06, Andrew D. Fant wrote: > > I'm working on a program to do some processing on a directory tree. If I > had > been doing it in a shell script, the core of the processing would have > been in > a "find $ROOT -type f -name FOO -print" command" > > On the web, I found a snippet of code that demonstrated the os.walk module > and > I created a simple test program to work on my tree that looked like this: > > #!/usr/bin/python > import os > > for (dirpath. subdirs, filenames) in os.walk("/foo/bar"): > for file in filenames: > if file.endswith(".baz"): > print os.path.join(dirpath,f) > > > when I try to run it, I get a "ValueError: too many values to unpack" > which I > think comes from the fact that there is a subdirectory of /foo/bar which > has > over 2500 files in it. The tree can't be easily restructured for legacy > reasons. Can anyone suggest the best way to get around this in code? > > Thanks, > Andy > > -- > Andrew Fant | And when the night is cloudy | This space to let > Molecular Geek | There is still a light |---------------------- > fant at pobox.com | That shines on me | Disclaimer: I don't > Boston, MA | Shine until tomorrow, Let it be | even speak for myself > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060130/11ede0da/attachment.html From john at fouhy.net Mon Jan 30 23:34:33 2006 From: john at fouhy.net (John Fouhy) Date: Tue, 31 Jan 2006 11:34:33 +1300 Subject: [Tutor] getting around ValueError in os.walk In-Reply-To: <43DE7434.60502@pobox.com> References: <43DE7434.60502@pobox.com> Message-ID: <5e58f2e40601301434x18a07d58q@mail.gmail.com> On 31/01/06, Andrew D. Fant wrote: > when I try to run it, I get a "ValueError: too many values to unpack" which I > think comes from the fact that there is a subdirectory of /foo/bar which has > over 2500 files in it. The tree can't be easily restructured for legacy > reasons. Can anyone suggest the best way to get around this in code? No, this means you are trying to unpack a tuple but you don't have enough variables to do so. example: >>> x, y = (1, 2, 3) Traceback (most recent call last): File "", line 1, in ? ValueError: too many values to unpack Assuming the code you have given is copied-and-pasted directly, the error is on this line: > for (dirpath. subdirs, filenames) in os.walk("/foo/bar"): Do you see that '.' after dirpath? It should be a comma :-) What you've done is something like this: >>> x.y, z = (1, 2, 3) Traceback (most recent call last): File "", line 1, in ? ValueError: too many values to unpack IMO, it's a somewhat misleading error message. If the arities lined up, you'd get: >>> x.y, z = (1, 2) Traceback (most recent call last): File "", line 1, in ? NameError: name 'x' is not defined which might give you a better clue as to where the problem is. HTH! -- John. From alan.gauld at freenet.co.uk Tue Jan 31 01:45:42 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 31 Jan 2006 00:45:42 -0000 Subject: [Tutor] Copy files References: <20060130142855.72363.qmail@web25907.mail.ukl.yahoo.com> Message-ID: <04cb01c625ff$aa645c70$0b01a8c0@xp> David, Can I suggest you rethink your variable names? That might make it clearer what is happening. > def compare_files(file_name1, file_name2): > x = cmp (file_name1, file_name2) > return x Seems fair enough except file_name1 and file_name2 are actually file *contents*! And in fact the function really just compares 2 strings. in fact it compares 2 anythings, It just returns the resulkt of cmp() so you could lose it entirely! You might find it easier to use the filecmp.cmp() function which compares two files using their filenames as arguments. > def open_files(file_name): > file_is = open(file_name,'r') > file_conts = file_is.read() > return file_conts And "open_files" actually only opens one file and then returns it contents. So a name like "contents_of(filename)" would be more descriptive > def change_files(file_1, file_2): > yesorno = raw_input("Do you want them to be the same Y or N ") > yesorno = string.upper(yesorno) > if yesorno == 'Y': > try: > shutil.copy2(file_1, file_2) > print "copy has been done " > except: > print "it did not work" The user prompt doesn't give the user much clue what he is agreeing to make the same but otherwise this seems OK. I assume you have write access to both files? > #main > file_name1 = open_files("test1.txt") > file_name2 = open_files("test2.txt") > file_name3 = open_files("test3.txt") the 3 variables above each contain not the *name* of the file but the contents. > import shutil > import string > > x = compare_files(file_name3, file_name1) x = cmp(f1,f2) would be just as useful. > if x != 0: > print "test1 and test3 are different" > change_files("test1.txt", "text3.txt", file_name1) The function above has 2 parameters but you are passing 3 arguments. I'd expect Python to complain at that? Also the first two are filenames but the last is the contents of file1 > else: > file_name1 = "test2.txt" but here you overwrite the contents with the filename > print file_name1 and print "text2.txt" I'm not sure what thats trying to do? > x = compare_files(file_name3, file_name2) again a simple cmp() would do the same job > if x != 0: > print "test2 and test3 are different" > change_files("test2.txt", "text3.txt") Since you didn't mention an error I assume your program always goes down this path? Despite the confusing names it looks like the program must be going down the second branch and trying to copy the two files. The only obvious thing I can think of is that the files do not have write permissions set appropriately? Not sure if that helps at all but the best I can do at 12:45am...:-) Alan G. From alan.gauld at freenet.co.uk Tue Jan 31 01:51:23 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 31 Jan 2006 00:51:23 -0000 Subject: [Tutor] getting around ValueError in os.walk References: <43DE7434.60502@pobox.com> Message-ID: <04d101c62600$75756080$0b01a8c0@xp> > for (dirpath. subdirs, filenames) in os.walk("/foo/bar"): You need a comma after dirpath, python sees only two values in the tuple but expects 3 (actually I'd expect a syntax error, unless there is no space in the real code?) > when I try to run it, I get a "ValueError: too many values to unpack" > which I This is the standard message when Python tries to unpack a tuple into fewer variables than are in the tuple. >>> a,b = (1,2,3) Traceback (most recent call last): File "", line 1, in ? ValueError: too many values to unpack >>> > think comes from the fact that there is a subdirectory of /foo/bar which > has > over 2500 files in it. The tree can't be easily restructured for legacy 2,500 files shouldn't cause Python to even blink. BTW The OS topic in my tutor covers os.walk too. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From emile at fenx.com Tue Jan 31 02:07:09 2006 From: emile at fenx.com (gmane) Date: Mon, 30 Jan 2006 17:07:09 -0800 Subject: [Tutor] I'm puzzled References: <20060122234626.GA73196@xs4all.nl> Message-ID: > Why will this little program crash when you enter the > enter key? > > while True: > a = raw_input('number? ') > if a.isdigit(): > print 'isdigit' > elif a[0] == '-' and a[1:].isdigit(): You could instead use elif a.startswith('-') and a[1:].isdigit(): as the empty string certainly doesn't start with '-', and python won't check the second half after the first check evaluates false. > print '- + isdigit' > elif a == 'q': > break > else: > print 'no digit' From fant at pobox.com Tue Jan 31 02:19:07 2006 From: fant at pobox.com (Andrew Fant) Date: Mon, 30 Jan 2006 20:19:07 -0500 Subject: [Tutor] getting around ValueError in os.walk In-Reply-To: <04d101c62600$75756080$0b01a8c0@xp> References: <43DE7434.60502@pobox.com> <04d101c62600$75756080$0b01a8c0@xp> Message-ID: <43DEBB0B.2000602@pobox.com> Mea culpa, Mea Maxima Culpa. I apoligize for sending quickly when I was trying to edit in vi. Thanks to everyone who caught my typo and explained ValueError to me in detail. Andy (vowing to RTFM more closely in the future) -- Andrew Fant | And when the night is cloudy | This space to let Molecular Geek | There is still a light |---------------------- fant at pobox.com | That shines on me | Disclaimer: I don't Boston, MA | Shine until tomorrow, Let it be | even speak for myself From k.weinert at gmx.net Tue Jan 31 02:26:47 2006 From: k.weinert at gmx.net (K. Weinert) Date: Tue, 31 Jan 2006 02:26:47 +0100 Subject: [Tutor] wxPython In-Reply-To: References: Message-ID: <43DEBCD7.1030305@gmx.net> > How can I avoid that the graphics freeze. > here is another example for doing this: http://uucode.com/texts/pylongopgui/pyguiapp.html It uses Tkinter, but it should work in wxPython, too. Kind regards, Karsten. From john at fouhy.net Tue Jan 31 02:28:24 2006 From: john at fouhy.net (John Fouhy) Date: Tue, 31 Jan 2006 14:28:24 +1300 Subject: [Tutor] getting around ValueError in os.walk In-Reply-To: <04d101c62600$75756080$0b01a8c0@xp> References: <43DE7434.60502@pobox.com> <04d101c62600$75756080$0b01a8c0@xp> Message-ID: <5e58f2e40601301728k51d7f51ar@mail.gmail.com> On 31/01/06, Alan Gauld wrote: > You need a comma after dirpath, python sees only two values > in the tuple but expects 3 (actually I'd expect a syntax error, > unless there is no space in the real code?) >>> 1 . __add__ ( 4 ) 5 Python is quite happy about whitespace either side of the '.' operator.. Some of the wxPython guys like their whitespace, eg: http://wiki.wxpython.org/index.cgi/DataAwareControlsMixin#head-d1249e34e446972c34012a866f67bc184db7bc52 :-) -- John. From carbonnb at sympatico.ca Tue Jan 31 03:10:31 2006 From: carbonnb at sympatico.ca (Bryan Carbonnell) Date: Mon, 30 Jan 2006 21:10:31 -0500 Subject: [Tutor] Getting Running File's Name Message-ID: Can Python return the name of the current file's name? In other works, if I am running a Python file (MyPythonFile.py) is there a function that will return 'MyPythonFile.py'? This will be used in Linux if that matters. Thanks -- Bryan Carbonnell - carbonnb at sympatico.ca Warning: dates on calendar are closer than they appear. From Hans.Dushanthakumar at navman.com Tue Jan 31 03:43:57 2006 From: Hans.Dushanthakumar at navman.com (Hans Dushanthakumar) Date: Tue, 31 Jan 2006 15:43:57 +1300 Subject: [Tutor] Getting Running File's Name Message-ID: <5667508E43F1B740BCFA57FF46E35300032D51E7@nav-akl-exch-c.newton.navman.com> Under WinXP, the variable sys.argv[0] holds the script file name (including the path). Not sure, but it may work the same under Linux as well. -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Bryan Carbonnell Sent: Tuesday, 31 January 2006 3:11 p.m. To: tutor at python.org Subject: [Tutor] Getting Running File's Name Can Python return the name of the current file's name? In other works, if I am running a Python file (MyPythonFile.py) is there a function that will return 'MyPythonFile.py'? This will be used in Linux if that matters. Thanks -- Bryan Carbonnell - carbonnb at sympatico.ca Warning: dates on calendar are closer than they appear. _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From wpmartin at gmail.com Tue Jan 31 04:04:47 2006 From: wpmartin at gmail.com (Pat Martin) Date: Mon, 30 Jan 2006 19:04:47 -0800 Subject: [Tutor] Life after beginner Message-ID: <44db03850601301904m53d08ef9lc4c36d2bd7e99f3a@mail.gmail.com> Hello, I have been reading about and playing with programming in python for awhile now. I have most of the basics down. I know what a tuple is, I know how to load modules, and I understand a fair amount of beginning programming theory. I have written some scripts for both home and work and have become fairly proficient at reading python code. My question is, what next? Is there some intermediate tutorials or books out there that I can start learning some real meat in the language? Things that just writing a simple script I might miss. I really want to learn about in depth programming and programming style but I am far from an expert. But with all the languages I have learned (really touched on) C, C++ perl, and python I seem to get to this point and then I am not sure where to go from here. I want to be able to write large projects in python and carry that experience over to the other languages as well. So any insight would be welcome. Thank you. Pat -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060130/706027ff/attachment.html From andre.roberge at gmail.com Tue Jan 31 04:13:56 2006 From: andre.roberge at gmail.com (Andre Roberge) Date: Mon, 30 Jan 2006 23:13:56 -0400 Subject: [Tutor] ANN: Rur-ple 0.95 has been released Message-ID: <7528bcdd0601301913o1588960fud839d4b888fe6228@mail.gmail.com> RUR-PLE 0.95 has been released. A link to the download page can be found at http://rur-ple.sourceforge.net (The site is slightly out of date, and there is no plan to update it in the future as it provides an excellent idea of what RUR-PLE is about.) This new version contains a few bug fixes and it should now work properly on MacOS. wxPython 2.6+ is strongly recommmended. There has been a few minor changes in the robot instructions, and the lessons has undergone some major changes. RUR-PLE stands for Roberge's Used Robot: a Python Learning Environment. This learning environment contains four main elements: 1. A simple html browser to look at the documentation and, potentially, the lessons. However, the new lessons use cascading style sheets which cannot be interpreted correctly by the browser. Usage of an external browser (Firefox :-) is strongly recommended. 2. A "robot world" with a robot that can accomplish tasks through Python programs. 3. A built-in interpreter which can be used to play with Python 4. A built-in file editor which can be used for futher Python explorations. The interface is available in English, French and Spanish. Translations are welcome! Version 0.95 contains 36 complete lessons (English version only). The lessons are also available as a separate download. Version 1.0, which will aim to be a "complete" Python tutorial for people that have never programmed before, should have approximately 50 lessons. A few "bonus" lessons have been included. In particular, it is suggested that you have a look at "A Robotic Fairy Tale". ===== In 1981, Richard Pattis introduced "Karel the Robot" as a tool to teach computer programming. Reeborg is a robot built on the 1981 Pattis' model... and it is starting to show its age. It has an oil leak, which allows us to follow its trail. Its compass is broken; it only knows if it is facing north or not, unlike Karel who could determine its orientation with respect to all four cardinal points. Pattis' Karel the Robot was named after the author Karel Capek, who popularized the word robot in his play Rossum's Universal Robots (RUR). While RUR-PLE shares the basic RUR acronym, in this case it stands for Roberge's Used Robot. However, through the magic of Guido van Rossum's Python, you can learn how to fix it and design a better one, worthy of the name Rossum's Universal Robot. ==== If you've read this far... Version 0.95 contains a new feature, which has been made available as a separate download: lightning.py This is a cross between a Python editor and a Python interpreter. Just enter a script in the Editor window, press "run", and you get the result in the output window. It handles input() and raw_input() through dialogs. I like it so much, that I submitted a simplified version to the online Python cookbook. From dyoo at hkn.eecs.berkeley.edu Tue Jan 31 07:54:43 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 30 Jan 2006 22:54:43 -0800 (PST) Subject: [Tutor] Life after beginner In-Reply-To: <44db03850601301904m53d08ef9lc4c36d2bd7e99f3a@mail.gmail.com> Message-ID: On Mon, 30 Jan 2006, Pat Martin wrote: > My question is, what next? Is there some intermediate tutorials or books > out there that I can start learning some real meat in the language? Hi Pat, Maybe you'd like something like: http://diveintopython.org/ which is pretty meaty (or, if you're vegetarian... er, maybe... gluteny?) It goes into using Python to do more substantial things like unit testing and making web services. You may also want to look at books that don't focus exclusively on Python. There are some classics like Code Complete, for example, that show fundamental and practical programming concepts: http://www.cc2e.com/ There are a lot more books out there, but my brain is off right now. *grin* I'm sure others can suggest other books. If you have more questions, please feel free to ask. Best of wishes! From w.damen at gmail.com Tue Jan 31 09:17:00 2006 From: w.damen at gmail.com (Rinzwind) Date: Tue, 31 Jan 2006 09:17:00 +0100 Subject: [Tutor] Getting Running File's Name In-Reply-To: <5667508E43F1B740BCFA57FF46E35300032D51E7@nav-akl-exch-c.newton.navman.com> References: <5667508E43F1B740BCFA57FF46E35300032D51E7@nav-akl-exch-c.newton.navman.com> Message-ID: <4677730601310017ybb519d0k60245799813d2cc8@mail.gmail.com> Why would that be any different under Linux? sys.argv[0] Wim On 1/31/06, Hans Dushanthakumar wrote: > Under WinXP, the variable > sys.argv[0] holds the script file name (including the path). Not sure, > but it may work the same under Linux as well. > > > -----Original Message----- > From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On > Behalf Of Bryan Carbonnell > Sent: Tuesday, 31 January 2006 3:11 p.m. > To: tutor at python.org > Subject: [Tutor] Getting Running File's Name > > Can Python return the name of the current file's name? > > In other works, if I am running a Python file (MyPythonFile.py) is there > a function that will return 'MyPythonFile.py'? > > This will be used in Linux if that matters. > > Thanks > > -- > Bryan Carbonnell - carbonnb at sympatico.ca > Warning: dates on calendar are closer than they appear. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From jonathan.r.moore at gmail.com Tue Jan 31 10:42:05 2006 From: jonathan.r.moore at gmail.com (Jon Moore) Date: Tue, 31 Jan 2006 09:42:05 +0000 Subject: [Tutor] Newbie question re. Functions Message-ID: Hi, I am still working my way through my 'Python for absolute beginners book' and have hit a brick wall with one of the end of chapter exercises. The challenge says: Improve the function ask_number() so that the function can be called with a step value. Make the default value of step 1. The function looks like this: def ask_number(question, low, high): """Ask for a number within the range""" response = None while response not in range(low, high): response = int(raw_input(question)) return response The author has not eluded to 'step values' in anyway that I can see in the proceeding chapters! HELP! -- Best Regards Jon Moore -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060131/445a95b2/attachment.html From alan.gauld at freenet.co.uk Tue Jan 31 10:50:23 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 31 Jan 2006 09:50:23 -0000 Subject: [Tutor] Life after beginner References: <44db03850601301904m53d08ef9lc4c36d2bd7e99f3a@mail.gmail.com> Message-ID: <04fa01c6264b$c1edaee0$0b01a8c0@xp> Hi Pat, > My question is, what next? Is there some intermediate tutorials or books There are lots of more advanced books, usually focusing on a particular topic. Some examples include: Python and Tkinter programming by Grayson Python Programming on Win32 by Hammond Text Processing in Python by Mertz and there are others on XML, etc. Programming Python by Lutz is also fairly in-depth and the new third edition promises to be more so. (I intend to replace my first edition when it finally hits the streets!) And of course Dive into Python sits somewhere between beginner tutor and advanced specialist book. > just writing a simple script I might miss. I really want to learn about in > depth programming and programming style but I am far from an expert. But > with all the languages I have learned (really touched on) C, C++ perl, Programming style covers two things: 1) Good fundamental programming rtechnique and 2) language idioms If you want to be a better programmer in general then you should consider reading some general programming books such as: Code Complete by McConnelk - Every programmer should read this Programming Pearls by Benley - likewise The Pragmattic Programmer by Hunt & Thomas The Practice of Programming by Kernighan/Pike These all discuss general techniques for making programs more readable, maintainable and more efficient, regardless of language. (In fact most include examples in multiple languages) > I want to be able to write large projects in python and carry that > experience over to the other languages as well. So join a large project. Sourceforge has lots of opensource projects crying out for volunteers. You can start by writing documentation as a way of getting to know the system, then testing new releases, then doing bug fixes and finally coding new features. All contributions are welcomed. And you can see your software being used by the world at large. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Tue Jan 31 12:02:15 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 31 Jan 2006 06:02:15 -0500 Subject: [Tutor] Life after beginner In-Reply-To: <44db03850601301904m53d08ef9lc4c36d2bd7e99f3a@mail.gmail.com> References: <44db03850601301904m53d08ef9lc4c36d2bd7e99f3a@mail.gmail.com> Message-ID: <43DF43B7.4020108@tds.net> Pat Martin wrote: > Hello, > > I have been reading about and playing with programming in python for > awhile now. I have most of the basics down. I know what a tuple is, I > know how to load modules, and I understand a fair amount of beginning > programming theory. I have written some scripts for both home and work > and have become fairly proficient at reading python code. > > My question is, what next? Is there some intermediate tutorials or books > out there that I can start learning some real meat in the language? > Things that just writing a simple script I might miss. I really want to > learn about in depth programming and programming style but I am far from > an expert. But with all the languages I have learned (really touched on) > C, C++ perl, and python I seem to get to this point and then I am not > sure where to go from here. I want to be able to write large projects in > python and carry that experience over to the other languages as well. So > any insight would be welcome. It sounds like you are looking for two different kinds of learning. First, you want a deeper knowledge of Python - what are the advanced features, how is Python really used? I found the book Python Cookbook to be a great intermediate step in my own learning - it is full of well-written, idiomatic Python code that shows you how experienced practitioners actually use the language. Second, you want to get better at the craft of programming. This is harder than learning Python and takes practice. Look at books that are not specifically Python oriented. As well as the books Danny and Alan recommend, I have some favorites listed here: http://personalpages.tds.net/~kent37/BookList.html Kent From kent37 at tds.net Tue Jan 31 12:12:38 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 31 Jan 2006 06:12:38 -0500 Subject: [Tutor] Newbie question re. Functions In-Reply-To: References: Message-ID: <43DF4626.1060206@tds.net> Jon Moore wrote: > Hi, > > I am still working my way through my 'Python for absolute beginners > book' and have hit a brick wall with one of the end of chapter exercises. > > The challenge says: > > Improve the function ask_number() so that the function can be called > with a step value. Make the default value of step 1. > > The function looks like this: > > def ask_number(question, low, high): > """Ask for a number within the range""" > response = None > while response not in range(low, high): > response = int(raw_input(question)) > return response > > The author has not eluded to 'step values' in anyway that I can see in > the proceeding chapters! I have the book and I don't understand what he is asking for in that question either. To me a 'step value' would be something that alters a sequence, for example the third argument to range() is a step value: >>> help(range) Help on built-in function range in module __builtin__: range(...) range([start,] stop[, step]) -> list of integers Return a list containing an arithmetic progression of integers. range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0. When step is given, it specifies the increment (or decrement). For example, range(4) returns [0, 1, 2, 3]. The end point is omitted! These are exactly the valid indices for a list of 4 elements. >>> range(0, 6) [0, 1, 2, 3, 4, 5] >>> range(0, 6, 2) [0, 2, 4] Kent From alan.gauld at freenet.co.uk Tue Jan 31 12:24:12 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 31 Jan 2006 11:24:12 -0000 Subject: [Tutor] Newbie question re. Functions References: Message-ID: <051201c62658$dcaa1770$0b01a8c0@xp> Hi Jon, > Improve the function ask_number() so that the function can be called with > a > step value. Make the default value of step 1. If its any consolation that doesn't really mean much to me either. I understand the concept of step value - range() takes one for example, check the docs. But how a step value would be used in this kind of user-input scenario I have no idea! def ask_number(question, low, high): """Ask for a number within the range""" response = None while response not in range(low, high): response = int(raw_input(question)) return response The only possibility I can think of is that the step value is used to narrow the acceptable range each time round the loop. But given we don't necessarily tell the user what the range is that would be weird. We'd need to modify question as we go or something. On the assumption you aren't being marked on this I'd just make up your own mind what it should do and do it! :-) ...and treat it as a good example of a bad statement of requirements! Alan G From davholla2002 at yahoo.co.uk Tue Jan 31 12:41:43 2006 From: davholla2002 at yahoo.co.uk (David Holland) Date: Tue, 31 Jan 2006 11:41:43 +0000 (GMT) Subject: [Tutor] Copy files In-Reply-To: <04cb01c625ff$aa645c70$0b01a8c0@xp> Message-ID: <20060131114143.43508.qmail@web25904.mail.ukl.yahoo.com> Alan, Thanks for that. Hopefully this now is easier to read. The only problem is that despite the fact that as the same user, I can manually change these files (so I must have the right file permissions ?) - the copying does not happening. def compare_files(file_name1, file_name2): x = filecmp.cmp (file_name1, file_name2) print x return x def change_files(file_1, file_2): yesorno = raw_input("Do you want them to be the same Y or N ") yesorno = string.upper(yesorno) if yesorno == 'Y': try: shutil.copy(file_1, file_2) print "the copy part thinks it worked" except: print "it did not work" def did_it_work(file_1, file_2): #this is to debug the copy afterchange = compare_files("test1.txt","test3.txt" ) if afterchange == 'True': print "the copy went fine" else: print "problem with the copy" #main import shutil import string import filecmp x = compare_files("test1.txt","test3.txt" ) if x == False: print "test1 and test3 are different" change_files("test1.txt", "text3.txt") did_it_work("test1.txt", "text3.txt") else: x = compare_files("test2.txt","test3.txt" ) if x == False: print "test2 and test3 are different" change_files("test2.txt", "text3.txt") did_it_work("test2.txt", "text3.txt") print "program finished" Alan Gauld wrote: David, Can I suggest you rethink your variable names? That might make it clearer what is happening. > def compare_files(file_name1, file_name2): > x = cmp (file_name1, file_name2) > return x Seems fair enough except file_name1 and file_name2 are actually file *contents*! And in fact the function really just compares 2 strings. in fact it compares 2 anythings, It just returns the resulkt of cmp() so you could lose it entirely! You might find it easier to use the filecmp.cmp() function which compares two files using their filenames as arguments. > def open_files(file_name): > file_is = open(file_name,'r') > file_conts = file_is.read() > return file_conts And "open_files" actually only opens one file and then returns it contents. So a name like "contents_of(filename)" would be more descriptive > def change_files(file_1, file_2): > yesorno = raw_input("Do you want them to be the same Y or N ") > yesorno = string.upper(yesorno) > if yesorno == 'Y': > try: > shutil.copy2(file_1, file_2) > print "copy has been done " > except: > print "it did not work" The user prompt doesn't give the user much clue what he is agreeing to make the same but otherwise this seems OK. I assume you have write access to both files? > #main > file_name1 = open_files("test1.txt") > file_name2 = open_files("test2.txt") > file_name3 = open_files("test3.txt") the 3 variables above each contain not the *name* of the file but the contents. > import shutil > import string > > x = compare_files(file_name3, file_name1) x = cmp(f1,f2) would be just as useful. > if x != 0: > print "test1 and test3 are different" > change_files("test1.txt", "text3.txt", file_name1) The function above has 2 parameters but you are passing 3 arguments. I'd expect Python to complain at that? Also the first two are filenames but the last is the contents of file1 > else: > file_name1 = "test2.txt" but here you overwrite the contents with the filename > print file_name1 and print "text2.txt" I'm not sure what thats trying to do? > x = compare_files(file_name3, file_name2) again a simple cmp() would do the same job > if x != 0: > print "test2 and test3 are different" > change_files("test2.txt", "text3.txt") Since you didn't mention an error I assume your program always goes down this path? Despite the confusing names it looks like the program must be going down the second branch and trying to copy the two files. The only obvious thing I can think of is that the files do not have write permissions set appropriately? Not sure if that helps at all but the best I can do at 12:45am...:-) Alan G. --------------------------------- To help you stay safe and secure online, we've developed the all new Yahoo! Security Centre. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060131/d90d2850/attachment.htm From jonathan.r.moore at gmail.com Tue Jan 31 13:10:54 2006 From: jonathan.r.moore at gmail.com (Jon Moore) Date: Tue, 31 Jan 2006 12:10:54 +0000 Subject: [Tutor] Newbie question re. Functions In-Reply-To: <051201c62658$dcaa1770$0b01a8c0@xp> References: <051201c62658$dcaa1770$0b01a8c0@xp> Message-ID: I guess I am not going mad then! I will skip this exercise and move on. Thanks Jon On 31/01/06, Alan Gauld wrote: > > Hi Jon, > > > Improve the function ask_number() so that the function can be called > with > > a > > step value. Make the default value of step 1. > > If its any consolation that doesn't really mean much to me either. > I understand the concept of step value - range() takes one for > example, check the docs. > > But how a step value would be used in this kind of user-input scenario > I have no idea! > > def ask_number(question, low, high): > """Ask for a number within the range""" > response = None > while response not in range(low, high): > response = int(raw_input(question)) > return response > > The only possibility I can think of is that the step value is used to > narrow the acceptable range each time round the loop. But given > we don't necessarily tell the user what the range is that would be > weird. We'd need to modify question as we go or something. > > On the assumption you aren't being marked on this I'd just > make up your own mind what it should do and do it! :-) > > ...and treat it as a good example of a bad statement of > requirements! > > Alan G > > -- Best Regards Jon Moore -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060131/2b1b5c8d/attachment.html From jjk_saji at yahoo.com Tue Jan 31 13:24:07 2006 From: jjk_saji at yahoo.com (John Joseph) Date: Tue, 31 Jan 2006 12:24:07 +0000 (GMT) Subject: [Tutor] Cannot run .py file from apache web server , Guidance requested Message-ID: <20060131122407.93478.qmail@web34805.mail.mud.yahoo.com> Hi I am trying to execute .py scripts from my apache web server , but it is not giving the results as how I run php files , it just displays the contents of the script , I am able to run and get results of PHP from the same loaction my ?sample-test.py ?file is as follows import cgi reshtml = '''Content-Type: text/html\n Friends CGI Demo (dynamic screen)

Friends list for: Joseph

Your name is: John

You have 20 friends. ''' When I access this script from the url ?http://192.168.20.99/~john/ sample-test.py? in the browser I see the contents of the file , not the result Is there any function similar to phpino() in python , so that I can test Guidance requested , Joseph John ___________________________________________________________ To help you stay safe and secure online, we've developed the all new Yahoo! Security Centre. http://uk.security.yahoo.com From bgailer at alum.rpi.edu Tue Jan 31 15:45:33 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Tue, 31 Jan 2006 06:45:33 -0800 Subject: [Tutor] Newbie question re. Functions In-Reply-To: References: Message-ID: <43DF780D.8070004@alum.rpi.edu> Jon Moore wrote: > Hi, > > I am still working my way through my 'Python for absolute beginners > book' and have hit a brick wall with one of the end of chapter exercises. > > The challenge says: > > Improve the function ask_number() so that the function can be called > with a step value. Make the default value of step 1. > > The function looks like this: > > def ask_number(question, low, high): > """Ask for a number within the range""" > response = None > while response not in range(low, high): > response = int(raw_input(question)) > return response > > The author has not eluded to 'step values' in anyway that I can see in > the proceeding chapters! This lights my frustration fire. I wonder whether the author tested the book? When I worked for a training company I was asked to test a new on-line course on JCL. I demurred by saying "But I don't know JCL.". The reply was "that's exactly what we want!" So a general recommendation to authors is to have a member of the target audience "test" the book. You Jon have done that but at some cost to you and those of us on this list. From jonathan.r.moore at gmail.com Tue Jan 31 16:02:46 2006 From: jonathan.r.moore at gmail.com (Jon Moore) Date: Tue, 31 Jan 2006 15:02:46 +0000 Subject: [Tutor] Newbie question re. Functions In-Reply-To: <43DF780D.8070004@alum.rpi.edu> References: <43DF780D.8070004@alum.rpi.edu> Message-ID: I know. Its hard enough for someone like me as it is without things like this complicating it! I have another one for the group, but I will save it for another day ;) I have been looking for contact details for the author to ask him what he was eluding to with the exercise, but to no avail. Jon On 31/01/06, Bob Gailer wrote: > > Jon Moore wrote: > > Hi, > > > > I am still working my way through my 'Python for absolute beginners > > book' and have hit a brick wall with one of the end of chapter > exercises. > > > > The challenge says: > > > > Improve the function ask_number() so that the function can be called > > with a step value. Make the default value of step 1. > > > > The function looks like this: > > > > def ask_number(question, low, high): > > """Ask for a number within the range""" > > response = None > > while response not in range(low, high): > > response = int(raw_input(question)) > > return response > > > > The author has not eluded to 'step values' in anyway that I can see in > > the proceeding chapters! > This lights my frustration fire. I wonder whether the author tested the > book? > > When I worked for a training company I was asked to test a new on-line > course on JCL. I demurred by saying "But I don't know JCL.". The reply > was "that's exactly what we want!" > > So a general recommendation to authors is to have a member of the target > audience "test" the book. You Jon have done that but at some cost to you > and those of us on this list. > -- Best Regards Jon Moore -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060131/834b2216/attachment.htm From bgailer at alum.rpi.edu Tue Jan 31 16:24:25 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Tue, 31 Jan 2006 07:24:25 -0800 Subject: [Tutor] Cannot run .py file from apache web server , Guidance requested In-Reply-To: <20060131122407.93478.qmail@web34805.mail.mud.yahoo.com> References: <20060131122407.93478.qmail@web34805.mail.mud.yahoo.com> Message-ID: <43DF8129.2050701@alum.rpi.edu> John Joseph wrote: > Hi > I am trying to execute .py scripts from my > apache web server , but it is not giving the results > as how I run php files , it just displays the > contents of the script , I am able to run and get > results of PHP from the same loaction > my ?sample-test.py ?file is as follows > For python scripts to run in my Apache2Triad installation the script must start with #!h:/apache2triad/python/bin/python.exe I suggest you add a similar comment (with your path to python.exe). When I remove that line I get Server Error 500. So I think there is more involved. In my Apache httpd.conf (configuration file) is the following: #python config LoadFile python\bin\python23.dll #LoadModule python_module modules/mod_python.so Alias /python/ "h:/apache2triad/python/" AddHandler python-program .spy PythonHandler run_spyceModpy::spyceMain AddHandler mod_python .psp PythonHandler mod_python.psp PythonDebug On Do you have anything like that in yours? > import cgi > reshtml = '''Content-Type: text/html\n > Friends CGI Demo (dynamic screen) > >

Friends list for: Joseph

> Your name is: John

> You have 20 friends. > ''' > When I access this script from the url > ?http://192.168.20.99/~john/ sample-test.py? > in the browser I see the contents of the file , not > the result > > Is there any function similar to phpino() in python , > so that I can test > Guidance requested , > Joseph John > > > > > ___________________________________________________________ > To help you stay safe and secure online, we've developed the all new Yahoo! Security Centre. http://uk.security.yahoo.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From bgailer at alum.rpi.edu Tue Jan 31 16:29:47 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Tue, 31 Jan 2006 07:29:47 -0800 Subject: [Tutor] Cannot run .py file from apache web server , Guidance requested In-Reply-To: <20060131122407.93478.qmail@web34805.mail.mud.yahoo.com> References: <20060131122407.93478.qmail@web34805.mail.mud.yahoo.com> Message-ID: <43DF826B.9040100@alum.rpi.edu> Further delving leads to "Apache Tutorial: Dynamic Content with CGI" in the Apache Documentation. Under that is a section "But it's still not working! ... you see ... The source code of your CGI program ...That means that you have not properly configured Apache to process your CGI program. Reread the section on configuring Apache and try to find what you missed" From intercodes at gmail.com Tue Jan 31 17:54:29 2006 From: intercodes at gmail.com (Intercodes) Date: Tue, 31 Jan 2006 22:24:29 +0530 Subject: [Tutor] smtplib with yahoo smtp server Message-ID: <37e70e3b0601310854h41208b0fi661c39e283699977@mail.gmail.com> Hello everyone, I am working with a registration system for my website in mod_python. I needed to send mail to registered users for confirmation. Since I can't use my ISP's smtp server, I used yahoo's smtp server and my yahoo username and password to connect and send mail using this script (see below). But I get the following error. "Traceback (most recent call last): File "mail.py", line 12, in ? session = smtplib.SMTP(smtpserver) File "/usr/lib/python2.4/smtplib.py", line 255, in __init__ addr = socket.gethostbyname(socket.gethostname()) socket.gaierror: (-2, 'Name or service not known') " I got this script from some website I can't remember and just changed some values to get it to work. Is is possible to send mail like this? Is there any other easy way to do this? Thanks for your time. --------------------------- import smtplib smtpserver = 'smtp.mail.yahoo.com' AUTHREQUIRED = 1 smtpuser = 'intercodes at .[snip]..' ** smtppass = '[snip]' RECIPIENTS = ['intercodes@[snip]'] SENDER = 'intercodes@[snip]' mssg = "mod python" session = smtplib.SMTP(smtpserver)*if* AUTHREQUIRED: session.login(smtpuser, smtppass) smtpresult = session.sendmail(SENDER, RECIPIENTS, mssg)** -- Intercodes -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060131/44158161/attachment.htm From alan.gauld at freenet.co.uk Tue Jan 31 18:56:38 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 31 Jan 2006 17:56:38 -0000 Subject: [Tutor] Copy files References: <20060131114143.43508.qmail@web25904.mail.ukl.yahoo.com> Message-ID: <051d01c6268f$af64b770$0b01a8c0@xp> > The only problem is that despite the fact that as the same user, > I can manually change these files (so I must have the right file > permissions ?) Can you do it from within python at the >>> prompt Use os.getcwd() to find out where you are Use os.chdir() to navigate Use os.listdir() to list the folder contents and use shutil.copy() to copy the files. Doing it manually from inside the >>> prompt should show up any problems. You can even try the filecomp call from in there too... >>> is a powerful tool. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From dyoo at hkn.eecs.berkeley.edu Tue Jan 31 20:27:29 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 31 Jan 2006 11:27:29 -0800 (PST) Subject: [Tutor] Newbie question re. Functions In-Reply-To: Message-ID: On Tue, 31 Jan 2006, Jon Moore wrote: > I have been looking for contact details for the author to ask him what > he was eluding to with the exercise, but to no avail. Hi Jon, I did find errata here: http://www.muskalipman.com/ptr_detail.cfm?group=Programming&all=1&isbn=1-59200-073-8 (bottom of the page) but as far as contact information, I haven't been able to find anything. I do agree the challenege exercise as you've put it seems somewhat nonsensical. *grin* From 3dbernard at gmail.com Tue Jan 31 20:53:02 2006 From: 3dbernard at gmail.com (Bernard Lebel) Date: Tue, 31 Jan 2006 14:53:02 -0500 Subject: [Tutor] Exit a child thread using threading.Thread() object Message-ID: <61d0e2b40601311153o3e209f30rd1aa16fb220ced69@mail.gmail.com> A quick question. I have started a child thread using the threading.Thread class. Is there any way to cleanly exit the child thread? What I mean by "cleanly" is for example if you use the thread.start_new() function to create a child thread, the function running in the child thread can call thread.exit() to terminate the thread. I could not find anything comparable in the Thread object's documentation. Thanks Bernard From kent37 at tds.net Tue Jan 31 21:17:09 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 31 Jan 2006 15:17:09 -0500 Subject: [Tutor] Exit a child thread using threading.Thread() object In-Reply-To: <61d0e2b40601311153o3e209f30rd1aa16fb220ced69@mail.gmail.com> References: <61d0e2b40601311153o3e209f30rd1aa16fb220ced69@mail.gmail.com> Message-ID: <43DFC5C5.1050900@tds.net> Bernard Lebel wrote: > A quick question. > > I have started a child thread using the threading.Thread class. Is > there any way to cleanly exit the child thread? > > What I mean by "cleanly" is for example if you use the > thread.start_new() function to create a child thread, the function > running in the child thread can call thread.exit() to terminate the > thread. > > I could not find anything comparable in the Thread object's documentation. Both thread.start_new() and threading.Thread wrap a callable object in a new thread. For start_new(), the callable is a parameter passed to the function. For threading.Thread, the callable can be passed as an initialization parameter or by overriding Thread.run(). In any case, the thread runs until the wrapped method terminates, either by a normal function return or by raising an uncaught exception. The usual way to exit a thread is for the wrapped callable to return (just a normal function return). thread.exit() just raises SystemExit which terminates the callable with an uncaught exception. You could probably do the same in a Thread by raising SystemExit explicitly or calling sys.exit() (which raises SystemExit for you). But just returning normally from the callable is the usual way to exit a thread from within the thread. If you want to stop a thread from another thread it is harder. The cleanest way to do it is to set a flag that the running thread will check. There are several recipes in the online cookbook that show how to do this. Kent