From dbroadwell at mindspring.com Thu Apr 1 01:53:04 2004 From: dbroadwell at mindspring.com (David Broadwell) Date: Thu Apr 1 01:48:07 2004 Subject: [Tutor] Advice; Pointers Needed Message-ID: I'm trying to get a handle on a pet project. What I'm trying to build is a basic 'dice' server to send and receive dice rolls with multiple internet clients. The 'dice' in this case is just a rolling algorithm to simulate different types of dice depending on what the 'game master' wants. Luckily the game master IS the programmer that will be at the server, and until it goes the only dice schema will be rock, paper, scissors OR d10 or d10. Also luckily is the fact there is only one client (for now), and that is the machine that the player (who is also the programmer) can get to via rotating his seat. Also luckily is the fact that both machines in question while in differing subnets (forcing internet communication) are one hub away from each other. The server will need to be able to roll dice, request dice roll from client, wait for die roll, evaluate success or failure, display result of roll, send message success/fail message to client, handle a client login, handle a client logout, forcibly log a client out. The client will need to read a incoming request for a die roll, roll die of the type requested, send the result to the server, wait for the response from the server and tell the player a success or fail message, login to server, logout from server. For a first pass, (Hardcode server and client) simply having the server send a client the succeeded or failed message will be a good starting success. -- I'm guessing that I'll be needing threads in there somewhere. But as far as the rest, where should I start? -- We game online pretty good, but this is the stumbling point ... having them roll dice under the eye of a web cam is a glorious waste of bandwidth. -- Programmer's Mantra; Observe, Brainstorm, Prototype, Repeat ... Quickly! David Broadwell From wiseone6 at hotmail.com Thu Apr 1 06:50:09 2004 From: wiseone6 at hotmail.com (Maxim Ryan) Date: Thu Apr 1 06:50:15 2004 Subject: [Tutor] unfininished Message-ID: An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040401/8afcb2d9/attachment.html -------------- next part -------------- import random import string def getlist(): file=open("A:\hanging.txt","r") words=file.read() split=string.split(words,'\n') return split def pickword(split): a=random.random()*len(split) a=int(a) b=split[a] print b return b alphabet=string.ascii_lowercase def unguessed(let,alphabet): area=string.find(alphabet,let) alphabet=alphabet[:area]+alphabet[area+1:] print "unguessed:"+alphabet return alphabet def question(b,alphabet): question=raw_input("press A to guess one letter at a time or B to guess the word: ") while question<>"a" and question<>"A" and question<>"b" and question<>"B": print " please enter a or b " question=raw_input("press A to guess one letter at a time or B to guess the whole word: ") if question=="a" or question=="A": partone(b,alphabet) elif question=="b" or question=="B": playgame(b,alphabet)#return #getguess(b) givenletters = [] def underscores(b): output = [] for letter in b: if letter in givenletters: output.append(letter) else: output.append('_') print "Word:" print string.join(output, ' ') def safeinput(b): underscores(b) let= raw_input("enter a letter: ") if let== "": print "please enter a value" return safeinput(b) if len(let)>1: print" please enter a single lowercase letter" return safeinput(b) for char in let: if string.find(string.lowercase,char) == -1: print "please enter a single lowercase letter" return safeinput(b) return let def printlet(let,b,alphabet): show=givenletters.append(let) if let not in b: print"wrong guess" unguessed(let,alphabet) win(b,alphabet) choice(b,alphabet) if let in b: print"good guess" unguessed(let,alphabet) win(b,alphabet) choice(b,alphabet) def getguess(b): ask=raw_input("try to guess the word: ") if ask=="": print "please enter a value" underscores(b) return getguess(b) for char in ask: if string.find(string.lowercase,char)==-1: print "please enter a lowercase letter" underscores(b) return getguess(b) return ask def testword(ask,b,alphabet): if ask ==b: print " CONGRATULATIONS U MADE A FLUKE " return loop(alphabet) return else: print" better luck next time" print "the word was" +" " + b return loop(alphabet) return def win(b,alphabet): for char in b: return b for char in givenletters: return givenletters if b==givenletters: print"dfdfd" loop(alphabet) def loop(alphabet): play=raw_input("DO YOU WANNA PLAY AGAIN? y/n: ") while play<>"y" and play<>"Y" and play<>"n" and play<>"N": print " please enter y or n " play=raw_input("DO YOU WANNA PLAY AGAIN? y/n: ") if play=="y" or play=="Y": start(alphabet) else: print "THE END" return def playgame(b,alphabet): #underscores(b) guess=getguess(b) #you guesses the entire word testword(guess,b,alphabet) #compares word with guess def partone(b,alphabet): safe=safeinput(b) printlet(safe,b,alphabet) #display entered letters in underscores def choice(b,alphabet): underscores(b) #print underscores question(b,alphabet) #choice between guessing word or each letter def start(alphabet): a=getlist() b=pickword(a) choice(b,alphabet) start(alphabet) #start From kbond at free.fr Thu Apr 1 13:20:09 2004 From: kbond at free.fr (kbond) Date: Thu Apr 1 13:21:19 2004 Subject: [Tutor] Python exes In-Reply-To: References: Message-ID: <406C5D59.9000708@free.fr> If you are looking for a way to convert py to exe I will advise you to have a look at the following link: http://starship.python.net/crew/theller/moin.cgi/Py2Exe Magnus Lycka wrote: >Brandon wrote: > > >>I've tried all I can about creating a .exe file in python. I've googled, searched, and found everything I could, but I still can not get anything to work. Can someone point me in the right direction? >> >> > >You're not very explicit with what you tried, and what >your problems were, but I've had memory errors with >py2exe and McMillan installer that disappeared when >I used cx_Freeze instead. See >http://starship.python.net/crew/atuining/cx_Freeze/ > > > From dyoo at hkn.eecs.berkeley.edu Thu Apr 1 14:55:15 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Apr 1 14:55:27 2004 Subject: [Tutor] unfininished [please don't ask us to do your homework] In-Reply-To: Message-ID: On Thu, 1 Apr 2004, Maxim Ryan wrote: > can u help me finish this program? as you run it u will see that after > the blanks are filled the prog. does not end [text cut] Hi Ryan, If you have particular questions on Python programming, we can help with that. And if you're running into a particular problem in your program, and you don't understand the error message that Python is giving, then we can talk about that. But if you just want us to do the program for you, then please read: http://www.catb.org/~esr/faqs/smart-questions.html#homework You mentioned that the program does not end. Can you give us more details what you mean? What part of your program doesn't end, or what part seems to repeat? Good luck. From amonroe at columbus.rr.com Thu Apr 1 19:47:05 2004 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Thu Apr 1 19:40:49 2004 Subject: [Tutor] Off Topic: Revision control system In-Reply-To: <20040330212020.GA28045@mubai.sakeos.net> References: <1080673704.951.6.camel@localhost.localdomain> <20040330212020.GA28045@mubai.sakeos.net> Message-ID: <179868462943.20040401194705@columbus.rr.com> >> vi testfile.py >> ./testfile.py >> cp testfile.py testfile2.py >> vi testfile2.py >> ./testfile2.py >> cp testfile2.py testfile3.py >> vi testfile3.py >> etc >> >> I keep copying so I don't destroy something that works. >> >> Now my question is, do you folks use any sort of revision control system >> on linux ? I've had a look at CVS and RCS but both seem a bit over the >> top for my needs. Makes you wish for the good old VMS way of life. For those that haven't used it, when you save with the same filename, the filesystem automatically makes file.py;1, file.py;2, etc. You could set the number of versions to keep (I think) per directory. Alan From sigurd at 12move.de Thu Apr 1 19:41:26 2004 From: sigurd at 12move.de (=?iso-8859-1?q?Karl_Pfl=E4sterer?=) Date: Thu Apr 1 19:44:43 2004 Subject: [Tutor] first steps In-Reply-To: <200403280825.i2S8Pb80000854@violet.noc.ucla.edu> (peter hodgson's message of "Sun, 28 Mar 2004 00:25:37 -0800") References: <200403280825.i2S8Pb80000854@violet.noc.ucla.edu> Message-ID: On 28 Mar 2004, peter hodgson <- py@humnet.ucla.edu wrote: > A. I DON'T UNDERSTAND THIS: > Here is another example of variable usage: > a = 1 > print a > a = a + 1 [...] > Even if it is the same variable on both sides [OF THE '='] the > computer still reads it as: First find out the data to store [RIGHT > SIDE OF THE '='?] and than [THEN] find out where the data goes [PRINT > COMMAND?]. The `=' sign is misleading; most people who have a feeling for mathematics stumble first on this. Some languages use for assignment a different sign to not confuse people. You uses the right words. If you assign a value you have a left hand side (lhs) and a right hand side (rhs). First the interpreter evaluates the rhs and after that it assigns the returned value to the lhs. So if you write a = a + 1 ^ ^ | | lhs rhs the interprter first evaluates a+1, stores that value somewhere and assigns then a to that value. From now on the old value of a is forgotten. > ---------------------- > B. WHY WON'T THIS RUN? > ----------------------- > #while 1 == 1: would perpetuate the printing of "help..." > #l3 - l6 [extracted from another program] should limit it to five times > count = 0 > max_count = 5 > while count > max_count: > count = count + 1 > print "help, i'm caught in a loop" > #but the program won't run A while loop runs as long as the test in its head returns True. Now look at your test condition: what does it return? > ----------------------------- > C.HAVE I PARSED THIS RIGHT? > ----------------------------- > #values into/out of a pail; #this is l1 > a = 1 #this means a = non-zero, that it is; > s = 0 #empty pail > print "enter numbers to add to the sum" #plus or minus > print "enter 0 to quit" #end the game > while a != 0: #i.e., you're still playing the game; > print "current sum:", s #so we start at 0 > a = input("nmber? ") #and we alter s by a, superceding a = 1 > s = s + a #and a is the increment > #reducing s to 0 won't close program > print "total sum = ", s #not indented cause it only runs at the end > #l2, l3 provide the contents and the pail; Right. > #l5, l6 provide for a way to end the game; IMO no. line 5 prints only a message to the screen. line 6 is the line which holds the test condition. > #playing the game is l4, plus the indented lines l7 - l9; Maybe. I wouldn't know which line should not belong to the game (except line 1 since it's only a comment). If you deleted any other line the game wouldn't run the way it does now. Karl -- Please do *not* send copies of replies to me. I read the list From sigurd at 12move.de Thu Apr 1 19:55:22 2004 From: sigurd at 12move.de (=?iso-8859-1?q?Karl_Pfl=E4sterer?=) Date: Thu Apr 1 20:00:56 2004 Subject: [Tutor] embedding an if In-Reply-To: <200403291839.i2TIdG9a018758@periwinkle.noc.ucla.edu> (peter hodgson's message of "Mon, 29 Mar 2004 10:39:16 -0800") References: <200403291839.i2TIdG9a018758@periwinkle.noc.ucla.edu> Message-ID: On 29 Mar 2004, peter hodgson <- py@humnet.ucla.edu wrote: > tutorial assignment; what am i doing wrong? thanks I think that password programm is one of the most often mentioned programs here :-) > #Modify the password guessing program to keep track of how many times > # the user has entered the password wrong. If it is more than 3 times, > # print "you're screwed, buddy!", or something like that; > passwd = "foobar" #a dummy passwd > count = 3 > current_count = 0 > while passwd != "unicorn": > current_count = current_count + 1 > passwd = raw_input("Passwd: ") > if current_count < count: > print "no, stupid! try again;" > else print "three times, you're out!" > print "welcome in" (you include tabs in your e-mails; that may result in wrong indentation in some e-mail clients or programs if someone tries your code) Did you try that program? It won't run. If you want to wite an else clause it's written like that: if foo == bar: baz else: print 'Python' Even if you program ran it wouldn't run in the way you probably expected; after printing the message you need a way to break the loop: the statement is called `break' (surprise). But then your program will process the code after the loop so a user would always see the welcome message. If you don't want that you need a way to stop the whole program; you must import the sys module and `sys.exit()'. Karl -- Please do *not* send copies of replies to me. I read the list From sigurd at 12move.de Thu Apr 1 20:09:16 2004 From: sigurd at 12move.de (=?iso-8859-1?q?Karl_Pfl=E4sterer?=) Date: Thu Apr 1 20:15:06 2004 Subject: [Tutor] checking variable types In-Reply-To: <5.1.0.14.1.20040322160047.00ac67d0@mailserv.esrf.fr> (Marie Robichon's message of "Mon, 22 Mar 2004 16:03:05 +0100") References: <5.1.0.14.1.20040322160047.00ac67d0@mailserv.esrf.fr> Message-ID: On 22 Mar 2004, Marie Robichon <- robichon@esrf.fr wrote: > How in my python script do I test whether it is a list or a string > before I do my processing ? You could either use try ... except and simply try a list method; if the value is a list no exception gets raised. But I must say I don't really like that approach since you know in advance what types your values may be so you could use the `types' module. >>> import types >>> s = 'string' >>> if type(s) == types.ListType: ... print 'A list' ... else: ... print 'A string' ... A string If your code can be written that it always assumes a list you could write: def string_to_list_maybe (s): if type(s) == types.StringType: return [s] else: return s >>> v = 'a string' >>> v = string_to_list_maybe(v) >>> v ['a string'] >>> L = range(10) >>> L = string_to_list_maybe(L) >>> L [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Karl -- Please do *not* send copies of replies to me. I read the list From dyoo at hkn.eecs.berkeley.edu Thu Apr 1 20:50:57 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Apr 1 20:51:02 2004 Subject: [Tutor] checking variable types In-Reply-To: Message-ID: On Fri, 2 Apr 2004, [iso-8859-1] Karl Pfl=E4sterer wrote: > If your code can be written that it always assumes a list [some text cut] Yes, it might be easier to always assume that the parameter values from the CGI program is a list, if you're reading from that multiple-value selectbox. The CGI documentation at: http://www.python.org/doc/lib/node404.html talks about a high-level function called getlist() that should be useful. It should return a list --- even a list of one element --- so that your processing of that data should be uniform. Hope this helps! From alex at alexnewby.com Fri Apr 2 01:28:03 2004 From: alex at alexnewby.com (Alex Newby) Date: Fri Apr 2 01:28:08 2004 Subject: [Tutor] Simple profile of cx_Freeze and py2exe Message-ID: <1080887283.22534.183766702@webmail.messagingengine.com> Given the discussion on converting Py to Exe, I tried both cx_Freeze and py2exe. I created a simple, print "hello world" raw_input() and, applied both utilities. Gordon MacMillan's site appears to be off-line, so his installer is excluded. 1. cx_Freeze ~ 3 files python23.dll _sre.pyd hello.exe 207kb --------------- dist is 1.18mb memory usage is 3,160K 2. py2exe ~ 5 files python23.dll _sre.pyd w9xpopen hello.exe 20kb library.zip 204kb ----------------- dist is 1.21mb memory usage is 2,948K cx_Freeze seems tidier and easier to initially use (no setup.py) than py2exe. Perhaps, py2exe has other advantages that I'm not aware of. I'm curious why cx_Freeze receives relatively little press. Before it was discussed here I was completely unaware of its existence. Alex Newby From glingl at aon.at Fri Apr 2 03:38:18 2004 From: glingl at aon.at (Gregor Lingl) Date: Fri Apr 2 03:37:29 2004 Subject: [Tutor] first steps (variable, assignment) In-Reply-To: References: <200403280825.i2S8Pb80000854@violet.noc.ucla.edu> Message-ID: <406D267A.1060404@aon.at> Karl Pfl?sterer schrieb: >>Here is another example of variable usage: >> >> >>a = 1 >>print a >>a = a + 1 >> >> >[...] > >You uses the right words. If you assign a value you have a left hand >side (lhs) and a right hand side (rhs). First the interpreter evaluates >the rhs and after that it assigns the returned value to the lhs. > >So if you write > a = a + 1 > ^ ^ > | | > lhs rhs > >the interprter first evaluates a+1, stores that value somewhere and >assigns then a to that value. From now on the old value of a is >forgotten. > > > Hi Karl! As assignment is a very important topic, I'd like to comment your explanation. It uses the word "assign to" in two different ways, which reflect two different views at assignment. The first one is the traditional one, a value is assigned to a "variable" (or a "variable name"). In my experience it is the by far more popular way to look at "assignment" in many tutorials, programming courses, cs-intro-books... In the second part of your explanation you say that a - the variable name - is assigned to the object just constructed and stored somewhere. That's the other way round. When programming with Python, I think, this is the by far more useful (and correct) view on the assignment statement. Simply think on Python producing (constructing) things (objects (e. g. numbers, strings, lists, trutles, httpservers etc. ...)) and if you want to use them (more than once) you have to name them. a = 1 # object 1 (an int) gets name a b = a # object named a gets a second name b a = a + 1 # new object a+1 is constructed and gets the name a So now name a is used for a different thing, but in this example object 1 ("the old value") is not forgotten as its second name b remains assigned to it. imho this view at the assignment statement in conjunction with the notion of mutable/immutable objects (not explained here) easily opens the whole universe of Python programming. Regards, Gregor P. S.: For my part, I'd like to consider the concept of "variable" as deprecated and to replace it entirely by the concepts "name" and "object". From Jan.Wilhelmsen at bilia.no Fri Apr 2 03:35:20 2004 From: Jan.Wilhelmsen at bilia.no (Wilhelmsen Jan) Date: Fri Apr 2 03:43:43 2004 Subject: [Tutor] Tuple! Message-ID: <9DB3344EC407D311A0A500508B0963E402AF0EBB@bilia.net> Hi! I have a tuple which is created from group membership of a user in active directory, the values becomes unicode strings. I need to do the following: Encode the values. Delete all the values that don't match with a certain search string, and when a match occurs I need to replace the value with a number. Then finally I need to write this value in a text file. If anyone could help me with some tips it would be great. The tuple might look like this: (u'CN=NO GG PRO Intranet,OU=Common Groups,OU=Groups,OU=NO,DC=xxxx,DC=yyy', u'CN=NO GG NO Users,OU=Common Groups,OU=Groups,OU=NO,DC=xxxx,DC=yyy', u'CN=SE GG APP TACDIS OST,OU=SE Application groups,OU=Groups,OU=SE,DC=xxxx,DC=yyy', u'CN=NO GG APP KundMarknad Admin,OU=Application Groups,OU=Groups,OU=NO,DC=xxxx,DC=yyy', u'CN=NO GG APP CarWebII,OU=Application Groups,OU=Groups,OU=NO,DC=xxxx,DC=yyy', u'CN=SE APPS VCOM OST,OU=SE Application groups,OU=Groups,OU=SE,DC=xxxx,DC=yyy', u'CN=NO COM Local Logon script,OU=Common Groups,OU=Groups,OU=NO,DC=xxxx,DC=yyy', u'CN=NO GG SYS Admin,OU=Admin Groups,OU=Groups,OU=NO,DC=xxxx,DC=yyy', u'CN=NO USG HQ IT,OU=User Groups (Organisation),OU=Groups,OU=NO,DC=xxxx,DC=yyy', u'CN=NO USG HQ Salg,OU=User Groups (Organisation),OU=Groups,OU=NO,DC=xxxx,DC=yyy', u'CN=NO USG \xd8kern Administrasjon,OU=User Groups (Organisation),OU=Groups,OU=NO,DC=xxxx,DC=yyy', u'CN=NO GG APP KundMarknad,OU=Application Groups,OU=Groups,OU=NO,DC=xxxx,DC=yyy', u'CN=NO APP Outlook Users,OU=Application Groups,OU=Groups,OU=NO,DC=xxxx,DC=yyy', u'CN=NO GG CTX Admin,OU=Admin Groups,OU=Groups,OU=NO,DC=xxxx,DC=yyy') Thanks in advanced Med vennlig hilsen / Best regards Jan Wilhelmsen IT-Technician -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040402/2e44ecd1/attachment-0001.html From nick at javacat.f2s.com Fri Apr 2 04:28:07 2004 From: nick at javacat.f2s.com (Nick Lunt) Date: Fri Apr 2 04:27:14 2004 Subject: [Tutor] Off Topic: Revision control system In-Reply-To: References: Message-ID: <1080898087.1140.3.camel@localhost.localdomain> Many thanks for all your responses. Magnus, I replied to this a couple of days ago but I did it through my webmail so Im not sure if it went to you directly (and accidentally) or got lost in cyberspace. Anyway, I followed your instructions as detailed below and Im now using RCS for all my python stuff, and I'll probably start using it for my unix scripts soon too. Thankyou for taking the time to post your RCS tutorial, it's covered all I need to know to use RCS to my advantage. Thanks again, Nick. On Tue, 2004-03-30 at 23:36, Magnus Lycka wrote: > > Now my question is, do you folks use any sort of revision control system > > on linux ? I've had a look at CVS and RCS but both seem a bit over the > > top for my needs. > > It's really a good habit to use a revision control system > for all files we change, whether they are python files, > html files or system configuration files. It's not a > substitute for backups of course, but for most human > mistakes with files it's a much better solution... > > RCS is the simplest solution, and for a few files and a > single user it's good enough. It's not difficult to use. > > Just go to http://www.hmug.org/man/1/rcsintro.html > and read about getting started. > > First of all, make a subdirectory called RCS in the > directory where you keep the files you want to version. > If you are a Linux user I assume you aren't afraid of > command lines. (It's hopeless how many Windows users > shy away from command line prompts these days...) > > $ mkdir RCS > > The normal procedure will then be just to run > > $ ci -l my_file.py > > when you have a file version that you want to preserve. > This means: Check in my_file.py into the RCS repository, > but keep it locked by me so I can continue editing it. > > If you look inside the RCS subdirectory, you will see that > there is a my_file.py,v which will contain the latest > checked in version as well as all diffs needed to revert > back to the first version you checked in. > > If you see that you mess things up and want to revert to the > last checked in version, you can overwrite it with the last > checked in version (-f means force, by default RCS won't > want to overwrite your working file): > > $ co -l -f my_file.py > > If it's an older revision you need to check out, just use > the -r flag to co to specify which version you need. > > You can use rlog to list what versions there are of a > file... > > $ rlog my_file.py > > ...and rcsdiff to see how they differ: > > $ rcsdiff my_file.py > > That will compare the current file with the latest > version checked into RCS and show you the difference. > > $ rcsdiff -r 1.2 my_file.py > > will compare revision 1.2 of my_file.py with the current > version. > > $ rcsdiff -r 1.2 -r 1.4 my_file.py > > will compare revisions 1.2 and 1.4 with each other. > > If you want to look at an older revision without > messing with the current version, just check out with > the -p flag, to get it into a pipe. You can pipe that > to a pager or redirect to another file name. > > $ co -p -r 1.3 my_file.py | less > > This might be all you ever need to know about RCS. Not > too bad, is it? > > If your ambition grows, and you eventually want a bigger > system, I agree that you should have a look at Subversion. > > Even little RCS has many more features, but you don't > need to worry about them until you feel that you need > them. As long as you are a single developer and don't > have to trace what versions of your software a number > of different customers are running, you might get away > with knowing no more about it than I wrote here. > > Oh, one more thing. It might be useful to put a comment > like this... > > # $ID$ > > or > > # $Log$ > > ...in the Python files you check in. Then you get revision > info in the copies of the files that you check out. > > Have fun! From nick at javacat.f2s.com Fri Apr 2 04:31:27 2004 From: nick at javacat.f2s.com (Nick Lunt) Date: Fri Apr 2 04:30:30 2004 Subject: [Tutor] Off Topic: Revision control system In-Reply-To: <179868462943.20040401194705@columbus.rr.com> References: <1080673704.951.6.camel@localhost.localdomain> <20040330212020.GA28045@mubai.sakeos.net> <179868462943.20040401194705@columbus.rr.com> Message-ID: <1080898286.1155.1.camel@localhost.localdomain> Never used VMS, but our company has just bought an OpenVME box. Im already having nightmares about it ... ;) Also, doesn't vi create a filename.py~ when a file is edited ? I've not looked into it but maybe that can be extended to filename.py~~, filename.py~~~ (ha) etc. Cheers Nick. On Fri, 2004-04-02 at 01:47, R. Alan Monroe wrote: > >> vi testfile.py > >> ./testfile.py > >> cp testfile.py testfile2.py > >> vi testfile2.py > >> ./testfile2.py > >> cp testfile2.py testfile3.py > >> vi testfile3.py > >> etc > >> > >> I keep copying so I don't destroy something that works. > >> > >> Now my question is, do you folks use any sort of revision control system > >> on linux ? I've had a look at CVS and RCS but both seem a bit over the > >> top for my needs. > > Makes you wish for the good old VMS way of life. For those that > haven't used it, when you save with the same filename, the filesystem > automatically makes file.py;1, file.py;2, etc. You could set the > number of versions to keep (I think) per directory. > > Alan > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From work at infomaniak.ch Fri Apr 2 08:19:42 2004 From: work at infomaniak.ch (BRINER Cedric) Date: Fri Apr 2 08:19:51 2004 Subject: [Tutor] create dict from 2 lists Message-ID: <406D686E.7070707@infomaniak.ch> hi, assume that I want to create the dict: p={1:11,2:22,3:33,4:44} and that i have: the keys=[1,2,3,4] and the values=[11,22,33,44] Is the simpliest way to do this, is to do : p={} for i in range(len(keys)): p[keys[i]]=values[i] or is there a hidded function which do this? C?dric BRINER From glingl at aon.at Fri Apr 2 08:38:31 2004 From: glingl at aon.at (Gregor Lingl) Date: Fri Apr 2 08:37:40 2004 Subject: [Tutor] create dict from 2 lists In-Reply-To: <406D686E.7070707@infomaniak.ch> References: <406D686E.7070707@infomaniak.ch> Message-ID: <406D6CD7.5050703@aon.at> BRINER Cedric schrieb: > hi, > > assume that I want to create the dict: > p={1:11,2:22,3:33,4:44} > > and that i have: > the keys=[1,2,3,4] and > the values=[11,22,33,44] > > Is the simpliest way to do this, is to do : > p={} > for i in range(len(keys)): > p[keys[i]]=values[i] > > or is there a hidded function which do this? > You could use the non-hidden function zip: (See: Python Library Reference 2.1) >>> keys=[1,2,3,4] >>> values=[11,22,33,44] >>> p={} >>> for key,value in zip(keys,values): p[key]=value >>> p {1: 11, 2: 22, 3: 33, 4: 44} Regards, Gregor > C?dric BRINER > From pythonTutor at venix.com Fri Apr 2 08:51:00 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Fri Apr 2 08:53:20 2004 Subject: [Tutor] checking variable types In-Reply-To: <5.1.0.14.1.20040322160047.00ac67d0@mailserv.esrf.fr> References: <5.1.0.14.1.20040322160047.00ac67d0@mailserv.esrf.fr> Message-ID: <1080913860.11428.2.camel@laptop.venix.com> If you are using the cgi module and its FieldStorage class, the getlist method will ALWAYS return a list, even for a single selection. I do not remember which version of Python added that method, but if you are using the current version of Python, I think that is the best way to manage. getfirst is the method to use if you NEVER want a list. It discards the extra choices. On Mon, 2004-03-22 at 10:03, Marie Robichon wrote: > Hi, > > I have a mutliple select box in html which (unfortunately) returns a list > if someone makes a multiple selection but returns a string if someone > selects one item only. > > How in my python script do I test whether it is a list or a string before I > do my processing ? > > Thanks in advance from a newbie, > > Marie > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From Chad.Crabtree at nationalcity.com Fri Apr 2 09:23:39 2004 From: Chad.Crabtree at nationalcity.com (Crabtree, Chad) Date: Fri Apr 2 09:24:04 2004 Subject: [Tutor] list method sort() Message-ID: <66F587DFDD46D511B65200508B6F8DD60EF88ED2@nt-kalopsapp07.ntl-city.com> Am I correct in my belief that sort() on lists is in place with no return value? If so does any one know WHY? WHY WHY? It doesn't make sense everything else returns a value istead of having crazy side affects for no dicernable reason. The only other one like this that I know of is 'del' which I've read is not technicly a function. ------------------------------------------------------------------------------------------- ***National City made the following annotations ------------------------------------------------------------------------------------------- This communication is a confidential and proprietary business communication. It is intended solely for the use of the designated recipient(s). If this communication is received in error, please contact the sender and delete this communication. =========================================================================================== From johnp at HomeLumber.com Fri Apr 2 09:52:05 2004 From: johnp at HomeLumber.com (John Purser) Date: Fri Apr 2 09:52:14 2004 Subject: [Tutor] list method sort() Message-ID: Because Guido, like all Dutchmen, is an evil genius hell bent on the destruction of all that's good, pure, and decent in the world! Oh well, whatcha gonna do? John Purser -----Original Message----- From: Crabtree, Chad [mailto:Chad.Crabtree@nationalcity.com] Sent: Friday, April 02, 2004 7:24 AM To: 'tutor@python.org' Subject: [Tutor] list method sort() Am I correct in my belief that sort() on lists is in place with no return value? If so does any one know WHY? WHY WHY? It doesn't make sense everything else returns a value istead of having crazy side affects for no dicernable reason. The only other one like this that I know of is 'del' which I've read is not technicly a function. ------------------------------------------------------------------------------------------- ***National City made the following annotations ------------------------------------------------------------------------------------------- This communication is a confidential and proprietary business communication. It is intended solely for the use of the designated recipient(s). If this communication is received in error, please contact the sender and delete this communication. =========================================================================================== _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From sigurd at 12move.de Fri Apr 2 10:47:25 2004 From: sigurd at 12move.de (=?iso-8859-1?q?Karl_Pfl=E4sterer?=) Date: Fri Apr 2 10:53:12 2004 Subject: [Tutor] Tuple! In-Reply-To: <9DB3344EC407D311A0A500508B0963E402AF0EBB@bilia.net> (Wilhelmsen Jan's message of "Fri, 2 Apr 2004 10:35:20 +0200") References: <9DB3344EC407D311A0A500508B0963E402AF0EBB@bilia.net> Message-ID: On 2 Apr 2004, Wilhelmsen Jan <- Jan.Wilhelmsen@bilia.no wrote: > I have a tuple which is created from group membership of a user in active > directory, the values becomes unicode strings. I need to do the following: > Encode the values. That's clear and easy. > Delete all the values that don't match with a certain search string, and > when a match occurs I need to replace the value with a number. That's not clear (at least to me). Do you want a regeexp search or a simple substring match? If a match occurs should the whole string get replaced by a number or only the part which matched? Is that number a constant? > If anyone could help me with some tips it would be great. That would be a lot easier if you provided more information. The task itself seems pretty straightforward; iterate over the tuple, encode the strings to a encoding you like and test if a match occurs. Karl -- Please do *not* send copies of replies to me. I read the list From sigurd at 12move.de Fri Apr 2 10:50:37 2004 From: sigurd at 12move.de (=?iso-8859-1?q?Karl_Pfl=E4sterer?=) Date: Fri Apr 2 10:53:29 2004 Subject: [Tutor] create dict from 2 lists In-Reply-To: <406D6CD7.5050703@aon.at> (Gregor Lingl's message of "Fri, 02 Apr 2004 15:38:31 +0200") References: <406D686E.7070707@infomaniak.ch> <406D6CD7.5050703@aon.at> Message-ID: On 2 Apr 2004, Gregor Lingl <- glingl@aon.at wrote: > BRINER Cedric schrieb: >> Is the simpliest way to do this, is to do : >> p={} >> for i in range(len(keys)): >> p[keys[i]]=values[i] >> or is there a hidded function which do this? > You could use the non-hidden function zip: > (See: Python Library Reference 2.1) > >>> keys=[1,2,3,4] > >>> values=[11,22,33,44] > >>> p={} > >>> for key,value in zip(keys,values): > p[key]=value > >>> p > {1: 11, 2: 22, 3: 33, 4: 44} > Regards, Gregor You don't even need a loop for that. >>> keys=[1,2,3,4] >>> values=[11,22,33,44] >>> dict(zip(keys, values)) {1: 11, 2: 22, 3: 33, 4: 44} Karl -- Please do *not* send copies of replies to me. I read the list From tim.one at comcast.net Fri Apr 2 10:57:26 2004 From: tim.one at comcast.net (Tim Peters) Date: Fri Apr 2 10:57:30 2004 Subject: [Tutor] create dict from 2 lists In-Reply-To: <406D6CD7.5050703@aon.at> Message-ID: [Cedric BRINER]: >> assume that I want to create the dict: >> p={1:11,2:22,3:33,4:44} >> >> and that i have: >> the keys=[1,2,3,4] and >> the values=[11,22,33,44] >> >> Is the simpliest way to do this, is to do : >> p={} >> for i in range(len(keys)): >> p[keys[i]]=values[i] >> >> or is there a hidded function which do this? [Gregor Lindl] > You could use the non-hidden function zip: > (See: Python Library Reference 2.1) > > >>> keys=[1,2,3,4] > >>> values=[11,22,33,44] > >>> p={} > >>> for key,value in zip(keys,values): > p[key]=value > > >>> p > {1: 11, 2: 22, 3: 33, 4: 44} Or print dict.__doc__, and ponder this section: dict(seq) -> new dictionary initialized as if via: d = {} for k, v in seq: d[k] = v So this also works: >>> keys = [1, 2, 3, 4] >>> values = [11, 22, 33, 44] >>> dict(zip(keys, values)) {1: 11, 2: 22, 3: 33, 4: 44} >>> From project5 at redrival.net Fri Apr 2 11:14:40 2004 From: project5 at redrival.net (Andrei) Date: Fri Apr 2 11:14:55 2004 Subject: [Tutor] Re: create dict from 2 lists References: <406D686E.7070707@infomaniak.ch> <406D6CD7.5050703@aon.at> Message-ID: <1hnqm0hy7hqjd$.m6fju1e63gdc$.dlg@40tude.net> Gregor Lingl wrote on Fri, 02 Apr 2004 15:38:31 +0200: > BRINER Cedric schrieb: > >> assume that I want to create the dict: >> p={1:11,2:22,3:33,4:44} >> >> and that i have: >> the keys=[1,2,3,4] and >> the values=[11,22,33,44] >> > >>> p={} > >>> for key,value in zip(keys,values): > p[key]=value > Or, even shorter: >>> dict(zip(keys, values)) {1: 11, 2: 22, 3: 33, 4: 44} -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From orbitz at ezabel.com Fri Apr 2 12:07:49 2004 From: orbitz at ezabel.com (orbitz@ezabel.com) Date: Fri Apr 2 12:08:13 2004 Subject: [Tutor] list method sort() In-Reply-To: <66F587DFDD46D511B65200508B6F8DD60EF88ED2@nt-kalopsapp07.ntl-city.com> References: <66F587DFDD46D511B65200508B6F8DD60EF88ED2@nt-kalopsapp07.ntl-city.com> Message-ID: <20040402120749.64ed5c12.orbitz@ezabel.com> Most of the list methods don't return the list. sort, reverse, append, extend, insert, remove. I dont' know *why*, perhaps it is to re-enforce that it is inplace. On Fri, 2 Apr 2004 09:23:39 -0500 "Crabtree, Chad" wrote: > Am I correct in my belief that sort() on lists is in place with no return > value? If so does any one know WHY? WHY WHY? It doesn't make sense > everything else returns a value istead of having crazy side affects for no > dicernable reason. The only other one like this that I know of is 'del' > which I've read is not technicly a function. > > ----------------------------------------------------------------------------- > --------------***National City made the following annotations > ----------------------------------------------------------------------------- > -------------- > > This communication is a confidential and proprietary business communication. > It is intended solely for the use of the designated recipient(s). If this > communication is received in error, please contact the sender and delete this > communication. > ============================================================================= > ============== > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From dbroadwell at mindspring.com Fri Apr 2 12:29:01 2004 From: dbroadwell at mindspring.com (David Broadwell) Date: Fri Apr 2 12:24:10 2004 Subject: [Tutor] list method sort() In-Reply-To: <20040402120749.64ed5c12.orbitz@ezabel.com> Message-ID: > Most of the list methods don't return the list. sort, reverse, > append, extend, insert, remove. I don't' know *why*, perhaps > it is to re-enforce that it is in place. Makes the list feel stackish ... which may be where Guido extended the list from. -- David Broadwell From project5 at redrival.net Fri Apr 2 12:46:31 2004 From: project5 at redrival.net (Andrei) Date: Fri Apr 2 12:46:38 2004 Subject: [Tutor] Re: list method sort() References: <66F587DFDD46D511B65200508B6F8DD60EF88ED2@nt-kalopsapp07.ntl-city.com> Message-ID: Crabtree, Chad wrote on Fri, 2 Apr 2004 09:23:39 -0500: > Am I correct in my belief that sort() on lists is in place with no return > value? If so does any one know WHY? WHY WHY? It doesn't make sense Yep, but I'm not sure why. Orbitz might have a point, in that it might be mainly for stylistic reasons, i.e. to emphasize that the list is modified in-place. Think of this: what would you have liked sort() to return? - the list itself? If you did: >>> myotherlist = mylist.sort() >>> myotherlist.append(5) wouldn't you be surprised to find that 5 was appended to mylist as well? - a copy of the list? This would become way too expensive in most cases, because when you sort a list, you generally want that list itself sorted, you don't want a sorted copy of the list. - a deepcopy of the list? This is even more expensive than a shallow copy. > everything else returns a value istead of having crazy side affects for no Keep in mind that most of 'everything else' (e.g. tuples, strings, booleans, integers) can simply not be changed in-place (unlike lists). This means that any operations on these types either returns a value, or nothing happens since these types can't be changed in-place. > dicernable reason. The only other one like this that I know of is 'del' Oh, I'll bet you know more, you just didn't think of them on the spot :). Operations on mutable types tend to NOT return anything. E.g. look at a dictionary: >>> d = {} >>> d.__setitem__(1,2) # modifies d in-place, doesn't return anything >>> d # demonstrate that d was modified: {1: 2} Or the list: >>> mylist = [] >>> mylist.append(4) # no return value, modifies in-place >>> mylist [4] It would be weird to have mylist.append() return the list, wouldn't it? It would seem weird to me anyway. Yet append() is not any different from sort(), so having one return something and the other not, would be very confusing and unpredictable. > which I've read is not technicly a function. It's a statement (like e.g. print, global or pass). Obviously it has no return value (neither does print for examle). -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From project5 at redrival.net Fri Apr 2 12:50:35 2004 From: project5 at redrival.net (Andrei) Date: Fri Apr 2 13:01:20 2004 Subject: [Tutor] Re: list method sort() References: <66F587DFDD46D511B65200508B6F8DD60EF88ED2@nt-kalopsapp07.ntl-city.com> Message-ID: <1i25m7wj8y9np$.hgc66xaodrzk.dlg@40tude.net> Crabtree, Chad wrote on Fri, 2 Apr 2004 09:23:39 -0500: > Am I correct in my belief that sort() on lists is in place with no return > value? If so does any one know WHY? WHY WHY? It doesn't make sense Forgot to mention that you could implement your own list class which does return something at the end of the sort() method if you really need it. Wouldn't even be that hard. -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From sigurd at 12move.de Fri Apr 2 14:03:35 2004 From: sigurd at 12move.de (=?iso-8859-1?q?Karl_Pfl=E4sterer?=) Date: Fri Apr 2 14:07:50 2004 Subject: [Tutor] Re: list method sort() In-Reply-To: (Andrei's message of "Fri, 2 Apr 2004 19:46:31 +0200") References: <66F587DFDD46D511B65200508B6F8DD60EF88ED2@nt-kalopsapp07.ntl-city.com> Message-ID: On 2 Apr 2004, Andrei <- project5@redrival.net wrote: > Crabtree, Chad wrote on Fri, 2 Apr 2004 09:23:39 -0500: >> Am I correct in my belief that sort() on lists is in place with no return >> value? If so does any one know WHY? WHY WHY? It doesn't make sense > Yep, but I'm not sure why. Orbitz might have a point, in that it might be > mainly for stylistic reasons, i.e. to emphasize that the list is modified > in-place. Think of this: what would you have liked sort() to return? The sorted list. > - the list itself? If you did: > >>> myotherlist = mylist.sort() > >>> myotherlist.append(5) > wouldn't you be surprised to find that 5 was appended to mylist as well? No. Since I know that append() and sort() are destructive functions. If I wanted a copy of the sorted list I would write: lst2 = lst.sort()[:] > - a copy of the list? This would become way too expensive in most cases, If I need a copy I say it explicitly. see above > because when you sort a list, you generally want that list itself sorted, > you don't want a sorted copy of the list. ACK. But that's no reason to ot return the sorted list. [...] >> everything else returns a value istead of having crazy side affects for no [...] > Oh, I'll bet you know more, you just didn't think of them on the spot :). > Operations on mutable types tend to NOT return anything. E.g. look at a > dictionary: >>>> d = {} >>>> d.__setitem__(1,2) # modifies d in-place, doesn't return anything >>>> d # demonstrate that d was modified: > {1: 2} Sometimes you which d got returned. > Or the list: >>>> mylist = [] >>>> mylist.append(4) # no return value, modifies in-place >>>> mylist > [4] > It would be weird to have mylist.append() return the list, wouldn't it? It Absolutely not. It seems to me you don't know Lisp where either append (non-destructively) or nconc (a destructively append) return the modified list. Especially sort() would make sense to return a value. Imagine a list comprehension; now you have to write to use a sorted result res = [x for x in something if x < something_else] res.sort() for y in res: ... but wouldn't it be nice to write: for y in [x for x in something if x < something_else].sort(): IMO yes. You can write your sort function which takes a list, calls its sort method and returns the sorted list, like: def nsort (lst, *args): lst.sort(*args) return lst But it would be nicer as a builtin. > would seem weird to me anyway. Yet append() is not any different from > sort(), so having one return something and the other not, would be very > confusing and unpredictable. ACK. Therefore both should return the altered list. Karl -- Please do *not* send copies of replies to me. I read the list From Doug.Shawhan at ge.com Fri Apr 2 14:16:40 2004 From: Doug.Shawhan at ge.com (Shawhan, Doug (EM, ITS)) Date: Fri Apr 2 14:17:01 2004 Subject: [Tutor] Critique and a big thanks! Message-ID: Tutors, We are having trouble with failed hard drives on a series of newly deployed computers at the plant I work at. There are ~ 300 of these and ~10% have had failed drive so far! I have been working on a python script to back up the important outlook email database files on these machines. The script grew from a simple copy thang to this threaded beast that works way better than I ever thought it would! Thank you all so much for your help and suggestions for reading material! My final question: What would you folks suggest to make this script more simple and easier to read? (...and if you see any horrible coding blemishes, I would like to know too!). Thanks again everyone! This list is one of the best things about python! d ------------------------------script-------------------------------------------------- '''MailMover.py Copies *.pst and *.pab files from remote hosts to backup on remote hosts to the \\Server\shared\company\MailBackup directory. Gets list of hosts to back up from the hosts.csv file in \tmp\MailMover. Our bunch has standardized on having mail folders in My Documents\EXCHANGE\, your group will probably do something different - edit accordingly! Usage: "python mailmover.py" Caveats: one must have superuser privileges (domain opers) on the remote machines to connect and copy /-Y files. There is, as yet, _no_ error reporting. ''' import glob import string import os import time from threading import Thread #static info destination_directory="\\\\Server\\shared\company\\MailBackup" host_list="c:\\tmp\\MailMover\\hosts.csv" MAX_THREADS=10 #create list for thread pool. gathers=[] #open the .csv file and strip out the linefeeds hostguffer=open(host_list,"r") hostholder=hostguffer.readlines() hosts=[] for host in hostholder: hosts.append(host[:-1]) class gather(Thread): def __init__(self, users, host, destination_directory): Thread.__init__(self) self.host=host self.users=users self.destination_directory=destination_directory def run(self): print "thread started" for user in self.users: #strip extraneous pathname info from username. #Assumes all hostnames are the same length username=user[21:] collection_path="%s\\MYDOCU~1\\Exchange\\"%user mailbox_list=[] mailboxes=glob.glob("%s*.pst"%collection_path) if mailboxes !=[]: #create pathname on storage host! storage_path="%s\\%s\\%s\\"%(self.destination_directory,self.host, username) os.system("mkdir %s"%storage_path) os.system("copy /Y %s*.pst %s"%(collection_path, storage_path)) #we'll just copy the addressbooks too, for smarts os.system("copy /Y %s*.pab %s"%(collection_path, storage_path)) def count_active(): #returns the number of living threads num_active = 0 for g in gathers: if g.isAlive(): num_active += 1 print "%d alive" % num_active return num_active for host in hosts: users=glob.glob("\\\\%s\\d$\\users\\*"%host)# collect the users on the host while count_active() >= MAX_THREADS: print "too many active" time.sleep(1) go=gather(users, host, destination_directory) gathers.append(go) go.start() From kbond at free.fr Fri Apr 2 14:33:22 2004 From: kbond at free.fr (kbond) Date: Fri Apr 2 14:33:35 2004 Subject: [Tutor] Practical Question Message-ID: <406DC002.9030808@free.fr> Hello, Yesterday I sent to this list a message with a zip attach to it (59 Ko) with an application in it but for some reason I cannot see the message on the list. I guess It was moderate because of the attachment. I am trying again without the zip if people are interested by the source code please do not hesitate to request it. Thank you for your help. Here it is a copy of my previous mail: Hello, I am quite new to python and I have complete my first useful application. I am not really sure that I am sending to right list if this is a mistake I am sorry. This tiny application is using wxpython, win32com, py2exe and of course python. This is exactly my problem I am sure there is something wrong in design of this application but I cannot tell what. The objective of this application is to glue together several PowerPoint files and to add a Table of content which is really painful to build for a powerpoint containing several hundreds of slides It is really important to be able to either launch it from a cmd prompt or to use it through a GUI. You will find below the point I want to improve of course if there is more please do not hesitate: - How to call pptGlue.py from the user interface till now I am doing it using os.popen2 as below: os.popen2("pptGlue.exe " + " ".join(commandLine) +" -n" + mergedPptFile) There is several problems with this way of doing: The first one I need to write the exact name of the program, the extension is important. I mean the code can only work before I launch py2exe, if it is pptGlue.py, or after if it is pptGlue.exe. I would like to have some thing more generic. - Another problem with this call is that I didn't not find out a way to display the error message in a dialog box if there is some errors neither to send a dialog box if everything went fine. - The function that is building the TOC is not working if there is a "..." a title of a slide composing the TOC. It is because "..." seems to be propriatary char in MS powerpoint and I cannot print it using the python "print" command. This is also important for me because in some cases I am just building the TOC in a command prompt to send the result to a text file. Thank you for your help if this application can be useful to some of you I would be more than happy. From project5 at redrival.net Fri Apr 2 15:08:37 2004 From: project5 at redrival.net (Andrei) Date: Fri Apr 2 15:08:47 2004 Subject: [Tutor] Re: Re: list method sort() References: <66F587DFDD46D511B65200508B6F8DD60EF88ED2@nt-kalopsapp07.ntl-city.com> Message-ID: <15oj4aqpb734y$.7sc76wkfaxr4$.dlg@40tude.net> Karl Pfl?sterer wrote on Fri, 02 Apr 2004 21:03:35 +0200: > No. Since I know that append() and sort() are destructive functions. > If I wanted a copy of the sorted list I would write: Well, yes, you can argue that *all* operations which modify in-place should return the modified object as well - I don't know if this would be better or not: I certainly see the advantages in some cases. My post was referring to inconsistent behavior (some operations returning, other ones not). >> It would be weird to have mylist.append() return the list, wouldn't it? It > > Absolutely not. It seems to me you don't know Lisp where either append > (non-destructively) or nconc (a destructively append) return the > modified list. No, I haven't found Lisp attractive enough to study it. Can't say I've missed the feature in Python, though I have occasionally wished sort() did return the list. But I'd rather have consistent behavior than special sorts of behavior. > Especially sort() would make sense to return a value. Imagine a list > comprehension; now you have to write to use a sorted result > > res = [x for x in something if x < something_else] > res.sort() > for y in res: ... > > but wouldn't it be nice to write: > > for y in [x for x in something if x < something_else].sort(): > > IMO yes. IMO in this particular case not, simply because the first option is clearer than the second one. I would however be tempted to write: for y in res.sort(): > You can write your sort function which takes a list, calls its sort > method and returns the sorted list, like: Sounds like a good idea to me :). >> would seem weird to me anyway. Yet append() is not any different from >> sort(), so having one return something and the other not, would be very >> confusing and unpredictable. > > ACK. Therefore both should return the altered list. So how would you handle the pop-like methods then? They're destructive, they *must* return the item which was popped, but they should also return the modified list/dict (for the sake of consistency). -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From tim.one at comcast.net Fri Apr 2 15:28:23 2004 From: tim.one at comcast.net (Tim Peters) Date: Fri Apr 2 15:28:28 2004 Subject: [Tutor] Re: Re: list method sort() In-Reply-To: <15oj4aqpb734y$.7sc76wkfaxr4$.dlg@40tude.net> Message-ID: [Andrei] > Well, yes, you can argue that *all* operations which modify in-place > should return the modified object as well - I don't know if this > would be better or not: ... Life would be hell in interactive Python shells if these things *didn't* return None: >>> somelist.sort() Oops! Nobody wants to sit and wait for an arbitrary amount of output then. Very early versions of Python *also* displayed the result of non-None expressions when running from .py files too, and then the only way to suppress mountains of unwanted output would have been to do something like: dummy = somelist.sort() Against my better judgment, Python 2.4 is adding a sorted() function to the builtins, to stop people whining about this particular case. That's against my wishes because bloating the builtins with functions that are trivially written in one or two lines bloats the builtins with functions that are trivially written in one or two lines . From pythonTutor at venix.com Fri Apr 2 15:29:34 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Fri Apr 2 15:31:59 2004 Subject: [Tutor] create dict from 2 lists In-Reply-To: <406D6CD7.5050703@aon.at> References: <406D686E.7070707@infomaniak.ch> <406D6CD7.5050703@aon.at> Message-ID: <1080937773.11428.14.camel@laptop.venix.com> You can take that one step further. p = dict(zip(keys,values)) dict will construct a dictionary from a list of pairs. On Fri, 2004-04-02 at 08:38, Gregor Lingl wrote: > BRINER Cedric schrieb: > > > hi, > > > > assume that I want to create the dict: > > p={1:11,2:22,3:33,4:44} > > > > and that i have: > > the keys=[1,2,3,4] and > > the values=[11,22,33,44] > > > > Is the simpliest way to do this, is to do : > > p={} > > for i in range(len(keys)): > > p[keys[i]]=values[i] > > > > or is there a hidded function which do this? > > > You could use the non-hidden function zip: > (See: Python Library Reference 2.1) > > >>> keys=[1,2,3,4] > >>> values=[11,22,33,44] > >>> p={} > >>> for key,value in zip(keys,values): > p[key]=value > > >>> p > {1: 11, 2: 22, 3: 33, 4: 44} > > Regards, Gregor > > > > C?dric BRINER > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From project5 at redrival.net Fri Apr 2 15:57:45 2004 From: project5 at redrival.net (Andrei) Date: Fri Apr 2 15:57:52 2004 Subject: [Tutor] Re: Critique and a big thanks! References: Message-ID: Shawhan, Doug (EM, ITS) wrote on Fri, 2 Apr 2004 14:16:40 -0500: > Tutors, > > The script grew from a simple copy thang to this threaded beast > that works way better than I ever thought it would! Thank you Perhaps 'beast' is too big a word for what amounts (in Python at least) to 60 lines of code ;). > My final question: What would you folks suggest to make this > script more simple and easier to read? For one thing, I'd get rid of tabs and use 4 spaces per indentation level. It's proper Python style, though there are of course people who prefer tabs. If you have a half-decent editor, you won't notice the difference actually, as you can keep using tabs and the editor converts your tab to 4 spaces. Real tabs look ugly in some mail clients (or they don't appear at all). E.g. mine indents tabs at 8 spaces, making your code excessively wide. Also it's good style to use spaces before and after assignment (=), e.g. "gathers = []" instead of "gathers=[]". A general note: you can use forward slashes in paths even on Windows. I haven't tried on network drives, but it works just fine on local ones. This should help you get rid of the '\\\\\\\' things. > #create list for thread pool. > gathers=[] > > #open the .csv file and strip out the linefeeds > hostguffer=open(host_list,"r") Using file() instead of open() is the modern way - more intuitive too. The result works the same. > hostholder=hostguffer.readlines() It's good practice to close files after you're finished reading from them. > hosts=[] > for host in hostholder: > hosts.append(host[:-1]) There's an alternative (shorter) way of doing this too, by looping directly over the file: hosts = [] for line in hostguffer: # don't need hostholder hosts.append(line[:-1]) or with a list comprehension (even shorter): hosts = [ line[:-1] for line in hostguffer ] > class gather(Thread): > def __init__(self, users, host, destination_directory): > Thread.__init__(self) > self.host=host > self.users=users > self.destination_directory=destination_directory I'm not a big fan of very long variable names: they're hard to type and they make lines very long. 'dest_dir' for example would be basically every bit as clear as 'destination_directory', at one third its size. > #strip extraneous pathname info from username. > #Assumes all hostnames are the same length > username=user[21:] Generally speaking it's not good to have magic numbers in the code. 21 here is a magic number and should either be a global constant, or be determined at runtime based on the location of some char in user, whichever is best for you. In you particular case it doesn't really matter, but imagine you have a similar loop in 10 places in your code and suddenly for whatever reason user names start at position 23 instead of 21. Using a magic number means you'd have to go and change all 10 places manually. If you'd used a global constant, you would only have to change a single value (that of the constant). If you'd written code to determine the position of the username at runtime, you wouldn't have to change anything. > collection_path="%s\\MYDOCU~1\\Exchange\\"%user > mailbox_list=[] You don't seem to use mailbox_list anywhere, so you should remove it. > mailboxes=glob.glob("%s*.pst"%collection_path) > if mailboxes !=[]: An empty list is automatically interpreted as False in a boolean context, while any non-empty list is interpreted as True. So you could just as well write: if mailboxes: # means "if mailboxes isn't an empty list" # do stuff The same neat shortucut is also available for other data types, e.g. username = raw_input('What is your name?\n > ').strip() # username now is a string, but it might have length 0 if username: # means the same as 'if username != "" ' # code which gets executed if a real user name was specified > #create pathname on storage host! > storage_path="%s\\%s\\%s\\"%(self.destination_directory,self.host, username) The os.path module has a nice function called join(): >>> import os.path >>> os.path.join('a', 'b', 'c') 'a\\b\\c' It looks better than the string formatting option and it's less cumbersome to modify if at some point it's necessary to add/remove a subdirectory in that path. > os.system("mkdir %s"%storage_path) Python has batteries for this task: os.mkdir() (or os.makedirs() if you want recursive directory creation). > os.system("copy /Y %s*.pst %s"%(collection_path, storage_path)) > #we'll just copy the addressbooks too, for smarts > os.system("copy /Y %s*.pab %s"%(collection_path, storage_path)) The shutil module has functions for copying files. In this case it's probably easier to use the DOS commands though, since shutil doesn't support wildcards AFAIK. But e.g. when you intend to write cross-plaform code, os.system really should be avoided :). > def count_active(): > #returns the number of living threads > num_active = 0 > for g in gathers: > if g.isAlive(): > num_active += 1 > print "%d alive" % num_active > return num_active This one-liner should work as well (though it's doubtful it's clearer than your solution): num_active = len([ g for g in gathers if g.isAlive() ]) -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From project5 at redrival.net Fri Apr 2 16:10:10 2004 From: project5 at redrival.net (Andrei) Date: Fri Apr 2 16:10:21 2004 Subject: [Tutor] Re: Re: Re: list method sort() References: <15oj4aqpb734y$.7sc76wkfaxr4$.dlg@40tude.net> Message-ID: Tim Peters wrote on Fri, 2 Apr 2004 15:28:23 -0500: > [Andrei] >> Well, yes, you can argue that *all* operations which modify in-place >> should return the modified object as well - I don't know if this >> would be better or not: ... > > Life would be hell in interactive Python shells if these things *didn't* > return None: > >>>> somelist.sort() > > Oops! Nobody wants to sit and wait for an arbitrary amount of output then. Very good point there; I should have thought of it, as I've written a little calculator-type application in Python which works similarly to the Python shell, but only evaluates expressions. I had to add special syntax and code in order to avoid exactly this kind of output. > Against my better judgment, Python 2.4 is adding a sorted() function to the > builtins, to stop people whining about this particular case. That's against Oh, I didn't know. I don't mind it, but I'm not very fond of the name as to me it sounds like it's supposed to return a boolean indicating whether that particular list is sorted or not. -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From pythonTutor at venix.com Fri Apr 2 16:17:57 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Fri Apr 2 16:20:18 2004 Subject: [Tutor] Re: Re: list method sort() In-Reply-To: <15oj4aqpb734y$.7sc76wkfaxr4$.dlg@40tude.net> References: <66F587DFDD46D511B65200508B6F8DD60EF88ED2@nt-kalopsapp07.ntl-city.com> <15oj4aqpb734y$.7sc76wkfaxr4$.dlg@40tude.net> Message-ID: <1080940676.11428.45.camel@laptop.venix.com> http://www.python.org/dev/doc/devel/whatsnew/node5.html A sorted builtin will be available in 2.4. It returns a copy of the sorted list. It's actually sorts any iterable, not just lists. On Fri, 2004-04-02 at 15:08, Andrei wrote: > Karl Pfl?sterer wrote on Fri, 02 Apr 2004 21:03:35 +0200: > > > No. Since I know that append() and sort() are destructive functions. > > If I wanted a copy of the sorted list I would write: > > > Well, yes, you can argue that *all* operations which modify in-place should > return the modified object as well - I don't know if this would be better > or not: I certainly see the advantages in some cases. My post was referring > to inconsistent behavior (some operations returning, other ones not). > > >> It would be weird to have mylist.append() return the list, wouldn't it? It > > > > Absolutely not. It seems to me you don't know Lisp where either append > > (non-destructively) or nconc (a destructively append) return the > > modified list. > > No, I haven't found Lisp attractive enough to study it. Can't say I've > missed the feature in Python, though I have occasionally wished sort() did > return the list. But I'd rather have consistent behavior than special sorts > of behavior. > > > Especially sort() would make sense to return a value. Imagine a list > > comprehension; now you have to write to use a sorted result > > > > res = [x for x in something if x < something_else] > > res.sort() > > for y in res: ... > > > > but wouldn't it be nice to write: > > > > for y in [x for x in something if x < something_else].sort(): > > > > IMO yes. > > IMO in this particular case not, simply because the first option is clearer > than the second one. I would however be tempted to write: > > for y in res.sort(): > > > You can write your sort function which takes a list, calls its sort > > method and returns the sorted list, like: > > Sounds like a good idea to me :). > > >> would seem weird to me anyway. Yet append() is not any different from > >> sort(), so having one return something and the other not, would be very > >> confusing and unpredictable. > > > > ACK. Therefore both should return the altered list. > > So how would you handle the pop-like methods then? They're destructive, > they *must* return the item which was popped, but they should also return > the modified list/dict (for the sake of consistency). -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From sigurd at 12move.de Fri Apr 2 16:22:20 2004 From: sigurd at 12move.de (=?iso-8859-1?q?Karl_Pfl=E4sterer?=) Date: Fri Apr 2 16:25:38 2004 Subject: [Tutor] Re: Re: list method sort() In-Reply-To: (Tim Peters's message of "Fri, 2 Apr 2004 15:28:23 -0500") References: Message-ID: On 2 Apr 2004, Tim Peters <- tim.one@comcast.net wrote: > [Andrei] >> Well, yes, you can argue that *all* operations which modify in-place >> should return the modified object as well - I don't know if this >> would be better or not: ... > Life would be hell in interactive Python shells if these things *didn't* > return None: >>>> somelist.sort() > Oops! Nobody wants to sit and wait for an arbitrary amount of output then. Regarding an interactive session I agree with you. [...] > Against my better judgment, Python 2.4 is adding a sorted() function to the > builtins, to stop people whining about this particular case. That's against > my wishes because bloating the builtins with functions that are trivially > written in one or two lines bloats the builtins with functions that are > trivially written in one or two lines . Here I also agree with you (the sort example can be written in three lines (and the penalty in performance should be negligible). But we also got sum, min and max. All three can simply (and clearly) be written with reduce. sort() gets new keywords IIRC; wouldn't it have be an option to simply add another keyword -- `return_value' -- which defaults to False? Karl -- Please do *not* send copies of replies to me. I read the list From vicki at stanfield.net Fri Apr 2 16:33:28 2004 From: vicki at stanfield.net (Vicki Stanfield) Date: Fri Apr 2 16:33:33 2004 Subject: [Tutor] counting space-delimited strings within a sequence Message-ID: <63477.206.53.226.235.1080941608.squirrel@www.thepenguin.org> This is probably a very simple question, but I am not sure of the best way to handle it. I am attempting to determine the number of parameters that are passed into my function. There might be none. I wrote the following: i=0 args = parameters.split(" ") for count in args: i+=1 self.numparams = i but if there are no parameters, self.numparams is still set to 1 instead of 0. I don't understand, but when I run this in idle, I get the same result. How do I split up a string of words which are space-delimited and handle the empty string as well? And yes, I'm sure that I'm just missing some fundamental Pythonism. --vicki "A pessimist sees the difficulty in every opportunity; an optimist sees the opportunity in every difficulty." -- Winston Churchill From johnp at HomeLumber.com Fri Apr 2 16:48:42 2004 From: johnp at HomeLumber.com (John Purser) Date: Fri Apr 2 16:48:47 2004 Subject: [Tutor] counting space-delimited strings within a sequence Message-ID: Well this works: >>> a = "How do you do?" >>> b = a.split() >>> n = len(b) >>> if not n: #or if n == 0 ... n = 1 -----Original Message----- From: Vicki Stanfield [mailto:vicki@stanfield.net] Sent: Friday, April 02, 2004 2:33 PM To: tutor@python.org Subject: [Tutor] counting space-delimited strings within a sequence This is probably a very simple question, but I am not sure of the best way to handle it. I am attempting to determine the number of parameters that are passed into my function. There might be none. I wrote the following: i=0 args = parameters.split(" ") for count in args: i+=1 self.numparams = i but if there are no parameters, self.numparams is still set to 1 instead of 0. I don't understand, but when I run this in idle, I get the same result. How do I split up a string of words which are space-delimited and handle the empty string as well? And yes, I'm sure that I'm just missing some fundamental Pythonism. --vicki "A pessimist sees the difficulty in every opportunity; an optimist sees the opportunity in every difficulty." -- Winston Churchill _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From project5 at redrival.net Fri Apr 2 16:50:10 2004 From: project5 at redrival.net (Andrei) Date: Fri Apr 2 16:50:22 2004 Subject: [Tutor] Re: counting space-delimited strings within a sequence References: <63477.206.53.226.235.1080941608.squirrel@www.thepenguin.org> Message-ID: <4xnacne3c0tf$.1hyuwqzn44s44$.dlg@40tude.net> Vicki Stanfield wrote on Fri, 2 Apr 2004 16:33:28 -0500 (EST): > This is probably a very simple question, but I am not sure of the best way > to handle it. I am attempting to determine the number of parameters that > are passed into my function. Wouldn't it be easier to pass real parameters instead of a string containing parameters separated by spaces? Something like this works very well if you don't know in advance how many arguments you will have: >>> def myfunc(*args): ... for arg in args: ... print arg ... >>> myfunc('a', 'b', 3) a b 3 >>> myfunc(1) 1 > There might be none. I wrote the following: > > i=0 > args = parameters.split(" ") You don't need to specify ' ' as argument for split(), because split() without arguments by default splits at whitespaces. > for count in args: > i+=1 In order to determine the length of an array, you can use the len() function, which is a lot easier than looping over an array and increasing a counter: self.numparams = len(args) By the way, this code works just fine with the "*args" trick I mentioned above. > but if there are no parameters, self.numparams is still set to 1 instead > of 0. I don't understand, but when I run this in idle, I get the same > result. How do I split up a string of words which are space-delimited and > handle the empty string as well? And yes, I'm sure that I'm just missing > some fundamental Pythonism. Leave out the parameter you pass to split: >>> ''.split(' ') [''] # 1 parameter (being an empty string) >>> ''.split() [] # no paramaters -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From dyoo at hkn.eecs.berkeley.edu Fri Apr 2 19:18:48 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Apr 2 19:18:57 2004 Subject: [Tutor] counting space-delimited strings within a sequence [split()] In-Reply-To: <63477.206.53.226.235.1080941608.squirrel@www.thepenguin.org> Message-ID: On Fri, 2 Apr 2004, Vicki Stanfield wrote: > This is probably a very simple question, but I am not sure of the best > way to handle it. I am attempting to determine the number of parameters > that are passed into my function. There might be none. I wrote the > following: > > i=0 > args = parameters.split(" ") > for count in args: > i+=1 > > self.numparams = i > > but if there are no parameters, self.numparams is still set to 1 instead > of 0. I don't understand, but when I run this in idle, I get the same > result. Hi Vicki, Can you show us a test case that exhibits this? As far as I can tell, your code snippet looks good: ### >>> def countParams(params): ... i = 0 ... args = params.split(" ") ... for arg in args: ... i = i + 1 ... return i ... >>> countParams("hello world this is a test") 6 ### So this appears to count the number of "parameters" properly. If you can show us an example that doesn't give expected results, that will help. Offhand, though, I can think of one thing that might be causing weirdness. One way to get an unexpected result is to use more than one space in the space-delimited string: ### >>> countParams("hello world") 3 ### What's happening is that the split is occuring between single spaces, and sure enough, when we split "hello world" using a single-space delimiter, we get three chunks back: ### >>> 'hello world'.split(" ") ['hello', '', 'world'] ### One solution is to use the default behavior of split(): if split() isn't given a delimiter, it'll use consecutive whitespace, so if there's a bunch of whitespace together, the default split() will eat it all: ### >>> def countParams(params): ... i = 0 ... args = params.split() ... for arg in args: ... i = i + 1 ... return i ... >>> countParams("hello world this is a test") 6 >>> countParams("hello world") 2 ### Side note: Python has a builtin called "len()" that knows how to measure the length of a list, so countParams() above can be rewritten like this: ### >>> def countParams(params): ... return len(params.split()) ... >>> countParams("hello world this is a test") 6 >>> countParams("hello world") 2 ### Nice and short. *grin* The default behavior of split() is useful because it works on all kinds of whitespace, and not just space. So we can even do things like this: ### >>> stopwords = ''' ... a ... about ... again ... aim ... all ... almost ... also ... although ... always ... among'''.split() >>> stopwords ['a', 'about', 'again', 'aim', 'all', 'almost', 'also', 'although', 'always', 'among'] ### Hope this helps! From bvande at po-box.mcgill.ca Sat Apr 3 04:27:02 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sat Apr 3 04:28:47 2004 Subject: [Tutor] puzzled by ident after list statement in IDLE Message-ID: <406E8366.80802@po-box.mcgill.ca> Hi all, I thought I was getting a handle on things, but I'm thrown by the following. I'm playing with some simple (or so I thought ;-) ) code for doing the 8 queens problem from Hetland's Practical Python. I may be giving too much detail, but since I'm confounded, I don't trust my sense of what matters. All the used code is: from __future__ import generators def conflict(state, nextX): nextY = len(state) for i in range(nextY): if abs(state[i]-nextX) in (0, nextY-i): return 1 return 0 def queens(num=8, state=()): for pos in range(num): if not conflict(state, pos): if len(state) == num-1: yield (pos,) else: for result in queens(num, state + (pos,)): yield (pos,) + result My understanding of this is that the queens function take 0-2 explicitly supplied arguments, and if two are supplied (without key words) in a tuple, the first is what num gets assigned, the second is state's assignment. State is a tuple in the code, so I thought I should be able to do >>> list(queens(5, (0, 2)) and have the function run with num = 5 and state = (0, 2) (at the beginning, at least), and then print the resulting list. But what I get is >>> list(queens(5, (0, 2)) | Where the "|" represents the flashing cursor. (If I hit enter, I drop a line, and any other input gives a syntax error.) So, save the lack of syntax colouring, it looks much like I'd entered something like: >>> def spam(): I've checked and if I assign >>> a = (0, 2) and then pass (5, a) to queens, things work fine (with respect to my current puzzlement, anyway). I've checked with the Tutorial to make sure I've understood how function defs with keyword arguments work, and as far as I can tell, I have it right. But then I can't see why I get the indented line, rather than listing the output of queens(5, (0, 2)). Python 2.3, IDLE 1.0.2 on WinMe. Sorry for being long-winded. Best, Brian vdB From Janssen at rz.uni-frankfurt.de Sat Apr 3 07:22:33 2004 From: Janssen at rz.uni-frankfurt.de (Michael Janssen) Date: Sat Apr 3 07:22:49 2004 Subject: [Tutor] puzzled by ident after list statement in IDLE In-Reply-To: <406E8366.80802@po-box.mcgill.ca> References: <406E8366.80802@po-box.mcgill.ca> Message-ID: On Sat, 3 Apr 2004, Brian van den Broek wrote: > But what I get is > >>> list(queens(5, (0, 2)) > | this is a case of "refusing correct indentation on error": you've missed a final closing bracket. That's all... The editor should give you some feedback about closing brackets so you are warned when this feedback doesn't come. Further the incorrect indentation should behave not like an indetation at all: typeing backspace refuses to do a 4 spaces jump back. I don't now what IDLE does but this is what emacs tries to help me. Michael > Where the "|" represents the flashing cursor. (If I hit enter, I > drop a line, and any other input gives a syntax error.) So, save > the lack of syntax colouring, it looks much like I'd entered > something like: From bvande at po-box.mcgill.ca Sat Apr 3 11:51:20 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sat Apr 3 11:56:53 2004 Subject: [Tutor] puzzled by ident after list statement in IDLE In-Reply-To: References: <406E8366.80802@po-box.mcgill.ca> Message-ID: <406EEB88.6010403@po-box.mcgill.ca> Michael Janssen said unto the world upon 03/04/2004 07:22: > On Sat, 3 Apr 2004, Brian van den Broek wrote: > > >>But what I get is >> >>> list(queens(5, (0, 2)) >> | > > > this is a case of "refusing correct indentation on error": you've > missed a final closing bracket. That's all... > > The editor should give you some feedback about closing brackets so > you are warned when this feedback doesn't come. Further the > incorrect indentation should behave not like an indetation at all: > typeing backspace refuses to do a 4 spaces jump back. I don't now > what IDLE does but this is what emacs tries to help me. > > Michael Michael, oh dear. Yes, in the light of day that is pretty clear. :-[ Lesson learned -- don't post puzzlements at 4am! Thanks for setting me straight. Best, Brian vdB From chris at chrislott.org Sat Apr 3 21:52:27 2004 From: chris at chrislott.org (Chris Lott) Date: Sat Apr 3 21:52:39 2004 Subject: [Tutor] why "self" in methods? Message-ID: <406F786B.60207@chrislott.org> Why do object methods need the (self) parameter rather than just accepting () as a function can? I mean, given: class Foo: def doIt(self): print "did it" why couldn't it be: def doIt(): c -- Chris Lott http://www.chrislott.org/ From alice_moomlyn at yahoo.com Sat Apr 3 23:08:34 2004 From: alice_moomlyn at yahoo.com (Alice Moomlyn) Date: Sat Apr 3 23:08:40 2004 Subject: [Tutor] Good threading tutorial In-Reply-To: Message-ID: <20040404040834.38940.qmail@web41708.mail.yahoo.com> I was reading through my email as I have a tendancy to do when I'm supposed to be doing something else, and I came across this interesting little snippet of threading code. I tried it out, and it works fine but I have a few little questions. ..................................... 1. Does: tt = printTaskThread() instantiate some kind of master thread-controller thing? and: self.task() create a new actual thread? Is that how it works? ......................................... 2. Could: self._finished = threading.Event() be alternatively (though not unadvisably) be implemented with a global boolean variable, much as num (the number of threads) has been? ......................................... 3. Does the start() method do a little 'behind the scenes' initialization and then call the run() method? ......................................... 4. What's a thread? (as opposed to a process) I noticed that when I start up python normally I see one instance of python when I type `ps` but after I do tt.start(), I have three. Then, after I do tt.shutdown(), I have two. I'm not really sure what is happening here. I vaguely remember reading something once about threads on Linux being processes with shared memory, and threads on Windows being an attempt to make up for the absense of a fork() system call and proper process differentiation, but am not really too clear on the whole concept. ......................................... Thanks in advance for anybody who takes the time to answer these questions. ----- import threading class TaskThread(threading.Thread): """Thread that executes a task every N seconds""" def __init__(self): threading.Thread.__init__(self) self._finished = threading.Event() #self._interval = 15.0 self._interval = 5.0 self.num = 0 def setInterval(self, interval): """Set the number of seconds we sleep between executing our task""" self._interval = interval def shutdown(self): """Stop this thread""" self._finished.set() def run(self): while 1: if self._finished.isSet(): return self.task() # sleep for interval or until shutdown self._finished.wait(self._interval) def task(self): """The task done by this thread - override in subclasses""" pass if __name__ == '__main__': global num class printTaskThread(TaskThread): def task(self): print 'running %d' %self.num self.num = self.num + 1 time.sleep(3) tt = printTaskThread() tt.setInterval(3) print 'starting' tt.start() print 'started, wait now' import time time.sleep(60) print 'killing the thread' tt.shutdown() print 'killed and done' ------- ===== "the only way to learn how to be clever is to say stupid things" - anon __________________________________ Do you Yahoo!? Yahoo! Small Business $15K Web Design Giveaway http://promotions.yahoo.com/design_giveaway/ From bgailer at alum.rpi.edu Sun Apr 4 06:05:53 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sun Apr 4 06:04:28 2004 Subject: [Tutor] why "self" in methods? In-Reply-To: <406F786B.60207@chrislott.org> References: <406F786B.60207@chrislott.org> Message-ID: <6.0.0.22.0.20040404040121.038ffc30@mail.mric.net> At 08:52 PM 4/3/2004, Chris Lott wrote: >Why do object methods need the (self) parameter rather than just accepting >() as a function can? Note that this applies to "class" methods rather than to "object" methods. >I mean, given: > >class Foo: > def doIt(self): > print "did it" > >why couldn't it be: > def doIt(): That's how it is in Visual Foxpro (VFP). As a consequence VFP needs a keyword "this" to identify the instance calling the method. Python lets you give the instance variable any name you like. "self" is used by tradition. Also Python's approach allows for "unbound" methods. Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From nick at javacat.f2s.com Sun Apr 4 13:26:53 2004 From: nick at javacat.f2s.com (Nick Lunt) Date: Sun Apr 4 13:25:45 2004 Subject: [Tutor] File Access Message-ID: <1081099612.1261.16.camel@localhost.localdomain> Hi folks, I need to go to the last line of a file and then to the start of a delimited section of that line, such as $ cat file.txt var1|var2|var3|var4|var5|var6|var7 var1|var2|var3|var4|var5|var6 var1|var2|var3|var4|var5|var6 What I want to do is goto the last line in the imaginary file.txt above and extract var3 for example. I could probably do a realines() until EOF overwriting a variable with the contents of each line so that at the end the variable will hold the contents of just the last line, or by putting each line of the file into a list and pulling the last element of the list out, but eventually the file.txt will get pretty big, so I thought of using seek(). However, I could not find on python.org or by googling any way to do this. So can anyone please give me a hint on the most efficient way to grab the contents of the last line of a large text file please ? Kind regards, Nick. From orbitz at ezabel.com Sun Apr 4 13:39:07 2004 From: orbitz at ezabel.com (orbitz@ezabel.com) Date: Sun Apr 4 13:39:23 2004 Subject: [Tutor] why "self" in methods? In-Reply-To: <406F786B.60207@chrislott.org> References: <406F786B.60207@chrislott.org> Message-ID: <20040404133907.1e6cc1bf.orbitz@ezabel.com> Python is very explicit about many things. In C++ or Java the 'self' (called this) is implicit, with python you explicitly give the name, as the first parameter of your class's method, that you can access the class from. The tutorial covers this concept. Read http://www.python.org/doc/current/tut/node11.html Also in the case of our fictional class Foo, something like: bar = Foo() bar.doIt() Really can be interpreted as bar = Foo() Foo.doIt(bar) Those two statements are synonymous, hope that helps somewhat. On Sat, 03 Apr 2004 17:52:27 -0900 Chris Lott wrote: > Why do object methods need the (self) parameter rather than just > accepting () as a function can? I mean, given: > > class Foo: > def doIt(self): > print "did it" > > why couldn't it be: > def doIt(): > > c > -- > Chris Lott > http://www.chrislott.org/ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From alan.gauld at blueyonder.co.uk Sun Apr 4 14:42:03 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Apr 4 14:41:54 2004 Subject: [Tutor] why "self" in methods? References: <406F786B.60207@chrislott.org> <6.0.0.22.0.20040404040121.038ffc30@mail.mric.net> Message-ID: <009f01c41a74$85fe71b0$6401a8c0@xp> > Also Python's approach allows for "unbound" methods. As a matter of interest, does anyone know of a valid use for unbound methods? I can't think of one... Alan G. (Just home from a weeks vacation without a computer in sight! :-) From orbitz at ezabel.com Sun Apr 4 15:34:30 2004 From: orbitz at ezabel.com (orbitz@ezabel.com) Date: Sun Apr 4 15:34:35 2004 Subject: [Tutor] why "self" in methods? In-Reply-To: <009f01c41a74$85fe71b0$6401a8c0@xp> References: <406F786B.60207@chrislott.org> <6.0.0.22.0.20040404040121.038ffc30@mail.mric.net> <009f01c41a74$85fe71b0$6401a8c0@xp> Message-ID: <20040404153430.7c0389e6.orbitz@ezabel.com> You could have a reference to a method when you don't have a specific object to act upon it yet. Useful for callbacks where you want to use the same method on a series of objects of the same type. On Sun, 4 Apr 2004 19:42:03 +0100 "Alan Gauld" wrote: > > Also Python's approach allows for "unbound" methods. > > As a matter of interest, does anyone know of a valid use > for unbound methods? I can't think of one... > > Alan G. > (Just home from a weeks vacation without a computer in sight! :-) > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From tony at tcapp.com Sun Apr 4 16:02:02 2004 From: tony at tcapp.com (Tony Cappellini) Date: Sun Apr 4 16:03:38 2004 Subject: [Tutor] re:Good threading tutorial In-Reply-To: References: Message-ID: <6.0.0.22.0.20040404130015.0374f880@tcapp.com> >---------------------------------------------------------------------- > >Message: 1 >Date: Wed, 31 Mar 2004 13:25:55 -0500 >From: "Shawhan, Doug \(EM, ITS\)" >Subject: [Tutor] Good threading tutorial >To: Aahz has a good tutorial on threading online here >http://starship.python.net/crew/aahz/OSCON2001/ from a presentation at Pycon 2001. There is a PDF of the whole presentation, and the Python source files are available that you can run, help to illustrate the same scenario, before AND after adding threads. Tony From tony at tcapp.com Sun Apr 4 16:04:55 2004 From: tony at tcapp.com (Tony Cappellini) Date: Sun Apr 4 16:05:27 2004 Subject: [Tutor] re:Good threading tutorial- correction Message-ID: <6.0.0.22.0.20040404130337.01c495d0@smtp.sbcglobal.net> >---------------------------------------------------------------------- > >Message: 1 >Date: Wed, 31 Mar 2004 13:25:55 -0500 >From: "Shawhan, Doug \(EM, ITS\)" >Subject: [Tutor] Good threading tutorial >To: The previous email about Aahz's threading tutorial stated the tutorial was presented at Pycon 2001. I should have typed OSCON 2001. Aahz has a good tutorial on threading online here >http://starship.python.net/crew/aahz/OSCON2001/ from a presentation at OSCON 2001. There is a PDF of the whole presentation, and the Python source files are available that you can run, help to illustrate the same scenario, before AND after adding threads. Tony From chris at chrislott.org Sun Apr 4 16:22:58 2004 From: chris at chrislott.org (Chris Lott) Date: Sun Apr 4 16:23:10 2004 Subject: [Tutor] Parsing OPML Message-ID: <40706EA2.1080900@chrislott.org> I am trying to write a script that will parse my Bloglines OPML export (see snippet below) and output an HTML blogroll. I can get at all the actual blog entries with the code below. But the problem is that I would like to get at the "folder" level ("Test and Demo" and "Unfiled" below) which just has a name and no other attributes so that I can group the entries in their "categories" something like this (http://rpc.bloglines.com/blogroll?html=1&id=chrislott). My code only lists the entries themselves... ********************************blogs.opml** Bloglines Subscriptions Sun, 4 Apr 2004 20:15:17 GMT chris@chrislott.org ********************************************my script** from xml.sax import make_parser from xml.sax.handler import ContentHandler class OPMLHandler(ContentHandler): def startElement(self, name, attrs): if name == 'outline': self.title = attrs.get('title', '') self.url = attrs.get('xmlUrl', '') def endElement(self, name): if name == 'outline': print self.level, ':', self.title, '-', self.url parser = make_parser() curHandler = OPMLHandler() parser.setContentHandler(curHandler) parser.parse(open('blogs.opml')) c -- Chris Lott From pythonTutor at venix.com Sun Apr 4 22:13:31 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Sun Apr 4 22:16:15 2004 Subject: [Tutor] File Access In-Reply-To: <1081099612.1261.16.camel@localhost.localdomain> References: <1081099612.1261.16.camel@localhost.localdomain> Message-ID: <1081131210.2092.5.camel@laptop.venix.com> files (file objects) support the seek method: f.seek(pos,how) pos is the position how is 0 for start 1 for current location 2 for end f.seek(0,2) would place you at the end of the file. Note that text mode in Windows can confuse things. binary mode and unix will work as you expect. On Sun, 2004-04-04 at 13:26, Nick Lunt wrote: > Hi folks, > > I need to go to the last line of a file and then to the start of a > delimited section of that line, such as > > $ cat file.txt > var1|var2|var3|var4|var5|var6|var7 > var1|var2|var3|var4|var5|var6 > var1|var2|var3|var4|var5|var6 > > What I want to do is goto the last line in the imaginary file.txt above > and extract var3 for example. > > I could probably do a realines() until EOF overwriting a variable with > the contents of each line so that at the end the variable will hold the > contents of just the last line, or by putting each line of the file into > a list and pulling the last element of the list out, but eventually the > file.txt will get pretty big, so I thought of using seek(). > > However, I could not find on python.org or by googling any way to do > this. > > So can anyone please give me a hint on the most efficient way to grab > the contents of the last line of a large text file please ? > > Kind regards, > Nick. > > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From dyoo at hkn.eecs.berkeley.edu Mon Apr 5 04:23:27 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Apr 5 04:23:41 2004 Subject: [Tutor] why "self" in methods? In-Reply-To: <009f01c41a74$85fe71b0$6401a8c0@xp> Message-ID: On Sun, 4 Apr 2004, Alan Gauld wrote: > > Also Python's approach allows for "unbound" methods. > > As a matter of interest, does anyone know of a valid use for unbound > methods? I can't think of one... Hi Alan, Yes: if one needs to call methods of a superclass, one way to do it is with an explicit call to the "unbound" method of the superclass. Here's a completely useless toy example: ### >>> class SomeClass(object): ... def sayHello(self): ... print "hi, I'm SomeClass" ... >>> class AnotherClass(SomeClass): ... def sayHello(self): ... print "well, here I am." ... >>> class OneMoreClass(SomeClass): ... def sayHello(self): ... SomeClass.sayHello(self) ... print "yeah" ... >>> s = SomeClass() >>> a = AnotherClass() >>> o = OneMoreClass() >>> s.sayHello() hi, I'm SomeClass >>> a.sayHello() well, here I am. >>> o.sayHello() hi, I'm SomeClass yeah ### Next time, I'll need to think of a better motivating example of calling superclass methods... *grin* Oh well. So that's one concrete example where unbound methods matter. As of Python 2.3, this sort of thing is a little easier to do with the super() builtin. ### >>> class YetAnotherClass(SomeClass): ... def sayHello(self): ... super(YetAnotherClass, self).sayHello() ... print "YetAnotherClass" ... >>> y = YetAnotherClass() >>> y.sayHello() hi, I'm SomeClass YetAnotherClass ### Note: the example with super() only works if we're using new-style classes. That's why we define SomeClass above to inherit from 'object'. If we don't, then we'll a weird error that looks like this: >>> y.sayHello() Traceback (most recent call last): File "", line 1, in ? File "", line 3, in sayHello TypeError: super() argument 1 must be type, not classobj Hope this helps! From dyoo at hkn.eecs.berkeley.edu Mon Apr 5 04:33:46 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Apr 5 04:34:04 2004 Subject: [Tutor] File Access In-Reply-To: <1081099612.1261.16.camel@localhost.localdomain> Message-ID: On Sun, 4 Apr 2004, Nick Lunt wrote: > I could probably do a realines() until EOF overwriting a variable with > the contents of each line so that at the end the variable will hold the > contents of just the last line, or by putting each line of the file into > a list and pulling the last element of the list out, but eventually the > file.txt will get pretty big, so I thought of using seek(). Hi Nick, Yes, that's one approach. If you are going to read a large file, definitely try to avoid using readlines(), because that tries to load the whole file into memory at once. Usually, we don't need to read the whole file at once: things often work if we read and process a line at a time, to avoid holding the whole file at once. So instead of: ### for line in somefile.readlines(): ## First approach ... ### it's more efficient to say: ### while 1: ## Second approach line = somefile.readline() if not line: break ... ### This second appraoch is a little ugly, even though it scales better than the first. Thankfully, there's a way out: recent versions of Python let us write a line-by-line approach by taking advantage of new features of the for loop: ### for line in somefile: ## Third approach ... ### Here, we "iterate" across a file, just as if we were iterating across a list. This third approach looks just as nice as the first 'buggy' approach, but with the low memory requirements of the second. So it's the best of both worlds. *grin* > However, I could not find on python.org or by googling any way to do > this. Try iterating across the whole loop, and keep track of the very last line that's read. That should be the line you're looking for. If you plan to do this sort of thing a lot, it might be worth it to build an "index" that records the byte offsets of each line. We can talk about that if you'd like. If you have any questions on this, please feel free to ask. Good luck to you! From alan.gauld at blueyonder.co.uk Mon Apr 5 06:25:17 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Mon Apr 5 06:25:05 2004 Subject: [Tutor] why "self" in methods? References: Message-ID: <00fc01c41af8$4a373480$6401a8c0@xp> > Yes: if one needs to call methods of a superclass, one way to do it is > with an explicit call to the "unbound" method of the superclass. Here's a > completely useless toy example: > > ### > >>> class SomeClass(object): > ... def sayHello(self): > ... print "hi, I'm SomeClass" > ... But sayHello is not unbound in the sense mentioned in the OP (which actually may not be the right term!). What I was really asking was what use (if any) do methods without a self parameter have? Python allows you to create them but, so far as I can tell, you can never use them? ie: >>> class SomeClass(object): ... def sayHello(self): ... print "hi, I'm SomeClass" ... def noSelf(): ... print "I'm selfless" ... >>> print SomeClass.sayHello >>> print SomeClass.noSelf So far they look the same. >>> s = SomeClass() >>> print s.sayHello > >>> print s.unboundMeth > And they still look similar after binding >>> s.sayHello() hi, I'm SomeClass >>> s.noSelf() Traceback (most recent call last): File "", line 1, in ? TypeError: noSelf() takes no arguments (1 given) But when you try to call them.... Now it might be sensible to tread noSelf as a class method - ie one which operates on the class level rather than the instance level... >>> SomeClass.noSelf() Traceback (most recent call last): File "", line 1, in ? AttributeError: type object 'SomeClass' has no attribute 'noSelf' >>> But nope, you can't do that either. So is there any way to use these? And if not why does Python happily allow them? It should be possible to detect parameterless function definintions within a class scope surely? (The only reason I can think of might be to allow definition of higher order methods - ie methods which return functions which may not take parameters.... but even that should be detectable...) Just curious, Alan G. From orbitz at ezabel.com Mon Apr 5 09:01:41 2004 From: orbitz at ezabel.com (orbitz@ezabel.com) Date: Mon Apr 5 09:02:00 2004 Subject: [Tutor] why "self" in methods? In-Reply-To: <00fc01c41af8$4a373480$6401a8c0@xp> References: <00fc01c41af8$4a373480$6401a8c0@xp> Message-ID: <20040405090141.6d1bb4fb.orbitz@ezabel.com> Taking no self argument is not the same as unbound. unbound just means the method is not bound to an instance. Take Danny's example of calling super class's method. >From Nevow's code: class Renderer(ChildPrefixMixin, resource.Resource, RenderFactory, DataFactory): def __init__(self, original=None): # Some other junk here... resource.Resource.__init__(self) Using unbound method to call the constructor of one of the parent classes. On Mon, 5 Apr 2004 11:25:17 +0100 "Alan Gauld" wrote: > > Yes: if one needs to call methods of a superclass, one way to do it > is > > with an explicit call to the "unbound" method of the superclass. > Here's a > > completely useless toy example: > > > > ### > > >>> class SomeClass(object): > > ... def sayHello(self): > > ... print "hi, I'm SomeClass" > > ... > > But sayHello is not unbound in the sense mentioned in the OP > (which actually may not be the right term!). What I was really > asking was what use (if any) do methods without a self parameter have? > > Python allows you to create them but, so far as I can tell, > you can never use them? > > ie: > > >>> class SomeClass(object): > ... def sayHello(self): > ... print "hi, I'm SomeClass" > ... def noSelf(): > ... print "I'm selfless" > ... > >>> print SomeClass.sayHello > > >>> print SomeClass.noSelf > > > So far they look the same. > > >>> s = SomeClass() > >>> print s.sayHello > 0xa06672c>> > >>> print s.unboundMeth > 0xa06672c>> > > And they still look similar after binding > > >>> s.sayHello() > hi, I'm SomeClass > >>> s.noSelf() > Traceback (most recent call last): > File "", line 1, in ? > TypeError: noSelf() takes no arguments (1 given) > > But when you try to call them.... > > Now it might be sensible to tread noSelf as a class method > - ie one which operates on the class level rather than the > instance level... > > >>> SomeClass.noSelf() > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: type object 'SomeClass' has no attribute 'noSelf' > >>> > > But nope, you can't do that either. > > So is there any way to use these? And if not why does Python happily > allow them? It should be possible to detect parameterless function > definintions within a class scope surely? (The only reason I can > think of might be to allow definition of higher order methods > - ie methods which return functions which may not take > parameters.... but even that should be detectable...) > > Just curious, > > Alan G. > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From chris at chrislott.org Mon Apr 5 11:13:08 2004 From: chris at chrislott.org (Chris Lott) Date: Mon Apr 5 11:13:21 2004 Subject: [Tutor] why "self" in methods? In-Reply-To: <00fc01c41af8$4a373480$6401a8c0@xp> References: <00fc01c41af8$4a373480$6401a8c0@xp> Message-ID: <40717784.4070608@chrislott.org> Alan Gauld wrote: >>>>>class SomeClass(object): >> >>... def sayHello(self): >>... print "hi, I'm SomeClass" >>... > > > But sayHello is not unbound in the sense mentioned in the OP > (which actually may not be the right term!). What I was really > asking was what use (if any) do methods without a self parameter have? The OP (me) is completely clueless at the moment, but I was asking about creating a method such as def noSelf() in your code below: >>>>class SomeClass(object): > > ... def sayHello(self): > ... print "hi, I'm SomeClass" > ... def noSelf(): > ... print "I'm selfless" My original question was why, if it lacked a parameter, it didn't just automatically take the parameter self... that they can be created but not used doesn't seem very Pythonic :) c -- Chris Lott From op73418 at mail.telepac.pt Mon Apr 5 11:26:05 2004 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Mon Apr 5 11:41:14 2004 Subject: [Tutor] why "self" in methods? In-Reply-To: <40717784.4070608@chrislott.org> References: <00fc01c41af8$4a373480$6401a8c0@xp> <40717784.4070608@chrislott.org> Message-ID: <7cu2701u8d7q9a95rab2sh8ua7pnetoknf@4ax.com> Em Mon, 05 Apr 2004 07:13:08 -0800, Chris Lott atirou este peixe aos pinguins: >Alan Gauld wrote: > > >>>>>class SomeClass(object): > >> > >>... def sayHello(self): > >>... print "hi, I'm SomeClass" > >>... > > > > > > But sayHello is not unbound in the sense mentioned in the OP > > (which actually may not be the right term!). What I was really > > asking was what use (if any) do methods without a self parameter have? > >The OP (me) is completely clueless at the moment, but I was asking about >creating a method such as def noSelf() in your code below: > > >>>>class SomeClass(object): > > > > ... def sayHello(self): > > ... print "hi, I'm SomeClass" > > ... def noSelf(): > > ... print "I'm selfless" > >My original question was why, if it lacked a parameter, it didn't just >automatically take the parameter self... that they can be created but >not used doesn't seem very Pythonic :) That's a problem of the programmer, not of the language right? Also, about the self controversy, think about nested definitions of classes. You get into trouble with the implicit self thingy. With my best regards, G. Rodrigues From marilyn at deliberate.com Mon Apr 5 12:52:44 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Mon Apr 5 12:52:51 2004 Subject: [Tutor] why "self" in methods? In-Reply-To: <7cu2701u8d7q9a95rab2sh8ua7pnetoknf@4ax.com> Message-ID: On Mon, 5 Apr 2004, Gon?alo Rodrigues wrote: > Em Mon, 05 Apr 2004 07:13:08 -0800, Chris Lott > atirou este peixe aos pinguins: > > >Alan Gauld wrote: > > > > >>>>>class SomeClass(object): > > >> > > >>... def sayHello(self): > > >>... print "hi, I'm SomeClass" > > >>... > > > > > > > > > But sayHello is not unbound in the sense mentioned in the OP > > > (which actually may not be the right term!). What I was really > > > asking was what use (if any) do methods without a self parameter have? > > > >The OP (me) is completely clueless at the moment, but I was asking about > >creating a method such as def noSelf() in your code below: > > > > >>>>class SomeClass(object): > > > > > > ... def sayHello(self): > > > ... print "hi, I'm SomeClass" > > > ... def noSelf(): > > > ... print "I'm selfless" > > > >My original question was why, if it lacked a parameter, it didn't just > >automatically take the parameter self... that they can be created but > >not used doesn't seem very Pythonic :) > > That's a problem of the programmer, not of the language right? The newish facilities staticmethod() and classmethod() are for providing a selfless method, and one that takes the class as the self: #!/usr/bin/env python2.2 '''In Python 2.2, staticmethod() and classmethod() give you this ability.''' class Static: number = 0 def __init__(self): Static.number += 1 def start_over(): # Note: no self for a static method! Static.number = 0 def jump_up(self, number): # Note: self will be the class print 'In classmethod(jump_up), self =', self Static.number += number start_over = staticmethod(start_over) jump_up = classmethod(jump_up) ############################################################ # Sample Run: # bash-2.05a$ python2.2 -i static2.py # >>> Static.jump_up(2) # In classmethod(jump_up), self = __main__.Static # >>> Static.number # 2 # >>> Static.start_over() # >>> Static.number # 0 # >>> s = Static() # >>> s.number # 1 # >>> s.start_over() # >>> s.number # 0 # >>> s.jump_up(101) # In classmethod(jump_up), self = __main__.Static # >>> s.number # 101 # >>> > > Also, about the self controversy, think about nested definitions of > classes. You get into trouble with the implicit self thingy. My sense is that 'self' is an implementation issue, something that is done to make the interpreter work. class C: def m(self): pass o = C() then o.m() becomes C.m(o) so we need a variable to receive the o. Is it being suggested that there should be a self = o in the method for free without any syntax required of the programmer? I don't immediately see the problem with this with nested class definitions, Gon?alo. Can you say something more? Interesting discussion. Marilyn Davis > > With my best regards, > G. Rodrigues > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- From nick at javacat.f2s.com Mon Apr 5 13:08:05 2004 From: nick at javacat.f2s.com (Nick Lunt) Date: Mon Apr 5 13:06:50 2004 Subject: [Tutor] File Access In-Reply-To: <1081131210.2092.5.camel@laptop.venix.com> References: <1081099612.1261.16.camel@localhost.localdomain> <1081131210.2092.5.camel@laptop.venix.com> Message-ID: <1081184884.15243.18.camel@localhost.localdomain> Hi Lloyd, thanks for the info. However, f.seek(0,2) takes me to the end of the file as you say, but what I need is the whole last line of the file. After doing f.seek(0,2) successive f.seek(-1, 1) calls will walk me backwards through the file but to make this useful I would need to keep checking the current character for an "\n". And unfortunately calls to f.read() and f.readline() take me back to the end of the file or line respectively. Im on linux and the fseek(3) manpage seems to indicate that I cannot take a file of unknown size and seek to the start of the last line, would be nice if it did tho ;) Am I talking rubbish or do you agree ? Thanks again, Nick. On Mon, 2004-04-05 at 03:13, Lloyd Kvam wrote: > files (file objects) support the seek method: > f.seek(pos,how) > pos is the position > how is 0 for start > 1 for current location > 2 for end > f.seek(0,2) would place you at the end of the file. > > Note that text mode in Windows can confuse things. binary mode and unix > will work as you expect. > > On Sun, 2004-04-04 at 13:26, Nick Lunt wrote: > > Hi folks, > > > > I need to go to the last line of a file and then to the start of a > > delimited section of that line, such as > > > > $ cat file.txt > > var1|var2|var3|var4|var5|var6|var7 > > var1|var2|var3|var4|var5|var6 > > var1|var2|var3|var4|var5|var6 > > > > What I want to do is goto the last line in the imaginary file.txt above > > and extract var3 for example. > > > > I could probably do a realines() until EOF overwriting a variable with > > the contents of each line so that at the end the variable will hold the > > contents of just the last line, or by putting each line of the file into > > a list and pulling the last element of the list out, but eventually the > > file.txt will get pretty big, so I thought of using seek(). > > > > However, I could not find on python.org or by googling any way to do > > this. > > > > So can anyone please give me a hint on the most efficient way to grab > > the contents of the last line of a large text file please ? > > > > Kind regards, > > Nick. > > > > > > > > > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor From alan.gauld at blueyonder.co.uk Mon Apr 5 13:12:21 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Mon Apr 5 13:12:01 2004 Subject: [Tutor] why "self" in methods? References: <00fc01c41af8$4a373480$6401a8c0@xp><40717784.4070608@chrislott.org> <7cu2701u8d7q9a95rab2sh8ua7pnetoknf@4ax.com> Message-ID: <014e01c41b31$29f3d690$6401a8c0@xp> Hi Goncalo, >>automatically take the parameter self... that they can be created but >>not used doesn't seem very Pythonic :) > > That's a problem of the programmer, not of the language right? Not if the compiler can detect the error.... > Also, about the self controversy, think about nested definitions > of classes. You get into trouble with the implicit self thingy. Really? How so? Surely that's merely a matter of scoping. I agree that self being explicit is "a good thing" but it is not necessary, other languages seem to manage quite well without it. Alan G From nick at javacat.f2s.com Mon Apr 5 13:21:55 2004 From: nick at javacat.f2s.com (Nick Lunt) Date: Mon Apr 5 13:20:40 2004 Subject: [Tutor] File Access In-Reply-To: References: Message-ID: <1081185714.15243.29.camel@localhost.localdomain> Hi Danny, 'for line in somefile' works very well, and like you say will not bog my system down (which is fortunate as my lowly 700Mhz machine is even struggling with linux now). * If you plan to do this sort of thing a lot, it might be worth it to build * an "index" that records the byte offsets of each line. We can talk about * that if you'd like. That sounds interesting. If you could give me a quick rundown on that concept or point me to somewhere that can I'd be very grateful. Many thanks, Nick. On Mon, 2004-04-05 at 09:33, Danny Yoo wrote: > On Sun, 4 Apr 2004, Nick Lunt wrote: > > > I could probably do a realines() until EOF overwriting a variable with > > the contents of each line so that at the end the variable will hold the > > contents of just the last line, or by putting each line of the file into > > a list and pulling the last element of the list out, but eventually the > > file.txt will get pretty big, so I thought of using seek(). > > Hi Nick, > > > Yes, that's one approach. > > If you are going to read a large file, definitely try to avoid using > readlines(), because that tries to load the whole file into memory at > once. Usually, we don't need to read the whole file at once: things often > work if we read and process a line at a time, to avoid holding the whole > file at once. > > So instead of: > > ### > for line in somefile.readlines(): ## First approach > ... > ### > > it's more efficient to say: > > ### > while 1: ## Second approach > line = somefile.readline() > if not line: break > ... > ### > > > This second appraoch is a little ugly, even though it scales better than > the first. Thankfully, there's a way out: recent versions of Python let > us write a line-by-line approach by taking advantage of new features of > the for loop: > > ### > for line in somefile: ## Third approach > ... > ### > > Here, we "iterate" across a file, just as if we were iterating across a > list. This third approach looks just as nice as the first 'buggy' > approach, but with the low memory requirements of the second. So it's the > best of both worlds. *grin* > > > > However, I could not find on python.org or by googling any way to do > > this. > > Try iterating across the whole loop, and keep track of the very last line > that's read. That should be the line you're looking for. > > > If you plan to do this sort of thing a lot, it might be worth it to build > an "index" that records the byte offsets of each line. We can talk about > that if you'd like. > > > If you have any questions on this, please feel free to ask. Good luck to > you! > > From dyoo at hkn.eecs.berkeley.edu Mon Apr 5 14:54:55 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Apr 5 14:55:05 2004 Subject: [Tutor] why "self" in methods? [compile-time vs run-time / pychecker] In-Reply-To: <40717784.4070608@chrislott.org> Message-ID: > The OP (me) is completely clueless at the moment, but I was asking about > creating a method such as def noSelf() in your code below: > > >>>>class SomeClass(object): > > > > ... def sayHello(self): > > ... print "hi, I'm SomeClass" > > ... def noSelf(): > > ... print "I'm selfless" > > My original question was why, if it lacked a parameter, it didn't just > automatically take the parameter self... Hi Chris, One possible reason is that 'self' isn't hardcoded into the language: we can just as easily start using 'this' instead: ### >>> class SomeClass(object): ... def sayHello(this): ... print "hi, I'm", this ... >>> s = SomeClass() >>> s.sayHello() hi, I'm <__main__.SomeClass object at 0x400e694c> ### The name that we use to pass around the instance is 'self' by community convension --- there's no technical reason why it couldn't have been 'this'. > that they can be created but not used doesn't seem very Pythonic :) Python doesn't do much compile-time checking; in particular, it doesn't check that we're sending the proper number of arguments to a function until we actually try firing off the function: ### >>> def hypo(a, b): ... return (a**2 + b**2)**0.5 ... >>> def foo(): ... print hypo(3) ... ### Notice here that we've just defined a function foo that tries to use 'hypo'... but we don't get an error yet! But we will see an expected error at "runtime": ### >>> foo() Traceback (most recent call last): File "", line 1, in ? File "", line 2, in foo TypeError: hypo() takes exactly 2 arguments (1 given) ### Going back to the original class example: ### class SomeClass(object): def sayHello(self): print "hi, I'm SomeClass" def noSelf(): print "I'm selfless" ### one reason why Python doesn't report an error for noSelf() outright is because it's not looking for parameter misuse at 'definition', or 'compile' time. Although Python itself doesn't flag the missing 'self' as an error, there are tools that will try to infer buggy usage. PyChecker, in particular, is a code-checking utility that detects these sort of problems: ### class SomeClass(object): def sayHello(self): print "hi, I'm SomeClass" def noSelf(): print "I'm selfless" [dyoo@tesuque dyoo]$ pychecker foo.py Processing foo... Warnings... foo.py:4: No method arguments, should have self as argument ### PyChecker can be found here: http://pychecker.sourceforge.net/ Please feel free to ask more questions. Hope this helps! From op73418 at mail.telepac.pt Mon Apr 5 15:57:45 2004 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Mon Apr 5 15:55:13 2004 Subject: [Tutor] why "self" in methods? In-Reply-To: <014e01c41b31$29f3d690$6401a8c0@xp> References: <00fc01c41af8$4a373480$6401a8c0@xp><40717784.4070608@chrislott.org> <7cu2701u8d7q9a95rab2sh8ua7pnetoknf@4ax.com> <014e01c41b31$29f3d690$6401a8c0@xp> Message-ID: <05d370h6tdlfv5etqse9o739pknllfhfba@4ax.com> Em Mon, 5 Apr 2004 18:12:21 +0100, "Alan Gauld" atirou este peixe aos pinguins: >> Also, about the self controversy, think about nested definitions >> of classes. You get into trouble with the implicit self thingy. > >Really? How so? Surely that's merely a matter of scoping. >I agree that self being explicit is "a good thing" but >it is not necessary, other languages seem to manage quite >well without it. > [Answering also to Marylin Davis] Suppose that self was a keyword naming the implicit object that's passed to methods. Consider the following example: class Outer(object): def amethod(arg): class Inner(object): def amethod(arg): self.arg = arg #What's self here? return inner() Is self from the inner or from the outer? The "logical" answer would be from the inner amethod from the Inner class. But then the outer self is shadowed -- not good. And since it's implicit... you know where I'm getting at. Explicit is better than implicit. And although from the top of my head I can't remember a use case of unbound methods, *I have used them* several times. Suppose there were no unbound methods, what should be class Outer(object): def amethod(arg): .... Outer.amethod If methods are attributes of the class object, then the above must return something sensible. And if it is to remain callable, well, it must receive the instance explicitely as a parameter. Perhaps you could write some wrappers, etc. that would do this for you, but somehow I think that without the explicit self it would not be very elegant. Besides, it gives a very handy syntax for calling a super class method that is overriden. Also in class methods, in meta methods, etc. the explicit self allows me to call the self, cls, that is class Outer(object): def method(cls): .... method = classmethod(method) which IMHO is much better from a raedability point of view Read the FAQ entry on this for a couple more reasons. So, my verdict is definitely: explicit self is a *very good* Python feature and a clear mark of excellent design. And to the stake with the blasphemers that dare oppose the BDFL :-) With my best regards, G. Rodrigues From amonroe at columbus.rr.com Mon Apr 5 17:53:53 2004 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Mon Apr 5 17:47:13 2004 Subject: [Tutor] File Access In-Reply-To: <1081184884.15243.18.camel@localhost.localdomain> References: <1081099612.1261.16.camel@localhost.localdomain> <1081131210.2092.5.camel@laptop.venix.com> <1081184884.15243.18.camel@localhost.localdomain> Message-ID: <1361203671047.20040405175353@columbus.rr.com> > thanks for the info. However, f.seek(0,2) takes me to the end of the > file as you say, but what I need is the whole last line of the file. > After doing f.seek(0,2) successive f.seek(-1, 1) calls will walk me > backwards through the file but to make this useful I would need to keep > checking the current character for an "\n". And unfortunately calls to > f.read() and f.readline() take me back to the end of the file or line > respectively. > Im on linux and the fseek(3) manpage seems to indicate that I cannot > take a file of unknown size and seek to the start of the last line, > would be nice if it did tho ;) If you were desperate you could look at the source code for gnu's version of the good old tail command. One thing you could try is reading successively larger and larger chunks from the end of the file, like powers of two (1 byte, 2 bytes, 4 bytes, 8 bytes, 16 bytes, etc.) until you grab a chunk that has a \n in it, then work forward from there. Haven't personally tried this, though. Alan From bvande at po-box.mcgill.ca Mon Apr 5 19:00:04 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Mon Apr 5 19:05:55 2004 Subject: [Tutor] how to check a user input path for dirve existence Message-ID: <4071E4F4.7050201@po-box.mcgill.ca> Hi all, as described in my previous post, I am trying to write a function which asks the user for a directory name, checks for existence, and offers to create it if it does not. The function asks for a directory this way: asked_dir = raw_input("What Directory shall we work in?\n") Since this gets a raw string, if I go from a failed existence check to an attempt to create the directory, I won't have ruled out trying to create, say, J:\spam on a system without a J: drive. I can think of two approaches: 1) Embed the mkdir('J:\\spam') within a try/except to catch the OSError. Print error msg and start again if exception is caught. 2) Initialize asked_drivename to an empty string. Check if asked_dir has a ':' (in effect, checking to see if the string begins with a drive name), and if so, then extract the beginning of the string up to and including the colon to asked_drivename. Finally, if asked_drivename is non-empty, then use os.path.exists(asked_drivename) to check if the asked_dir string begins with a valid drive name. Process if it does, complain to user if not. My questions: 1) Pro's and con's of the two approaches I outline? 2) Other alternatives I've missed in my noobieness? (Wouldn't shock me in the least!) Thanks and best, Brian vdB From bvande at po-box.mcgill.ca Mon Apr 5 19:01:47 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Mon Apr 5 19:06:00 2004 Subject: [Tutor] how to catch particular Errno for Exceptions Message-ID: <4071E55B.4050101@po-box.mcgill.ca> Hi all, how do I catch a specific Errno for an exception? I have no G: drive and have tried the following code: import os try: os.mkdir('g:\\silly') except OSError: print 'OSError caught!' try: os.mkdir('gGg:\\sillier') except OSError, (2,): #what to write here? print 'OSError Errno 2 caught!' The first works try clause just fine, the second gives me a "can't assign to a literal" error when I try to run it out of IDLE. I've tried "except OSError, 2", "except OSError, (2)" and various other combinations, but no luck. Consulting the Tutorial, the Language Reference, and Learning Python has not cleared it up for me. Also, I've just posted three questions all on related, but distinct topics. Most list I am on prefer 3 msgs in such situations. Would it be preferred that I had posted all in one? (The last thing I want to do is annoy all the generous and patient Python tutors!) Thanks and best, Brian vdB From bvande at po-box.mcgill.ca Mon Apr 5 18:59:39 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Mon Apr 5 19:06:03 2004 Subject: [Tutor] puzzled by modes in os.mkdir() Message-ID: <4071E4DB.1050703@po-box.mcgill.ca> Hi all, I've made my first foray into the Library Reference, and I am a bit confused. I am using Python 2.3.3 on WinMe. What I am doing is creating a function that asks the user to input a directory name, checks such a directory exists, and if not, asks if one should be created. (I haven't checked if such a function is readily available; at my stage of learning, reinventing the wheel for simple things seems worth doing for the learning.) All is good until the creation part. I thought I should use os.mkdir( path[, mode]) for the creation. It takes an optional mode argument. Reading the Library Reference on this function (in section 6.1.4) it says: mkdir( path[, mode]) Create a directory named path with numeric mode mode. The default mode is 0777 (octal). On some systems, mode is ignored. Where it is used, the current umask value is first masked out. Availability: Macintosh, Unix, Windows. This is opaque to me, I am afraid. Here are my questions: 1) Are the modes here referred to the same ones as it the stat module? They don't seem to me to be, but the description of os.cmod(path, mode) references stat and nothing else. 2) Either way, I'd appreciate a pointer on what to read so that I can understand the Lib Ref's description of mkdir. (I don't know what is going on well enough to do a fruitful google-search.) In particular, I need to know what "0777 octal" means. (Knowing about the other options would be nice, too.) 3) I assume nothing will go wrong if I create a directory using the default mode argument for mkdir. Is this correct? I am going to keep going without knowing, but would want to be sure before I used my function for anything that matters. 4) What is the preferred syntax in postings, etc., for referring to functions that require arguments? "mkdir()" seems misleading in suggesting that it can be called with zero arguments, "mkdir(path)" seems too verbose. Thanks and best, Brian vdB From chronolee24 at hotmail.com Mon Apr 5 19:06:00 2004 From: chronolee24 at hotmail.com (Yaj Lis) Date: Mon Apr 5 19:06:15 2004 Subject: [Tutor] python help.. dictionary. Message-ID: hello .. i'm new too python.. and programming..and learning slowly... i'm creating a bank teller program. It has a list and dictionary. It askes for the user's input (raw_input) asking for an amount. If the user enters letters instead of an amount it would count it as 'counterfiet'. Would i have to write a for loop function? how would i compare to see if it is a string or an interger?..and i can't figure out how to work it with the dictionary.. like if i put in $30.25.. it would return "you have 1 $20 bill, 1 ten, and 1 quarter" .. i'm so frustrated. here's what i have so far.. wallet=raw_input("money in wallet ") for i in conterfeit(x): bank={} bank['h']=100 bank['F']=50 bank['T']=20 bank['t']=10 bank['f']=5 bank['o']=1 bank['q']=.25 bank['d']=.10 bank['p']=.01 x=wallet counterfeit(x) I want the program to output something like this...It should report the total value of the legal money as a floating point value (e.g. 123.45) and the total number of counterfeit pieces received. Money in wallet: asdfasdf Contained "1" counterfiet piece(s). Total amount in bank $20.00 asking for any help? thanks a lot.. _________________________________________________________________ Watch LIVE baseball games on your computer with MLB.TV, included with MSN Premium! http://join.msn.com/?page=features/mlb&pgmarket=en-us/go/onm00200439ave/direct/01/ From alan.gauld at blueyonder.co.uk Mon Apr 5 19:31:23 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Mon Apr 5 19:30:57 2004 Subject: [Tutor] why "self" in methods? References: Message-ID: <016601c41b66$1c495a80$6401a8c0@xp> > > >>>>class SomeClass(object): > > > ... def sayHello(self): > > > ... print "hi, I'm SomeClass" > > > ... def noSelf(): > > > ... print "I'm selfless" > > The newish facilities staticmethod() and classmethod() are for providing > a selfless method, and one that takes the class as the self: Yes and very welcome they are too. But I always thought the selfless method should be interpreted as a class method(ie static method) without any extra work. And up till 2.2 it was accepted but not accessible. Of course what you've just pointed out is that these new features mean my suggestion of issuing an error is no longer an option since Python can't tell if you will call staticmethod() later... So I guess that answers my question of what you can do with selfless methods - you can make them into class methods by calling staticmethod(). Just seems a wee bit clumsy IMHO. Thanks for the reminder, Alan G. From alan.gauld at blueyonder.co.uk Mon Apr 5 19:36:45 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Mon Apr 5 19:36:15 2004 Subject: [Tutor] why "self" in methods? [compile-time vs run-time /pychecker] References: Message-ID: <017101c41b66$dbbff0e0$6401a8c0@xp> > one reason why Python doesn't report an error for noSelf() outright is > because it's not looking for parameter misuse at 'definition', or > 'compile' time. > Good point Danny, I'd forgotten that feature. It makes Python quite consistent after all. In combination with the staticmethod() stuff Marlyn mentioned it all makes pefect sense - as usual! :-) My holiday was obviously more relaxing than I thought! > are tools that will try to infer buggy usage. PyChecker, in particular, > is a code-checking utility that detects these sort of problems: > > [dyoo@tesuque dyoo]$ pychecker foo.py > Processing foo... > > Warnings... > > foo.py:4: No method arguments, should have self as argument > ### > > > PyChecker can be found here: > > http://pychecker.sourceforge.net/ > And thanks for the reminder here too, I meant to check out pychecker once before and never got round to it... Alan G. From alan.gauld at blueyonder.co.uk Mon Apr 5 19:46:54 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Mon Apr 5 19:46:23 2004 Subject: [Tutor] how to check a user input path for dirve existence References: <4071E4F4.7050201@po-box.mcgill.ca> Message-ID: <017a01c41b68$465b6500$6401a8c0@xp> > check to an attempt to create the directory, I won't have ruled > out trying to create, say, J:\spam on a system without a J: drive. This presupposes that drive letters can be part of a path, which kind of limits things to CP/M(do we get Python for CP/M?) and Windows/DOS. (I think they are the only OS's that use drive letters as part of a path? Macs use drives but they have names and no other distinguishing features...) Given that limitation we know that the drive info can only consist of a single letter and a colon. So the only thing to test for is: if path[1] == ':' Which makes > 2) Initialize asked_drivename to an empty string. Check if > asked_dir has a ':' (in effect, checking to see if the string > begins with a drive name), and if so, then extract the beginning > of the string up to and including the colon to asked_drivename. fairly trivial: path = path[2:] But checking that path.exists is always a good idea too! Also my brain is still adjusting to Python & Programming after a weeks break so maybe I'm missing some complexity somewhere - like network drives maybe... Alan G. From orbitz at ezabel.com Mon Apr 5 20:11:05 2004 From: orbitz at ezabel.com (orbitz@ezabel.com) Date: Mon Apr 5 20:11:20 2004 Subject: [Tutor] python help.. dictionary. In-Reply-To: References: Message-ID: <20040405201105.3319c9e4.orbitz@ezabel.com> Try to convert the string to a float, or iterate over teh string and see if only digits and a . are contained in it. Using float() to convert it to a float is probably easiest, but you will need a try/except block to catch the exception it will throw if it fails. The rest of your program seems pretty standard and should be easy to figure out if you think about it. Hope that helps. On Mon, 05 Apr 2004 19:06:00 -0400 "Yaj Lis" wrote: > hello .. i'm new too python.. and programming..and learning slowly... > > i'm creating a bank teller program. It has a list and dictionary. > It askes for the user's input (raw_input) asking for an amount. If the user > enters letters instead of an amount it would count it as 'counterfiet'. > Would i have to write a for loop function? how would i compare to see if it > is a string or an interger?..and i can't figure out how to work it with the > dictionary.. like if i put in $30.25.. it would return "you have 1 $20 bill, > 1 ten, and 1 quarter" .. i'm so frustrated. > > here's what i have so far.. > > wallet=raw_input("money in wallet ") > > for i in conterfeit(x): > > bank={} > bank['h']=100 > bank['F']=50 > bank['T']=20 > bank['t']=10 > bank['f']=5 > bank['o']=1 > bank['q']=.25 > bank['d']=.10 > bank['p']=.01 > > x=wallet > counterfeit(x) > > > I want the program to output something like this...It should report the > total value of the legal money as a floating point value (e.g. 123.45) and > the total number of counterfeit pieces received. > > Money in wallet: asdfasdf > Contained "1" counterfiet piece(s). > Total amount in bank $20.00 > > asking for any help? thanks a lot.. > > _________________________________________________________________ > Watch LIVE baseball games on your computer with MLB.TV, included with MSN > Premium! > http://join.msn.com/?page=features/mlb&pgmarket=en-us/go/onm00200439ave/direct/01/ > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From sigurd at 12move.de Mon Apr 5 20:50:04 2004 From: sigurd at 12move.de (=?iso-8859-1?q?Karl_Pfl=E4sterer?=) Date: Mon Apr 5 20:54:11 2004 Subject: [Tutor] puzzled by modes in os.mkdir() In-Reply-To: <4071E4DB.1050703@po-box.mcgill.ca> (Brian van den Broek's message of "Mon, 05 Apr 2004 18:59:39 -0400") References: <4071E4DB.1050703@po-box.mcgill.ca> Message-ID: On 6 Apr 2004, Brian van den Broek <- bvande@po-box.mcgill.ca wrote: > mkdir( path[, mode]) > Create a directory named path with numeric mode mode. The default > mode is 0777 (octal). On some systems, mode is ignored. Where it > is used, the current umask value is first masked out. > Availability: Macintosh, Unix, Windows. > This is opaque to me, I am afraid. > Here are my questions: > 1) Are the modes here referred to the same ones as it the stat > module? They don't seem to me to be, but the description of > os.cmod(path, mode) references stat and nothing else. You're right they are different. > 2) Either way, I'd appreciate a pointer on what to read so that I > can understand the Lib Ref's description of mkdir. (I don't know > what is going on well enough to do a fruitful google-search.) In > particular, I need to know what "0777 octal" means. (Knowing about > the other options would be nice, too.) You should know Linux/Unix for that. In these systems the file access permissions can be defined for the different groups: the user (the owner of the file), the group (the user group the file owner belongs to) and other (which means all users which are not part of the two other groups). The file access is defined for reading, writing and executing a file. This means it can be written as a binary number with three digits. A binary with three digits has values from 0 to 7 which means it can also be written as a octal number. 777 would mean to allow everyone everything (all three bits set for each group); if you want to know more search for a manpage for the chmod command chmod(1) (that means search for chmod in section 1 of the manpages). > 3) I assume nothing will go wrong if I create a directory using > the default mode argument for mkdir. Is this correct? I am going Since you use WinME the mode has no effect. > 4) What is the preferred syntax in postings, etc., for referring > to functions that require arguments? "mkdir()" seems misleading in > suggesting that it can be called with zero arguments, > "mkdir(path)" seems too verbose. If prefer mkdir(). That's the way functions are written in many postings (assuming languages where you call functions like that). Karl -- Please do *not* send copies of replies to me. I read the list From sigurd at 12move.de Mon Apr 5 21:17:19 2004 From: sigurd at 12move.de (=?iso-8859-1?q?Karl_Pfl=E4sterer?=) Date: Mon Apr 5 21:19:20 2004 Subject: [Tutor] how to catch particular Errno for Exceptions In-Reply-To: <4071E55B.4050101@po-box.mcgill.ca> (Brian van den Broek's message of "Mon, 05 Apr 2004 19:01:47 -0400") References: <4071E55B.4050101@po-box.mcgill.ca> Message-ID: On 6 Apr 2004, Brian van den Broek <- bvande@po-box.mcgill.ca wrote: > how do I catch a specific Errno for an exception? I don't think this can be done. > I have no G: drive and have tried the following code: > import os > try: > os.mkdir('g:\\silly') > except OSError: > print 'OSError caught!' > try: > os.mkdir('gGg:\\sillier') > except OSError, (2,): #what to write here? > print 'OSError Errno 2 caught!' > The first works try clause just fine, the second gives me a "can't > assign to a literal" error when I try to run it out of IDLE. I've That's clear. It tries to assign the error number to `2' which happens to be a literal value. If you want to know the eeror number adfterwards it's written clearly in the Tutorial how to achieve that. [...] > Also, I've just posted three questions all on related, but > distinct topics. Most list I am on prefer 3 msgs in such > situations. Would it be preferred that I had posted all in one? I can only speak for myself: IMO it was absolutely rihgt the way you did it. Karl -- Please do *not* send copies of replies to me. I read the list From dyoo at hkn.eecs.berkeley.edu Mon Apr 5 21:32:27 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Apr 5 21:32:32 2004 Subject: [Tutor] how to catch particular Errno for Exceptions In-Reply-To: <4071E55B.4050101@po-box.mcgill.ca> Message-ID: On Mon, 5 Apr 2004, Brian van den Broek wrote: > how do I catch a specific Errno for an exception? > > I have no G: drive and have tried the following code: > > import os > > try: > os.mkdir('g:\\silly') > except OSError: > print 'OSError caught!' > > try: > os.mkdir('gGg:\\sillier') > except OSError, (2,): #what to write here? > print 'OSError Errno 2 caught!' Hi Brian, According to the library documentation on the builtin exceptions: http://www.python.org/doc/lib/module-exceptions.html we can take the exception instance, and look at its 'errno' attribute value. For example: ### >>> try: ... os.mkdir("/g/silly") ... except OSError, e: ... print e.errno, e.strerror ... 2 No such file or directory ### We capture the exception instance in a name called 'e', and then we can access the individual fields in 'e' to get a more specific reason why things are broken. But how do we know what error code number 2 means? That's when we want to look at the 'errno' module: http://www.python.org/doc/lib/module-errno.html ### >>> import errno >>> errno.errorcode[2] 'ENOENT' ### So in your block of code that tests for the error type, you may want to avoid hardcoding the number '2', and instead use the symbolic error code name errno.ENOENT. Hope this helps! From bvande at po-box.mcgill.ca Mon Apr 5 22:11:28 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Mon Apr 5 22:12:01 2004 Subject: [Tutor] how to check a user input path for dirve existence In-Reply-To: <017a01c41b68$465b6500$6401a8c0@xp> References: <4071E4F4.7050201@po-box.mcgill.ca> <017a01c41b68$465b6500$6401a8c0@xp> Message-ID: <407211D0.6090902@po-box.mcgill.ca> Alan, thanks for the response. I have some reactions interspersed below. Alan Gauld said unto the world upon 05/04/2004 19:46: >>check to an attempt to create the directory, I won't have ruled >>out trying to create, say, J:\spam on a system without a J: drive. > > > This presupposes that drive letters can be part of a path, which > kind of limits things to CP/M(do we get Python for CP/M?) and > Windows/DOS. (I think they are the only OS's that use drive > letters as part of a path? Macs use drives but they have > names and no other distinguishing features...) Yes to the presupposition, but a qualified no to the limit, I think. (Perhaps my intent was ill-described.) What I want is to rule out non-existent drives being referenced in the user input path. Since I work mostly with Win (never have managed to install Linux on my laptop :-( ) that is most relevant to me. But what I was aiming at was to disallow any path which begins X: where X is some string and X: is not a valid drive letter. I might be wrong, but for any OS not using L: (L a letter) as a drive name, the test will still work, albeit trivially since no such string is ever a valid drive name. But you are right, it won't catch non-existent drive references on a box with a different OS. > Given that limitation we know that the drive info can only consist > of a single letter and a colon. So the only thing to test for is: > > if path[1] == ':' That is the limitation on valid drivenames. But I also want to rule out user input like: there:\is\no\telling\what\people\will\type which attempts to use 'users:' as a drive name. So, I don't think if path[1] == ':': do some stuff will work. That only gets it if the input respects the Windows/DOS 'drive names have a single letter' convention. Maybe I am over-fretting about possible input errors, but I am quite new to programming and recently read a text on general style which suggested trying to 'user-error proof' your code as much as possible. Thinking about it more, though, I believe I've answered the question of which method (the one here discussed or try/except clauses) is better. Going this way will have to build a block of code for testing for valid drive letters, one for testing that no disallowed characters ('*', '?', etc.) are included and so forth. Seems exception handling will be the way to go. > Also my brain is still adjusting to Python & Programming after > a weeks break so maybe I'm missing some complexity somewhere > - like network drives maybe... Break? I've heard of them, but thought they were a myth ;-) > Alan G. > Thanks again, Brian vdB From bvande at po-box.mcgill.ca Mon Apr 5 22:33:18 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Mon Apr 5 22:36:50 2004 Subject: [Tutor] how to catch particular Errno for Exceptions In-Reply-To: References: Message-ID: <407216EE.3050001@po-box.mcgill.ca> Danny Yoo said unto the world upon 05/04/2004 21:32: > On Mon, 5 Apr 2004, Brian van den Broek wrote: > >>how do I catch a specific Errno for an exception? > Hi Brian, > > According to the library documentation on the builtin exceptions: > > http://www.python.org/doc/lib/module-exceptions.html > > we can take the exception instance, and look at its 'errno' attribute > value. For example: > Hope this helps! Danny and Karl, thanks for your responses. They clear it up for me considerably! Thanks and best, Brian vdB From photonuv at kudos.net Tue Apr 6 05:03:34 2004 From: photonuv at kudos.net (Gerald Wann) Date: Tue Apr 6 05:04:12 2004 Subject: [Tutor] sys.exit() syntax error Message-ID: <6.0.1.1.1.20040406045814.01ad0cc8@127.0.0.1> Hi - The answer to this is probably so trivial that i'll kick myself for asking... ;-) i'm trying to use the sys.exit() function inside an error trap block and the interpreter keeps telling me there's a syntax error e.g. import sys try: open(file) except: IOError print 'blah' print 'blah' sys.exit() python doesn't like this... and says there's a syntax error at the sys.exit() line however, when i dedent the sys.exit() call outside the except: block, it runs just fine, (except for the fact that it shuts the whole thing down ;-) What am i missing here? I'm using Komodo 2.5 IDE and python 2.2.3 TIA Jerry From op73418 at mail.telepac.pt Tue Apr 6 05:25:40 2004 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Tue Apr 6 05:23:02 2004 Subject: [Tutor] why "self" in methods? In-Reply-To: References: <05d370h6tdlfv5etqse9o739pknllfhfba@4ax.com> Message-ID: Em Mon, 5 Apr 2004 16:20:40 -0700 (PDT), Marilyn Davis atirou este peixe aos pinguins: >> Suppose that self was a keyword naming the implicit object that's >> passed to methods. Consider the following example: >> >> class Outer(object): >> def amethod(arg): >> class Inner(object): >> def amethod(arg): >> self.arg = arg #What's self here? >> return inner() >> >> Is self from the inner or from the outer? The "logical" answer would >> be from the inner amethod from the Inner class. But then the outer >> self is shadowed -- not good. And since it's implicit... you know > >I think that attributes of Outer are not visible from Inner anyway? >Do I have that right? > Well, if self is implicit, inside the Inner amethod only one self can be visible. It seems logical that the it be the Inner self. But then, because of impliciteness, you cannot get at the Outer self. Now, let us try the same with the current rules. class Outer(object) def amethod(outerself, arg): outerself.arg = arg class Inner(object): def amethot(self, arg): self.arg = arg*(outerself.arg) return Inner(1) See the difference? Because of explicit naming, in the Inner amethod, outerself is visible (because of nested scopes). Of course, you can still get around this in the implicit case by renaming, but IMHO, added to the other reasons, I think implicit self is bad. With my best regards, G. Rodrigues From op73418 at mail.telepac.pt Tue Apr 6 05:35:15 2004 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Tue Apr 6 05:32:35 2004 Subject: [Tutor] sys.exit() syntax error In-Reply-To: <6.0.1.1.1.20040406045814.01ad0cc8@127.0.0.1> References: <6.0.1.1.1.20040406045814.01ad0cc8@127.0.0.1> Message-ID: Em Tue, 06 Apr 2004 05:03:34 -0400, Gerald Wann atirou este peixe aos pinguins: >Hi - > >The answer to this is probably so trivial that i'll kick myself for >asking... ;-) > >i'm trying to use the sys.exit() function inside an error trap block and >the interpreter keeps telling me there's a syntax error e.g. > >import sys > >try: > open(file) >except: IOError ^^^^^^^^ Should be (notice the position of the colon) except IOError: > print 'blah' > print 'blah' > sys.exit() > >python doesn't like this... and says there's a syntax error at the >sys.exit() line > >however, when i dedent the sys.exit() call outside the except: block, it >runs just fine, (except for the fact that it shuts the whole thing down ;-) > >What am i missing here? > Exactly. Remember, the use of a : tells Python that a new block is starting. Strictly speaking the : is redundant, because indenting already tells Python so, but visually, the presence of the : helps a lot. Python complains with a syntax error because if the block is in the same (that is try: except: ) then . can only have one line (excluding continuation lines, etc.). Something like try: except: Is ruled out -- and it is obvious isn't it. It's not indented right! With my best regards, G. Rodrigues From jmpurser at comcast.net Tue Apr 6 05:34:16 2004 From: jmpurser at comcast.net (John M. Purser) Date: Tue Apr 6 05:33:34 2004 Subject: [Tutor] sys.exit() syntax error In-Reply-To: <6.0.1.1.1.20040406045814.01ad0cc8@127.0.0.1> Message-ID: Yep, this is a self kicker. The problem is in the line: except: IOError try this instead: except IOError: John Purser -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org]On Behalf Of Gerald Wann Sent: Tuesday, April 06, 2004 3:04 AM To: tutor@python.org Subject: [Tutor] sys.exit() syntax error Hi - The answer to this is probably so trivial that i'll kick myself for asking... ;-) i'm trying to use the sys.exit() function inside an error trap block and the interpreter keeps telling me there's a syntax error e.g. import sys try: open(file) except: IOError print 'blah' print 'blah' sys.exit() python doesn't like this... and says there's a syntax error at the sys.exit() line however, when i dedent the sys.exit() call outside the except: block, it runs just fine, (except for the fact that it shuts the whole thing down ;-) What am i missing here? I'm using Komodo 2.5 IDE and python 2.2.3 TIA Jerry _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From marilyn at deliberate.com Tue Apr 6 13:02:08 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Tue Apr 6 13:02:14 2004 Subject: [Tutor] why "self" in methods? (fwd) Message-ID: I realize that I only sent this to Gon?alo: -- ---------- Forwarded message ---------- Date: Mon, 5 Apr 2004 16:20:40 -0700 (PDT) From: Marilyn Davis To: Gon?alo Rodrigues Subject: Re: [Tutor] why "self" in methods? On Mon, 5 Apr 2004, Gon?alo Rodrigues wrote: > Em Mon, 5 Apr 2004 18:12:21 +0100, "Alan Gauld" > atirou este peixe aos pinguins: > > >> Also, about the self controversy, think about nested definitions > >> of classes. You get into trouble with the implicit self thingy. > > > >Really? How so? Surely that's merely a matter of scoping. > >I agree that self being explicit is "a good thing" but > >it is not necessary, other languages seem to manage quite > >well without it. > > > > [Answering also to Marylin Davis] > > Suppose that self was a keyword naming the implicit object that's > passed to methods. Consider the following example: > > class Outer(object): > def amethod(arg): > class Inner(object): > def amethod(arg): > self.arg = arg #What's self here? > return inner() > > Is self from the inner or from the outer? The "logical" answer would > be from the inner amethod from the Inner class. But then the outer > self is shadowed -- not good. And since it's implicit... you know I think that attributes of Outer are not visible from Inner anyway? Do I have that right? > where I'm getting at. No. I don't. > > Explicit is better than implicit. And although from the top of my head > I can't remember a use case of unbound methods, *I have used them* > several times. Suppose there were no unbound methods, what should be > > class Outer(object): > def amethod(arg): > .... > > Outer.amethod > > If methods are attributes of the class object, then the above must > return something sensible. And if it is to remain callable, well, it > must receive the instance explicitely as a parameter. Perhaps you > could write some wrappers, etc. that would do this for you, but > somehow I think that without the explicit self it would not be very > elegant. Besides, it gives a very handy syntax for calling a super > class method that is overriden. > > Also in class methods, in meta methods, etc. the explicit self allows > me to call the self, cls, that is > > > class Outer(object): > def method(cls): > .... > method = classmethod(method) > > which IMHO is much better from a raedability point of view > > Read the FAQ entry on this for a couple more reasons. > > So, my verdict is definitely: explicit self is a *very good* Python > feature and a clear mark of excellent design. And to the stake with > the blasphemers that dare oppose the BDFL :-) Gulp. I googled for what GvR says: 6.9. Q. Why must 'self' be declared and used explicitly in method definitions and calls? A. By asking this question you reveal your C++ background. :-) When I added classes, this was (again) the simplest way of implementing methods without too many changes to the interpreter. I borrowed the idea from Modula-3. It turns out to be very useful, for a variety of reasons. First, it makes it more obvious that you are using a method or instance attribute instead of a local variable. Reading "self.x" or "self.meth()" makes it absolutely clear that an instance variable or method is used even if you don't know the class definition by heart. In C++, you can sort of tell by the lack of a local variable declaration (assuming globals are rare or reasily recognizable) -- but in Python, there are no local variable declarations, so you'd have to look up the class definition to be sure. Second, it means that no special syntax is necessary if you want to explicitly reference or call the method from a particular class. In C++, if you want to use a method from base class that is overridden in a derived class, you have to use the :: operator -- in Python you can write baseclass.methodname(self, ). This is particularly useful for __init__() methods, and in general in cases where a derived class method wants to extend the base class method of the same name and thus has to call the base class method somehow. Lastly, for instance variables, it solves a syntactic problem with assignment: since local variables in Python are (by definition!) those variables to which a value assigned in a function body (and that aren't explicitly declared global), there has to be some way to tell the interpreter that an assignment was meant to assign to an instance variable instead of to a local variable, and it should preferably be syntactic (for efficiency reasons). C++ does this through declarations, but Python doesn't have declarations and it would be a pity having to introduce them just for this purpose. Using the explicit "self.var" solves this nicely. Similarly, for using instance variables, having to write "self.var" means that references to unqualified names inside a method don't have to search the instance's directories. -- > > With my best regards, > G. Rodrigues > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- From marilyn at deliberate.com Tue Apr 6 13:13:01 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Tue Apr 6 13:13:05 2004 Subject: [Tutor] why "self" in methods? In-Reply-To: Message-ID: On Tue, 6 Apr 2004, Gon?alo Rodrigues wrote: > Em Mon, 5 Apr 2004 16:20:40 -0700 (PDT), Marilyn Davis > atirou este peixe aos pinguins: > > >> Suppose that self was a keyword naming the implicit object that's > >> passed to methods. Consider the following example: > >> > >> class Outer(object): > >> def amethod(arg): > >> class Inner(object): > >> def amethod(arg): > >> self.arg = arg #What's self here? > >> return inner() > >> > >> Is self from the inner or from the outer? The "logical" answer would > >> be from the inner amethod from the Inner class. But then the outer > >> self is shadowed -- not good. And since it's implicit... you know > > > >I think that attributes of Outer are not visible from Inner anyway? > >Do I have that right? No. I didn't have that right! And that was my confusion. > > > > Well, if self is implicit, inside the Inner amethod only one self can > be visible. It seems logical that the it be the Inner self. But then, > because of impliciteness, you cannot get at the Outer self. > > Now, let us try the same with the current rules. > > class Outer(object) > def amethod(outerself, arg): > outerself.arg = arg > class Inner(object): > def amethot(self, arg): > self.arg = arg*(outerself.arg) > return Inner(1) > > See the difference? Because of explicit naming, in the Inner amethod, > outerself is visible (because of nested scopes). Indeed. I ran your code: class Outer(object): def amethod(outerself, arg): outerself.arg = arg class Inner(object): def amethod(self, arg): self.arg = arg print self.arg, outerself.arg return Inner(1) ######################################## # bash-2.05a$ python2.2 -i outer.py # >>> x = Outer # >>> x = Outer() # >>> y = x.amethod('hey') # >>> y.amethod('ho') # ho hey # >>> > > Of course, you can still get around this in the implicit case by > renaming, but IMHO, added to the other reasons, I think implicit self > is bad. Explicit is better for sure! Thank you for your patience! Marilyn > > With my best regards, > G. Rodrigues > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- From alan.gauld at blueyonder.co.uk Tue Apr 6 13:28:11 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Apr 6 13:28:03 2004 Subject: [Tutor] why "self" in methods? References: <05d370h6tdlfv5etqse9o739pknllfhfba@4ax.com> Message-ID: <003801c41bfc$88f9fe50$6401a8c0@xp> >> class Outer(object): >> def amethod(arg): >> class Inner(object): >> def amethod(arg): >> self.arg = arg #What's self here? >> return inner() >> > >Well, if self is implicit, inside the Inner amethod only one self can >be visible. It seems logical that the it be the Inner self. But then, >because of impliciteness, you cannot get at the Outer self. The C++ approach to this would be to use the scoping operator '::' so you could access the data, within the scoping rules, using Outer::amethod(). Although in C++ nested classes are discouraged and friends preferred: class Inner{ friend class Outer; private: int foo; ...}; class Outer{ Inner myInner; int& bar = myInner.foo; // direct access to inner members here ...}; Which is all pretty messy and shows why explicit self is better! > class Outer(object) > def amethod(outerself, arg): > outerself.arg = arg > class Inner(object): > def amethot(self, arg): > self.arg = arg*(outerself.arg) > return Inner(1) > > See the difference? Neat! Although I still haven't thought of a need to do that, but its nice to know you can! :-) Alan G. From nick at javacat.f2s.com Tue Apr 6 13:43:15 2004 From: nick at javacat.f2s.com (Nick Lunt) Date: Tue Apr 6 13:41:57 2004 Subject: [Tutor] File Access In-Reply-To: <1361203671047.20040405175353@columbus.rr.com> References: <1081099612.1261.16.camel@localhost.localdomain> <1081131210.2092.5.camel@laptop.venix.com> <1081184884.15243.18.camel@localhost.localdomain> <1361203671047.20040405175353@columbus.rr.com> Message-ID: <20040406184315.6e2bf036.nick@javacat.f2s.com> On Mon, 5 Apr 2004 17:53:53 -0400 "R. Alan Monroe" wrote: > If you were desperate you could look at the source code for gnu's > version of the good old tail command. Ha, I aint that desperate. The last thing I want to do is get my old C books out. I never really got my head round pointers and I don't wanna try again now ;) > One thing you could try is reading successively larger and larger > chunks from the end of the file, like powers of two (1 byte, 2 bytes, > 4 bytes, 8 bytes, 16 bytes, etc.) until you grab a chunk that has a \n > in it, then work forward from there. Haven't personally tried this, > though. I guess that would work, but it seems a bit of a fudge doesn't it ? I could also pad the lines out before they are written to the file, then when I seek to the end of the file I would know how many bytes to rewind to get to the start of the line. So it's pad the lines so each line is x bytes, which again seems like a fudge. Or use 'for line in file' which would be slow on a file with many lines. Ho hum, I still don't know which is best. Cheers Nick. From mjekl at clix.pt Tue Apr 6 17:05:40 2004 From: mjekl at clix.pt (mjekl@clix.pt) Date: Tue Apr 6 17:05:53 2004 Subject: [Tutor] Generating OpenOffice files or Automation Message-ID: <20040406210540.11685.qmail@maboque.srv.clix.pt> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040406/6c327861/attachment.html From tim at johnsons-web.com Tue Apr 6 22:04:28 2004 From: tim at johnsons-web.com (Tim Johnson) Date: Tue Apr 6 22:04:05 2004 Subject: [Tutor] MySQLdb: dropping zeroes! Message-ID: <20040407020428.GY1860@johnsons-web.com> Hello All: I'm using MySQLdb to read and write from a database where I have values stored as a decimal(10,2) datatype. To illustrate: The following value which is stored as 0.94 is read back by MySQLdb with the DictCursor option as 0.94 so far so good! But, alas! A value stored as 1.00 is read back by MySQLdb with the DictCursor option as 1.0 That is not good! My type-checking will flag that value as invalid because a precision of 2 places to the right of the decimal point is expected. I can handle this with my own code, but perhaps someone can tell me if the MySQLdb api can take care of this with some internal setting. TIA tim -- Tim Johnson http://www.alaska-internet-solutions.com From py at gogol.humnet.ucla.edu Wed Apr 7 02:15:02 2004 From: py at gogol.humnet.ucla.edu (peter hodgson) Date: Wed Apr 7 02:15:08 2004 Subject: [Tutor] trying to understand the logic of functions Message-ID: <200404070615.i376F2WD017259@nightshade.noc.ucla.edu> On Monday 22 March 2004 20:47, python_simpleton wrote that terms like 'parameter' were confusing; here's another newbie's attempt to sort out parameter's node of terms: 1. a function is defined thus: def NAME(LIST OF PARAMETERS): STATEMENTS 2. when a function is called: it takes [gets passed] an argument [value or variable], and returns a result [return value], or performs an action; 3. variables are the boxes for values; parameters are the variables used in the definition of a function, inside the parentheses, to refer to the value[s] which will be passed as arguments when the function is called; 4. function names, as well as the names of variables [incl. parameters] can be arbitrary; they are not what gets stored in memory and manipulated by the function when it is called; they are just labelled boxes; 5. statements can assign values to variables; an example is a statement which assigns the return value of a function to a variable; e.g.: variable = function (argument); thus, a parameter [which is a variable] can be a function, i.e. its result is the argument of its parent function: e.g.: fun1 (fun2()), or even fun1 (fun2(fun3(argument))) From glingl at aon.at Wed Apr 7 03:13:14 2004 From: glingl at aon.at (Gregor Lingl) Date: Wed Apr 7 03:12:27 2004 Subject: [Tutor] trying to understand the logic of functions In-Reply-To: <200404070615.i376F2WD017259@nightshade.noc.ucla.edu> References: <200404070615.i376F2WD017259@nightshade.noc.ucla.edu> Message-ID: <4073AA0A.9080503@aon.at> Hi Peter! I tried to rewrite your recent posting, just using different terms. I hope this sheds a different light on this topic. What do you think of this? 1. a function is defined thus: def NAME(LIST OF PARAMETERS): STATEMENTS 2. when a function is called: it takes [gets passed] an argument [object (i. e. const or name or expression (*))], and returns a result [return value, i.e. another object], or performs an action; 3. variables are the names for objects; parameters are the names used in the definition of a function, inside the parentheses, to refer to the objects which will be passed as arguments when the function is called; 4. function names, as well as parameter names can be arbitrary; they are not what gets stored in memory and manipulated by the function when it is called; they are just names; 5. statements can assign names to objects; an example is a statement which assigns a name to the object returned by a function e.g.: name = function (argument); thus, a parameter [which is a name] can be the result of a *function call*, i.e. its result is the argument of its parent function: e.g.: fun1 (fun2()), or even fun1 (fun2(fun3(argument))) There is a very important difference between a function call and a function. if you use a function call as argument, the resulting object is bound to the parameter (name). But you can also use function(-objects) as arguments, in order to call them somewhere in the body of the function to be defined. I think this is a *somewhat* advanced topic - therefore here a very short example to clarify it: >>> def square(x): return x*x >>> def cubus(x): return x*x*x >>> def table(fun): for x in range(5): print x, fun(x) >>> table(square) 0 0 1 1 2 4 3 9 4 16 >>> table(cubus) 0 0 1 1 2 8 3 27 4 64 >>> (*) strictly speaking constants and names are also expression (albeit simple ones in contrast to compound expressions) Regards, Gregor peter hodgson schrieb: >On Monday 22 March 2004 20:47, python_simpleton wrote that terms like >'parameter' were confusing; > >here's another newbie's attempt to sort out parameter's node of terms: > >1. a function is defined thus: > > def NAME(LIST OF PARAMETERS): > STATEMENTS > >2. when a function is called: > > it takes [gets passed] an argument [value or variable], > > and returns a result [return value], > or performs an action; > >3. variables are the boxes for values; > > parameters are the variables used in the definition of a function, > inside the parentheses, to refer to the value[s] which will be > passed as arguments when the function is called; > >4. function names, as well as the names of variables [incl. > parameters] can be arbitrary; they are not what gets stored in > memory and manipulated by the function when it is called; they are > just labelled boxes; > >5. statements can assign values to variables; an example is a > statement which assigns the return value of a function to a > variable; e.g.: > > variable = function (argument); > >thus, a parameter [which is a variable] can be a function, >i.e. its result is the argument of its parent function: e.g.: > > fun1 (fun2()), or even > fun1 (fun2(fun3(argument))) > > > > > > > > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > From scot at possum.in-berlin.de Wed Apr 7 09:21:25 2004 From: scot at possum.in-berlin.de (Scot W. Stevenson) Date: Wed Apr 7 09:24:20 2004 Subject: [Tutor] Python suddenly finding ".DS_Store" files in folder Message-ID: <200404071521.25430.scot@possum.in-berlin.de> Hello there, Part of a Python program I'm writing uses the os.listdir("myfolder") call to get a list of the files in a folder (Python 2.3.3, Mac OS X 10.3.3). Suddenly, without me doing anything I'm aware of, I have a file .DS_Store in my directory, which screws up all kinds of things. I can't see how Python is doing this (but I'm writing here just to be sure), and Mac OS X shouldn't be running around inserting files into my Python folders, either, and, finally, I'm not happy about os.listdir() finding hidden files without me explicitly telling it to. That is, uh, sort of the reason for having them hidden... Does any of this make any sense, and if yes, does anybody have any suggestions? Thank you, Y, Scot -- Scot W. Stevenson - Panketal, Germany From godoy at ieee.org Wed Apr 7 10:30:09 2004 From: godoy at ieee.org (Jorge Godoy) Date: Wed Apr 7 10:40:42 2004 Subject: [Tutor] Monte Carlo method modules & references Message-ID: Hi! Anyone can give me some pointers on where to look after Monte Carlo method with Python? As of now, I'm going through some links from the Google search of "Monte Carlo python", but some opinion is greatly appreciated and will reduce the time I'll spend here. Thanks in advance, -- Godoy. From pythonTutor at venix.com Wed Apr 7 08:33:25 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Wed Apr 7 10:41:24 2004 Subject: [Tutor] MySQLdb: dropping zeroes! In-Reply-To: <20040407020428.GY1860@johnsons-web.com> References: <20040407020428.GY1860@johnsons-web.com> Message-ID: <1081341204.7860.15.camel@laptop.venix.com> The MySQLdb module will return decimal values as Python floats. The floats are binary representations of the underlying decimal values and are as accurate as possible. All integers are exactly correct. Remember that 1.0 == 1.00 == 1.000000 You may have a notation where the number of digits after the decimal point represents the accuracy of a measurement, but that is not how the computer works. >>> "%7.4f" % 1.0 ' 1.0000' >>> "%07.4f" % 1.0 '01.0000' You can use format strings to control how many decimal places get displayed. I'm not sure what your type checking is trying to do. On Tue, 2004-04-06 at 22:04, Tim Johnson wrote: > Hello All: > I'm using MySQLdb to read and write from a database where > I have values stored as a decimal(10,2) datatype. > To illustrate: > The following value which is stored as > 0.94 > is read back by MySQLdb with the DictCursor option as > 0.94 > so far so good! > But, alas! A value stored as > 1.00 > is read back by MySQLdb with the DictCursor option as > 1.0 > > That is not good! My type-checking will flag that value as invalid > because a precision of 2 places to the right of the decimal point > is expected. > > I can handle this with my own code, but perhaps someone can tell > me if the MySQLdb api can take care of this with some internal > setting. > > TIA > tim -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From tim at johnsons-web.com Wed Apr 7 11:56:36 2004 From: tim at johnsons-web.com (Tim Johnson) Date: Wed Apr 7 11:56:10 2004 Subject: [Tutor] MySQLdb: dropping zeroes! In-Reply-To: <1081341204.7860.15.camel@laptop.venix.com> References: <20040407020428.GY1860@johnsons-web.com> <1081341204.7860.15.camel@laptop.venix.com> Message-ID: <20040407155636.GC1860@johnsons-web.com> * Lloyd Kvam [040407 06:49]: > The MySQLdb module will return decimal values as Python floats. The > floats are binary representations of the underlying decimal values and > are as accurate as possible. All integers are exactly correct. Hi Lloyd: See my quote below > Remember that 1.0 == 1.00 == 1.000000 Of course > You may have a notation where the number of digits after the decimal > point represents the accuracy of a measurement, but that is not how the > computer works. > > >>> "%7.4f" % 1.0 > ' 1.0000' > >>> "%07.4f" % 1.0 > '01.0000' > > You can use format strings to control how many decimal places get > displayed. :-) > I'm not sure what your type checking is trying to do. Client wants data verified in an input form as having two digits following the decimal point. So ... when data is read back to a form when being edited, it would fail a javascript check. However, either the js check can be modified or an extra zero can be added, via something like fstring = %7.2f" % floatval # and fstring = fstring.lstrip() # not thoroughly tested. To quote the mysql manual: "The DECIMAL type is considered a numeric type (as is its synonym, NUMERIC), but such values are stored as strings." So I thought there might be a way to override the MySQLdb type conversion and get them back as strings. thanks Lloyd! tim > On Tue, 2004-04-06 at 22:04, Tim Johnson wrote: > > Hello All: > > I'm using MySQLdb to read and write from a database where > > I have values stored as a decimal(10,2) datatype. > > To illustrate: > > The following value which is stored as > > 0.94 > > is read back by MySQLdb with the DictCursor option as > > 0.94 > > so far so good! > > But, alas! A value stored as > > 1.00 > > is read back by MySQLdb with the DictCursor option as > > 1.0 > > > > That is not good! My type-checking will flag that value as invalid > > because a precision of 2 places to the right of the decimal point > > is expected. > > > > I can handle this with my own code, but perhaps someone can tell > > me if the MySQLdb api can take care of this with some internal > > setting. > > > > TIA > > tim > -- > > Lloyd Kvam > Venix Corp. > 1 Court Street, Suite 378 > Lebanon, NH 03766-1358 > > voice: 603-653-8139 > fax: 801-459-9582 -- Tim Johnson http://www.alaska-internet-solutions.com From Christian.Wyglendowski at greenville.edu Wed Apr 7 12:05:15 2004 From: Christian.Wyglendowski at greenville.edu (Christian Wyglendowski) Date: Wed Apr 7 12:05:27 2004 Subject: [Tutor] File Access Message-ID: > -----Original Message----- > > > Hi folks, > > I need to go to the last line of a file and then to the start > of a delimited section of that line, such as > > $ cat file.txt > var1|var2|var3|var4|var5|var6|var7 > var1|var2|var3|var4|var5|var6 > var1|var2|var3|var4|var5|var6 > > What I want to do is goto the last line in the imaginary > file.txt above and extract var3 for example. You might want to check out the following recipe at the python cookbook. It is kind of a basic tail written in python. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/276149 Christian http://www.dowski.com From project5 at redrival.net Wed Apr 7 15:05:31 2004 From: project5 at redrival.net (Andrei) Date: Wed Apr 7 15:05:41 2004 Subject: [Tutor] Re: Generating OpenOffice files or Automation References: <20040406210540.11685.qmail@maboque.srv.clix.pt> Message-ID: <169dj9xqyug9a.1oi92zpb11vt3.dlg@40tude.net> mjekl@clix.pt wrote on Tue, 06 Apr 2004 22:05:40 +0100: > I've been considering Automation to generate OpenOffice files with Python (this lead me to using pyUNO and the Python 22 included in the > distribution of OpenOffice). My second alternative is generating OpenOffice XML files from Python. > I guess (since I'm a beginner in Programming) both approaches are suitable for template (template like) generation of files. I have a feeling that using > XML would probably be simpler ? I'm tempted to share that feeling, particularly if you only need a relatively limited subset of what OpenOffice offers: I think it would prove easier than learning pyUNO properly. Btw, you could perhaps even consider (X)HTML, which OpenOffice should be able to import. On the other hand, if you plan to do more OOo stuff later, it's probably worth investing some time in learning how to use pyUno now. > Can anyone give me some ideas / impressions on this.< /p> The formats are such that if you know what you want, you can probably just write a 'template' for it in OO Writer, save, unzip, open the xml in some text editor and use that as a template. This might be sufficient for relatively simple stuff, without even reading specs :). By the way, please try to post in plain text only or plain text and HTML (but not just HTML). Some people won't even see your message if it's in HTML format and others (like me) will have to do extra work to get to the HTML contents. -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From michele.alzetta at aliceposta.it Wed Apr 7 15:28:21 2004 From: michele.alzetta at aliceposta.it (Michele Alzetta) Date: Wed Apr 7 15:28:27 2004 Subject: [Tutor] Monte Carlo method modules & references In-Reply-To: References: Message-ID: <1081366100.6123.5.camel@localhost> Monte Carlo methods are very well supported by R, I believe. ( http://cran.r-project.org ) You can call R from Python with RS module. www.omegahat.org/RSPython/ -- Michele Alzetta -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Questa parte del messaggio =?ISO-8859-1?Q?=E8?= firmata Url : http://mail.python.org/pipermail/tutor/attachments/20040407/fd7884cd/attachment.bin From michele.alzetta at aliceposta.it Wed Apr 7 16:12:13 2004 From: michele.alzetta at aliceposta.it (Michele Alzetta) Date: Wed Apr 7 16:12:23 2004 Subject: [Tutor] understanding fileinput Message-ID: <1081368733.6123.22.camel@localhost> I recently tried to solve a problem I had: changing a certain pattern of text within all files in a certain directory and changing any filename with the same pattern in the same fashion. [Note: I have solved my actual problem with the judicious use of sed + a bash script called renna - and secondly by finding the correct option of wget to use when downloading asp web pages :-) ] However, it seemed like an interesting excercise in learning python. At first I thought it ought to be very easy to code this, but it isn't really for a newbie like me. This is what I've come up with at the moment: #!/usr/bin/python import os, sys, re, fileinput try: target_folder = (sys.argv[1]) original_pattern = (sys.argv[2]) result_pattern = (sys.argv[3]) except: print "\n Substitutes a string with another in all files of a specified directory and its subdirectories" print "Use: ./MyScript.py directory string other_string" sys.exit() for folders, folder, filelist in os.walk(target_folder): for filename in filelist: file = os.path.join(folders,filename) for line in fileinput.input(file,'inplace=1'): line = re.sub(original_pattern,result_pattern,line) print line # fileinput.close() I haven't yet tried to add the code for changing filenames but it seems pretty straightforward: re.sub + os.rename, I suppose. Two questions here: - this correctly changes the pattern in filecontent but for some reason adds a newline for every newline originally present in the file at every pass - why ? - from documentation of fileinput I thought fileinput.close() was necessary, but actually commenting it out doesn't change anything for good or ill in the working of the program. -- Michele Alzetta -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Questa parte del messaggio =?ISO-8859-1?Q?=E8?= firmata Url : http://mail.python.org/pipermail/tutor/attachments/20040407/6c65afea/attachment.bin From dyoo at hkn.eecs.berkeley.edu Wed Apr 7 16:15:37 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Apr 7 16:15:54 2004 Subject: [Tutor] Python suddenly finding ".DS_Store" files in folder In-Reply-To: <200404071521.25430.scot@possum.in-berlin.de> Message-ID: On Wed, 7 Apr 2004, Scot W. Stevenson wrote: > Part of a Python program I'm writing uses the os.listdir("myfolder") > call to get a list of the files in a folder (Python 2.3.3, Mac OS X > 10.3.3). Suddenly, without me doing anything I'm aware of, I have a > file > > .DS_Store > > in my directory, which screws up all kinds of things. I can't see how > Python is doing this (but I'm writing here just to be sure), and Mac OS > X shouldn't be running around inserting files into my Python folders, > either Hi Scot, Actually, it _is_ Mac OS X running around inserting files. The '.DS_Store' file contains information that the Mac OS X Finder uses to store the folder's state (like window position, the type of view being used, etc...) > , and, finally, I'm not happy about os.listdir() finding hidden files > without me explicitly telling it to. That is, uh, sort of the reason for > having them hidden... os.listdir() is just being too truthful, then. *grin* Files that begin with a dot in Unix aren't really hidden: they're just not displayed by default by the standard 'ls' file listing command (and other utilities that follow the leading-dot-should-be-invisible convention.) And if we want our programs to follow the same conventions, we'll have to filter out those filenames ourselves. If you write a small helper function that filters out os.listdir()'s output, that should do the trick. Hope this helps! From godoy at ieee.org Wed Apr 7 16:28:27 2004 From: godoy at ieee.org (Jorge Godoy) Date: Wed Apr 7 16:30:42 2004 Subject: [Tutor] Re: Monte Carlo method modules & references References: <1081366100.6123.5.camel@localhost> Message-ID: <6s4ek1-tjs.ln1@wintermute.g2ctech> On Qua 07 Abr 2004 16:28, Michele Alzetta wrote: > Monte Carlo methods are very well supported by R, I believe. > ( http://cran.r-project.org ) > > You can call R from Python with RS module. > www.omegahat.org/RSPython/ This would add more requisites to the application, reducing its portability or the easiness to install it. But I'm going after the links you posted. Thanks Michele. -- Godoy. From scot at possum.in-berlin.de Wed Apr 7 19:43:25 2004 From: scot at possum.in-berlin.de (Scot W. Stevenson) Date: Wed Apr 7 19:45:50 2004 Subject: [Tutor] Python suddenly finding ".DS_Store" files in folder In-Reply-To: References: Message-ID: <200404080143.25807.scot@possum.in-berlin.de> Hello Danny, > Actually, it _is_ Mac OS X running around inserting files. Ye Gods. How strange. They certainly don't tell you that in the switcher ads, do they ... > And if we want our programs to follow the same conventions, we'll have to > filter out those filenames ourselves. If you write a small helper > function that filters out os.listdir()'s output, that should do the trick. Yeah, now I have an ugly hack that checks if the file is .DS_Store and if so, skips it. I think I might want to take another look at Yellow Dog Linux... Thank you for the help! Y, Scot -- Scot W. Stevenson - Panketal, Germany From klappnase at freenet.de Wed Apr 7 20:28:49 2004 From: klappnase at freenet.de (Michael Lange) Date: Wed Apr 7 20:29:27 2004 Subject: [Tutor] understanding fileinput In-Reply-To: <1081368733.6123.22.camel@localhost> References: <1081368733.6123.22.camel@localhost> Message-ID: <20040408022849.676b9c90.klappnase@freenet.de> On Wed, 07 Apr 2004 22:12:13 +0200 Michele Alzetta wrote: Hi Michele, > #!/usr/bin/python > import os, sys, re, fileinput > > try: > target_folder = (sys.argv[1]) > original_pattern = (sys.argv[2]) > result_pattern = (sys.argv[3]) > except: > print "\n Substitutes a string with another in all files of a > specified directory and its subdirectories" > print "Use: ./MyScript.py directory string other_string" > sys.exit() > for folders, folder, filelist in os.walk(target_folder): > for filename in filelist: > file = os.path.join(folders,filename) > for line in fileinput.input(file,'inplace=1'): > line = re.sub(original_pattern,result_pattern,line) > print line > # fileinput.close() > > I haven't yet tried to add the code for changing filenames but it seems > pretty straightforward: re.sub + os.rename, I suppose. > > Two questions here: > > - this correctly changes the pattern in filecontent but for some reason > adds a newline for every newline originally present in the file at every > pass - why ? > I guess "print line" adds the newline; try "sys.stdout.write(line)" instead. > - from documentation of fileinput I thought fileinput.close() was > necessary, but actually commenting it out doesn't change anything for > good or ill in the working of the program. > fileinput.input() closes the file itself when the end is reached; You can use the close() method to stop iterating over the file ( and start iterating over the next file if you pass a tuple of several files to input() ). This might be useful if you look for a certain pattern in large files to speed up the whole thing I think. (by the way: be careful using "file" as a variable name, it's a built in function) > -- > Michele Alzetta > I hope this helps Michael From dyoo at hkn.eecs.berkeley.edu Wed Apr 7 22:15:17 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Apr 7 22:15:22 2004 Subject: [Tutor] Python suddenly finding ".DS_Store" files in folder [use helper functions] In-Reply-To: <200404080143.25807.scot@possum.in-berlin.de> Message-ID: On Thu, 8 Apr 2004, Scot W. Stevenson wrote: > > Actually, it _is_ Mac OS X running around inserting files. > > Ye Gods. How strange. They certainly don't tell you that in the switcher > ads, do they ... Hi Scot, The page: http://www.bresink.de/osx/TinkerToolFAQ.html is one place that talks about them in a little more detail. Actually, there appears to be a lot of controversy about the implementation of the '.DS_Store' mechanism in the Finder; I googled for it, and the first thing that comes up is a program to remove '.DS_Store' files. *grin* > > And if we want our programs to follow the same conventions, we'll have > > to filter out those filenames ourselves. If you write a small helper > > function that filters out os.listdir()'s output, that should do the > > trick. > > Yeah, now I have an ugly hack that checks if the file is .DS_Store and > if so, skips it. It shouldn't have to be ugly, if we add one level of indirection: ### def mylistdir(directory): """A specialized version of os.listdir() that ignores files that start with a leading period.""" filelist = os.listdir(directory) return [x for x in filelist if not (x.startswith('.'))] ### We can use 'mylistdir()' function instead of os.listdir(). By writing a helper function, we can limit the scope of the change to, effectively, a few lines. Hope this helps! From bvande at po-box.mcgill.ca Thu Apr 8 02:49:18 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Thu Apr 8 02:50:50 2004 Subject: [Tutor] can you turn strings from a file into raw strings? Message-ID: <4074F5EE.2050304@po-box.mcgill.ca> Hi all, I am wondering if there is anyway to force the output of somefile.readline() to be a raw string? I can see that you wouldn't be able to fetch the readline as raw (you'd loose the \n marking EOL). But once you have the readline, can it be turned into a raw string? I've looked through the docs, but they only talk of 'r' being prepended to string literals. But I think my desire must come up from time to time, so I wonder if there is a way I didn't find. (I'm using Python 2.3.3.) I thought about trying the replace string method, but since there is a lot of variability in characters following an escape sequence, it seemed like I'd have to go with regex and I'm not quite ready for that, I think. Would regex work? Is there an easier way? Why I care: I am wanting to store a series of directory names in a plain text config file. I can read the file just fine and have can do all I've tried with the output of the readline() method so far. But, since I am on a Windows machine, I would prefer to turn the readline() output into a raw string. Otherwise, the directory separator '\' gets read as an escape character. I know I can solve it by using '/' in place of '\' in the data, but I don't want things to break if I forget when editing the config file that I need to use '/'s. Thanks and best, Brian vdB From sigurd at 12move.de Thu Apr 8 12:32:10 2004 From: sigurd at 12move.de (=?iso-8859-1?q?Karl_Pfl=E4sterer?=) Date: Thu Apr 8 12:37:34 2004 Subject: [Tutor] can you turn strings from a file into raw strings? In-Reply-To: <4074F5EE.2050304@po-box.mcgill.ca> (Brian van den Broek's message of "Thu, 08 Apr 2004 02:49:18 -0400") References: <4074F5EE.2050304@po-box.mcgill.ca> Message-ID: On 8 Apr 2004, Brian van den Broek <- bvande@po-box.mcgill.ca wrote: [...] > Why I care: > I am wanting to store a series of directory names in a plain text > config file. I can read the file just fine and have can do all I've > tried with the output of the readline() method so far. But, since I am > on a Windows machine, I would prefer to turn the readline() output > into a raw string. Otherwise, the directory separator '\' gets read as > an escape character. I know I can solve it by using '/' in place of Did you actually try that? Here's a small example: $ cat > raw_string c:\foo\bar\test\new\end $ python Python 2.3.3 (#1, Dec 30 2003, 08:29:25) [GCC 3.3.1 (cygming special)] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> f = file('raw_string') >>> f.readline() 'c:\\foo\\bar\\test\\new\\end\r\n' >>> f = file('raw_string') >>> print f.readline() c:\foo\bar\test\new\end No interpolation happens (\t is tab and \n newline). Karl -- Please do *not* send copies of replies to me. I read the list From bvande at po-box.mcgill.ca Thu Apr 8 12:59:05 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Thu Apr 8 13:01:08 2004 Subject: [Tutor] can you turn strings from a file into raw strings? In-Reply-To: References: <4074F5EE.2050304@po-box.mcgill.ca> Message-ID: <407584D9.1090800@po-box.mcgill.ca> Karl Pfl?sterer said unto the world upon 08/04/2004 12:32: > On 8 Apr 2004, Brian van den Broek <- bvande@po-box.mcgill.ca wrote: > > [...] > >>Why I care: >>I am wanting to store a series of directory names in a plain text >>config file. I can read the file just fine and have can do all I've >>tried with the output of the readline() method so far. But, since I am >>on a Windows machine, I would prefer to turn the readline() output >>into a raw string. Otherwise, the directory separator '\' gets read as >>an escape character. I know I can solve it by using '/' in place of > > > Did you actually try that? Here's a small example: > > $ cat > raw_string > c:\foo\bar\test\new\end > > $ python > Python 2.3.3 (#1, Dec 30 2003, 08:29:25) > [GCC 3.3.1 (cygming special)] on cygwin > Type "help", "copyright", "credits" or "license" for more information. > >>>>f = file('raw_string') >>>>f.readline() > > 'c:\\foo\\bar\\test\\new\\end\r\n' > >>>>f = file('raw_string') >>>>print f.readline() > > c:\foo\bar\test\new\end > > No interpolation happens (\t is tab and \n newline). > > > > Karl Karl, right you are. Thanks. I think I confused myself by assuming that stuff that worked one way in the interactive prompt on strings typed in as literals and assigned to variables would work the same on a string taken from file.readline(). Clearly I need to know more about Python before running around making assumptions! Sorry. On the plus side, I am getting the hang of it, if slowly. Thanks again and best, Brian vdB From alan.gauld at blueyonder.co.uk Thu Apr 8 16:50:57 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Apr 8 16:50:15 2004 Subject: [Tutor] Python suddenly finding ".DS_Store" files in folder References: <200404080143.25807.scot@possum.in-berlin.de> Message-ID: <00d601c41dab$31350d30$6401a8c0@xp> > > Actually, it _is_ Mac OS X running around inserting files. > > Ye Gods. How strange. They certainly don't tell you that in the switcher ads, > do they ... Nope, nor do Microsoft tell you about all the crud they write to the registry or about the "hidden" files they use in the C:\ root directory. Every OS uses hidden or special files to do its job, provided the ordinary user doesn't uncover the gory details thats fine. BTW You do realise that Mac OS X applications are actually folders and not really the simple files that finder displays don't you?! :-) > > And if we want our programs to follow the same conventions, we'll have to > > filter out those filenames ourselves. If you write a small helper > > function that filters out os.listdir()'s output, that should do the trick. > > Yeah, now I have an ugly hack that checks if the file is .DS_Store and if so, > skips it. You could skip all files that begin with. if name[0] == '.' and filter all hidden files. > I think I might want to take another look at Yellow Dog Linux... What makes you think it would be any different? listdir will still show hidden files there too, its not the OS its the way the function is defined to work. Alan G. From alan.gauld at blueyonder.co.uk Thu Apr 8 16:58:09 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Apr 8 16:57:27 2004 Subject: [Tutor] can you turn strings from a file into raw strings? References: <4074F5EE.2050304@po-box.mcgill.ca> Message-ID: <00df01c41dac$3289f960$6401a8c0@xp> > I am wondering if there is anyway to force the output of > somefile.readline() to be a raw string? I'm not sure what you mean, it is a raw string. > I am wanting to store a series of directory names in a plain text > config file. I can read the file just fine and have can do all > I've tried with the output of the readline() method so far. But, > since I am on a Windows machine, I would prefer to turn the > readline() output into a raw string. Otherwise, the directory > separator '\' gets read as an escape character. No the '\' will be read as a '\' character and when you print the file Python will corrctly display it with double \\ The \ is a specific ascii character that is written to the file. Whether you write r'foo\t' or 'foo\\t' is immaterial in termns of what actually gets written to the file(and hence read back), its the same 5 ascii characters. The only difference is in the representation on the screen. Can you show us an example of what you are doing that seems broken? Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From Doug.Shawhan at ge.com Thu Apr 8 17:39:47 2004 From: Doug.Shawhan at ge.com (Shawhan, Doug (EM, ITS)) Date: Thu Apr 8 17:39:56 2004 Subject: [Tutor] List comprehension and generators. Message-ID: Howdy, Been playing at chopping up strings with list comprehension: >>> s='hondoharrietshappyhippiehuthyundai' >>> [(s[:3]) for each in range(5)] ['hon', 'hon', 'hon', 'hon', 'hon'] and more fun.. import random >>> [(s[:random.randint(1,10)]) for each in range(random.randint(1,10))] ['hondoharri', 'hondoharri', 'h', 'hond', 'hondoharr', 'hondohar', 'h', 'hondoharri'] >>> [(s[:random.randint(1,10)]) for each in range(random.randint(1,10))] ['ho', 'ho', 'hondoharri'] >>> [(s[:random.randint(1,10)]) for each in range(random.randint(1,10))] ['hondoharri', 'hondo', 'hondohar'] >>> [(s[:random.randint(1,10)]) for each in range(random.randint(1,10))] ['hondoh', 'hondoha', 'hondoha', 'hondoh', 'hondoharri', 'hon', 'hondoharr', 'hondohar'] Now this is all very fun, but it leads me to three questions: 1. How would one split that entire string into a list of same-size elements: I.e. ['hondoh', 'arriets', 'happyhi', 'ppiehuth', 'yundai'] 2. How would one split that string into a list of *non-repeating* random-sized elements? I.e. ['ho', 'ndoharri', 'etshappyhippieh', 'uthyundai'] (I know I could do it with a 'for' loop, but I'll bet you can do it with list comprehension) Which in turn leads me to: 3. How would one use comprehension or a generator to create a random-sized list of random numbers? (Or is this not the proper use of a generator?) From chris at chrislott.org Thu Apr 8 20:59:29 2004 From: chris at chrislott.org (Chris Lott) Date: Thu Apr 8 20:59:35 2004 Subject: [Tutor] Python suddenly finding ".DS_Store" files in folder In-Reply-To: <00d601c41dab$31350d30$6401a8c0@xp> References: <200404080143.25807.scot@possum.in-berlin.de> <00d601c41dab$31350d30$6401a8c0@xp> Message-ID: <4075F571.2060902@chrislott.org> Alan Gauld wrote: > Nope, nor do Microsoft tell you about all the crud they write to > the registry or about the "hidden" files they use in the C:\ root > directory. Every OS uses hidden or special files to do its job, > provided the ordinary user doesn't uncover the gory details thats > fine. True enough, but there isn't a hidden file for EVERY file and/or directory in these other cases, whereas all the ._* and .DS_Store (for that matter, why can't it all be stored in .DS_Store and get rid of the ._* files), one of the former per file and one of the latter in seemingly every directory gets pretty annoying. >>I think I might want to take another look at Yellow Dog Linux... > > > What makes you think it would be any different? listdir will still > show hidden files there too, its not the OS its the way the function > is defined to work. I'm surprised that the .DS_Store file is even needed on the the Mac OS-- why not have this all packed away in the resource fork somehow? The real problem I have are OSs that are not smart enough to get rid of unnecessary items when transferring to different filesystems... c -- Chris Lott (chris@chrislott.org) http://www.chrislott.org/ "May my silences become more accurate" --Theodore Roethke From syrinx at simplecom.net Fri Apr 9 00:54:58 2004 From: syrinx at simplecom.net (Scott) Date: Fri Apr 9 00:55:22 2004 Subject: [Tutor] Cookies Message-ID: <20040408235458.67a882a8.syrinx@simplecom.net> Hi all. Is there a way to get the value of a particular cookie for a particular website that has been left behind by a web-browser? Hopefully, this would work whether the user has Mozilla or IE or Opera, etc. Thanks. From isrgish at fastem.com Fri Apr 9 01:20:11 2004 From: isrgish at fastem.com (Isr Gish) Date: Fri Apr 9 01:20:23 2004 Subject: [Tutor] File Access Message-ID: Nick Lunt wrote: > >Hi Lloyd, > >thanks for the info. However, f.seek(0,2) takes me to the end of the >file as you say, but what I need is the whole last line of the file. > >After doing f.seek(0,2) successive f.seek(-1, 1) calls will walk me >backwards through the file but to make this useful I would need to keep >checking the current character for an "\n". And unfortunately calls to >f.read() and f.readline() take me back to the end of the file or line >respectively. You can try reading a chunk that you are sure is more than the length of the longest line. Then do str.rfind('\n') to find the last line. All the best Isr Gish > >Im on linux and the fseek(3) manpage seems to indicate that I cannot >take a file of unknown size and seek to the start of the last line, >would be nice if it did tho ;) > >Am I talking rubbish or do you agree ? > >Thanks again, >Nick. From scot at possum.in-berlin.de Thu Apr 8 20:42:26 2004 From: scot at possum.in-berlin.de (Scot W. Stevenson) Date: Fri Apr 9 05:26:49 2004 Subject: [Tutor] Python suddenly finding ".DS_Store" files in folder In-Reply-To: <00d601c41dab$31350d30$6401a8c0@xp> References: <200404080143.25807.scot@possum.in-berlin.de> <00d601c41dab$31350d30$6401a8c0@xp> Message-ID: <200404090242.26583.scot@possum.in-berlin.de> Hello Alan, > BTW You do realise that Mac OS X applications are actually > folders and not really the simple files that finder displays > don't you?! :-) I figured that out the hard way when I was trying to setup my new iBook G4 as an X Terminal for my home machine, which we use as a Mock Mainframe (shameless plug: http://www.tldp.org/HOWTO/Mock-Mainframe/index.html). Mac OS X 10.3.3 includes two (!) versions of X, one in /usr/X11/bin etc. where it belongs, the other in /Appplications/Utilities/X11/Content/MacOS/X11 or something to that effect. The problem: The "normal" X server will run the required command line parameters fine, but the "Mac OS" X11 bombs. Strange. I've had the iBook for a few weeks now, and as pretty and easy to use Mac OS is for beginners, it seems to be one ugly beast once you lift off the GUI layer. I'm still not sure what a "resource fork" is and why I'm supposed to need one on a Unix machine... > > I think I might want to take another look at Yellow Dog Linux... > What makes you think it would be any different? listdir will still > show hidden files there too, its not the OS its the way the function > is defined to work. But KDE doesn't spread hidden files all over the place like rabbit droppings, as far as I can tell. Writing configuation files in this way is rather unpleasant, to say the least. Y, Scot -- Scot W. Stevenson - Panketal, Germany From jsh47 at cam.ac.uk Fri Apr 9 06:23:42 2004 From: jsh47 at cam.ac.uk (Jonathan Hayward) Date: Fri Apr 9 06:23:56 2004 Subject: [Tutor] can you turn strings from a file into raw strings? In-Reply-To: <407584D9.1090800@po-box.mcgill.ca> References: <4074F5EE.2050304@po-box.mcgill.ca> <407584D9.1090800@po-box.mcgill.ca> Message-ID: <407679AE.5070707@cam.ac.uk> > > I think I confused myself by assuming that stuff that worked one way > in the interactive prompt on strings typed in as literals and assigned > to variables would work the same on a string taken from > file.readline(). Clearly I need to know more about Python before > running around making assumptions! Go ahead and make mistakes, and let other people see your assumptions. It's one of the best ways to learn, and Tutor has people who will gently correct your assumptions. Neil Postman, in _The End of Education_, talked about mistakes. He describes them as a valuable opportunity for a teacher to see what a student is thinking, and offer guidance that the teacher might not know to offer. Someone said, 'You need to make a million mistakes to learn a language, so get cracking!' -- ++ Jonathan Hayward, jonathan.hayward@pobox.com ** To see an award-winning website with stories, essays, artwork, ** games, and a four-dimensional maze, why not visit my home page? ** All of this is waiting for you at http://JonathansCorner.com From project5 at redrival.net Fri Apr 9 08:46:22 2004 From: project5 at redrival.net (Andrei) Date: Fri Apr 9 08:46:32 2004 Subject: [Tutor] Re: List comprehension and generators. References: Message-ID: <1655tyrps73tb$.1tc3w3rlr8lgd$.dlg@40tude.net> Shawhan, Doug (EM, ITS) wrote on Thu, 8 Apr 2004 17:39:47 -0400: Hi, My examples are for the following string: >>> s = "abcdefghijklmnopqrstuvwx" >>> len(s) 24 >>> from random import randint as rnd # save me some typing > 1. How would one split that entire string into a list of same-size elements: > > I.e. ['hondoh', 'arriets', 'happyhi', 'ppiehuth', 'yundai'] >>> size = 4 # size of the pieces we want >>> [ s[i*size:(i+1)*size] for i in range(len(s)//size) ] ['abcd', 'efgh', 'ijkl', 'mnop', 'qrst', 'uvwx'] > 2. How would one split that string into a list of *non-repeating* random-sized elements? > > I.e. ['ho', 'ndoharri', 'etshappyhippieh', 'uthyundai'] Can't think of a way to do this with a list comprehension directly. What can be done is manipulate an existing list object inside the list comprehension. >>> mylist = [] # list object which will store our results >>> [ mylist.append(ss) for ss in [ s[rnd(0,len(s)):rnd(0,len(s))] for i in range(rnd(8,20)) ] if ss and ss not in mylist ] [None, None, None, None, None] >>> mylist ['ghijklmnopqr', 'mnopq', 'jklmnopqrstu', 'opqrstu', 'cde'] The inner list comprehension: [ s[rnd(0,len(s)):rnd(0,len(s))] for i in range(rnd(8,20)) ] just creates random number pairs and pulls the corresponding pieces out of the string. You can run this on its own and get something like this: >>> [ s[rnd(0,len(s)):rnd(0,len(s))] for i in range(rnd(8,20)) ] ['bcdefghijklmnopqrs', '', '', 'bcdefghijklmnopqr', '', 'hijklm', 'ghijklmnopqrs', '', '', ''] The outer list comprehension loops over this list, calling each of its elements ss and checks if ss is non-empty and if ss isn't already in mylist. If both these conditions are True, ss is added to mylist, otherwise the code just skips to the next element inside the inner list. Now this has a list being manipulated in a list comprehension containing a second list comprehension and two conditions. The result is not pretty and I wouldn't recommend using this kind of code. Rolling out this code into an explicit for-loop would be much, much clearer. > (I know I could do it with a 'for' loop, but I'll bet you can do it with list comprehension) Can != should :) > Which in turn leads me to: > > 3. How would one use comprehension or a generator to create a > random-sized list of random numbers? (Or is this not the proper > use of a generator?) You already had the code required for this in your own examples: [(s[:random.randint(1,10)]) for each in range(random.randint(1,10))] The second part takes care of this list being of random length, the first part can be adapted to insert a random number instead of a piece of the string: >>> [random.randint(1,10) for each in range(random.randint(1,10))] [2, 1, 4, 5, 6, 3] You could to some extent see generators as lists which are not in-memory and can only be accessed sequentially. >>> def randnumgen(n=None): ... if n==None: ... n = random.randint(1,10) ... for i in range(n): ... yield random.randint(0,10) ... >>> list(randnumgen()) [7, 5, 9, 0, 9, 2, 3, 3, 7, 9] >>> list(randnumgen()) [1, 4, 0, 1] This is useful if you intend to manipulate a really huge list: you wouldn't run out of memory just creating that list. E.g.: >>> for elem in range(10000000): ... pass By the end of this run, Python is using about 160 MB. Now you could write a generator for it, e.g.: >>> def mygen(n): # a bit like range(n) ... i = 0 ... while i>> for elem in mygen(100000000): ... pass This one has no influence upon Python's memory usage. By the way, in this case the generator is about 2x slower than the built-in range function on my computer, presumably because range() is looping in C, while my generator loops in Python. But if I increase the number to 20 mln instead of 10 mln, the generator outperforms the range() by a factor 2 because the overhead of allocating memory to that list (probably includes some swapping) is larger than the overhead of the loop. If that number is increased even more, range() will become completely unusable due to its memory requirements (my Python interpreter consumes well over 200 MB at this point and peaked at nearly 300 MB!), while the generator will continue to work regardless of how many elements you make it generate. -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From alan.gauld at blueyonder.co.uk Fri Apr 9 09:14:06 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Apr 9 09:13:56 2004 Subject: [Tutor] Python suddenly finding ".DS_Store" files in folder References: <200404080143.25807.scot@possum.in-berlin.de><00d601c41dab$31350d30$6401a8c0@xp> <200404090242.26583.scot@possum.in-berlin.de> Message-ID: <002b01c41e34$89be76b0$6401a8c0@xp> > OS X 10.3.3 includes two (!) versions of X, one in /usr/X11/bin etc. where > it belongs, the other in /Appplications/Utilities/X11/Content/MacOS/X11 I oinly have OS X 10.2 (Jaguar) but aso have 2 X installs, one the XFree86 port for Mac and the other the official Apple beta. I assume they have shipped the same on Panther(10.3) > I've had the iBook for a few weeks now, and as pretty and easy to use Mac OS > is for beginners, it seems to be one ugly beast once you lift off the GUI > layer. I don;t think its that ugly. Have you tried any of the more advanced books which explain the innards (and you do have David pogues invaluable "Missing Manual" I'm still not sure what a "resource fork" is and why I'm supposed to > need one on a Unix machine... > > > > I think I might want to take another look at Yellow Dog Linux... > > > What makes you think it would be any different? listdir will still > > show hidden files there too, its not the OS its the way the function > > is defined to work. > > But KDE doesn't spread hidden files all over the place like rabbit droppings, > as far as I can tell. Writing configuation files in this way is rather > unpleasant, to say the least. > > Y, Scot > -- > Scot W. Stevenson - Panketal, Germany > > > > From alan.gauld at blueyonder.co.uk Fri Apr 9 09:26:51 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Apr 9 09:26:39 2004 Subject: [Tutor] Python suddenly finding ".DS_Store" files in folder Message-ID: <003001c41e36$51a5e3b0$6401a8c0@xp> Sorry, this got sent prematurely... > > OS X 10.3.3 includes two (!) versions of X, one in /usr/X11/bin etc. > where it belongs, the other in > /Appplications/Utilities/X11/Content/MacOS/X11 > > I only have OS X 10.2 (Jaguar) but aso have 2 X installs, one the > XFree86 port for Mac and the other the official Apple beta. > > I assume they have shipped the same on Panther(10.3) > > is for beginners, it seems to be one ugly beast once you lift off > the GUI layer. I don't think it's that ugly. Have you tried any of the more advanced books which explain the innards (and you do have David Pogue's invaluable "Missing Manual" don't you?) I found "MacOS X Hacks" a good source of explanation and tips for non GUI udsers. And Mac OS X Unleashed was also useful for getting "under the hood". > I'm still not sure what a "resource fork" is and why I'm supposed to > need one on a Unix machine... The resource fork is where all the nib files and stuff are kept, including the GUI language files etc. Keeping them out of the binary has the advantage that you can go in and tweak them without having access to the source code! > What makes you think it would be any different? listdir will still > show hidden files there too, its not the OS its the way the > function is defined to work. > > > But KDE doesn't spread hidden files all over the place like rabbit > droppings, as far as I can tell. Not quite so many I agree, but there are still a lot of rc files scattered about my Linux box, and the /etc heirarchy is a mess and even /tmp gets busy... But I agree these tend to be in one place whereas Apple has distributed them. The Apple approach does have the advantage that moving part of a folder heirarchy from one machine to another brings all the settings files etc with it, so it appears on the new machine exactly as it did on the old. Mac Os is the only OS I've ever worked with that can manage that trick. And remember, an important aspect of Mac OS is that it is really assumed that you will be working in the GUI and only using the terminal for "down n dirty" stuff. Up until OS X you didn't even have the option! I've used Linux since 1993 and its come a long way and its still my preferred server environmemnt but as a general user desktop I have to say MacOs beats it hands down IMHO. I haven't tried using MacOS as a server but I suspect all the stuff that makes it cool on the desktop; would be irrelevant in a server and just get in the way... Alan G. From vianney.de-bellabre at insa-lyon.fr Fri Apr 9 10:11:28 2004 From: vianney.de-bellabre at insa-lyon.fr (DE BELLABRE) Date: Fri Apr 9 10:11:35 2004 Subject: [Tutor] Launching an app into a frame Message-ID: <1081519888.4076af10248bf@webmail.insa-lyon.fr> Hy all, I'm trying to launch an application from my python code. Not too hard using os.system(), but I'd like to bound the app window into a GUI component of my python window (I'm using boa constructor to create my window). For example I'd like to create a frame into my window, and launch the app into this frame (kwrite for example, I'm developping under mandrake), does someone know if it's possible and how to do that ? thanks Djoumy From dyoo at hkn.eecs.berkeley.edu Fri Apr 9 13:42:47 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Apr 9 13:42:55 2004 Subject: [Tutor] List comprehension and generators. In-Reply-To: Message-ID: On Thu, 8 Apr 2004, Shawhan, Doug (EM, ITS) wrote: > Now this is all very fun, but it leads me to three questions: > > 1. How would one split that entire string into a list of same-size > elements: > > I.e. ['hondoh', 'arriets', 'happyhi', 'ppiehuth', 'yundai'] Hi Doug, It's possible to do this with the list comprehension approach that you're using now. The range() builtin can take in 3 arguments: a 'start', an 'end' and a 'skip': ### >>> range(0, 10, 3) [0, 3, 6, 9] ### We can combine this with list slicing to dice up a list: ### >>> numbers = range(50) >>> [numbers[i:i+5] for i in range(0, 50, 5)] [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20, 21, 22, 23, 24], [25, 26, 27, 28, 29], [30, 31, 32, 33, 34], [35, 36, 37, 38, 39], [40, 41, 42, 43, 44], [45, 46, 47, 48, 49]] ### There are other approaches we can take. In particular, we can even use regular expressions: ### >>> re.findall('.....', "supercalifragilisticexpialidosious") ['super', 'calif', 'ragil', 'istic', 'expia', 'lidos'] ### This may be easier to comprehend than comprehensions, depending on your background. > 2. How would one split that string into a list of *non-repeating* > random-sized elements? Can you write a function that takes that string and returns a list of random-sized elements? And is there a specific number of chunks that we want to break our string into? Do we always want to break the string into 5 or 6 parts, or is that too meant to be random? It may be easier to approach the more-general problem, and then tack on the requirement for 'non-repeats' as a refinement afterwards. > 3. How would one use comprehension or a generator to create a > random-sized list of random numbers? (Or is this not the proper use of a > generator?) This feels like list comprehension abuse to me. Any implemenation that makes this work will probably be nonobvious. *grin* Is there a specific requirement to use comprehensions? Using loops might be more straightforward. Talk to you later! From dyoo at hkn.eecs.berkeley.edu Fri Apr 9 15:39:41 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Apr 9 15:39:48 2004 Subject: [Tutor] Cookies In-Reply-To: <20040408235458.67a882a8.syrinx@simplecom.net> Message-ID: On Thu, 8 Apr 2004, Scott wrote: > Hi all. Is there a way to get the value of a particular cookie for a > particular website that has been left behind by a web-browser? > Hopefully, this would work whether the user has Mozilla or IE or Opera, > etc. Thanks. Hi Scott, Hmmm... I believe that cookies are stored on by the browser itself, so if you have access to the cookie file that lives on the browser, it should be possible to eat that. The Mozilla browser, for example, keeps a 'cookies.txt' file, and it looks something like this: ### [dyoo@tesuque 987rqvz4.slt]$ head cookies.txt # HTTP Cookie File # http://www.netscape.com/newsref/std/cookie_spec.html # This is a generated file! Do not edit. # To delete cookies, use the Cookie Manager. ads.specificpop.com FALSE FALSE 1609459199 id 526702577 ads.specificpop.com FALSE FALSE 1609459199 fci 10-326-1-1060739521-1%3A10-35-1-1061334715-1 www.baxter2.com FALSE FALSE 1092257148 lang english www.linuxjournal.com FALSE FALSE 1092862778 lang english .specificpop.com TRUE FALSE 1609459199 cpa 156-1136-109-1061334715 ### Hmmm... so it should be possible to parse this file, since it's tab-delimited. Ah! Someone has written a parser for cookie files in the Python Cookbook: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66454 Ok, so that step is done. *grin* I did some more Googling, and according to: http://www.computer-2tr.com/Tips/03/20030310.html the cookies for IE lives in a 'Cookies' subdirectory, but that subdirectory is in several possible places, depending on what version of Windows you're running. Thankfully, there's also an entry in the Cookbook to grab IE cookie files without having to worry about that detail: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/80443 I can't test this since I don't have Windows available at the moment. Can anyone confirm that it has the same structure as the Mozilla cookie file? So all the pieces are almost there. I don't think anyone has yet worked on writing a nice set of functions to uniformly grab cookie files for all the different browsers, though. If one did exist, I'd expect it in 'webbrowser', so perhaps it might be worthwhile to try adding some functionality in 'webbrowser' to do this. Talk to you later! From marilyn at deliberate.com Fri Apr 9 17:03:47 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Fri Apr 9 17:03:56 2004 Subject: [Tutor] List of available modules Message-ID: I think I remember that I can import something so that I can look at the list of available modules. Can anyone remind me of how that goes? Thank you. Marilyn Davis From op73418 at mail.telepac.pt Fri Apr 9 17:36:01 2004 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Fri Apr 9 17:33:24 2004 Subject: [Tutor] List of available modules In-Reply-To: References: Message-ID: Em Fri, 9 Apr 2004 14:03:47 -0700 (PDT), Marilyn Davis atirou este peixe aos pinguins: > >I think I remember that I can import something so that I can look at >the list of available modules. Can anyone remind me of how that goes? > What do you mean by "list of available modules", the modules that are available for import? As far as I know there isn't one. There can be many such, not just the ones from the standard library but also third-party ones. The docs are your best bet. The *already imported* modules? Then >>> import sys >>> print sys.modules {'code': , ... [long list snipoped] With my best regards, G. Rodrigues From jsidiqi at hotmail.com Fri Apr 9 19:23:39 2004 From: jsidiqi at hotmail.com (ABDUL JABBAR SIDDIQUE) Date: Fri Apr 9 19:23:45 2004 Subject: [Tutor] difficulty in reading csv file Message-ID: An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040409/b2bba0cc/attachment.html From dyoo at hkn.eecs.berkeley.edu Fri Apr 9 19:57:34 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Apr 9 19:57:40 2004 Subject: [Tutor] difficulty in reading csv file In-Reply-To: Message-ID: On Fri, 9 Apr 2004, ABDUL JABBAR SIDDIQUE wrote: > I am new to Python programming. I am trying to import data from a csv > file. the data composed of some text values and some integer/float > values. When I import the data as text through csv reader it works ok. > however, when I convert the values into float it does'nt work. The > program runs without throwing any error but it does'nt show any values > in python shell window. I don't know whats the problem. I'll appreciate > your help. Hi Jabbar, Hmmm... I think we'll need to see some example code that we can test. At the moment, there's too little information to diagnose the problem. Are you using a module to read the CSV file? There's a specialized CSV module from Object Craft: http://www.object-craft.com.au/projects/csv/ but there's also a 'csv' module in the Standard Library now, http://www.python.org/doc/lib/module-csv.html That's why we need more details, since there are several ways of doing CSV parsing. Are you using either of these modules, or have you written your own parser? Also, how are you converting the values into floats? The 'float()' builtin takes a string, and returns a float: ### >>> s = '3.1415926' >>> float(s) 3.1415926000000001 ### and may be useful here. 'csv' itself has no idea if it's reading floats or ints: it should just be returning each row as a column of strings. The 'csv' module leaves data conversion to us, so I suspect the bug may have less to do with 'csv' itself, and more with what happens with the manipulation done to the string values afterwards. If you have more questions, please feel free to ask them. Good luck to you! From dyoo at hkn.eecs.berkeley.edu Fri Apr 9 20:06:39 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Apr 9 20:06:46 2004 Subject: [Tutor] List of available modules In-Reply-To: Message-ID: On Fri, 9 Apr 2004, [ISO-8859-1] Gon=E7alo Rodrigues wrote: > Em Fri, 9 Apr 2004 14:03:47 -0700 (PDT), Marilyn Davis > atirou este peixe aos pinguins: > > > > >I think I remember that I can import something so that I can look at > >the list of available modules. Can anyone remind me of how that goes? > > > > What do you mean by "list of available modules", the modules that are > available for import? As far as I know there isn't one. There can be > many such, not just the ones from the standard library but also > third-party ones. The docs are your best bet. Hello, Actually, there is a way to do it: 'help()' knows what modules are accessible: ### >>> help('modules') Please wait a moment while I gather a list of all available modules... ArrayPrinter buildDecorator lovins signal Autoformat cPickle macpath site BaseHTTPServer cStringIO macurl2path smtpd Bastion cacher mailbox smtplib Bio (package) calendar mailcap sndhdr BioSQL (package) cgi make_xml_descriptor socket CDROM cgitb markupbase spmatrix CGIHTTPServer chunk marshal spmatrix_util Canvas cmath math sqlite (package) CompatMysqldb cmd maximum_digit_total sre ConfigParser code md5 sre_compile Cookie codecs memsize sre_constants DLFCN codeop merge sre_parse [... lots of text cut] ### But the output can be so overwhelming that it might not really be useful. The module documentation in: http://www.python.org/doc/lib/ is still lengthy, but tries to summarize each publically documented module, rather than all available modules. Is there a particular module that you're looking for, though? Talk to you later! From op73418 at mail.telepac.pt Sat Apr 10 07:46:16 2004 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Sat Apr 10 07:43:36 2004 Subject: [Tutor] List of available modules In-Reply-To: References: Message-ID: Em Fri, 9 Apr 2004 17:06:39 -0700 (PDT), Danny Yoo atirou este peixe aos pinguins: > > >On Fri, 9 Apr 2004, [ISO-8859-1] Gon?o Rodrigues wrote: > >> Em Fri, 9 Apr 2004 14:03:47 -0700 (PDT), Marilyn Davis >> atirou este peixe aos pinguins: >> >> > >> >I think I remember that I can import something so that I can look at >> >the list of available modules. Can anyone remind me of how that goes? >> > >> >> What do you mean by "list of available modules", the modules that are >> available for import? As far as I know there isn't one. There can be >> many such, not just the ones from the standard library but also >> third-party ones. The docs are your best bet. > > >Hello, > > >Actually, there is a way to do it: 'help()' knows what modules are >accessible: > >### >>>> help('modules') Thanks for correcting me! Do you know if help("modules") also lists third-party modules? And how about reliability? I mean, *how* does it gather the list of modules? Since there isn't a central registry of installed Python modules I suppose that it just crawls through the "standard paths" (the standard lib + site-packages + ...) and gathers all files with .py extension. Of course this can pick up files which are not, strictly speaking, modules, like scripts which are not meant to be imported. Anyway, thanks for the info, with my best regards, G. Rodrigues P.S: After writing the above, I fired up Python and tried help("modules"). It indeed crawls through sys.path and picks the modules/packages. I know this, because my sitecustomize.py file is customized to append some directories to sys.path with some of my own modules (to facilitate testing). So the first question, and I would assume the second also, are answered. From jmpurser at comcast.net Sat Apr 10 10:01:41 2004 From: jmpurser at comcast.net (John M. Purser) Date: Sat Apr 10 10:01:36 2004 Subject: [Tutor] List of available modules In-Reply-To: Message-ID: Just so I can measure the duration of my ignorance: How long has Python had help()? Thanks, John Purser -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org]On Behalf Of Goncalo Rodrigues Sent: Saturday, April 10, 2004 5:46 AM To: tutor@python.org Subject: Re: [Tutor] List of available modules Em Fri, 9 Apr 2004 17:06:39 -0700 (PDT), Danny Yoo atirou este peixe aos pinguins: > > >On Fri, 9 Apr 2004, [ISO-8859-1] Gon?o Rodrigues wrote: > >> Em Fri, 9 Apr 2004 14:03:47 -0700 (PDT), Marilyn Davis >> atirou este peixe aos pinguins: >> >> > >> >I think I remember that I can import something so that I can look at >> >the list of available modules. Can anyone remind me of how that goes? >> > >> >> What do you mean by "list of available modules", the modules that are >> available for import? As far as I know there isn't one. There can be >> many such, not just the ones from the standard library but also >> third-party ones. The docs are your best bet. > > >Hello, > > >Actually, there is a way to do it: 'help()' knows what modules are >accessible: > >### >>>> help('modules') Thanks for correcting me! Do you know if help("modules") also lists third-party modules? And how about reliability? I mean, *how* does it gather the list of modules? Since there isn't a central registry of installed Python modules I suppose that it just crawls through the "standard paths" (the standard lib + site-packages + ...) and gathers all files with .py extension. Of course this can pick up files which are not, strictly speaking, modules, like scripts which are not meant to be imported. Anyway, thanks for the info, with my best regards, G. Rodrigues P.S: After writing the above, I fired up Python and tried help("modules"). It indeed crawls through sys.path and picks the modules/packages. I know this, because my sitecustomize.py file is customized to append some directories to sys.path with some of my own modules (to facilitate testing). So the first question, and I would assume the second also, are answered. _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From mjekl at clix.pt Sat Apr 10 10:02:19 2004 From: mjekl at clix.pt (mjekl@clix.pt) Date: Sat Apr 10 10:02:24 2004 Subject: [Tutor] os.system() problem executing application / program Message-ID: <20040410140219.460.qmail@maboque.srv.clix.pt> Hi, I'm experimenting with os.system() to start another application in my pc. I have no problems with the following statement: os.system("start C:\\MyDb1.mdb") A command box appears/ desappears and Access starts running. *** On the other hand the following statement doesn't work: os.system("start C:\Program Files\Internet Explorer\Iexplorer.exe") I'm as sure as I can be that this as something to do with either long file names or spaces in the dos command. If this is true this is not really a Python problem, but still is something probably alot of people encounter, so ther is probably a fast answer to my hair pulling problem :-) I'm running Python2.3 on MSW98 2nd. Txs, Miguel Clix Rapidix - Aumente até 6X a velocidade da sua Internet Adira em http://acesso.clix.pt e comece logo a navegar From project5 at redrival.net Sat Apr 10 10:08:50 2004 From: project5 at redrival.net (Andrei) Date: Sat Apr 10 10:09:00 2004 Subject: [Tutor] Re: os.system() problem executing application / program References: <20040410140219.460.qmail@maboque.srv.clix.pt> Message-ID: mjekl@clix.pt wrote on Saturday 10 April 2004 16:02: > On the other hand the following statement doesn't work: > > os.system("start C:\Program Files\Internet Explorer\Iexplorer.exe") > > I'm as sure as I can be that this as something to do with either long file > names or spaces in the dos command. Spaces are a problem. Try putting double quotes around them, so: os.system('start "C:\Program Files\Internet Explorer\Iexplorer.exe"') By the way, are you absolutely sure it's not "iexplore.exe"? (I'm not on Windows now, so I can't check.) Also you don't really need the path at all, just "iexplore" should work. > If this is true this is not really a Python problem, but still is > something > probably alot of people encounter, so ther is probably a fast answer to my > hair pulling problem :-) No, it's all over Windows. If you look at shortcuts to the Program Files folder you'll notice a lot of quoting too. -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From project5 at redrival.net Sat Apr 10 10:16:25 2004 From: project5 at redrival.net (Andrei) Date: Sat Apr 10 10:16:32 2004 Subject: [Tutor] RE: List of available modules References: Message-ID: John M. Purser wrote on Saturday 10 April 2004 16:01: > Just so I can measure the duration of my ignorance: > How long has Python had help()? I think just about forever :). It was there when I started learning Python, which was about 1.5 years ago and I learned about it from tutorials older than that. I've done a Google and I noticed some discussion on http://mail.python.org/pipermail/python-dev/2000-December/011000.html Presumably that was before its implementation, which probably happened in 2001. So my guess is that it's about 3 years old. -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From dlafrance at cs-linux.ubishops.ca Sat Apr 10 13:53:28 2004 From: dlafrance at cs-linux.ubishops.ca (dlafrance@cs-linux.ubishops.ca) Date: Sat Apr 10 13:53:32 2004 Subject: [Tutor] how is memory de-allocated? Message-ID: <1216.216.209.121.157.1081619608.squirrel@cs-linux.ubishops.ca> Hi, I would like know how is memory de-allocated? Through explicit programmer instruction like c++ or via garbage collection like Java And if it is possible can you give me an example Thanks. From project5 at redrival.net Sat Apr 10 15:26:28 2004 From: project5 at redrival.net (Andrei) Date: Sat Apr 10 15:26:41 2004 Subject: [Tutor] Re: how is memory de-allocated? References: <1216.216.209.121.157.1081619608.squirrel@cs-linux.ubishops.ca> Message-ID: dlafrance@cs-linux.ubishops.ca wrote on Saturday 10 April 2004 19:53: > I would like know how is memory de-allocated? > Through explicit programmer instruction like c++ or via garbage collection > like Java Generally speaking, memory management is not something that you should worry about. It's all done automatically for you. There are some exceptions though, which are of course regarded as unpythonic, e.g.: http://www.dwerg.net/2004/articles/libxml -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From pythonTutor at venix.com Sat Apr 10 15:26:43 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Sat Apr 10 15:29:44 2004 Subject: [Tutor] how is memory de-allocated? In-Reply-To: <1216.216.209.121.157.1081619608.squirrel@cs-linux.ubishops.ca> References: <1216.216.209.121.157.1081619608.squirrel@cs-linux.ubishops.ca> Message-ID: <1081625202.2232.27.camel@laptop.venix.com> There is automatic garbage collection as in Java. IF we no longer need an object we can delete the name we use to refer to the object. If that was the last reference then the memory used by that object will be reclaimed. The example below creates a tuple and uses the name x to refer to that tuple. Once the name is deleted, the garbage collection will detect that the tuple can no longer be used and will reclaim the memory. >>> x = (1,2,3) >>> x (1, 2, 3) >>> del x >>> x Traceback (most recent call last): File "", line 1, in ? NameError: name 'x' is not defined On Sat, 2004-04-10 at 13:53, dlafrance@cs-linux.ubishops.ca wrote: > Hi, > > I would like know how is memory de-allocated? > > Through explicit programmer instruction like c++ or via garbage collection > like Java > > And if it is possible can you give me an example > > Thanks. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From alan.gauld at blueyonder.co.uk Sat Apr 10 16:46:10 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Apr 10 16:45:37 2004 Subject: [Tutor] RE: List of available modules References: Message-ID: <005201c41f3c$db05b660$6401a8c0@xp> > > How long has Python had help()? > > I think just about forever :). After 1.5 and before 2.3.... Browsing the old documentation I found this in the "whats new in 2.2" for 2.2.3, dated May 30, 2003 --------- In the interpreter's interactive mode, there's a new built-in function help() that uses the pydoc module introduced in Python 2.1 to provide interactive help. help(object) displays any available help text about object. help() with no argument puts you in an online help utility, where you can enter the names of functions, classes, or modules to read their help text. (Contributed by Guido van Rossum, using Ka-Ping Yee's pydoc module.) -------------- 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 Sat Apr 10 17:47:23 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Apr 10 17:47:28 2004 Subject: [Tutor] List of available modules In-Reply-To: Message-ID: On Sat, 10 Apr 2004, John M. Purser wrote: > Just so I can measure the duration of my ignorance: How long has Python > had help()? Hi John Ka-Ping Yee wrote the 'pydoc' module module quite a while back, and that module was incorporated into the Standard Library around Python 2.1: http://python.org/doc/2.2/lib/module-pydoc.html http://www.onlamp.com/pub/a/python/2001/04/18/pydoc.html pydoc.help() was accessible around then, but it was a little awkward to type 'from pydoc import help' every time one wanted to use it. We had a discussion on getting help() as a builtin on the edu-sig list, http://mail.python.org/pipermail/edu-sig/2001-June/001376.html http://mail.python.org/pipermail/edu-sig/2001-June/001401.html As a result of that fruitful discussion, Guido checked in a patch to make help() a builtin. http://cvs.sourceforge.net/viewcvs.py/python/python/dist/src/Lib/site.py?r1=1.26&r2=1.27 So, in short: we've had help() since about 2001. *grin* Hope this helps! From pythonTutor at venix.com Sat Apr 10 21:21:36 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Sat Apr 10 21:24:45 2004 Subject: [Tutor] how is memory de-allocated? In-Reply-To: <1081625202.2232.27.camel@laptop.venix.com> References: <1216.216.209.121.157.1081619608.squirrel@cs-linux.ubishops.ca> <1081625202.2232.27.camel@laptop.venix.com> Message-ID: <1081646496.4495.4.camel@laptop.venix.com> I should have pointed out that local names are deleted automatically when a function or method completes executing. Those names "pass out of scope". Objects that are no longer referenced (no longer accessible) will be deleted and their memory reclaimed by the garbage collector. It is seldom necessary to explicitly delete variables. On Sat, 2004-04-10 at 15:26, Lloyd Kvam wrote: > There is automatic garbage collection as in Java. IF we no longer need > an object we can delete the name we use to refer to the object. If that > was the last reference then the memory used by that object will be > reclaimed. > > The example below creates a tuple and uses the name x to refer to that > tuple. Once the name is deleted, the garbage collection will detect > that the tuple can no longer be used and will reclaim the memory. > > >>> x = (1,2,3) > >>> x > (1, 2, 3) > >>> del x > >>> x > Traceback (most recent call last): > File "", line 1, in ? > NameError: name 'x' is not defined > > On Sat, 2004-04-10 at 13:53, dlafrance@cs-linux.ubishops.ca wrote: > > Hi, > > > > I would like know how is memory de-allocated? > > > > Through explicit programmer instruction like c++ or via garbage collection > > like Java > > > > And if it is possible can you give me an example > > > > Thanks. > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From dbroadwell at mindspring.com Sat Apr 10 23:49:43 2004 From: dbroadwell at mindspring.com (David Broadwell) Date: Sat Apr 10 23:44:34 2004 Subject: [Tutor] Launching an app into a frame In-Reply-To: <1081519888.4076af10248bf@webmail.insa-lyon.fr> Message-ID: > I'm trying to launch an application from my python code. Not too > hard using os.system(), but I'd like to bound the app window into > a GUI component of my python window (I'm using boa constructor to > create my window). For example I'd like to create a frame into my > window, and launch the app into this frame > does someone know if it's possible and how to do that ? It sounds too easy to be impossible. For what it's worth; if you can that part of your application always read something particular ... say a 127.0.0.1:NNNN port. then run the application to be displayed with the os settings to redirect output to the 127.0.0.1:NNNN port? For security's sake please use a port over 1024 ... there would be a limitation with this method of text only, I think. Any feedback from the more knowledgeable code slingers out there? p.s. I'd love to see code on this ... -- Programmer's mantra; Observe, Brainstorm, Prototype, Repeat David Broadwell From vianney.de-bellabre at insa-lyon.fr Sun Apr 11 09:48:31 2004 From: vianney.de-bellabre at insa-lyon.fr (Djoumy) Date: Sun Apr 11 09:48:38 2004 Subject: [Tutor] Launching an app into a frame In-Reply-To: References: Message-ID: <1081691311.40794caf92ced@webmail.insa-lyon.fr> Hy, > It sounds too easy to be impossible. That's what I believe too :) > if you can that part of your application always read something particular > ... say a 127.0.0.1:NNNN port. > then run the application to be displayed with the os settings to redirect > output to the 127.0.0.1:NNNN port? Sounds good but how would you do that ? And would the app interact with user's input into the frame that contains the app ? An other way should be using an X server (using the os variable DISPLAY), but I just managed to install xlib and didn't find any valuable doc about how to use it correctly, especially how to bound the app to a display (for example 'localhost:0.3')... Does anyone know if it could be a good solution ? > p.s. I'd love to see code on this ... No pb, I'll mail the code to tutor list. > > I'm trying to launch an application from my python code. Not too > > hard using os.system(), but I'd like to bound the app window into > > a GUI component of my python window (I'm using boa constructor to > > create my window). For example I'd like to create a frame into my > > window, and launch the app into this frame > > does someone know if it's possible and how to do that ? Djoumy From jmpurser at comcast.net Sun Apr 11 11:12:16 2004 From: jmpurser at comcast.net (John M. Purser) Date: Sun Apr 11 11:11:13 2004 Subject: [Tutor] List of available modules In-Reply-To: Message-ID: Thanks to all who replied. Oh well I did get pretty good at looking things up in the python documentation in the three years I wandered lost and alone! Okay now who can plumb the depths of my ignorance! John Purser -----Original Message----- From: Danny Yoo [mailto:dyoo@hkn.eecs.berkeley.edu] Sent: Saturday, April 10, 2004 3:47 PM To: John M. Purser Cc: Tutor Subject: RE: [Tutor] List of available modules On Sat, 10 Apr 2004, John M. Purser wrote: > Just so I can measure the duration of my ignorance: How long has Python > had help()? Hi John Ka-Ping Yee wrote the 'pydoc' module module quite a while back, and that module was incorporated into the Standard Library around Python 2.1: http://python.org/doc/2.2/lib/module-pydoc.html http://www.onlamp.com/pub/a/python/2001/04/18/pydoc.html pydoc.help() was accessible around then, but it was a little awkward to type 'from pydoc import help' every time one wanted to use it. We had a discussion on getting help() as a builtin on the edu-sig list, http://mail.python.org/pipermail/edu-sig/2001-June/001376.html http://mail.python.org/pipermail/edu-sig/2001-June/001401.html As a result of that fruitful discussion, Guido checked in a patch to make help() a builtin. http://cvs.sourceforge.net/viewcvs.py/python/python/dist/src/Lib/site.py?r1= 1.26&r2=1.27 So, in short: we've had help() since about 2001. *grin* Hope this helps! From jsidiqi at hotmail.com Sun Apr 11 11:39:56 2004 From: jsidiqi at hotmail.com (ABDUL JABBAR SIDDIQUE) Date: Sun Apr 11 11:40:03 2004 Subject: [Tutor] How to calculate Standard Deviation Message-ID: An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040411/c807b744/attachment.html From dbroadwell at mindspring.com Sun Apr 11 12:29:40 2004 From: dbroadwell at mindspring.com (David Broadwell) Date: Sun Apr 11 12:24:37 2004 Subject: [Tutor] Launching an app into a frame In-Reply-To: <1081691311.40794caf92ced@webmail.insa-lyon.fr> Message-ID: >>> Djoumy >> David Broadwell > Djoumy David Broadwell >>> I'm trying to launch an application from my python code. >>> Not too hard using os.system(), but I'd like to bound the >>> app window into a GUI component of my python window (I'm >>> using boa constructor to create my window). For example >>> I'd like to create a frame into my window, and launch the >>> app into this frame does someone know if it's possible >>> and how to do that ? >> It sounds too easy to be impossible. > That's what I believe too :) I've learned that the things that sound doable are, but that sound too easy are bloody hard. This sounds fun to ... and as an extension of could be a place to send cli output before shitting off the shell to a gui app. Actually it would be very useful module in any number of my pet programming projects. >> David Wrote: if you can that part of your application always >> read something particular ... say a 127.0.0.1:NNNN port. >> then run the application to be displayed with the os settings >> to redirect output to the 127.0.0.1:NNNN port? > Sounds good but how would you do that ? And would the app > interact with user's input into the frame that contains the > app ? Interaction would mean that the app needs to also be able to monitor ... a second port? and not only mirror that to the display so the user think they typed in it, but be able to reply with a result? > An other way should be using an X server (using the os variable > DISPLAY), but I just managed to install xlib and didn't find > any valuable doc about how to use it correctly, especially how > to bound the app to a display (for example 'localhost:0.3')... > Does anyone know if it could be a good solution ? I have one argument with this, platform dependent. -- Programmer's mantra; Observe, Brainstorm, Prototype, Repeat David Broadwell From jmpurser at comcast.net Sun Apr 11 14:36:45 2004 From: jmpurser at comcast.net (John M. Purser) Date: Sun Apr 11 14:35:43 2004 Subject: [Tutor] How to calculate Standard Deviation In-Reply-To: Message-ID: Jabbar, You might want to look at Numerical python or Numarray: http://www.pfdubois.com/numpy/html2/numpy.html which has a function described as: "td(m, axis = 0) returns the unbiased estimate of the population standard deviation from a sample along the axis'th dimension of m. (That is, the denominator for the calculation is n-1, not n.)" John Purser -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org]On Behalf Of ABDUL JABBAR SIDDIQUE Sent: Sunday, April 11, 2004 9:40 AM To: tutor@python.org Subject: [Tutor] How to calculate Standard Deviation Hi guys, Can any body guide me how to calculate Standard Deviation of a set of values in each row of a table? Is there any built-in function to calculate it directly or I have to formulate it by myself? I will appreciate your replys. Regards jabbar MSN 8 helps ELIMINATE E-MAIL VIRUSES. Get 2 months FREE*. From drachkk at yahoo.com Sun Apr 11 16:01:04 2004 From: drachkk at yahoo.com (Erick) Date: Sun Apr 11 16:01:13 2004 Subject: [Tutor] help with FTP program Message-ID: <20040411200104.65694.qmail@web21410.mail.yahoo.com> Hi I'm new to python and programming in general. As a practice and learning project i am developing and FTP program. Where i stand now, i Have 2 problem.: 1- How do i use get_full_url? I dont understand how to use REQUEST OBJECT from a module. I have been able to use cmdloop but i can't figure out get_full_url, get_selector and all the objet from URLLIB2. 2-I am using CMDLOOP as a prompt, How could i get Python to: Write in a file what the user is typing in, what are the answer from the server, like a record book of everything that goes in and out of my FTP program. Eric --------------------------------- Do you Yahoo!? Yahoo! Tax Center - File online by April 15th -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040411/fb286099/attachment.html From alex at alexnewby.com Sun Apr 11 16:41:36 2004 From: alex at alexnewby.com (Alex Newby) Date: Sun Apr 11 16:47:02 2004 Subject: [Tutor] Re: How to calculate Standard Deviation Message-ID: <1081716096.25019.184254724@webmail.messagingengine.com> Date: Sun, 11 Apr 2004 15:39:56 +0000 From: "ABDUL JABBAR SIDDIQUE" Subject: [Tutor] How to calculate Standard Deviation To: tutor@python.org http://www.google.com/search?q=python+statistics&sourceid=mozilla-search&start=0&start=0&ie=utf-8&oe=utf-8 Happy hunting! You might also try Rpy. Or, as you say, you could just write it yourself... Alex Newby From adam at monkeez.org Sun Apr 11 17:19:30 2004 From: adam at monkeez.org (Adam) Date: Sun Apr 11 17:20:23 2004 Subject: [Tutor] Newbie - mixing floats and integers (first post) Message-ID: <4079B662.9060007@monkeez.org> Just picking up python with Learning Python (on day 3 now - be kind) and have written my own small calculator script: arg1 = raw_input("What is your first number?:") oper = raw_input("What operation: +, -, *, / ?") arg3 = raw_input("What is your second number?:") num1 = long(arg1) #oper = arg [2] num2 = long(arg3) if oper == "+": answer = num1+num2 elif oper == "-": answer = num1-num2 elif oper == "/": answer = (num1/num2) elif oper == "x": answer = (num1*num2) print num1, oper, num2, "=", answer I've read in learning Python that the variable types look after themselves - "great" I think, less hassle than Java. However, when I try and run this program with floats, it won't work and I get errors. Is there something I have to do to enable this to work with both floats and integers? Thanks in advance. adam From missive at hotmail.com Sun Apr 11 19:22:32 2004 From: missive at hotmail.com (Lee Harr) Date: Sun Apr 11 19:22:38 2004 Subject: [Tutor] Re: Newbie - mixing floats and integers Message-ID: >arg1 = raw_input("What is your first number?:") >oper = raw_input("What operation: +, -, *, / ?") >arg3 = raw_input("What is your second number?:") > >num1 = long(arg1) >#oper = arg [2] >num2 = long(arg3) > >if oper == "+": > answer = num1+num2 >elif oper == "-": > answer = num1-num2 >elif oper == "/": > answer = (num1/num2) >elif oper == "x": > answer = (num1*num2) > >print num1, oper, num2, "=", answer > > >However, when I try and run this program with floats, it won't work and >I get errors. Is there something I have to do to enable this to work >with both floats and integers? What input? What errors? Most likely, what you want to do is use float(arg) instead of long(arg) long() is going to produce a long integer, which in python is an integer that can be arbitrarily large (or anti-large). Remember that you can run some of this stuff by the interactive interpreter to see what it means ... >>>3.5 3.5 >>>long(3.5) 3L >>>long(-3.5) -3L >>>long(-39999999999999999999999999999999999999) -39999999999999999999999999999999999999L >>>float(35) 35.0 >>>float(35.5) 35.5 >>>float('thirty-five') Traceback (most recent call last): File "", line 1, in ? ValueError: invalid literal for float(): thirty-five >>>float('35') 35.0 >>>float('35.5') 35.5 _________________________________________________________________ The new MSN 8: advanced junk mail protection and 2 months FREE* http://join.msn.com/?page=features/junkmail From FallenJ7456 at aol.com Sun Apr 11 23:46:27 2004 From: FallenJ7456 at aol.com (FallenJ7456@aol.com) Date: Sun Apr 11 23:46:38 2004 Subject: [Tutor] python help Message-ID: <1da.1eb9cc6a.2dab6b13@aol.com> if there is anyone willing to help me in some basics of python please e-mail me also if anyone uses pygame and has info on it mail me thanx fallenj -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040411/d9549058/attachment.html From py at gogol.humnet.ucla.edu Mon Apr 12 00:37:00 2004 From: py at gogol.humnet.ucla.edu (peter hodgson) Date: Mon Apr 12 00:37:05 2004 Subject: [Tutor] trying to understand the logic of functions Message-ID: <200404120437.i3C4b0pe024412@nightshade.noc.ucla.edu> Hi Gregor. Thanks. You have certainly given me a lot to think about. I believe I have grasped the sense of your terms, and put them, IN CAPS, under my tentative definitions [>], below, just for comparison. As for your last example, the one about function calls and function objects, I am still working on that one [see #comments# below]. Thanks again. Peter On Wed, 07 Apr 2004 Gregor Lingl wrote: Hi Peter! I tried to rewrite your recent posting, just using different terms. I hope this sheds a different light on this topic. What do you think of this? 1. a function is defined thus: def NAME(LIST OF PARAMETERS): STATEMENTS 2. when a function is called: > it takes [gets passed] an argument [value or variable], it takes [gets passed] an argument [OBJECT (i. e. constant or name or expression (*))], (*) strictly speaking constants and names are also expressions (albeit simple ones in contrast to compound expressions) > and returns a result [return value], and returns a result [return value, i.e. another OBJECT], or performs an action; >3. variables are the boxes for values; 3. variables are the NAMES for OBJECTS; > parameters are the variables used in the definition of a function, parameters are the NAMES used in the definition of a function, > inside the parentheses, to refer to the value[s] which will be inside the parentheses, to refer to the OBJECTS which will be passed as arguments when the function is called; >4. function names, as well as the names of variables [incl. parameters] 4. function names, as well as PARAMETER NAMES can be arbitrary; they are not what gets stored in memory and manipulated by the function when it is called; they are > just labelled boxes; just NAMES; >5. statements can assign values to variables; an example is a 5. statements can assign NAMES to OBJECTS; an example is a > statement which assigns the return value of a function to a variable; statement which assigns a NAME to the OBJECT returned by a function e.g.: > variable = function (argument); NAME = function (argument); >thus, a parameter [which is a variable] can be a function thus, a parameter [which is a NAME] can be the RESULT OF A *FUNCTION CALL*, i.e. its result is the argument of its parent function: e.g.: fun1 (fun2()), or even fun1 (fun2(fun3(argument))) - ---------------------------------------------------- There is a very important difference between a function call and a function. if you use a function call as argument, the resulting object is bound to the parameter (name). But you can also use function(-objects) as arguments, in order to call them somewhere in the body of the function to be defined. I think this is a *somewhat* advanced topic - therefore here a very short example to clarify it: >>> def square(x): return x*x >>> def cubus(x): return x*x*x >>> def table(fun): for x in range(5): print x, fun(x) # fun is the function object being called?# >>> table(square) #square is a function object as argument?# 0 0 1 1 2 4 3 9 4 16 >>> table(cubus) #cubus is a function object as argument?# 0 0 1 1 2 8 3 27 4 64 >>> Regards, Gregor peter hodgson schrieb: >On Monday 22 March 2004 20:47, python_simpleton wrote that terms like >'parameter' were confusing; > >here's another newbie's attempt to sort out parameter's node of terms: > >1. a function is defined thus: > > def NAME(LIST OF PARAMETERS): > STATEMENTS > >2. when a function is called: > > it takes [gets passed] an argument [value or variable], > > and returns a result [return value], > or performs an action; > >3. variables are the boxes for values; > > parameters are the variables used in the definition of a function, > inside the parentheses, to refer to the value[s] which will be > passed as arguments when the function is called; > >4. function names, as well as the names of variables [incl. > parameters] can be arbitrary; they are not what gets stored in > memory and manipulated by the function when it is called; they are > just labelled boxes; > >5. statements can assign values to variables; an example is a > statement which assigns the return value of a function to a > variable; e.g.: > > variable = function (argument); > >thus, a parameter [which is a variable] can be a function, >i.e. its result is the argument of its parent function: e.g.: > > fun1 (fun2()), or even > fun1 (fun2(fun3(argument))) > > > > > > > > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > From bvande at po-box.mcgill.ca Mon Apr 12 03:37:40 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Mon Apr 12 03:39:50 2004 Subject: [Tutor] can you turn strings from a file into raw strings? In-Reply-To: <407679AE.5070707@cam.ac.uk> References: <4074F5EE.2050304@po-box.mcgill.ca> <407584D9.1090800@po-box.mcgill.ca> <407679AE.5070707@cam.ac.uk> Message-ID: <407A4744.3060003@po-box.mcgill.ca> Jonathan Hayward said unto the world upon 09/04/2004 06:23: > >> >> I think I confused myself by assuming that stuff that worked one way >> in the interactive prompt on strings typed in as literals and assigned >> to variables would work the same on a string taken from >> file.readline(). Clearly I need to know more about Python before >> running around making assumptions! > > > Go ahead and make mistakes, and let other people see your assumptions. > It's one of the best ways to learn, and Tutor has people who will gently > correct your assumptions. > > Neil Postman, in _The End of Education_, talked about mistakes. He > describes them as a valuable opportunity for a teacher to see what a > student is thinking, and offer guidance that the teacher might not know > to offer. Someone said, 'You need to make a million mistakes to learn a > language, so get cracking!' > Hi all, I've been away from the computer for a few days, so I am consolidating thanks and replies to several respondents into one post. My experience so far amply bears out Jonathan's point about "gently". I've managed to talk out of my hat in more than one post so far, and yet no flames :-) Alan, I take your point that I should post actual code. In retrospect, formalizing my concern would either resolve it of focus it. Roy, thanks for the suggestion of Learning Python. I have it, and thought it was quite accessible and more comprehensive than the other accessible presentations I'd seen on the net. You mentioned you are half-way through. If I may suggest, don't do what I did -- I read it on the bus, reading through without frequent time at the keyboard. I've retained the forest, but some of the details are hazy. This thread proves the last point, if nothing else :-) So, thanks to all on the list for being kind as I publicly stumble towards understanding! (Apologies if I overlooked any responses.) Best to all, Brian vdB From nouda at freemail.nl Mon Apr 12 06:03:33 2004 From: nouda at freemail.nl (nouda) Date: Mon Apr 12 06:01:06 2004 Subject: [Tutor] Newbie - want to learn more about Python Message-ID: Hello Python, I'm Noud Aldenhoven, I'm 15 years old and I'm from Holland. I started a month ago with Python, the first programming languisch I ever studied. But I've one big problem... My english is ways to bad to read the Python Tutrial in Enlish. So here's my question: 'Isn't there anywhere a complete Dutch Tutorial for Python?' If there isn't: 'Does someone who can speak Dutch and can programe with Python want to help me to tell me more about Python?' Thank you all! Noud Aldenhoven Nijmegen Netherlands From johnp at HomeLumber.com Mon Apr 12 09:52:37 2004 From: johnp at HomeLumber.com (John Purser) Date: Mon Apr 12 09:52:48 2004 Subject: [Tutor] Newbie - want to learn more about Python Message-ID: Noud, I found: http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/IDLE-vertaling.html by googling "python, Dutch, documents". I found the next link at www.python.org under documents and non-English documents. http://www.python.org/doc/NonEnglish.html#dutch Good Luck, John Purser -----Original Message----- From: nouda [mailto:nouda@freemail.nl] Sent: Monday, April 12, 2004 03:04 To: tutor@python.org Subject: [Tutor] Newbie - want to learn more about Python Hello Python, I'm Noud Aldenhoven, I'm 15 years old and I'm from Holland. I started a month ago with Python, the first programming languisch I ever studied. But I've one big problem... My english is ways to bad to read the Python Tutrial in Enlish. So here's my question: 'Isn't there anywhere a complete Dutch Tutorial for Python?' If there isn't: 'Does someone who can speak Dutch and can programe with Python want to help me to tell me more about Python?' Thank you all! Noud Aldenhoven Nijmegen Netherlands _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From dbroadwell at mindspring.com Mon Apr 12 11:00:19 2004 From: dbroadwell at mindspring.com (David Broadwell) Date: Mon Apr 12 10:55:36 2004 Subject: [Tutor] 'Common' mistake ... for other newbies Message-ID: I started with the text below, but if you don't like detailed reports of newbie fumbles, skip this post. Points to not quitting but continuing to hack at it ... my first real bug. ... I'm having an odd problem that I don't know how to debug. What is going on is as a exercise, I'm playing rock paper scissors in code. I'm using; Python 2.2, Windows2kServer, PII450@386mb w/80gb ... At full run with a 100 item result list it failed on the average 97th roll, but with a 6 entry list only averages 10 rolls instead before dying. It seems that the smaller the resultlist the more often an IndexError occurs. The code is like this (static data for brevity); >>> from random import randint >>> resultlist = ['rock','paper','scissors','rock','paper','scissors'] >>> def roll(): ''' returns a random item from resultlist ''' return resultlist[randint(0,len(resultlist))] >>> for item in range(1000): roll() 'scissors' 'paper' 'paper' 'paper' 'paper' 'rock' 'scissors' Traceback (most recent call last): File "", line 2, in ? roll() File "", line 3, in roll return resultlist[randint(0,len(resultlist))] IndexError: list index out of range >>> So to debug, I rewrote roll into debugroll() >>> def debugroll(): temp = len(resultlist) print "len(resultlist) = %s" % temp temp = randint(0,temp) print "randint(0,len(resultlist)) = %s" % temp temp = resultlist[temp] print "resultlist[randint(0,len(resultlist))] = %s" % temp return temp >>> for item in range(1000): debugroll() len(resultlist) = 6 randint(0,len(resultlist)) = 5 resultlist[randint(0,len(resultlist))] = scissors 'scissors' len(resultlist) = 6 randint(0,len(resultlist)) = 6 Traceback (most recent call last): File "", line 2, in ? debugroll() File "", line 6, in debugroll temp = resultlist[temp] IndexError: list index out of range after a bit more testing (or frantically repeating the error) I noted that it only died when the randomly generated index was 6 ... and then it hit me, a list of len 6 has no index six and the uncrashable roll function needed to reflect that is as follows. The solution; >>> def roll(): ''' returns a random item from resultlist ''' return resultlist[randint(0,len(resultlist)-1)] ... I got bit because I count from 1 and the computer counts from 0, a 'common' mistake. As a note this was the last hurdle to having the code play rock paper scissors against itself, I'm sure it's not nearly as elegant as it could be, but it's very, very, readable. -- Programmer's mantra; Observe, Brainstorm, Prototype, Repeat David Broadwell From missive at hotmail.com Mon Apr 12 13:14:58 2004 From: missive at hotmail.com (Lee Harr) Date: Mon Apr 12 13:15:04 2004 Subject: [Tutor] Re: 'Common' mistake ... for other newbies Message-ID: >I started with the text below, but if you don't like detailed reports of >newbie fumbles, skip this post. Points to not quitting but continuing to >hack at it ... my first real bug. > This is excellent advice for everyone ... So many times, I have started working on a message to a mailing list or bug tracker trying to explain exactly what I am doing and what is going wrong when ! oh... I see what the problem is now! It is one reason I prefer mailing lists to irc. It forces us to think about things a bit more for ourselves, rather than just getting the answer. Thanks for sending this in even though you figured it out. I am sure it will light a bulb for someone else, and maybe encourage someone to write a good question even if they can't find the answer on their own. _________________________________________________________________ Tired of spam? Get advanced junk mail protection with MSN 8. http://join.msn.com/?page=features/junkmail From dyoo at hkn.eecs.berkeley.edu Mon Apr 12 14:45:54 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Apr 12 14:46:05 2004 Subject: [Tutor] Newbie - mixing floats and integers (first post) In-Reply-To: <4079B662.9060007@monkeez.org> Message-ID: On Sun, 11 Apr 2004, Adam wrote: > Just picking up python with Learning Python (on day 3 now - be kind) and > have written my own small calculator script: > > arg1 = raw_input("What is your first number?:") > oper = raw_input("What operation: +, -, *, / ?") > arg3 = raw_input("What is your second number?:") > > num1 = long(arg1) > #oper = arg [2] > num2 = long(arg3) > > if oper == "+": > answer = num1+num2 > elif oper == "-": > answer = num1-num2 > elif oper == "/": > answer = (num1/num2) > elif oper == "x": > answer = (num1*num2) > > print num1, oper, num2, "=", answer > > I've read in learning Python that the variable types look after > themselves - "great" I think, less hassle than Java. > > However, when I try and run this program with floats, it won't work and > I get errors. Is there something I have to do to enable this to work > with both floats and integers? Hi Adam, Yes, there's a way to do it. (By the way, instead of using long(), use int(). In Python 2.3, int() will automagically use long() if the integer is larger than your machine's native integer size: ### >>> int("323984729834729374293892749327894273984723895") 323984729834729374293892749327894273984723895L ### so unless you're trying to maintain compatibility with older versions of Python, you don't have to worry about overflowing.) The issue is the conversion of the 'arg1' and 'arg3' strings to some kind of number. At the moment, the code is indiscriminately trying to convert everything to long integers. But when we try feeding in a string that looks like a float, though, we'll get exceptions that warn us that we're probably doing something silly: ### >>> long("3.1415") Traceback (most recent call last): File "", line 1, in ? ValueError: invalid literal for long(): 3.1415 ### We can, however, convert a string that looks like a float directly into a float: ### >>> float("3.1415") 3.1415000000000002 ### One way to fix the program is to call either int() or float(), conditionally based on the content of the string. Here's one approach: if the string contains a decimal point, we can call our float conversion routine. And otherwise, we can call our integer-converting routine: ### >>> def num(s): ... """Returns either an integer or a float out of string 's'.""" ... if '.' in s: ... return float(s) ... else: ... return int(s) ... >>> num("3.1415926") 3.1415926000000001 >>> num("42") 42 ### You can use this 'num()' function to do the string-to-numeric conversions, and it should do the right thing, for the most part. *grin* The problem is very similar to what happens in Java when we use Java's Integer.parseInt() function on a string that looks like a floating-point number: ### [dyoo@tesuque dyoo]$ jython Jython 2.1 on java1.4.1_01 (JIT: null) Type "copyright", "credits" or "license" for more information. >>> import java >>> java.lang.Integer.parseInt("3.1415926") Traceback (innermost last): File "", line 1, in ? java.lang.NumberFormatException: For input string: "3.1415926" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48) [... long Java traceback cut] ### (I'm using Jython --- a Java/Python bridge --- to show what things look like on the Java side. It's a very nice tool if you have Java experience.) So the conversion issues between strings and the primitive types are also similar in Java --- the string-to-integer routines on both are a bit strict. Please feel free to ask more questions. Hope this helps! From alan.gauld at blueyonder.co.uk Mon Apr 12 14:54:24 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Mon Apr 12 14:53:19 2004 Subject: [Tutor] Newbie - mixing floats and integers (first post) References: <4079B662.9060007@monkeez.org> Message-ID: <006101c420bf$92e4b140$6401a8c0@xp> > arg1 = raw_input("What is your first number?:") > oper = raw_input("What operation: +, -, *, / ?") > arg3 = raw_input("What is your second number?:") > > num1 = long(arg1) > #oper = arg [2] > num2 = long(arg3) If you convert to floats instead of longs it will work. ( Within the limited accuracy of floating point representation on a computer) > However, when I try and run this program with floats, it won't work and > I get errors. Is there something I have to do to enable this to work > with both floats and integers? Alternatively you can try testing to see if the number read is a float - check if it has a decimal point is one way. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at blueyonder.co.uk Mon Apr 12 14:58:27 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Mon Apr 12 14:57:21 2004 Subject: [Tutor] Newbie - want to learn more about Python References: Message-ID: <007001c420c0$237e5cb0$6401a8c0@xp> > 'Isn't there anywhere a complete Dutch Tutorial for Python?' There should be, have you checked the non-english web page on python.org? There is ertainly an active Dutch user community. BTW If German or Italian or Spanish are any easier you can read my tutor in those languages too. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From tony at tcapp.com Mon Apr 12 15:16:47 2004 From: tony at tcapp.com (Tony Cappellini) Date: Mon Apr 12 15:16:55 2004 Subject: [Tutor] Re: Tutor Digest, Vol 2, Issue 23 In-Reply-To: Message-ID: <20040412121424.N64795-100000@yamato.yamato.com> > I'm having an odd problem that I don't know how to debug. > What is going on is as a exercise, I'm playing rock paper scissors in code. > I'm using; Python 2.2, Windows2kServer, PII450@386mb w/80gb > Just as an aside, I believe there is at least 1 (possibly more) python solutions to Paper, ROck , Scissors in the Python Cookbook, at ActiveState.com This was a program we had to write for an intro to Python class I took. From adam at monkeez.org Mon Apr 12 15:37:55 2004 From: adam at monkeez.org (Adam) Date: Mon Apr 12 15:37:52 2004 Subject: [Tutor] Newbie - mixing floats and integers (first post) In-Reply-To: References: <4079B662.9060007@monkeez.org> Message-ID: <20040412203755.6cee07df.adam@monkeez.org> On Mon, 12 Apr 2004 11:45:54 -0700 (PDT) Danny Yoo wrote: > > > On Sun, 11 Apr 2004, Adam wrote: > > > Just picking up python with Learning Python (on day 3 > > now - be kind) and have written my own small calculator > > script: > > > > arg1 = raw_input("What is your first number?:") > > oper = raw_input("What operation: +, -, *, / ?") > > arg3 = raw_input("What is your second number?:") > > > > num1 = long(arg1) > > #oper = arg [2] > > num2 = long(arg3) > > > > if oper == "+": > > answer = num1+num2 > > elif oper == "-": > > answer = num1-num2 > > elif oper == "/": > > answer = (num1/num2) > > elif oper == "x": > > answer = (num1*num2) > > > > print num1, oper, num2, "=", answer > > > > I've read in learning Python that the variable types > > look after themselves - "great" I think, less hassle > > than Java. > > > > However, when I try and run this program with floats, it > > won't work and I get errors. Is there something I have > > to do to enable this to work with both floats and > > integers? > > > Hi Adam, > > > Yes, there's a way to do it. > > > One way to fix the program is to call either int() or > float(), conditionally based on the content of the string. > Here's one approach: if > the string contains a decimal point, we can call our float > conversion routine. And otherwise, we can call our > integer-converting routine: > > ### > >>> def num(s): > ... """Returns either an integer or a float out of > string 's'."""... if '.' in s: > ... return float(s) > ... else: > ... return int(s) > ... > >>> num("3.1415926") > 3.1415926000000001 > >>> num("42") > 42 > ### > > You can use this 'num()' function to do the > string-to-numeric conversions, and it should do the right > thing, for the most part. *grin* > > > > > The problem is very similar to what happens in Java when > we use Java's Integer.parseInt() function on a string that > looks like a floating-point number: > > ### > [dyoo@tesuque dyoo]$ jython > Jython 2.1 on java1.4.1_01 (JIT: null) > Type "copyright", "credits" or "license" for more > information. > >>> import java > >>> java.lang.Integer.parseInt("3.1415926") > Traceback (innermost last): > File "", line 1, in ? > java.lang.NumberFormatException: For input string: > "3.1415926" > at > java.lang.NumberFormatException.forInputString(NumberForm > atException.java:48) > > [... long Java traceback cut] > ### > > (I'm using Jython --- a Java/Python bridge --- to show > what things look like on the Java side. It's a very nice > tool if you have Java experience.) > > So the conversion issues between strings and the primitive > types are also similar in Java --- the string-to-integer > routines on both are a bit strict. > Please feel free to ask more questions. Hope this helps! Danny, Many thanks for your reply - very helpful stuff (much more helpful than the Java forums). I really liked the idea of checking for a '.' and then casting appropriately (does casting mean anything in python)? This seems like a clean solution and most appropriate for both conditions (int and float). I'm also glad to report that my experience here (albeit a short one) is much more positive than the brief experiences I had within the java help community (although, I imagine that they are normally helpful). I'm afraid, it looks like I'll be staying :-) Thanks once again. adam From dyoo at hkn.eecs.berkeley.edu Mon Apr 12 16:26:17 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Apr 12 16:26:23 2004 Subject: [Tutor] Newbie - mixing floats and integers (first post) In-Reply-To: <20040412203755.6cee07df.adam@monkeez.org> Message-ID: > > So the conversion issues between strings and the primitive types are > > also similar in Java --- the string-to-integer routines on both are a > > bit strict. Please feel free to ask more questions. Hope this helps! > > I really liked the idea of checking for a '.' and then casting > appropriately (does casting mean anything in python)? Hi Adam, Not really --- the int(), float(), and str() functions aren't typecasts, but are more 'function'-like. In Python terminology, they are 'callables': ### >>> int >>> float >>> callable(int) True >>> callable(float) True ### So you can think of them as functions that take any input, and they either return their namesake, or raise an exception if they have problems. Because they're callables, it makes sense to call str() on anything: ### >>> str('hello world') 'hello world' >>> str(42) '42' >>> str([1, 2, 3, 4, 5]) '[1, 2, 3, 4, 5]' ### In Java, one of the most frequent occurences of typecasting is when we we use Java's generic container classes: /*** Pseudo-Java ***/ for(int i = 0; i < someListOfNames.size(); i++) { String name = (String) someListOfNames.get(i); ... } /******/ In Python, though, we don't have to worry about typecasting: ### Pseudo-Python -- (purposely structured similar to Java code: better to ### use 'for name in someListOfNames:...') ### for i in range(len(someListOfNames)): name = someListOfNames[i] ... ### An object's 'type' is attached to the value, and not to the name. ### >>> def printType(thing): ... print "the type of", thing, "is:", type(thing) ... >>> printType(42) the type of 42 is: >>> printType("adam") the type of adam is: ### > I'm also glad to report that my experience here (albeit a short one) is > much more positive than the brief experiences I had within the java help > community (although, I imagine that they are normally helpful). The forums at: http://forum.java.sun.com/ do seem active; have you asked your questions there? Hope this helps! From drachkk at yahoo.com Mon Apr 12 16:45:03 2004 From: drachkk at yahoo.com (Erick) Date: Mon Apr 12 16:45:14 2004 Subject: [Tutor] new to python error handling question Message-ID: <20040412204503.15843.qmail@web21408.mail.yahoo.com> Hi i started playing with python 2-3 days. i'm developping an FTP software. i use some error handling here's how it goes: def do_list(*??*): try: ftp.retrlines("list") pass except (AttributeError): print "AttributeError" pass return () Why does it for sure detect AttributError when if i take the Try,Except off, it does'nt. Also i'm not totally sur how to decide what goes in (*??*) For this one i putted (ftp, retrlines). It does'nt cause any problem put i dont think its right because i could put anything and it would do fine.....What is the difference????? Eric --------------------------------- Do you Yahoo!? Yahoo! Tax Center - File online by April 15th -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040412/22ce8878/attachment.html From denis.spir at free.fr Mon Apr 12 17:04:44 2004 From: denis.spir at free.fr (denis) Date: Mon Apr 12 17:16:10 2004 Subject: [Tutor] Newbie - want to learn more about Python References: Message-ID: <006601c420d3$5958da00$ae2ae4d5@spir> Hello, Your english doesn't seem so bad, et least better than mine (i'm french :-). If you plan to go on with computers, I would encourage you to learn and work both in dutch and english. On one side, you will quickly realise how poor, repetitive and easy the technical language is : once you get a few key words and expressions, that's it ! The point is, maybe, that most of the books and tutorials are, to my opinion, pedagogically really poor -- including Guido's writings. One notable exception is "how to think like a computer scientist", which helps and understand python's particularities ; and also learn how to program properly. You'll find it (download) on www.thinkpython.com or www.ibiblio.org On the other hand, an interesting experience is to mix language (in this case : dutch, english and... python). You can program in your own language, naming (variable, functions, etc) and commenting in dutch. Also try the pretty funny test of translating python's slang (keyword, function names...) into dutch. What words would you choose ? denis ----- Original Message ----- From: John Purser To: nouda ; Sent: Monday, April 12, 2004 3:52 PM Subject: RE: [Tutor] Newbie - want to learn more about Python Noud, I found: http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/IDLE-vertaling.html by googling "python, Dutch, documents". I found the next link at www.python.org under documents and non-English documents. http://www.python.org/doc/NonEnglish.html#dutch Good Luck, John Purser -----Original Message----- From: nouda [mailto:nouda@freemail.nl] Sent: Monday, April 12, 2004 03:04 To: tutor@python.org Subject: [Tutor] Newbie - want to learn more about Python Hello Python, I'm Noud Aldenhoven, I'm 15 years old and I'm from Holland. I started a month ago with Python, the first programming languisch I ever studied. But I've one big problem... My english is ways to bad to read the Python Tutrial in Enlish. So here's my question: 'Isn't there anywhere a complete Dutch Tutorial for Python?' If there isn't: 'Does someone who can speak Dutch and can programe with Python want to help me to tell me more about Python?' Thank you all! Noud Aldenhoven Nijmegen Netherlands _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From denis.spir at free.fr Mon Apr 12 17:36:32 2004 From: denis.spir at free.fr (denis) Date: Mon Apr 12 17:36:57 2004 Subject: [Tutor] 'Common' mistake ... for other newbies Message-ID: <008901c420d6$3bb19340$ae2ae4d5@spir> Well, Thank you David for this clear message. Are they here people who think that such a so-called "mistake" is not a mistake ? That David programmed the way he (and we, humans should ; and that the error lies in language, not in his brain ? Why are indexes based on 0 instead of 1 ? denis [PS : if you're interested in such a way of reflexion, like "ameliorating python", or "the ideal programming language", I would really welcome your ideas -- outside the list] > ----- Original Message ----- > From: David Broadwell > To: > Sent: Monday, April 12, 2004 5:00 PM > Subject: [Tutor] 'Common' mistake ... for other newbies > > > > I started with the text below, but if you don't like detailed reports of > > newbie fumbles, skip this post. Points to not quitting but continuing to > > hack at it ... my first real bug. > > > > ... > > > > I'm having an odd problem that I don't know how to debug. > > What is going on is as a exercise, I'm playing rock paper scissors in > code. > > I'm using; Python 2.2, Windows2kServer, PII450@386mb w/80gb > > > > ... > > > > At full run with a 100 item result list it failed on the average 97th > roll, > > but with a 6 entry list only averages 10 rolls instead before dying. It > > seems that the smaller the resultlist the more often an IndexError occurs. > > > > The code is like this (static data for brevity); > > > > >>> from random import randint > > >>> resultlist = ['rock','paper','scissors','rock','paper','scissors'] > > >>> def roll(): > > ''' returns a random item from resultlist ''' > > return resultlist[randint(0,len(resultlist))] > > > > >>> for item in range(1000): > > roll() > > > > 'scissors' > > 'paper' > > 'paper' > > 'paper' > > 'paper' > > 'rock' > > 'scissors' > > Traceback (most recent call last): > > File "", line 2, in ? > > roll() > > File "", line 3, in roll > > return resultlist[randint(0,len(resultlist))] > > IndexError: list index out of range > > >>> > > > > So to debug, I rewrote roll into debugroll() > > > > >>> def debugroll(): > > temp = len(resultlist) > > print "len(resultlist) = %s" % temp > > temp = randint(0,temp) > > print "randint(0,len(resultlist)) = %s" % temp > > temp = resultlist[temp] > > print "resultlist[randint(0,len(resultlist))] = %s" % temp > > return temp > > > > >>> for item in range(1000): > > debugroll() > > > > len(resultlist) = 6 > > randint(0,len(resultlist)) = 5 > > resultlist[randint(0,len(resultlist))] = scissors > > 'scissors' > > len(resultlist) = 6 > > randint(0,len(resultlist)) = 6 > > Traceback (most recent call last): > > File "", line 2, in ? > > debugroll() > > File "", line 6, in debugroll > > temp = resultlist[temp] > > IndexError: list index out of range > > > > after a bit more testing (or frantically repeating the error) I noted that > > it only died when the randomly generated index was 6 ... and then it hit > me, > > a list of len 6 has no index six and the uncrashable roll function needed > to > > reflect that is as follows. > > > > The solution; > > >>> def roll(): > > ''' returns a random item from resultlist ''' > > return resultlist[randint(0,len(resultlist)-1)] > > > > ... > > > > I got bit because I count from 1 and the computer counts from 0, a > 'common' > > mistake. > > > > As a note this was the last hurdle to having the code play rock paper > > scissors against itself, I'm sure it's not nearly as elegant as it could > be, > > but it's very, very, readable. > > > > -- > > > > Programmer's mantra; Observe, Brainstorm, Prototype, Repeat > > > > David Broadwell > > > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > From amonroe at columbus.rr.com Mon Apr 12 17:54:32 2004 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Mon Apr 12 17:46:36 2004 Subject: [Tutor] 'Common' mistake ... for other newbies In-Reply-To: <008901c420d6$3bb19340$ae2ae4d5@spir> References: <008901c420d6$3bb19340$ae2ae4d5@spir> Message-ID: <1581808510770.20040412175432@columbus.rr.com> > Why are indexes based on > 0 instead of 1 ? I always chalked this up to computers running on electricity, and the base state being "all the electricity turned off". Even if it's not accurate it's a handy mnemonic. Alan From dyoo at hkn.eecs.berkeley.edu Mon Apr 12 18:50:48 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Apr 12 18:51:00 2004 Subject: [Tutor] 'Common' mistake ... for other newbies [counting starts at zero?] In-Reply-To: <008901c420d6$3bb19340$ae2ae4d5@spir> Message-ID: On Mon, 12 Apr 2004, denis wrote: > Are they here people who think that such a so-called "mistake" is not a > mistake ? That David programmed the way he (and we, humans should ; and > that the error lies in language, not in his brain ? Why are indexes > based on 0 instead of 1 ? Hi Denis, It's not a mistake, but it is one of those points of confusion: http://c2.com/cgi/wiki?ZeroAndOneBasedIndexes Edgar Dijkstra wrote a memo about this (also linked from the above url): http://www.cs.utexas.edu/users/EWD/ewd08xx/EWD831.PDF So this is something that has been at least planned --- it's not an arbitrary feature that indices start at zero. There are some other nice features about zero indexing. Let's say that we have a sample of words: ### >>> def sample(L, n=50): ... """Returns a random sampling of 'n' elements out of L.""" ... L2 = [(random.random(), x) for x in L] ... L2.sort() ... return [x for (r, x) in L2[:n]] ... >>> words = sample([w.strip() for w in open('/usr/share/dict/words')], 20) >>> words ['acquired', 'Rocco', 'alternatively', 'acculturates', 'asphyxia', 'parcel', 'establish', 'antagonizing', 'unreliable', 'triangular', 'silt', 'inflatable', 'regards', 'nugget', 'seeker', 'eigenvalue', 'antiquarian', 'seducing', 'immerse', 'plastered'] ### and want to break these words down into a few groups. There are at least two direct ways of doing this, based on simple arithmetic: the division and the remainder operations: ### >>> for i in range(len(words)): ... print words[i], i / 5 ... acquired 0 Rocco 0 alternatively 0 acculturates 0 asphyxia 0 parcel 1 establish 1 antagonizing 1 unreliable 1 triangular 1 silt 2 inflatable 2 regards 2 nugget 2 seeker 2 eigenvalue 3 antiquarian 3 seducing 3 immerse 3 plastered 3 >>> >>> >>> for i in range(len(words)): ... print words[i], i % 4 ... acquired 0 Rocco 1 alternatively 2 acculturates 3 asphyxia 0 parcel 1 establish 2 antagonizing 3 unreliable 0 triangular 1 silt 2 inflatable 3 regards 0 nugget 1 seeker 2 eigenvalue 3 antiquarian 0 seducing 1 immerse 2 plastered 3 ### That is, we can use the division operation on the indicies to say that: 'acquired', 'Rocco', 'alternatively', 'acculturates', and 'asphyxia' are all part of a single group. Or we can use the remainder operation, and say that: 'acquired', 'asphyxia', 'unreliable', 'regards' and 'antiquarian' are all in the same group. This divisioning is simple, and quite easy to get right. But if the indexing of list elements starts at one instead of zero, then the process above will involve adding or subtracting 1's to make the math work out. It's also possibly a lot more error prone for newcomers (as well as experienced programmers!) to see off-by-one errors. This isn't to say that 0-based indexing is always easier to deal with than 1-based indexing. But in the majority of cases that we deal with, 0-based indexing seems to be a big win. Hope this helps! From jb at riseup.net Mon Apr 12 18:51:09 2004 From: jb at riseup.net (jb) Date: Mon Apr 12 18:53:36 2004 Subject: [Tutor] 'Common' mistake ... for other newbies In-Reply-To: <008901c420d6$3bb19340$ae2ae4d5@spir> References: <008901c420d6$3bb19340$ae2ae4d5@spir> Message-ID: <20040412225109.GB10373@mubai.sakeos.net> On Mon, Apr 12, 2004 at 11:36:32PM +0200, denis wrote: > > Well, > > Thank you David for this clear message. > Are they here people who think that such a so-called "mistake" is not a > mistake ? That David programmed the way he (and we, humans should ; and > that the error lies in language, not in his brain ? Why are indexes based on > 0 instead of 1 ? most computer people come from the C programming language, and indexes start from 0 in C, so this is what many people are used to. it's my understanding that indexes start from 0 in C to simplify pointer arithmetics: in C, when you want to use an array, you need to allocate a block of memory to store it: here I use an array a with room for 3 integers: I have to allocate it with the following incantation: "a = (int*) malloc(3*sizeof(int))" - the value that will be stored in "a" is the address of the first cell of the array in memory. a a+1 a+2 <- addresses in memory __________________ | | | | | 5 | 4 | 3 | <- values stored in my array |_____|_____|_____| if you want consistency between the place of something in the array and its place in memory (i.e. its address in memory), the simplest thing is to use the convention that indexes start at 0, so that you can write horrors like *a (same as a[0]), *(a+1) (same as a[1]), etc. some languages (FORTRAN and probably others) have indexes that start from 1, but they have no pointers. also, counting from 0 or from 1 really depends on the person. When I was at school, i had no fun putting variables i had called x0, x1 in arrays indexed from 1 (in FORTRAN, of course.), and at that time, I had not been brainwashed by programming languages :) i hope this helps. jb From dbroadwell at mindspring.com Mon Apr 12 19:02:25 2004 From: dbroadwell at mindspring.com (David Broadwell) Date: Mon Apr 12 18:57:33 2004 Subject: [Tutor] 'Common' mistake ... for other newbies In-Reply-To: <008901c420d6$3bb19340$ae2ae4d5@spir> Message-ID: > Thank you David for this clear message. Glad I decided to send anyway ... but it seeded a shame to waste the thought on it. > Are they here people who think that such a so-called "mistake" > is not a mistake ? Not in though but; > That David programmed the way he (and we, humans should and > that the error lies in language, not in his brain ? I DID have an error, I was going the long way around of getting a random item from a list. The function for that is; random.choice([someindexibleitem]) instead of; someindexibleitem[random.randint(0,len(someindexibleitem)-1)] Which are computationally equivalent in effect. Can't answer about speed, In that situation, I should never have been wasting my personal runtime on numerical indexes, is not python a 'very' high level language after all? > Why are indexes based on 0 instead of 1 ? Tradition. And having done basic logic circuits, I should have known better. Call it a mistake from a 6 month lapse in coding. Wasting my brain time is in fact WHY I started programming at all. I hate doing things twice. Especially typing them twice. I hit a case of repetitive copying and pasting of text files 425 of them into a new format and decided it was time to code a routine. Other commentary of why one started programming? > [PS : if you're interested in such a way of reflexion, like "ameliorating > python", or "the ideal programming language", I would really welcome your > ideas -- outside the list] I kind of think there is no perfect language, so far python (my first language grok) is the closest that has trained the ability to be functional as well as close. -- Programmer's mantra; Observe, Brainstorm, Prototype, Repeat David Broadwell From dyoo at hkn.eecs.berkeley.edu Mon Apr 12 19:08:23 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Apr 12 19:19:16 2004 Subject: [Tutor] 'Common' mistake ... for other newbies In-Reply-To: Message-ID: On Mon, 12 Apr 2004, David Broadwell wrote: > > Are they here people who think that such a so-called "mistake" is not > > a mistake ? > Not in though but; > > > That David programmed the way he (and we, humans should and > > that the error lies in language, not in his brain ? > I DID have an error, I was going the long way around of getting a random > item from a list. > > The function for that is; > > random.choice([someindexibleitem]) > > instead of; > > someindexibleitem[random.randint(0,len(someindexibleitem)-1)] Hi David, Yes. Furthermore, random.randint() is deprecated: we shouldn't be using it if we can help it: ### >>> help(random.randint) Help on method randint in module random: randint(self, a, b) method of random.Random instance Return random integer in range [a, b], including both end points. (Deprecated; use randrange(a, b+1).) ### randint() is deprecated precisely because it is prone to one-off errors, like the one that the original poster ran into. The original code would have been fine if random.randrange() were used: someindexibleitem[random.randrange(0, len(someindexibleitem))] Hope this helps! From alan.gauld at blueyonder.co.uk Mon Apr 12 19:38:09 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Mon Apr 12 19:36:58 2004 Subject: [Tutor] Newbie - mixing floats and integers (first post) References: <4079B662.9060007@monkeez.org> <20040412203755.6cee07df.adam@monkeez.org> Message-ID: <00a701c420e7$365a0560$6401a8c0@xp> > helpful than the Java forums). I really liked the idea of > checking for a '.' and then casting appropriately (does > casting mean anything in python)? Not really, the "cast" that Danny used is actually a conversion. casting means treat the data (without changing it) as if it were some other type. Conversion means take the data and change it into some other type. Python converts data it doesn't cast it. > I'll be staying :-) Your welcome aboard :-) Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at blueyonder.co.uk Mon Apr 12 19:50:00 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Mon Apr 12 19:48:51 2004 Subject: [Tutor] new to python error handling question References: <20040412204503.15843.qmail@web21408.mail.yahoo.com> Message-ID: <00b101c420e8$de5b6690$6401a8c0@xp> Erick, I think you maybe need to slow down and take a few steps back here. There are a few weird things in your code that suggest you don't really understand whats happening and that will lead to problems later. BTW YOu don;t say if you have any previous programming experience in other languages? If so that helps us phrase our responses. > def do_list(*??*): The *??* is where you pass in values that your function will use. In this function a sensible thing wouyld be the address used by the ftp.retrlines call def do_list(address): > try: > ftp.retrlines("list") You would then use the address parameter in here ftp.retrlines(address) > pass You don't need this it literally does nothing! > except (AttributeError): This checks for an AttributeError being raised in the previous try section. BTW I donlt think you need the parens around AttributeError. If the try/except was missed out the error would be passed back to Python and it would print an error message. > print "AttributeError" > pass Again the pass does nothing > return () And this returns an empty tuple to the caller, which is probably not what you want? > Why does it for sure detect AttributError when > if i take the Try,Except off, it does'nt. Dunno, can you show/tell us what you do get without the try/except? It looks like you need to read the bit about defining functions in your tutorial (whichever it is) soince you seem confused about how they work. Also the try/except stuff. Both are covered in my web tutor if you can't find it elsewhere, look under "Modules & Functions" and "Error Handling" Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at blueyonder.co.uk Mon Apr 12 19:59:24 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Mon Apr 12 19:59:31 2004 Subject: [Tutor] 'Common' mistake ... for other newbies References: <008901c420d6$3bb19340$ae2ae4d5@spir> Message-ID: <00b801c420ea$2e871fa0$6401a8c0@xp> > Are they here people who think that such a so-called "mistake" is not a > mistake ? That David programmed the way he (and we, humans should ; and > that the error lies in language, not in his brain ? Why are indexes based on > 0 instead of 1 ? In some languages they aren't but it has become part of programming culture. Partly it comes from the C language. And the reason it adopted it is that it used the index as an address offset. So the first element of the array was located at the list location itself (zero offset) and the next element was at the list location plus one, so index one. Some ASCII art follows, it will only work on fixed width fonts like courier... List -----> Item1 Address = 12345 => List + 0 | Item2 Address = 12346 => List + 1 | Item3 Address = 12347 => List + 2 | . | . +----> ItemN Address = 123XX => List + N-1 Thus for any language written in C it is very easy to implement zero based indexing. And experienced programmers are used to it. There are also some mathematical reasons for doing this in that it makes some algorithms easier to code, but I believe the real reason was just the ease of creating fast indexing based on address arithmeticin C, and now its traditional. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From adam at monkeez.org Tue Apr 13 05:58:42 2004 From: adam at monkeez.org (Adam) Date: Tue Apr 13 06:00:59 2004 Subject: [Tutor] Newbie - mixing floats and integers (first post) In-Reply-To: <00a701c420e7$365a0560$6401a8c0@xp> References: <4079B662.9060007@monkeez.org> <20040412203755.6cee07df.adam@monkeez.org> <00a701c420e7$365a0560$6401a8c0@xp> Message-ID: <407BB9D2.3020109@monkeez.org> Alan Gauld wrote: >>helpful than the Java forums). I really liked the idea of >>checking for a '.' and then casting appropriately (does >>casting mean anything in python)? >> >> > >Not really, the "cast" that Danny used is actually a conversion. >casting means treat the data (without changing it) as if it were >some other type. Conversion means take the data and change it >into some other type. Python converts data it doesn't cast it. > > > >>I'll be staying :-) >> >> > >Your welcome aboard :-) > >Alan G >Author of the Learn to Program web tutor >http://www.freenetpages.co.uk/hp/alan.gauld > > Alan, Thanks once again for your comments - it is becoming clearer. It is often good to know what goes on under the hood and how data is treated. I'm working my way through "Learning Python" (thanks to http://safari.oreilly.com) which is proving to be a very good starting document - I can recommend this to others if they're just starting out. Thanks once again. adam From Chad.Crabtree at nationalcity.com Tue Apr 13 11:30:48 2004 From: Chad.Crabtree at nationalcity.com (Crabtree, Chad) Date: Tue Apr 13 11:31:13 2004 Subject: [Tutor] New Style Classes Message-ID: <66F587DFDD46D511B65200508B6F8DD60EF88EF8@nt-kalopsapp07.ntl-city.com> I have not found any good documentation on the New Style Classes "class foo(object):" Could somone please point me in a good direction. I've googled but I only get examples of how to do it. Not mind you why. ------------------------------------------------------------------------------------------- ***National City made the following annotations ------------------------------------------------------------------------------------------- This communication is a confidential and proprietary business communication. It is intended solely for the use of the designated recipient(s). If this communication is received in error, please contact the sender and delete this communication. =========================================================================================== From denis.spir at free.fr Tue Apr 13 12:40:30 2004 From: denis.spir at free.fr (denis) Date: Tue Apr 13 12:44:04 2004 Subject: [Tutor] more on index handling References: <008901c420d6$3bb19340$ae2ae4d5@spir> <00b801c420ea$2e871fa0$6401a8c0@xp> Message-ID: <007801c42176$815c8bc0$db25933e@spir> Thank you for all these answers about index base 0 in python ; which lead to one more question and a comment. Question : why does python exclude the last index of a slice ? Below what I mean : ************ >>> l=[1,2,3,4,5] >>> l[1:3] [2, 3] ************ I would "naturally" expect that l[1:3] returns [1,2,3], but as i know that the indexes are 0-based I expect python to return [2,3,4]. Actually by a slice extraction the last index in excluded, which seems even trickier than the simple indexing. To be noughty, it's a bit inconsistent notation, because [a:b] meens (in math) "for a to b, including both borders", while here we get in fact a:b[ , that is "for a to b, including a but not b". Comment about index base 0 : I really understand the (C) historical reasons -- and the algorithmic tricks one can "base" (sic) on it. I knew a bit of this, and also like most of python users chose that language precisely for the reason that it breaks with many of the (unfounded and) unreadable syntactic rules of the former (and present) computer dialects. I like clear and more natural code. I also have in mind the explicite purpose that python be an easy to learn language (because more natural), and Guido's "CP4E" project (computer programming for everybody). Isn't all of this worth letting down such weird syntax forms ? That's why i wish that l[1] returns the first element of l, and l[len(l)] the last one -- instead of an error ! Human brains work so, or what ? I guess no street in the whole world has a number zero (#0) ; there is no year 0 ; and the 1st subscriber in this list wasn't the 0th. Well, that's enough, you understand what i mean... may python lead you to joy ! denis From dyoo at hkn.eecs.berkeley.edu Tue Apr 13 13:57:42 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Apr 13 13:58:42 2004 Subject: [Tutor] more on index handling In-Reply-To: <007801c42176$815c8bc0$db25933e@spir> Message-ID: On Tue, 13 Apr 2004, denis wrote: > Thank you for all these answers about index base 0 in python; which lead > to one more question and a comment. > > Question : why does python exclude the last index of a slice ? Below > what I mean : > > ************ > >>> l=[1,2,3,4,5] > >>> l[1:3] > [2, 3] > ************ > > I would "naturally" expect that l[1:3] returns [1,2,3], but as i know > that the indexes are 0-based I expect python to return [2,3,4]. Actually > by a slice extraction the last index in excluded, which seems even > trickier than the simple indexing. Hi Denis, Python's slices act like "half-open" intervals --- you're probably familiar with the mathematical notation: [0:5) to include the numbers: [0, 1, 2, 3, 4]. > Question : why does python exclude the last index of a slice ? Half-open intervals --- the ones that exclude the last index --- have nice properties. For example, they "glue" together very well: ### >>> range(0, 5) + range(5, 10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] ### and, in the reverse direction, it's easy to split a list in half without having to worry about +1/-1 stuff: ### >>> numbers = range(10) >>> numbers [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> numbers[:3], numbers[3:] ([0, 1, 2], [3, 4, 5, 6, 7, 8, 9]) ### It's also very easy to count how many elements there are in a slice. If we're slicing: l[1:3] then it's just a matter of a direct subtraction to say that there are two elements in the slice. All the operations above become just slightly more difficult with closed intervals. With closed intervals, there's more need to do +1 and -1 stuff for casual list manipulation. Half-open intervals appear to reduce the chance for off-by-one errors. > Human brains work so, or what ? I guess no street in the whole world has > a number zero (#0) ; there is no year 0 ; and the 1st subscriber in this > list wasn't the 0th. Well, that's enough, you understand what i mean... Sure, it's perfectly understandable that zero is weird. It is. (In fact, there are also several languages that start from one instead of zero. Fortran is one of them, and is still very popular with the numerical folks. Most reasonable languages stick with a single choice, and consistantly use it.) Questions about starting from zero come up a lot. In fact, it was on the 'edu-sig' Python-in-education list just a few months back: http://mail.python.org/pipermail/edu-sig/2004-January/003468.html So counting from zero and the use of half-open intervals may be the source of a never-ending debate. *grin* Good luck! From askoose at sandia.gov Tue Apr 13 15:11:40 2004 From: askoose at sandia.gov (Kooser, Ara S) Date: Tue Apr 13 15:11:55 2004 Subject: [Tutor] Filter question Message-ID: <9A4B2157EFDBE546BECD68C62AC3B1C81738F0C2@es05snlnt.sandia.gov> Hello, I am new to python. I am trying to covert one file type to another (molecular dynamics output to visualizer input). I have set up the following filter, but it is not working. I don't receive an error message just a blank prompt at shell. Here is the code. I am trying to filter out any line the begins with I. I am using python 2.3.3. Thanks. Ara def filterFile(lmps, out): inp = open("lmps","r") outp = open("out","w") while 1: text = inp.readline() if line == "": break if line[0] == 'I': continue outp.write(line) inp.close() outp.close() -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040413/aabf8e5a/attachment.html From yduppen at xs4all.nl Tue Apr 13 15:13:47 2004 From: yduppen at xs4all.nl (Yigal Duppen) Date: Tue Apr 13 15:13:51 2004 Subject: [Tutor] more on index handling In-Reply-To: <007801c42176$815c8bc0$db25933e@spir> References: <008901c420d6$3bb19340$ae2ae4d5@spir> <00b801c420ea$2e871fa0$6401a8c0@xp> <007801c42176$815c8bc0$db25933e@spir> Message-ID: <200404132113.48130.yduppen@xs4all.nl> On Tuesday 13 April 2004 18:40, denis wrote: > Thank you for all these answers about index base 0 in python ; which lead > to one more question and a comment. > > Question : why does python exclude the last index of a slice ? There is a nice paper by Dijkstra which explains the different approaches: http://www.cs.utexas.edu/users/EWD/transcriptions/EWD08xx/EWD831.html YDD -- http://www.xs4all.nl/~yduppen From dyoo at hkn.eecs.berkeley.edu Tue Apr 13 15:31:48 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Apr 13 15:31:53 2004 Subject: [Tutor] Filter question In-Reply-To: <9A4B2157EFDBE546BECD68C62AC3B1C81738F0C2@es05snlnt.sandia.gov> Message-ID: > (molecular dynamics output to visualizer input). I have set up the > following filter, but it is not working. I don't receive an error > message just a blank prompt at shell. Here is the code. I am trying to > filter out any line the begins with I. I am using python 2.3.3. Thanks. > > Ara > > def filterFile(lmps, out): > inp = open("lmps","r") > outp = open("out","w") > while 1: > text = inp.readline() > if line == "": > break > if line[0] == 'I': > continue > outp.write(line) > > inp.close() > outp.close() Hi Ara, There's a bug in the file opening code: ### def filterFile(lmps, out): inp = open("lmps","r") outp = open("out","w") ... ### The code, as written, is trying to open up a file that's literally named 'Imps' for reading. It's also trying to open up a file that is literally called 'out'. Hope this helps! From askoose at sandia.gov Tue Apr 13 15:50:33 2004 From: askoose at sandia.gov (Kooser, Ara S) Date: Tue Apr 13 15:50:43 2004 Subject: [Tutor] Filter question Message-ID: <9A4B2157EFDBE546BECD68C62AC3B1C81738F0C4@es05snlnt.sandia.gov> Thank you for the reply. I first tried just a simple copy from with the same opening code and I had no problem. When I added the filter statement then it stopped working. I will go read up more on the folterFile. I guess I am entering something wrong. Here is the copy code I used. inp = open("lmps.txt","r") outp = open("out.txt","w") for line in inp.readlines(): outp.write(line) print "1 file copied" inp.close() outp.close() -----Original Message----- From: Danny Yoo [mailto:dyoo@hkn.eecs.berkeley.edu] Sent: Tuesday, April 13, 2004 1:32 PM To: Kooser, Ara S Cc: 'tutor@python.org' Subject: Re: [Tutor] Filter question > (molecular dynamics output to visualizer input). I have set up the > following filter, but it is not working. I don't receive an error > message just a blank prompt at shell. Here is the code. I am trying to > filter out any line the begins with I. I am using python 2.3.3. > Thanks. > > Ara > > def filterFile(lmps, out): > inp = open("lmps","r") > outp = open("out","w") > while 1: > text = inp.readline() > if line == "": > break > if line[0] == 'I': > continue > outp.write(line) > > inp.close() > outp.close() Hi Ara, There's a bug in the file opening code: ### def filterFile(lmps, out): inp = open("lmps","r") outp = open("out","w") ... ### The code, as written, is trying to open up a file that's literally named 'Imps' for reading. It's also trying to open up a file that is literally called 'out'. Hope this helps! From marilyn at deliberate.com Tue Apr 13 16:14:37 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Tue Apr 13 16:14:41 2004 Subject: [Tutor] mod_python and PIL? Message-ID: Hello, I don't know if this is the best place for this question, but if it isn't, I do know that this is the best place to be pointed to the right place. I just upgraded to 2.3.3 and I put in PIL and made a mod_python for Apache. But when I run my script as a cgi, it can't import Image. When I run it directly, it finds Image just fine. In fact, all my (many) resident versions of python find Image. So what could be wrong? Is there a way to find out for sure which version of python is running? Can I output the version number? Thank you for your help. Marilyn Davis From denis.spir at free.fr Tue Apr 13 16:24:02 2004 From: denis.spir at free.fr (denis) Date: Tue Apr 13 16:24:54 2004 Subject: [Tutor] Filter question References: <9A4B2157EFDBE546BECD68C62AC3B1C81738F0C2@es05snlnt.sandia.gov> Message-ID: <001801c42195$58f34c40$ad72933e@spir> Two comments : You try to open files using (between quotes) the names of the function parameters, while they already are strings. You shoulg get an error, unless there actually is in your current directory a file called "lmps". Try without quotes. The way you list the lines of your input files is a bit hard. There are more readable loop structures for that, like (not tested) : *** lines = inp.readlines() for l in lines: if l[0] == 'L' : outp.write(l) *** You don't need to 'wildly' test for the eof. denis ----- Original Message ----- From: Kooser, Ara S To: Sent: Tuesday, April 13, 2004 9:11 PM Subject: [Tutor] Filter question > Hello, > > I am new to python. I am trying to covert one file type to another > (molecular dynamics output to visualizer input). I have set up the following > filter, but it is not working. I don't receive an error message just a blank > prompt at shell. Here is the code. I am trying to filter out any line the > begins with I. I am using python 2.3.3. Thanks. > > Ara > > def filterFile(lmps, out): > inp = open("lmps","r") > outp = open("out","w") > while 1: > text = inp.readline() > if line == "": > break > if line[0] == 'I': > continue > outp.write(line) > > inp.close() > outp.close() > ---------------------------------------------------------------------------- ---- > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From dyoo at hkn.eecs.berkeley.edu Tue Apr 13 16:53:15 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Apr 13 16:53:19 2004 Subject: [Tutor] Filter question ["quotation" and parameters] In-Reply-To: <9A4B2157EFDBE546BECD68C62AC3B1C81738F0C4@es05snlnt.sandia.gov> Message-ID: On Tue, 13 Apr 2004, Kooser, Ara S wrote: > Thank you for the reply. I first tried just a simple copy from with the > same opening code and I had no problem. When I added the filter > statement then it stopped working. I will go read up more on the > folterFile. I guess I am entering something wrong. Here is the copy code > I used. > > inp = open("lmps.txt","r") > outp = open("out.txt","w") > for line in inp.readlines(): > outp.write(line) > print "1 file copied" > inp.close() > outp.close() Hi Kooser, Sure, this code makes sense. The program here opens up a file named 'lmps.txt', and writes a copy out to 'out.txt'. Let's oversimplify things for a moment. Say that we have the following function: ### def sayHello(name): print "Hello" print name ### What happens if we redefine this as this? ### def sayHello(name): print "Hello" print "name" ### Does this make sense? Please feel free to ask questions about this. Good luck! From dyoo at hkn.eecs.berkeley.edu Tue Apr 13 16:58:47 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Apr 13 16:58:51 2004 Subject: [Tutor] mod_python and PIL? In-Reply-To: Message-ID: On Tue, 13 Apr 2004, Marilyn Davis wrote: > I just upgraded to 2.3.3 and I put in PIL and made a mod_python for > Apache. But when I run my script as a cgi, it can't import Image. When > I run it directly, it finds Image just fine. In fact, all my (many) > resident versions of python find Image. > > So what could be wrong? Hi Marilyn, It sounds like you may have multiple versions of Python installed. The PATH that the mod_python programs are running under may be different than the one in your current environment. Can you check to see if you can change which Python is running for mod_python? > Is there a way to find out for sure which version of python is running? > Can I output the version number? Yes. Here you go: ### >>> import sys >>> print sys.version 2.2.1 (#1, Sep 3 2002, 14:52:01) [GCC 2.96 20000731 (Red Hat Linux 7.3 2.96-112)] ### Good luck to you. From dyoo at hkn.eecs.berkeley.edu Tue Apr 13 17:07:57 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Apr 13 17:08:05 2004 Subject: [Tutor] New Style Classes In-Reply-To: <66F587DFDD46D511B65200508B6F8DD60EF88EF8@nt-kalopsapp07.ntl-city.com> Message-ID: On Tue, 13 Apr 2004, Crabtree, Chad wrote: > I have not found any good documentation on the New Style Classes "class > foo(object):" Could somone please point me in a good direction. I've > googled but I only get examples of how to do it. Not mind you why. Hi Chad, The pages on New-Style classes might be useful: http://www.python.org/2.2.3/descrintro.html http://www.python.org/doc/newstyle.html Does the tutorial help from the first link help? What parts of it are completely opaque? *grin* Hope this helps! From garryknight at gmx.net Tue Apr 13 16:27:03 2004 From: garryknight at gmx.net (Garry Knight) Date: Tue Apr 13 18:11:12 2004 Subject: [Tutor] Re: New Style Classes References: <66F587DFDD46D511B65200508B6F8DD60EF88EF8@nt-kalopsapp07.ntl-city.com> Message-ID: In message <66F587DFDD46D511B65200508B6F8DD60EF88EF8@nt-kalopsapp07.ntl-city.com>, Crabtree, Chad wrote: > I have not found any good documentation on the New Style Classes "class > foo(object):" Could somone please point me in a good direction. I've > googled but I only get examples of how to do it. Not mind you why. Did you find this one? http://www.python.org/doc/newstyle.html -- Garry Knight garryknight@gmx.net ICQ 126351135 Linux registered user 182025 From jsidiqi at hotmail.com Tue Apr 13 18:33:31 2004 From: jsidiqi at hotmail.com (ABDUL JABBAR SIDDIQUE) Date: Tue Apr 13 18:33:38 2004 Subject: [Tutor] Reading multiple text files and writing data on one file Message-ID: An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040413/26ddd6d8/attachment.html From alan.gauld at blueyonder.co.uk Tue Apr 13 18:44:17 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Apr 13 18:44:11 2004 Subject: [Tutor] more on index handling References: <008901c420d6$3bb19340$ae2ae4d5@spir><00b801c420ea$2e871fa0$6401a8c0@xp> <007801c42176$815c8bc0$db25933e@spir> Message-ID: <011301c421a8$daaba1c0$6401a8c0@xp> > Question : why does python exclude the last index of a slice ? Below what I > mean : > ************ > >>> l=[1,2,3,4,5] > >>> l[1:3] > [2, 3] > ************ > I would "naturally" expect that l[1:3] returns [1,2,3], but as i know that > the indexes are 0-based I expect python to return [2,3,4]. Slices are different :-) They work like a knife being inserted before the items you specify. So thinking of [1,2,3,4,5] Inset the knife before item 1 and item 3 (at the comma if you like) and you get [2,3]... Why? Dunno, but it's consistent with the range function range(1,3) returns [1,2] not [1,2,3] and slicing [0,1,2,3] with [1:3} returns [1,2] the same as range. So you can think of range as a type of slicing function... No it's not very convincing is it?! :-) Alan G. From alan.gauld at blueyonder.co.uk Tue Apr 13 18:47:43 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Apr 13 18:47:34 2004 Subject: [Tutor] more on index handling References: Message-ID: <011801c421a9$551b7930$6401a8c0@xp> > Half-open intervals --- the ones that exclude the last index --- have nice > properties. For example, they "glue" together very well: > > ### > >>> range(0, 5) + range(5, 10) > [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] And of course thats obvious with literal numbers but when the values are stored in variables like: range(0,mid_point) + range(mid_point,limit) The advantages may be more obvious. I had seen that explanation before but had forgotten. Thanks for the reminder Danny. Alan G. From alan.gauld at blueyonder.co.uk Tue Apr 13 18:54:07 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Apr 13 18:53:58 2004 Subject: [Tutor] Filter question References: <9A4B2157EFDBE546BECD68C62AC3B1C81738F0C2@es05snlnt.sandia.gov> Message-ID: <012001c421aa$3a60dd00$6401a8c0@xp> > def filterFile(lmps, out): > inp = open("lmps","r") > outp = open("out","w") > while 1: > text = inp.readline() > if line == "": > break > if line[0] == 'I': > continue > outp.write(line) It looks like it should work. You could try a debug print statement after reading the line, just to check you are getting the data OK. Also in 2.3 it might be easier to use a for loop: def filterFile(filename, outputfile): inf = file(filename) outf = file(outputfile, 'w') for line in inf: if not line[0] == 'I': out.write(line) # may need to add \n... inf.close() outf.close() HTH, Alan G. From magnus at thinkware.se Tue Apr 13 20:13:28 2004 From: magnus at thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Tue Apr 13 20:10:52 2004 Subject: [Tutor] MySQLdb: dropping zeroes! In-Reply-To: <20040407155636.GC1860@johnsons-web.com> References: <1081341204.7860.15.camel@laptop.venix.com> <20040407020428.GY1860@johnsons-web.com> <1081341204.7860.15.camel@laptop.venix.com> Message-ID: <5.2.1.1.0.20040414020842.02f5ee20@www.thinkware.se> At 07:56 2004-04-07 -0800, Tim Johnson wrote: > To quote the mysql manual: > > "The DECIMAL type is considered a numeric type (as is its synonym, > NUMERIC), but such values are stored as strings." > > So I thought there might be a way to override the > MySQLdb type conversion and get them back as strings. The problem (which I hope will be fixed in a not too far future) is that Python lacks a standard decimal type/class. ADODBAPI does it the other way around, and returns DECIMAL as strings, and that's not without problems either. For instance, with e.g. Swedish settings in Windows, 1/2 will be returned as '0,5', not '0.5', and float('0,5') won't make Python happy. Anyway, I guess you could replace "SELECT X FROM Y" with "SELECT CAST(X AS CHAR(10)) AS X FROM Y" or something like that. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From dyoo at hkn.eecs.berkeley.edu Tue Apr 13 20:30:40 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Apr 13 20:30:57 2004 Subject: [Tutor] Reading multiple text files and writing data on one file In-Reply-To: Message-ID: On Tue, 13 Apr 2004, ABDUL JABBAR SIDDIQUE wrote: > First of all I must tell all of you that I'm new to programming. So > please bear with me. Hi Abdul, Not a problem; please tell us if the explanations or answers you get are weird. *grin* Let's take a look at the code: > # Create the equivalent of: COPY MENU.TXT MENU.BAK > > # First open the files to read(r) and write(w) > inp = open("S_1.OUT","r") > outp1 = open ("O_1.csv","w") > > i=0 > for line in inp.readlines(): > i=i+1 > if i > 5 and i <= 76: > outp1.write((line[:12]+line[88:96])+"\n") > > print "1 file copied..." > > # Now close the files > inp.close() > outp1.close() It's possible to 'for loop' across a file without having to read all of its lines at once. You may want to rewrite the loop from: ### for line in inp.readlines(): ... ### to: ### for line in inp: ... ### This becomes more important when the files get much larger. > I dont know how to further read selected data from say "S_2.OUT, S_3.OUT > etc" and write it to the same file i.e. "outp1.csv. Just to verify: for each of the other files, do you also want to restrict the captured lines from the 5th through to the 76th's lines? It sounds like you want to repeat the process of: ### i=0 for line in inp: i=i+1 if i > 5 and i <= 76: outp1.write((line[:12]+line[88:96])+"\n") ### over and over, for S_2.OUT, S_3.OUT, etc. Let's first give a name to this process: ### def process(inp, outp): i=0 for line in inp: i=i+1 if i > 5 and i <= 76: outp.write((line[:12]+line[88:96])+"\n") ### If we have this function, then the program can look like this: ### def process(inp, outp): i=0 for line in inp: i=i+1 if i > 5 and i <= 76: outp.write((line[:12]+line[88:96])+"\n") inp = open("S_1.OUT","r") outp1 = open ("O_1.csv","w") process(inp, outp1) print "1 file copied..." # Now close the files inp.close() outp1.close() ### Does this make sense so far? Hope this helpS! From marilyn at deliberate.com Tue Apr 13 20:49:41 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Tue Apr 13 20:49:47 2004 Subject: [Tutor] mod_python and PIL? In-Reply-To: Message-ID: Thank you Danny. On Tue, 13 Apr 2004, Danny Yoo wrote: > > > On Tue, 13 Apr 2004, Marilyn Davis wrote: > > > I just upgraded to 2.3.3 and I put in PIL and made a mod_python for > > Apache. But when I run my script as a cgi, it can't import Image. When > > I run it directly, it finds Image just fine. In fact, all my (many) > > resident versions of python find Image. > > > > So what could be wrong? > > > Hi Marilyn, > > It sounds like you may have multiple versions of Python installed. The > PATH that the mod_python programs are running under may be different than > the one in your current environment. Can you check to see if you can > change which Python is running for mod_python? > It's still the old mod_python because I forgot to "apachectl restart". Duh. But doing so tells me: Cannot load /www/libexec/mod_python.so into server: /www/libexec/mod_python.so: undefined symbol: pthread_sigmask And I'm stumped. For python2.3.3: [root@maildance mod_python-2.7.8]# cd ../Python-2.3.3 [root@maildance Python-2.3.3]# ./configure --with-threads=no running build running build_ext much deleted ... *** WARNING: renaming "_testcapi" since importing it failed: build/lib.linux-i686-2.3/_testcapi.so: undefined symbol: PyGILState_Ensure *** WARNING: renaming "_bsddb" since importing it failed: build/lib.linux-i686-2.3/_bsddb.so: undefined symbol: PyGILState_Ensure *** WARNING: renaming "zlib" since importing it failed: build/lib.linux-i686-2.3/zlib.so: undefined symbol: PyThread_acquire_lock *** WARNING: renaming "bz2" since importing it failed: build/lib.linux-i686-2.3/bz2.so: undefined symbol: PyThread_acquire_lock *** WARNING: renaming "_tkinter" since importing it failed: build/lib.linux-i686-2.3/_tkinter.so: undefined symbol: PyThread_acquire_lock running build_scripts [root@maildance Python-2.3.3]# So I guess that means that threads aren't happening? I notice, though, that when I "python2.3 setup.py build" to make PIL, I get lots like this: [root@maildance Imaging-1.1.4]# python2.3 setup.py build gcc -pthread -shared build/temp.linux-i686-2.3/_imaging.o build/temp.linux-i686-2.3/decode.o build/temp.linux-i686-2.3/encode.o build/temp.linux-i686-2.3/map.o build/temp.linux-i686-2.3/display.o build/temp.linux-i686-2.3/outline.o build/temp.linux-i686-2.3/path.o -LlibImaging -lImaging -ljpeg -lz -o build/lib.linux-i686-2.3/_imaging.so building '_imagingtk' extension creating build/temp.linux-i686-2.3/Tk gcc -pthread -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -fPIC -IlibImaging -I/usr/local/include/python2.3 -c Tk/tkImaging.c -o build/temp.linux-i686-2.3/Tk/tkImaging.o So I see that -pthread and wonder if that's what's causing it. But this is seeming too hard. I can't help thinking that I'm doing something wrong from the start. Any ideas? Marilyn > > > > Is there a way to find out for sure which version of python is running? > > Can I output the version number? > > Yes. Here you go: > > ### > >>> import sys > >>> print sys.version > 2.2.1 (#1, Sep 3 2002, 14:52:01) > [GCC 2.96 20000731 (Red Hat Linux 7.3 2.96-112)] > ### > > > Good luck to you. > > -- From idiot1 at netzero.net Wed Apr 14 01:58:43 2004 From: idiot1 at netzero.net (Kirk Bailey) Date: Wed Apr 14 01:59:33 2004 Subject: [Tutor] critter had a stroke Message-ID: <407CD313.2080401@netzero.net> in which the drive housing the /var dir died, so the opsys refused to boot. He is being doctored in the cyberemergency room by the good cyberdoctor James Porter, who as we speak is rebuilding him bigger and badder- and FINALLY is getting the modern python installed. When done, Critter will have twice the memory, 5 times the disk space- and this time as SCSI instead of extended ide- twice the clock speed, and fortunately all the stuff for 4 websites is still safe. This means, I can now update a lot of code to the modern python definitions, as soon as the good mad scientist stops laughing miniaclly and playing fiendish organ music on his surround sound system, and finishes his ghoulish work. And yes, I would not put that past him as a breif giggle. James I mean. Critter likes Industrial Rock or techno. -- Respectfully, Kirk D Bailey, Pinellas county Florida USA think http://www.tinylist.org/ - $FREE$ Liberating software +-------+ http://www.pinellasintergroupsociety.org/ - NeoPagan | BOX | http://www.listville.net/ - $FREE$ list hosting! +-------+ http://www.howlermonkey.net/ - $FREE$ email Accounts kniht http://www.sacredelectron.org/ - My personal site From dbroadwell at mindspring.com Wed Apr 14 03:18:39 2004 From: dbroadwell at mindspring.com (David Broadwell) Date: Wed Apr 14 03:13:54 2004 Subject: [Tutor] Network pointers requested In-Reply-To: <407CD313.2080401@netzero.net> Message-ID: So now that I have this wonderfully extendible rock paper scissors engine (the computer can play itself!). I want to perform the glorious, all important task of playing rock paper scissors between my two consoles and learning more networking. To hit the learning curve, let's say that I have to use tcp/ip and for my sake I'd like a pure python solution. I'm aware of Tcp/ip from the client level and where it falls into the realm of ports, icmp is a bit more than a buzzword and my firewall is running on advanced rules. Any recommended python api's for network stuff? Where I've looked; I heard of Twisted http://twistedmatrix.com and like the concept of multi-server integration. glanced at http://www.amk.ca/python/howto/sockets/ skimmed http://www.onlamp.com/pub/a/python/2003/11/06/python_nio.html?page=1 Of course as I'm on windows there are the win32 api wrappers ... and things like http://www.nongnu.org/pydonkey/pysocket.html the Library Reference has the 11.15 SocketServer Maybe even lower than that, where should I start? Comments as always, appreciated. -- Programmer's mantra; Observe, Brainstorm, Prototype, Repeat David Broadwell From george at visp.com.au Wed Apr 14 05:18:16 2004 From: george at visp.com.au (George Patterson) Date: Wed Apr 14 05:18:53 2004 Subject: [Tutor] Client-Server programming and trapping sigkils Message-ID: <20040414184816.224e3aac@beast.spyderweb.com.au> Skipped content of type multipart/mixed-------------- 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/20040414/536eb1d8/attachment-0001.bin From Chad.Crabtree at nationalcity.com Wed Apr 14 13:44:06 2004 From: Chad.Crabtree at nationalcity.com (Crabtree, Chad) Date: Wed Apr 14 13:44:30 2004 Subject: [Tutor] On New Style Classes Message-ID: <66F587DFDD46D511B65200508B6F8DD60EF88EFE@nt-kalopsapp07.ntl-city.com> Well I'm not sure why I was unable to find those pages before. I appologize. However I do have a question. I understand the descriptors could be usefull for my transparency with user created classes or perhaps event oriented programing. However class methods and static classes don't really make sence to me. They seem to be a syntatictic kludge. I know what they are but not why python needs them. In addition are "Classic" classes going to be depreciated? ------------------------------------------------------------------------------------------- ***National City made the following annotations ------------------------------------------------------------------------------------------- This communication is a confidential and proprietary business communication. It is intended solely for the use of the designated recipient(s). If this communication is received in error, please contact the sender and delete this communication. =========================================================================================== From tim at johnsons-web.com Wed Apr 14 14:29:25 2004 From: tim at johnsons-web.com (Tim Johnson) Date: Wed Apr 14 14:28:27 2004 Subject: [Tutor] MySQLdb: dropping zeroes! In-Reply-To: <5.2.1.1.0.20040414020842.02f5ee20@www.thinkware.se> References: <1081341204.7860.15.camel@laptop.venix.com> <20040407020428.GY1860@johnsons-web.com> <1081341204.7860.15.camel@laptop.venix.com> <5.2.1.1.0.20040414020842.02f5ee20@www.thinkware.se> Message-ID: <20040414182925.GY16993@johnsons-web.com> * Magnus Lyck? [040413 16:15]: > At 07:56 2004-04-07 -0800, Tim Johnson wrote: > > To quote the mysql manual: > > > > "The DECIMAL type is considered a numeric type (as is its synonym, > > NUMERIC), but such values are stored as strings." > > > > So I thought there might be a way to override the > > MySQLdb type conversion and get them back as strings. > > The problem (which I hope will be fixed in a not too far future) > is that Python lacks a standard decimal type/class. :-) Knowing python folks, I know that you will do it right and do it carefully.... > ADODBAPI does it the other way around, and returns DECIMAL > as strings, and that's not without problems either. For > instance, with e.g. Swedish settings in Windows, 1/2 will > be returned as '0,5', not '0.5', and float('0,5') won't make > Python happy. No. > Anyway, I guess you could replace "SELECT X FROM Y" with > "SELECT CAST(X AS CHAR(10)) AS X FROM Y" or something like > that. That is a really good tip. Always best to try to make mysql to as much of the work as possible IMHO. Didn't know about 'CAST' and will research it. Thanks! tim > -- > Magnus Lycka (It's really Lyckå), magnus@thinkware.se > Thinkware AB, Sweden, www.thinkware.se > I code Python ~ The Agile Programming Language > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Tim Johnson http://www.alaska-internet-solutions.com From alan.gauld at blueyonder.co.uk Wed Apr 14 16:31:07 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Apr 14 16:30:44 2004 Subject: [Tutor] Network pointers requested References: Message-ID: <018001c4225f$6a2d07b0$6401a8c0@xp> > I'm aware of Tcp/ip from the client level and where it falls into the realm > of ports, icmp is a bit more than a buzzword and my firewall is running on > advanced rules. > > Any recommended python api's for network stuff? I'd start with the socket module. > glanced at http://www.amk.ca/python/howto/sockets/ > Maybe even lower than that, where should I start? Well you could go to ioctl and write your own networking protocol, but I'd advise sticking to IP and using sockets... Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From askoose at sandia.gov Wed Apr 14 17:28:10 2004 From: askoose at sandia.gov (Kooser, Ara S) Date: Wed Apr 14 17:28:25 2004 Subject: [Tutor] Filtering text files Message-ID: <9A4B2157EFDBE546BECD68C62AC3B1C81738F0CC@es05snlnt.sandia.gov> Hello, I posted several question about filtering text files. I am still a little confused. I ran through some of the tutorials on python.org and I am still getting hung up. I am running python 2.3.3. When I try and run the program below I receive the prompt on the shell and no new file is created in my directory. Here is the code from http://www.ibiblio.org/obp/thinkCSpy/chap11.htm . I have in my directory a file named lmps for the input file. Also do the names in the function have to be the same as the names of the files being loaded? I have tried both. Thanks Ara def filterFile(lmps, newFile): f1 = open(lmps, "r") f2 = open(newFile, "w") while 1: text = f1.readline() if text == "": break if text[0] == 'I': continue f2.write(text) f1.close() f2.close() return -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040414/07143a2c/attachment.html From dyoo at hkn.eecs.berkeley.edu Wed Apr 14 17:49:23 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Apr 14 17:49:30 2004 Subject: [Tutor] Filtering text files In-Reply-To: <9A4B2157EFDBE546BECD68C62AC3B1C81738F0CC@es05snlnt.sandia.gov> Message-ID: On Wed, 14 Apr 2004, Kooser, Ara S wrote: > I posted several question about filtering text files. I am still a > little confused. I ran through some of the tutorials on python.org and I > am still getting hung up. I am running python 2.3.3. When I try and run > the program below I receive the prompt on the shell Hi Ara, Hmmm... Can you show us how you're running the program? Just do a cut-and-paste of the session, and that should be enough. If the complete program that you are executing is this: ### > def filterFile(lmps, newFile): > f1 = open(lmps, "r") > f2 = open(newFile, "w") > while 1: > text = f1.readline() > if text == "": > break > if text[0] == 'I': > continue > f2.write(text) > f1.close() > f2.close() > return ### then something might be missing: although the definition of filterFile() looks ok, unless there is an activating call to filterFile(), nothing will happen. Can you double check to see that the filterFile() function is being called? See: http://www.ibiblio.org/obp/thinkCSpy/chap03.htm for more details about defining and calling functions. If you have questions, please feel free to ask them; we'll try to help. Good luck! From dyoo at hkn.eecs.berkeley.edu Wed Apr 14 18:06:29 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Apr 14 18:06:34 2004 Subject: [Tutor] mod_python and PIL? In-Reply-To: Message-ID: > Cannot load /www/libexec/mod_python.so into server: > /www/libexec/mod_python.so: undefined symbol: pthread_sigmask Hi Marilyn, Gaaah! Yikes. > And I'm stumped. For python2.3.3: > > [root@maildance mod_python-2.7.8]# cd ../Python-2.3.3 > [root@maildance Python-2.3.3]# ./configure --with-threads=no You shouldn't have to do this. The error message that you're getting involves mod_python --- recompiling mod_python to use the new Python 2.3.3 may have more success than recompiling Python. > But this is seeming too hard. I can't help thinking that I'm doing > something wrong from the start. This is mod_python specific; it's definitely a little more advanced than most Tutor stuff... *grin* You may want to talk with the folks on the modpython mailing list. http://mailman.modpython.org/mailman/listinfo/mod_python It appears that some other folks are running into the same exact problem on FreeBSD too: http://www.modpython.org/pipermail/mod_python/2003-April/013536.html so whatever is going on is affecting others; don't be hard on yourself. There are actually quite a few FAQ entries on the mod_python page that may apply to the issues you're having: http://www.modpython.org/FAQ/faqw.py?req=all In particular, http://www.modpython.org/FAQ/faqw.py?req=all#4.2 says that mod_python versions < 3 will have compile-time issues with Python 2.3. You're trying to install mod_python 2.7.8, so that may be a contributing factor to the compile mischief. Try using a later version of mod_python, like 3.1.3: http://mailman.modpython.org/mailman/listinfo/mod_python Also, since you have multiple versions of Python installed on your system, you may need to explicitely tell mod_python to use the right one during './configure': http://www.modpython.org/live/current/doc-html/inst-configure.html The folks on the modpython mailing list should be better equipped to handle installation problems, so talk with them: they'll know what to do. (I hope. *grin*) From askoose at sandia.gov Wed Apr 14 18:13:40 2004 From: askoose at sandia.gov (Kooser, Ara S) Date: Wed Apr 14 18:13:55 2004 Subject: [Tutor] Filtering text files Message-ID: <9A4B2157EFDBE546BECD68C62AC3B1C81738F0CE@es05snlnt.sandia.gov> Sure, I am running the file in IDLE. I go to run, run module. Here is the shell screen: Maybe it's WinXP (*grin*). I will try this on my linux box at home. I am currently waiting for my linux box to arrive at work. I will read up on functions. Thank you for your help and the pointers. Ara Python 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. **************************************************************** Personal firewall software may warn about the connection IDLE makes to its subprocess using this computer's internal loopback interface. This connection is not visible on any external interface and no data is sent to or received from the Internet. **************************************************************** IDLE 1.0.2 >>> ================================ RESTART ================================ >>> >>> -----Original Message----- From: Danny Yoo [mailto:dyoo@hkn.eecs.berkeley.edu] Sent: Wednesday, April 14, 2004 3:49 PM To: Kooser, Ara S Cc: 'tutor@python.org' Subject: Re: [Tutor] Filtering text files On Wed, 14 Apr 2004, Kooser, Ara S wrote: > I posted several question about filtering text files. I am still a > little confused. I ran through some of the tutorials on python.org and > I am still getting hung up. I am running python 2.3.3. When I try and > run the program below I receive the prompt on the shell Hi Ara, Hmmm... Can you show us how you're running the program? Just do a cut-and-paste of the session, and that should be enough. If the complete program that you are executing is this: ### > def filterFile(lmps, newFile): > f1 = open(lmps, "r") > f2 = open(newFile, "w") > while 1: > text = f1.readline() > if text == "": > break > if text[0] == 'I': > continue > f2.write(text) > f1.close() > f2.close() > return ### then something might be missing: although the definition of filterFile() looks ok, unless there is an activating call to filterFile(), nothing will happen. Can you double check to see that the filterFile() function is being called? See: http://www.ibiblio.org/obp/thinkCSpy/chap03.htm for more details about defining and calling functions. If you have questions, please feel free to ask them; we'll try to help. Good luck! From bvande at po-box.mcgill.ca Wed Apr 14 18:28:40 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Wed Apr 14 18:29:04 2004 Subject: [Tutor] Filtering text files In-Reply-To: <9A4B2157EFDBE546BECD68C62AC3B1C81738F0CC@es05snlnt.sandia.gov> References: <9A4B2157EFDBE546BECD68C62AC3B1C81738F0CC@es05snlnt.sandia.gov> Message-ID: <407DBB18.60803@po-box.mcgill.ca> Kooser, Ara S said unto the world upon 14/04/2004 17:28: > Hello, > > I posted several question about filtering text files. I am still a little > confused. I ran through some of the tutorials on python.org and I am still > getting hung up. I am running python 2.3.3. When I try and run the program > below I receive the prompt on the shell and no new file is created in my > directory. Here is the code from > http://www.ibiblio.org/obp/thinkCSpy/chap11.htm > . I have in my directory a > file named lmps for the input file. Also do the names in the function have > to be the same as the names of the files being loaded? I have tried both. > Thanks > > Ara > > def filterFile(lmps, newFile): > f1 = open(lmps, "r") > f2 = open(newFile, "w") > while 1: > text = f1.readline() > if text == "": > break > if text[0] == 'I': > continue > f2.write(text) > f1.close() > f2.close() > return > > Ara, Use caution before assuming that what follows is true in its entirety. I am a newbie too! Did you post the complete code that you are running? If so, the problem is that you have defined a function and then stopped. You need to call the function too, in order for it to do any work. (Think of the function definition as a list of instructions that can be done in one fell swoop after they have been defined. But a list of instructions doesn't do anything by itself. For stuff to happen, they need to be followed.) The 'lmps' and 'newFile' in the function definition are the names internal to the function. A function call of filterFile as the code above defines it needs two arguments, one which plays the role the function gives to lmps, the other newFile. So, to use the function to read firstfile.txt and write the contents to secondfile.txt you need to call the function like this: filterFile(firstfile.txt, secondfile.txt) The two arguments in the filterFile function call can be any files whatsoever. You could even read a file called newFile and write to a file called lmps by calling the function like so: filterFile(newFile, lmps) This might seem confusing, because the two arguments are in the opposite order of the function definition. But the names used in the function definition are arbitrary placeholders (you could just as well define with 'first_argument', 'second_argument' as the names in the definition). They serve to define the function by keeping the role of each argument straight. They need not have any relation to the actual arguments used when you call the function later. So, to make it work, follow the function definition with a function call like I gave as an example, and it should work as you want. Two other things: 1) The claim that the argument names are completely arbitrary holds true for simple function definitions, but the ability to define keyword arguments adds a bit of complication. I'd say worry about that a bit later, though -- or at least get an explanation from someone who knows better than I what they are talking about ;-) 2) The function calls that I gave did not provide a file path. Thus, they will work as given only if the file specified in the first argument lives in the current working directory. HTH Brian vdB From garryknight at gmx.net Wed Apr 14 19:54:20 2004 From: garryknight at gmx.net (Garry Knight) Date: Wed Apr 14 19:54:29 2004 Subject: [Tutor] Re: Filtering text files References: <9A4B2157EFDBE546BECD68C62AC3B1C81738F0CC@es05snlnt.sandia.gov> <407DBB18.60803@po-box.mcgill.ca> Message-ID: In message <407DBB18.60803@po-box.mcgill.ca>, Brian van den Broek wrote: > Kooser, Ara S said unto the world upon 14/04/2004 17:28: > >> def filterFile(lmps, newFile): >> f1 = open(lmps, "r") >> f2 = open(newFile, "w") > > filterFile(firstfile.txt, secondfile.txt) Since the open() call takes a string as the first parameter, filterFile should be called with two string arguments: filterFile("firstfile.txt", "secondfile.txt") -- Garry Knight garryknight@gmx.net ICQ 126351135 Linux registered user 182025 From dtalaga at novodynamics.com Wed Apr 14 20:22:06 2004 From: dtalaga at novodynamics.com (David Talaga) Date: Wed Apr 14 20:21:51 2004 Subject: [Tutor] Filtering text files In-Reply-To: <9A4B2157EFDBE546BECD68C62AC3B1C81738F0CC@es05snlnt.sandia.gov> Message-ID: Filtering text filesCan I get some help here!! Ok, here's the deal, I am using tkinter and trying to figure out how to un select the radio button at startup. here is my code in it's entirety. import os import Tkinter root=Tkinter.Tk() var=Tkinter.StringVar() entry=Tkinter.Entry(root, textvariable=var) entry.focus_set() entry.pack() var.set(root.title()) def changeTitle(): root.title(var.get()) def changeDriveC(): os.chdir('C:\\') def changeDriveD(): os.chdir('D:\\') def changeDriveE(): os.chdir('E:\\') def changeDriveF(): os.chdir('F:\\') def changeDriveG(): os.chdir('G:\\') Tkinter.Button(root, text="Change Title", command=changeTitle).pack() Tkinter.Button(root, text="Iconify", command=root.iconify).pack() Tkinter.Button(root, text="Close", command=root.destroy).pack() C=Tkinter.Radiobutton(text="Change dir to C:", value=0).pack() D=Tkinter.Radiobutton(text="Change dir to D:", value=0).pack() E=Tkinter.Radiobutton(text="Change dir to E:", value=0).pack() F=Tkinter.Radiobutton(text="Change dir to F:", value=0).pack() G=Tkinter.Radiobutton(text="Change dir to G:", value=0).pack() if C.select(): C=Tkinter.Radiobutton(text="Change dir to C:", value=1,command=os.chdir('C:\\').pack() Tkinter.mainloop The if statement was a test that went wrong. Anyone? Anyone? Eric Idle is king! David Talaga -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org]On Behalf Of Kooser, Ara S Sent: Wednesday, April 14, 2004 5:28 PM To: 'tutor@python.org' Subject: [Tutor] Filtering text files Hello, I posted several question about filtering text files. I am still a little confused. I ran through some of the tutorials on python.org and I am still getting hung up. I am running python 2.3.3. When I try and run the program below I receive the prompt on the shell and no new file is created in my directory. Here is the code from http://www.ibiblio.org/obp/thinkCSpy/chap11.htm. I have in my directory a file named lmps for the input file. Also do the names in the function have to be the same as the names of the files being loaded? I have tried both. Thanks Ara def filterFile(lmps, newFile): f1 = open(lmps, "r") f2 = open(newFile, "w") while 1: text = f1.readline() if text == "": break if text[0] == 'I': continue f2.write(text) f1.close() f2.close() return -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040414/fcdfe8fe/attachment.html From dtalaga at novodynamics.com Wed Apr 14 20:28:57 2004 From: dtalaga at novodynamics.com (David Talaga) Date: Wed Apr 14 20:28:39 2004 Subject: [Tutor] Filtering text files In-Reply-To: Message-ID: Filtering text filesOh yea, including this, the other problem I am having is when I run it the statement after the if statements is aid to be illegal syntax!?!?!?! The revised code is as follows: import os import Tkinter root=Tkinter.Tk() var=Tkinter.StringVar() entry=Tkinter.Entry(root, textvariable=var) entry.focus_set() entry.pack() var.set(root.title()) def changeTitle(): root.title(var.get()) def changeDriveC(): os.chdir('C:\\') def changeDriveD(): os.chdir('D:\\') def changeDriveE(): os.chdir('E:\\') def changeDriveF(): os.chdir('F:\\') def changeDriveG(): os.chdir('G:\\') Tkinter.Button(root, text="Change Title", command=changeTitle).pack() Tkinter.Button(root, text="Iconify", command=root.iconify).pack() Tkinter.Button(root, text="Close", command=root.destroy).pack() C=Tkinter.Radiobutton(text="Change dir to C:", value=0).pack() D=Tkinter.Radiobutton(text="Change dir to D:", value=0).pack() E=Tkinter.Radiobutton(text="Change dir to E:", value=0).pack() F=Tkinter.Radiobutton(text="Change dir to F:", value=0).pack() G=Tkinter.Radiobutton(text="Change dir to G:", value=0).pack() if C.select(): C=Tkinter.Radiobutton(text="Change dir to C:", value=1,command=os.chdir('C:\\').pack() elif D.select(): D=Tkinter.Radiobutton(text="Change dir to D:", value=1,command=os.chdir('D:\\').pack() elif E.select(): E=Tkinter.Radiobutton(text="Change dir to D:", value=1,command=os.chdir('E:\\').pack() elif F.select(): F=Tkinter.Radiobutton(text="Change dir to D:", value=1,command=os.chdir('F:\\').pack() elif G.select(): G=Tkinter.Radiobutton(text="Change dir to D:", value=1,command=os.chdir('G:\\').pack() Tkinter.mainloop -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org]On Behalf Of David Talaga Sent: Wednesday, April 14, 2004 8:22 PM To: Kooser, Ara S; tutor@python.org Subject: RE: [Tutor] Filtering text files Can I get some help here!! Ok, here's the deal, I am using tkinter and trying to figure out how to un select the radio button at startup. here is my code in it's entirety. import os import Tkinter root=Tkinter.Tk() var=Tkinter.StringVar() entry=Tkinter.Entry(root, textvariable=var) entry.focus_set() entry.pack() var.set(root.title()) def changeTitle(): root.title(var.get()) def changeDriveC(): os.chdir('C:\\') def changeDriveD(): os.chdir('D:\\') def changeDriveE(): os.chdir('E:\\') def changeDriveF(): os.chdir('F:\\') def changeDriveG(): os.chdir('G:\\') Tkinter.Button(root, text="Change Title", command=changeTitle).pack() Tkinter.Button(root, text="Iconify", command=root.iconify).pack() Tkinter.Button(root, text="Close", command=root.destroy).pack() C=Tkinter.Radiobutton(text="Change dir to C:", value=0).pack() D=Tkinter.Radiobutton(text="Change dir to D:", value=0).pack() E=Tkinter.Radiobutton(text="Change dir to E:", value=0).pack() F=Tkinter.Radiobutton(text="Change dir to F:", value=0).pack() G=Tkinter.Radiobutton(text="Change dir to G:", value=0).pack() if C.select(): C=Tkinter.Radiobutton(text="Change dir to C:", value=1,command=os.chdir('C:\\').pack() Tkinter.mainloop The if statement was a test that went wrong. Anyone? Anyone? Eric Idle is king! David Talaga -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org]On Behalf Of Kooser, Ara S Sent: Wednesday, April 14, 2004 5:28 PM To: 'tutor@python.org' Subject: [Tutor] Filtering text files Hello, I posted several question about filtering text files. I am still a little confused. I ran through some of the tutorials on python.org and I am still getting hung up. I am running python 2.3.3. When I try and run the program below I receive the prompt on the shell and no new file is created in my directory. Here is the code from http://www.ibiblio.org/obp/thinkCSpy/chap11.htm. I have in my directory a file named lmps for the input file. Also do the names in the function have to be the same as the names of the files being loaded? I have tried both. Thanks Ara def filterFile(lmps, newFile): f1 = open(lmps, "r") f2 = open(newFile, "w") while 1: text = f1.readline() if text == "": break if text[0] == 'I': continue f2.write(text) f1.close() f2.close() return -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040414/7a3fc690/attachment.html From dtalaga at novodynamics.com Wed Apr 14 20:34:43 2004 From: dtalaga at novodynamics.com (David Talaga) Date: Wed Apr 14 20:34:27 2004 Subject: [Tutor] Filtering text files In-Reply-To: Message-ID: Filtering text filesok, so I am an idiot! There wan no ) after the .pack( ). Never mind about that. But now it is saying the this "AttributeError: 'NoneType' object has no attribute 'select'" in the ugly red letters. What now?!?!?! -----Original Message----- From: David Talaga [mailto:dtalaga@novodynamics.com] Sent: Wednesday, April 14, 2004 8:29 PM To: David Talaga; Kooser, Ara S; tutor@python.org Subject: RE: [Tutor] Filtering text files Oh yea, including this, the other problem I am having is when I run it the statement after the if statements is aid to be illegal syntax!?!?!?! The revised code is as follows: import os import Tkinter root=Tkinter.Tk() var=Tkinter.StringVar() entry=Tkinter.Entry(root, textvariable=var) entry.focus_set() entry.pack() var.set(root.title()) def changeTitle(): root.title(var.get()) def changeDriveC(): os.chdir('C:\\') def changeDriveD(): os.chdir('D:\\') def changeDriveE(): os.chdir('E:\\') def changeDriveF(): os.chdir('F:\\') def changeDriveG(): os.chdir('G:\\') Tkinter.Button(root, text="Change Title", command=changeTitle).pack() Tkinter.Button(root, text="Iconify", command=root.iconify).pack() Tkinter.Button(root, text="Close", command=root.destroy).pack() C=Tkinter.Radiobutton(text="Change dir to C:", value=0).pack() D=Tkinter.Radiobutton(text="Change dir to D:", value=0).pack() E=Tkinter.Radiobutton(text="Change dir to E:", value=0).pack() F=Tkinter.Radiobutton(text="Change dir to F:", value=0).pack() G=Tkinter.Radiobutton(text="Change dir to G:", value=0).pack() if C.select(): C=Tkinter.Radiobutton(text="Change dir to C:", value=1,command=os.chdir('C:\\').pack() elif D.select(): D=Tkinter.Radiobutton(text="Change dir to D:", value=1,command=os.chdir('D:\\').pack() elif E.select(): E=Tkinter.Radiobutton(text="Change dir to D:", value=1,command=os.chdir('E:\\').pack() elif F.select(): F=Tkinter.Radiobutton(text="Change dir to D:", value=1,command=os.chdir('F:\\').pack() elif G.select(): G=Tkinter.Radiobutton(text="Change dir to D:", value=1,command=os.chdir('G:\\').pack() Tkinter.mainloop -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org]On Behalf Of David Talaga Sent: Wednesday, April 14, 2004 8:22 PM To: Kooser, Ara S; tutor@python.org Subject: RE: [Tutor] Filtering text files Can I get some help here!! Ok, here's the deal, I am using tkinter and trying to figure out how to un select the radio button at startup. here is my code in it's entirety. import os import Tkinter root=Tkinter.Tk() var=Tkinter.StringVar() entry=Tkinter.Entry(root, textvariable=var) entry.focus_set() entry.pack() var.set(root.title()) def changeTitle(): root.title(var.get()) def changeDriveC(): os.chdir('C:\\') def changeDriveD(): os.chdir('D:\\') def changeDriveE(): os.chdir('E:\\') def changeDriveF(): os.chdir('F:\\') def changeDriveG(): os.chdir('G:\\') Tkinter.Button(root, text="Change Title", command=changeTitle).pack() Tkinter.Button(root, text="Iconify", command=root.iconify).pack() Tkinter.Button(root, text="Close", command=root.destroy).pack() C=Tkinter.Radiobutton(text="Change dir to C:", value=0).pack() D=Tkinter.Radiobutton(text="Change dir to D:", value=0).pack() E=Tkinter.Radiobutton(text="Change dir to E:", value=0).pack() F=Tkinter.Radiobutton(text="Change dir to F:", value=0).pack() G=Tkinter.Radiobutton(text="Change dir to G:", value=0).pack() if C.select(): C=Tkinter.Radiobutton(text="Change dir to C:", value=1,command=os.chdir('C:\\').pack() Tkinter.mainloop The if statement was a test that went wrong. Anyone? Anyone? Eric Idle is king! David Talaga -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org]On Behalf Of Kooser, Ara S Sent: Wednesday, April 14, 2004 5:28 PM To: 'tutor@python.org' Subject: [Tutor] Filtering text files Hello, I posted several question about filtering text files. I am still a little confused. I ran through some of the tutorials on python.org and I am still getting hung up. I am running python 2.3.3. When I try and run the program below I receive the prompt on the shell and no new file is created in my directory. Here is the code from http://www.ibiblio.org/obp/thinkCSpy/chap11.htm. I have in my directory a file named lmps for the input file. Also do the names in the function have to be the same as the names of the files being loaded? I have tried both. Thanks Ara def filterFile(lmps, newFile): f1 = open(lmps, "r") f2 = open(newFile, "w") while 1: text = f1.readline() if text == "": break if text[0] == 'I': continue f2.write(text) f1.close() f2.close() return -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040414/4202f088/attachment-0001.html From dyoo at hkn.eecs.berkeley.edu Wed Apr 14 21:03:10 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Apr 14 21:03:15 2004 Subject: [Tutor] Tkinter debugging [widget.pack() doesn't have a return value] In-Reply-To: Message-ID: Hi David, [You replied to an older message from Ara's request about working with text files. Your messages have the subject line 'Filtering Text Files', even though your question has more to do with Tkinter stuff. Next time, start a new thread by composing a new message to Tutor. This is for purely practical reasons. One reason why it's important is because our archiver "threads" messages based on subject: http://mail.python.org/pipermail/tutor/2004-April/thread.html and it become much harder to trace or follow a conversation if the subject line isn't describing the topic of discussion. Also, some folks who are working with in Tkinter stuff will pay more attention to your problem. Ok, let's get to your question. *grin*] > Filtering text filesok, so I am an idiot! There wan no ) after the .pack( ). > Never mind about that. But now it is saying the this "AttributeError: > 'NoneType' object has no attribute 'select'" > in the ugly red letters. What now?!?!?! Breathe, and DON'T PANIC. Be careful not to paraphrase the error when asking for help. There's has to be more in the error message, because most Python error messages come with line numbers that will point at where the problem is. Here's an example of what we like to see in an error message: ### [dyoo@tesuque dyoo]$ cat foo.py class SomeClass(object): def sayHello(self): pass def noSelf(): print "I'm selfless" foobar! [dyoo@tesuque dyoo]$ [dyoo@tesuque dyoo]$ [dyoo@tesuque dyoo]$ python foo.py File "foo.py", line 7 foobar! ^ SyntaxError: invalid syntax ### All the lines, starting from "File ..." are important for debugging purposes. Notice that the error message here says exactly what line it thinks might be causing the problem. That helps because we don't have to look at the whole program: we can localize our bug hunt to a smaller area. So when you see an error message in your own program, make sure to record that line number and look at the line, and make sure to send the whole bug error message to Tutor, so that we can follow along. Going back to the error message you sent, > "AttributeError:'NoneType' object has no attribute 'select'" >From the error message, we can see that it has to do with something with 'select'. So we can do a search through the program and see if we can find it. There are a few places where a "select" is being looked up, near the bottom of the program: > if C.select(): > C=Tkinter.Radiobutton(text="Change dir to C:", > value=1,command=os.chdir('C:\\').pack() > elif D.select(): > D=Tkinter.Radiobutton(text="Change dir to D:", > value=1,command=os.chdir('D:\\').pack() > elif E.select(): > E=Tkinter.Radiobutton(text="Change dir to D:", > value=1,command=os.chdir('E:\\').pack() > elif F.select(): > F=Tkinter.Radiobutton(text="Change dir to D:", > value=1,command=os.chdir('F:\\').pack() > elif G.select(): > G=Tkinter.Radiobutton(text="Change dir to D:", > value=1,command=os.chdir('G:\\').pack() And that's why the line number is important: that error message could apply to any one of these, so it would have helped to isolate the error a little further. Ah, ok, I think I see the problem. The pack() method of a widget actually doesn't have a return value --- so something like: G = Tkinter.Radiobutton(text="Change dir to D:", value=1,command=os.chdir('G:\\').pack() actually needs to be broken down into two statements: G = Tkinter.Radiobutton(text="Change dir to D:", value=1,command=os.chdir('G:\\') G.pack() This is probably the reason why C, D, E, F, and G are showing up as None. To make life a little easier, we can write a quicky helper function to do the work of constructing and packing a radiobutton: ### def makeRadiobutton(text, value): newButton = Tkinter.Radiobutton(text = text, value = value) newButton.pack() return newButton ### This should allow you to make radiobuttons without having to worry about packing them separately: ### C = makeRadiobutton(text="Change dir to C:", value=0) D = makeRadiobutton(text="Change dir to D:", value=0) ... ### Finally, the last statement in the program: > Tkinter.mainloop needs parentheses, or else it won't fire off: Tkinter.mainloop() Good luck to you. From darnold02 at sprynet.com Wed Apr 14 21:06:03 2004 From: darnold02 at sprynet.com (Don Arnold) Date: Wed Apr 14 21:05:15 2004 Subject: [Tutor] Fwd: Tkinter (was Filtering text files) Message-ID: <1149B1F6-8E79-11D8-A4A2-000A95C4F940@sprynet.com> >> From: Don Arnold >> Date: April 14, 2004 8:01:33 PM CDT >> To: "David Talaga" >> Cc: >> Subject: Tkinter (was Filtering text files) >> >> >> On Apr 14, 2004, at 7:34 PM, David Talaga wrote: >> >>> ok, so I am an idiot! There wan no ) after the .pack( ).? Never mind >>> about that. But now it is saying the this "AttributeError: >>> 'NoneType' object has no attribute 'select'" >>> in the ugly red letters.? What now?!?!?! >>> -----Original Message----- >>> From: David Talaga [mailto:dtalaga@novodynamics.com] >>> Sent: Wednesday, April 14, 2004 8:29 PM >>> To: David Talaga; Kooser, Ara S; tutor@python.org >>> Subject: RE: [Tutor] Filtering text files >>> >>> Oh yea, including this, the other problem I am having is when I run >>> it the statement after the if statements is aid to be illegal >>> syntax!?!?!?! >>> The revised code is as follows: >>> import os >>> import Tkinter >>> root=Tkinter.Tk() >>> var=Tkinter.StringVar() >>> entry=Tkinter.Entry(root, textvariable=var) >>> entry.focus_set() >>> entry.pack() >>> var.set(root.title()) >>> def changeTitle(): root.title(var.get()) >>> def changeDriveC(): os.chdir('C:\\') >>> def changeDriveD(): os.chdir('D:\\') >>> def changeDriveE(): os.chdir('E:\\') >>> def changeDriveF(): os.chdir('F:\\') >>> def changeDriveG(): os.chdir('G:\\') >>> Tkinter.Button(root, text="Change Title", command=changeTitle).pack() >>> Tkinter.Button(root, text="Iconify", command=root.iconify).pack() >>> Tkinter.Button(root, text="Close", command=root.destroy).pack() >>> C=Tkinter.Radiobutton(text="Change dir to C:", value=0).pack() >>> D=Tkinter.Radiobutton(text="Change dir to D:", value=0).pack() >>> E=Tkinter.Radiobutton(text="Change dir to E:", value=0).pack() >>> F=Tkinter.Radiobutton(text="Change dir to F:", value=0).pack() >>> G=Tkinter.Radiobutton(text="Change dir to G:", value=0).pack() >>> >> From what I recall of Tkinter, the pack() method returns None, not >> the widget being packed. Try: >> >> C = Tkinter.Radiobutton(text='Change dir to C:', value=0) >> C.pack() >> etc. >> >> and see how that works. >> >> HTH, >> Don -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: text/enriched Size: 5984 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20040414/4ce62129/attachment.bin From firephreek at earthlink.net Fri Apr 2 10:42:39 2004 From: firephreek at earthlink.net (firephreek) Date: Wed Apr 14 21:28:11 2004 Subject: [Tutor] Classes and has_key Message-ID: <000301c418c9$219ff240$6f01010a@Rachel> Hey, I'm just fiddling, trying to write a program that will take values from two different excel spreadsheets, compare the values, and show me the differences. In writing this class to use as my list of values, I tried running it in idle, and everything seems to work fine, but after running the program, and checking that the variable is still resident, I tried to run some tests to make sure my syntax is correct for some other things I want to be able to do. but when I try to do: >>> a.has_key('oranges') I get: Traceback (most recent call last): File "", line 1, in -toplevel- a.has_key['oranges'] AttributeError: itemList instance has no attribute 'has_key'' I had thought 'has_key()' was a builtin, but mayhaps this isn't so. So is there someway I have to exlpicitly inherit this? And what other methods do I have to do this for? class itemList: def __init__(self): self.container={} def addItem(self, item): if self.container.has_key(item): print "This Container already has that item!" else: self.container[item]={} print "item added!" def addPart(self, item, key, value): self.container[item][key]=value def view(self, item=None): if item: print self.container[item] else: print self.container def remove(self, item): del self.container.[item] #use this func to remove items from the dictionary. def count(self): pass a=itemList() a.addItem('item1') a.addItem('item2') a.addItem('item3') a.addPart('item1', 'desc', 'apples') a.addPart('item1', 'Price', '10') a.addPart('item2', 'desc', 'oranges') a.addPart('item2', 'Price', '15') a.addPart('item3', 'desc', 'cherries') a.addPart('item3', 'Price', '20') a.view() From mjekl at iol.pt Thu Apr 1 13:21:10 2004 From: mjekl at iol.pt (Miguel Lopes) Date: Wed Apr 14 21:30:01 2004 Subject: [Tutor] os.system() start an application / program Message-ID: <001f01c41816$6dc52400$6601a8c0@jaimelopes> Hi, I'm experimenting with os.system() to start another application in my pc. I have no problems with the following statement: os.system("start C:\\MyDb1.mdb") A command box appears/ desappears and Access starts running. *** On the other hand the following statement doesn't work: os.system("start C:\Program Files\Internet Explorer\Iexplorer.exe") I'm as sure as I can be that this as something to do with either long file names or spaces in the dos command. If this is true this is not really a Python problem, but still is something probably alot of people encounter, so ther is probably a fast answer to my hair pulling problem :-) I'm running Python2.3 on MSW98 2nd. Txs, Miguel From mjust at sun11.ukl.uni-freiburg.de Tue Apr 6 07:12:00 2004 From: mjust at sun11.ukl.uni-freiburg.de (Michael Just) Date: Wed Apr 14 21:30:32 2004 Subject: [Tutor] command call in Windows for Image converting with ImageMagick Message-ID: <40729080.5040808@ukl.uni-freiburg.de> command call in Windows for Image converting with ImageMagick ############################################# Hello, python is quite new to me, so sorry for my stupid questions. I have a image files which I want to have in the right dimensions for a program to import. SOME of the images (which are bigger than 600x400) need to be transformed into smaller size. In Photoshop I can script a batch job (a so called photoshop-"action") which loads the imgages from directory "dir_in", resize the images a save the imgages in a directory "dir_out"). This is doing well. Unfortunately a photoshop-action can NOT DECIDE if the Image need to be resized. The man at the WinXP-computer where the program should run has no admin-rights. So the program has to be an exe (which I want to build with py2exe) or need no deeper installation (like ImageMagick). So I thought this will be a good job for Python an ImageMagick. Image Magick can analyse a image-file with the identify-program: "identify " which gives the output " JPEG 1017x282+0+0 ....." Depending on that output the program should decide to resize with the ImageMagick programm "convert" : "convert -geometry 600x400 ". ############################################################# # # Here are my questions: 1) How can I start the program "identify "? I got the already with "os.listdir(os.curdir)" 2) How I fetch the output of "identify "? The call for "convert" will be the same as for 1) and 2). 3) How about error-handling, when a file could not be resized? # # ################################################################## I wil be happy for any hint. Thanks Michael Just mjust@ukl.uni-freiburg.de University Hospital Freiburg Germany From olavi at vision.ee Mon Apr 12 00:49:49 2004 From: olavi at vision.ee (olavi) Date: Wed Apr 14 21:30:59 2004 Subject: [Tutor] python help In-Reply-To: <1da.1eb9cc6a.2dab6b13@aol.com> References: <1da.1eb9cc6a.2dab6b13@aol.com> Message-ID: <407A1FED.5030505@vision.ee> FallenJ7456@aol.com wrote: > if there is anyone willing to help me in some basics of python please > e-mail me > also if anyone uses pygame and has info on it mail me thanx > > fallenj > >------------------------------------------------------------------------ > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > You should visit http://python.org/topics/learn/ Olavi Ivask From py at humnet.ucla.edu Fri Apr 2 09:25:49 2004 From: py at humnet.ucla.edu (peter hodgson) Date: Wed Apr 14 21:31:28 2004 Subject: [Tutor] passwd.py Message-ID: <200404021425.i32EPnWB013077@nightshade.noc.ucla.edu> thanks karl; i'm back again with that pesky passwd.py; 'break' works fine; still some trouble with sys.exit() i've manually indented, instead of tabbing; o.k.? ------------------------------ #Modify the password guessing program to keep track of how many times # the user has entered the password wrong. If it is more than 3 times, # print ``three times, you're out!'' import sys #no "welcome.." after else: passwd = "foobar" #a dummy passwd count = 3 current_count = 0 while passwd != "unicorn": current_count = current_count + 1 passswd = raw_input("Passwd: ") #P..as text; p.. is a var if current_count < count: print "no, stupid! try again;" else: print "three times, you're out!" break #double indent;breaks loop sys.exit(1) #no good for "unicorn" print "welcome in" #without 'count': keep asking for password until the jerk gets it right; #with count: he only gets three chances; #sys.exit() [per w.chung, core PYTHON PROGRAMMING]; # indented twice fails to stop "welcome in"; # indented once causes exit after first incorrect password; # not indented works fine with wrong passwds; # but also kicks out 'unicorn' w/ "three times, you're out!" From py at humnet.ucla.edu Sat Apr 3 01:38:11 2004 From: py at humnet.ucla.edu (peter hodgson) Date: Wed Apr 14 21:31:37 2004 Subject: [Tutor] 2.2 and 2.3 Message-ID: <200404030638.i336cBK3007581@geranium.noc.ucla.edu> [running 2.3 on a gentoo box] i'm afraid my python 2.2 tutorial may be out of step with python 2.3; HERE'S THE EXCERPT FROM THE 2.2 TUTORIAL def catTwice(part1, part2): cat = part1 + part2 printTwice(cat) This function takes two arguments, concatenates them, and then prints the result twice. We can call the function with two strings: >>> chant1 = "Pie Jesu domine, " >>> chant2 = "Dona eis requiem." >>> catTwice(chant1, chant2) Pie Jesu domine, Dona eis requiem. Pie Jesu domine, Dona eis requiem. HERE'S WHAT HAPPENED WHEN I TRIED TO TEST THE SUSPICIOUS printTwice(): IS printTwice SOMETHING NO LONGER ACTIVE IN 2.3? >>> printTwice('forty') Traceback (most recent call last): File "", line 1, in ? NameError: name 'printTwice' is not defined HERE'S WHAT HAPPENED WHEN I TRIED TO DEFINE THE FUNCTION AND CALL IT: ARE THERE NEW PROTOCOLS IN 2.3 FOR INTERACTIVE SYNTAX ? >>> def catTwice(part1, part2) File "", line 1 def catTwice(part1, part2) ^ SyntaxError: invalid syntax >>> def catTwice(part1, part2): ... cat = part1 + part2 ... printTwice(cat) ... chant1 = "pie Jesu domine," File "", line 4 chant1 = "pie Jesu domine," ^ SyntaxError: invalid syntax >>> HERE'S WHAT HAPPENED WHEN I TRIED TO RUN THE FILE cat.py: bash-2.05b$ python cat.py Traceback (most recent call last): File "cat.py", line 7, in ? catTwice(chant1, chant2) File "cat.py", line 3, in catTwice printTwice(cat) NameError: global name 'printTwice' is not defined From py at humnet.ucla.edu Sat Apr 3 01:43:31 2004 From: py at humnet.ucla.edu (peter hodgson) Date: Wed Apr 14 21:31:44 2004 Subject: [Tutor] python 2.2 and 2.3 Message-ID: <200404030643.i336hVbk013456@larkspur.noc.ucla.edu> OUCH! i just discovered that the function printTwice() was presumed to be already defined in the interactive session in question: but i'm still in the dark about the interactive syntax, and 2.3 vs. 2.2 in general; minutes ago i wrote: i'm afraid my python 2.2 tutorial may be out of step with python 2.3; HERE'S THE EXCERPT FROM THE 2.2 TUTORIAL def catTwice(part1, part2): cat = part1 + part2 printTwice(cat) This function takes two arguments, concatenates them, and then prints the result twice. We can call the function with two strings: >>> chant1 = "Pie Jesu domine, " >>> chant2 = "Dona eis requiem." >>> catTwice(chant1, chant2) Pie Jesu domine, Dona eis requiem. Pie Jesu domine, Dona eis requiem. HERE'S WHAT HAPPENED WHEN I TRIED TO TEST THE SUSPICIOUS printTwice(): >>> printTwice('forty') Traceback (most recent call last): File "", line 1, in ? NameError: name 'printTwice' is not defined HERE'S WHAT HAPPENED WHEN I TRIED TO DEFINE THE FUNCTION AND CALL IT: >>> def catTwice(part1, part2) File "", line 1 def catTwice(part1, part2) ^ SyntaxError: invalid syntax >>> def catTwice(part1, part2): ... cat = part1 + part2 ... printTwice(cat) ... chant1 = "pie Jesu domine," File "", line 4 chant1 = "pie Jesu domine," ^ SyntaxError: invalid syntax >>> HERE'S WHAT HAPPENED WHEN I TRIED TO RUN THE FILE cat.py: bash-2.05b$ python cat.py Traceback (most recent call last): File "cat.py", line 7, in ? catTwice(chant1, chant2) File "cat.py", line 3, in catTwice printTwice(cat) NameError: global name 'printTwice' is not defined From dtalaga at novodynamics.com Wed Apr 14 22:59:03 2004 From: dtalaga at novodynamics.com (David Talaga) Date: Wed Apr 14 22:58:48 2004 Subject: [Tutor] Tkinter dialog boxes Message-ID: Does anyone know how to create a dialog box to open a file in Python. My guess would be there has got to be some kind of way! Any help you be greatly appreciated! David Talaga dtalaga@novodynamics.com From fredm at smartypantsco.com Thu Apr 15 01:26:09 2004 From: fredm at smartypantsco.com (Alfred Milgrom) Date: Thu Apr 15 01:27:18 2004 Subject: [Tutor] Tkinter dialog boxes In-Reply-To: Message-ID: <5.1.0.14.0.20040415151741.034eb130@192.168.1.1> At 10:59 PM 14/04/04 -0400, David Talaga wrote: >Does anyone know how to create a dialog box to open a file in Python. My >guess would be there has got to be some kind of way! Any help you be greatly >appreciated! > >David Talaga >dtalaga@novodynamics.com Tkinter has built-in facilities for this. What about: from Tkinter import * import tkFileDialog top = Tk() top.withdraw() initDir = 'C:/windows/desktop' filetype = [('Text files', 'txt')] FileName = tkFileDialog.askopenfilename(initialdir=initDir, filetypes=filetype) print FileName Hope this helps, Alfred Milgrom From padmaja at agere.com Thu Apr 15 02:57:03 2004 From: padmaja at agere.com (Jayanthi, Satya Padmaja (Satya Padmaja)) Date: Thu Apr 15 02:57:22 2004 Subject: [Tutor] Python wrappers for TCL routines Message-ID: Hi all : Can any one let me know if I can somehow directly write Python wrappers for TCL routines. I would like to avoid using any other language like C in between. Thanks and Regards, Padmaja ----------------------------------------------------------------- "Black holes are where God divided by zero." - Steven Wright From alan.gauld at blueyonder.co.uk Thu Apr 15 03:13:48 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Apr 15 03:13:18 2004 Subject: [Tutor] On New Style Classes References: <66F587DFDD46D511B65200508B6F8DD60EF88EFE@nt-kalopsapp07.ntl-city.com> Message-ID: <01bc01c422b9$32c06420$6401a8c0@xp> > event oriented programing. However class methods and static classes don't > really make sence to me. They seem to be a syntatictic kludge. I know what > they are but not why python needs them. I'm confused by this statement. Python needs class methods for the same reason other OO languages need them - to implement class behaviour and enable metaclass style programming. That is, to implement behaviour that is common to all instances of the class or that can be invoked without an instance in existence. Why would Python not need such capability? Alan G. From alan.gauld at blueyonder.co.uk Thu Apr 15 03:20:11 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Apr 15 03:19:40 2004 Subject: [Tutor] Filtering text files References: <9A4B2157EFDBE546BECD68C62AC3B1C81738F0CE@es05snlnt.sandia.gov> Message-ID: <01c701c422ba$171d8ad0$6401a8c0@xp> > I am running the file in IDLE. I go to run, run module. Here is the shell > screen: > >>> ================================ RESTART > ================================ > >>> > >>> OK, That looks like the explanation. ;-) At a guess: You have defined a function in your code but you are not calling the function. So when you run the module all it does is load the function definition, it doesn't execute the function. (Assuming the code you semnt is the complete module) Could that be it? What I mean is that after loading the module you need to add a line like this: mymodule.filterFile("somefile.txt","result.txt") to actually execute it... HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld > If the complete program that you are executing is this: > > ### > > def filterFile(lmps, newFile): > > f1 = open(lmps, "r") > > f2 = open(newFile, "w") > > while 1: > > text = f1.readline() > > if text == "": > > break > > if text[0] == 'I': > > continue > > f2.write(text) > > f1.close() > > f2.close() > > return > ### > From alan.gauld at blueyonder.co.uk Thu Apr 15 03:34:14 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Apr 15 03:33:43 2004 Subject: [Tutor] Filtering text files References: Message-ID: <01da01c422bc$0d70d170$6401a8c0@xp> HI, Can you choose a new subject for messages about a new subject please? It gets very confusing to find a completely different topic inside a message from another thread, not to mention hard to find it in the future from the archives. Thanks. > C=Tkinter.Radiobutton(text="Change dir to C:", value=0).pack() > D=Tkinter.Radiobutton(text="Change dir to D:", value=0).pack() > E=Tkinter.Radiobutton(text="Change dir to E:", value=0).pack() > F=Tkinter.Radiobutton(text="Change dir to F:", value=0).pack() > G=Tkinter.Radiobutton(text="Change dir to G:", value=0).pack() First problem is pack returns zero so all your variables store zero not the widgets! You must do it in 2 stages: C=Tkinter.Radiobutton(text="Change dir to C:", value=0) C.pack() > if C.select(): > C=Tkinter.Radiobutton(text="Change dir to C:", > value=1,command=os.chdir('C:\\').pack() This creates a new button. You only want to change the value I think. Something like C['value'] = 1 should be all you need Also the command will call the os.system finction which returns zero and that will be stored, not much use. You need to pass a function object as the value of command, and do it where you define the object. I'd try something like: def cdToC(): os.chdir('C:/') def cdToD(): os.chdir('D:/') etc C=Tkinter.Radiobutton(text="Go to C:", value=0, command=cdToC) or use lambda expressions like so: C=Tkinter.Radiobutton(text="Go to C:", value=0, command=lambda : os.chdir('C:/')) HTH Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at blueyonder.co.uk Thu Apr 15 03:39:48 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Apr 15 03:39:15 2004 Subject: [Tutor] Classes and has_key References: <000301c418c9$219ff240$6f01010a@Rachel> Message-ID: <01f401c422bc$d42f9260$6401a8c0@xp> > >>> a.has_key('oranges') > > I get: > > Traceback (most recent call last): > File "", line 1, in -toplevel- > a.has_key['oranges'] > AttributeError: itemList instance has no attribute 'has_key'' > > I had thought 'has_key()' was a builtin, Its a part of builtin dictionaries but you aren't using a builtin dictionary you are using your own class: > class itemList: > def __init__(self): > def addItem(self, item): > def addPart(self, item, key, value): > def view(self, item=None): > def remove(self, item): > def count(self): > > a=itemList() Which as you can see, has no has_key() operation... YOu either need to subclass your class from dictionary or provide a has_key() method. Alan G. From alan.gauld at blueyonder.co.uk Thu Apr 15 03:47:37 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Apr 15 03:47:06 2004 Subject: [Tutor] passwd.py References: <200404021425.i32EPnWB013077@nightshade.noc.ucla.edu> Message-ID: <01ff01c422bd$ebc201a0$6401a8c0@xp> > import sys #no "welcome.." after else: > > passwd = "foobar" #a dummy passwd > count = 3 > current_count = 0 > while passwd != "unicorn": > current_count = current_count + 1 > passswd = raw_input("Passwd: ") #P..as text; p.. is a var > if current_count < count: A wee bug here I think. This will fail on the third attempt - ie your users only get two guesses! You need to check for (current_count <= count) I think. > print "no, stupid! try again;" > else: > print "three times, you're out!" > break #double indent;breaks loop I dont think you need break and sys.exit. If you puit the exit instead of the bbreak it should work. > sys.exit(1) #no good for "unicorn" This gets called after you exit the loop regardless of whether it was succesfully or not. > print "welcome in" > #sys.exit() [per w.chung, core PYTHON PROGRAMMING]; > # indented twice fails to stop "welcome in"; Thats because you hit break first and it exits the loop > # indented once causes exit after first incorrect password; Thats because its part of the loop and executes after the if statement each time. > # not indented works fine with wrong passwds; > # but also kicks out 'unicorn' w/ "three times, you're out!" I think thats the <= bug I mentioned earlier. HTH Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at blueyonder.co.uk Thu Apr 15 03:54:33 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Apr 15 03:54:01 2004 Subject: [Tutor] 2.2 and 2.3 References: <200404030638.i336cBK3007581@geranium.noc.ucla.edu> Message-ID: <020401c422be$e3bafe70$6401a8c0@xp> > i'm afraid my python 2.2 tutorial may be out of step with python 2.3; Nope its a problem in the code not the tutorial... > def catTwice(part1, part2): > cat = part1 + part2 > printTwice(cat) > > This function takes two arguments, concatenates them, and then prints > the result twice. Strictly speaking it doesn't. It takes two aguments, concatenates them then calls another function called printTwice using the concatentation as an argument. It will only print them twice if a function called printTwice() actually exists and has code to print twice! ie somewhere something like this exists: def printTwice(arg): print arg, arg > HERE'S WHAT HAPPENED WHEN I TRIED TO TEST THE SUSPICIOUS printTwice(): > IS printTwice SOMETHING NO LONGER ACTIVE IN 2.3? It was never active in any Python version you need to write it - presumably it appeared earlier in the tutorial? > >>> printTwice('forty') > Traceback (most recent call last): > File "", line 1, in ? > NameError: name 'printTwice' is not defined So Python is simply saying that it doesn't know anything about printTwice(). Add the function definition above to your code and it should work... > >>> def catTwice(part1, part2): > ... cat = part1 + part2 > ... printTwice(cat) > ... chant1 = "pie Jesu domine," Y0u need to get back to the >>> prompt before typing the chant= line. Just hit an extra return after the function definition part: >>> def catTwice(part1, part2): ... cat = part1 + part2 ... printTwice(cat) ... >>> chant1 = "pie Jesu domine," HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From adam at monkeez.org Thu Apr 15 05:08:26 2004 From: adam at monkeez.org (Adam) Date: Thu Apr 15 05:09:36 2004 Subject: [Tutor] Advice needed on first project Message-ID: <407E510A.30809@monkeez.org> I've started coding some python as my first attempt at learning it - I kind of learn things by doing them. I'd appreciate some feedback, if that's possible and guidance for an error that I've come up against (which is obviously created by my code, not python). The background is that this is a small command line application which collects data about magazine articles which will be written to a text file. However, I'm not at that stage yet. I have a meny.py file which initiates the program, and then I'm trying to create a new article through create_new_article.py. Menu calls create_new_article, and I want to return a list (article_items) back to menu.py. You can see the code at: http://www.monkeez.org/python/mag/menu.txt and http://www.monkeez.org/python/mag/create_new_article.txt How do I return the article_items so that menu.py has access to it? Does "global article_items" only affect the create_new_article module, or will it apply even further. In my case, it only seems to apply to that function. I'd also appreciate some feedback on the code design. Does the code reflect the best design, or would there be a better way of doing this? Thanks in advance. adam From orbitz at ezabel.com Thu Apr 15 07:53:29 2004 From: orbitz at ezabel.com (orbitz@ezabel.com) Date: Thu Apr 15 07:54:37 2004 Subject: [Tutor] os.system() start an application / program In-Reply-To: <001f01c41816$6dc52400$6601a8c0@jaimelopes> References: <001f01c41816$6dc52400$6601a8c0@jaimelopes> Message-ID: <20040415075329.4ed9e803.orbitz@ezabel.com> Look at the differences between the two lines, one has \\ the other doesn't. You can just use a raw string and use \ if you want. See the tutorial for how to use raw strings. On Thu, 1 Apr 2004 19:21:10 +0100 "Miguel Lopes" wrote: > Hi, > > I'm experimenting with os.system() to start another application in my pc. > I have no problems with the following statement: > > os.system("start C:\\MyDb1.mdb") > > A command box appears/ desappears and Access starts running. > > *** > > On the other hand the following statement doesn't work: > > os.system("start C:\Program Files\Internet Explorer\Iexplorer.exe") > > I'm as sure as I can be that this as something to do with either long file > names or spaces in the dos command. > If this is true this is not really a Python problem, but still is something > probably alot of people encounter, so ther is probably a fast answer to my > hair pulling problem :-) > > I'm running Python2.3 on MSW98 2nd. > > > Txs, > Miguel > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From klappnase at freenet.de Thu Apr 15 08:17:44 2004 From: klappnase at freenet.de (Michael Lange) Date: Thu Apr 15 08:18:34 2004 Subject: [Tutor] command call in Windows for Image converting with ImageMagick In-Reply-To: <40729080.5040808@ukl.uni-freiburg.de> References: <40729080.5040808@ukl.uni-freiburg.de> Message-ID: <20040415141744.41980eea.klappnase@freenet.de> On Tue, 06 Apr 2004 13:12:00 +0200 Michael Just wrote: > Here are my questions: > > 1) How can I start the program "identify "? > I got the already with "os.listdir(os.curdir)" > > 2) How I fetch the output of "identify "? > import commands image_data = commands.getoutput("identify ") > The call for "convert" will be the same as for 1) and 2). > > 3) How about error-handling, when a file could not be resized? import os exit_state = os.system("convert ") if exit_state == 0: ... else: ... I must admit that I'm not really sure if this works on windows, with linux I think this should do what you want. I hope this helps Michael From Chad.Crabtree at nationalcity.com Thu Apr 15 09:25:31 2004 From: Chad.Crabtree at nationalcity.com (Crabtree, Chad) Date: Thu Apr 15 09:26:25 2004 Subject: [Tutor] On New Style Classes Message-ID: <66F587DFDD46D511B65200508B6F8DD60EF88F00@nt-kalopsapp07.ntl-city.com> Well I guess that my post was superflous. I just felt that the syntax for the classmethod and static methods where just wierd. In addition it doesn't seem like they are needed because in the past it just seemed that you would put the function in a module which for all intents looks like a class. It just isn't clear to me how this feature improves objects or how they are used. -----Original Message----- From: Alan Gauld [mailto:alan.gauld@blueyonder.co.uk] Sent: Thursday, April 15, 2004 3:14 AM To: Crabtree, Chad; tutor@python.org Subject: Re: [Tutor] On New Style Classes > event oriented programing. However class methods and static classes don't > really make sence to me. They seem to be a syntatictic kludge. I know what > they are but not why python needs them. I'm confused by this statement. Python needs class methods for the same reason other OO languages need them - to implement class behaviour and enable metaclass style programming. That is, to implement behaviour that is common to all instances of the class or that can be invoked without an instance in existence. Why would Python not need such capability? Alan G. ------------------------------------------------------------------------------------------- ***National City made the following annotations ------------------------------------------------------------------------------------------- This communication is a confidential and proprietary business communication. It is intended solely for the use of the designated recipient(s). If this communication is received in error, please contact the sender and delete this communication. =========================================================================================== From dtalaga at novodynamics.com Thu Apr 15 09:38:04 2004 From: dtalaga at novodynamics.com (David Talaga) Date: Thu Apr 15 09:37:44 2004 Subject: [Tutor] deleting CR within files Message-ID: Hi all! Here is my next problem. I am trying to rid some files of pesky from files. Here is my code. Any help would be great! import re, os, dialog #dialog is a dialog box function sub = re.sub fileName = dialog in_file = open(fileName,'r') #I open the file for reading out_file = open(fileName + '_cleaned', 'w') #I opne the file and rename it as filename_cleaned. for i in in_file.readlines(): I thikn you get the rest tmp = sub('\x0D','', i) out_file.write(tmp) in_file.close() out_file.close() David Talaga dtalaga@novodynamics.com 734-205-9127 From magnus at thinkware.se Thu Apr 15 10:56:14 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Thu Apr 15 10:56:27 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gQWR2aWNlIG5lZWRlZCBvbiBmaXJzdCBwcm9qZWN0?= Message-ID: Adam wrote: > I've started coding some python as my first attempt at learning it - I > kind of learn things by doing them. Welcome to the world of Python! I hope you will enjoy it. > You can see the code at: http://www.monkeez.org/python/mag/menu.txt and > http://www.monkeez.org/python/mag/create_new_article.txt > > How do I return the article_items so that menu.py has access to it? You return it alright. That's not the problem... > Does > "global article_items" only affect the create_new_article module, or Global means global within a module (i.e. file) in Python. You shouldn't use global variables in cases like this anyway. > will it apply even further. In my case, it only seems to apply to that > function. Your problem is that, while the newarticle() function returns a value, you don't receive it, you just throw it away! You must assign the value you receive to a variable in the calling scope. Try replacing the line: create_new_article.newarticle() with article_items = create_new_article.newarticle() Then you obviously need some more code that actually does something with the article items. > I'd also appreciate some feedback on the code design. Does the code > reflect the best design, or would there be a better way of doing this? No. There is always a better way of doing things. Is it good enough? Well, since it doesn't actually work yet, and seems far from complete, I guess it's a bit early to say... One detail is that you shouldn't make lines longer that 70-80 characters (just like with normal text) as it gets difficult to read. It's also not very pythonic to make such small modules. I this case I see no reason to make more than one file. Split it if it really needs to be split, i.e. if it gets big, has several maintainers etc. With the typical "if __name__ == '__main__':" trick, you can still use the code as a module even if it also works as a stand alone program. I also see two cases where it might be more pythonic to use a loop and a more data driven approach, You might also consider using triple quoted milti line strings for your welcome message. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From dtalaga at novodynamics.com Thu Apr 15 11:23:38 2004 From: dtalaga at novodynamics.com (David Talaga) Date: Thu Apr 15 11:23:20 2004 Subject: FW: [Tutor] deleting CR within files Message-ID: -----Original Message----- From: David Talaga [mailto:dtalaga@novodynamics.com] Sent: Thursday, April 15, 2004 10:49 AM To: Roger Merchberger Subject: RE: [Tutor] deleting CR within files Ok, here is what we have now: import os import Tkinter import dialog import sys import re root=Tkinter.Tk() f=Tkinter.Button(root, text="Find Files", command=dialog.dialog).pack() x=Tkinter.Button(root, text="Close", command=sys.exit).pack() sub = re.sub fileName= dialog.dialog in_file = open(fileName,'r') out_file = open(fileName + '_cleaned', 'w') for i in in_file.readlines(): out_file.write(i[:1] + '\n') print 'File cleaned' in_file.close() out_file.close() Tkinter.mainloop() Now when I run it is says this: Traceback (most recent call last): File "", line 1, in ? execfile('crgui.py') File "crgui.py", line 13, in ? in_file = open(fileName,'r') TypeError: coercing to Unicode: need string or buffer, function found I did not know that I was using unicode up there... I am realy at a loss. The program runs fine as far ad the dialog box coming up and the print statement executing. I just dont know what the error is saying. Do I need a string in place of fileName and if I do how would I go about putting a string in there and still trying to call dialog.dialog? Any help or direction would be greatly appreciated and also the option to take my first born son. (Not realy, well, OK, if you realy thikn it's a fair trade...) David Talaga -----Original Message----- From: Roger Merchberger [mailto:zmerch@30below.com] Sent: Thursday, April 15, 2004 10:23 AM To: David Talaga Subject: Re: [Tutor] deleting CR within files Rumor has it that David Talaga may have mentioned these words: >Hi all! >Here is my next problem. I am trying to rid some files of pesky from >files. Here is my code. Any help would be great! What platform? If it's *nix, you're using the wrong tool for the job. There's command line utilities that can do that, usually named 'dos2unix' and 'unix2dos' to either remove or insert \r characters. If you're in windows, there are unix-ish utilities you can download (google for cygwin) that give you a bashprompt on WinNT4/2K/XP and methinks 98+, but don't quote me on that last part... Also, it would help us to know what type of files you're editing - are they basic text files where the \r is either the last or next-to-last character in the line? If so, you're working too hard... Try this: >import os, dialog #dialog is a dialog box function > >fileName = dialog > >in_file = open(fileName,'r').readlines() #I read the whole file at once >out_file = open(fileName + '_cleaned', 'w') #I opne the file and rename it >as filename_cleaned. >for i in in_file: ## I thikn you get the rest > out_file.write(i[:-2] + '\n') # Use this line if you're removing > \r\n or \n\r > out_file.write(i[:-1]) # use this line if you're removing \n\r > out_file.write(i[:-1] + '\n') # use this line if you're removing \r only >out_file.close() If you need to find a \r in the middle of a string, regular expressions (the re module) is still overkill - try this: import string teststr = "here's the string with \r in it" wherecr = string.index(teststr,'\r') newstr = teststr[:wherecr] + [wherecr+1:] =-=-=-=-=-=-=-=-=-=-= if you have multiple \r's in a line, you'd need to add a flag & a while loop - I'll leave that up as an exercise to the reader... ;-) HTH, Roger "Merch" Merchberger -- Roger "Merch" Merchberger | A new truth in advertising slogan sysadmin, Iceberg Computers | for MicroSoft: "We're not the oxy... zmerch@30below.com | ...in oxymoron!" -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040415/8899c79b/attachment.html From project5 at redrival.net Thu Apr 15 12:39:01 2004 From: project5 at redrival.net (Andrei) Date: Thu Apr 15 12:39:32 2004 Subject: [Tutor] Re: os.system() start an application / program References: <001f01c41816$6dc52400$6601a8c0@jaimelopes> Message-ID: Funny, a virtually identical message appeared a few days ago and I even answered to it :). Miguel, perhaps you should check the Tutor archives. > I'm experimenting with os.system() to start another application in my pc. > I have no problems with the following statement: > > os.system("start C:\\MyDb1.mdb") > > A command box appears/ desappears and Access starts running. > > *** > > On the other hand the following statement doesn't work: > > os.system("start C:\Program Files\Internet Explorer\Iexplorer.exe") > > I'm as sure as I can be that this as something to do with either long file > names or spaces in the dos command. > If this is true this is not really a Python problem, but still is > something probably alot of people encounter, so ther is probably a fast > answer to my hair pulling problem :-) > > I'm running Python2.3 on MSW98 2nd. -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From adam at monkeez.org Thu Apr 15 12:49:25 2004 From: adam at monkeez.org (Adam) Date: Thu Apr 15 12:51:13 2004 Subject: [Tutor] Advice needed on first project In-Reply-To: References: Message-ID: <407EBD15.4030308@monkeez.org> Thanks Magnus. I have some more related questions below Magnus Lycka wrote: > Adam wrote: > >>I've started coding some python as my first attempt at learning it - I >>kind of learn things by doing them. > > > Try replacing the line: > > create_new_article.newarticle() > > with > > article_items = create_new_article.newarticle() > I did try this earlier, but must have had a syntax problem, or something similar - it seemed to me to be the most obvious thing to do. Am I right in thinking that the passed article_items and the menu article_items are different references - or do they point to the same object? What I'm trying to say is, does it produce a copy of that object, or is it another pointer to that same object ? > >>I'd also appreciate some feedback on the code design. Does the code >>reflect the best design, or would there be a better way of doing this? > > > No. There is always a better way of doing things. Is it good enough? > Well, since it doesn't actually work yet, and seems far from complete, > I guess it's a bit early to say... > > One detail is that you shouldn't make lines longer that 70-80 characters > (just like with normal text) as it gets difficult to read. Agreed > It's also not very pythonic to make such small modules. I this case > I see no reason to make more than one file. Split it if it really needs > to be split, i.e. if it gets big, has several maintainers etc. With the > typical "if __name__ == '__main__':" trick, you can still use the code > as a module even if it also works as a stand alone program. Ah, I did wonder this - it is good to know this sooner than later. I will try to encorporate the code in to fewer files. > I also see two cases where it might be more pythonic to use a loop > and a more data driven approach, Hmm - I'm not sure what you mean here - would this involve producing something like a query module, which acts as a menu which receives the options that are available and then outputs them to the user and handles the response? I imagine that this would save a lot of coding. Is this possible? It is difficult for me to be clear without writing some code. I might have a stab at this this evening. > You might also consider using triple quoted milti line strings for > your welcome message. > What benefit does this offer? I thought that the quotes pretty much acted in the same ways, unless you used 'special chars', like " and ' inside them. Does this have something to do with the newline characters? Thanks again. Already I feel at home! adam From project5 at redrival.net Thu Apr 15 12:43:48 2004 From: project5 at redrival.net (Andrei) Date: Thu Apr 15 12:51:51 2004 Subject: [Tutor] Re: deleting CR within files References: Message-ID: Hi, David Talaga wrote on Thursday 15 April 2004 15:38: > Here is my next problem. I am trying to rid some files of pesky from > files. Here is my code. Any help would be great! Perhaps you should mention what the problem is, not just the code. Just guessing here, are you writing a file containing '\n' on Windows? If so, those '\n' get automatically expanded to '\r\n' because that's the way Windows does newlines. The only way to get around this (AFAIK) is to open both files in binary body ('rb' respectively 'wb') and read one character at a time. If that character's ord() is 10 (or is 13? I keep mixing them up), don't write it to the out_file, otherwise do write it. -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From askoose at sandia.gov Thu Apr 15 13:05:26 2004 From: askoose at sandia.gov (Kooser, Ara S) Date: Thu Apr 15 13:06:27 2004 Subject: [Tutor] Filtering text files Message-ID: <9A4B2157EFDBE546BECD68C62AC3B1C81738F0D2@es05snlnt.sandia.gov> Hello, Thank you for help with the calling of the function. I went through your tutorial and that exlained the problems I was having. Now I am running into another problem. My output file is blank. The current version of the code I am using is below on Python 2.3.3. The python shell shows the final print statement and then a out.txt is created but is blank. I am guessing that something is wrong with my write command. Thanks again. Ara def filterFile(lmps,out): inp = open("lmps.txt", "r") outp = open("out.txt", "w") while 1: text = inp.readline() if text =="": break if text[0] =="I": continue outp.write(text) inp.close() outp.close() return filterFile("lmps.txt","out.txt") print "One file has been filtered" From andy at andybak.net Thu Apr 15 13:07:15 2004 From: andy at andybak.net (Andy Baker) Date: Thu Apr 15 13:07:43 2004 Subject: [Tutor] command call in Windows for Image converting with ImageMagick In-Reply-To: Message-ID: Just to point out that Photoshop is very easy to automate with scripting. Photoshop 5 had decent OLE scripting but needed all the constants defined. Photoshop 6 and 7 had a type library that defined everything you need and some reasonable documentation. Pretty much everything is scriptable although not every function has properly exposed method name. Most obvious stuff is though and scripting from Python would be a breeze. From askoose at sandia.gov Thu Apr 15 13:09:24 2004 From: askoose at sandia.gov (Kooser, Ara S) Date: Thu Apr 15 13:10:13 2004 Subject: [Tutor] Filtering text files Message-ID: <9A4B2157EFDBE546BECD68C62AC3B1C81738F0D3@es05snlnt.sandia.gov> I got it. Thank you all for your help. I was being dumb and mis-spaced the commands. Ara From zmerch at 30below.com Thu Apr 15 13:18:20 2004 From: zmerch at 30below.com (Roger Merchberger) Date: Thu Apr 15 13:18:37 2004 Subject: [Tutor] deleting CR within files Message-ID: <5.1.0.14.2.20040415131748.00ae8e28@mail.30below.com> Rumor has it that David Talaga may have mentioned these words: import os, Tkinter, dialog, sys # You weren't using re anymore, no need to import it root=Tkinter.Tk() f=Tkinter.Button(root, text="Find Files", command=dialog.dialog).pack() x=Tkinter.Button(root, text="Close", command=sys.exit(0)).pack() # you didn't use 'sub' anymore, so... # sub = re.sub fileName= dialog.dialog # if you call readlines() on the open, it opens, reads, and # closes all in one step, it makes readability easier... in_file = open(fileName,'r').readlines() # See my previous post about how you can put the _cleaned *before* # the extension so you can still open the files by extension... out_file = open(fileName + '_cleaned', 'w') for i in in_file: # There's a non-syntax bug in the next line: if you need to remove # the last character in the line, use -1. A negative index means: # "Go from the end of the array (in this case an array of chars) # and work backwards." # what you coded was "Take the first character of every string, # lop off the rest, and add a \n." Prolly not what you wanted. ;-) out_file.write(i[:-1] + '\n') # Remember, this is not actually searching for '\r' chars - it's only # lopping off the last character, and adding a \n. If this is in # winders, this won't work, as the standard line ending is # '\r\n' - and the code above is lopping off a \n to add a \n. # out_file.write(i[:-2] + '\n') # is what you'd want for winders. print 'File cleaned' # Python is "indent-loop" based - you'll be printing 'File cleaned' # for *every line* in the file, not only at the end of the file. # You'd wanna move that out of the loop by unindenting it. # Next line not necessary if you readlines() with the open... # in_file.close() out_file.close() # I haven't done a lot of Tk programming, but shouldn't the next # line be: root.mainloop() # instead of Tkinter.mainloop? =-=-=-= My (so far one and only) main Tkinter script I wrote is here: http://tivo.30below.com/zmerch/AviSynth_2.pyw It's been tested on Python 2.2.2 and 2.3.x - and it's for a winders platform... [snip] >Now when I run it is says this: >Traceback (most recent call last): > File "", line 1, in ? > execfile('crgui.py') > File "crgui.py", line 13, in ? > in_file = open(fileName,'r') >TypeError: coercing to Unicode: need string or buffer, function found For this error, what I'd do is right before this line, put in this: =-=-=-=-= print fileName sys.exit(0) =-=-=-=-= If what prints looks like: u'ThisIsUnicode.txt' ^^ starting with a U, then the dialog.dialog script is returning a unicode string instead of standard ASCII string, which is what's necessary to open files. Try this line instead: fileName= str(dialog.dialog) That may convert the unicode to standard ASCII. HTH, Roger "Merch" Merchberger -- Roger "Merch" Merchberger -- sysadmin, Iceberg Computers zmerch@30below.com What do you do when Life gives you lemons, and you don't *like* lemonade????????????? From project5 at redrival.net Thu Apr 15 13:33:41 2004 From: project5 at redrival.net (Andrei) Date: Thu Apr 15 13:33:54 2004 Subject: [Tutor] Re: Advice needed on first project References: <407EBD15.4030308@monkeez.org> Message-ID: Adam wrote on Thursday 15 April 2004 18:49: >> Try replacing the line: >> create_new_article.newarticle() >> with >> article_items = create_new_article.newarticle() > I did try this earlier, but must have had a syntax problem, or something > similar - it seemed to me to be the most obvious thing to do. Am I right > in thinking that the passed article_items and the menu article_items are > different references - or do they point to the same object? What I'm > trying to say is, does it produce a copy of that object, or is it > another pointer to that same object ? Not a pointer, a reference. Assignments always bind an existing object to a new name. You can avoid that and force Python to create a new object by using the copy module (copy.copy and copy.deepcopy). >> You might also consider using triple quoted milti line strings for >> your welcome message. > > What benefit does this offer? I thought that the quotes pretty much > acted in the same ways, unless you used 'special chars', like " and ' > inside them. Does this have something to do with the newline characters? Triple-quoted strings can have this form: """First line Second line""", which makes them a better way of specifying long strings. So it does have to do with the newline characters in long strings :). It would also remove the need to make a function especially for the purpose of showing the welcome string, since it could simply be a variable which gets printed, "print welcome". Another neat trick is to use a docstring at the top of your module and use that for welcome too: """My doc""" # doc string for module print __doc__ # print docstring at top of module Other suggestions about the code: - don't use tabs. The preferred way of writing Python code is by using 4 spaces per indentation level. This is what you do in create_new_articles, but you use tabs in menu. If you now try to copy-paste code from the one to the other in order to avoid the mini-modules, you'll get some errors I think. The best way to not worry about this is to set up your editor in such a way that pressing TAB will insert 4 spaces and that auto-indentation uses 4 spaces. - raw_input takes a parameter: >>> raw_input("Your name: ") Your name: Adam 'Adam' Use this in order to avoid all the print statements in create_new_article. This will almost halve the amount of code in that function. - always assume your users are stupid - I do that even if I only code for myself :). What happens if your user answers "n" or 'new' in the menu or accidentally types a space before or after the 'n'? He's told the choice is invalid. Case sensitive menus are not a very good idea. That's why it makes sense to clean up the response a bit: response = response.strip().lower() # remove spaces and lower-case it In order to account for cases when the user answers 'new', you could also: response = response[:1] # only look at the first char - there's no way to exit from the menu, nor instructions on how to terminate the program by other means (Ctrl+Z). -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From alan.gauld at blueyonder.co.uk Thu Apr 15 14:05:02 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Apr 15 14:04:30 2004 Subject: [Tutor] Filtering text files References: <9A4B2157EFDBE546BECD68C62AC3B1C81738F0D2@es05snlnt.sandia.gov> Message-ID: <020901c42314$2c53e430$6401a8c0@xp> > statement and then a out.txt is created but is blank. I am guessing that > something is wrong with my write command. Thanks again. > > Ara > > def filterFile(lmps,out): > inp = open("lmps.txt", "r") > outp = open("out.txt", "w") > while 1: > text = inp.readline() > if text =="": > break > if text[0] =="I": > continue > outp.write(text) This is outside the loop so only the last line gets printed, but the last line is ""! You need to move the write inside the loop. Alan G. From alan.gauld at blueyonder.co.uk Thu Apr 15 14:20:41 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Apr 15 14:20:06 2004 Subject: [Tutor] Python wrappers for TCL routines References: Message-ID: <022d01c42316$5c06f8f0$6401a8c0@xp> > Can any one let me know if I can somehow directly write > Python wrappers for TCL routines. I would like to avoid > using any other language like C in between. Yes there is. There is a hook in Tkinter whereby you can execute arbitrary Tcl code, so you could wrap that ina function call. Search the comp.lang.python newgroups on Google groups and you should find a mail from, I think, Cameron Laird which shows how... Alan G. From askoose at sandia.gov Thu Apr 15 14:35:29 2004 From: askoose at sandia.gov (Kooser, Ara S) Date: Thu Apr 15 14:35:46 2004 Subject: [Tutor] Parsing text file? Message-ID: <9A4B2157EFDBE546BECD68C62AC3B1C81738F0D4@es05snlnt.sandia.gov> Hello, I have finished the filter program which removes the header in original file. I now need to remove the first column of data and then convert the second. Is parsing right for this? Are there good websites for me to read or books on this? I am trying to write as much of my own code as possible and ask questions. ;) Thanks. This is on Python 2.3.3. My data files looks like this: 16 1 1 0.00000 0.68337 0.25020 2 2 0.00000 0.29020 0.25020 3 3 0.00000 0.08104 0.25020 4 4 0.00000 0.00000 0.25020 Etc... Ara -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040415/cb75c960/attachment-0001.html From scot at possum.in-berlin.de Thu Apr 15 14:15:18 2004 From: scot at possum.in-berlin.de (Scot W. Stevenson) Date: Thu Apr 15 15:19:57 2004 Subject: [Tutor] Is defining functions as dummies pythonic? Message-ID: <200404152015.18118.scot@possum.in-berlin.de> Hello there, I'm writing a program where I let the user use a "-v" option to decide if he wants the output to be verbose. At the beginning, I was putting lots of lines such as: if isverbose: print "(Somewhat informative text)" where "isverbose" is a bool. After a while, this got to be a bore, and I rewrote the whole thing by starting with: if isverbose: def verbosize(text=""): print text else: def verbosize(text=""): pass and then plastered the whole program with verbosize("(Somewhat informative text)") This works fine, and if I understand the way the lower reaches of Python work, it should be faster, since I got rid of a bunch of "if"s and turned them into "passes" (which I hope the compiler completely gets rid of. However, defining functions based on parameters seems to be, well, strange, if not downright C-preprocessoresque. Is there any reason _not_ to do things this way, or, even better, is there a standard way to handle verbose program output I'm just not aware of? As always, thank you again for the help! Y, Scot -- Scot W. Stevenson - Panketal, Germany From garryknight at gmx.net Thu Apr 15 15:21:36 2004 From: garryknight at gmx.net (Garry Knight) Date: Thu Apr 15 15:21:49 2004 Subject: [Tutor] RE: Filtering text files References: <9A4B2157EFDBE546BECD68C62AC3B1C81738F0D2@es05snlnt.sandia.gov> Message-ID: In message <9A4B2157EFDBE546BECD68C62AC3B1C81738F0D2@es05snlnt.sandia.gov>, Kooser, Ara S wrote: > def filterFile(lmps,out): > inp = open("lmps.txt", "r") > outp = open("out.txt", "w") ... > filterFile("lmps.txt","out.txt") Alan explained what was going wrong with your code. I just thought I'd point out something else: you're calling filterFile with 2 arguments, "lmps.txt" and "out.txt", but those arguments are not being used in the filterFile function. You've declared that filterFile takes two parameters, lmps and out, but you don't actually use them in the function; instead, you've directly embedded the filenames in the body of the function. This is OK if you don't ever intend to call filterFile with different filenames, but it's redundant practice to declare parameters and then not use them. It's more usual to do this kind of thing: def filterFile(lmps,out): inp = open(lmps, "r") outp = open(out, "w") ... filterFile("lmps.txt","out.txt") What's happening here is that you're calling filterFile with the arguments "lmps.txt" and "out.txt". Within the function, the parameter lmps 'stands for' the argument "lmps.txt" and so the open() call works just as you want it to. Likewise, the parameter out 'stands for' the argument "out.txt" and so the second open() call works, too. So you don't actually need to use names like 'lmps' and 'out' for the filterFile function's parameters. It might make more sense to call them something like 'infname' and 'outfname': def filterFile(infname,outfname): inp = open(infname, "r") outp = open(outfname, "w") ... filterFile("lmps.txt","out.txt") Do you understand what's going on here? The string "lmps.txt" is being passed to the filterFile function, which receives it into the parameter 'infname'. The open() call uses it to open the correct file. A similar thing happens with the string "out.txt" and the parameter 'outfname'. You could later call the function with: filterFile("other.txt", "thisone.txt") and the file "other.txt" would be read and the results written to the file "thisone.txt". What you're seeing in action is the substitution of arguments to a function into the parameters of a function and it's one of the main reasons for having functions in the first place: so that the same piece of code can be reused over and over again with different arguments. If you're still not sure about all this, you might want to re-read one or more of the tutorials that deal with functions. And by all means, ask more questions on this list. -- Garry Knight garryknight@gmx.net ICQ 126351135 Linux registered user 182025 From askoose at sandia.gov Thu Apr 15 15:28:25 2004 From: askoose at sandia.gov (Kooser, Ara S) Date: Thu Apr 15 15:28:40 2004 Subject: [Tutor] RE: Filtering text files Message-ID: <9A4B2157EFDBE546BECD68C62AC3B1C81738F0D5@es05snlnt.sandia.gov> Thanks. That works great and helps to clean up my code. Thanks again. Ara -----Original Message----- From: Garry Knight [mailto:garryknight@gmx.net] Sent: Thursday, April 15, 2004 1:22 PM To: tutor@python.org Subject: [Tutor] RE: Filtering text files In message <9A4B2157EFDBE546BECD68C62AC3B1C81738F0D2@es05snlnt.sandia.gov>, Kooser, Ara S wrote: > def filterFile(lmps,out): > inp = open("lmps.txt", "r") > outp = open("out.txt", "w") ... > filterFile("lmps.txt","out.txt") Alan explained what was going wrong with your code. I just thought I'd point out something else: you're calling filterFile with 2 arguments, "lmps.txt" and "out.txt", but those arguments are not being used in the filterFile function. You've declared that filterFile takes two parameters, lmps and out, but you don't actually use them in the function; instead, you've directly embedded the filenames in the body of the function. This is OK if you don't ever intend to call filterFile with different filenames, but it's redundant practice to declare parameters and then not use them. It's more usual to do this kind of thing: def filterFile(lmps,out): inp = open(lmps, "r") outp = open(out, "w") ... filterFile("lmps.txt","out.txt") What's happening here is that you're calling filterFile with the arguments "lmps.txt" and "out.txt". Within the function, the parameter lmps 'stands for' the argument "lmps.txt" and so the open() call works just as you want it to. Likewise, the parameter out 'stands for' the argument "out.txt" and so the second open() call works, too. So you don't actually need to use names like 'lmps' and 'out' for the filterFile function's parameters. It might make more sense to call them something like 'infname' and 'outfname': def filterFile(infname,outfname): inp = open(infname, "r") outp = open(outfname, "w") ... filterFile("lmps.txt","out.txt") Do you understand what's going on here? The string "lmps.txt" is being passed to the filterFile function, which receives it into the parameter 'infname'. The open() call uses it to open the correct file. A similar thing happens with the string "out.txt" and the parameter 'outfname'. You could later call the function with: filterFile("other.txt", "thisone.txt") and the file "other.txt" would be read and the results written to the file "thisone.txt". What you're seeing in action is the substitution of arguments to a function into the parameters of a function and it's one of the main reasons for having functions in the first place: so that the same piece of code can be reused over and over again with different arguments. If you're still not sure about all this, you might want to re-read one or more of the tutorials that deal with functions. And by all means, ask more questions on this list. -- Garry Knight garryknight@gmx.net ICQ 126351135 Linux registered user 182025 _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From sigurd at 12move.de Thu Apr 15 15:31:49 2004 From: sigurd at 12move.de (=?iso-8859-1?q?Karl_Pfl=E4sterer?=) Date: Thu Apr 15 15:33:43 2004 Subject: [Tutor] Parsing text file? In-Reply-To: <9A4B2157EFDBE546BECD68C62AC3B1C81738F0D4@es05snlnt.sandia.gov> (Ara S. Kooser's message of "Thu, 15 Apr 2004 12:35:29 -0600") References: <9A4B2157EFDBE546BECD68C62AC3B1C81738F0D4@es05snlnt.sandia.gov> Message-ID: On 15 Apr 2004, Kooser, Ara S <- askoose@sandia.gov wrote: > file. I now need to remove the first column of data and then convert the > second. Is parsing right for this? Are there good websites for me to read or > books on this? I am trying to write as much of my own code as possible and > ask questions. ;) Thanks. This is on Python 2.3.3. > My data files looks like this: > 16 > 1 1 0.00000 0.68337 0.25020 > 2 2 0.00000 0.29020 0.25020 > 3 3 0.00000 0.08104 0.25020 > 4 4 0.00000 0.00000 0.25020 > Etc... Is `16' in the first line part of your file? Your task could be solved pretty straightly: read each line of the file, split it on whitespace, convert the second column and write the data in a new file. (no need for a lot of books here). If you used a generator function you could write it like that: ******************************************************************** def proc_file (f, cfun=lambda n: n): for line in f: line = line.split()[1:] line[0] = cfun(line[0]) yield ' '.join(line) + '\n' inf = file('INFILE') out = file('OUTFILE', 'w') out.writelines(proc_file(inf, convfun)) out.close() inf.close() ******************************************************************** `convfun' must be the function to convert your data (if you don't use a second argument the identity function gets used). If `16' is part of your data you must treat the first line specific. Karl -- Please do *not* send copies of replies to me. I read the list From adam at monkeez.org Thu Apr 15 15:33:29 2004 From: adam at monkeez.org (Adam) Date: Thu Apr 15 15:34:23 2004 Subject: [Tutor] Re: Advice needed on first project In-Reply-To: References: <407EBD15.4030308@monkeez.org> Message-ID: <407EE389.7020303@monkeez.org> Andrei wrote: > Adam wrote on Thursday 15 April 2004 18:49: > > > > > Triple-quoted strings can have this form: > """First line > Second line""", > which makes them a better way of specifying long strings. So it does have to > do with the newline characters in long strings :). It would also remove the > need to make a function especially for the purpose of showing the welcome > string, since it could simply be a variable which gets printed, "print > welcome". > > Another neat trick is to use a docstring at the top of your module and use > that for welcome too: > > """My doc""" # doc string for module > print __doc__ # print docstring at top of module I thought so - this is a very intuitive language to pick up (well, at least for me it is). This will be adopted. > Other suggestions about the code: > > - don't use tabs. The preferred way of writing Python code is by using 4 > spaces per indentation level. This is what you do in create_new_articles, > but you use tabs in menu. If you now try to copy-paste code from the one to > the other in order to avoid the mini-modules, you'll get some errors I > think. > The best way to not worry about this is to set up your editor in such a way > that pressing TAB will insert 4 spaces and that auto-indentation uses 4 > spaces. > > - raw_input takes a parameter: > >>> raw_input("Your name: ") > Your name: Adam > 'Adam' > Use this in order to avoid all the print statements in create_new_article. > This will almost halve the amount of code in that function. I think I already experienced some problems with the tabs already. I started off using jedit (please don't start a discussion about merits of text editors!) and then gave pyalamode a go - it seemed to report errors with the indentation. I imagine that if I use one editor consistently, it will prevent this. > - always assume your users are stupid - I do that even if I only code for > myself :). What happens if your user answers "n" or 'new' in the menu or > accidentally types a space before or after the 'n'? He's told the choice is > invalid. Case sensitive menus are not a very good idea. That's why it makes > sense to clean up the response a bit: > > response = response.strip().lower() # remove spaces and lower-case it > > In order to account for cases when the user answers 'new', you could also: > > response = response[:1] # only look at the first char > > - there's no way to exit from the menu, nor instructions on how to terminate > the program by other means (Ctrl+Z). > This kind of feature is coming and it seems very easy to implement, but I bet that it is quite difficult to do well (ie. taking into account all eventualities of user input). Thanks again. adam From Doug.Shawhan at ge.com Thu Apr 15 15:51:34 2004 From: Doug.Shawhan at ge.com (Shawhan, Doug (EM, ITS)) Date: Thu Apr 15 15:51:44 2004 Subject: [Tutor] binary data as string? Message-ID: I have a question about the term 'bitwise' and whether binary data can be chopped and compared like strings. When one does 'bitwise' movements over data in strings it is actually moving 'characterwise', correct? Is there a way one could do actual 'bitsize' bitwise comparison and manipulation with binary data? I have a need to do bit by bit comparisons of various binary filetypes (images, soundfiles as well as text). The data does not need to be displayed, saved or otherwise presented to a human, simply chopped into small pieces and compared with other small pieces. I suppose I could use binascii and play with all of it as text (after all, it does not need to be rewritten out to files, just pickled :-), but I am hoping for a cleaner solution. Thanks! From sigurd at 12move.de Thu Apr 15 16:41:12 2004 From: sigurd at 12move.de (=?iso-8859-1?q?Karl_Pfl=E4sterer?=) Date: Thu Apr 15 16:46:11 2004 Subject: [Tutor] Is defining functions as dummies pythonic? In-Reply-To: <200404152015.18118.scot@possum.in-berlin.de> (Scot W. Stevenson's message of "Thu, 15 Apr 2004 20:15:18 +0200") References: <200404152015.18118.scot@possum.in-berlin.de> Message-ID: On 15 Apr 2004, Scot W. Stevenson <- scot@possum.in-berlin.de wrote: > where "isverbose" is a bool. After a while, this got to be a bore, and I > rewrote the whole thing by starting with: > if isverbose: > def verbosize(text=""): > print text > else: > def verbosize(text=""): > pass > and then plastered the whole program with > verbosize("(Somewhat informative text)") > This works fine, and if I understand the way the lower reaches of Python > work, it should be faster, since I got rid of a bunch of "if"s and turned > them into "passes" (which I hope the compiler completely gets rid of. > However, defining functions based on parameters seems to be, well, strange, > if not downright C-preprocessoresque. Is there any reason _not_ to do things > this way, or, even better, is there a standard way to handle verbose program > output I'm just not aware of? I would simply write: def verbosize (string): if isverbose: print string else: pass I don't know if there is a standard way (I don't believe it). I also don't see a reason to do it your way if *you* feel fine with it. At least you have to read and write your code. And that makes only fun if the code is written in a way that you have a cozy feeling about it (I don't know how to describe it better; you must feel at home when you look at the code in your editor). Karl -- Please do *not* send copies of replies to me. I read the list From alan.gauld at blueyonder.co.uk Thu Apr 15 16:54:45 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Apr 15 16:54:10 2004 Subject: [Tutor] On New Style Classes References: <66F587DFDD46D511B65200508B6F8DD60EF88F00@nt-kalopsapp07.ntl-city.com> Message-ID: <025001c4232b$e2034ed0$6401a8c0@xp> > Well I guess that my post was superflous. Not at all, it is a valid question, I just wasn't sure what aspects you were questioning. For what its worth I don't like the syntax much either. > seem like they are needed because in the past it just seemed that you would > put the function in a module which for all intents looks like a class. That works for behaviour that doen't need an instance to work. But the classic example of class method is a counter that returns the number of instances. Thus you can tell things about the class, like whether there are more than one instance, how many there are, ask how many superclasses there are, and so on. Its also a useful place to put factory methods - that is methods which create new instances. As an example of the latter, say we want the first instance to be the master and all others to have a reference to it, we can do that by manually keeping track and passing it to the constructor, but thats hard to do in a multi-threaded application. Alternatively we can define a class method that creates instances. The first one it holds in a variable and the subsequent it passes the variable to the constructor. Or maybe we provide a class method to grab a reference to the first instance (as stored by the factory method) There are lots of applications for class methods but they tend to be quite esoteric and are not used a lot, but its nice to have them available. We already had class level attributes, so could have the init method update the instance count for example, but class methods allow a lot more sophistication. Finally remember that classes are objects too, you can pass classes around as arguments to functions etc. This really brings us into the realm of meta programming and thats a whole new topic, but there are some interesting opportunities once you pass a class object into a fuinction and allow the function to call class methods of that object! But try this for fun: class C: clsAttr = 42 def instanceMethod(self): print "I'm an instance method" def classMethod(c): print "My class attribute is", c.clsAttr f = classmethod(classMethod) class D(C): clsAttr = 57 classes = [C,D] for cls in classes: print cls.clsAttr cls.f() # call the class method try: cls.instanceMethod() # no instance! except: print 'oops no instance' obj = cls() obj.instanceMethod() obj.f() # works with instances too! del(obj) Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at blueyonder.co.uk Thu Apr 15 17:04:13 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Apr 15 17:03:32 2004 Subject: [Tutor] Parsing text file? References: <9A4B2157EFDBE546BECD68C62AC3B1C81738F0D4@es05snlnt.sandia.gov> Message-ID: <027d01c4232d$3479e240$6401a8c0@xp> > I have finished the filter program which removes the header in original > file. I now need to remove the first column of data and then convert the > second. If this is just for pratice in Python its OK. If you don't have access to unix tools (even via cygwin) its also OK, but if its a serious task then the unix cut command can do this a lot easier, or even awk... > Is parsing right for this? Yes, but there are shades of parsing... Since your data is regular spaced you can just use string slicing to extract the characters you need, or alternatively the string split() method will give you a list of the column data > books on this? There is a book by David Metz on Text Processing with Python. Its available online for free too - try searching for Metz and Text Processing Python... > My data files looks like this: > 16 > 1 1 0.00000 0.68337 0.25020 > 2 2 0.00000 0.29020 0.25020 Alan G. From Chad.Crabtree at nationalcity.com Thu Apr 15 17:24:14 2004 From: Chad.Crabtree at nationalcity.com (Crabtree, Chad) Date: Thu Apr 15 17:24:39 2004 Subject: [Tutor] On New Style Classes Message-ID: <66F587DFDD46D511B65200508B6F8DD60EF88F07@nt-kalopsapp07.ntl-city.com> I think I get it. So as an example. Say you need an object but you will only ever need on instance of it. However you don't know at design time when (if ever?) it will be instantiated. You could use a class method to check wether there is an instance already if not return a new instance. Maybe also it could help automate understanding of it's siblings? However I thought that's what static methods where. Or can static methods only be used with an instance. Well I experimented and I don't get the staticmethod thing. I see it does not need to be instataited so how is that different? I see it doesn't need self. Is this just a way of adding a dizzying array of x.x.x.x.x.something like in java? class C: clsAttr = 42 def instanceMethod(self): print "I'm an instance method" def astaticMethod(): print "I should be static" xyz=staticmethod(astaticMethod) def classMethod(c): print "My class attribute is", c.clsAttr f = classmethod(classMethod) class D(C): clsAttr = 57 classes = [C,D] for cls in classes: print cls.clsAttr cls.f() # call the class method try: cls.instanceMethod() # no instance! except: print 'oops no instance' try: print "before instantiation:\t", cls.xyz() except: print "Maybe so" obj = cls() obj.instanceMethod() obj.xyz() obj.f() # works with instances too! del(obj) 42 My class attribute is 42 oops no instance before instantiation: I should be static I'm an instance method I should be static My class attribute is 42 57 My class attribute is 57 oops no instance before instantiation: I should be static I'm an instance method I should be static My class attribute is 57 ------------------------------------------------------------------------------------------- ***National City made the following annotations ------------------------------------------------------------------------------------------- This communication is a confidential and proprietary business communication. It is intended solely for the use of the designated recipient(s). If this communication is received in error, please contact the sender and delete this communication. =========================================================================================== From mumrah1 at yahoo.com Thu Apr 15 18:38:08 2004 From: mumrah1 at yahoo.com (Moe) Date: Thu Apr 15 18:38:13 2004 Subject: [Tutor] Tutorials Message-ID: <20040415223808.44037.qmail@web14521.mail.yahoo.com> Ok, Honestly i didn't read anything that came with the win version of python(2.3 IDLE1.0). but i was reading stuff online. but now i think i've read all of the "hello world" tutorials out there. not i'm like "now what", can anyone tell me any good tutorials? or what i should do now. thnx __________________________________ Do you Yahoo!? Yahoo! Tax Center - File online by April 15th http://taxes.yahoo.com/filing.html From askoose at sandia.gov Thu Apr 15 18:44:50 2004 From: askoose at sandia.gov (Kooser, Ara S) Date: Thu Apr 15 18:45:07 2004 Subject: [Tutor] Tutorials Message-ID: <9A4B2157EFDBE546BECD68C62AC3B1C81738F0D6@es05snlnt.sandia.gov> There are many tutorials listed at python.org as well as in the threads here. -----Original Message----- From: Moe To: tutor@python.org Sent: 4/15/2004 4:38 PM Subject: [Tutor] Tutorials Ok, Honestly i didn't read anything that came with the win version of python(2.3 IDLE1.0). but i was reading stuff online. but now i think i've read all of the "hello world" tutorials out there. not i'm like "now what", can anyone tell me any good tutorials? or what i should do now. thnx __________________________________ Do you Yahoo!? Yahoo! Tax Center - File online by April 15th http://taxes.yahoo.com/filing.html _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From askoose at sandia.gov Thu Apr 15 18:52:44 2004 From: askoose at sandia.gov (Kooser, Ara S) Date: Thu Apr 15 18:52:59 2004 Subject: [Tutor] Tutorials Message-ID: <9A4B2157EFDBE546BECD68C62AC3B1C81738F0D7@es05snlnt.sandia.gov> http://www.python.org/doc/Intros.html And reading the IDLE help as you are writing is a good idea too. -----Original Message----- From: Moe To: tutor@python.org Sent: 4/15/2004 4:38 PM Subject: [Tutor] Tutorials Ok, Honestly i didn't read anything that came with the win version of python(2.3 IDLE1.0). but i was reading stuff online. but now i think i've read all of the "hello world" tutorials out there. not i'm like "now what", can anyone tell me any good tutorials? or what i should do now. thnx __________________________________ Do you Yahoo!? Yahoo! Tax Center - File online by April 15th http://taxes.yahoo.com/filing.html _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From klappnase at freenet.de Thu Apr 15 19:19:14 2004 From: klappnase at freenet.de (Michael Lange) Date: Thu Apr 15 19:20:07 2004 Subject: FW: [Tutor] deleting CR within files In-Reply-To: References: Message-ID: <20040416011914.0309f629.klappnase@freenet.de> On Thu, 15 Apr 2004 11:23:38 -0400 "David Talaga" wrote: > > -----Original Message----- > From: David Talaga [mailto:dtalaga@novodynamics.com] > Sent: Thursday, April 15, 2004 10:49 AM > To: Roger Merchberger > Subject: RE: [Tutor] deleting CR within files > > > Ok, here is what we have now: > > import os > import Tkinter > import dialog > import sys > import re > > root=Tkinter.Tk() > f=Tkinter.Button(root, text="Find Files", command=dialog.dialog).pack() > x=Tkinter.Button(root, text="Close", command=sys.exit).pack() > > sub = re.sub > fileName= dialog.dialog > in_file = open(fileName,'r') > out_file = open(fileName + '_cleaned', 'w') > for i in in_file.readlines(): > out_file.write(i[:1] + '\n') > print 'File cleaned' > in_file.close() > out_file.close() > > Tkinter.mainloop() > > Now when I run it is says this: > Traceback (most recent call last): > File "", line 1, in ? > execfile('crgui.py') > File "crgui.py", line 13, in ? > in_file = open(fileName,'r') > TypeError: coercing to Unicode: need string or buffer, function found > > > I did not know that I was using unicode up there... I am realy at a loss. > The program runs fine as far ad the dialog box coming up and the print > statement executing. I just dont know what the error is saying. Do I need a > string in place of fileName and if I do how would I go about putting a > string in there and still trying to call dialog.dialog? Any help or > direction would be greatly appreciated and also the option to take my first > born son. (Not realy, well, OK, if you realy thikn it's a fair trade...) > > David Talaga > > Hi David, what's the "dialog.dialog", a dialog box widget you wrote yourself, I guess? Maybe it works similar to a tkSimpleDialog.askstring() ? Maybe you just should call fileName= dialog.dialog() ?? Just a shot in the dark, but I think you might have a closer look at the dialog module. Michael From dbroadwell at mindspring.com Thu Apr 15 20:05:22 2004 From: dbroadwell at mindspring.com (David Broadwell) Date: Thu Apr 15 19:59:47 2004 Subject: [Tutor] Re: Network Pointers; Thank You. Message-ID: In a bit of good news, I went after sockets with the 'SocketServer' and the echo server example. By the time I was done I had individual client and server scripts and was chatting it up with a friend of mine across the net. Now I have a wort covered toy to integrate, smooth, extend and refactor! Thank you. -- Programmer's mantra; Observe, Brainstorm, Prototype, Repeat David Broadwell From garryknight at gmx.net Thu Apr 15 20:00:19 2004 From: garryknight at gmx.net (Garry Knight) Date: Thu Apr 15 20:00:29 2004 Subject: [Tutor] Re: Tutorials References: <20040415223808.44037.qmail@web14521.mail.yahoo.com> Message-ID: In message <20040415223808.44037.qmail@web14521.mail.yahoo.com>, Moe wrote: > can anyone tell me any good tutorials? There are some good ones listed here: http://www.tcfb.com/freetechbooks/bookphyton.html In particular, I recommend this one: http://www.greenteapress.com/thinkpython/ -- Garry Knight garryknight@gmx.net ICQ 126351135 Linux registered user 182025 From nmaleve at all2all.org Thu Apr 15 20:06:21 2004 From: nmaleve at all2all.org (nicolas maleve) Date: Thu Apr 15 20:06:25 2004 Subject: [Tutor] read sound file via url Message-ID: hello, I make my first steps with the snack library. I would like to make a python script to read an ogg file over the net. At the moment the only solution I could manage to get working is to save the file on disk and then read it. For larger sound file, I would prefer to read them directly via a url. Can anyone put me in the right direction? here follows my script with the locally saved version... #! /usr/bin/env python # # Usage: oggplay.py http://www.myserver.com/file.ogg # # Note: this script will also play audio files in any other format supported # by tkSnack import urllib import sys from Tkinter import * from tkSnack import * initializeSnack(Tkinter.Tk()) # Load the Ogg/Vorbis format package Tk().tk.eval('package require snackogg') if sys.argv[1:]: host=sys.argv[1] file=urllib.urlopen(host) test=file.info() print test print "reading\n" snd_net = file.read() f=open("test.ogg","wb") print "opening file for writing" f.write(snd_net) print "writing\n" f.close() print "closed\n" print "now trying to play\n" snd=Sound(file="test.ogg") snd.play(blocking=1) print "does it exit now?" else: print "Usage: oggplay.py http://www.myserver.com/file.ogg" -- * * * * * * * * * C O N S T A N T V Z W From marilyn at deliberate.com Fri Apr 16 03:14:53 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Fri Apr 16 03:14:58 2004 Subject: [Tutor] mod_python and PIL? In-Reply-To: Message-ID: Thank you, Danny, for giving this a thought. So my son upgraded me to Apache 2 and I redid everything, keeping the defaults, including threads, and it all works splendidly. I did ask on the imaging-sig and mod_python lists and someone helped me on mod_python. Thank you again. This list is wonderful. Marilyn On Wed, 14 Apr 2004, Danny Yoo wrote: > > > > Cannot load /www/libexec/mod_python.so into server: > > /www/libexec/mod_python.so: undefined symbol: pthread_sigmask > > Hi Marilyn, > > > Gaaah! Yikes. > > > > > And I'm stumped. For python2.3.3: > > > > [root@maildance mod_python-2.7.8]# cd ../Python-2.3.3 > > [root@maildance Python-2.3.3]# ./configure --with-threads=no > > > You shouldn't have to do this. The error message that you're getting > involves mod_python --- recompiling mod_python to use the new Python 2.3.3 > may have more success than recompiling Python. > > > > But this is seeming too hard. I can't help thinking that I'm doing > > something wrong from the start. > > This is mod_python specific; it's definitely a little more advanced than > most Tutor stuff... *grin* > > > > You may want to talk with the folks on the modpython mailing list. > > http://mailman.modpython.org/mailman/listinfo/mod_python > > > It appears that some other folks are running into the same exact problem > on FreeBSD too: > > http://www.modpython.org/pipermail/mod_python/2003-April/013536.html > > so whatever is going on is affecting others; don't be hard on yourself. > > > > There are actually quite a few FAQ entries on the mod_python page that may > apply to the issues you're having: > > http://www.modpython.org/FAQ/faqw.py?req=all > > > In particular, > > http://www.modpython.org/FAQ/faqw.py?req=all#4.2 > > says that mod_python versions < 3 will have compile-time issues with > Python 2.3. You're trying to install mod_python 2.7.8, so that may be a > contributing factor to the compile mischief. Try using a later version of > mod_python, like 3.1.3: > > http://mailman.modpython.org/mailman/listinfo/mod_python > > > > Also, since you have multiple versions of Python installed on your system, > you may need to explicitely tell mod_python to use the right one during > './configure': > > http://www.modpython.org/live/current/doc-html/inst-configure.html > > > > The folks on the modpython mailing list should be better equipped to > handle installation problems, so talk with them: they'll know what to do. > (I hope. *grin*) > > -- From alan.gauld at blueyonder.co.uk Fri Apr 16 03:36:10 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Apr 16 03:35:32 2004 Subject: [Tutor] Is defining functions as dummies pythonic? References: <200404152015.18118.scot@possum.in-berlin.de> Message-ID: <02a301c42385$7cbd9bc0$6401a8c0@xp> > if isverbose: > def verbosize(text=""): > print text > else: > def verbosize(text=""): > pass > > However, defining functions based on parameters seems to be, well, strange, Nope its perfectly legitimate. Its one of the things you can only do in a dynamic language like Python which is why you don't see it done very often, but its good. Alan G. From alan.gauld at blueyonder.co.uk Fri Apr 16 03:49:30 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Apr 16 03:48:44 2004 Subject: [Tutor] binary data as string? References: Message-ID: <02b001c42387$59863020$6401a8c0@xp> > When one does 'bitwise' movements over data in strings > it is actually moving 'characterwise', correct? No, characters are bytesize, bitwise means looking at the individual bits. Usually this is done by taking a byte and applying a "mask" to the byte to determine the value. For example applying a bitwise AND of 0x01 to a byte will return the rightmost bit, by "leftshifting" the mask and repeating we can see each individual bit in turn: mask = 1 data = 42 for n in range(8): print (data & mask) and 1 or 0, mask = mask << 1 Will print out the bit pattern of 42... HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From scot at possum.in-berlin.de Thu Apr 15 22:10:43 2004 From: scot at possum.in-berlin.de (Scot W. Stevenson) Date: Fri Apr 16 04:09:50 2004 Subject: [Tutor] Is defining functions as dummies pythonic? In-Reply-To: References: <200404152015.18118.scot@possum.in-berlin.de> Message-ID: <200404160410.43241.scot@possum.in-berlin.de> Hello Karl, > I would simply write: > > def verbosize (string): > if isverbose: > print string > else: > pass But doesn't that mean that every time this function is called, the program has to do the test all over again, even though I already have the information from the start? This sound hideously inefficient... Dankesch?n, Y, Scot -- Scot W. Stevenson - Panketal, Germany From alan.gauld at blueyonder.co.uk Fri Apr 16 04:11:02 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Apr 16 04:10:16 2004 Subject: [Tutor] Tutorials References: <20040415223808.44037.qmail@web14521.mail.yahoo.com> Message-ID: <02cb01c4238a$5becef90$6401a8c0@xp> > Ok, Honestly i didn't read anything that came with the > win version of python(2.3 IDLE1.0). but i was reading > stuff online. but now i think i've read all of the > "hello world" tutorials out there. not i'm like "now > what", can anyone tell me any good tutorials? Have you done the official tutorial that ships with Python? If you know the basics of programming its the logical place to go. Certainly more than "Hello World". > or what i should do now. thnx Write some programs? If you can't think of anything try looking at the Useless Python page which has a list of ideas, also lots of examples of short programs other newbies (and not so newbies) have created. HTH, Alan G. From adam at monkeez.org Fri Apr 16 06:16:34 2004 From: adam at monkeez.org (Adam) Date: Fri Apr 16 06:16:48 2004 Subject: [Tutor] Why is this write defined as a tuple, instead of picking list? Message-ID: <20040416111634.73b2eb6c@debian> I'm using this function to cycle through a list and add some formatting to it to prepare it for saving: def prepare_for_saving(article_items): """This function formats the article_items list so that it's in HTML format and looks nice""" print "article_items is type: ", type(article_items) for x in article_items: write = "

", article_items[0], "

" print "write is type: ", type(write) #write = str(article_items)#deprecated - replaced by the formatting loop return (write) At the time article_items is passed it is a list - however, when I try to do the formatting with write =, write is declared as a tuple - why is this, and how can I force it to be a string (I believe I need a string for the file saving function?) Thanks adam From mwagman at charter.net Fri Apr 16 07:33:05 2004 From: mwagman at charter.net (Mike Wagman) Date: Fri Apr 16 07:43:12 2004 Subject: [Tutor] Error Fedora Code 1 and CPickle Message-ID: <1082115185.3312.11.camel@c68.115.26.18.jvl.wi.charter.com> Hi, I'm getting an error in Cpickle using Fedora Code 1. Something about a bad unicode ASUTF8St5ring. Specifically I am using cx_freeze on code that import cPickle. I'm run into some reference to this problem before - but have not found a solution. Has anyone run into this - and if so what is the solution. Also thanks again to the list in the help getting cxfreeze up and running. From Janssen at rz.uni-frankfurt.de Fri Apr 16 09:03:00 2004 From: Janssen at rz.uni-frankfurt.de (Michael Janssen) Date: Fri Apr 16 09:03:12 2004 Subject: [Tutor] Is defining functions as dummies pythonic? In-Reply-To: <200404160410.43241.scot@possum.in-berlin.de> References: <200404152015.18118.scot@possum.in-berlin.de> <200404160410.43241.scot@possum.in-berlin.de> Message-ID: On Fri, 16 Apr 2004, Scot W. Stevenson wrote: > > I would simply write: > > > > def verbosize (string): > > if isverbose: > > print string > > else: > > pass > > But doesn't that mean that every time this function is called, the program > has to do the test all over again, even though I already have the > information from the start? This sound hideously inefficient... the test itself should be very efficient especially compared against a print operarion. Further you won't use such a function very often: it prints text and the user has a limited capacity of reading text ;-) Since it is a seldom used function you can put a lot of logic into it without the user noting. I would bet a 100 if and elses aren't enough to make a difference. That's the good thing with all this efficiency issues: in most situations it simply doesn't matter and you free to code the way it makes it best readable/ understandable for you. Nevertheless, defining functions on runtime is damned cool. regards Michael From lumbricus at gmx.net Fri Apr 16 09:03:40 2004 From: lumbricus at gmx.net (=?ISO-8859-1?Q?=22J=F6rg_W=F6lke=22?=) Date: Fri Apr 16 09:03:47 2004 Subject: [Tutor] binary data as string? References: <02b001c42387$59863020$6401a8c0@xp> Message-ID: <12322.1082120620@www43.gmx.net> Hello! [ snip ] > mask = 1 > data = 42 > for n in range(8): > print (data & mask) and 1 or 0, > mask = mask << 1 s/<>/ > Will print out the bit pattern of 42... > > HTH, > > Alan G > Author of the Learn to Program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld Greets, J"o! -- Sie duerfen diesen Satz zitieren. NEU : GMX Internet.FreeDSL Ab sofort DSL-Tarif ohne Grundgeb?hr: http://www.gmx.net/info From mwagman at charter.net Fri Apr 16 11:14:29 2004 From: mwagman at charter.net (Mike Wagman) Date: Fri Apr 16 11:20:24 2004 Subject: [Tutor] Re: [wxPython-users] Re: Error Fedora Code 1 and CPickle In-Reply-To: References: <1082115185.3312.11.camel@c68.115.26.18.jvl.wi.charter.com> Message-ID: <1082128305.3219.1.camel@c68.115.26.18.jvl.wi.charter.com> Still getting the same error. Tried upgrading the pthon and python-developers on Fedora - no help. I keep getting Failed to load PyunicodeUCS_EncodeUTF8 - even with the change. It seems to only happen with code that uses cPickle. On Fri, 2004-04-16 at 09:05, Chris Green wrote: > Mike Wagman writes: > > > I'm getting an error in Cpickle using Fedora Code 1. Something about a > > bad unicode ASUTF8St5ring. Specifically I am using cx_freeze on code > > that import cPickle. > > > > I'm run into some reference to this problem before - but have not found > > a solution. Has anyone run into this - and if so what is the > > solution. > > I think that is related to the codecs functionality. I ran into a > similar problem when trying to use 4suite + wxPython. I traced it > down to the codecs module trying to dynamically __import__ the utf-8 > charset. > > To get cx_Freeze to pick it up, I added a kludge: > > import encodings.utf_8 > > to my main module. This works well enough since utf_8 is the only > thing I support. From dtalaga at novodynamics.com Fri Apr 16 11:41:52 2004 From: dtalaga at novodynamics.com (David Talaga) Date: Fri Apr 16 11:41:40 2004 Subject: [Tutor] deleting CR within files In-Reply-To: <5.1.0.14.2.20040415131748.00ae8e28@mail.30below.com> Message-ID: Hello all, need some help again! Here is the code I have: import os import Tkinter import dialog import sys #import re root=Tkinter.Tk() f=Tkinter.Button(root, text="Find Files", command=dialog.dialog).pack() x=Tkinter.Button(root, text="Close", command=sys.exit).pack() #sub = re.sub if f: fileName= dialog.dialog() in_file = open(fileName,'r').readlines() out_file = open(fileName + '_cleaned', 'w') for i in dialog().readline: out_file.write(i[:-1] + '\n') print 'File cleaned' #in_file.close() out_file.close() print filename root.mainloop() I get no error message when I run it but I also have a test document that I tested it on and nothing happens. I did what you suggested below and I am not getting anything. I figured I would put an if statement in there to avoid the needing a string error for in_file = open(fileName,'r').readlines(). So here is where I am at. Stuck. I can not wait to be more proficient in this language! -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org]On Behalf Of Roger Merchberger Sent: Thursday, April 15, 2004 1:18 PM To: tutor@python.org Subject: RE: [Tutor] deleting CR within files Rumor has it that David Talaga may have mentioned these words: import os, Tkinter, dialog, sys # You weren't using re anymore, no need to import it root=Tkinter.Tk() f=Tkinter.Button(root, text="Find Files", command=dialog.dialog).pack() x=Tkinter.Button(root, text="Close", command=sys.exit(0)).pack() # you didn't use 'sub' anymore, so... # sub = re.sub fileName= dialog.dialog # if you call readlines() on the open, it opens, reads, and # closes all in one step, it makes readability easier... in_file = open(fileName,'r').readlines() # See my previous post about how you can put the _cleaned *before* # the extension so you can still open the files by extension... out_file = open(fileName + '_cleaned', 'w') for i in in_file: # There's a non-syntax bug in the next line: if you need to remove # the last character in the line, use -1. A negative index means: # "Go from the end of the array (in this case an array of chars) # and work backwards." # what you coded was "Take the first character of every string, # lop off the rest, and add a \n." Prolly not what you wanted. ;-) out_file.write(i[:-1] + '\n') # Remember, this is not actually searching for '\r' chars - it's only # lopping off the last character, and adding a \n. If this is in # winders, this won't work, as the standard line ending is # '\r\n' - and the code above is lopping off a \n to add a \n. # out_file.write(i[:-2] + '\n') # is what you'd want for winders. print 'File cleaned' # Python is "indent-loop" based - you'll be printing 'File cleaned' # for *every line* in the file, not only at the end of the file. # You'd wanna move that out of the loop by unindenting it. # Next line not necessary if you readlines() with the open... # in_file.close() out_file.close() # I haven't done a lot of Tk programming, but shouldn't the next # line be: root.mainloop() # instead of Tkinter.mainloop? =-=-=-= My (so far one and only) main Tkinter script I wrote is here: http://tivo.30below.com/zmerch/AviSynth_2.pyw It's been tested on Python 2.2.2 and 2.3.x - and it's for a winders platform... [snip] >Now when I run it is says this: >Traceback (most recent call last): > File "", line 1, in ? > execfile('crgui.py') > File "crgui.py", line 13, in ? > in_file = open(fileName,'r') >TypeError: coercing to Unicode: need string or buffer, function found For this error, what I'd do is right before this line, put in this: =-=-=-=-= print fileName sys.exit(0) =-=-=-=-= If what prints looks like: u'ThisIsUnicode.txt' ^^ starting with a U, then the dialog.dialog script is returning a unicode string instead of standard ASCII string, which is what's necessary to open files. Try this line instead: fileName= str(dialog.dialog) That may convert the unicode to standard ASCII. HTH, Roger "Merch" Merchberger -- Roger "Merch" Merchberger -- sysadmin, Iceberg Computers zmerch@30below.com What do you do when Life gives you lemons, and you don't *like* lemonade????????????? _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040416/d85296db/attachment.html From cmg at dok.org Fri Apr 16 10:05:06 2004 From: cmg at dok.org (Chris Green) Date: Fri Apr 16 12:10:27 2004 Subject: [Tutor] Re: Error Fedora Code 1 and CPickle References: <1082115185.3312.11.camel@c68.115.26.18.jvl.wi.charter.com> Message-ID: Mike Wagman writes: > I'm getting an error in Cpickle using Fedora Code 1. Something about a > bad unicode ASUTF8St5ring. Specifically I am using cx_freeze on code > that import cPickle. > > I'm run into some reference to this problem before - but have not found > a solution. Has anyone run into this - and if so what is the > solution. I think that is related to the codecs functionality. I ran into a similar problem when trying to use 4suite + wxPython. I traced it down to the codecs module trying to dynamically __import__ the utf-8 charset. To get cx_Freeze to pick it up, I added a kludge: import encodings.utf_8 to my main module. This works well enough since utf_8 is the only thing I support. -- Chris Green Chicken's thinkin' From project5 at redrival.net Fri Apr 16 12:54:50 2004 From: project5 at redrival.net (Andrei) Date: Fri Apr 16 12:55:00 2004 Subject: [Tutor] Re: Re: Advice needed on first project References: <407EBD15.4030308@monkeez.org> <407EE389.7020303@monkeez.org> Message-ID: Adam wrote on Thursday 15 April 2004 21:33: > Andrei wrote: > I thought so - this is a very intuitive language to pick up (well, at > least for me it is). This will be adopted. I rather like it too :). >> - don't use tabs. The preferred way of writing Python code is by using 4 >> spaces per indentation level. This is what you do in create_new_articles, >> but you use tabs in menu. If you now try to copy-paste code from the one >> to the other in order to avoid the mini-modules, you'll get some errors I >> think. > I think I already experienced some problems with the tabs already. I > started off using jedit (please don't start a discussion about merits of > text editors!) and then gave pyalamode a go - it seemed to report > errors with the indentation. I imagine that if I use one editor > consistently, it will prevent this. It's not a matter of which editor you prefer, because every decent general-purpose editor I've seen allows you to specify the indentation settings I mentioned above. It's possible that special-purpose Python editors will lock you in 4 space-style, but that's a good thing. I don't know what PyAlaMode uses for settings, but I'll bet a versatile editor like Jedit allows you to configure it. I prefer SciTE for Python editing nowadays, though I do use more special-purpose editors like Boa and Spe when I want a class browser or a debugger. >> - always assume your users are stupid - I do that even if I only code for >> myself :). What happens if your user answers "n" or 'new' in the menu or >> accidentally types a space before or after the 'n'? He's told the choice >> is invalid. Case sensitive menus are not a very good idea. That's why it >> makes sense to clean up the response a bit: > This kind of feature is coming and it seems very easy to implement, but > I bet that it is quite difficult to do well (ie. taking into account all > eventualities of user input). Of course you can't easily account for everything (like someone typing 'nyesyesyesYESYES!!' and getting recognized as no), but that's not the point of the exercise :). The purpose is just to prevent common mistakes not being handled (uppercase sensitivity in a menu is highly unintuitive for example). -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From alan.gauld at blueyonder.co.uk Fri Apr 16 13:47:30 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Apr 16 13:46:39 2004 Subject: [Tutor] Is defining functions as dummies pythonic? References: <200404152015.18118.scot@possum.in-berlin.de> <200404160410.43241.scot@possum.in-berlin.de> Message-ID: <02fb01c423da$e3e95960$6401a8c0@xp> >> def verbosize (string): >> if isverbose: >> print string >> else: >> pass > > But doesn't that mean that every time this function is called, the program > has to do the test all over again, even though I already have the > information from the start? This sound hideously inefficient... Not hideously inefficient - the function call is more expensive than the test. But it is less efficient than your conditional function defintion. Alan G From dtalaga at novodynamics.com Fri Apr 16 14:00:00 2004 From: dtalaga at novodynamics.com (David Talaga) Date: Fri Apr 16 13:59:44 2004 Subject: FW: [Tutor] deleting CR within files In-Reply-To: <20040416011914.0309f629.klappnase@freenet.de> Message-ID: Here is the whole thing. See what you can do? I am stuck and sitting here looking at it doesn't help my situation... #This is the dialog.py module: from Tkinter import * import tkFileDialog import sys def dialog(fileName): top = Tk() top.withdraw() initDir = 'C:/windows/desktop' filetype = [('All files', '.*')] fileName = tkFileDialog.askopenfilename(initialdir=initDir, filetypes=filetype) return fileName And here is the crgui.py module: import os import Tkinter import sys import dialog root=Tkinter.Tk() f=Tkinter.Button(root, text="Find Files", command=dialog.dialog).pack() x=Tkinter.Button(root, text="Close", command=sys.exit).pack() if f: in_file = open(fileName,'r').readlines() out_file = open(fileName + '_cleaned', 'w') for i in dialog().readline: out_file.write(i[:-1] + '\n') print 'File cleaned' out_file.close() print filename root.mainloop() The dialog function is not returning the information I believe. I think this is where my problem lies. I am not able to access the text i am trying to access because I believe that for some reason I am not getting the actual file, just a printed version of it. David Talaga -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org]On Behalf Of Michael Lange Sent: Thursday, April 15, 2004 7:19 PM To: tutor@python.org Subject: Re: FW: [Tutor] deleting CR within files On Thu, 15 Apr 2004 11:23:38 -0400 "David Talaga" wrote: > > -----Original Message----- > From: David Talaga [mailto:dtalaga@novodynamics.com] > Sent: Thursday, April 15, 2004 10:49 AM > To: Roger Merchberger > Subject: RE: [Tutor] deleting CR within files > > > Ok, here is what we have now: > > import os > import Tkinter > import dialog > import sys > import re > > root=Tkinter.Tk() > f=Tkinter.Button(root, text="Find Files", command=dialog.dialog).pack() > x=Tkinter.Button(root, text="Close", command=sys.exit).pack() > > sub = re.sub > fileName= dialog.dialog > in_file = open(fileName,'r') > out_file = open(fileName + '_cleaned', 'w') > for i in in_file.readlines(): > out_file.write(i[:1] + '\n') > print 'File cleaned' > in_file.close() > out_file.close() > > Tkinter.mainloop() > > Now when I run it is says this: > Traceback (most recent call last): > File "", line 1, in ? > execfile('crgui.py') > File "crgui.py", line 13, in ? > in_file = open(fileName,'r') > TypeError: coercing to Unicode: need string or buffer, function found > > > I did not know that I was using unicode up there... I am realy at a loss. > The program runs fine as far ad the dialog box coming up and the print > statement executing. I just dont know what the error is saying. Do I need a > string in place of fileName and if I do how would I go about putting a > string in there and still trying to call dialog.dialog? Any help or > direction would be greatly appreciated and also the option to take my first > born son. (Not realy, well, OK, if you realy thikn it's a fair trade...) > > David Talaga > > Hi David, what's the "dialog.dialog", a dialog box widget you wrote yourself, I guess? Maybe it works similar to a tkSimpleDialog.askstring() ? Maybe you just should call fileName= dialog.dialog() ?? Just a shot in the dark, but I think you might have a closer look at the dialog module. Michael _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040416/6e9535f3/attachment.html From dyoo at hkn.eecs.berkeley.edu Fri Apr 16 14:05:19 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Apr 16 14:05:27 2004 Subject: [Tutor] Reading multiple text files and writing data on one file (fwd) Message-ID: [Forwarding to Tutor] ---------- Forwarded message ---------- Date: Thu, 15 Apr 2004 16:46:11 +0000 From: ABDUL JABBAR SIDDIQUE To: dyoo@hkn.eecs.berkeley.edu Subject: Re: [Tutor] Reading multiple text files and writing data on one file Danny Yoo, thnx for your reply. yes the following code works for one file. ### def process(inp, outp): i=0 for line in inp: i=i+1 if i > 5 and i <= 76: outp.write((line[:12]+line[88:96])+"\n") inp = open("S_1.OUT","r") outp1 = open ("O_1.csv","w") process(inp, outp1) print "1 file copied..." # Now close the files inp.close() outp1.close() ### However, I want to add columns 3,4,5,6,.... 11 in my output file ("O_1.csv"): outp.write((line[:12]+line[88:96])+....+......+.......+"\n") from files "S_2.OUT","S_3.OUT"......"S_10.OUT". The data to be caprtured from "S_2,S_3, .... S_10.OUT" files lies in the same column (say column 8) in all the .OUT files. I will highly appreciate your reply. Thnx A. jabbar siddique __________________________________________________________________________________ The new MSN 8: smart spam protection and 2 months FREE* From project5 at redrival.net Fri Apr 16 14:07:07 2004 From: project5 at redrival.net (Andrei) Date: Fri Apr 16 14:07:15 2004 Subject: [Tutor] Re: Tutorials References: <20040415223808.44037.qmail@web14521.mail.yahoo.com> Message-ID: Moe wrote on Friday 16 April 2004 00:38: > what", can anyone tell me any good tutorials? or what > i should do now. thnx Write apps of course. I don't know if you mean you really only know >>> print "Hello world" or that you just know basics (e.g. the Python language without the OOP part). If you do know about the basics, you can already write simple applications (and even complex ones if you're stubborn enough :)). I don't know what your interests are, but simple things that you can do are e.g. number-guessing games, id3 tag manipulation, fetching stuff from the web periodically (and extracting data from the downloaded html), programs which perform physics calculations ( Once you feel you have a decent grasp on the basics (meaning that you don't have to look up syntax for e.g. list slicing, aren't surprised that this happens: >>> a = [5]; b = a; b.append(6); print a [5, 6] you can move on to more complex stuff. -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From alan.gauld at blueyonder.co.uk Fri Apr 16 14:09:50 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Apr 16 14:08:56 2004 Subject: [Tutor] binary data as string? References: <02b001c42387$59863020$6401a8c0@xp> <12322.1082120620@www43.gmx.net> Message-ID: <030601c423de$02b51430$6401a8c0@xp> > > mask = 1 > > data = 42 > > for n in range(8): > > print (data & mask) and 1 or 0, > > mask = mask << 1 > > s/<>/ > > > Will print out the bit pattern of 42... Actually no, that'll drop the 1 off the end and only print the first bit accurately. However mine wasn't much better since it prints the bits in reverse order! Lets fix both errors: mask = 128 # = 1000000 data = 42 for n in range(8): print (data & mask) and 1 or 0, mask = mask >> 1 Should do it properly... :-) Alan G. From alan.gauld at blueyonder.co.uk Fri Apr 16 14:16:54 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Apr 16 14:16:00 2004 Subject: [Tutor] deleting CR within files References: Message-ID: <030e01c423de$ff58d460$6401a8c0@xp> > root=Tkinter.Tk() > f=Tkinter.Button(root, text="Find Files", command=dialog.dialog).pack() > x=Tkinter.Button(root, text="Close", command=sys.exit).pack() Like another recent poster you are assigning the value of pack() to the variables. But pack returns None. In this case you don't use f or x so it doesn't matter but could lead to some strange things if you tried to use them later... > if f: Oops, sorry, you do use f, it will be false since pack() returns none wich is considered as false. As a result the block of code inside the if never gets executed. You need to define the widget then pack it: f=Tkinter.Button(root, text="Find Files", command=dialog.dialog) f.pack() The other problem is that oits not clear how you rtrieve the output from dialog.dialog. I suspect you need to wrap that in a local function that stores the value for you: result = 0 def doDialog() global result result = dialog.dialog() Now pass doDialog into the command parameter and when the button is pressed the result will be stored in the global variable result. [ If you were using objects you would make the doDialog a method and store the result in an attribute of the class to avoid using a global variable...] HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From project5 at redrival.net Fri Apr 16 14:22:37 2004 From: project5 at redrival.net (Andrei) Date: Fri Apr 16 14:22:45 2004 Subject: [Tutor] Re: Why is this write defined as a tuple, instead of picking list? References: <20040416111634.73b2eb6c@debian> Message-ID: Adam wrote on Friday 16 April 2004 12:16: > I'm using this function to cycle through a list and add some > formatting to it to prepare it for saving: > for x in article_items: > write = "

", article_items[0], "

" > print "write is type: ", type(write) > At the time article_items is passed it is a list - however, > when I try to do the formatting with write =, write is > declared as a tuple - why is this, and how can I force it to > be a string (I believe I need a string for the file saving > function?) The relevant line looks like this: write = "a", "b", "c' This happens to be syntax for tuples, meaning that write becomes a tuple. If you want to concatenate strings, you should use "+": write = "a" + "b" + "c" It is generally not recommended to use this, because it's slow. It's better to have a list of substrings like this: write = ["a", "b", "c"] and then use the string method join() to convert that list into a string when you really need it to be a string (e.g. before writing to a file): strwrite = "".join(write) Have a good look at this syntax, many (or even most) people find it counter-intuitive at first. "" is the separator char that will be inserted between the string parts in the list. In this case it's an empty string, but you could also use "\n" (newline) for example to make each of the substrings appear on a new line in the concatenated string. In this particular (partial) case, I'd even recommend string formatting: write = "

%s

" % article_items[0] But if you plan to add more content to the HTML page, the solution with a list which is joined at a later point in time is the best one. Btw, I don't understand this logic: > for x in article_items: > write = "

", article_items[0], "

" Why are you writing the same header for every item in the list? -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From dyoo at hkn.eecs.berkeley.edu Fri Apr 16 14:27:48 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Apr 16 14:27:52 2004 Subject: [Tutor] Why is this write defined as a tuple, instead of picking list? In-Reply-To: <20040416111634.73b2eb6c@debian> Message-ID: On Fri, 16 Apr 2004, Adam wrote: > def prepare_for_saving(article_items): > """This function formats the article_items list > so that it's in HTML format and looks nice""" > print "article_items is type: ", type(article_items) > for x in article_items: > write = "

", article_items[0], "

" > print "write is type: ", type(write) > #write = str(article_items)#deprecated - replaced by the > formatting loop return (write) > > when I try to do the formatting with write =, write is > declared as a tuple - why is this, and how can I force it to > be a string Hi Adam, Let's take a closer look at how 'write' is being defined: write = "

", article_items[0], "

" This is defining a tuple of three elements ('

', article_items[0], '

') and that's why we're getting a tuple. What you probably want, instead, is a concatenation of the three strings. One way to do concatenation is by using the '+' operator: write = '

' + article_items[0] + '

' By doing this, 'write' should have all three strings glued together. See: http://www.python.org/doc/tut/node5.html#SECTION005120000000000000000 for more information on string manipulation. Hope this helps! From dyoo at hkn.eecs.berkeley.edu Fri Apr 16 14:38:17 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Apr 16 14:38:24 2004 Subject: [Tutor] Is defining functions as dummies pythonic? In-Reply-To: <200404152015.18118.scot@possum.in-berlin.de> Message-ID: > I'm writing a program where I let the user use a "-v" option to decide > if he wants the output to be verbose. At the beginning, I was putting > lots of lines such as: > > if isverbose: > print "(Somewhat informative text)" > > where "isverbose" is a bool. After a while, this got to be a bore, and I > rewrote the whole thing by starting with: > > if isverbose: > def verbosize(text=""): > print text > else: > def verbosize(text=""): > pass [some text cut] Hi Scot, You might want to look at the 'logging' module: http://www.python.org/doc/lib/module-logging.html It's designed to handle several levels of verbosity, and is quite nice. Good luck! From dyoo at hkn.eecs.berkeley.edu Fri Apr 16 14:42:11 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Apr 16 14:42:21 2004 Subject: [Tutor] Parsing text file? [Text Processing in Python] In-Reply-To: <9A4B2157EFDBE546BECD68C62AC3B1C81738F0D4@es05snlnt.sandia.gov> Message-ID: On Thu, 15 Apr 2004, Kooser, Ara S wrote: > I have finished the filter program which removes the header in > original file. I now need to remove the first column of data and then > convert the second. Is parsing right for this? Are there good websites > for me to read or books on this? I am trying to write as much of my own > code as possible and ask questions. ;) Thanks. This is on Python 2.3.3. Hi Ara, Actually, there is! *grin* David Mertz has written a book on Text Processing in Python: http://gnosis.cx/TPiP/ and he's graciously put his book online. His book has a 'functional' slant, so it's also an introduction to practical functional programming. Hope this helps! From adam at monkeez.org Fri Apr 16 15:04:00 2004 From: adam at monkeez.org (Adam) Date: Fri Apr 16 15:04:00 2004 Subject: [Tutor] Re: Why is this write defined as a tuple, instead of picking list? In-Reply-To: References: <20040416111634.73b2eb6c@debian> Message-ID: <20040416200400.44b567fd@debian> On Fri, 16 Apr 2004 20:22:37 +0200 Andrei wrote: > Adam wrote on Friday 16 April 2004 12:16: > > > I'm using this function to cycle through a list and add > > some formatting to it to prepare it for saving: > > > for x in article_items: > > write = "

", article_items[0], "

" > > print "write is type: ", type(write) > > > At the time article_items is passed it is a list - > > however, when I try to do the formatting with write =, > > write is declared as a tuple - why is this, and how can > > I force it to be a string (I believe I need a string for > > the file saving function?) > > The relevant line looks like this: > > write = "a", "b", "c' > > This happens to be syntax for tuples, meaning that write > becomes a tuple. If you want to concatenate strings, you > should use "+": > > write = "a" + "b" + "c" > > It is generally not recommended to use this, because it's > slow. It's better to have a list of substrings like this: > > write = ["a", "b", "c"] This is very obvious now - thanks to you and to Danny. My experience of previous programming (a little java) is that problems are often difficult to find, but here it seems that they are very obvious. > and then use the string method join() to convert that list > into a string when you really need it to be a string (e.g. > before writing to a file): > > strwrite = "".join(write) > > Have a good look at this syntax, many (or even most) > people find it counter-intuitive at first. "" is the > separator char that will be inserted between the string > parts in the list. In this case it's an empty string, but > you could also use "\n" (newline) for example to make each > of the substrings appear on a new line in the concatenated > string. > > In this particular (partial) case, I'd even recommend > string formatting: > > write = "

%s

" % article_items[0] > > But if you plan to add more content to the HTML page, the > solution with a list which is joined at a later point in > time is the best one. I did look at the join to do this, and I agree that it is by far a better way of doing it. > > Btw, I don't understand this logic: > > > for x in article_items: > > write = "

", article_items[0], "

" > > Why are you writing the same header for every item in the > list? I'm not giving the same header - these are just variables that were collected earlier in the application and then are to be saved to disk as a HTML document. A sort of mini content management system for me to keep notes on articles that I read. The next part of the code will be something like: write = "

", article_items[0], "

", "

", article_item(1), "

" ... and so on with the data. I often find that I spend ages looking for an article, and keeping some kind of electronic record of what I read is an ideal way for me to search through them all. I thought python might be useful for this very task. And it is definitely turning out to be! If anyone wants this code once it's finished, I'll be happy to share it under GPL. > Yours, > > Andrei Thanks again Andrei. adam From nouda at freemail.nl Fri Apr 16 15:56:51 2004 From: nouda at freemail.nl (nouda) Date: Fri Apr 16 15:54:08 2004 Subject: [Tutor] compile a python program to .exe Message-ID: Hello, First I want to thank all folks who gave me some advice about tutorials. So: Thank you Folks! Second: I've a question. I want to compile a program, scripted in python, to a .exe program. This could be done with a compiler. But I don't know which one and I don't know how. I read some info about compilers on python.org, but I didn't quite understand it. Could someone help me? Thank you, and I hope my English is readable. Bye, Noud Aldenhoven From nouda at freemail.nl Fri Apr 16 16:01:32 2004 From: nouda at freemail.nl (nouda) Date: Fri Apr 16 15:58:51 2004 Subject: [Tutor] Making a database Message-ID: Hello again. I want to make, to become better in programming, a simple Database. This Database can save texts, titles and dates. If it saves a text (with title and date) it can be read again and it will be saved into a .txt file. Are there any tutorials on Internet which explain some more about databases and how to make them? Thank you, Noud Aldenhoven From pythontut at pusspaws.net Fri Apr 16 17:19:08 2004 From: pythontut at pusspaws.net (Dave S) Date: Fri Apr 16 16:24:55 2004 Subject: [Tutor] Stripping HTML tags. Message-ID: <40804DCC.9040007@pusspaws.net> Hello, I need to strip HTML tags from a string called "stockdata". I have come up with ... import re ..... # Hack out the HTML tags to save room on the drive rematch=re.compile('<[^>]*>') stockdata=rematch.sub('',stockdata) .... It works but seems a bit messy. Is there a neater way to do this ? Dave From Simonjthecat at aol.com Fri Apr 16 16:50:19 2004 From: Simonjthecat at aol.com (Simonjthecat@aol.com) Date: Fri Apr 16 16:50:28 2004 Subject: [Tutor] Python open source Message-ID: <109.2f5749f7.2db1a10b@aol.com> I'm new to python and to programming period. I've gone through tons of beginner tutorials, but I'm having trouble figuring out how to put a complete program together. So what I'm looking for is some kind of simple python code to look at to get me started. All the open source stuff that I've found is either too big to figure out what's going on or incomplete so I don't know if what I'm looking at is correct coding or not... So does anybody know of a website(s) that have some simple programs to check out? Simon the Cat -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040416/c11fe967/attachment.html From adam at monkeez.org Fri Apr 16 16:51:08 2004 From: adam at monkeez.org (Adam) Date: Fri Apr 16 16:52:03 2004 Subject: [Tutor] compile a python program to .exe In-Reply-To: References: Message-ID: <4080473C.5040501@monkeez.org> nouda wrote: > Hello, > > First I want to thank all folks who gave me some advice about tutorials. > So: > > Thank you Folks! > > Second: > > I've a question. I want to compile a program, scripted in python, to a > .exe program. This could be done with a compiler. But I don't know which > one and I don't know how. I read some info about compilers on > python.org, but I didn't quite understand it. Could someone help me? > > Thank you, and I hope my English is readable. > > Bye, > > Noud Aldenhoven > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor My answer will not be as anywhere near as comprehensive as others' but have a search for py2exe - I managed to get an exe in a couple of minutes - it is quite easy to use. There may be hidden disadvantages to using this, that others might be able to point out. HTH adam From alan.gauld at blueyonder.co.uk Fri Apr 16 17:21:24 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Apr 16 17:20:33 2004 Subject: FW: [Tutor] deleting CR within files References: Message-ID: <033b01c423f8$c56fda40$6401a8c0@xp> > from Tkinter import * > import tkFileDialog > import sys > def dialog(fileName): > top = Tk() > top.withdraw() I'm not sure what this does, I don't think you need it. But I may be wrong, it certainly should do any harm... > initDir = 'C:/windows/desktop' > filetype = [('All files', '.*')] > fileName = tkFileDialog.askopenfilename(initialdir=initDir, > filetypes=filetype) > return fileName OK, as suspected you return the filename but the code in the main program doesn't pick it up. > And here is the crgui.py module: > > import os > import Tkinter > import sys > import dialog > > root=Tkinter.Tk() > f=Tkinter.Button(root, text="Find Files", command=dialog.dialog) f.pack() > x=Tkinter.Button(root, text="Close", command=sys.exit) x.pack() > > if f: > in_file = open(fileName,'r').readlines() > out_file = open(fileName + '_cleaned', 'w') > for i in dialog().readline: dialog is a module not a function. you need to call dialog.dialog() And even then it returns a finlename not a file so you can't call readlines. In fact given you have already opened a file for reading I'm not sure why you are doing this at all? Assuming you want to ignore your opriginal in_file You need something like: infile = file(dialog.dialog()) for line in infile: # in v2.3 readlines is no longer needed out_file.write(line[:-1] + '\n') Which strips the last character from every line and replaces it with a newline character. You could do pretty much the same with the strip method: out_file.write(line.strip() + '\n') > print 'File cleaned' > out_file.close() > print filename > > root.mainloop() > > The dialog function is not returning the information I believe. I think > this is where my problem lies. dialog() probably is returning the filename but a filename is not a file. Unfortunately you were calling the module not the function. BTW Why do you create the Tkinter buttons? You never use them... I suspect what you really want to do is create a local function with the stuff inside the if block. Then pass that to the button. Then when somebody clicks the button your function gets called and you pop up the dialog, read the filename and process the file. Like this(warning untested code!): def cleanFile(): filename = dialog.dialog() if filename: try: inFile = file(filename) outFile = file(filename+'_cleaned','w') for line in inFile: out_file.write(line.strip() + '\n') inFile.close() outFile.close() except IOError: print "Couldn't open file" # could use warning dialog... Tkinter.Button(..... command=cleanFile) I think thats what you are trying to do? Alan G. From garryknight at gmx.net Fri Apr 16 17:43:22 2004 From: garryknight at gmx.net (Garry Knight) Date: Fri Apr 16 17:43:29 2004 Subject: [Tutor] Re: Python open source References: <109.2f5749f7.2db1a10b@aol.com> Message-ID: In message <109.2f5749f7.2db1a10b@aol.com>, Simonjthecat@aol.com wrote: > does anybody know of a website(s) that have some simple programs > to check out? Lots of source code here: http://www.vex.net/parnassus/ Smaller stuff here: http://www.uselesspython.com/ -- Garry Knight garryknight@gmx.net ICQ 126351135 Linux registered user 182025 From alan.gauld at blueyonder.co.uk Fri Apr 16 18:07:17 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Apr 16 18:06:20 2004 Subject: [Tutor] Re: Why is this write defined as a tuple, instead of picking list? References: <20040416111634.73b2eb6c@debian> Message-ID: <036001c423ff$2e8669d0$6401a8c0@xp> > The relevant line looks like this: > > write = "a", "b", "c' > > This happens to be syntax for tuples, meaning that write becomes a tuple. If > you want to concatenate strings, you should use "+": > > write = "a" + "b" + "c" > > It is generally not recommended to use this, because it's slow. It's better > to have a list of substrings like this: > > write = ["a", "b", "c"] > > and then use the string method join() to convert that list into a string Or even use a format operator with the tuple: write = "%s%s%s" % ("a", "b", "c') > In this particular (partial) case, I'd even recommend string formatting: > > write = "

%s

" % article_items[0] Yes in this case hard coding the

makes even more sense! And formatting is pretty fast coz it happens in C. Alan G. From alan.gauld at blueyonder.co.uk Fri Apr 16 18:10:21 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Apr 16 18:09:22 2004 Subject: [Tutor] Re: Why is this write defined as a tuple, instead ofpicking list? References: <20040416111634.73b2eb6c@debian> <20040416200400.44b567fd@debian> Message-ID: <036b01c423ff$9c0e9310$6401a8c0@xp> > > > for x in article_items: > > > write = "

", article_items[0], "

" > > > > Why are you writing the same header for every item in the > > list? > > I'm not giving the same header ... Yes you are, you never change article_items. I assume you meant to write x[0] instead? Alan G. From alan.gauld at blueyonder.co.uk Fri Apr 16 18:16:11 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Apr 16 18:15:28 2004 Subject: [Tutor] compile a python program to .exe References: Message-ID: <037001c42400$6d03ebf0$6401a8c0@xp> > I've a question. I want to compile a program, scripted in python, to a .exe > program. This could be done with a compiler. OK, First I start with my usual caveat. While this is possible its not necessarily a good thing, it won't bring major performance boosts for example, it is only really useful for distributing programs to those without Python installed. And you might be better installing Python and distributing the .pyc files instead. Subsequent installs will be smaller since the exe basically is a combination of the Python interpreter, all the modules you need plus your code boiled into a single largish file. OK, Now assuming that you've considered that and still feel you need to have a .exe file look at py2exe and Gordon McMillan's installer. The former is reportedly easiest to use, while the latter is more powerful (more options). HTH, Alan G. From alan.gauld at blueyonder.co.uk Fri Apr 16 18:20:29 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Apr 16 18:19:29 2004 Subject: [Tutor] Making a database References: Message-ID: <037501c42401$064551f0$6401a8c0@xp> > I want to make, to become better in programming, a simple Database. > This Database can save texts, titles and dates. If it saves a text (with > title and date) it can be read again and it will be saved into a .txt file. > > Are there any tutorials on Internet which explain some more about databases > and how to make them? The easiest way to do this in Python is use the shelve module - which looks a lot like a dictionary - to store the data in a file. Or you can go for a full blown SQL database (several freebies on the web) and use Pythons DBI modules to access it. But you need to learn SQL first to do that! Alternatively you can take the hard road and just write some custom code to write your data to a file and another function to read it back. Maybe another function to search for a single record etc... All good experience but ultimately unlikely to be any better than the pre-written modules mebntioned above. I'd go with shelve! Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at blueyonder.co.uk Fri Apr 16 18:22:22 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Apr 16 18:21:24 2004 Subject: [Tutor] Stripping HTML tags. References: <40804DCC.9040007@pusspaws.net> Message-ID: <037a01c42401$4a067180$6401a8c0@xp> > It works but seems a bit messy. Is there a neater way to do this ? Yes use the html parser module. There is some sample code that shows how to strip all tags to get plain text from an html file. And your code is less reliable(tags spanning lines, nested tags etc) than the html parser code... Alan G. From alan.gauld at blueyonder.co.uk Fri Apr 16 18:24:38 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Apr 16 18:23:40 2004 Subject: [Tutor] Python open source References: <109.2f5749f7.2db1a10b@aol.com> Message-ID: <038201c42401$9ab70770$6401a8c0@xp> > I'm new to python and to programming period. I've gone through tons of > beginner tutorials, but I'm having trouble figuring out how to put a complete > program together. If you went through mine you should have noticed that it finishes with a full program case study... > I'm looking at is correct coding or not... So does anybody know of a > website(s) that have some simple programs to check out? Useless Python website has lots of small programs, some truly are useless (in the sense of not being useful) others not quite so much. But they all illustrate some features of Python and are complete programs. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From pythontut at pusspaws.net Fri Apr 16 19:28:55 2004 From: pythontut at pusspaws.net (Dave S) Date: Fri Apr 16 18:28:48 2004 Subject: [Tutor] Stripping HTML tags. In-Reply-To: <037a01c42401$4a067180$6401a8c0@xp> References: <40804DCC.9040007@pusspaws.net> <037a01c42401$4a067180$6401a8c0@xp> Message-ID: <40806C37.9080807@pusspaws.net> Alan Gauld wrote: >>It works but seems a bit messy. Is there a neater way to do this ? >> >> > >Yes use the html parser module. There is some sample code that shows >how >to strip all tags to get plain text from an html file. And your >code is less reliable(tags spanning lines, nested tags etc) than >the html parser code... > >Alan G. > > > Thanks for that ... I looked at that module but did not think it could do what I wanted. I will take another look :-) Dave From orbitz at ezabel.com Fri Apr 16 18:30:11 2004 From: orbitz at ezabel.com (orbitz@ezabel.com) Date: Fri Apr 16 18:30:33 2004 Subject: [Tutor] Making a database In-Reply-To: References: Message-ID: <20040416183011.14f19edc.orbitz@ezabel.com> I wouldn't suggest such a thing in python Noud. There are already plenty of databases out there. I'd suggest taking a peak at berkely db (python comes with an api to use it I beleive). To become a better programmer I think doing a problem that possibly uses a premade database might be a better idea. Beyond simple table like database, making one is actually rather complex and takes a lot of math knowledge to implement correctly. On Fri, 16 Apr 2004 22:01:32 +0200 "nouda" wrote: > Hello again. > > I want to make, to become better in programming, a simple Database. > This Database can save texts, titles and dates. If it saves a text (with > title and date) it can be read again and it will be saved into a .txt file. > > Are there any tutorials on Internet which explain some more about databases > and how to make them? > > Thank you, > > Noud Aldenhoven > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From lumbricus at gmx.net Fri Apr 16 18:53:03 2004 From: lumbricus at gmx.net (=?ISO-8859-1?Q?=22J=F6rg_W=F6lke=22?=) Date: Fri Apr 16 18:53:09 2004 Subject: [Tutor] binary data as string? References: <030601c423de$02b51430$6401a8c0@xp> Message-ID: <16971.1082155983@www53.gmx.net> > > > for n in range(8): > > > print (data & mask) and 1 or 0, > > > mask = mask << 1 > > s/<>/ > > > > > Will print out the bit pattern of 42... > > Actually no, that'll drop the 1 off the end and > only print the first bit accurately. silly me - I didn`t see that you where shifting mask not data! > the bits in reverse order! Why not shift data and reverse the result? That seemed to be the more general approach to me. > > mask = 128 # = 1000000 If it is guarateed, that the Data unit is 8 bits. > Should do it properly... > > :-) > > Alan G. Greetings, J"o! -- Sie duerfen diesen Satz zitieren. NEU : GMX Internet.FreeDSL Ab sofort DSL-Tarif ohne Grundgeb?hr: http://www.gmx.net/info From dyoo at hkn.eecs.berkeley.edu Fri Apr 16 19:27:02 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Apr 16 19:27:07 2004 Subject: [Tutor] Stripping HTML tags. In-Reply-To: <037a01c42401$4a067180$6401a8c0@xp> Message-ID: On Fri, 16 Apr 2004, Alan Gauld wrote: > > It works but seems a bit messy. Is there a neater way to do this ? > > Yes use the html parser module. There is some sample code that shows how > to strip all tags to get plain text from an html file. And your code is > less reliable(tags spanning lines, nested tags etc) than the html parser > code... Hi Dave, Here's a concrete (but still far-fetched) example of why this sort of stuff is hard to get right the first time: """

testing

This is a te

st.

""" The regular expression: ### rematch=re.compile('<[^>]*>') ### won't account for attribute values, so the example above can trick it. Regex parsing of HTML can be slightly subtle, so it might be worth it to invest some time with HTMLParser: http://www.python.org/doc/lib/module-HTMLParser.html Good luck! From jsidiqi at hotmail.com Fri Apr 16 20:39:48 2004 From: jsidiqi at hotmail.com (ABDUL JABBAR SIDDIQUE) Date: Fri Apr 16 20:39:55 2004 Subject: [Tutor] csv files Message-ID: An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040417/3a76f036/attachment-0001.html From project5 at redrival.net Fri Apr 16 20:46:24 2004 From: project5 at redrival.net (Andrei) Date: Fri Apr 16 20:46:31 2004 Subject: [Tutor] Re: Stripping HTML tags. References: <40804DCC.9040007@pusspaws.net> <037a01c42401$4a067180$6401a8c0@xp> <40806C37.9080807@pusspaws.net> Message-ID: Dave S wrote on Saturday 17 April 2004 01:28: > Alan Gauld wrote: > >>>It works but seems a bit messy. Is there a neater way to do this ? >> >>Yes use the html parser module. There is some sample code that shows >>how >>to strip all tags to get plain text from an html file. And your >>code is less reliable(tags spanning lines, nested tags etc) than >>the html parser code... > Thanks for that ... I looked at that module but did not think it could > do what I wanted. > I will take another look :-) I think it (the SGML parser might be even easier in this case as you don't care about the tags) would do the job just fine. Manual parsing means you'll have to perform quite a lot of debugging to catch special cases, as Danny and Alan mentioned before me. I've tried parsing HTML with regexes too (for a different purpose though) and gave up on it in favor of a parser from the batteries :). -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From carroll at tjc.com Sat Apr 17 01:46:03 2004 From: carroll at tjc.com (Terry Carroll) Date: Sat Apr 17 01:46:08 2004 Subject: [Tutor] Web app in Python: alternatives to CGI? Message-ID: Just checking: I want to use Python to write a web application that will prompt the user for input, and do some calculations with the input, and provide an answer. Is CGI my only choice? The nature of my app is that whether one set or another set of questions will be asked depends on the replies to earlier questions; so I need something that handles that well, and trying to tie multiple prompts into a CGI program, using either cookies, hidden date or some other trick isn't something I'd really like to do. (Okay: what I want to do is write something that will calculate the copyright expiration date of a work based on data supplied by the user, and the rules for this vary wildly, depending on whether and when the work was published. For example, for works published prior to 1978, the date of publication is critical, but irrelevant for (most) other works; for works created after 1977, the date of the author's death is the critical factor. And let's not even talk about works created (but not pubished) prior to 1978. Way too complicated to explain, easier to just code.) From alan.gauld at blueyonder.co.uk Sat Apr 17 04:01:13 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Apr 17 04:00:30 2004 Subject: [Tutor] binary data as string? References: <030601c423de$02b51430$6401a8c0@xp> <16971.1082155983@www53.gmx.net> Message-ID: <03ba01c42452$27198a80$6401a8c0@xp> > Why not shift data and reverse the result? Personal preference, I don't like modifying original data and since shifting is destructive (you lose the bits) you need to take a copy of the data before modifying it. > That seemed to be the more general approach to me. > > > > mask = 128 # = 1000000 > > If it is guarateed, that the Data unit is 8 bits. In this case we were discussing characters so 8 bits is probably right (assuming UTF8 encoding). The approach is general however, you just change the mask value to whatever size you need... Alan G. From andy at andybak.net Sat Apr 17 10:12:15 2004 From: andy at andybak.net (Andy Baker) Date: Sat Apr 17 10:12:15 2004 Subject: [Tutor] Re: Why is this write defined as a tuple, instead of picking list? In-Reply-To: Message-ID: > Date: Fri, 16 Apr 2004 23:07:17 +0100 > From: "Alan Gauld" > Subject: Re: [Tutor] Re: Why is this write defined as a > tuple, instead > of picking list? > To: "Andrei" , > > If > > you want to concatenate strings, you should use "+": > > > > write = "a" + "b" + "c" > > > > It is generally not recommended to use this, because it's slow. It's > better > > to have a list of substrings like this: > > > > write = ["a", "b", "c"] > > > > and then use the string method join() to convert that list into a > string > Yuk! > Or even use a format operator with the tuple: > > write = "%s%s%s" % ("a", "b", "c') > Double Yuk! > > In this particular (partial) case, I'd even recommend string > formatting: > > > > write = "

%s

" % article_items[0] > > Yes in this case hard coding the

makes even more sense! > And formatting is pretty fast coz it happens in C. > > Alan G. I would prefer to go with concantenation for readabilityin most cases. Why is concantenation so slow and could the Python developers speed it up rather than force us to use the uglier syntax? From missive at hotmail.com Sat Apr 17 10:27:15 2004 From: missive at hotmail.com (Lee Harr) Date: Sat Apr 17 10:27:21 2004 Subject: [Tutor] Re: Web app in Python: alternatives to CGI? Message-ID: >Just checking: I want to use Python to write a web application that will >prompt the user for input, and do some calculations with the input, and >provide an answer. > >Is CGI my only choice? > You should look at Zope and Twisted (with nevow). http://zope.org/ http://www.twistedmatrix.com/ _________________________________________________________________ The new MSN 8: smart spam protection and 2 months FREE* http://join.msn.com/?page=features/junkmail From alan.gauld at blueyonder.co.uk Sat Apr 17 10:43:36 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Apr 17 10:43:30 2004 Subject: [Tutor] Re: Why is this write defined as a tuple, instead ofpicking list? References: <20040416111634.73b2eb6c@debian><20040416200400.44b567fd@debian><036b01c423ff$9c0e9310$6401a8c0@xp> <20040417121516.10786d45@debian> Message-ID: <03c001c4248a$5d828c60$6401a8c0@xp> CC'd to tutor.... > > > > > for x in article_items: > > > > > write = "

", article_items[0], "

" > I've realised that I really don't need the loop here, just > the statement which adds each part of article_items(x). If you know how many items you can certainly do it in one write, thats true. > I'm looking into saving two versions of this data - the list > itself and then the 'exported' html version. > here). Is it easy to parse the list text file back into a > python script? OK, The list can be written to a file as text quite easily using the repr() function and on reading it back eval() will convert it back into a list - but beware that eval() has security implications since it will evaluate any arbitrary string as a python expression, including 'os.system(.....)' strings and the like. > What is the separator between them, Whatever you want it to be! :-) > imagine that Python will just 'see' it as text initially. Yes but if you use the repr/eval pair it should write/read fairly transparently. Alan G. From lumbricus at gmx.net Sat Apr 17 10:48:00 2004 From: lumbricus at gmx.net (=?ISO-8859-1?Q?=22J=F6rg_W=F6lke=22?=) Date: Sat Apr 17 10:48:04 2004 Subject: [Tutor] Stripping HTML tags. References: Message-ID: <31857.1082213280@www62.gmx.net> Hello! [ snip ] > Regex parsing of HTML can be slightly subtle, so it might be worth it to > invest some time with HTMLParser: Wrong it's not "slightly subtle" or "tricky" to parse nested Languages wit Regex - It's _impossible_. Greetings, J"o! -- Sie duerfen diesen Satz zitieren. NEU : GMX Internet.FreeDSL Ab sofort DSL-Tarif ohne Grundgeb?hr: http://www.gmx.net/info From dtalaga at novodynamics.com Sat Apr 17 11:47:34 2004 From: dtalaga at novodynamics.com (David Talaga) Date: Sat Apr 17 11:47:17 2004 Subject: [Tutor] deleting CR within files In-Reply-To: <030e01c423de$ff58d460$6401a8c0@xp> Message-ID: Skipped content of type multipart/alternative-------------- next part -------------- import os import Tkinter import sys import dialog root=Tkinter.Tk() result = 0 def doDialog(): global result result = dialog.dialog() f=Tkinter.Button(root, text="Find Files", command=doDialog) f.pack() x=Tkinter.Button(root, text="Close", command=sys.exit) x.pack() if f: fileName=dialog.dialog() in_file = open(fileName,'r').readlines() out_file = open(fileName + '_cleaned', 'w') for i in dialog().readline: in_file out_file.write(i[:-1] + '\n') print 'File cleaned' in_file.close() out_file.close() print filename root.mainloop() -------------- next part -------------- from Tkinter import * import tkFileDialog import sys def dialog(): top = Tk() top.withdraw() initDir = 'C:/windows/desktop' filetype = [('All files', '.*')] fileName = tkFileDialog.askopenfilename(initialdir=initDir, filetypes=filetype) return fileName From dtalaga at novodynamics.com Sat Apr 17 12:04:40 2004 From: dtalaga at novodynamics.com (David Talaga) Date: Sat Apr 17 12:04:23 2004 Subject: [Tutor] deleting CR within files In-Reply-To: <030e01c423de$ff58d460$6401a8c0@xp> Message-ID: Alan and Roger! I actually found a way to write the file to the other file perfectly. It is not taking out the but that is OK for right now. It is just something more to work on. At least it is not deleting it all the way! Big Step! Here is what I have: import os import Tkinter import sys import dialog root=Tkinter.Tk() result = 0 def doDialog(): global result result = dialog.dialog() f=Tkinter.Button(root, text="Find Files", command=doDialog) f.pack() x=Tkinter.Button(root, text="Close", command=sys.exit) x.pack() if f: fileName=dialog.dialog() in_file = open(fileName,'r').readlines() out_file = open(fileName + '_cleaned', 'w') for i in in_file: #Changed the for statement to say in_file (duh!) out_file.write(i[:-1] + '\n') #maybe the problem is here? print 'File cleaned' in_file.close() out_file.close() print filename root.mainloop() -----Original Message----- From: Alan Gauld [mailto:alan.gauld@blueyonder.co.uk] Sent: Friday, April 16, 2004 2:17 PM To: David Talaga; Roger Merchberger; tutor@python.org Subject: Re: [Tutor] deleting CR within files > root=Tkinter.Tk() > f=Tkinter.Button(root, text="Find Files", command=dialog.dialog).pack() > x=Tkinter.Button(root, text="Close", command=sys.exit).pack() Like another recent poster you are assigning the value of pack() to the variables. But pack returns None. In this case you don't use f or x so it doesn't matter but could lead to some strange things if you tried to use them later... > if f: Oops, sorry, you do use f, it will be false since pack() returns none wich is considered as false. As a result the block of code inside the if never gets executed. You need to define the widget then pack it: f=Tkinter.Button(root, text="Find Files", command=dialog.dialog) f.pack() The other problem is that oits not clear how you rtrieve the output from dialog.dialog. I suspect you need to wrap that in a local function that stores the value for you: result = 0 def doDialog() global result result = dialog.dialog() Now pass doDialog into the command parameter and when the button is pressed the result will be stored in the global variable result. [ If you were using objects you would make the doDialog a method and store the result in an attribute of the class to avoid using a global variable...] HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040417/1387cf79/attachment.html From dtalaga at novodynamics.com Sat Apr 17 12:08:58 2004 From: dtalaga at novodynamics.com (David Talaga) Date: Sat Apr 17 12:08:39 2004 Subject: [Tutor] deleting CR within files In-Reply-To: Message-ID: >From the last post I sent I said that the problem is in the for statement. I still think that. But how would I take out the extra 's? Am I doing it right? import os import Tkinter import sys import dialog root=Tkinter.Tk() result = 0 def doDialog(): global result result = dialog.dialog() f=Tkinter.Button(root, text="Find Files", command=doDialog) f.pack() x=Tkinter.Button(root, text="Close", command=sys.exit) x.pack() if f: fileName=dialog.dialog() in_file = open(fileName,'r').readlines() out_file = open(fileName + '_cleaned', 'w') for i in in_file: #Changed the for statement to say in_file (duh!) out_file.write(i[:-1] + '\n') #maybe the problem is here? print 'File cleaned' in_file.close() out_file.close() print filename root.mainloop() -----Original Message----- From: Alan Gauld [mailto:alan.gauld@blueyonder.co.uk] Sent: Friday, April 16, 2004 2:17 PM To: David Talaga; Roger Merchberger; tutor@python.org Subject: Re: [Tutor] deleting CR within files > root=Tkinter.Tk() > f=Tkinter.Button(root, text="Find Files", command=dialog.dialog).pack() > x=Tkinter.Button(root, text="Close", command=sys.exit).pack() Like another recent poster you are assigning the value of pack() to the variables. But pack returns None. In this case you don't use f or x so it doesn't matter but could lead to some strange things if you tried to use them later... > if f: Oops, sorry, you do use f, it will be false since pack() returns none wich is considered as false. As a result the block of code inside the if never gets executed. You need to define the widget then pack it: f=Tkinter.Button(root, text="Find Files", command=dialog.dialog) f.pack() The other problem is that oits not clear how you rtrieve the output from dialog.dialog. I suspect you need to wrap that in a local function that stores the value for you: result = 0 def doDialog() global result result = dialog.dialog() Now pass doDialog into the command parameter and when the button is pressed the result will be stored in the global variable result. [ If you were using objects you would make the doDialog a method and store the result in an attribute of the class to avoid using a global variable...] HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040417/5235c63e/attachment.html From zmerch at 30below.com Sat Apr 17 12:26:08 2004 From: zmerch at 30below.com (Roger Merchberger) Date: Sat Apr 17 12:25:20 2004 Subject: [Tutor] deleting CR within files In-Reply-To: References: Message-ID: <5.1.0.14.2.20040417122215.039636f0@mail.30below.com> Rumor has it that David Talaga may have mentioned these words: [snip] > out_file.write(i[:-1] + '\n') #maybe the problem is here? If this is on a windows platform, you'll want this: out_file.write(i[:-2] + '\n') ^^^ For the more popular computers/OSs, this is what the line endings are: Linux: \n only MS-DOS / Winders: \r\n MacOS (at least thru ver.9): \r only So you need to lop off the last 2 characters of the string on Winders and replace with a single \n for *nix machines; Your current code on Winders is only replacing the last \n with a \n, which isn't quite what you want. ;-) HTH, Roger "Merch" Merchberger -- Roger "Merch" Merchberger -- sysadmin, Iceberg Computers zmerch@30below.com What do you do when Life gives you lemons, and you don't *like* lemonade????????????? From dtalaga at novodynamics.com Sat Apr 17 12:41:43 2004 From: dtalaga at novodynamics.com (David Talaga) Date: Sat Apr 17 12:41:24 2004 Subject: [Tutor] deleting CR within files In-Reply-To: <5.1.0.14.2.20040417122215.039636f0@mail.30below.com> Message-ID: Closer Roger, But I noticed that it is taking off 2 character (obviously -2) from the last and not touching the 's. hrmmm. How would I get rid of those pesky 's???? -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org]On Behalf Of Roger Merchberger Sent: Saturday, April 17, 2004 12:26 PM To: tutor@python.org Subject: RE: [Tutor] deleting CR within files Rumor has it that David Talaga may have mentioned these words: [snip] > out_file.write(i[:-1] + '\n') #maybe the problem is here? If this is on a windows platform, you'll want this: out_file.write(i[:-2] + '\n') ^^^ For the more popular computers/OSs, this is what the line endings are: Linux: \n only MS-DOS / Winders: \r\n MacOS (at least thru ver.9): \r only So you need to lop off the last 2 characters of the string on Winders and replace with a single \n for *nix machines; Your current code on Winders is only replacing the last \n with a \n, which isn't quite what you want. ;-) HTH, Roger "Merch" Merchberger -- Roger "Merch" Merchberger -- sysadmin, Iceberg Computers zmerch@30below.com What do you do when Life gives you lemons, and you don't *like* lemonade????????????? _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From alan.gauld at blueyonder.co.uk Sat Apr 17 12:47:33 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Apr 17 12:47:21 2004 Subject: [Tutor] deleting CR within files References: Message-ID: <03cc01c4249b$ae1cf280$6401a8c0@xp> > From the last post I sent I said that the problem is in the for statement. I > still think that. But how would I take out the extra 's? > fileName=dialog.dialog() > in_file = open(fileName,'r').readlines() > out_file = open(fileName + '_cleaned', 'w') > for i in in_file: #Changed the for statement to say in_file (duh!) > out_file.write(i[:-1] + '\n') #maybe the problem is here? What happens if you don't put the \n back on? As it stands you are stipping off one character with the [:-1] and putting another on with the +'\n'. Maybe just leaving off the \n will do what you want? > root.mainloop() BTW The Tkinter stuff is doing nothing useful so far, it's just adding confusion to the code. You might be better stripping it out until you are ready to use it. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at blueyonder.co.uk Sat Apr 17 12:52:15 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Apr 17 12:52:04 2004 Subject: [Tutor] Web app in Python: alternatives to CGI? References: Message-ID: <03df01c4249c$562bddb0$6401a8c0@xp> > Is CGI my only choice? No there are loads of choices from ASP to Zope. But CGI is perfectly capable of what you ask, just capture the data, submit the form and display the results. The complexity, as you describe it, is all in the calculation surely? > copyright expiration date of a work based on data supplied by the user, > and the rules for this vary wildly, depending on whether and when the work > was published. And the country... If you are putting it on the web you may have users from many countries accessing it. Something to consider - even if its only with a US only disclaimer... Alan G. From dtalaga at novodynamics.com Sat Apr 17 12:57:35 2004 From: dtalaga at novodynamics.com (David Talaga) Date: Sat Apr 17 12:57:17 2004 Subject: [Tutor] deleting CR within files In-Reply-To: <03cc01c4249b$ae1cf280$6401a8c0@xp> Message-ID: Actually I changed it even more since last. for i in in_file: out_file.write(i[:]) This does what I need with the excpetion that it dosent do it for every line. It is currous because it will take off a from one line and not the next 2 and then from another line... currious... -----Original Message----- From: Alan Gauld [mailto:alan.gauld@blueyonder.co.uk] Sent: Saturday, April 17, 2004 12:48 PM To: David Talaga; Roger Merchberger; tutor@python.org Subject: Re: [Tutor] deleting CR within files > From the last post I sent I said that the problem is in the for statement. I > still think that. But how would I take out the extra 's? > fileName=dialog.dialog() > in_file = open(fileName,'r').readlines() > out_file = open(fileName + '_cleaned', 'w') > for i in in_file: #Changed the for statement to say in_file (duh!) > out_file.write(i[:-1] + '\n') #maybe the problem is here? What happens if you don't put the \n back on? As it stands you are stipping off one character with the [:-1] and putting another on with the +'\n'. Maybe just leaving off the \n will do what you want? > root.mainloop() BTW The Tkinter stuff is doing nothing useful so far, it's just adding confusion to the code. You might be better stripping it out until you are ready to use it. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at blueyonder.co.uk Sat Apr 17 13:02:29 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Apr 17 13:02:19 2004 Subject: [Tutor] Re: Why is this write defined as a tuple, instead of picking list? References: Message-ID: <03e601c4249d$c45f6cb0$6401a8c0@xp> > > > write = "a" + "b" + "c" > > > > > > It is generally not recommended to use this, because it's slow. > > > write = "

%s

" % article_items[0] > > > > Yes in this case hard coding the

makes even more sense! > > And formatting is pretty fast coz it happens in C. > I would prefer to go with concantenation for readability in most cases. Why > is concantenation so slow and could the Python developers speed it up rather > than force us to use the uglier syntax? concatenation creates a new string for each addition. Because, you'll recall, strings are immutable - you can't change one once its been created, you can only create a new modified copy. Python has to allocate a new chunk of memory then copy both sets of charatcters into that new space. Then the next addition it creates another new space and copies.... Something like this: def addStrings(a,b): L1 = len(a) L2 = len(b) mem = newMemory(L1+L2) for char in L1: mem.append(char) for char in L2: mem.append(char) return mem That's slow, even when it's done in C (as it is) and getting slower as the string gets bigger. And there's not much the interpreter writers can do to speed it up, tey;'ve already tweaked it. The other techniques are much faster - because they do it all in one go, and they are more flexible since, with formatting at least, multiple data types etc can be accomodated and close control of the final sizes of the string can be maintained. That's why I hardly ever use string conceatenation and also why I introduce format strings in the very first chapter of my tutor! :-) Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at blueyonder.co.uk Sat Apr 17 13:09:40 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Apr 17 13:09:31 2004 Subject: [Tutor] deleting CR within files References: Message-ID: <03f401c4249e$c67f7110$6401a8c0@xp> > Well, so now it is saying the the module object is not callable referring to > the for statement. > for i in dialog().readline: > in_file > out_file.write(I[:-1] + '\n') > Is this because I am not able to call the dialog function from here? Correct. The dialog function is inside the dialog module so you have to specify it using module.function syntax: ie. dialog.dialog() > doesn't seem like it should be this difficult. All I want to do is: > > 1. Read the file selected by the dialog() function. > 2. Create a new file called filename_cleaned.txt > 3. Write the file selected in step 1 to the file named in step 2 > a.Take out the extra character returns from the file in step 1 > 4. Close all the opened files. Yes and thats all it takes. The problem seems to be in defining exactly what you want removed. Have you tried using the string strip() method I suggested earlier? It is designed to remove crud from the end of a line... It might be more reliable that the -1 slice technique. > This is all I need to do and I have a strange suspicion that I am doing WAY > to much work for this. All the Tkinter stuff is overkill. Indeed why botrher with the dialog stuff, why not just ask thre user using raw_input()? At least till you get it working. One of the fundamental principles of good design is that you should separate the user interrace from the logic. So if you write a function that cleans the file given a filename, then capturing the filename becomes a separate (and much easier) problem. Get the core of the program working first then add the flashy GUI if you feel you need it. The case study in my tutor gives an example of this, by building a command line version 1st then adding a GUI later... Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From pythonTutor at venix.com Sat Apr 17 15:06:02 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Sat Apr 17 15:06:12 2004 Subject: [Tutor] csv files In-Reply-To: References: Message-ID: <1082228761.5847.64.camel@laptop.venix.com> Here are some suggestions for rewriting the process function: change inp1,inp2,... to a list. I'll call it inplist from here on. Keep the 76 line assumption for now. curlines = [inp.readline() for inp in inplist] # read files in parallel into a list of current lines outdata1 = [line[88:96] for line in curlines] # pull out data from each line outlabel = '"' + curlines[0][:12] + '"' # pull out the lable value from first line and add quotes # that line is not so readable, but I think it is OK outstring = ','.join([outlabel] + [outdata]) # make label + data into a list. # make the list into a string with comma separators Now you can write the string to the output file. use the same kind of logic for outp2. Notice that the four lines above would be exactly the same for outp2 except for the slice values 88:96 and 123:130. So rather than cutting and pasting those lines and changing the slice value, you could make them into a function that returns the string to be written. To call process with a list of input files: process([inp1,inp2,inp3,inp4,inp5,inp6,inp7,inp8,inp9,inp10],outp1,outp2) simply put [] square brackets around the input files. I used the list comprehension syntax for processing the inplist. Though it may look a little strange as compared to C or Java code, it is a very nice syntax for making new lists from existing lists. Note that you never use the csv module. It doesn't look like you need it for this problem. On Fri, 2004-04-16 at 20:39, ABDUL JABBAR SIDDIQUE wrote: > As I mentioned in my last mail that I am new to programming and may > ask stupid questions. :)Bare with me please. > > I have coded as follows to convert some text files into csv format for > onward reading into python programming. It seems that there must be > some short way to do all this which I don't know. I will > appreciate your advices. Following is the code: > > from csv import * > > def > process(inp1,inp2,inp3,inp4,inp5,inp6,inp7,inp8,inp9,inp10,outp1,outp2): > for i in range(76): # it means i from 0 to 75 > line1=inp1.readline() > line2=inp2.readline() > line3=inp3.readline() > line4=inp4.readline() > line5=inp5.readline() > line6=inp6.readline() > line7=inp7.readline() > line8=inp8.readline() > line9=inp9.readline() > line10=inp10.readline() > > if i >= 5: ### Data values begin from line 5 > > outp1.write(('"'+line1[:12]+'"'+','+line1[88:96]+','+line2[88:96]+','+line3[88:96]+','+line4[88:96]+',' \ > > +line5[88:96]+','+line6[88:96]+','+line7[88:96]+','+line8[88:96]+',' \ > +line9[88:96]+','+line10[88:96])+"\n") ### > Data values for Control Delays (MOE) is written to output file > > > outp2.write(('"'+line1[:12]+'"'+','+line1[123:130]+','+line2[123:130]+','+line3[123:130]+','+line4[123:130]+',' \ > > +line5[123:130]+','+line6[123:130]+','+line7[123:130]+','+line8[123:130]+',' \ > +line9[123:130]+','+line10[123:130])+"\n") > ### Data values for Speed (MOE) is written to output > file > > inp1 = open("S_1.OUT","r") ### Results of Simulation output are > named as S_1.OUT, S_2.OUT etc. > inp2 = open("S_2.OUT","r") > inp3 = open("S_3.OUT","r") > inp4 = open("S_4.OUT","r") > inp5 = open("S_5.OUT","r") > inp6 = open("S_6.OUT","r") > inp7 = open("S_7.OUT","r") > inp8 = open("S_8.OUT","r") > inp9 = open("S_9.OUT","r") > inp10 = open("S_10.OUT","r") > > outp1 = open ("CD.csv","w") > outp2 = open ("Speed.csv","w") > > > process(inp1,inp2,inp3,inp4,inp5,inp6,inp7,inp8,inp9,inp10,outp1,outp2) > > > print "data copied to file..." ### Mentioning that process of > data extraction is completed. > > # Now close the files > inp1.close() > inp2.close() > inp3.close() > inp4.close() > inp5.close() > inp6.close() > inp7.close() > inp8.close() > inp9.close() > inp10.close() > ### Finally output file is closed. > outp1.close() > outp2.close() > > Jabbar > > > > ______________________________________________________________________ > Protect your PC - Click here for McAfee.com VirusScan Online > > ______________________________________________________________________ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From pythonTutor at venix.com Sat Apr 17 15:13:58 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Sat Apr 17 15:14:04 2004 Subject: [Tutor] csv files In-Reply-To: <1082228761.5847.64.camel@laptop.venix.com> References: <1082228761.5847.64.camel@laptop.venix.com> Message-ID: <1082229238.5847.71.camel@laptop.venix.com> Sorry, two OBVIOUS typos. There could be more. On Sat, 2004-04-17 at 15:06, Lloyd Kvam wrote: > Here are some suggestions for rewriting the process function: > > change inp1,inp2,... to a list. I'll call it inplist from here on. > > Keep the 76 line assumption for now. > > curlines = [inp.readline() for inp in inplist] > # read files in parallel into a list of current lines > > outdata = [line[88:96] for line in curlines] > # pull out data from each line CHANGED to outdata > > outlabel = '"' + curlines[0][:12] + '"' > # pull out the lable value from first line and add quotes > # that line is not so readable, but I think it is OK > > outstring = ','.join([outlabel] + outdata) > # make label + data into a list. > # make the list into a string with comma separators outdata is already a list. It doesn't need square brackets to enclose it. outlabel is "listified" by putting it in square brackets. + combines two lists into one longer list. > > Now you can write the string to the output file. > > use the same kind of logic for outp2. Notice that the four lines above > would be exactly the same for outp2 except for the slice values 88:96 > and 123:130. So rather than cutting and pasting those lines and > changing the slice value, you could make them into a function that > returns the string to be written. > > To call process with a list of input files: > process([inp1,inp2,inp3,inp4,inp5,inp6,inp7,inp8,inp9,inp10],outp1,outp2) > simply put [] square brackets around the input files. > > I used the list comprehension syntax for processing the inplist. Though > it may look a little strange as compared to C or Java code, it is a very > nice syntax for making new lists from existing lists. > > Note that you never use the csv module. It doesn't look like you need > it for this problem. > > > On Fri, 2004-04-16 at 20:39, ABDUL JABBAR SIDDIQUE wrote: > > As I mentioned in my last mail that I am new to programming and may > > ask stupid questions. :)Bare with me please. > > > > I have coded as follows to convert some text files into csv format for > > onward reading into python programming. It seems that there must be > > some short way to do all this which I don't know. I will > > appreciate your advices. Following is the code: > > > > from csv import * > > > > def > > process(inp1,inp2,inp3,inp4,inp5,inp6,inp7,inp8,inp9,inp10,outp1,outp2): > > for i in range(76): # it means i from 0 to 75 > > line1=inp1.readline() > > line2=inp2.readline() > > line3=inp3.readline() > > line4=inp4.readline() > > line5=inp5.readline() > > line6=inp6.readline() > > line7=inp7.readline() > > line8=inp8.readline() > > line9=inp9.readline() > > line10=inp10.readline() > > > > if i >= 5: ### Data values begin from line 5 > > > > outp1.write(('"'+line1[:12]+'"'+','+line1[88:96]+','+line2[88:96]+','+line3[88:96]+','+line4[88:96]+',' \ > > > > +line5[88:96]+','+line6[88:96]+','+line7[88:96]+','+line8[88:96]+',' \ > > +line9[88:96]+','+line10[88:96])+"\n") ### > > Data values for Control Delays (MOE) is written to output file > > > > > > outp2.write(('"'+line1[:12]+'"'+','+line1[123:130]+','+line2[123:130]+','+line3[123:130]+','+line4[123:130]+',' \ > > > > +line5[123:130]+','+line6[123:130]+','+line7[123:130]+','+line8[123:130]+',' \ > > +line9[123:130]+','+line10[123:130])+"\n") > > ### Data values for Speed (MOE) is written to output > > file > > > > inp1 = open("S_1.OUT","r") ### Results of Simulation output are > > named as S_1.OUT, S_2.OUT etc. > > inp2 = open("S_2.OUT","r") > > inp3 = open("S_3.OUT","r") > > inp4 = open("S_4.OUT","r") > > inp5 = open("S_5.OUT","r") > > inp6 = open("S_6.OUT","r") > > inp7 = open("S_7.OUT","r") > > inp8 = open("S_8.OUT","r") > > inp9 = open("S_9.OUT","r") > > inp10 = open("S_10.OUT","r") > > > > outp1 = open ("CD.csv","w") > > outp2 = open ("Speed.csv","w") > > > > > > process(inp1,inp2,inp3,inp4,inp5,inp6,inp7,inp8,inp9,inp10,outp1,outp2) > > > > > > print "data copied to file..." ### Mentioning that process of > > data extraction is completed. > > > > # Now close the files > > inp1.close() > > inp2.close() > > inp3.close() > > inp4.close() > > inp5.close() > > inp6.close() > > inp7.close() > > inp8.close() > > inp9.close() > > inp10.close() > > ### Finally output file is closed. > > outp1.close() > > outp2.close() > > > > Jabbar > > > > > > > > ______________________________________________________________________ > > Protect your PC - Click here for McAfee.com VirusScan Online > > > > ______________________________________________________________________ > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From alan.gauld at blueyonder.co.uk Sat Apr 17 15:47:27 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Apr 17 15:47:17 2004 Subject: [Tutor] deleting CR within files References: Message-ID: <03f901c424b4$cffcf030$6401a8c0@xp> > for i in in_file: > out_file.write(i[:]) > > This does what I need with the excpetion that it dosent do it for every > line. It is currous because it will take off a from one line and not > the next 2 and then from another line... currious... Are you sure thats not the origoinal data? Try using the strip function since it will only strip off if there is anything to strip so should work in all cases. ie. out_file.write(i.strip()) HTH, Alan G From bvande at po-box.mcgill.ca Sat Apr 17 15:56:43 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sat Apr 17 16:04:44 2004 Subject: [Tutor] working code for adding line numbers -- request for criticism Message-ID: <40818BFB.9020007@po-box.mcgill.ca> Hi all, having learned the lessons of posting under-thought-out questions and not wishing to further test the goodwill of those on the list, I have code to post this time! (Thanks again for past tolerance.) I've found that traceback errors identified by line numbers can be tricky to track down without line number indications in the code or the editor. (IDLE doesn't seem to provide for line numbers, and it's no fun counting line on screen in a long file.) So, I wrote a script to take a file and output a file with line number comments added. (BTW, is there a module that will do this? If so, no harm, as the exercise was useful, but I'd probably be better off with a module than my script.) I've worked through a way to do it. But I'd very much appreciate being told where and how this code is kludgey and could be improved. As I said, it seems to work, but I don't think it will win any prizes for beauty or being Pythonic. If asking for such a critique is over-imposing, I understand. (My aim in asking is to break bad habits before they become entrenched. Brutal criticism is happily accepted.) Right near the top, there is a comment where I have a question about how to do it better. One case where I know it does not work is for files without any extension at all. I want file.txt to come out as file_numbered.txt but file comes out as fil_numberede. I can see how to fix that (by constructing the output filename differently depending on whether the filename contains a '.' or not, but it didn't seem worth doing. I also understand that adding comments to arbitrary lines may violate syntax (say, by adding a comment to other than the last line of a long string). It also may well take lines past 80 characters. Neither worry me; the line number comments are being added to a new file intended for inspection rather than running. Also, it is likely OS specific to DOS/Windows. That's what I run (for now) and what I can test on. Thanks and best to all, Brian vdB ----- import os.path def get_filename(): f = raw_input('What file would you like to process? \n \ (Specify a full path if it is not in the current working directory) \n') # This makes for ugly screen output. How can I left allign the output # without breaking the function def's indetation? return f def get_multiple(): print m = raw_input('By default, I mark each %i lines with line numbers.\n \ Would you like a different choice of line multiples to mark? \n \ If so, enter a positive whole number now. \n \ (All other choices will result in the use of the default value of %i)\ \n' %(default, default)) o = 'Your input was not a positive integer. \n \ The default multiple of %i will be used instead' %default try: m = int(m) if m > 0: return m else: print o; return default except: print o; return default default = 5 print print 'Yout current working directory is ' + os.getcwd() print sfilename = get_filename() # 'sfilename', etc. for source file name, etc. # Likewise for 'tfilename' and taget file name. print while os.path.isfile(sfilename) == False: print "I'm sorry, but you have specified a non-existent file path.\ Please try again. (You can press CTRL-C to end if you prefer)" sfilename = get_filename() multiple = get_multiple() print sfile = file(sfilename) sfile_base = os.path.basename(sfilename) i = sfile_base.rfind('.') tfile_base = sfile_base[:i] + '_numbered' + sfile_base[i:] # inserts '_numbered' immediately before the extension (if any) of the filename # otherwsie before the last character. A bit broken, but doesn't matter. tfilename = os.path.join(os.path.dirname(sfilename), tfile_base) # Prints output file name and location # if os.path.dirname(tfilename) == '': dirname = os.getcwd() # To ensure that the directory is displayed in print below. Needed as # os.path.dirname(tfilename) == '' when the dirname is the cwd else: dirname = os.path.dirname(tfilename).capitalize() # Capitalize ensures that drive letter displays in DOS convention target = (tfile_base, dirname) print 'Your numbered file will be %s in the directory %s' %target tfile = file(tfilename, 'w') i = 1 for line in sfile: if i%multiple == 0 and line[-1] == '\n': line = line[:-1] + ' # ' + str(i) + '\n' if i%multiple == 0 and line[-1] != '\n': line = line + ' # ' + str(i) tfile.write(line) i = i + 1 tfile.close() sfile.close() From denis.spir at free.fr Sat Apr 17 16:29:35 2004 From: denis.spir at free.fr (denis) Date: Sat Apr 17 16:30:32 2004 Subject: [Tutor] deleting CR within files References: Message-ID: <004d01c424ba$c7e1d680$ec25933e@spir> ----- Original Message ----- From: David Talaga To: Alan Gauld ; Roger Merchberger ; Sent: Saturday, April 17, 2004 6:57 PM Subject: RE: [Tutor] deleting CR within files > Actually I changed it even more since last. > > for i in in_file: > out_file.write(i[:]) > > This does what I need with the excpetion that it dosent do it for every > line. It is currous because it will take off a from one line and not > the next 2 and then from another line... currious... Here absracts from the standard python (2.3.3) help files (just in case). **************** file( filename[, mode[, bufsize]]) [...] mode may be 'U' or 'rU'. If Python is built with universal newline support (the default) the file is opened as a text file, but lines may be terminated by any of '\n', the Unix end-of-line convention, '\r', the Macintosh convention or '\r\n', the Windows convention. All of these external representations are seen as '\n' by the Python program. If Python is built without universal newline support mode 'U' is the same as normal text mode. Note that file objects so opened also have an attribute called newlines which has a value of None (if no newlines have yet been seen), '\n', '\r', '\r\n', or a tuple containing all the newline types seen. Files support the iterator protocol. Each iteration returns the same result as file.readline(), and iteration ends when the readline() method returns an empty string. newlines (file object's read-only attribute) If Python was built with the --with-universal-newlines option (the default) this read-only attribute exists, and for files opened in universal newline read mode it keeps track of the types of newlines encountered while reading the file. The values it can take are '\r', '\n', '\r\n', None (unknown, no newlines read yet) or a tuple containing all the newline types seen, to indicate that multiple newline conventions were encountered. For files not o pened in universal newline read mode the value of this attribute will be None. **************** On my (windows) platform : >>> def testNewlines(): fich = file('d:\\essais\\test.txt','r') # 'r' : normal newline mode for line in fich.readlines() : print line[:-1], print fich.newlines fich.close >>> testNewlines() a b c None >>> def testNewlines(): fich = file('d:\\essais\\test.txt','rU') for line in fich.readlines():print line[:-1], nl = fich.newlines print ord(nl[0]),ord(nl[1]),nl fich.close >>> testNewlines() a b c 13 10 ^ here a non printable (square) caracter visible in Idle I guess this control caracter is the way Idle shows '\r\n' on the screen. denis From project5 at redrival.net Sat Apr 17 16:58:00 2004 From: project5 at redrival.net (Andrei) Date: Sat Apr 17 16:58:06 2004 Subject: [Tutor] Re: Re: Why is this write defined as a tuple, instead of picking list? References: Message-ID: <1xc3p19foko6x$.ec5b9mtduqg6$.dlg@40tude.net> Andy Baker wrote on Sat, 17 Apr 2004 15:12:15 +0100: >>> It is generally not recommended to use this, because it's slow. It's >> better >>> to have a list of substrings like this: >>> >>> write = ["a", "b", "c"] >>> >>> and then use the string method join() to convert that list into a >> string > Yuk! I'll have to disagree with this "Yuk". This method is Python idiom and is extremely well known an extremely frequently used (unlike string concatenation). The join() method may seem a little awkward at first (particularly the fact that it's a string method instead of a list method like one would most likely expect), but it's much better and more clear than string concatenation. Let's assume you want to write a set of values to a comma-separated list - just the kind of task join() is meant for. You advocate using something like this: s = "" for elem in mylist: s = s + ", " + elem # s will start with ", " s = s.strip(", ") # need to remove leading ", " You'll probably agree that it's clearer to write: s = ", ".join(mylist) >> Or even use a format operator with the tuple: >> >> write = "%s%s%s" % ("a", "b", "c') > > Double Yuk! I disagree even more with you disliking this - remember, this example is contrived and only an idiot would do this instead of 'write = "abc"', it's just meant to demonstrate the use of the formatting operator. String concatentation is a pain in the butt compared to string formatting. It's hard to maintain, slow and will get you in trouble if you ever plan on e.g. internationalizing your application (unless you enjoy going over existing code to change all string concatentations to format strings). I wouldn't recommend string concatenation instead of string formatting even if string concatenation was fast. And again, formatting improves readability, it does not lessen it, just like writing a simple "5" improves readability compared to writing "3 + 2". An example: farm = pig = horse = 1 print "Old MacDonald had: %d farm, %d pig, %d horse" % (farm, pig, horse) versus: farm = pig = horse = 1 print "Old MacDonald had: " + str(farm) + " farm, " + str(pig) + " pig, " + str(horse) + " horse" Where string formatting is used, it's immediately clear what the output will look like: something mentioning the amount of farms, pigs and horses. In the second case you'll have to parse the string concatenation mentally in order to find out what will be printed. >>> write = "

%s

" % article_items[0] > I would prefer to go with concantenation for readabilityin most cases. Why > is concantenation so slow and could the Python developers speed it up rather > than force us to use the uglier syntax? String concatenation is not readable, as I demonstrated above. If you're just concatenating "a" and "b", you can use concatenation, it's not such an important speed penalty and readability doesn't suffer. But when large amounts (i.e. more than two pieces) of data need to be concatenated to a single string, the other two methods of string building are both faster and more readable. -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From pythonTutor at venix.com Sat Apr 17 17:18:35 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Sat Apr 17 17:18:48 2004 Subject: [Tutor] working code for adding line numbers -- request for criticism In-Reply-To: <40818BFB.9020007@po-box.mcgill.ca> References: <40818BFB.9020007@po-box.mcgill.ca> Message-ID: <1082236714.5847.90.camel@laptop.venix.com> On Sat, 2004-04-17 at 15:56, Brian van den Broek wrote: > Hi all, > > having learned the lessons of posting under-thought-out questions and not > wishing to further test the goodwill of those on the list, I have code to post > this time! (Thanks again for past tolerance.) > > I've found that traceback errors identified by line numbers can be tricky to > track down without line number indications in the code or the editor. (IDLE > doesn't seem to provide for line numbers, and it's no fun counting line on > screen in a long file.) Use Alt-G to jump to a line. (Works for me in Linux & WinNT) > So, I wrote a script to take a file and output a file > with line number comments added. (BTW, is there a module that will do this? If > so, no harm, as the exercise was useful, but I'd probably be better off with a > module than my script.) > > I've worked through a way to do it. But I'd very much appreciate being told > where and how this code is kludgey and could be improved. As I said, it seems to > work, but I don't think it will win any prizes for beauty or being Pythonic. If > asking for such a critique is over-imposing, I understand. (My aim in asking is > to break bad habits before they become entrenched. Brutal criticism is happily > accepted.) > The fileinput module makes it easy to process lists of input files or piped input through stdin. That's usually better than prompting for filenames in your program. > Right near the top, there is a comment where I have a question about how to do > it better. Use triple quotes for multi-line strings. These can break the indent rules. I adjusted your code down below. One other thing to note, Python now has an enumerate function which will provide a counter as you iterate. This allows you to write: for i,line in enumerate(sfile): and helps avoid errors where you forget to initialize the counter or fail to increment the counter. > > One case where I know it does not work is for files without any extension at > all. I want file.txt to come out as file_numbered.txt but file comes out as > fil_numberede. I can see how to fix that (by constructing the output filename > differently depending on whether the filename contains a '.' or not, but it > didn't seem worth doing. > > I also understand that adding comments to arbitrary lines may violate syntax > (say, by adding a comment to other than the last line of a long string). It also > may well take lines past 80 characters. Neither worry me; the line number > comments are being added to a new file intended for inspection rather than > running. Also, it is likely OS specific to DOS/Windows. That's what I run (for > now) and what I can test on. > > Thanks and best to all, > > Brian vdB > > ----- > import os.path > > def get_filename(): filename_prompt = '''What file would you like to process? (Specify a full path if it is not in the current working directory) ''' > f = raw_input(filename_prompt) > # This makes for ugly screen output. How can I left allign the output > # without breaking the function def's indetation? > return f > > def get_multiple(): > print > m = raw_input('By default, I mark each %i lines with line numbers.\n \ > Would you like a different choice of line multiples to mark? \n \ > If so, enter a positive whole number now. \n \ > (All other choices will result in the use of the default value of %i)\ > \n' %(default, default)) > o = 'Your input was not a positive integer. \n \ > The default multiple of %i will be used instead' %default > try: > m = int(m) > if m > 0: return m > else: > print o; return default > except: > print o; return default > > default = 5 > print > print 'Yout current working directory is ' + os.getcwd() > print > > sfilename = get_filename() > # 'sfilename', etc. for source file name, etc. > # Likewise for 'tfilename' and taget file name. > print > while os.path.isfile(sfilename) == False: > print "I'm sorry, but you have specified a non-existent file path.\ > Please try again. (You can press CTRL-C to end if you prefer)" > sfilename = get_filename() > > multiple = get_multiple() > print > > sfile = file(sfilename) > sfile_base = os.path.basename(sfilename) > i = sfile_base.rfind('.') > tfile_base = sfile_base[:i] + '_numbered' + sfile_base[i:] > # inserts '_numbered' immediately before the extension (if any) of the filename > # otherwsie before the last character. A bit broken, but doesn't matter. > tfilename = os.path.join(os.path.dirname(sfilename), tfile_base) > > # Prints output file name and location > # > if os.path.dirname(tfilename) == '': dirname = os.getcwd() > # To ensure that the directory is displayed in print below. Needed as > # os.path.dirname(tfilename) == '' when the dirname is the cwd > else: dirname = os.path.dirname(tfilename).capitalize() > # Capitalize ensures that drive letter displays in DOS convention > target = (tfile_base, dirname) > print 'Your numbered file will be %s in the directory %s' %target > > tfile = file(tfilename, 'w') > i = 1 > for line in sfile: > if i%multiple == 0 and line[-1] == '\n': > line = line[:-1] + ' # ' + str(i) + '\n' > if i%multiple == 0 and line[-1] != '\n': > line = line + ' # ' + str(i) > tfile.write(line) > i = i + 1 > > tfile.close() > sfile.close() > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From project5 at redrival.net Sat Apr 17 17:40:47 2004 From: project5 at redrival.net (Andrei) Date: Sat Apr 17 17:40:55 2004 Subject: [Tutor] Re: working code for adding line numbers -- request for criticism References: <40818BFB.9020007@po-box.mcgill.ca> Message-ID: Brian van den Broek wrote on Sat, 17 Apr 2004 15:56:43 -0400: > I've found that traceback errors identified by line numbers can be tricky to > track down without line number indications in the code or the editor. (IDLE > doesn't seem to provide for line numbers, and it's no fun counting line on > screen in a long file.) So, I wrote a script to take a file and output a file Tip: I don't use/know a lot about Idle, but other editors (like SciTE) show the numbers AND allow you double-click on the line number in the traceback to jump directly to the offending line. > I also understand that adding comments to arbitrary lines may violate syntax > (say, by adding a comment to other than the last line of a long string). It also > may well take lines past 80 characters. Neither worry me; the line number > comments are being added to a new file intended for inspection rather than > running. Also, it is likely OS specific to DOS/Windows. That's what I run (for > now) and what I can test on. If you code this kind of stuff properly, it will generally be cross-platform without you even thinking about it :). > def get_filename(): > f = raw_input('What file would you like to process? \n \ > (Specify a full path if it is not in the current working directory) \n') > # This makes for ugly screen output. How can I left allign the output > # without breaking the function def's indetation? Tip 2: have a look at the discusion started by Adam, with the title "Why is this write defined as tuple...", it contains some useful tips about building strings that you should find helpful. More the the point: you could either A) use print to write the string in pieces or B) make a list of string pieces and join them like this: message = ["What file blabla", "More text here (will be on a new line)", "Third line"] f = raw_input("\n".join(message)) In your case, I'd opt for printing the message in pieces. Triple-quoting the string is also an option, but that breaks the indentation visually, which I think would be a pity in this case. > try: > m = int(m) > if m > 0: return m > else: > print o; return default I don't like the way you wrote this. It's not customary to have more than one statement on a single line. In fact, at first I didn't even notice there was a return in the else, I just saw "print" and thought that o and a bunch of other stuff will be printed. I'd also recommend being consistent in the way you indent code, so IMO the best thing is to always have a newline + indentation after a ":". if m > 0: return m else: print o return default > except: > print o; return default Same here with the ";". New lines are cheap, so use them :). > sfilename = get_filename() > # 'sfilename', etc. for source file name, etc. > # Likewise for 'tfilename' and taget file name. > print > while os.path.isfile(sfilename) == False: > print "I'm sorry, but you have specified a non-existent file path.\ > Please try again. (You can press CTRL-C to end if you prefer)" > sfilename = get_filename() You should initialize loop variables immediately above the loop (for readability). In this case you have the initialization, then some distraction in the form of comments and a print and only after that the loop starts. > sfile = file(sfilename) > sfile_base = os.path.basename(sfilename) > i = sfile_base.rfind('.') > tfile_base = sfile_base[:i] + '_numbered' + sfile_base[i:] There's a battery for this included in Python: the os.path.splitext() function. It should also solve the problem you mentioned with extension-less filenames. > if os.path.dirname(tfilename) == '': dirname = os.getcwd() > # To ensure that the directory is displayed in print below. Needed as > # os.path.dirname(tfilename) == '' when the dirname is the cwd > else: dirname = os.path.dirname(tfilename).capitalize() That's ugly :). I was surprized when I came across the else, already having forgotten about the if, given the fact that the indentation seemed to jump back to 0. Better: if os.path.dirname(tfilename) == '': # no directory specified dirname = os.getcwd() # file in current directory else: dirname = os.path.dirname(tfilename).capitalize() # DOS-style Why don't you use the DOS-style when getcwd() is used? Neat trick (uses the knowledge that Python regards empty strings/lists/tuples as "False" in a boolean context and that "" or "b" returns "b" while "a" or "b" returns "a"): dirname = os.path.dirname(tfilename) or os.getcwd() dirname = dirname.capitalize() > tfile = file(tfilename, 'w') > i = 1 > for line in sfile: > if i%multiple == 0 and line[-1] == '\n': > line = line[:-1] + ' # ' + str(i) + '\n' > if i%multiple == 0 and line[-1] != '\n': > line = line + ' # ' + str(i) > tfile.write(line) > i = i + 1 I'd dump the line[-1] condition and use rstrip() to get rid of any chars at the end. By the way, I'd also put line numbers at the beginning of the line instead of at the end. Format strings would help readability here. -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From bvande at po-box.mcgill.ca Sat Apr 17 18:27:11 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sat Apr 17 18:27:31 2004 Subject: [Tutor] working code for adding line numbers -- request for criticism In-Reply-To: <1082236714.5847.90.camel@laptop.venix.com> References: <40818BFB.9020007@po-box.mcgill.ca> <1082236714.5847.90.camel@laptop.venix.com> Message-ID: <4081AF3F.4090206@po-box.mcgill.ca> Lloyd Kvam said unto the world upon 17/04/2004 17:18: > On Sat, 2004-04-17 at 15:56, Brian van den Broek wrote: > >>Hi all, >> >>having learned the lessons of posting under-thought-out questions and not >>wishing to further test the goodwill of those on the list, I have code to post >>this time! (Thanks again for past tolerance.) >> >>I've found that traceback errors identified by line numbers can be tricky to >>track down without line number indications in the code or the editor. (IDLE >>doesn't seem to provide for line numbers, and it's no fun counting line on >>screen in a long file.) > > > Use Alt-G to jump to a line. (Works for me in Linux & WinNT) Hi Lloyd, Well, that *is* handy. Not sure how I missed that in IDLE's Edit menu, but there you go. Thanks! >>So, I wrote a script to take a file and output a file >>with line number comments added. (BTW, is there a module that will do this? If >>so, no harm, as the exercise was useful, but I'd probably be better off with a >>module than my script.) >> >>I've worked through a way to do it. But I'd very much appreciate being told >>where and how this code is kludgey and could be improved. As I said, it seems to >>work, but I don't think it will win any prizes for beauty or being Pythonic. If >>asking for such a critique is over-imposing, I understand. (My aim in asking is >>to break bad habits before they become entrenched. Brutal criticism is happily >>accepted.) >> > > The fileinput module makes it easy to process lists of input files or > piped input through stdin. That's usually better than prompting for > filenames in your program. Thanks for the tip. I will look into that module closely. On quick inspection though, its Library Reference entry ends with "Caveat: The current implementation does not work for MS-DOS 8+3 filesystems.", which, I expect, will matter to a Windows victim -- I mean user -- like myself. I take it the point is that the in program prompt makes it harder to abstract as a module for other programs to import? >>Right near the top, there is a comment where I have a question about how to do >>it better. > > > Use triple quotes for multi-line strings. These can break the indent > rules. I adjusted your code down below. Thanks, I knew that was an option. What I meant by not breaking the function's definition indentation was not just avoiding a syntax error, but also not loosing the visual cue of the indent. For a smallish script like the one I posted I guess it doesn't matter. But I was looking for a way to print nice while keeping the visual indent for ease of code-scanning. (For some reason, my eye recoils when I see out-dented text in a definition of a conditional code block.) But now that I think about it, I could just assign the string to a variable outside the function definition. (I've snipped out all of my original code save the chunk relevant to the point above.) > One other thing to note, Python now has an enumerate function which will > provide a counter as you iterate. This allows you to write: > > for i,line in enumerate(sfile): > > and helps avoid errors where you forget to initialize the counter or > fail to increment the counter. That is cool. As it happens, I forgot to increment the counter when I first wrote it and spent a head-scratch moment or two being puzzled by the funny output. Thanks for the feedback! And just before I sent this, I saw there are new replies. Thanks for those too; I've not yet had a chance to look, but will. Best, Brian vdB >> >>----- >>import os.path >> >>def get_filename(): > > filename_prompt = '''What file would you like to process? > (Specify a full path if it is not in the current working directory) > ''' > >> f = raw_input(filename_prompt) >> # This makes for ugly screen output. How can I left allign the output >> # without breaking the function def's indetation? >> return f From alan.gauld at blueyonder.co.uk Sat Apr 17 18:39:12 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Apr 17 18:38:58 2004 Subject: [Tutor] working code for adding line numbers -- request for criticism References: <40818BFB.9020007@po-box.mcgill.ca> Message-ID: <043001c424cc$ce3d51f0$6401a8c0@xp> > I've found that traceback errors identified by line numbers can be tricky to > track down without line number indications in the code or the editor. (IDLE > doesn't seem to provide for line numbers, FWIW IDLE has a "Go To Line" menu option (Alt+G) which takes you to the line you need. > So, I wrote a script to take a file and output a file > with line number comments added. But it's a good enough idea since notepad users (why???) can use it. :-) > fil_numberede. I can see how to fix that (by constructing the output filename > differently depending on whether the filename contains a '.' or not, but it > didn't seem worth doing. Or put "numbered_" in front instead: numbered_file.txt Just some ideas, Alan G From dyoo at hkn.eecs.berkeley.edu Sat Apr 17 19:31:19 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Apr 17 19:31:27 2004 Subject: [Tutor] Stripping HTML tags. In-Reply-To: <31857.1082213280@www62.gmx.net> Message-ID: On Sat, 17 Apr 2004, [ISO-8859-1] "J=F6rg W=F6lke" wrote: > > Regex parsing of HTML can be slightly subtle, so it might be worth it > > to invest some time with HTMLParser: > > Wrong it's not "slightly subtle" or "tricky" to parse nested Languages > wit Regex - It's _impossible_. I like to understate things. *grin* But it's possible to do limited processing of HTML using regular expressions alone. I'd better be careful by saying that the processing isn't really parsing --- it's more like "munging". http://www.catb.org/~esr/jargon/html/M/munge.html Dave's original problem can be done with just regular expressions, but only because we're not trying to maintain or reconstruct the tree of nested tags. Stripping HTML tags with with just regular expressions correctly is really ugly, but it is doable. Since Dave's doing the right thing by looking at HTMLParser, I guess it's ok to now show how we can try to approach it with regexes: ### """A small function to try to strip HTML from a string, using just regular expressions.""" import re pattern =3D re.compile(""" ( < ## start character, ## following by any number of the following ## three cases: ( ([^>"']) ## Case 1: a non-closing, non-quote character | ( ## Case 2: a double-quoted string " [^"]* " ) | ( ## Case 3: a single-quoted string ' [^']* ' ) )* > ## end character ) """, re.VERBOSE) def strip_html(s): """Removes HTML from a string s""" return pattern.sub('', s) ### And this sorta works... but it's still not correct! *grin* It doesn't handle HTML comments correctly. Ooops. The regex approach above can be extended to work, and Tom Christiansen of Perl fame wrote a very nice, comprehensive article that shows how to do it correctly in his "Far More Than Everything You've Ever Wanted to Know About" on Regular Expressions: http://www.perl.com/doc/FMTEYEWTK/regexps.html But rather than go through all that pain, it might just be simpler to use HTMLParser from the Standard Library. *grin* Hope this helps! From carroll at tjc.com Sat Apr 17 23:18:52 2004 From: carroll at tjc.com (Terry Carroll) Date: Sat Apr 17 23:18:57 2004 Subject: [Tutor] Web app in Python: alternatives to CGI? In-Reply-To: <03df01c4249c$562bddb0$6401a8c0@xp> Message-ID: On Sat, 17 Apr 2004, Alan Gauld wrote: > > Is CGI my only choice? > > No there are loads of choices from ASP to Zope. > But CGI is perfectly capable of what you ask, just > capture the data, submit the form and display the > results. The complexity, as you describe it, is > all in the calculation surely? Well, it's submit the form, capture the data; based on the data, figure out what additional data is needed, and then submit another form and capture the data; based on that data, figure out what additional data is required, etc. For example, if the work was published prior to 1978, the date of the author's death is not needed, so I don't want to ask it. Similarly, if the work was created after 1977, the date of publication is irrelevant, so I don't want to ask. So I'll ask something like: Was the work: () published in 1977 or earlier; () created in 1978 or later; () created in 1977 or earlier, but not published prior to 1978; () don't know. Then if the user selected "published in 1977 or earlier", the next screen would ask "what's the date of publication"; but if he sleected "created in 1978 or later," the next screen would ask "is the author still alive"; if the third, it would go on to ask if the work was ever published. After each of these, there is another branch to take until all the data is collected. So it's not just one CGI process. I need to save status from call to call; cookies or something I guess. That's what I meant by I need something that handles that [whether one set or another set of questions will be asked depends on the replies to earlier questions ] well, and trying to tie multiple prompts into a CGI program, using either cookies, hidden [data] or some other trick isn't something I'd really like to do. (Not the clearest way of explaining it, I guess.) > And the country... If you are putting it on the web you may > have users from many countries accessing it. Something to > consider - even if its only with a US only disclaimer... This is US only. From carroll at tjc.com Sat Apr 17 23:22:22 2004 From: carroll at tjc.com (Terry Carroll) Date: Sat Apr 17 23:22:27 2004 Subject: [Tutor] Re: Web app in Python: alternatives to CGI? In-Reply-To: Message-ID: On Sat, 17 Apr 2004, Lee Harr wrote: > You should look at Zope and Twisted (with nevow). Thanks. I should mention, it's not my web server, it's my ISP's. I've never looked much into Zope or Twisted; can I install and use them without being sysadmin? (I'm a minority user by using Python for CGI, I think, so I won't have any luck getting my sysadmin to install something new for one app of one user. We're running Python 2.1, and Ive managed to get installing 2.3 on his to-do list, but it's a very low priority. I ended up installing my own copy.) From idiot1 at netzero.net Sun Apr 18 02:09:00 2004 From: idiot1 at netzero.net (Kirk Bailey) Date: Sun Apr 18 02:07:05 2004 Subject: [Tutor] automatic account destruction Message-ID: <40821B7C.3080007@netzero.net> I give people free email accounts. From time to time, I have the task of searching for abandoned accounts and removing them, which is a time consuming chore. This is a bother, world class. So I am building a script which opens the first line of every email popbox and extracts the first line. This is formatted as: "From idiot1@netzero.net Fri Nov 9 00:30:27 2001" (quotemarks mine, not found in data) and I must crunch as needed to turn it into SECONDS SINCE THE EPOCH. I then add a magic number to it (the number of seconds in 2 months), and compare it to NOW. If that sum is smaller than NOW, the message is VERY OLD, and we assume the account is abandoned, and delete it. We repeat this loop for every popbox in the directory, which contains nothing else BUT mailboxes, glob.glob('*.') to the rescue here. This script is still in alpha stage, but I thought the list may find the process to do this crunching intresting. I am unsure how to have a script run a su function. Sure, os.system('rmuser'+filename) comes to mind, but will FreeBSD accept such commands from a script running as a cronjob? I will post the incomplete script on the tinylist site. Click THIS http://www.tinylist.org/abandontest.txt to view it. Please keep in mind this script is untested as of yet and can use LOTS of work, and I welcome advice. As always, it is COPIOUSLY commented. -- Respectfully, Kirk D Bailey, Pinellas county Florida USA think http://www.tinylist.org/ - $FREE$ Liberating software +-------+ http://www.pinellasintergroupsociety.org/ - NeoPagan | BOX | http://www.listville.net/ - $FREE$ list hosting! +-------+ http://www.howlermonkey.net/ - $FREE$ email Accounts kniht http://www.sacredelectron.org/ - My personal site From alan.gauld at blueyonder.co.uk Sun Apr 18 03:25:21 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Apr 18 03:25:01 2004 Subject: [Tutor] Web app in Python: alternatives to CGI? References: Message-ID: <044e01c42516$4edfbb10$6401a8c0@xp> > Well, it's submit the form, capture the data; based on the data, figure > out what additional data is needed, and then submit another form and > capture the data; based on that data, figure out what additional data is > required, etc. Sure, but usually by thinking through the logic you can collapse it to two forms max. And there is nothing more annoying than an application that requires you to go through a heap of little forms so it helps your user too. For example its usually better to capture some irrelevant data than to present more forms... > For example, if the work was published prior to 1978, the date of the > author's death is not needed, so I don't want to ask it. Similarly, if > the work was created after 1977, the date of publication is irrelevant, so > I don't want to ask. > > So I'll ask something like: > > Was the work: > () published in 1977 or earlier; > () created in 1978 or later; > () created in 1977 or earlier, but not published prior to 1978; > () don't know. > > Then if the user selected "published in 1977 or earlier", the next screen > would ask "what's the date of publication"; but if he sleected "created in > 1978 or later," the next screen would ask "is the author still alive"; if > the third, it would go on to ask if the work was ever published. Or just combine all that in one screen. Actually there's no harm in just getting them to fill in the date regardless - then you can figure out when it was published and which rules apply - much less hassle for the user. Especially if you use a drop down list which includes a "Not Published" option... In fact looking at your list above I'd suggest you jave two drop down lists, one for creation date and one for published date. Then you can figure out the right permutation easily and the user And ask if the author is still alive regardless of date. And if dead the date of death. You can use GUI design tricks to break the form into visual sections too. That is much faster for the user (no network waits), and easier for you to process. > So it's not just one CGI process. I need to save status from call to > call; cookies or something I guess. That's what I meant by Usually you just pass a hidden data member as part of the form data which is some kind of encoded string capturing all data up till now. > > And the country... If you are putting it on the web you may > > have users from many countries accessing it. Something to > > consider - even if its only with a US only disclaimer... > > This is US only. Yes, but if its on the internet (as opposed to the intranet) other countries will access it. One of my pet peeves is the number of US sites that assume that only US folks will use them, but don't tell you that their data is US specific! And I don't know why, but it seems to be only US sites that do this! In other words its not a matter of who the targetted audience is but where the site is hosted. If its an intranet then US only is fine, if its on the internet it should cater for non US users too - at least by saying its only intended for the US! Alan G. From magnus at thinkware.se Sun Apr 18 03:48:02 2004 From: magnus at thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sun Apr 18 03:59:45 2004 Subject: [Tutor] Re: Web app in Python: alternatives to CGI? In-Reply-To: References: Message-ID: <5.2.1.1.0.20040418092005.024973d0@www.thinkware.se> At 20:22 2004-04-17 -0700, Terry Carroll wrote: >Thanks. I should mention, it's not my web server, it's my ISP's. I've >never looked much into Zope or Twisted; can I install and use them without >being sysadmin? Even if you could, I doubt that your ISP will allow you to have long running processes on the web server, so you're probably stuck with CGI scripts. See http://www.python.org/cgi-bin/moinmoin/PythonHosting for Python friently ISPs. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From orbitz at ezabel.com Sun Apr 18 12:20:43 2004 From: orbitz at ezabel.com (orbitz@ezabel.com) Date: Sun Apr 18 12:21:45 2004 Subject: [Tutor] Re: Web app in Python: alternatives to CGI? In-Reply-To: References: Message-ID: <20040418122043.2ef3721d.orbitz@ezabel.com> You could always run the services on your own computer, atleast just to get an idea of how they all work. I run a twisted server on my computer and it works out well. I just signed up for one of those dynamic dns services so people can access it. For web applications in twisted I'd suggest checking out nevow: http://divmod.org/Home/Projects/Nevow/ On Sat, 17 Apr 2004 20:22:22 -0700 (PDT) Terry Carroll wrote: > On Sat, 17 Apr 2004, Lee Harr wrote: > > > You should look at Zope and Twisted (with nevow). > > Thanks. I should mention, it's not my web server, it's my ISP's. I've > never looked much into Zope or Twisted; can I install and use them without > being sysadmin? > > (I'm a minority user by using Python for CGI, I think, so I won't have > any luck getting my sysadmin to install something new for one app of one > user. We're running Python 2.1, and Ive managed to get installing 2.3 on > his to-do list, but it's a very low priority. I ended up installing my > own copy.) > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From jb at riseup.net Sun Apr 18 13:09:30 2004 From: jb at riseup.net (jb) Date: Sun Apr 18 13:13:04 2004 Subject: [Tutor] automatic account destruction In-Reply-To: <40821B7C.3080007@netzero.net> References: <40821B7C.3080007@netzero.net> Message-ID: <20040418170930.GA9462@mubai.sakeos.net> On Sun, Apr 18, 2004 at 02:09:00AM -0400, Kirk Bailey wrote: > I give people free email accounts. From time to time, I have the task > of searching for abandoned accounts and removing them, which is a time > consuming chore. This is a bother, world class. So I am building a > script which opens the first line of every email popbox and extracts > the first line. This is formatted as: > "From idiot1@netzero.net Fri Nov 9 00:30:27 2001" > (quotemarks mine, not found in data) > and I must crunch as needed to turn it into SECONDS SINCE THE EPOCH. you can use the os.stat function to do something similar (with the st_ctime field) without reading the file. st_ctime is in seconds since the epoch, if i remember correctly. > I then add a magic number to it (the number of seconds in 2 months), > and compare it to NOW. If that sum is smaller than NOW, the message is > VERY OLD, and we assume the account is abandoned, and delete it. We > repeat this loop for every popbox in the directory, which contains > nothing else BUT mailboxes, glob.glob('*.') to the rescue here. > > This script is still in alpha stage, but I thought the list may find > the process to do this crunching intresting. > > I am unsure how to have a script run a su function. Sure, > os.system('rmuser'+filename) > comes to mind, but will FreeBSD accept such commands from a script > running as a cronjob? if you really want that you can run such a script in root' crontab, or use sudo and a (NOPASSWD) option. however, running rmuser automatically seems a bit scary! i would advocate the use of a confirmation step somewhere in this process :) > I will post the incomplete script on the tinylist site. Click THIS > http://www.tinylist.org/abandontest.txt > to view it. > > Please keep in mind this script is untested as of yet and can use LOTS > of work, and I welcome advice. As always, it is COPIOUSLY commented. > From bvande at po-box.mcgill.ca Sun Apr 18 14:00:51 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sun Apr 18 14:02:49 2004 Subject: [Tutor] Re: working code for adding line numbers -- request for criticism In-Reply-To: References: <40818BFB.9020007@po-box.mcgill.ca> Message-ID: <4082C253.30203@po-box.mcgill.ca> Hi All, thanks to Alan and Andrei for the feedback. (And to Llyod from a previous reply and to those who wrote me off-list, too!) I'm consolidating responses to Andrei and Alan into one post. Replies interspersed below. There are a couple of places where I don't quite understand and have asked follow-ups. But I do apologize that this is getting to be a l_o_n_g post. :-( > Brian van den Broek wrote on Sat, 17 Apr 2004 15:56:43 -0400: > > >>I've found that traceback errors identified by line numbers can be tricky to >>track down without line number indications in the code or the editor. (IDLE >>doesn't seem to provide for line numbers, and it's no fun counting line on >>screen in a long file.) So, I wrote a script to take a file and output a file > Andrei: > > Tip: I don't use/know a lot about Idle, but other editors (like SciTE) show > the numbers AND allow you double-click on the line number in the traceback > to jump directly to the offending line. Alan: > > FWIW IDLE has a "Go To Line" menu option (Alt+G) which takes you to > the line you need. > > > But it's a good enough idea since notepad users (why???) > can use it. > The IDLE tip makes the whole thing largely moot, but it was worthwhile to do for the learning anyway. Plus, I can imagine other situations where I might use it, so no effort wasted. As for why Notepad -- well, Bill invented computers, right? (Just after the wheel and fire.) So Notepad must be the best editor after all! ;-) Andrei: >>running. Also, it is likely OS specific to DOS/Windows. That's what I run (for >>now) and what I can test on. > > > If you code this kind of stuff properly, it will generally be > cross-platform without you even thinking about it :). I was mostly thinking about the lines: else: dirname = os.path.dirname(tfilename).capitalize() # Capitalize ensures that drive letter displays in DOS convention target = (tfile_base, dirname) print 'Your numbered file will be %s in the directory %s' %target Since the user could type "c:\myfile.txt" without that .capitalize() method the dirname came out as "c:". Forcing it to be "C:" seemed the part specific to DOS/Win systems. (I don't know the Lin/UNix drive conventions, but Alan pointed out in a previous post that something I was doing was DOS drive convention centered.) But that is a small thing. One factor that made me pick Python to try and learn programming was the frequent claim of ease of cross-platform coding. I've been to two install-fests and have yet to come away with a working Linux install on my laptop :-( , but I hope to be free soon :-), and definitely didn't want my early steps in programming to be Win-centric. Alan: >>fil_numberede. I can see how to fix that (by constructing the output >>filename differently depending on whether the filename contains a >>'.' or not, but it didn't seem worth doing. > > > Or put "numbered_" in front instead: > > numbered_file.txt That would be easier, and I thought about it. But in a directory with a lot of files it would make the original and the processed file be far away from each other in a directory listing. I will think about which inconvenience is more important to me. Andrei: > > >>def get_filename(): >> f = raw_input('What file would you like to process? \n \ >> (Specify a full path if it is not in the current working directory) \n') >> # This makes for ugly screen output. How can I left allign the output >> # without breaking the function def's indetation? > > > Tip 2: have a look at the discusion started by Adam, with the title "Why is > this write defined as tuple...", it contains some useful tips about > building strings that you should find helpful. More the the point: you > could either A) use print to write the string in pieces or B) make a list > of string pieces and join them like this: > > message = ["What file blabla", > "More text here (will be on a new line)", > "Third line"] > f = raw_input("\n".join(message)) > > In your case, I'd opt for printing the message in pieces. Triple-quoting > the string is also an option, but that breaks the indentation visually, > which I think would be a pity in this case. I like the join suggestion. I'd originally tried the triple quote but didn't like the loss of visual indent either. Since I posted, I've changed it to triple quote assignments outside the function definition, but the join is nice in that it lets the indent be respected and function-specific text stay within the function. Thanks! Andrei: > > >> try: >> m = int(m) >> if m > 0: return m >> else: >> print o; return default > > > I don't like the way you wrote this. It's not customary to have more than > one statement on a single line. In fact, at first I didn't even notice > there was a return in the else, I just saw "print" and thought that o and a > bunch of other stuff will be printed. I'd also recommend being consistent > in the way you indent code, so IMO the best thing is to always have a > newline + indentation after a ":". >> except: >> print o; return default > > > Same here with the ";". New lines are cheap, so use them :). I'd thought it the multiple statements on a line OK for simple statements and a good thing in that more code could be seen on the screen at once. But the fact that on a first read someone with much more Python experience than I missed the else clause's return makes me think that in a few months I'd likely miss it too. So, no more multiple statement lines for me! Thanks. Andrei: > > >>sfilename = get_filename() >># 'sfilename', etc. for source file name, etc. >># Likewise for 'tfilename' and taget file name. >>print >>while os.path.isfile(sfilename) == False: >> print "I'm sorry, but you have specified a non-existent file path.\ >> Please try again. (You can press CTRL-C to end if you prefer)" >> sfilename = get_filename() > > > You should initialize loop variables immediately above the loop (for > readability). In this case you have the initialization, then some > distraction in the form of comments and a print and only after that the > loop starts. I absolutely see the point with respect to the print statement. But I wonder then where to put the comments on the variable names. I put them there as that is where the "sfilename" is defined and I thought that a longer, more self-documenting name such as "source_filename" would be getting too long. (I don't recall if it was this variable or another, but I do know I ended up shortening some names so as to more easily live with 80 character lines.) So, where to document the name? Above its first use seems odd to me. Is that the normal Python-practice? If so, I'll get over seeing it as odd :-) Andrei: > That's ugly :). I was surprized when I came across the else, already having > forgotten about the if, given the fact that the indentation seemed to jump > back to 0. Better: > > if os.path.dirname(tfilename) == '': # no directory specified > dirname = os.getcwd() # file in current directory > else: > dirname = os.path.dirname(tfilename).capitalize() # DOS-style > > Why don't you use the DOS-style when getcwd() is used? As for the ugly, you've convinced me. :-) But in the last line quoted above, I'm not sure what you mean. It seemed to me that os.getcwd() did return a capitalized drive letter and the only time I didn't have a CAPped drive was when the user input was of the from "d:\path\file" where 'd' is an small-case valid drive letter. (IOW, getcwd().capitalize() seemed redundant.) Have I missed your point? Andrei: > Neat trick (uses the knowledge that Python regards empty > strings/lists/tuples as "False" in a boolean context and that "" or "b" > returns "b" while "a" or "b" returns "a"): > > dirname = os.path.dirname(tfilename) or os.getcwd() > dirname = dirname.capitalize() Much cooler than what I had! Thanks. Andrei: >>tfile = file(tfilename, 'w') >>i = 1 >>for line in sfile: >> if i%multiple == 0 and line[-1] == '\n': >> line = line[:-1] + ' # ' + str(i) + '\n' >> if i%multiple == 0 and line[-1] != '\n': >> line = line + ' # ' + str(i) >> tfile.write(line) >> i = i + 1 > > > I'd dump the line[-1] condition and use rstrip() to get rid of any chars at > the end. By the way, I'd also put line numbers at the beginning of the line > instead of at the end. Format strings would help readability here. I don't (as yet) follow the rstrip() suggestion, but I will have a look and post again if I don't clear it up for myself. The line numbers at the front is how I did it at first. But unless I miss your meaning, it seemed a bad idea. Consider: def some_function: first line here if some condition: third line here fourth line here fifth line here assuming that the def line was the first line of the file (not likely, but its an e.g. :-) ) and every 5 lines were numbered, this would get rendered something like: def some_function: first line here if some condition: third line here # 5 fourth line here fifth line here That would, I think, make it harder for me to process what belonged to what block. Anyway, thanks again to all who've advised. I've learned a fair bit and been talked out of a few bad practices before they became habitual. A good result! Best, Brian vdB From harm.kirchhoff at web.de Sun Apr 18 21:04:36 2004 From: harm.kirchhoff at web.de (Harm Kirchhoff) Date: Sun Apr 18 21:07:29 2004 Subject: [Tutor] Encoding in non ASCII Message-ID: <408325A4.8050902@web.de> Probably many will not be able to read all of the following code: I am running Python on a Japanese Windows 2000 machine, whenever I want to open a file path that contains Japanese characters (such as the Desktop, which is spelled in Japanese, python fails.) I have been looking for code examples how to choose the best encoding but could not find enlightment. Does anybody (may be a Japanese colleague, have a hint ?) >>> f=open("C:\Documents and Settings\Kirchhoff\??????\test.txt",'r') Traceback (most recent call last): File "", line 1, in ? f=open("C:\Documents and Settings\Kirchhoff\??????\test.txt",'r') IOError: [Errno 2] No such file or directory: 'C:\\Documents and Settings\\Kirchhoff\\\x83f\x83X\x83N\x83g\x83b\x83v\test.txt' >>> From pythonTutor at venix.com Sun Apr 18 21:55:21 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Sun Apr 18 21:55:35 2004 Subject: [Tutor] automatic account destruction In-Reply-To: <20040418170930.GA9462@mubai.sakeos.net> References: <40821B7C.3080007@netzero.net> <20040418170930.GA9462@mubai.sakeos.net> Message-ID: <1082339720.2139.57.camel@laptop.venix.com> On Sun, 2004-04-18 at 13:09, jb wrote: > On Sun, Apr 18, 2004 at 02:09:00AM -0400, Kirk Bailey wrote: > > I give people free email accounts. From time to time, I have the task > > of searching for abandoned accounts and removing them, which is a time > > consuming chore. This is a bother, world class. So I am building a > > script which opens the first line of every email popbox and extracts > > the first line. This is formatted as: > > "From idiot1@netzero.net Fri Nov 9 00:30:27 2001" > > (quotemarks mine, not found in data) > > and I must crunch as needed to turn it into SECONDS SINCE THE EPOCH. > > you can use the os.stat function to do something similar (with the st_ctime > field) without reading the file. st_ctime is in seconds since the epoch, if > i remember correctly. > > > I then add a magic number to it (the number of seconds in 2 months), > > and compare it to NOW. If that sum is smaller than NOW, the message is > > VERY OLD, and we assume the account is abandoned, and delete it. We > > repeat this loop for every popbox in the directory, which contains > > nothing else BUT mailboxes, glob.glob('*.') to the rescue here. > > > > This script is still in alpha stage, but I thought the list may find > > the process to do this crunching intresting. > > > > I am unsure how to have a script run a su function. Sure, > > os.system('rmuser'+filename) > > comes to mind, but will FreeBSD accept such commands from a script > > running as a cronjob? > > if you really want that you can run such a script in root' crontab, or > use sudo and a (NOPASSWD) option. however, running rmuser automatically > seems a bit scary! i would advocate the use of a confirmation step > somewhere in this process :) > > > I will post the incomplete script on the tinylist site. Click THIS > > http://www.tinylist.org/abandontest.txt > > to view it. > > > > Please keep in mind this script is untested as of yet and can use LOTS > > of work, and I welcome advice. As always, it is COPIOUSLY commented. > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From pythonTutor at venix.com Sun Apr 18 22:30:12 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Sun Apr 18 22:30:25 2004 Subject: [Tutor] Re: working code for adding line numbers -- request for criticism In-Reply-To: <4082C253.30203@po-box.mcgill.ca> References: <40818BFB.9020007@po-box.mcgill.ca> <4082C253.30203@po-box.mcgill.ca> Message-ID: <1082341811.2139.80.camel@laptop.venix.com> One more remark about strings in source code. Successive string literals in python source are automatically concatenated. s = "abc" "def" # results in "abcdef" The successive string literals can be on different lines either by using the line continuation (\ at end of the line) or because the strings are in a bracketed expression and python will automatically continue the lines s = ("abc" "def") # also results in "abcdef" I usually rely on this feature when writing long SQL statements. On Sun, 2004-04-18 at 14:00, Brian van den Broek wrote: > Hi All, (snipped) > Best, > > Brian vdB > > > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From dtalaga at novodynamics.com Mon Apr 19 08:29:09 2004 From: dtalaga at novodynamics.com (David Talaga) Date: Mon Apr 19 08:28:49 2004 Subject: [Tutor] deleting CR within files In-Reply-To: <03f901c424b4$cffcf030$6401a8c0@xp> Message-ID: Ok, so now I am extremely close! It is now deleting al of the character returns instead of leaving just one. I tried to put an argument in there but as it is defined there can only be a string in write. I am not to sure where to go next. I am playing around with the other string manipulation options but don't know where to add that I need to keep 1 David Talaga -----Original Message----- From: Alan Gauld [mailto:alan.gauld@blueyonder.co.uk] Sent: Saturday, April 17, 2004 3:47 PM To: David Talaga; Roger Merchberger; tutor@python.org Subject: Re: [Tutor] deleting CR within files > for i in in_file: > out_file.write(i[:]) > > This does what I need with the excpetion that it dosent do it for every > line. It is currous because it will take off a from one line and not > the next 2 and then from another line... currious... Are you sure thats not the origoinal data? Try using the strip function since it will only strip off if there is anything to strip so should work in all cases. ie. out_file.write(i.strip()) HTH, Alan G From project5 at redrival.net Mon Apr 19 09:15:42 2004 From: project5 at redrival.net (Andrei) Date: Mon Apr 19 09:16:00 2004 Subject: [Tutor] Re: Re: working code for adding line numbers -- request for criticism References: <40818BFB.9020007@po-box.mcgill.ca> <4082C253.30203@po-box.mcgill.ca> Message-ID: Brian van den Broek wrote on Sunday 18 April 2004 20:00: >> If you code this kind of stuff properly, it will generally be >> cross-platform without you even thinking about it :). > I was mostly thinking about the lines: > else: dirname = os.path.dirname(tfilename).capitalize() Ah, you're right, changing caps on non-Windows systems isn't a great idea. I would avoid manipulation file names for frivolous reasons - it breaks cross-platformness and doesn't really gain you anything. > Since the user could type "c:\myfile.txt" without that .capitalize() > method the dirname came out as "c:". Forcing it to be "C:" seemed the part Is C really standard notation on Windows? I don't tend to type caps in command lines and such to be honest. I've noticed in other people's code that lowercase tends to be used for drives even if Explorer shows uppercase names. Ah well, I don't think anyone would be confused by seeing "c:" instead of "C:", since humans aren't case-sensitive. > specific to DOS/Win systems. (I don't know the Lin/UNix drive conventions, > but Alan pointed out in a previous post that something I was doing was DOS > drive convention centered.) But that is a small thing. *nix doesn't have drives :), everything is a directory. The CD-ROM is something along the lines of /mnt/cdrom (with / being the root of the file system). A directory can be on any drive on *nix, the user doesn't know nor care where exactly it's located when using the OS. In that respect all directories are like "My Documents" in Windows, which appears to be a top-level directory but is actually hidden somewhere in "c:\Documents and settings". > install-fests and have yet to come away with a working Linux install on my > laptop :-( , but I hope to be free soon :-), and definitely didn't want my > early steps in programming to be Win-centric. Ah, you must have come across some of those problems with Win-only hardware. Used to have a modem and soundcard like that. I'm a Linux newbie, but what I've noticed is that distro's get better at hardware detection all the time. Everything works for me now (didn't 1 year ago), except that I can't get my printer to work (attached to a router/printer server which the manufacturar - SMC - so far refuses to support under Linux, even though the machine shouldn't have anything platform-specific about it). > I'd thought it the multiple statements on a line OK for simple statements > and a good thing in that more code could be seen on the screen at once. I avoid multiple statements on the same line like the plague. Not just in Python, but in any language. I only use them e.g. when using the timeit module, or when I post a code sample and need to do some initializations first which are not relevant to the sample itself, but never in real code. > I absolutely see the point with respect to the print statement. But I > wonder then where to put the comments on the variable names. I put them I try to put short comments at then end of the line, long comments as docstrings to a method. But I'll get back to this topic below. > there as that is where the "sfilename" is defined and I thought that a > longer, more self-documenting name such as "source_filename" would be > getting too long. (I don't recall if it was this variable or another, but I agree there :). I don't quite agree with your choice of abbreviation (the "source" part is IMO more important than the "filename" part, yet the "source" is abbreviated to one letter, while the other part remains intact. I'd rather use something like "sourcefn"/"source"/"sourcefile" than "sfilename", but it's not that bad - it would be bad if you'd named it "x" or something :)). This point is related to comments, since good variable names prevent the need for some comments. The line "source = getfilename()" makes it immediately clear that source is a file name of a source file, there's no need to comment the obvious - unless of course the getfilename method doesn't do what its name suggests :). One could argue that variable names which need comment to be explained aren't good names, but I'm not sure that's true in all cases :). >> dirname = os.getcwd() # file in current directory > But in the last line quoted above, I'm not sure what you mean. It seemed > to me that os.getcwd() did return a capitalized drive letter and the only Oh, well, if that's the case, you're right. I had no idea what kind of caps getcwd() returns. > The line numbers at the front is how I did it at first. But unless I miss > your meaning, it seemed a bad idea. Consider: > assuming that the def line was the first line of the file (not likely, but > its an e.g. :-) ) and every 5 lines were numbered, this would get rendered > something like: > > def some_function: > first line here > if some condition: > third line here > # 5 fourth line here > fifth line here > > That would, I think, make it harder for me to process what belonged to > what block. You're right, it would. But I could give you a counter-argument: def some_function: some very long line doing interesting things # comment some other long line doing other stuff # comment # 3 and another line with statements # comment That #3 will not jump at you like it would at the start of the line, and even less if you view the file in a syntax coloring editor. So instead, here's an elegant solution with the best of both worlds :): indent ALL lines by say 5 spaces, but only add numbers in front of those where numbers are required. Adjust the numbers to make sure that the number plus trailing/leading spaces equals 5 characters. This would make your code look like this: def some_function: 2 ??? ?first?line?here ?????if?some?condition: 4?? ? ?????third?line?here ?????fourth?line?here 6??? ?fifth?line?here Format strings are useful for this purpose. -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From dtalaga at novodynamics.com Mon Apr 19 09:57:47 2004 From: dtalaga at novodynamics.com (David Talaga) Date: Mon Apr 19 09:57:29 2004 Subject: [Tutor] deleting CR within files In-Reply-To: <03f901c424b4$cffcf030$6401a8c0@xp> Message-ID: Is there such a thing as a do loop in Python? Like, do this until this is done. In my program I have a simple widget and need to initiate it before my dialog pops up. And then give the user the option to select more files with the same widget. I know that I need to use some kind of loop and in VB a do loop would work best. But what about in Python? David Talaga -----Original Message----- From: Alan Gauld [mailto:alan.gauld@blueyonder.co.uk] Sent: Saturday, April 17, 2004 3:47 PM To: David Talaga; Roger Merchberger; tutor@python.org Subject: Re: [Tutor] deleting CR within files > for i in in_file: > out_file.write(i[:]) > > This does what I need with the excpetion that it dosent do it for every > line. It is currous because it will take off a from one line and not > the next 2 and then from another line... currious... Are you sure thats not the origoinal data? Try using the strip function since it will only strip off if there is anything to strip so should work in all cases. ie. out_file.write(i.strip()) HTH, Alan G From py at gogol.humnet.ucla.edu Mon Apr 19 11:07:49 2004 From: py at gogol.humnet.ucla.edu (peter hodgson) Date: Mon Apr 19 11:07:56 2004 Subject: [Tutor] dicey slices Message-ID: <200404191507.i3JF7nnh028260@nightshade.noc.ucla.edu> Hi. Thanks for being here. I'm weighing in on an earlier discussion about indexing. ## here's what a tutorial says: SLICES and indeces: The best way to remember how slices work is to think of the indices as pointing between characters, with the left edge of the first character numbered 0. Then the right edge of the last character of a string of n characters has index n, for example: +---+---+---+---+---+ | H | e | l | p | A | +---+---+---+---+---+ 0 1 2 3 4 5 - - -5 -4 -3 -2 -1 ## here's what i infer; does it compute? thanks again; peter i.e: each char's index takes the number of the LEFT side of the space occupied by the character, ASCENDING [n] or DESCENDING [-n] / 1 / 2 / 3 / 4 / 5 / 0 1 2 3 4 5 - - -5 -4 -3 -2 -1 >>> s = '12345' >>> s[1] '2' >>> s[-1] '5' NB: index and slice "read" differently: s[n] names the char in the n+1th space, ascending >>> s[1], s[2], s[3] ('2', '3', '4') BUT: >>> s[1:3] '23' so we must type >>> s[1:4] '234' s[-n] names the char in the nth space, descending, >>> s[-4], s[-3], s[-2] ('2', '3', '4') BUT: >>> s[-4:-2] '23' so we must type >>> s[-4:-1] '234' thus, also >>> s[1:-1] '234' >>> s[-4:4] '234' so, for slices, s[X:X+n] yields a segment starting with the char in the (X+1)th space, but no including the char in the (X+n)th space; >>> t[2:4] '34' >>> t[2:6] '3456' TWO COUNTERINTUITIVE FEATURES EMERGE: 1/ negative indeces yield the [-]numbered char space; 2/ right-hand slice limits exclude the actual indexed char space; these features are manifest thus: a slice [X:-n] grabs UP TO the char which is n spaces from the end; but the slice [X:n] grabs UP TO the char which is n+1 spaces from the beginning; which yields the corollary: if len(s) == i: and if i % 2 == 1 then s[n] !== s[-n] [i.e., in a string with an odd number of items, char #n will never be the same as char #-n] >>> s[3], s[-3] ('4', '3') >>> t = '123456' >>> t[3], t[-3] ('4', '4') From dtalaga at novodynamics.com Mon Apr 19 11:24:06 2004 From: dtalaga at novodynamics.com (David Talaga) Date: Mon Apr 19 11:23:47 2004 Subject: [Tutor] deleting CR within files In-Reply-To: <03f901c424b4$cffcf030$6401a8c0@xp> Message-ID: To all concerned: Thank you so much for all the help! The project is done!! -----Original Message----- From: Alan Gauld [mailto:alan.gauld@blueyonder.co.uk] Sent: Saturday, April 17, 2004 3:47 PM To: David Talaga; Roger Merchberger; tutor@python.org Subject: Re: [Tutor] deleting CR within files > for i in in_file: > out_file.write(i[:]) > > This does what I need with the excpetion that it dosent do it for every > line. It is currous because it will take off a from one line and not > the next 2 and then from another line... currious... Are you sure thats not the origoinal data? Try using the strip function since it will only strip off if there is anything to strip so should work in all cases. ie. out_file.write(i.strip()) HTH, Alan G From bvande at po-box.mcgill.ca Mon Apr 19 11:30:09 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Mon Apr 19 11:32:01 2004 Subject: [Tutor] deleting CR within files In-Reply-To: References: Message-ID: <4083F081.1030107@po-box.mcgill.ca> David Talaga said unto the world upon 19/04/2004 09:57: > Is there such a thing as a do loop in Python? Like, do this until this > is done. In my program I have a simple widget and need to initiate it > before my dialog pops up. And then give the user the option to select > more files with the same widget. I know that I need to use some kind of > loop and in VB a do loop would work best. But what about in Python? > > David Talaga > Hi David, *warning* -- response from a newbie! Unless it has been added to Python since the versions for which the books I am reading was written, no, I don't think there is a do loop. But what about something like this pseudo-code: while 1: some stuff here if done condition is met: break Would this meet your needs? Best, Brian vdB From andy at andybak.net Mon Apr 19 12:02:47 2004 From: andy at andybak.net (Andy Baker) Date: Mon Apr 19 12:03:03 2004 Subject: [Tutor] Adding items to wxListControl Message-ID: This is driving me mad! This is from the examples folder: items = musicdata.items() for x in range(len(items)): key, data = items[x] self.list.InsertImageStringItem(x, data[0], self.idx1) self.list.SetStringItem(x, 1, data[1]) self.list.SetStringItem(x, 2, data[2]) self.list.SetItemData(x, key) X is a loop counter. What is self.idx1? What is the last line about! X and the key are the same so what is it doing? The wxDOcs say: wxListCtrl::SetItemData bool SetItemData(long item, long data) Associates application-defined data with this item. This is about as clear as mud to me! You are passing it two long's. What does the second long represent? I was getting on really well with Python until I started GUI programming. For a beginner there seems to be a real lack of clear docs on both wx and Tk. The general friendliness and quick learning curve of Python in general don't seem to be there when you move onto GUI programming From magnus at thinkware.se Mon Apr 19 12:08:36 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Mon Apr 19 12:08:49 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gZGljZXkgc2xpY2Vz?= Message-ID: > +---+---+---+---+---+ > | H | e | l | p | A | > +---+---+---+---+---+ > 0 1 2 3 4 5 > - - -5 -4 -3 -2 -1 This picture isn't quite right. The negative indices are wrong. It should be: > +---+---+---+---+---+ > | H | e | l | p | A | > +---+---+---+---+---+ > 0 1 2 3 4 5 > -5 -4 -3 -2 -1 E.g. >>> s = "HelpA" >>> s[4:5] 'A' >>> s[-2:-1] 'p' >>> s[-1:] 'A' There is no negative zero in Python, so there is no way to explicitly name the upper bound if you are using negative indices. For instance, you can do this: >>> for i in range(0,len(s),2): lower, upper = i, i+2 print lower, upper, s[lower:upper] 0 2 He 2 4 lp 4 6 A But trying to do the same trick with negative bounds won't work >>> for i in range(0,len(s),2): lower, upper = -i-2, -i print lower, upper, s[lower:upper] -2 0 -4 -2 el -6 -4 H See? The first line "ought" to have printed "-2 -0 pA", but there is no -0, and 0 is before the first position, not after the last. Actually, it just occurred to me that you can use s[-2:None] instead of s[-2:]. (Is this a documented feature or does it just happen to work?) This means that you can do: >>> for i in range(0,len(s),2): lower, upper = i or None, i+2 or None print lower, upper, s[lower:upper] None 2 He 2 4 lp 4 6 A >>> for i in range(0,len(s),2): lower, upper = -i-2 or None, -i or None print lower, upper, s[lower:upper] -2 None pA -4 -2 el -6 -4 H Yes! Our symmetry is back! -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From dtalaga at novodynamics.com Mon Apr 19 12:31:54 2004 From: dtalaga at novodynamics.com (David Talaga) Date: Mon Apr 19 12:31:34 2004 Subject: [Tutor] Adding items to wxListControl In-Reply-To: Message-ID: I feel ya. But hey, if you ever need a program to delete extra carriage returns I'm the man. I just spent about a week straight trying to figure that one out and now I am about where you are. I need to develop a list box that saves the files that I "cleaned" into a list box and I am starting all over... Again... -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org]On Behalf Of Andy Baker Sent: Monday, April 19, 2004 12:03 PM To: tutor@python.org Subject: [Tutor] Adding items to wxListControl This is driving me mad! This is from the examples folder: items = musicdata.items() for x in range(len(items)): key, data = items[x] self.list.InsertImageStringItem(x, data[0], self.idx1) self.list.SetStringItem(x, 1, data[1]) self.list.SetStringItem(x, 2, data[2]) self.list.SetItemData(x, key) X is a loop counter. What is self.idx1? What is the last line about! X and the key are the same so what is it doing? The wxDOcs say: wxListCtrl::SetItemData bool SetItemData(long item, long data) Associates application-defined data with this item. This is about as clear as mud to me! You are passing it two long's. What does the second long represent? I was getting on really well with Python until I started GUI programming. For a beginner there seems to be a real lack of clear docs on both wx and Tk. The general friendliness and quick learning curve of Python in general don't seem to be there when you move onto GUI programming _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From jtk at yahoo.com Mon Apr 19 13:34:14 2004 From: jtk at yahoo.com (Jeff Kowalczyk) Date: Mon Apr 19 12:32:07 2004 Subject: [Tutor] Not-quite-unicode string, how to convert to ascii? Message-ID: I have string input in some strange encoding, some editors (Win32 TextPad) pick it up as Unicode, linux gedit doesn't recognize the encoding and won't load it as utf-8. Python's encode('ascii') doesn't even alter the string. I can see that it is double byte, but which sub-encoding, I have no idea. Source reads ' Batch ' >>> f = open('input.txt','r') >>> s = f.read() >>> s[:20] ' \x00 \x00B\x00a\x00t\x00c\x00h\x00 \x00 \x00 \x00' I was almost tempted to just iterate over the raw string and remove '\x00' and leave it at that. The input files are about 180kb in size. Can anyone suggest a way to convert the DBCS input to plain ascii? Thanks. From jtk at yahoo.com Mon Apr 19 13:49:37 2004 From: jtk at yahoo.com (Jeff Kowalczyk) Date: Mon Apr 19 12:47:27 2004 Subject: [Tutor] Re: Not-quite-unicode string, how to convert to ascii? References: Message-ID: I figured it out, i needed to chain a decoding and encoding: >>> f = open('input.txt','r') >>> s = f.read() >>> s[:20] ' \x00 \x00B\x00a\x00t\x00c\x00h\x00 \x00 \x00 \x00' >>> s[:20].decode('utf-16') u' Batch ' >>> s[:20].decode('utf-16').encode('ascii') ' Batch ' From carroll at tjc.com Mon Apr 19 13:27:35 2004 From: carroll at tjc.com (Terry Carroll) Date: Mon Apr 19 13:27:39 2004 Subject: [Tutor] Web app in Python: alternatives to CGI? In-Reply-To: <044e01c42516$4edfbb10$6401a8c0@xp> Message-ID: On Sun, 18 Apr 2004, Alan Gauld wrote: > Sure, but usually by thinking through the logic you can collapse > it to two forms max. And there is nothing more annoying than an > application that requires you to go through a heap of little > forms so it helps your user too. I'd have to disagree with you there. I'd find it more annoying to be asked for information that's not necessary, especially if the information may be hard to find. I could have all the input on one page, heavily commented on what's skippable when, but then the input will be too overwhelming for the user. There are a couple other reasons why I want to do it step-by-step, too. First, if there is some information that's required but that the user doesn't have, I want to be able to give the best partial answer that I can, i.e., in terms of the missing information. That's easiest, I think, if I can walk through and stop at the first "don't know" response. Also, in addition to making the process available to the average person on the Internet, I intend for it to be usable as a training aid for law students, and a practice aid for practicing attorneys. I want them able to see the logic flow as it goes. > For example its usually better to capture some irrelevant data > than to present more forms... I'm probably not getting across very well the potential for just how much irrelevant data there will always be, and how difficult it may be to answer. For example, if someone wants to know when "House on Pooh Corner" goes PD, I don't want to ask when the author died, because it's not relevant. Now, this is a fairly trivial case, because A.A. Milne is a well-enough known author that his death can readily be looked up on the web. But if the work is, say, the orginale edition of "The Joy of Cooking," it's going to be a lot harder to find out whether and when Irma Rombauer has died. I'd rather not have the user go trying to find out that bit of trivia when it's not needed. Multiply that by several other pieces of data and I think you have a recipe for serious annoyance, enough to make the app unusable. > Or just combine all that in one screen. That's a gross oversimplification of the needed data. > > So it's not just one CGI process. I need to save status from call > to > > call; cookies or something I guess. That's what I meant by > > Usually you just pass a hidden data member as part of the form data > which is some kind of encoded string capturing all data up till now. Yeah,; that's what I meant by "hidden data." > Yes, but if its on the internet (as opposed to the intranet) > other countries will access it. One of my pet peeves is the > number of US sites that assume that only US folks will use them, > but don't tell you that their data is US specific! It will be clear that it's US only. That's a very good point, and I should have made it more clear that I agreed with you. Thanks for all your input. If I actually get this up and running, I'll post the link here. Terry Carroll Santa Clara, CA carroll@tjc.com Modell delendus est From carroll at tjc.com Mon Apr 19 13:29:23 2004 From: carroll at tjc.com (Terry Carroll) Date: Mon Apr 19 13:29:26 2004 Subject: [Tutor] Re: Web app in Python: alternatives to CGI? In-Reply-To: <5.2.1.1.0.20040418092005.024973d0@www.thinkware.se> Message-ID: On Sun, 18 Apr 2004, Magnus Lyck? wrote: > Even if you could, I doubt that your ISP will allow you to have > long running processes on the web server, so you're probably stuck > with CGI scripts. Great; that's what I needed to know. > See http://www.python.org/cgi-bin/moinmoin/PythonHosting for Python > friently ISPs. Ah, I love my ISP apart from the fact that I seem to be the only Python user. One hobbyist web app isn't worth moving my domain for. But thanks for the pointers. Terry Carroll Santa Clara, CA carroll@tjc.com Modell delendus est From andy at andybak.net Mon Apr 19 14:20:26 2004 From: andy at andybak.net (Andy Baker) Date: Mon Apr 19 14:20:28 2004 Subject: [Tutor] (no subject) Message-ID: > > You're completely correct. So when you're done writing your > WxPython tutorial, please send it to me, and I'll be more > than happy to proofread it. ;) > > Later, > Blake. > You wait! :-) As it turned out I was getting rather mixed up. I was getting mixed up. I remembered needing one command to set a new row and another to add an item to another column in that row. SetItemData was just a red herring. This is what I was looking for: self.list.InsertStringItem(row,string) self.list.SetStringItem(row, column, string) So I get the following: for i, row in enumerate(list): for j, item in enumerate(row): if j==0: self.list.InsertStringItem(i,item) else: self.list.SetStringItem(i, j, item) The conditional statement is there to set up the column on the first item and merely add a column to it after that. Does anyone know a more elegant way to do this? From denis.spir at free.fr Mon Apr 19 14:15:49 2004 From: denis.spir at free.fr (denis) Date: Mon Apr 19 14:37:39 2004 Subject: [Tutor] Re: Re: working code for adding line numbers -- request forcriticism References: <40818BFB.9020007@po-box.mcgill.ca><4082C253.30203@po-box.mcgill.ca> Message-ID: <000201c4263d$52d3f6a0$0225933e@spir> ----- Original Message ----- From: Andrei To: Sent: Monday, April 19, 2004 3:15 PM Subject: [Tutor] Re: Re: working code for adding line numbers -- request forcriticism > I agree there :). I don't quite agree with your choice of abbreviation (the > "source" part is IMO more important than the "filename" part, yet the > "source" is abbreviated to one letter, while the other part remains intact. > I'd rather use something like "sourcefn"/"source"/"sourcefile" than > "sfilename", but it's not that bad - it would be bad if you'd named it "x" > or something :)). > > This point is related to comments, since good variable names prevent the > need for some comments. The line "source = getfilename()" makes it > immediately clear that source is a file name of a source file, there's no > need to comment the obvious - unless of course the getfilename method > doesn't do what its name suggests :). > One could argue that variable names which need comment to be explained > aren't good names, but I'm not sure that's true in all cases :). I agree there too :-) Will just add that it's often useful to know what kind of object is hidden behind the variable name. e.g. in your 'source' may be (supposed you know it has something to do with a file !) the file object, the file name or the data themselves -- and you may well need the three of them in the same piece of code. To avoid confusion, I use type (in the usual sense, not technical) prefixing. In that case : fnSource or fn_source. I have a whole set of semi-standard prefixes. Some of them beeing doubled, like n- or nbr- for number (in the sense of a cardinal), i or num (french : num?ro) for an index (ordinal). But of course none has two meanings. It's easier in french cause the "typing" words naturally come before the "meaningful" words : "nom du fichier source" instead of "source file name". But you can think at it as "file name of the source". It may be strange but these prefixes don't lower the readibility -- once you know they're prefixes. I don't see them unless I need them. Probably the separations (capital letter or underscore) play their role properly. denis From denis.spir at free.fr Mon Apr 19 14:20:17 2004 From: denis.spir at free.fr (denis) Date: Mon Apr 19 14:37:46 2004 Subject: [Tutor] deleting CR within files References: Message-ID: <000501c4263d$53943960$0225933e@spir> Please use both of these great ideas : -1- type 'do', 'loop' or 'until' in the python standard help files' index -2- give your post an appropriate title salutation, denis ----- Original Message ----- From: David Talaga To: Alan Gauld ; Roger Merchberger ; Sent: Monday, April 19, 2004 3:57 PM Subject: RE: [Tutor] deleting CR within files > Is there such a thing as a do loop in Python? Like, do this until this is > done. In my program I have a simple widget and need to initiate it before > my dialog pops up. And then give the user the option to select more files > with the same widget. I know that I need to use some kind of loop and in VB > a do loop would work best. But what about in Python? From alan.gauld at blueyonder.co.uk Mon Apr 19 17:04:08 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Mon Apr 19 17:08:03 2004 Subject: [Tutor] deleting CR within files In-Reply-To: Message-ID: <196FAF2C-9245-11D8-B84D-0003937D2B12@blueyonder.co.uk> > Is there such a thing as a do loop in Python? There's a while loop which will do anything a do loop can, but... > done. In my program I have a simple widget and need to initiate it > before > my dialog pops up. And then give the user the option to select more > files > with the same widget. I think you are missing the point of event driven programming. When they press the widget it processes a file, if they press it again it processes another file, and so on. In other words you don't need a loop to do that. Or more to the point the Tk.mainloop() is the only loop you need. > I know that I need to use some kind of loop and in VB > a do loop would work best. But what about in Python? You shouldn't need a loop in VB either! Alan G. From zmerch at 30below.com Mon Apr 19 18:01:05 2004 From: zmerch at 30below.com (Roger Merchberger) Date: Mon Apr 19 18:00:36 2004 Subject: [Tutor] do: vs. while: (was: deleting CR within files) In-Reply-To: <196FAF2C-9245-11D8-B84D-0003937D2B12@blueyonder.co.uk> References: Message-ID: <5.1.0.14.2.20040419174654.04ac5428@mail.30below.com> Rumor has it that Alan Gauld may have mentioned these words: [[[ Dudez... I'm on the list, and I hopped out of this thread quite a while ago... ;-) ]]] >>Is there such a thing as a do loop in Python? > >There's a while loop which will do anything a do loop can, >but... Not quite. IIRC, in VB and some other basics, there are both do/until loops, and while/wend loops. The difference is this: while/wend loops are always evaluated at the beginning of the loop and run the "risk" of not get executing at all if the initial test is false; try this: while 0: print "You will never see this." whereas do/until loops are evaluated at the end and always execute, at least once, in pythonlike-parlance, it would look like this: do: print "you will see this anyway, even tho the test is false..." until 0 # Yes, I know this isn't python... it's an example, eh? As previously posted, if you *gotta have* the do/until functionality, just use a while 1: loop, and put your test at the bottom of the loop with a breakout, like this: while 1: print "You will see this once; maybe more depending on the test." if gitmeouttahere: break IMNSHO, I always thought having both a do/until and while/wend loop structures were overkill, as it was so easy to replicate one with the other... >>done. In my program I have a simple widget and need to initiate it before >>my dialog pops up. And then give the user the option to select more files >>with the same widget. > >I think you are missing the point of event driven programming. >When they press the widget it processes a file, if they press >it again it processes another file, and so on. > >In other words you don't need a loop to do that. Or more to >the point the Tk.mainloop() is the only loop you need. > >>I know that I need to use some kind of loop and in VB >>a do loop would work best. But what about in Python? > >You shouldn't need a loop in VB either! *unless* he's referencing a multi-selectable combo box - then you're both correct. He doesn't need a loop to work the main structure of the GUI, but he will need some form of loop to work each of the files that's been multi-selected. Of course, that's the beauty of "for eachfile in mycombobox:" ;-) As an aside, in VB, the "Tk.mainloop()" structure is implied - it's totally hidden from the user, so he may not understand why it's required in Python... Anywho, HTH and HAND... ;-) Roger "Merch" Merchberger -- Roger "Merch" Merchberger --- sysadmin, Iceberg Computers zmerch@30below.com Hi! I am a .signature virus. Copy me into your .signature to join in! From tpc at csua.berkeley.edu Mon Apr 19 18:41:54 2004 From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu) Date: Mon Apr 19 18:41:59 2004 Subject: [Tutor] Python dictionary element order Message-ID: <20040419151709.P58885-100000@localhost.name> hi everybody, I am confused about the default element order for keys of type string in Python dictionary. fruitlist = ['apple', 'grape', 'orange', 'pear', 'watermelon', 'mango'] eaten = {} while fruitlist: fruit = fruitlist.pop() if fruit not in eaten: eaten[fruit] = 1 eaten outputs {'grape': 1, 'apple': 1, 'pear': 1, 'mango': 1, 'watermelon': 1, 'orange': 1} When I input a list of numbers: numlist = [1, 2, 3, 4, 5, 6] numdict = {} while numlist: num = numlist.pop() if num not in numdict: numdict[num] = 'NULL' numdict outputs {1: 'NULL', 2: 'NULL', 3: 'NULL', 4: 'NULL', 5: 'NULL', 6: 'NULL'} I understand list.pop() outputs the last element in the list, so the dictionary element order indicated to me there was some kind of default sorting. The first element in eaten should be 'mango', or at the very least 'apple' if Python dictionaries by default sort keys of type string alphabetically. What is going on here ? From pythonTutor at venix.com Mon Apr 19 19:06:54 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Mon Apr 19 19:07:07 2004 Subject: [Tutor] Python dictionary element order In-Reply-To: <20040419151709.P58885-100000@localhost.name> References: <20040419151709.P58885-100000@localhost.name> Message-ID: <1082416014.3228.46.camel@laptop.venix.com> The ordering of keys and values retrieved from a dictionary is undefined. There is no requirement that keys or values support an ordering. For instance, they could be complex numbers. On Mon, 2004-04-19 at 18:41, tpc@csua.berkeley.edu wrote: > hi everybody, I am confused about the default element order for keys of > type string in Python dictionary. > > > fruitlist = ['apple', 'grape', 'orange', 'pear', 'watermelon', 'mango'] > eaten = {} > while fruitlist: > fruit = fruitlist.pop() > if fruit not in eaten: > eaten[fruit] = 1 > > eaten outputs > {'grape': 1, 'apple': 1, 'pear': 1, 'mango': 1, 'watermelon': 1, 'orange': > 1} > > When I input a list of numbers: > > > numlist = [1, 2, 3, 4, 5, 6] > numdict = {} > while numlist: > num = numlist.pop() > if num not in numdict: > numdict[num] = 'NULL' > > numdict outputs > {1: 'NULL', 2: 'NULL', 3: 'NULL', 4: 'NULL', 5: 'NULL', 6: 'NULL'} > > I understand list.pop() outputs the last element in the list, so > the dictionary element order indicated to me there was some kind of > default sorting. The first element in eaten should be 'mango', or at the > very least 'apple' if Python dictionaries by default sort keys of type string > alphabetically. > > What is going on here ? > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From denis.spir at free.fr Mon Apr 19 20:26:45 2004 From: denis.spir at free.fr (denis) Date: Tue Apr 20 08:19:34 2004 Subject: [Tutor] Python dictionary element order References: <20040419151709.P58885-100000@localhost.name> <1082416014.3228.46.camel@laptop.venix.com> Message-ID: <000201c426d1$aa06a8c0$6b27933e@spir> ----- Original Message ----- From: Lloyd Kvam To: Cc: Sent: Tuesday, April 20, 2004 1:06 AM Subject: Re: [Tutor] Python dictionary element order > The ordering of keys and values retrieved from a dictionary is > undefined. There is no requirement that keys or values support an > ordering. For instance, they could be complex numbers. Python's dicts use hash fuctions to boost the search of values. Below wikipedia's definition at http://en.wikipedia.org/wiki/Hash_table : *********** Hash table >From Wikipedia, the free encyclopedia. In computer science, a hash table is a data structure that implements an associative array. Like any associative array a hash table is used to store many key => value associations (this is a many to one relationship as the hash table is almost universally smaller than the number of keys). A hash table maintains two arrays, one for keys, one for values (or possibly one array of (key, value) pairs - it doesn't really matter). The elements of these arrays are referred to as buckets. When required to find the associated value for a given key, the key is fed through a hash function to yield an integer (called the hash value). This integer is then the index to the associated value. Commonly the hash value is calculated using modulo arithmetic, modulo a prime p (with a hash table of size p). *********** The hash function yields (small) integers because they're the easiest and fastest processed data type. These integers are then used as pointers to the searched data. When in a dictionary you precisely use (small ?) integer keys, I imagine that the hash values produced out of them will have the same sort order as the original integers. (morever, as the hash functions are based on modulo operations, if the integers are smaller than the table size, they may be simply let unchanged, or what ?). Well, this is just guessing. I got this from unsorted integer keys : >>> l=[3,4,1,5,2] >>> r={} >>> for i in l : r[i]=i >>> for k in r.keys() : print k, 1 2 3 4 5 salutation, denis PS : I find this list great. Thank you all. (Having these days a bit more time than usually, I try to answer -- for myself -- many of the questions : I learn much thanks to that and, above all, I discover more and more how much I didn't know !) > On Mon, 2004-04-19 at 18:41, tpc@csua.berkeley.edu wrote: > > hi everybody, I am confused about the default element order for keys of > > type string in Python dictionary. > > > > > > fruitlist = ['apple', 'grape', 'orange', 'pear', 'watermelon', 'mango'] > > eaten = {} > > while fruitlist: > > fruit = fruitlist.pop() > > if fruit not in eaten: > > eaten[fruit] = 1 > > > > eaten outputs > > {'grape': 1, 'apple': 1, 'pear': 1, 'mango': 1, 'watermelon': 1, 'orange': > > 1} > > > > When I input a list of numbers: > > > > > > numlist = [1, 2, 3, 4, 5, 6] > > numdict = {} > > while numlist: > > num = numlist.pop() > > if num not in numdict: > > numdict[num] = 'NULL' > > > > numdict outputs > > {1: 'NULL', 2: 'NULL', 3: 'NULL', 4: 'NULL', 5: 'NULL', 6: 'NULL'} > > > > I understand list.pop() outputs the last element in the list, so > > the dictionary element order indicated to me there was some kind of > > default sorting. The first element in eaten should be 'mango', or at the > > very least 'apple' if Python dictionaries by default sort keys of type string > > alphabetically. > > > > What is going on here ? > > > > > > > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > -- > > Lloyd Kvam > Venix Corp. > 1 Court Street, Suite 378 > Lebanon, NH 03766-1358 > > voice: 603-653-8139 > fax: 801-459-9582 > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From dtalaga at novodynamics.com Tue Apr 20 11:51:28 2004 From: dtalaga at novodynamics.com (David Talaga) Date: Tue Apr 20 11:51:06 2004 Subject: [Tutor] Tkinter dilemas Message-ID: I am working with Tkinter and trying to create a box that has three buttons (in the Open() function) and these buttons seem to not work. I am wondering what I am doing wrong. Here is all of the code but I think that the problem lies within the Open function. The first window pops up upon running the program but there is nothing in the window. Can you help!!! #Created by dtalaga for Novo Dynamics import os from Tkinter import * import tkFileDialog import sys import re import Tkinter #--------------------------------------------------------------------------- ------------ #Define all variables global root root=Tk() result = 0 sub = re.sub #--------------------------------------------------------------------------- ------------ # define the dialog function to call the dialog box def dialog(): root.withdraw() initDir = 'C:/windows/desktop' filetype = [('All files', '.*')] fileName = tkFileDialog.askopenfilename(initialdir=initDir, filetypes=filetype) return fileName #--------------------------------------------------------------------------- ------------ #Define the doDialog function. Uses the dialog function from another file def doDialog(): global result result = dialog() #--------------------------------------------------------------------------- ------------ #Define the List function that displays the list of "cleaned" files def Open(): f = Tkinter.Button(root, text = "Find Files", command = Clean) f.pack() l = Tkinter.Button(root, text = "View List", command = List) l.pack() x = Tkinter.Button(root, text = "Exit", command = sys.exit) x.pack #--------------------------------------------------------------------------- ------------ #Define function List to be used in the Open() function. def List(): S = Tkinter.Scrollbar() L = Tkinter.Listbox() S.pack(side = Tkinter.RIGHT, fill = Tkinter.Y) L.pack(side = Tkinter.LEFT, fill = Tkinter.Y) S.config(command = L.yview) L.config(yscrollcommand = S.set) #--------------------------------------------------------------------------- ------------ #Define function Clean. Clean will take the files and clean them def Clean(): if f: fileName = dialog() in_file = open(fileName,'r').readlines() out_file = open(fileName + '_cleaned.txt', 'w') for i in in_file: tmp = sub('\x0D','', i) out_file.write(tmp) print 'File cleaned' if x: out_file.close() if l: List() print fileName #--------------------------------------------------------------------------- ------------ #Call the working functions #Open() #--------------------------------------------------------------------------- ------------ #Make the path where the cleaned files will be stored if os.path.isdir("C:\\Cleaned_Files"): print "C:\\Cleaned_Files exists" else: os.mkdir("C:\\Cleaned_Files") #--------------------------------------------------------------------------- ------------ root.mainloop() David Talaga dtalaga@novodynamics.com 734-205-9127 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040420/be0e36e6/attachment.html From Chad.Crabtree at nationalcity.com Tue Apr 20 12:42:01 2004 From: Chad.Crabtree at nationalcity.com (Crabtree, Chad) Date: Tue Apr 20 12:42:22 2004 Subject: [Tutor] Tkinter dilemas Message-ID: <66F587DFDD46D511B65200508B6F8DD612B993F6@nt-kalopsapp07.ntl-city.com> -----Original Message----- From: David Talaga [mailto:dtalaga@novodynamics.com] Sent: Tuesday, April 20, 2004 11:51 AM To: Python Tutor Subject: [Tutor] Tkinter dilemas I am working with Tkinter and trying to create a box that has three buttons (in the Open() function) and these buttons seem to not work. I am wondering what I am doing wrong. Here is all of the code but I think that the problem lies within the Open function. The first window pops up upon running the program but there is nothing in the window. Can you help!!! #Created by dtalaga for Novo Dynamics import os from Tkinter import * import tkFileDialog import sys import re import Tkinter #--------------------------------------------------------------------------- ------------ #Define all variables global root root=Tk() result = 0 sub = re.sub #--------------------------------------------------------------------------- ------------ # define the dialog function to call the dialog box def dialog(): root.withdraw() initDir = 'C:/windows/desktop' filetype = [('All files', '.*')] fileName = tkFileDialog.askopenfilename(initialdir=initDir, filetypes=filetype) return fileName #--------------------------------------------------------------------------- ------------ #Define the doDialog function. Uses the dialog function from another file def doDialog(): global result result = dialog() #--------------------------------------------------------------------------- ------------ #Define the List function that displays the list of "cleaned" files def Open(): f = Tkinter.Button(root, text = "Find Files", command = Clean) f.pack() l = Tkinter.Button(root, text = "View List", command = List) l.pack() x = Tkinter.Button(root, text = "Exit", command = sys.exit) x.pack Right here you forgot to put the parenthesis on pack #--------------------------------------------------------------------------- ------------ #Define function List to be used in the Open() function. def List(): S = Tkinter.Scrollbar() L = Tkinter.Listbox() S.pack(side = Tkinter.RIGHT, fill = Tkinter.Y) L.pack(side = Tkinter.LEFT, fill = Tkinter.Y) S.config(command = L.yview) L.config(yscrollcommand = S.set) #--------------------------------------------------------------------------- ------------ #Define function Clean. Clean will take the files and clean them def Clean(): if f: fileName = dialog() in_file = open(fileName,'r').readlines() out_file = open(fileName + '_cleaned.txt', 'w') for i in in_file: tmp = sub('\x0D','', i) out_file.write(tmp) print 'File cleaned' if x: out_file.close() if l: List() print fileName #--------------------------------------------------------------------------- ------------ #Call the working functions #Open() When I uncommented Open() it ran and showed the buttons with the pack problem above it showed all buttons #--------------------------------------------------------------------------- ------------ #Make the path where the cleaned files will be stored if os.path.isdir("C:\\Cleaned_Files"): print "C:\\Cleaned_Files exists" else: os.mkdir("C:\\Cleaned_Files") #--------------------------------------------------------------------------- ------------ root.mainloop() David Talaga dtalaga@novodynamics.com 734-205-9127 Your clean method will not work. Look on activestate for a shim recipie so you can pass arguments with tkinter. Well I googled I know there is one on AS but here is a url for another page. Look this over you should be able to figure this out. I needed a similar thing in the past. http://www.astro.washington.edu/owen/TkinterSummary.html#CallbackShims Good luck ------------------------------------------------------------------------------------------- ***National City made the following annotations ------------------------------------------------------------------------------------------- This communication is a confidential and proprietary business communication. It is intended solely for the use of the designated recipient(s). If this communication is received in error, please contact the sender and delete this communication. =========================================================================================== -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040420/c56d1b9c/attachment.html From dtalaga at novodynamics.com Tue Apr 20 12:47:58 2004 From: dtalaga at novodynamics.com (David Talaga) Date: Tue Apr 20 12:47:38 2004 Subject: [Tutor] Tkinter dilemas In-Reply-To: <66F587DFDD46D511B65200508B6F8DD612B993F6@nt-kalopsapp07.ntl-city.com> Message-ID: Actually the clean method does. I am not to sure if it is not supposed to but that aspect of the progam is tested. And as far as the ). I found that out no big deal. I am an idiot :) what the problem is though now is that after I select a file to be cleaned, it cleans it and then i can not get back to the Open() function. I tried to call it from the bottom of the Clean() function ut still, nothing... Here is the new version of the program: (It is still in the works. tinkering around with it and al) import os import tkFileDialog import sys import re import Tkinter #--------------------------------------------------------------------------- ------------ #Define all variables global root root=Tkinter.Tk() result = 0 sub = re.sub #--------------------------------------------------------------------------- ------------ # define the dialog function to call the dialog box def dialog(): root.withdraw() initDir = 'C:/windows/desktop' filetype = [('All files', '.*')] fileName = tkFileDialog.askopenfilename(initialdir=initDir, filetypes=filetype) return fileName #--------------------------------------------------------------------------- ------------ #Define the doDialog function. Uses the dialog function from another file def doDialog(): global result result = dialog() #--------------------------------------------------------------------------- ------------ #Define the List function that displays the list of "cleaned" files def Open(): global f f = Tkinter.Button(root, text = "Find Files", command = Clean) f.pack() global l l = Tkinter.Button(root, text = "View List", command = List) l.pack() global x x = Tkinter.Button(root, text = "Exit", command = sys.exit) x.pack() #--------------------------------------------------------------------------- ------------ #Define function List to be used in the Open() function. def List(): S = Tkinter.Scrollbar() global L L = Tkinter.Listbox() S.pack(side = Tkinter.RIGHT, fill = Tkinter.Y) L.pack(side = Tkinter.LEFT, fill = Tkinter.Y) S.config(command = L.yview) L.config(yscrollcommand = S.set) os.chdir('C:\Cleaned_Files') Populate() #--------------------------------------------------------------------------- --------- #Define the function to populate the listbox def Populate(): if os.path.isfile('cleaned_files.txt'): print "cleaned_files.txt exists" else: file('cleaned_files.txt', 'a', 1) clean = open('cleaned_files.txt', 'r+') clean.write(fileName) clean.close() #--------------------------------------------------------------------------- --------- #Define the Clean function to clean the files def Clean(): if f: global fileName fileName = dialog() in_file = open(fileName,'r').readlines() out_file = open(fileName + '_cleaned.txt', 'w') for i in in_file: tmp = sub('\x0D','', i) out_file.write(tmp) print 'File cleaned' if x: out_file.close() if l: List() print fileName #--------------------------------------------------------------------------- ------------ #Call the working function Open() #--------------------------------------------------------------------------- ------------ #Make the path where the cleaned files will be stored if os.path.isdir("C:\\Cleaned_Files"): print "C:\\Cleaned_Files exists" else: os.mkdir("C:\\Cleaned_Files") #--------------------------------------------------------------------------- ------------ root.mainloop() -----Original Message----- From: Crabtree, Chad [mailto:Chad.Crabtree@nationalcity.com] Sent: Tuesday, April 20, 2004 12:42 PM To: 'David Talaga' Cc: 'tutor@python.org' Subject: RE: [Tutor] Tkinter dilemas -----Original Message----- From: David Talaga [mailto:dtalaga@novodynamics.com] Sent: Tuesday, April 20, 2004 11:51 AM To: Python Tutor Subject: [Tutor] Tkinter dilemas I am working with Tkinter and trying to create a box that has three buttons (in the Open() function) and these buttons seem to not work. I am wondering what I am doing wrong. Here is all of the code but I think that the problem lies within the Open function. The first window pops up upon running the program but there is nothing in the window. Can you help!!! #Created by dtalaga for Novo Dynamics import os from Tkinter import * import tkFileDialog import sys import re import Tkinter #--------------------------------------------------------------------------- ------------ #Define all variables global root root=Tk() result = 0 sub = re.sub #--------------------------------------------------------------------------- ------------ # define the dialog function to call the dialog box def dialog(): root.withdraw() initDir = 'C:/windows/desktop' filetype = [('All files', '.*')] fileName = tkFileDialog.askopenfilename(initialdir=initDir, filetypes=filetype) return fileName #--------------------------------------------------------------------------- ------------ #Define the doDialog function. Uses the dialog function from another file def doDialog(): global result result = dialog() #--------------------------------------------------------------------------- ------------ #Define the List function that displays the list of "cleaned" files def Open(): f = Tkinter.Button(root, text = "Find Files", command = Clean) f.pack() l = Tkinter.Button(root, text = "View List", command = List) l.pack() x = Tkinter.Button(root, text = "Exit", command = sys.exit) x.pack Right here you forgot to put the parenthesis on pack #--------------------------------------------------------------------------- ------------ #Define function List to be used in the Open() function. def List(): S = Tkinter.Scrollbar() L = Tkinter.Listbox() S.pack(side = Tkinter.RIGHT, fill = Tkinter.Y) L.pack(side = Tkinter.LEFT, fill = Tkinter.Y) S.config(command = L.yview) L.config(yscrollcommand = S.set) #--------------------------------------------------------------------------- ------------ #Define function Clean. Clean will take the files and clean them def Clean(): if f: fileName = dialog() in_file = open(fileName,'r').readlines() out_file = open(fileName + '_cleaned.txt', 'w') for i in in_file: tmp = sub('\x0D','', i) out_file.write(tmp) print 'File cleaned' if x: out_file.close() if l: List() print fileName #--------------------------------------------------------------------------- ------------ #Call the working functions #Open() When I uncommented Open() it ran and showed the buttons with the pack problem above it showed all buttons #--------------------------------------------------------------------------- ------------ #Make the path where the cleaned files will be stored if os.path.isdir("C:\\Cleaned_Files"): print "C:\\Cleaned_Files exists" else: os.mkdir("C:\\Cleaned_Files") #--------------------------------------------------------------------------- ------------ root.mainloop() David Talaga dtalaga@novodynamics.com 734-205-9127 Your clean method will not work. Look on activestate for a shim recipie so you can pass arguments with tkinter. Well I googled I know there is one on AS but here is a url for another page. Look this over you should be able to figure this out. I needed a similar thing in the past. http://www.astro.washington.edu/owen/TkinterSummary.html#CallbackShims Good luck -------------------------------------------------------------------------- ----------------- ***National City made the following annotations -------------------------------------------------------------------------- ----------------- This communication is a confidential and proprietary business communication. It is intended solely for the use of the designated recipient(s). If this communication is received in error, please contact the sender and delete this communication. ============================================================================ =============== -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040420/c25d5d26/attachment-0001.html From magnus at thinkware.se Tue Apr 20 13:55:00 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Tue Apr 20 13:55:26 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gVGtpbnRlciBkaWxlbWFz?= Message-ID: I fear that there is no really beginner-friendly way of writing GUI code in Python. Tkinter isn't great, but the other GUI tool kits are thin wrappers for C or C++ libraries where quirks caused by the underlying language shine through. We can't really compete with VB on the beginner level here... Will someone please write PyNewbieGui or VisualPython? David Talaga wrote: > global root > root=Tk() The global statement is meaningless here. Use global within a local scope to declare that a certain name in that (local) scope refers to a global variable. E.g: >>> x = "Hello" >>> def f(): global x x = 'Hi' >>> print x Hello >>> f() >>> print x Hi There is no way you can stop local variables overriding globals like you seem to be trying to do. On the other hand, you never assign to the name "root" in any local scope, so you don't need that anyway. As a general rule, try to avoid global variables. Your program is short but still seems messy to me. Maybe you can try to clean it up a bit. For instance, you use both "from Tkinter import *" and "import Tkinter". Why all of Tkinter in two scopes? For clarity, avoid using "from import *". You should also try to give all variables and functions good names. Try to spend some time thinking about that. It will make it easier for others to understand your code, and it might help you make it clear for yourself what the different parts of the program are really supposed to do. (If you can't think of a good name for a function or variable, it's likely that it's not a very good function or variable...) > import re .. > sub = re.sub .. > tmp = sub('\x0D','', i) Don't do that! Skip the middle step and do > import re .. > tmp = re.sub('\x0D','', i) A call to "re.sub" is meaningful to any experienced Python coder reading your code. Just "sub" means that he has to look in some other place in the code (remember that "real" programs get thousands of lines long) to figure out that your sub is simply the sub in the re module. Also, for a Python newbie reading "re.sub" it will be clear where to find out more about what the sub function does. > def doDialog(): > global result > result = dialog() Why this strange two step solution? #Define the List function that displays the list of "cleaned" files def Open(): Incorrect comments are worse than no comments... ;) > def Clean(): > if f: > fileName = dialog() > in_file = open(fileName,'r').readlines() > out_file = open(fileName + '_cleaned.txt', 'w') > for i in in_file: > tmp = sub('\x0D','', i) > out_file.write(tmp) > print 'File cleaned' > > if x: > out_file.close() > if l: > List() > print fileName Huh? Neither f, x nor l are defined in this scope (or globally). In the function where they *are* defined they all refer to Buttons, and should all be "true" all the time. It seems these if-statements have nothing to do in this function. Clean should only be called if you pressed the Clean button anyway. Have you really understood the concept of callbacks in Tkinter? You know, the Tkinter.Button(... command = ...) thingie? > #Make the path where the cleaned files will be stored > if os.path.isdir("C:\\Cleaned_Files"): > print "C:\\Cleaned_Files exists" > else: > os.mkdir("C:\\Cleaned_Files") This is exactly the kind of situation where you might possibly want global variables (but probably not the global statement) after all. Don't repeat yourself! Note that you should have used this directory in the Clean() function as well (and in List()?), if it's going to be meaningful. Defining the same string like that over and over again is a bug waiting to happen. One day you will want to move the directory, but forget to change the code in one place. :( So: CLEANED_FILES_DIR = "C:\\Cleaned_Files" .. out_file_name = os.path.join(CLEANED_FILES_DIR, fileName + '_cleaned.txt') out_file = open(out_file_name, 'w') .. #Make the path where the cleaned files will be stored if os.path.isdir(CLEANED_FILES_DIR): print CLEANED_FILES_DIR, "exists" else: os.mkdir(CLEANED_FILES_DIR) Frankly, your code smells of cargo cult programming*) ;). What I mean is that it seems you are writing (copying?) code that you don't really understand. That won't work. Perhaps you need to slow down a little, and try to make something very small and elementary work, and make sure you understand exactly what all the parts are for, and how they interact. Then you can expand on that, a small step at a time. It seems to me that GUI code is an area where OO code with classes is a very suitable approach. Classes give you a good tool to retain values (attributes of the object) between function calls, and still keep all these values in a well defined place. But maybe it's a bit too much to introduce that concept right now... I might do something like below, but perhaps I'm just confusing you by introducing a class if that is a new concept for you. Also note that I'm far from a Tkinter guru. Anyway, don't expand further on this unless/until you feel that you understand it completely. Feel free to ask more questions of course... import Tkinter import sys import tkFileDialog class MyMenu: def __init__(self, root): # Set up menu self.cleanButton = Tkinter.Button(root, text = "Clean File", command = self.onCleanButton) self.cleanButton.pack() self.viewButton = Tkinter.Button(root, text = "View List", command = self.onViewButton) self.viewButton.pack() self.exitButton = Tkinter.Button(root, text = "Exit", command = sys.exit) self.exitButton.pack() self.filename = None def openFile(self): initDir = 'C:/windows/desktop' filetype = [('All files', '.*')] self.fileName = tkFileDialog.askopenfilename(initialdir=initDir, filetypes=filetype) def cleanFile(self): if not self.fileName: return # You know what to put here... print "Process", self.fileName def onCleanButton(self): self.openFile() self.cleanFile() def onViewButton(self): print "View List" # I don't quite understand what you are trying to do in "List()", # but I suspect you want a new window for this? A Toplevel? root = Tkinter.Tk() MyMenu(root) root.mainloop() *) See http://www.science.uva.nl/~mes/jargon/c/cargocultprogramming.html -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From dyoo at hkn.eecs.berkeley.edu Tue Apr 20 14:07:50 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Apr 20 14:07:57 2004 Subject: [Tutor] Tkinter dilemas [PythonCard?] In-Reply-To: Message-ID: On Tue, 20 Apr 2004, Magnus Lycka wrote: > I fear that there is no really beginner-friendly way of writing GUI code > in Python. Tkinter isn't great, but the other GUI tool kits are thin > wrappers for C or C++ libraries where quirks caused by the underlying > language shine through. We can't really compete with VB on the beginner > level here... Will someone please write PyNewbieGui or VisualPython? I believe that PythonCard is meant to fill this role: http://pythoncard.sourceforge.net/ but I have to admit that I haven't had time to use it yet. Has anyone played with it? From alan.gauld at blueyonder.co.uk Tue Apr 20 14:23:28 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Apr 20 14:27:29 2004 Subject: [Tutor] deleting CR within files In-Reply-To: Message-ID: David, This is a reply to the code you posted today, unfortunately the mail tool I'm using doesn't work properly with the digest! :-( I think you need to look at the structure of your code. Here is what I think you are trying to do? You want to build a GUI that has 3 buttons. One of them will bring up a file dialog from which the user selects a file for processing. On closing the file you process the selected file The user can select another file by repeating the above process. (as someone else pointed out, your user may select multiple files in which case you need a loop to process them and the correct one to choose is probably a for loop.) If I got the idea right then you need: 1) a function to display the file dialog(you got it is dialog()) 2) a function to process a single file 3) an event handler to call the dialog() function to store the result in a global variable and then call the file processing function - you almost got it, its doDialog() 4) a function to define the GUI widgets and pack them into the top level window, binding the doDialog function to the Choose files button. (I can't recall what the middle button was...) 5) a GUI mainloop, which you get for free with Tk.mainloop() It should just be a case of assembling the bits and letting Tkinter do its stuff, you do not need to call any of the above functions except the GUI building one from your main program and doDialog() calls both dialog() and processFile() internally. Does that help? Have I understood what you are trying to do? Alan G. (Normal service resumed on Thursday!:-) From AKolinski at nriindustries.com Tue Apr 20 16:12:20 2004 From: AKolinski at nriindustries.com (Andrzej Kolinski) Date: Tue Apr 20 16:13:29 2004 Subject: [Tutor] Tkinter dilemas - off topic In-Reply-To: Message-ID: Magnus, What's your IQ, Magnus? I guess it is way above 150 (if I'm insulting you, my apologies; I didn't mean that). I'm not a programmer, but being a python enthusiast I'm always impressed by clarity and depth of your messages. I don't only read them several times but also save them for future studies:-). Thank you so much! _/_/ _/ _/ _/ _/ _/ _/ _/_/_/_/ _/_/ _/ _/ _/ _/ _/ _/ _/ _/ Andrzej Kolinski I fear that there is no really beginner-friendly way of writing GUI code in Python. Tkinter isn't great, but the other GUI tool kits are thin wrappers for C or C++ libraries where quirks caused by the underlying language shine through. We can't really compete with VB on the beginner level here... Will someone please write PyNewbieGui or VisualPython? David Talaga wrote: > global root > root=Tk() The global statement is meaningless here. Use global within a local scope to declare that a certain name in that (local) scope refers to a global variable. E.g: >>> x = "Hello" >>> def f(): global x x = 'Hi' >>> print x Hello >>> f() >>> print x Hi There is no way you can stop local variables overriding globals like you seem to be trying to do. On the other hand, you never assign to the name "root" in any local scope, so you don't need that anyway. As a general rule, try to avoid global variables. Your program is short but still seems messy to me. Maybe you can try to clean it up a bit. For instance, you use both "from Tkinter import *" and "import Tkinter". Why all of Tkinter in two scopes? For clarity, avoid using "from import *". You should also try to give all variables and functions good names. Try to spend some time thinking about that. It will make it easier for others to understand your code, and it might help you make it clear for yourself what the different parts of the program are really supposed to do. (If you can't think of a good name for a function or variable, it's likely that it's not a very good function or variable...) > import re .. > sub = re.sub .. > tmp = sub('\x0D','', i) Don't do that! Skip the middle step and do > import re .. > tmp = re.sub('\x0D','', i) A call to "re.sub" is meaningful to any experienced Python coder reading your code. Just "sub" means that he has to look in some other place in the code (remember that "real" programs get thousands of lines long) to figure out that your sub is simply the sub in the re module. Also, for a Python newbie reading "re.sub" it will be clear where to find out more about what the sub function does. > def doDialog(): > global result > result = dialog() Why this strange two step solution? #Define the List function that displays the list of "cleaned" files def Open(): Incorrect comments are worse than no comments... ;) > def Clean(): > if f: > fileName = dialog() > in_file = open(fileName,'r').readlines() > out_file = open(fileName + '_cleaned.txt', 'w') > for i in in_file: > tmp = sub('\x0D','', i) > out_file.write(tmp) > print 'File cleaned' > > if x: > out_file.close() > if l: > List() > print fileName Huh? Neither f, x nor l are defined in this scope (or globally). In the function where they *are* defined they all refer to Buttons, and should all be "true" all the time. It seems these if-statements have nothing to do in this function. Clean should only be called if you pressed the Clean button anyway. Have you really understood the concept of callbacks in Tkinter? You know, the Tkinter.Button(... command = ...) thingie? > #Make the path where the cleaned files will be stored > if os.path.isdir("C:\\Cleaned_Files"): > print "C:\\Cleaned_Files exists" > else: > os.mkdir("C:\\Cleaned_Files") This is exactly the kind of situation where you might possibly want global variables (but probably not the global statement) after all. Don't repeat yourself! Note that you should have used this directory in the Clean() function as well (and in List()?), if it's going to be meaningful. Defining the same string like that over and over again is a bug waiting to happen. One day you will want to move the directory, but forget to change the code in one place. :( So: CLEANED_FILES_DIR = "C:\\Cleaned_Files" .. out_file_name = os.path.join(CLEANED_FILES_DIR, fileName + '_cleaned.txt') out_file = open(out_file_name, 'w') .. #Make the path where the cleaned files will be stored if os.path.isdir(CLEANED_FILES_DIR): print CLEANED_FILES_DIR, "exists" else: os.mkdir(CLEANED_FILES_DIR) Frankly, your code smells of cargo cult programming*) ;). What I mean is that it seems you are writing (copying?) code that you don't really understand. That won't work. Perhaps you need to slow down a little, and try to make something very small and elementary work, and make sure you understand exactly what all the parts are for, and how they interact. Then you can expand on that, a small step at a time. It seems to me that GUI code is an area where OO code with classes is a very suitable approach. Classes give you a good tool to retain values (attributes of the object) between function calls, and still keep all these values in a well defined place. But maybe it's a bit too much to introduce that concept right now... I might do something like below, but perhaps I'm just confusing you by introducing a class if that is a new concept for you. Also note that I'm far from a Tkinter guru. Anyway, don't expand further on this unless/until you feel that you understand it completely. Feel free to ask more questions of course... import Tkinter import sys import tkFileDialog class MyMenu: def __init__(self, root): # Set up menu self.cleanButton = Tkinter.Button(root, text = "Clean File", command = self.onCleanButton) self.cleanButton.pack() self.viewButton = Tkinter.Button(root, text = "View List", command = self.onViewButton) self.viewButton.pack() self.exitButton = Tkinter.Button(root, text = "Exit", command = sys.exit) self.exitButton.pack() self.filename = None def openFile(self): initDir = 'C:/windows/desktop' filetype = [('All files', '.*')] self.fileName = tkFileDialog.askopenfilename(initialdir=initDir, filetypes=filetype) def cleanFile(self): if not self.fileName: return # You know what to put here... print "Process", self.fileName def onCleanButton(self): self.openFile() self.cleanFile() def onViewButton(self): print "View List" # I don't quite understand what you are trying to do in "List()", # but I suspect you want a new window for this? A Toplevel? root = Tkinter.Tk() MyMenu(root) root.mainloop() *) See http://www.science.uva.nl/~mes/jargon/c/cargocultprogramming.html -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040420/7eaab5e4/attachment-0001.html From bvande at po-box.mcgill.ca Tue Apr 20 18:37:27 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Tue Apr 20 18:40:05 2004 Subject: [Tutor] Tkinter dilemas In-Reply-To: References: Message-ID: <4085A627.9050304@po-box.mcgill.ca> Magnus Lycka said unto the world upon 20/04/2004 13:55: > I fear that there is no really beginner-friendly way of writing GUI code > in Python. Tkinter isn't great, but the other GUI tool kits are thin > wrappers for C or C++ libraries where quirks caused by the underlying > language shine through. We can't really compete with VB on the beginner > level here... Will someone please write PyNewbieGui or VisualPython? > Hi all, I'm still busy getting a grip on the basics of Python, but I am also starting to feel a GUI-itch. What little looking I have done at Tkinter made me think I ought wait until I've a few more notches in my programmer's belt ;-) But I was wondering if anygui (http://anygui.sourceforge.net/) could be seen as going some distance towards PyNewbieGui? Again, I don't know too much (indeed, I'm partly looking for opinions of this tool), but from what I've read, it seems designed to be a "as little fuss as possible" GUI tool. Anyone with experience to confirm this idea or disabuse me of it? Best to all, Brian vdB From dyoo at hkn.eecs.berkeley.edu Tue Apr 20 19:17:29 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Apr 20 19:17:45 2004 Subject: [Tutor] Complex numbers can't be ordered algebraically In-Reply-To: <1082416014.3228.46.camel@laptop.venix.com> Message-ID: On 19 Apr 2004, Lloyd Kvam wrote: > The ordering of keys and values retrieved from a dictionary is > undefined. There is no requirement that keys or values support an > ordering. For instance, they could be complex numbers. Hi Lloyd, I just wanted to raise awareness of the fact that the complex numbers are not "ordered" from a mathematical perspective. That is, they can't be compared by using the less-than or greater-than operators that follow the math definition of "order": http://en.wikipedia.org/wiki/Ordered_field ### >>> x = 3+4j >>> y = 4+5j >>> x < y Traceback (most recent call last): File "", line 1, in ? TypeError: cannot compare complex numbers using <, <=, >, >= ### In this, Python follows what mathematicians have defined. But why? This might seem weird --- why shouldn't y be 'greater' than x? All the numbers are bigger! But there's a strong math basis for the restriction. For an "ordered field", the square of any number 'x' is nonnegative: x**2 >= 0 This is a combination of "Positive times positive is positive" / "negative times negative is positive" rules from elementary school. *grin* Unfortunately, complex numbers violate this law: ### >>> (-1j) * (-1j) (-1-0j) ### The conclusion we can make from this is that complex numbers aren't compatible with the concept of algebraic order. So that's why the complex numbers are excluded from being compared by '<', '<=', '>' or '>='. Hope this helps! From magnus at thinkware.se Tue Apr 20 19:53:03 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Tue Apr 20 19:53:16 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gVGtpbnRlciBkaWxlbWFz?= Message-ID: Brian van den Broek wrote: > But I was wondering if anygui (http://anygui.sourceforge.net/) could be seen > as going some distance towards PyNewbieGui? Again, I don't know too much > (indeed, I'm partly looking for opinions of this tool), but from what I've > read, it seems designed to be a "as little fuss as possible" GUI tool. > Anyone with experience to confirm this idea or disabuse me of it? It's still not at version 0.2 as far as I understand... My uninformed guess is that PythonCard might be your best bet, just as Danny suggested. It seems to be actively developed, more mature, and based on the powerful wxPython tool kit. See http://pythoncard.sourceforge.net/ -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From missive at hotmail.com Tue Apr 20 20:04:26 2004 From: missive at hotmail.com (Lee Harr) Date: Tue Apr 20 20:04:35 2004 Subject: [Tutor] Re: Tkinter dilemas Message-ID: >I fear that there is no really beginner-friendly way of writing GUI code >in Python. Tkinter isn't great, but the other GUI tool kits are thin >wrappers for C or C++ libraries where quirks caused by the underlying >language shine through. We can't really compete with VB on the beginner >level here... Will someone please write PyNewbieGui or VisualPython? > I really like pythoncard for simple, cross-platform gui programs. http://pythoncard.sourceforge.net/ If you are on Linux or BSD, then PyQT / PyKDE are pretty easy to work with also. http://www.riverbankcomputing.co.uk/pyqt/index.php http://www.riverbankcomputing.co.uk/pyqt/index.php Of course, I have never used VB (thankful for the small things in life :o) so I cannot really make a comparison. _________________________________________________________________ Tired of spam? Get advanced junk mail protection with MSN 8. http://join.msn.com/?page=features/junkmail From pythonTutor at venix.com Tue Apr 20 20:54:50 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Tue Apr 20 20:55:41 2004 Subject: [Tutor] Complex numbers can't be ordered algebraically In-Reply-To: References: Message-ID: <1082508889.2125.4.camel@laptop.venix.com> Obviously, I was not terribly clear. I DID mean to point out that complex numbers were NOT ordered. I was trying to offer the example of complex numbers as keys or values in a dictionary and not having a natural default ordering. Thanks for taking the time to make sure there was no misunderstanding. On Tue, 2004-04-20 at 19:17, Danny Yoo wrote: > On 19 Apr 2004, Lloyd Kvam wrote: > > > The ordering of keys and values retrieved from a dictionary is > > undefined. There is no requirement that keys or values support an > > ordering. For instance, they could be complex numbers. > > > Hi Lloyd, > > > I just wanted to raise awareness of the fact that the complex numbers are > not "ordered" from a mathematical perspective. That is, they can't be > compared by using the less-than or greater-than operators that follow the > math definition of "order": > > http://en.wikipedia.org/wiki/Ordered_field > > > ### > >>> x = 3+4j > >>> y = 4+5j > >>> x < y > Traceback (most recent call last): > File "", line 1, in ? > TypeError: cannot compare complex numbers using <, <=, >, >= > ### > > > In this, Python follows what mathematicians have defined. But why? This > might seem weird --- why shouldn't y be 'greater' than x? All the numbers > are bigger! > > > But there's a strong math basis for the restriction. For an "ordered > field", the square of any number 'x' is nonnegative: > > x**2 >= 0 > > This is a combination of "Positive times positive is positive" / "negative > times negative is positive" rules from elementary school. *grin* > > > Unfortunately, complex numbers violate this law: > > ### > >>> (-1j) * (-1j) > (-1-0j) > ### > > > The conclusion we can make from this is that complex numbers aren't > compatible with the concept of algebraic order. So that's why the complex > numbers are excluded from being compared by '<', '<=', '>' or '>='. > > > Hope this helps! -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From tony at tcapp.com Wed Apr 21 02:54:17 2004 From: tony at tcapp.com (Tony Cappellini) Date: Wed Apr 21 02:55:24 2004 Subject: [Tutor] Need help with multi-line regex identification In-Reply-To: References: Message-ID: <6.0.0.22.0.20040420232943.01c454f0@tcapp.com> I'm writing a program to give me a listing of function definitions in source files, for an in-house programming language. The language is very much like C (in the sense of that it has macros, which work *almost* the same as C functions) a macro in this language is declared as macro MyMacroName // this is the beginning of the macro // this is the body of the macro integer X; X=X+1 print"X=" X // this is the body of the macro emacro // this is the end of the macro Some macro files have 20 or more macro definitions, and often there are 10 or more macro files in one program. So it's very convenient to have a program to list all of the macros in the source files. With any program development, code doesn't always work the first time, and some macros are commented out. With this in mind, I don't want macros that are commented out to be found by my "macro listing program" This language uses both C and C++ style comments. I'm new to regex's, but I've come up with the regex below to find the beginning of a macro definition. re.compile(r"""^ *[MACRO]+[ \t]+[a-zA-Z0-9]+""", re.IGNORECASE) The regex below re.compile(r"""^ *//""") I use to find a macro definition, that has been commented out, by a C++-style comment. Now for the real problem I don't want my macro lister program, to find macro definitions that are inside of a multi-line C-style comment. That is /* macro MyMacro */ or this /* macro MyMacro */ or this /* macro MyMacro * / should be IGNORED by my program, but I don't know how to do this with regex. (or any variation of the above C-style multi-line comment) . Obviously, this can be done without regexs, but I think the resulting code could be shortened significantly by using regexs Could someone help point me in the right direction for this ? thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040420/dfe6ec75/attachment.html From godoy at ieee.org Wed Apr 21 07:13:02 2004 From: godoy at ieee.org (Jorge Godoy) Date: Wed Apr 21 07:20:17 2004 Subject: [Tutor] Re: Need help with multi-line regex identification References: <6.0.0.22.0.20040420232943.01c454f0@tcapp.com> Message-ID: On Qua 21 Abr 2004 03:54, Tony Cappellini wrote: > Could someone help point me in the right direction for this ? In Perl we used to use multiline/extended match for that. Either we made the line terminator become irrelevant and handled everything as if it was in one line (something like that, but not exactly that) or we used some extensions on grep (you can read Perl's documentation on regular expressions for that: perldoc perlre). It became something along the lines of what's in this part of the docs: --------------------------------------------------------------------- m Treat string as multiple lines. That is, change "^" and "$" from matching the start or end of the string to matching the start or end of any line anywhere within the string. s Treat string as single line. That is, change "." to match any character whatsoever, even a newline, which normally it would not match. The "/s" and "/m" modifiers both override the $* setting. That is, no matter what $* contains, "/s" without "/m" will force "^" to match only at the beginning of the string and "$" to match only at the end (or just before a newline at the end) of the string. Together, as /ms, they let the "." match any character whatsoever, while still allowing "^" and "$" to match, respectively, just after and just before newlines within the string. --------------------------------------------------------------------- I mean the regexp became "//ms". Even there, where regexps are highly recommended for lots of things we find problems with such things and there's a "more recommended" approach: using a lexical parser. So, this is what I'm questioning you: wouldn't it be a lot easier for you to change the language, expand it and also parse it if you had a parser for it? On a short search through Google ("python lexical parser") I found this: http://christophe.delord.free.fr/en/tpg/ There's also the parser-sig (whose page links to http://www.python.org/topics/parsing.html) where you can get other options if the above doesn't satisfy your needs. For using Plex, there's even an example where the author is handling "comments" on code. It might interest you better. The docs are at http://www.cosc.canterbury.ac.nz/~greg/python/Plex/version/doc/index.html and the page where the parser-sig points to is at http://www.cosc.canterbury.ac.nz/~greg/python/Plex/ Take a look at the other ones too... And use a parser. It will be better and easier, IMHO. Be seeing you, -- Godoy. From Chad.Crabtree at nationalcity.com Wed Apr 21 11:02:29 2004 From: Chad.Crabtree at nationalcity.com (Crabtree, Chad) Date: Wed Apr 21 11:02:46 2004 Subject: [Tutor] On GUI's Message-ID: <66F587DFDD46D511B65200508B6F8DD612B99400@nt-kalopsapp07.ntl-city.com> I just wanted to make a comment about GUI programing. I recently was trying to make a command line menu driven text console for a little project. I found the complexities of that system greatly outwieghed the same in GUI's especially Tkinter. I was just mentioning this for those people new to GUI programing that yes they are wierd but I believe all UI's are fiarly difficult to implement. Especially as they become more feature rich. ------------------------------------------------------------------------------------------- ***National City made the following annotations ------------------------------------------------------------------------------------------- This communication is a confidential and proprietary business communication. It is intended solely for the use of the designated recipient(s). If this communication is received in error, please contact the sender and delete this communication. =========================================================================================== From lumbricus at gmx.net Wed Apr 21 11:29:28 2004 From: lumbricus at gmx.net (=?ISO-8859-1?Q?=22J=F6rg_W=F6lke=22?=) Date: Wed Apr 21 11:29:33 2004 Subject: [Tutor] On GUI's References: <66F587DFDD46D511B65200508B6F8DD612B99400@nt-kalopsapp07.ntl-city.com> Message-ID: <27504.1082561368@www42.gmx.net> > I just wanted to make a comment about GUI programing. I recently was > trying > to make a command line menu driven text console for a little project. I > found the complexities of that system greatly outwieghed the same in GUI's > especially Tkinter. I was just mentioning this for those people new to > GUI > programing that yes they are wierd but I believe all UI's are fiarly > difficult to implement. Especially as they become more feature rich. Did you try ncurses or dialog for python? "http://dialogpython.sourceforge.net" HTH and Greets, J"o! -- Sie duerfen diesen Satz zitieren. NEU : GMX Internet.FreeDSL Ab sofort DSL-Tarif ohne Grundgebühr: http://www.gmx.net/dsl From adam at monkeez.org Wed Apr 21 12:56:31 2004 From: adam at monkeez.org (Adam) Date: Wed Apr 21 12:56:26 2004 Subject: [Tutor] On GUI's In-Reply-To: <66F587DFDD46D511B65200508B6F8DD612B99400@nt-kalopsapp07.ntl-city.com> References: <66F587DFDD46D511B65200508B6F8DD612B99400@nt-kalopsapp07.ntl-city.com> Message-ID: <20040421175631.01ea33b4@debian> On Wed, 21 Apr 2004 11:02:29 -0400 "Crabtree, Chad" wrote: > I just wanted to make a comment about GUI programing. I > recently was trying to make a command line menu driven > text console for a little project. I found the > complexities of that system greatly outwieghed the same in > GUI's especially Tkinter. I was just mentioning this for > those people new to GUI programing that yes they are wierd > but I believe all UI's are fiarly difficult to implement. > Especially as they become more feature rich. Sorry. I'm new to the world of gui programming under python. I'm not exactly clear on what you're trying to say here. Are you saying that you found it more difficult to write a command line menu? adam From magnus at thinkware.se Wed Apr 21 13:13:02 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Wed Apr 21 13:13:16 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gT24gR1VJJ3M=?= Message-ID: Chad Crabtree wrote: > I just wanted to make a comment about GUI programing. I recently was trying > to make a command line menu driven text console for a little project. I > found the complexities of that system greatly outwieghed the same in GUI's > especially Tkinter. I was just mentioning this for those people new to GUI > programing that yes they are wierd but I believe all UI's are fiarly > difficult to implement. Especially as they become more feature rich. Very true. One of the Unix Philosophy tenets is to avoid captive user interfaces in general. We have become used to these user interfaces where we interactively walk through menues and fill in forms. Maybe it's better to think outside this paradigm. For instance, let's imagine that we have a program where we report our working hours, and what project we worked on. The typical WIMP approach might be a GUI app where we can choose beween a list view where we can view, delete, edit, add entries, and an add/edit window with labels, text entry fields and a few buttons. Something like this (you need a fixed font to view this...) /--------------------------------------\ | +-----------+ | | Employee | | | | +-----------+ | | +-----------+ | | Project | | | | +-----------+ | | +----------+ | | Date |____-__-__| | | +----------+ | | +--------+ /------\ | | Start |__:__:__| | Save || | | +--------+ \======// | | +--------+ /------\ | | Stop |__:__:__| |Cancel|| | | +--------+ \======// | \--------------------------------------/ A competely different approach is to make a non-interactive program which for instance acts on command line switches -l (for list entries), -r (for remove entry) and -a (for add entry). We can imagine something like this: $ timereport.py -l -uMagnus -d2004-04-19 1234, "The Oregon Project", 08:14:10, 11:34:00 1235, "Adminstration", 11:34:00, 13:00:00 1236, "The Oregon Project", 14:14:10, 19:34:00 $ timereport.py -r1235 $ timereport.py -l -uMagnus -d2004-04-19 1234, "The Oregon Project", 08:14:10, 11:34:00 1236, "The Oregon Project", 14:14:10, 19:34:00 $ timereport.py -l 1236 employee: Magnus project: The Oregon Project date: 2004-04-19 start: 14:14:10 stop: 19:34:00 (This we can redirect to a file) $ timereport.py -l 1236 > temp.txt $ edit temp.txt (Change the text file as you like in your editor) $ timereport.py -r1236 $ timereport.py -a temp.txt $ timereport.py -l -uMagnus -d2004-04-19 1234, "The Oregon Project", 08:14:10, 11:34:00 1237, "The Oregon Project", 14:00:00, 19:45:00 You might think that this is a very old fashioned and primitive way of working, just as my five year old son thinks it's very primitive and old fashioned to actually learn how to read and write when there are telephones and TV (and parents who can read for you). ;) Actually, I suspect that you'd work faster with this system than with a GUI system. You can have a fixed file that you just double click on to edit, and then you can just double click on another icon to do "timereport.py -a timeentry.txt", and click on a third which is a tiny bat-file containing: timereport.py -l -uMagnus > timelog.txt notepad.exe timelog.txt Whatever... Apart from being as easy to use as soon as you get used to it, it will be much faster to develop, and much, much more flexible regarding further development than any application with a captive user interface. It would be easy to write a program (in Python or some other language) that provided an email interface for this, so that you can just send emails to a certain address to get them registered in the database. The email system would use just the same interface as you do. Same thing with a web interface, or an interface that allows you to report time through your mobile phone. No big deal. Try to write a program that recieves SMS messages from a GSM phone and enters the data in the message into a system with only a GUI interface! -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From tpc at csua.berkeley.edu Wed Apr 21 13:21:48 2004 From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu) Date: Wed Apr 21 13:32:37 2004 Subject: [Tutor] hotshot profile Python web application Message-ID: <20040421100652.N81509-100000@localhost.name> hi everybody, I have a Python script I wrote that seemed to work fine as a web application on a specific server. When I ported it to another machine with a different setup it took an unbelievably long time to return a page to me. I would like to find out what line the script is spending most of its time in, and, for various input, the time it takes to get a page returned to me. I have heard about Python profiler and hotshot, and was reading this page: http://www.python.org/doc/current/lib/hotshot-example.html Since my application is activated by opening a URL, I thought I would start off by opening a simple "Hello World!" page. So far I have: >>> import hotshot, hotshot.stats >>> from urllib import urlopen >>> prof = hotshot.Profile("test.txt") >>> prof.run(urlopen('http://foo.com')) Traceback (most recent call last): File "", line 1, in -toplevel- prof.run(urlopen('http://foo.com')) File "/usr/lib/python2.3/hotshot/__init__.py", line 56, in run return self.runctx(cmd, dict, dict) File "/usr/lib/python2.3/hotshot/__init__.py", line 64, in runctx code = compile(cmd, "", "exec") TypeError: expected a readable buffer object >>> prof.run(urlopen('http://foo.com').read()) Traceback (most recent call last): File "", line 1, in -toplevel- benchtime, stones = prof.run(urlopen('http://foo.com').read()) File "/usr/lib/python2.3/hotshot/__init__.py", line 56, in run return self.runctx(cmd, dict, dict) File "/usr/lib/python2.3/hotshot/__init__.py", line 64, in runctx code = compile(cmd, "", "exec") File "", line 1 Hello World! ^ SyntaxError: invalid syntax >>> prof.runcall(urlopen("http://foo.com")) Traceback (most recent call last): File "", line 1, in -toplevel- prof.runcall(urlopen("http://foo.com")) File "/usr/lib/python2.3/hotshot/__init__.py", line 76, in runcall return self._prof.runcall(func, args, kw) AttributeError: addinfourl instance has no __call__ method >>> prof.runcall('urlopen("http://foo.com")') Traceback (most recent call last): File "", line 1, in -toplevel- prof.runcall('urlopen("http://foo.com")') File "/usr/lib/python2.3/hotshot/__init__.py", line 76, in runcall return self._prof.runcall(func, args, kw) TypeError: 'str' object is not callable Arrgh! From project5 at redrival.net Wed Apr 21 13:42:24 2004 From: project5 at redrival.net (Andrei) Date: Wed Apr 21 13:42:37 2004 Subject: [Tutor] Re: On GUI's References: <66F587DFDD46D511B65200508B6F8DD612B99400@nt-kalopsapp07.ntl-city.com> <20040421175631.01ea33b4@debian> Message-ID: Adam wrote on Wed, 21 Apr 2004 17:56:31 +0100: > On Wed, 21 Apr 2004 11:02:29 -0400 > "Crabtree, Chad" wrote: > >> I just wanted to make a comment about GUI programing. I >> recently was trying to make a command line menu driven >> text console for a little project. I found the >> complexities of that system greatly outwieghed the same in > > Sorry. I'm new to the world of gui programming under python. > I'm not exactly clear on what you're trying to say here. Are > you saying that you found it more difficult to write a > command line menu? For some purposes it's much easier to just write a GUI and be done with it instead of handling all kinds of user input and ending up with an ugly program half the people won't want to use just because it doesn't have a GUI. Ok, that half probably still won't want to use it if it's written in Tkinter, but that's not the point :). For very simple stuff I like easygui (http://www.ferg.org/easygui/), a Tkinter wrapper. It beats console style and it's just as easy to program for (if not easier, since you don't have to check that much if the user gave some stupid input). -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From dyoo at hkn.eecs.berkeley.edu Wed Apr 21 14:21:02 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Apr 21 14:21:09 2004 Subject: [Tutor] Complex numbers can't be ordered algebraically In-Reply-To: <1082508889.2125.4.camel@laptop.venix.com> Message-ID: On 20 Apr 2004, Lloyd Kvam wrote: > Obviously, I was not terribly clear. I DID mean to point out that > complex numbers were NOT ordered. I was trying to offer the example of > complex numbers as keys or values in a dictionary and not having a > natural default ordering. Hi Lloyd, You were perfectly clear --- I did know that you knew that complex numbers weren't ordered. Hmmm... but I didn't make that clear in my own message on Tutor. My apologies! I meant to address my response to folks on the list. I wanted to show the details why you mentioned complex numbers. For people who are not too familiar with them, it seems very counterintuitive to say that '<' doesn't apply to complex numbers. Aren't they're "numbers"? And in our intuitive experience, numbers can be ordered. It's something to keep in the back of one's mind, because it's the reason why sort()ing a list of complex numbers won't work without manual intervention. ### >>> import random >>> def makeRandomComplex(): ... return random.randrange(0, 10) + random.randrange(0, 10) * 1j ... >>> numbers = [makeRandomComplex() for x in range(5)] >>> numbers [(6+3j), (4+4j), (7+4j), (6+4j), (2+0j)] >>> >>> numbers.sort() Traceback (most recent call last): File "", line 1, in ? TypeError: cannot compare complex numbers using <, <=, >, >= >>> >>> >>> def mag(c): ... return (c.imag **2 + c.real ** 2)**(0.5) ... >>> def cmpByMag(a, b): ... return cmp(mag(a), mag(b)) ... >>> numbers.sort(cmpByMag) >>> numbers [(2+0j), (4+4j), (6+3j), (6+4j), (7+4j)] ### Hope this helps! From magnus at thinkware.se Wed Apr 21 14:21:35 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Wed Apr 21 14:22:00 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gTmVlZCBoZWxwIHdpdGggbXVsdGktbGluZSByZWdleCBpZGVudGlmaWNhdGlvbg==?= Message-ID: Tony Cappellini wrote: > Now for the real problem > I don't want my macro lister program, to find macro definitions that are > inside of a multi-line C-style comment. I'm sure you can write a regular expression that works for this most of the time, but if you want to take into consideration things like... /* We comment out some code sprintf("We can use */ inside a string of course"); Now we end the comment */ ..it gets much harder. I havn't used lexers or parsers, and as an old electronics engieneer, I'd probably use a state machine for this, and walk through the file, byte by byte, like this: data = """ //macro MyMacroName1 // this is the beginning of the macro // this is the body of the macro //integer X; // X=X+1 // print"X=" X // this is the body of the macro //emacro // this is the end of the macro macro MyMacroName1 // this is the beginning of the macro // this is the body of the macro integer X; X=X+1 print"X=" X // this is the body of the macro emacro // this is the end of the macro ThisIsNotAComment = "//" /* macro MyMacroName2 // this is the beginning of the macro // this is the body of the macro integer X; X=X+1 print"X=" X // this is the body of the macro emacro // this is the end of the macro */ macro MyMacroName3 integer X; X=X+1 print"X=" X emacro """ # These functions find state transitions. def macroStart(data, n): return data[n-6:n] == '\nmacro' def macroEnd(data, n): return data[n-7:n] == '\nemacro' def cCommentStart(data, n): return data[n-2:n] == '/*' def cCommentEnd(data, n): return data[n-2:n] == '*/' def cppCommentStart(data, n): return data[n-2:n] == '//' def lineEnd(data, n): return data[n] == '\n' def stringLiteralMarker(data, n): return data[n] == '"' # These classes represent states. class Normal: def __call__(self, data, n): if stringLiteralMarker(data, n): return StringLiteral() if macroStart(data, n): return Macro() if cCommentStart(data, n): return CComment() if cppCommentStart(data, n): return CppComment() class Macro: def __init__(self): self.start = None def __call__(self, data, n): if self.start is None: self.start = n-6 if stringLiteralMarker(data, n): return StringLiteral() if macroEnd(data, n): print print data[self.start:n+1] print return -1 if cCommentStart(data, n): return CComment() if cppCommentStart(data, n): return CppComment() class StringLiteral: def __call__(self, data, n): if stringLiteralMarker(data, n): return -1 if lineEnd(data, n): print "Error, end of line in string literal!" print data[n-100:n+100] return -1 class CComment: def __call__(self, data, n): if stringLiteralMarker(data, n): return StringLiteral() if cCommentEnd(data, n): return -1 class CppComment: def __call__(self, data, n): if lineEnd(data, n): return -1 state = [Normal()] for n in range(len(data)): # Uncomment next line to see what's happening... #print n, data[n], state new_state = state[-1](data, n) if not new_state: continue elif new_state == -1: state.pop() else: state.append(new_state) -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From godoy at ieee.org Wed Apr 21 14:22:59 2004 From: godoy at ieee.org (Jorge Godoy) Date: Wed Apr 21 14:36:13 2004 Subject: [Tutor] Parsing the contents of an email message. Message-ID: Hi! I'm working with a CVS project where I'll need to get some information from the report it does via an email message. I've been reading the "Global Module Index" (http://www.python.org/doc/current/modindex.html) looking for tools to parse the body of such a message. I'm planning on having such messages delivered locally to a file, so I can use some method to make that file the message, without having to setup a POP/IMAP server. Is email.Parser the best module for such a task? One example of such a kind of message: ------------------------------------------------------------------------------- Return-Path: X-Original-To: godoy@godoy.homeip.net Delivered-To: godoy@godoy.homeip.net Received: by wintermute.g2ctech (Postfix, from userid 500) id CC3F44FDF4; Tue, 20 Apr 2004 14:22:03 -0300 (BRT) MIME-Version: 1.0 To: godoy@godoy.homeip.net Subject: Imported Sources X-Mailer: activitymail 1.19, http://search.cpan.org/dist/activitymail/ Content-Type: multipart/mixed; boundary="t79lL2nSPjcLg" Message-Id: <20040420172203.CC3F44FDF4@wintermute.g2ctech> Date: Tue, 20 Apr 2004 14:22:03 -0300 (BRT) From: godoy@g2ctech.com (Jorge Luiz Godoy Filho) X-Bogosity: No, tests=bogofilter, spamicity=0.000000, version=0.17.0 X-UID: 48164 Update of /home/cvs/clientes/dataprev/teste/tempo In directory wintermute.g2ctech:/tmp/cvs-serv19067 Log Message: Teste Dataprev Status: Vendor Tag: godoy Release Tags: start N clientes/dataprev/teste/tempo/a.ppt N clientes/dataprev/teste/tempo/b.doc No conflicts created by this import ------------------------------------------------------------------------------- Another kind of message is the one generated by commits, where there are attachments (that I'm not interested in and I want to discard for the task I'm working on): ------------------------------------------------------------------------------- Return-Path: X-Original-To: godoy@godoy.homeip.net Delivered-To: godoy@godoy.homeip.net Received: by wintermute.g2ctech (Postfix, from userid 500) id 65A744FF89; Tue, 20 Apr 2004 14:07:17 -0300 (BRT) MIME-Version: 1.0 To: godoy@godoy.homeip.net Subject: Teste. X-Mailer: activitymail 1.19, http://search.cpan.org/dist/activitymail/ Content-Type: multipart/mixed; boundary="iT.nVIPzX.7a." Message-Id: <20040420170717.65A744FF89@wintermute.g2ctech> Date: Tue, 20 Apr 2004 14:07:17 -0300 (BRT) From: godoy@g2ctech.com (Jorge Luiz Godoy Filho) X-Bogosity: No, tests=bogofilter, spamicity=0.000000, version=0.17.0 X-UID: 48163 Status: RO X-Status: OR X-KMail-EncryptionState: N X-KMail-SignatureState: N X-KMail-MDN-Sent: --iT.nVIPzX.7a. Content-Type: text/plain Log Message: ----------- Teste. Modified Files: -------------- clientes/dataprev/teste: teste.comum clientes/dataprev/teste/tempo: a.ppt b.doc --iT.nVIPzX.7a. Content-Disposition: attachment; filename=godoy-200442017717-diff.txt Content-Transfer-Encoding: 8bit Content-Type: text/plain; charset=ISO-8859-1 Index: teste.comum =================================================================== RCS file: /home/cvs/clientes/dataprev/teste/teste.comum,v retrieving revision 1.1.1.1 retrieving revision 1.2 diff -Ldataprev/teste/teste.comum -Ldataprev/teste/teste.comum -u -r1.1.1.1 -r1.2 --- dataprev/teste/teste.comum +++ dataprev/teste/teste.comum @@ -0,0 +1 @@ +teste Index: b.doc =================================================================== RCS file: /home/cvs/clientes/dataprev/teste/tempo/b.doc,v retrieving revision 1.2 retrieving revision 1.3 diff -Ldataprev/teste/tempo/b.doc -Ldataprev/teste/tempo/b.doc -u -r1.2 -r1.3 --- dataprev/teste/tempo/b.doc +++ dataprev/teste/tempo/b.doc @@ -1 +1 @@ -b +bb Index: a.ppt =================================================================== RCS file: /home/cvs/clientes/dataprev/teste/tempo/a.ppt,v retrieving revision 1.3 retrieving revision 1.4 diff -Ldataprev/teste/tempo/a.ppt -Ldataprev/teste/tempo/a.ppt -u -r1.3 -r1.4 --- dataprev/teste/tempo/a.ppt +++ dataprev/teste/tempo/a.ppt @@ -1 +1 @@ -aa +a --iT.nVIPzX.7a.-- ------------------------------------------------------------------------------- Thanks in advance, -- Godoy. From tpc at csua.berkeley.edu Wed Apr 21 14:59:55 2004 From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu) Date: Wed Apr 21 15:00:31 2004 Subject: [Tutor] Parsing the contents of an email message. In-Reply-To: Message-ID: <20040421115047.E83197-100000@localhost.name> hi Jorge, I am finishing up an application that grabs emails, passes them through a filter, and parses them. I ended up using: import MySQLdb, re from imaplib import IMAP4_SSL from email import message_from_string from email.Utils import parsedate_tz, mktime_tz from time import strftime, strptime, localtime, time As you will see, dateTime is very important when parsing emails, especially when debugging your application by writing an errorlog of emails that didn't parse correctly. On Wed, 21 Apr 2004, Jorge Godoy wrote: > Hi! > > > I'm working with a CVS project where I'll need to get some information from > the report it does via an email message. > > I've been reading the "Global Module > Index" (http://www.python.org/doc/current/modindex.html) looking for tools > to parse the body of such a message. > > I'm planning on having such messages delivered locally to a file, so I can > use some method to make that file the message, without having to setup a > POP/IMAP server. > > Is email.Parser the best module for such a task? > > From dyoo at hkn.eecs.berkeley.edu Wed Apr 21 15:05:41 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Apr 21 15:05:49 2004 Subject: [Tutor] Finding C comments with regular expressions In-Reply-To: Message-ID: On Wed, 21 Apr 2004, Magnus Lycka wrote: > Tony Cappellini wrote: > > Now for the real problem > > I don't want my macro lister program, to find macro definitions that are > > inside of a multi-line C-style comment. > > I'm sure you can write a regular expression that works for this most of > the time, but if you want to take into consideration things like... > > /* We comment out some code > > sprintf("We can use */ inside a string of course"); > > Now we end the comment */ > > ..it gets much harder. Hi Magnus, Actually, C should behave as if: > /* We comment out some code > > sprintf("We can use */ were the comment: C comments don't care if there are quotes in the comment content. The regular expression is a little tricky, because the beginning and ending of a comment uses two characters instead of one. Here's a regular expression that takes this into consideration: ### pattern = re.compile(r""" / \* ## Leading "/*" ( ## Followed by any number of ([^*]) ## non star characters | ## or (\* [^/]) ## star-nonslash )* \* / ## with a trailing "/*" """, re.VERBOSE) ### Does this work? Let's see this in action: ### >>> match = pattern.search(""" ... str = ajStrNew(); ... ... /* seed the random number generator */ ... ajRandomSeed(); ... """) >>> >>> match.group(0) '/* seed the random number generator */' >>> >>> >>> >>> >>> match = pattern.search(""" ... /* We comment out some code ... ... sprintf("We can use */ inside a string of course"); ... ... Now we end the comment */ ... """) >>> >>> match.group(0) '/* We comment out some code\n\nsprintf("We can use */' ### I hope this helps! From dyoo at hkn.eecs.berkeley.edu Wed Apr 21 15:07:34 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Apr 21 15:07:48 2004 Subject: [Tutor] Re: Finding C comments with regular expressions In-Reply-To: Message-ID: > The regular expression is a little tricky, because the beginning and > ending of a comment uses two characters instead of one. Here's a regular > expression that takes this into consideration: > > ### > pattern = re.compile(r""" > / \* ## Leading "/*" > > ( ## Followed by any number of > ([^*]) ## non star characters > | ## or > (\* [^/]) ## star-nonslash > )* > \* / ## with a trailing "/*" > """, re.VERBOSE) > ### Argh. The comment at the end of the regex is wrong. Let me correct that: ### pattern = re.compile(r""" / \* ## Leading "/*" ( ## Followed by any number of ([^*]) ## non star characters | ## or (\* [^/]) ## star-nonslash )* \* / ## with a trailing "*/" """, re.VERBOSE) ### I'm being too hasty these days... *grin* My apologies! From magnus at thinkware.se Wed Apr 21 15:11:06 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Wed Apr 21 15:11:25 2004 Subject: =?ISO-8859-1?B?UmU6IFJFOiBbVHV0b3JdIE9uIEdVSSdz?= Message-ID: I assume this was for the list. David Talaga wrote: > I understand what you are saying but lets take a look at the regular "user". > If we had a program like the one below and (for conversation's sake) only > the payroll individual can work within the program, now the person that is > in charge of inputting the information has quit. Now we have to train some > one else all over to do this same thing. With a GUI it is much more time > and cost efficient to train and use. The people that develop these kinds of > things are responsible for the upkeep. So, now all the person has to learn > is how to type. Simple as that. Type?! I have to type? Can't I just choose everything from a menu? ;) It's very different to write a program for "the regular user" or to write a program for oneself or for ones peers. I certainly think it's beneficial for the average Python hacker to get used to efficient command line interfaces, and the limitations of GUIs. On the other hand, I can respect if he doesn't force this "enlightenment" on all people around him... That might be a bit too close to the role of Don Quixote... :) But note three things: - If you have made a program like the one I suggested, you can always wrap it in a GUI or a Web UI. If it's a well written python program, you can just import it as a module from the GUI. Keeping the logic out of the GUI is usually a good thing. But if it's for your own use, it's rarely worth the effort. If the functionality is only accessible through the GUI, it's a dead end. - Windows, Icons, Menus and Pointing Devices (WIMP) might make easy things easier, but they certainly make many hard things even harder. Working a computer only through WIMP is a bit like trying to write messages using magnetic letters on a fridge door instead of learning how to use a pen and paper. It's one thing that GUIs are used by people who only rarely use computers, but I've seen paid (I would not say professional) programmers who get all pale if you open a command line prompt on their computer and try to explain how to do some trivial thing. I've seen database administrators, systems administrators and SCM administrators who have tried to manage the system they were resonsible for completely through the GUI. The administration GUIs for advanced systems like DB2, Oracle, ClearCase etc have a few things in common: - They have very limited functionality compared to the command line tools. - They are poorly implemented, often unstable, unreasonably resource hungry or hiding error messages etc in a way that makes using them into a confusing experience when you don't exactly follow the usage scenario imagined by the developer. - Experienced users rarely use them. - The reason they were written was to give the impression that this big and complex system isn't actually so difficult to use. - They actaully hinder users from learning how the system works, and how to make their work more effective. - People who only use GUIs never learn how to actually empower themselves by making the computer work for them in an effective way. They use the computer as "power steering" to make their work a little simpler, while they could actually make the computer do a lot of work on its own while they spend their time doing funnier things. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From vicki at stanfield.net Wed Apr 21 15:27:11 2004 From: vicki at stanfield.net (Vicki Stanfield) Date: Wed Apr 21 15:27:27 2004 Subject: [Tutor] Virtual Machine Terminology Message-ID: <20040421192711.GA8107@thepenguin.org> Is Python itself or tual machine is a machine written in software, which provides an abstract machine? Confused by the term itself, I went to applications. In a layered application the virtual machine acts as th and found this or a program written in Python considered to be a virtual machine? Confused by the term itself, I went online and found this definition: A virtual machine is a machine written in software, which provides an abstract layer to applications. In a layered application the virtual machine acts as the lowest layer, providing abstraction over the native environment. If an application is be ported to another environment only the virtual machine needs to be re implemented. The application layers written above it remain unchanged, as they use the same abstract interface to the virtual machine. This definition seems to fit almost any programming or scripting language. Is a BASH script which handles printing also then a virtual machine? Or even the operating system? Can anyone shed some light on this for me? --vicki From vicki at thepenguin.org Wed Apr 21 15:28:20 2004 From: vicki at thepenguin.org (Vicki Stanfield) Date: Wed Apr 21 15:28:32 2004 Subject: [Tutor] Virtual Machine Terminology Message-ID: <20040421192820.GA8190@thepenguin.org> Is Python itself or wxPython or a program written in Python considered to be a virtual machine? Confused by the term itself, I went online and found this definition: A virtual machine is a machine written in software, which provides an abstract layer to applications. In a layered application the virtual machine acts as the lowest layer, providing abstraction over the native environment. If an application is be ported to another environment only the virtual machine needs to be re implemented. The application layers written above it remain unchanged, as they use the same abstract interface to the virtual machine. This definition seems to fit almost any programming or scripting language. Is a BASH script which handles printing also then a virtual machine? Or even the operating system? Can anyone shed some light on this for me? --vicki From godoy at ieee.org Wed Apr 21 15:35:43 2004 From: godoy at ieee.org (Jorge Godoy) Date: Wed Apr 21 15:45:40 2004 Subject: [Tutor] Re: Parsing the contents of an email message. References: <20040421115047.E83197-100000@localhost.name> Message-ID: <9ivil1-qul.ln1@wintermute.g2ctech> On Qua 21 Abr 2004 15:59, tpc@csua.berkeley.edu wrote: > > hi Jorge, I am finishing up an application that grabs emails, passes them > through a filter, and parses them. I ended up using: > > import MySQLdb, re > from imaplib import IMAP4_SSL > from email import message_from_string > from email.Utils import parsedate_tz, mktime_tz > from time import strftime, strptime, localtime, time > > As you will see, dateTime is very important when parsing emails, > especially when debugging your application by writing an errorlog of > emails that didn't parse correctly. Thanks. I'm more interested in the contents of the message as I said and I'm planning on dealing with them sequentially as they arrive (using a Maildir or something like that and sorting the list of files by their creation date). Those files will be removed after successful processing them or the processing would stop at the defective file, so that it's possible to debug the problem. I ended up with something like that to get the contents of the (5) samples I had here: --------------------------------------------------------------------- import email.Parser import sys message = open(sys.argv[1], 'r') parsed_message = email.message_from_file(message) if parsed_message.is_multipart() is True: print parsed_message.get_payload(0) else: print "It is not a multipart message" print parsed_message.get_payload() --------------------------------------------------------------------- The "else" clause is there only for safety, since I found out that the messages I'm interested in are all MIME wrapped (but it works with other messages --- I tested it on a 154 messages Maildir). I'll adapt it to the program I'm writing. Now it's just a matter of parsing the contents of the payload. ;-) Thanks, -- Godoy. From magnus at thinkware.se Wed Apr 21 15:55:19 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Wed Apr 21 15:55:29 2004 Subject: =?ISO-8859-1?B?UmU6IFJFOiBbVHV0b3JdIE9uIEdVSSdz?= Message-ID: I assume this was for the list too: firephreek wrote: > >From what you've described, it seems like you've taken the gui as the > program. From what I've read from tkinter manuals and such, gui's seem > more like a front end to functions. I don't know if this is just a > fault of perception on my part or not, or if there is really any > difference at all. A GUI is certainly a front end to a computer program, but in many cases, the application logic is very tightly coupled with the GUI. You can do things differently. Tkinter is a wrapper over Tk, which is a GUI toolkit for the Tcl scripting language. Tcl is mainly intended as a "glue" language, a tool to provide a thin GUI and/or automation layer over other programs developed in systems programming languages such as C, C++ or Fortran. Regardless of your programming language and GUI tool kit, it's usually a good idea to try to make your GUI code thin and separate from the application logic, but this is something that needs to be determined individually for each project. Python is not the kind of simple scripting language Tcl is. It's very capable of handling advanced application logic, but it's still a good idea to keep logic and GUI in separate modules. The reason I described a non-GUI solution to an everyday problem was mainly to try to make people think outside the box. Most people have become so used to GUIs that they take them for granted and expect them to be the normal interface with the computer. This is a bit sad, since the GUI is often a dead end. > In the example you give, if I were to consider a gui for this sort of > app, I would want to just have a set of buttons that just run the > various command lines (rather, the functions that the command lines > effectively run with those args) maybe having some sort of display > window to show the results. Could this be as effective? Or am I > looking at this all wrong? Are there any 'rules of thumb' when it comes > to creating gui's? The Unix Philosophy suggests that you should write every program as a filter, make each program do one (and only one) thing well, and to use pipes and files to combine differnent programs to provide a multitude of functions. This is a very powerful approach, but it has two shortcomings: - It assumes quite a bit of skill from each computer user. - A stream of text sent from stdout of one program to stdin of the next isn't always the best data structure for data exchange between two pieces of code. As you are suggesting, python modules importing and calling each other opens for more power with less effort than the traditional Unix approach. And in Python it's easy to make a program file work both as a module to be used by others, and as a stand alone program. The Unix approach is still vastly superior to the traditional Windows approach to computer use though, where people often do things like run a monolithis program which displays a result in a window, and then they open another monolithic application and manually type what they see in the first window into a text entry field in the second window. Yuk! (Fortunately, Python and cygwin comes to the rescue for us who have to use Windows. After all, even Mac OS is Unix these days, and comes bundled with Python, so it's good that those crippled systems from Redmond can be complemented with some proper stuff! ;) For program integration approaches that allows you to use Python with code written in other languages, see http://www.thinkware.se/cgi-bin/thinki.cgi/UsingPythonWithOtherLanguages Anyway, I hope that even in this day and age, people will not always take a GUI for granted for every program they write, but that they consider other approaches to data entray, and most importantly, that they consider how useful it is to be able to quickly integrate various components into a new function. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From orbitz at ezabel.com Wed Apr 21 16:14:44 2004 From: orbitz at ezabel.com (orbitz@ezabel.com) Date: Wed Apr 21 16:16:09 2004 Subject: [Tutor] Virtual Machine Terminology In-Reply-To: <20040421192820.GA8190@thepenguin.org> References: <20040421192820.GA8190@thepenguin.org> Message-ID: <20040421161444.6baacd0f.orbitz@ezabel.com> Python is a language. A program written in Python is just a program. A in python written with wxPython is just a program. A virtual machine is what your python program will run in. It will interpret your python bytecode and offer your program an interface tothe actual machine. On Wed, 21 Apr 2004 14:28:20 -0500 Vicki Stanfield wrote: > Is Python itself or wxPython or a program written in Python considered to be a > virtual machine? Confused by the term itself, I went online and found this > definition: > > A virtual machine is a machine written in software, which provides an abstract > layer to applications. In a layered application the virtual machine acts as > the lowest layer, providing abstraction over the native environment. If an > application is be ported to another environment only the virtual machine needs > to be re implemented. The application layers written above it remain > unchanged, as they use the same abstract interface to the virtual machine. > > This definition seems to fit almost any programming or scripting language. Is > a BASH script which handles printing also then a virtual machine? Or even the > operating system? Can anyone shed some light on this for me? > > --vicki > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From magnus at thinkware.se Wed Apr 21 16:29:06 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Wed Apr 21 16:29:17 2004 Subject: [Tutor] Re: Finding C comments with regular expressions Message-ID: Danny Yoo wrote: > Actually, C should behave as if: > > > /* We comment out some code > > > > sprintf("We can use */ Silly me, of course. This is what the program I wrote did (I think). But you still has to take string literals into consideration, since a C comment can't start inside a string. E.g. the following C code contains no comments: a = " Oh /* dear"; b = " Here */ we go again"; I also think that the middle line below isn't commented out, right? // /* x = "Not commented out"; // */ On the other hand, the // in the line below doesn't start a C++ style comment... /* // */ ..so you can't just parse the code for all C++ comments first, and remove them, and then parse for C style comments and remove them, and you can't do it the other way around either. And even if you only had one type of comments, you have the same kind of problem with string literals, as you noticed above. I don't know how to write regular expressions to handle such things, and I feel overwhelmed by the thought of trying to describe and solve all the problems at once. With the state machine approach I described, I can solve my problem one step at a time. If I'm inside a macro I will get into a comment if I run into /* or //, and I will get into a string literal if I run into ", and the macro ends if I get to emacro. If I'm in a string literal I get out of it if I find " , and it's an error if the line ends. (There might be \ escapes to consider I guess.) If I'm in a C++ comment, it will end when the line ends and so on. Each piece is fairly simple. Combined they solve the problem. For speed use pyrex! -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From magnus at thinkware.se Wed Apr 21 18:29:50 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Wed Apr 21 18:29:59 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gVmlydHVhbCBNYWNoaW5lIFRlcm1pbm9sb2d5?= Message-ID: Orbitz wrote: > Python is a language. A program written in Python is just a program. A in > python written with wxPython is just a program. A virtual machine is what your > python program will run in. It will interpret your python bytecode and offer > your program an interface tothe actual machine. Well, virtual machine is not the same thing as an interpreter, even if you might say that "virtual machine" is just a fancy name for an interpreter. :) Vicki wrote: > Is a BASH script which handles printing also then a virtual machine? A bash script can't possibly be a virual machine, but the bash interpreter is not a virual machine in the typical sense of the word either. The term virtual machine has been used for the Python interpreter, but the terminology isn't completely clear cut, see for instance: http://wingide.com/pipermail/marketing-python/2004-February/005457.html When you write a program in e.g. C, you compile it into the machine language of the hardware you intend to run the program on. This is a much lower level language where you lack most of the abstractions of "normal" programming languages such as data types, loops etc. Here you shuffle individual bytes between various registers or memory locations, perform simple aritmetic and logic operations, and do conditional jumps between memory addresses etc. Each statement in C (or whatever) will typically translate into several machine code statements. This is the kind of instructions understood by the actual hardware you run on, the CPU. (Actually, there might be something called microcode in the CPU that interprets this, and that could be considered a kind of virtual machine as well, Transmeta has driven this approach very far, but never mind that now.) A Java program has to be compiled. The compiled java program consists of something called bytecode. This is machine code for a Java CPU, just as the code you get if you compile for a Pentium is machine code for a Intel Pentium. While Java CPUs have been manufactured, they never became a big hit, since Java turned out to be a programming language for normal computers, and not for toasters as originally intended. ;) So, the typical runtime environment for Java bytecode is not a Java chip, but a program, a Java Virtual Machine (JVM), which behaves as if it was a Java CPU chip and translates the Java instructions into machine code for the real CPU that we are running the program on. This way you can compile Java programs once and run them on many different hardware platforms. (At least in theory.) Bash isn't like this at all. Bash interprets plain text, and runs different routines based on how it interprets the text. Bash doesn't try to behave like a CPU at all. Python is more like Java. When you run (or import) a Python module it is compiled (if Python doesn't find an alreay compiled and uptodate .pyc or .pyo file). The result of the compilation is called bytecode, just like in the case of Java, and it's not very different. But python.exe *is* different from a JVM. First of all, Python bytecode doesn't always look the same. You can't expect .pyc-files made under one computer architecture to work on another computer architecture, it will for instance look different on a 64 bit machine and on a 32 bit machine. Secondly, the Python interpreter (or PVM) doesn't quite pretend to be a machine of its own the way Java does. It doesn't shield you from the surrounding operating system. A Python program can interact with the surrounding computer platform, and access native machine code programs on the current platform in a way Java programs can't. The PVM is not the kind of isolated island that the JVM is. It seems the concept of virtual machines have confused people before. See for instance (note the answer for the second question :). http://mail.python.org/pipermail/python-list/2002-November/132562.html Microsofts .NET environment contains a Virtual Machine called Common Language Runtime (CLR), and C#, VB.NET, COBOL.NET etc all compile to CLR bytecode. The Perl developers are constructing a Virtual Machine for the upcoming Perl version 6, which is called Parrot. (The name actually started as an April's fool's joke about a merger between Python and Perl.) The Parrot developers seems convinced that the Parrot Virtual Machine will be able to run Python programs faster than the Python interpreter, but few Python developers seem to believe that. We'll see during OSCON this summer when the Pie-Thon competition will take place. Either way, we win! :) -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From op73418 at mail.telepac.pt Wed Apr 21 18:30:52 2004 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Wed Apr 21 18:34:17 2004 Subject: [Tutor] Virtual Machine Terminology In-Reply-To: <20040421192820.GA8190@thepenguin.org> References: <20040421192820.GA8190@thepenguin.org> Message-ID: Em Wed, 21 Apr 2004 14:28:20 -0500, Vicki Stanfield atirou este peixe aos pinguins: >Is Python itself or wxPython or a program written in Python considered to be a >virtual machine? Confused by the term itself, I went online and found this >definition: > >A virtual machine is a machine written in software, which provides an abstract >layer to applications. In a layered application the virtual machine acts as the >lowest layer, providing abstraction over the native environment. If an >application is be ported to another environment only the virtual machine needs >to be re implemented. The application layers written above it remain unchanged, >as they use the same abstract interface to the virtual machine. > >This definition seems to fit almost any programming or scripting language. Is a >BASH script which handles printing also then a virtual machine? Or even the >operating system? Can anyone shed some light on this for me? > Yes, the definition is a little too vague... Think of a virtual machine (VM) as an application simulating an idealized computer. As you know, the original language of every CPU is assembler, and just as a program in C, say, is translated to this assembler language so that it can be run on your home computer, a Python program (and a Java, and a Perl, and...) is compiled to the "assembler language" of the Python virtual machine, so that Python's VM (another program) can run it. As the above definition states, this provides a layer of abstraction. You can change the implementation of the VM without all the programs targetting it. Also, note that the "assembler language" of Python is/was especially designed with the Python language in mind. It is considerably at a "higher level" than your usual raw asembler (copy this address of memory to the register, push this address to the stack, pop from the stack, etc..) with bytecodes (the names of the single Python "assembler language" instructions) for fetching an attribute, calling a method, etc. Hope it helps, with my best regards, G. Rodrigues From tim at johnsons-web.com Wed Apr 21 18:44:02 2004 From: tim at johnsons-web.com (Tim Johnson) Date: Wed Apr 21 18:42:24 2004 Subject: [Tutor] Finding Match in nexted tuple Message-ID: <20040421224402.GI19982@johnsons-web.com> Let's say I have a list of zip codes returned from a MySQLdb query zip_code_list = (('84536',), ('85003',), ('85004',), ('85006',), ('85007',), ('85008',)) # and I want to look for a match for a value like '85004' # I can think of doing it like this: (untested) zzip = '85004' for Z in zip_code_list: if zzip in Z: print 'found' But: Is there a quicker or more pythonesque way to do this? Even tho' I *think* I know what I'm doing I tend to get really interesting answers from you'all. thanks tim -- Tim Johnson http://www.alaska-internet-solutions.com From zmerch at 30below.com Wed Apr 21 19:32:33 2004 From: zmerch at 30below.com (Roger Merchberger) Date: Wed Apr 21 19:31:30 2004 Subject: [Tutor] Finding Match in nexted tuple In-Reply-To: <20040421224402.GI19982@johnsons-web.com> Message-ID: <5.1.0.14.2.20040421191528.049952d0@mail.30below.com> At 02:44 PM 4/21/2004 -0800, Tim Johnson wrote: >Let's say I have a list of zip codes returned from a MySQLdb query >zip_code_list = (('84536',), ('85003',), ('85004',), ('85006',), > ('85007',), ('85008',)) ># and I want to look for a match for a value like '85004' ># I can think of doing it like this: (untested) Maybe I'm being a blasphemer here, but why not put the zipcode in as part of your MySQLdb query? At least for me, knowing more about how you're getting your dataset from MySQL would help me more on how to better answer your question. Laterz, Roger "Merch" Merchberger -- Roger "Merch" Merchberger | "Bugs of a feather flock together." sysadmin, Iceberg Computers | Russell Nelson zmerch@30below.com | From tim at johnsons-web.com Wed Apr 21 19:52:16 2004 From: tim at johnsons-web.com (Tim Johnson) Date: Wed Apr 21 19:50:38 2004 Subject: [Tutor] Finding Match in nexted tuple In-Reply-To: <5.1.0.14.2.20040421191528.049952d0@mail.30below.com> References: <20040421224402.GI19982@johnsons-web.com> <5.1.0.14.2.20040421191528.049952d0@mail.30below.com> Message-ID: <20040421235214.GJ19982@johnsons-web.com> * Roger Merchberger [040421 15:39]: > At 02:44 PM 4/21/2004 -0800, Tim Johnson wrote: > >Let's say I have a list of zip codes returned from a MySQLdb query > >zip_code_list = (('84536',), ('85003',), ('85004',), ('85006',), > > ('85007',), ('85008',)) > ># and I want to look for a match for a value like '85004' > ># I can think of doing it like this: (untested) > > Maybe I'm being a blasphemer here, but why not put the zipcode in as part > of your MySQLdb query? :-) You're not being a blasphemer, that's a real world way for that particular problem, I should have used a different example... My question still stand regardless of whether its from mysql or not. What if it were a hard-coded data-structure? thanks tim > At least for me, knowing more about how you're getting your dataset from > MySQL would help me more on how to better answer your question. > > Laterz, > Roger "Merch" Merchberger > > -- > Roger "Merch" Merchberger | "Bugs of a feather flock together." > sysadmin, Iceberg Computers | Russell Nelson > zmerch@30below.com | > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Tim Johnson http://www.alaska-internet-solutions.com From magnus at thinkware.se Wed Apr 21 20:57:41 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Wed Apr 21 20:57:50 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gRmluZGluZyBNYXRjaCBpbiBuZXh0ZWQgdHVwbGU=?= Message-ID: Tim Johnson wrote: > Let's say I have a list of zip codes returned from a MySQLdb query > zip_code_list = (('84536',), ('85003',), ('85004',), ('85006',), > ('85007',), ('85008',)) > # and I want to look for a match for a value like '85004' If you know that the format is exactly like that, you can simply do: if ('85004',) in zip_code_list: print "Found!" ..but maybe that's not what you intended? If '85004' might just be in an arbitrary position in a sequence of tuples with more columns than the zip codes, you could for instance do: if '85004' in str(zip_code_list): print "Found!" -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From tim at johnsons-web.com Wed Apr 21 21:32:36 2004 From: tim at johnsons-web.com (Tim Johnson) Date: Wed Apr 21 21:31:01 2004 Subject: [Tutor] Finding Match in nexted tuple In-Reply-To: References: Message-ID: <20040422013236.GK19982@johnsons-web.com> * Magnus Lycka [040421 17:04]: > Tim Johnson wrote: > > Let's say I have a list of zip codes returned from a MySQLdb query > > zip_code_list = (('84536',), ('85003',), ('85004',), ('85006',), > > ('85007',), ('85008',)) > > # and I want to look for a match for a value like '85004' > > If you know that the format is exactly like that, you can > simply do: > > if ('85004',) in zip_code_list: > print "Found!" Good tip.. > ..but maybe that's not what you intended? If '85004' might > just be in an arbitrary position in a sequence of tuples with > more columns than the zip codes, you could for instance do: > > if '85004' in str(zip_code_list): > print "Found!" Eureka! That's what I meant by a 'pythonesque' solution. I must ask: what is the overhead in the call to str? I presume that str(zip_code_list) is being handled by compiled binary ("C") code - so must not be too much, I bet. Thank you Magnus. tim > -- > Magnus Lycka, Thinkware AB > Alvans vag 99, SE-907 50 UMEA, SWEDEN > phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 > http://www.thinkware.se/ mailto:magnus@thinkware.se -- Tim Johnson http://www.alaska-internet-solutions.com From alan.gauld at blueyonder.co.uk Thu Apr 22 03:04:00 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Apr 22 03:04:01 2004 Subject: [Tutor] On GUI's References: Message-ID: <005301c42837$fd687450$6401a8c0@xp> DT> I understand what you are saying but lets take a look at the regular "user". I know what you mean David, but strictly speaking the *regular* user is the one who benefits from a command line interface, it is the *irregular user* who benefits from a GUI! :-) DT> If we had a program like the one below and (for conversation's sake) only DT> the payroll individual can work within the program, now the person that is DT> in charge of inputting the information has quit. Now we have to train some DT> one else all over to do this same thing. And the question you need to answer is: Will the cost of training exceed the time saved in improved productivity after training? In other words how often do you need to train.? DT> With a GUI it is much more time and cost efficient to train and use. NO, its more cost efficient to train but not to use. A good CLI is faster than a GUI, but less friendly. The book "The Pragmatic Programmer" has much to say on this. ML> - If you have made a program like the one I suggested, you can always ML> wrap it in a GUI or a Web UI. If it's a well written python program, And this is an absolutely vital point. If you structure your program well you can separate the interface from the working code. This allows you to wrap it in a GUI as well as have a CLI. The users get the best of both worlds. ML> - People who only use GUIs never learn how to actually empower ML> themselves by making the computer work for them in an effective ML> way. They use the computer as "power steering" to make their ML> work a little simpler, And of course there is nothing wrong with this either. Provided we recognise the limitations of the approach. For example I used command line email for years and it had a lot of power. But nowadays I use a GUI client and am quite happy because I simply don't need the power. And for the few things I do in mail the GUI is more fun to use. Alan G From alan.gauld at blueyonder.co.uk Thu Apr 22 03:21:09 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Apr 22 03:21:07 2004 Subject: [Tutor] Virtual Machine Terminology References: <20040421192711.GA8107@thepenguin.org> Message-ID: <005801c4283a$62864f40$6401a8c0@xp> > Is Python itself a virtual machine? No. But the current implementations of Pyhon employ a virtual machine architecture. > A virtual machine is a machine written in software, which > provides an abstract layer to applications. In a layered > application the virtual machine acts as the lowest layer, > providing abstraction over the native environment. A virtual machine is a set of primitive operations soimilar to those provided by assembler. These operations come with an interpreter than translates them into native machine code for the native platform (Unix, Windows, VMS etc) Python for example compiles code into .pyc files. These are the virtual machine executables but they are not executable on the native machine (you need Python installed to use them). You can see a representation of the pyc files by using the Python disassembler module. You will see Python assembler whilch looks a lot like a high level native assembler language. The Python interpreter then translates these assembler codes into native machine code. This is much easier to port than a full Python translator would be and is one reason why Python is so portable. The virtual machine (the pyc files) are the same its only the underlying translation that differs. Jython works slightly differently. It compiles python source into Java Virtual assembler. Then you use the standard Java translator to convert from JVM code to native code. So the same Python source can run on the Python virtual machine or a Java virtuial machine depending on the compiler you choose. This shows that it is not Python itself that is the virtual machine but rather the implementation. > This definition seems to fit almost any programming or > scripting language. Is a BASH script which handles printing > also then a virtual machine? No. Many programming languages translate the source directly into native machine code. Bash interprets commands directly into executable code. Compiled C is simply native machine code. VB, Perl, Python, Smalltalk, UCSD Pascal and others all use a virtual machine approach. Microsoft .NET platform is another example of a virtual machine. Here it doesn't matter which language you use(VB.NET, C#, Managed C++, Python.NET) it all gets translated into the common runtime language. The .NET platform then runs the program by translating the CLR code into Win32 code. (There is at least 1 project working on translating NET virtual machine to Linux...) HTH, Alan G. From alan.gauld at blueyonder.co.uk Thu Apr 22 03:27:54 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Apr 22 03:27:50 2004 Subject: [Tutor] Virtual Machine Terminology References: Message-ID: <007201c4283b$53a99260$6401a8c0@xp> > doesn't always look the same. You can't expect .pyc-files made under one > computer architecture to work on another computer architecture, it will > for instance look different on a 64 bit machine and on a 32 bit machine. Is this true? I though pyc files were portable between architectures. For example I can take pyc files from my windows box and run them on my Sun box. (Admittedly they are both still 32 bit but I thought even that should be transparent) Alan G. From magnus at thinkware.se Thu Apr 22 06:08:42 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Thu Apr 22 06:08:54 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gRmluZGluZyBNYXRjaCBpbiBuZXh0ZWQgdHVwbGU=?= Message-ID: Tim Johnson wrote: > > if '85004' in str(zip_code_list): > > print "Found!" > > Eureka! That's what I meant by a 'pythonesque' solution. > > I must ask: what is the overhead in the call to str? That obviously depends on the size of your tuple... You don't really need to ask, sincce it's so easy to measure. >>> import time >>> t = tuple(range(10000)) >>> start=time.clock();s=str(t);stop=time.clock() >>> print stop-start 0.0117802648716 >>> print (stop-start)/len(s) 2.00038459358e-007 >>> t = tuple(range(100000)) >>> start=time.clock();s=str(t);stop=time.clock() >>> print stop-start 0.129701084998 >>> print (stop-start)/len(s) 1.88275464875e-007 >>> t = tuple(range(1000000)) >>> start=time.clock();s=str(t);stop=time.clock() >>> print stop-start 1.45181707401 >>> print (stop-start)/len(s) 1.84033124306e-007 About 0.2 microseconds per character in the string on a machine which benchmarks at 24469.9 pystones/second. :) But these aren't nested tuples. Does that make a difference? >>> t = tuple([(x,) for x in range(10000)]) >>> start=time.clock();s=str(t);stop=time.clock() >>> print stop-start 0.0236703202027 >>> print (stop-start)/len(s) 2.66287773683e-007 >>> t = tuple([(x,) for x in range(100000)]) >>> start=time.clock();s=str(t);stop=time.clock() >>> print stop-start 0.245343962614 >>> print (stop-start)/len(s) 2.48100357587e-007 >>> t = tuple([(x,) for x in range(1000000)]) >>> start=time.clock();s=str(t);stop=time.clock() >>> print stop-start 2.9241021068 >>> print (stop-start)/len(s) 2.68539961998e-007 It grew? Let's try once more. >>> start=time.clock();s=str(t);stop=time.clock() >>> print stop-start 2.66894405045 >>> print (stop-start)/len(s) 2.45107081663e-007 So, it seems we end up at 0.25 microseconds per character in the resulting string for your type of nested tuple. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From denis.spir at free.fr Thu Apr 22 06:36:36 2004 From: denis.spir at free.fr (denis) Date: Thu Apr 22 07:47:27 2004 Subject: [Tutor] Finding Match in nexted tuple References: <20040422013236.GK19982@johnsons-web.com> Message-ID: <003f01c4285f$83597a60$ca25933e@spir> ----- Original Message ----- From: Tim Johnson To: Sent: Thursday, April 22, 2004 3:32 AM Subject: Re: [Tutor] Finding Match in nexted tuple > * Magnus Lycka [040421 17:04]: > > Tim Johnson wrote: > Tim Johnson wrote: > > Let's say I have a list of zip codes returned from a MySQLdb query > > zip_code_list = (('84536',), ('85003',), ('85004',), ('85006',), > > ('85007',), ('85008',)) > > # and I want to look for a match for a value like '85004' > > If '85004' might > > just be in an arbitrary position in a sequence of tuples with > > more columns than the zip codes, you could for instance do: > > > > if '85004' in str(zip_code_list): > > print "Found!" > > Eureka! That's what I meant by a 'pythonesque' solution. > > I must ask: what is the overhead in the call to str? > > I presume that str(zip_code_list) is being handled by compiled binary > ("C") code - so must not be too much, I bet. > > Thank you Magnus. > tim I don't know mySQL, especially if that kind of tuple of single value tuples is its standard query result form. If yes, and i had to work with such thing, I would write a short function to make simple list out of them : def ThingsToList : >>> zip_list=(('84536',), ('85003',), ('85004',), ('85006',),('85007',), ('85008',)) >>> list(zip_list) [('84536',), ('85003',), ('85004',), ('85006',), ('85007',), ('85008',)] # no way with list() ! # one solution : >>> def QueryResultToList(t) : l=[] for item in t : l.append(item[0]) return l >>> zips = QueryResultToList(zip_list) >>> zips ['84536', '85003', '85004', '85006', '85007', '85008'] >>> '85004' in zips True This is the most versatile solution, as it then allows you any operation on your query result, not only searching an element in it, with a simple, one level, list. In you only need searching, you may build a more specific function for that purpose, changes the searched item rather than the query result's structure : >>> def FoundInQueryResult(t,s) : # tuple is a tuple of single element tuples # s is a string, item (below) a single element tuple item=(s,) ; print item # print statement only for test p?rpose if item in t : return True else : return False >>> FoundInQueryResult(zip_list,'85004') ('85004',) True I hope both of these solutions are pythonesque ! (they're really my coding style) Now, if your needs of processing with such things are really big, you'd better write a QueryResult class, and implement such function as methods. This would lead to nicer (my OOP taste) code like this : zip_list.found('85004') denis From magnus at thinkware.se Thu Apr 22 08:58:32 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Thu Apr 22 09:16:26 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gVmlydHVhbCBNYWNoaW5lIFRlcm1pbm9sb2d5?= Message-ID: Alan Gauld wrote: > > doesn't always look the same. You can't expect .pyc-files made under > one > > computer architecture to work on another computer architecture, it > will > > for instance look different on a 64 bit machine and on a 32 bit > machine. > > Is this true? I though pyc files were portable between architectures. > For example I can take pyc files from my windows box and run them on > my Sun box. (Admittedly they are both still 32 bit but I thought even > that should be transparent) Now that you question it, I'm not sure. On the other hand, the byte code is not guaranteed to be the same between Python versions, which is probably a worse problem. You might well be right, since I probably heard about this when I used Python version 1.4.2 or something like that... I put some integers in a list and looked at the corresponding byte code, and for numbers like 1, 2, 258, ... the byte code showed 105 1 0 0 0 105 2 0 0 0 105 2 1 0 0 105 ... which is consistent with what I expected for a 32 bit little endian, but when the numbers got bigger, such as 16777217 (256**3+1) I was expecting to see 105 1 0 0 1 105, but instead I saw 105 2 0 0 0 78 40 1 0 0 0 115, so it seems Python changes the way it stores integers as they grow bigger. I tried to look at the modules in the standard Python compiler package, to understand how this is handled, but this is far over my head... I'd need someone to lead me gently through that code to understand how it works. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From Chad.Crabtree at nationalcity.com Thu Apr 22 10:15:32 2004 From: Chad.Crabtree at nationalcity.com (Crabtree, Chad) Date: Thu Apr 22 10:16:34 2004 Subject: FW: RE: [Tutor] On GUI's Message-ID: <66F587DFDD46D511B65200508B6F8DD612B99402@nt-kalopsapp07.ntl-city.com> -----Original Message----- From: Crabtree, Chad Sent: Thursday, April 22, 2004 9:39 AM To: 'Alan Gauld' Subject: RE: RE: [Tutor] On GUI's > ML> - If you have made a program like the one I suggested, you can > always > ML> wrap it in a GUI or a Web UI. If it's a well written python > program, > > And this is an absolutely vital point. If you structure your > program well you can separate the interface from the working > code. This allows you to wrap it in a GUI as well as have a > CLI. The users get the best of both worlds. > > ML> - People who only use GUIs never learn how to actually empower > ML> themselves by making the computer work for them in an effective > ML> way. They use the computer as "power steering" to make their > ML> work a little simpler, > I got started (but didn't finish) a Dietitian tool and thinking it would be nice separate the UI from the code I tried first to do this with a menu driven text UI. They code for the UI got way more complex and confusing than the program logic. Since I have lambasted myself for not just designing the GUI first then doing the engine part. I'm doing this now on a project I'm doing it's helping me to better understand what needs to be done. Perhaps this is because of my exposure to GUI's that I kind of think in them. However the conversation on pipes and filters and stuff is interesting. I was reading about modularity (where I cannot remember, think it was the guy who started bonobo 'GNOME') they author mentioned the UNIX way of doing things. He mentioned COM and how much he liked it and others Like CORBA XML-RPC. I just wanted to comment on this because the UNIX way seems more error prone than the remote procedure calls. With RPC's you can be reasonable certain about the data and stuff. However this has more or less been said in this thread in regards to python's import functionality. It's my impression that the UNIX way is kind of the old way, oven open source is going toward greater and greater abstraction. GNOME team seems to be putting a lot of wieght behind the MONO project. For what it's work C# look pretty decent. ------------------------------------------------------------------------------------------- ***National City made the following annotations ------------------------------------------------------------------------------------------- This communication is a confidential and proprietary business communication. It is intended solely for the use of the designated recipient(s). If this communication is received in error, please contact the sender and delete this communication. =========================================================================================== From magnus at thinkware.se Thu Apr 22 10:58:43 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Thu Apr 22 11:24:12 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gRmluZGluZyBNYXRjaCBpbiBuZXh0ZWQgdHVwbGU=?= Message-ID: Denis wrote: > # one solution : > >>> def QueryResultToList(t) : > l=[] > for item in t : > l.append(item[0]) > return l > >>> zips = QueryResultToList(zip_list) With list comprehension, this would be: zips = [item[0] for item in zip_list] Once you get used to the concept, it feels quite natural and obvious to write it like this. Whether to use a "brute force" approach like converting the entire tuple of tuples to a string, or to actually use the data structure as intended is a matter of your own judgement. In the typical case, with arbitrary kind of data from a database table, I'd certainly want to make sure that the number I found was really from the zip code column, and not a salary or something entirely different! Sometimes, there are pressing reasons to use shortcuts though, and knowing how to make things faster is often a good thing. The trick is often to use the builtin features of Python that are implemented in C, in a clever way. For instance, Python (used right) is the fastest tool I have found to be available on the Windows box where I work for simple search and replace operations in very large files. I don't use y = x.replace(a,b) though, I use l = x.split(a); y = b.join(l) E.g, I want to remove all ';' in a 1571 kB SQL file. With notepad, the search/replace operation takes 80 seconds. With such a tiny file, both Python approaches work well. >>> start=time.clock();d2=d.replace(';','');print time.clock()-start 0.0231808726582 >>> start=time.clock();l=d.split(';');d2="".join(l);print time.clock()-start 0.184793267079 str.replace() is actaully 8 times faster than my split/join trick, but 0.18 seconds is fast enough... If we make the file ten times bigger (15 MB) we have a tie: >>> start=time.clock();d2=d.replace(';','');print time.clock()-start 0.235426783173 >>> start=time.clock();l=d.split(';');d2="".join(l);print time.clock()-start 0.221046747269 I don't want to think about how long it would take to do search and replace of a 15MB file in notepad, or any other Windows editor. It might even be a bit slow in vi. Naturally, the pain treshold has to do with the amount of RAM available, and on the machine I sit at now, I didn't wait for either of my search and replace strategies to finish with a 150 MB file. But I did try it on a 45 MB file. >>> start=time.clock();l=d.split(';');d2="".join(l);print time.clock()-start 0.634140474798 >>> start=time.clock();d2=d.replace(';','');print time.clock()-start 20.1864200097 See? With this size, split/join is almost 32 times faster than str.replace. Even str.count() is slower than str.split() on big strings. >>> start=time.clock();print d.count(';');print time.clock()-start 300780 1.84793015651 >>> start=time.clock();print len(d.split(';'))-1;print time.clock()-start 300780 0.614577658731 Of course, these kinds of performace difference between different approaches are certainly as common in other languages, but in Python it's so quick and easy to evaluate different working solutions like this, so you're likely to reach an optimized state much quicker in Python than in most other languages. That's a reason Python programs are often not nearly as slow compared to programs written in C++ or C etc, as the difference in raw processing speed might suggest. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From tony at tcapp.com Thu Apr 22 12:49:32 2004 From: tony at tcapp.com (Tony Cappellini) Date: Thu Apr 22 12:49:30 2004 Subject: [Tutor] Python development-moving from Windows to Linux (finally) In-Reply-To: Message-ID: <20040422093845.S75398-100000@yamato.yamato.com> I've installed Python on a linux system, and now I'm trying to understand how to better configure my environment for executing python scripts that I've written. THe scripts that I've written do have the shebang line, and do have the permissions set to executable. However, since I've written so many, I don't think it is really feasible to add 20 or more directories to my path, or to PYTHONPATH. When developing a script, I usually test is in the current project directory, until it's finished. Then I move the script to a directory in the execution path. Just like a binary exectuable, I would like to have all of my executable python scripts in one directory (ie /home/tony/bin - or whatever I decide). However, when I'm not in the directory where my python scripts are, I find that I need to add the explicit path to the python script, in order to be able to run it /home/tony/bin/myscript.py This mechanism obviosuly defeats the whole purpose of having directories in a searcable path. I've already added /home/tony/bin to my PYTHONPATH (all caps) in my.bashrc, and exported it. I can see it by typing echo $PYTHONPATH Would anyone care to drope me a hint ? thanks From Chad.Crabtree at nationalcity.com Thu Apr 22 13:04:44 2004 From: Chad.Crabtree at nationalcity.com (Crabtree, Chad) Date: Thu Apr 22 13:05:02 2004 Subject: FW: [Tutor] Python development-moving from Windows to Linux ( fin ally) Message-ID: <66F587DFDD46D511B65200508B6F8DD612B99407@nt-kalopsapp07.ntl-city.com> -----Original Message----- From: Crabtree, Chad Sent: Thursday, April 22, 2004 1:04 PM To: 'Tony Cappellini' Subject: RE: [Tutor] Python development-moving from Windows to Linux ( finally) I'm not sure but I believe you need to append to the $PATH the directory your talking about. $PYTHONPATH tells python where to look for modules and such. ------------------------------------------------------------------------------------------- ***National City made the following annotations ------------------------------------------------------------------------------------------- This communication is a confidential and proprietary business communication. It is intended solely for the use of the designated recipient(s). If this communication is received in error, please contact the sender and delete this communication. =========================================================================================== From dyoo at hkn.eecs.berkeley.edu Thu Apr 22 13:16:34 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Apr 22 13:17:42 2004 Subject: [Tutor] Finding Match in nexted tuple In-Reply-To: <20040422013236.GK19982@johnsons-web.com> Message-ID: On Wed, 21 Apr 2004, Tim Johnson wrote: > * Magnus Lycka [040421 17:04]: > > Tim Johnson wrote: > > > Let's say I have a list of zip codes returned from a MySQLdb query > > > zip_code_list = (('84536',), ('85003',), ('85004',), ('85006',), > > > ('85007',), ('85008',)) > > > # and I want to look for a match for a value like '85004' > > > > If you know that the format is exactly like that, you can > > simply do: > > > > if ('85004',) in zip_code_list: > > print "Found!" > > Good tip.. > > > ..but maybe that's not what you intended? If '85004' might > > just be in an arbitrary position in a sequence of tuples with > > more columns than the zip codes, you could for instance do: > > > > if '85004' in str(zip_code_list): > > print "Found!" > > Eureka! That's what I meant by a 'pythonesque' solution. Hi Jim, Be wary of string solutions. In this particular case, a string-search approach will work because we're assuming fixed-width, comma-delimited zip-code data. In the general case, we have to be careful, because the 'in' check on strings is a "substring' check. Not only is something like: 'hello' in 'hello world' True, but 'or' in 'hello world' is also True. That's why string-searching approaches to lookup can be potentially flaky. I suspect that the first approach that Magnus suggested, if ('85004',) in zip_code_list: ... is probably faster than the str() approach, but I have no empirical data yet to back my guesses. *grin* But I'd feel more secure about using this, as opposed to "if '85004' in str(zip_code_list): ...". Both approaches, though, use a linear scan through 'zip_code_list'. If your list is long, and if you plan to do repeated searches, then you may want to later look into 'sets': http://www.python.org/doc/lib/module-sets.html as they allow us to look things up more efficiently than in the two previous approaches. Hope this helps! From bvande at po-box.mcgill.ca Thu Apr 22 13:34:25 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Thu Apr 22 13:36:31 2004 Subject: [Tutor] how best to store and process varriable ammounts of paired data Message-ID: <40880221.2070003@po-box.mcgill.ca> Hi all, I'm starting a project to write a bunch of functions for parsing the datafiles of a particular application I use. Thanks to help from the group I now understand how to work with files :-) but I have a question about efficient storage of the information I extract. I want to extract from the files two types of lines that always come in pairs where one is a unique numerical id and the other a title string. The id numbers are unique, but not necessarily in numerical order. The associated strings are not necessarily unique. The lines are seperated by varriable ammounts of data, but in each case, I am sure I know how to extract only the information of interest. :-) After extraction I want to do something with those pairs. My tasks will leave the pair invarriant in the extracted data I store, so an immutable type is fine. There can be anywhere from a small number of pairs to tens of thousands, depending on the particular datafile in question. I can think of three main methods for storing and using the extracted data. 1) Iterate over the file and build a dictionary as I go, using the identified numerical ids as the keys, and the title strings as the values. Then work by iteration over the dictionary keys. 2) Iterate the file and build two lists, one of the id's and one of the title strings. Then: a) make a dictionary from the lists and work with the dictionary, or b) Just work from the lists themselves, iterating over the indices. 3) Parse the file, building tuples (id, string title) as I go and putting them in a list. Then iterate over the list, and read each tupple value as needed. So, since there may be 1000's of (id, title) pairs, I am wanting to choose the best method -- best here being defined as some compromise between high speed and small memory footprint. Pointers as to which method here listed would be the way to go? Or some other way I've overlooked? Or, I am worrying about something that doesn't really matter? Perhaps my problem is, last name notwithstanding, I'm not Dutch: There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. ;-) Thanks and best to all, Brian vdB From chidorex-pytutor at yahoo.com Thu Apr 22 14:24:44 2004 From: chidorex-pytutor at yahoo.com (Rex) Date: Thu Apr 22 14:24:50 2004 Subject: [Tutor] Standard library modules not installed Message-ID: <20040422182444.34404.qmail@web13422.mail.yahoo.com> Hi, I'm a newbie to Python, but proficient in Perl. Loving it so far :) I wrote a basic program that uses the comma-separated values standard library csv to work on files. I use a Gentoo Linux box as my main developing environment and csv is included as it is supposed to be. However, I am going to run this program in a RedHat 9 machine, and for some strange reason some libraries are not included in this python installation (ver. 2.2.2). I have looked at several library locations (e.g. Vaults of Parnassus) but the standard libraries are not there. Where can I find and install these libraries that should, AFAIK, be included in the standard installation of Python? Why would these libraries be missing from the RPM python package? Do you know if there is any RPM package that includes these libraries? Might be even easier to get. Thanks for your help. Rex -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040422/f77e6f1f/attachment.html From tony at tcapp.com Thu Apr 22 14:32:34 2004 From: tony at tcapp.com (Tony Cappellini) Date: Thu Apr 22 14:32:37 2004 Subject: [Tutor] Python development-moving from Windows to Linux (finally) In-Reply-To: <4088060A.6080406@chrislott.org> Message-ID: <20040422113053.S78102-100000@yamato.yamato.com> On Thu, 22 Apr 2004, Chris Lott wrote: > Tony Cappellini wrote: > > > > > I've installed Python on a linux system, and now I'm trying to understand > > how to better configure my environment for executing python scripts that > > I've written. > > I think you have two paths confused. As I understand it, $PYTHONPATH is > just for the location of Python executables, modules, etc. > > If you want to run your scripts without specifying the location, they > need to be somewhere in your $PATH, which specifies where the shell > looks for executables when you try to run them. So just add > /home/tony/bin to your $PATH variable. > This is already in the path. It was a default, I didn't add it. This is why I don't understand why I need to use /home/tony/bin/myscript.py to run my scripts. From magnus at thinkware.se Thu Apr 22 14:41:39 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Thu Apr 22 14:48:32 2004 Subject: =?ISO-8859-1?B?UmU6IEZXOiBSRTogW1R1dG9yXSBPbiBHVUkncw==?= Message-ID: Chad Crabtree wrote: > I got started (but didn't finish) a Dietitian tool and thinking it would be > nice separate the UI from the code I tried first to do this with a menu > driven text UI. They code for the UI got way more complex and confusing > than the program logic. Since I have lambasted myself for not just > designing the GUI first then doing the engine part. I'm doing this now on a > project I'm doing it's helping me to better understand what needs to be > done. Perhaps this is because of my exposure to GUI's that I kind of think > in them. If it works for you, it's good. It's important to consider how the system is to be used of course, and thinking about the user interface might help you to do that. On the other hand, thinking too much about the user interface too early might make you a bit narrowminded about the application, and just because you failed to write a program and tried to write the logic first that time, it doesn't mean that writing the GUI first is a better solution in general. The important thing in my mind is to separate the application logic from the user interface code. > However the conversation on pipes and filters and stuff is interesting. I > was reading about modularity (where I cannot remember, think it was the guy > who started bonobo 'GNOME') they author mentioned the UNIX way of doing > things. He mentioned COM and how much he liked it and others Like CORBA > XML-RPC. I just wanted to comment on this because the UNIX way seems more > error prone than the remote procedure calls. With the unix approach, any power user who is familiar with the general tools can cook up his own applications without any programming. You can't do that with remote procedure calls or object request brokers. Thus, you are back to a situation where the programmers have to predict all stuff the users will ever want to do, and write more or less monolithic applications (even if they are distributed and built from components) that the users use just the way they are. Unix is like a well equipped workshop where a good craftsman can do really great things, while some people are more likely to just injure themselves. Windows is more like a vending machine where you enter coins, press buttons and (hopefully) get the stuff you select from the limited selection available. At least when I am in my romantic mode, I much prefer the idea of more and more people being able to use a good workshop, than the idea of providing better and better vending machines with more and more buttons... I wrote a simple application to demonstrate how GUI layer and application layer can be separated. The program below is now also placed at http://www.thinkware.se/cgi-bin/thinki.cgi/GuiSampleApp I really perfer wxPython to Tkinter, but I don't have access to that right now. Anyway, with this application, you can click in the list box, enter a name in the entry field of the new window that popped up, save that etc. By clicking on names in the list, you open their entries, and you can edit or delete them. Changes are saved to file when you quit. It's a meaningless little application, but it shows you the principle. I put it all into one file, but it's trivial to split this into two files, one with the application logic, and one with the GUI. The application logic is very simple in this case. It's basically just an interface to a little register stored as a shelve. The PersonModel class has methods for adding, updating, removing, returning and listing persons. It has a commit method to persist the database, and it supports the Observer pattern so that Views of the data can be updated when something changes. (You will see how the listing changes if you delete or save a person for instance.) This program is similar to the Model View Controller Pattern used in SmallTalk, but since GUI tool kits like Tkinter have the system for event handling and callbacks that they have, it's really little point making a separate Controller class, so I didn't do that. (The MVC Controllers in SmallTalk we subclasses of a Control class which handled the interaction with mouse and keyboard.) Please ask/comment. # Application logic part import shelve ALL_OBJECTS = 'ALL OBJECTS' DB_FILE_NAME = 'person.db' class PersonModel: def __init__(self): self._observers = {} self._persons = shelve.open(DB_FILE_NAME) self._id = max([int(x) for x in self._persons.keys()]+[0]) # Application logic methods. def addPerson(self, person): self._id += 1 self._persons[str(self._id)] = person self.notify(None) return self._id def updatePerson(self, id, person): self._persons[str(id)] = person self.notify(id) def removePerson(self, id): del self._persons[str(id)] self.notify(id) def getPerson(self, id): return self._persons[str(id)] def listPersons(self): personList = [(int(key),value) for (key, value) in self._persons.items()] personList.sort() return personList def commit(self): self._persons.close() self._persons = shelve.open(DB_FILE_NAME) # Observer pattern methods. def attach(self, observer, what): self._observers[observer] = what def detach(self, observer): del self._observers[observer] def notify(self, what_changed): for observer, what_to_observe in self._observers.items(): if what_to_observe in [what_changed, ALL_OBJECTS]: try: observer.update() except: pass # Here comes the GUI! import Tkinter as Tk class PersonListView(Tk.Frame): def __init__(self, model): self.model = model model.attach(self, ALL_OBJECTS) Tk.Frame.__init__(self, None) self.pack() self.list = Tk.Listbox(self) self.list.insert(0,' ') self.list.bind("", self.listClick) self.list.pack() quitButton = Tk.Button(self, text="Quit", command = self.doQuit) quitButton.pack() self.update() def doQuit(self): self.model.detach(self) self.model.commit() self.quit() def listClick(self, event): text = self.list.get(self.list.curselection()).strip() if text: id = int(text.split(':')[0]) else: id = self.model.addPerson('') PersonEditView(self.model, id) def update(self): # Clear Listbox self.list.delete(0, self.list.size()-1) assert self.list.size() == 0 # Fill listbox for i, (id, person) in enumerate(self.model.listPersons()): self.list.insert(i, "%i : %s" % (id, person)) self.list.insert(self.list.size(), " ") class PersonEditView(Tk.Toplevel): def __init__(self, model, id): self.model = model self.id = id model.attach(self, id) Tk.Toplevel.__init__(self, None) self.label = Tk.Label(self, text = str(id)) self.label.pack() self.person = Tk.StringVar() self.entry = Tk.Entry(self, textvariable=self.person) self.entry.pack() self.saveButton = Tk.Button(self, text='Save', command = selfdoSave) self.saveButton.pack() self.deleteButton = Tk.Button(self, text='Delete', command = self.doDelete) self.deleteButton.pack() self.update() def update(self): try: person = self.model.getPerson(self.id) self.person.set(person) except KeyError: self.destroy() def doSave(self): self.model.updatePerson(self.id, self.person.get()) def doDelete(self): self.model.removePerson(self.id) if __name__ == '__main__': pm = PersonModel() app = PersonListView(pm) app.master.title("GUI Example") app.mainloop() -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From magnus at thinkware.se Thu Apr 22 15:14:16 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Thu Apr 22 15:14:27 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gUHl0aG9uIGRldmVsb3BtZW50LW1vdmluZyBmcm9tIFdpbmRvd3MgdG8gTGludXggKGZpbmFsbHkp?= Message-ID: > However, since I've written so many, I don't think it is really feasible > to add 20 or more directories to my path, or to PYTHONPATH. Don't! Modules should be in the python site-packages directory, and your scripts should be in a directory in your PATH unless you want to give the path when you call it. That's all there is to it. PYTHONPATH is only relevant if you have big systems such as Twisted that want to live in their own part of the file system. > However, when I'm not in the directory where my python scripts are, I find > that I need to add the explicit path to the python script, in order to be > able to run it > /home/tony/bin/myscript.py If $ /home/tony/bin/myscript.py works, but $ myscript.py doesn't, I can only imagine two reasons. 1. "/home/tony/bin/" isn't actually in your path. (Maybe the environment variables are confusing you. Put another program, such as a shell script or a compiled C program there and see if that works better. Do they run as expected?) 2. Another myscript.py which does something else (like nothing) is also in your path, and is found first! What happens if you type "which myscript.py" at the $ prompt? Erh... by the way, I hope you are typing just "myscript.py" at the $ prompt, not "python myscript.py", otherwise it doesn't matter what you set your path to. The point with the #!-hack is that *Linux* should find out which program should interpret the script, *not* the user! In general, it's much easier to diagnose screen dumps than prose, so please copy and paste more from your terminal window. That's less typing for you. :) Tip: If you type "script" on a line by itself at the Linux/Unix shell prompt, all things you type and see on the screen will be saved in a text file called "typescript" until you type Ctrl-D on a line of its own. That's a convenient way of capturing the strange behaviour you run into. Then you can pick out the juicy parts from this file and put in your email. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From davidd at sponge.xevion.net Thu Apr 22 15:09:31 2004 From: davidd at sponge.xevion.net (David Dorgan) Date: Thu Apr 22 15:19:47 2004 Subject: [Tutor] Python development-moving from Windows to Linux (finally) In-Reply-To: <20040422093845.S75398-100000@yamato.yamato.com> References: <20040422093845.S75398-100000@yamato.yamato.com> Message-ID: <20040422190931.GA1061@eng.xevion.net> Quoting Tony Cappellini (tony@tcapp.com): > Would anyone care to drope me a hint ? I would imagine it's one of three things 1) Add ~/bin to your PATH, so in say your .bashrc have PATH=$PATH:~/bin 2) Make sure they are executable, chmod u+rwx ~/bin/*.py 3) Make sure the first line in the file points to python, so if it's , for example, #!/usr/local/bin/python check if that file exists To find the one you're probably using type which python David From sigurd at 12move.de Thu Apr 22 15:18:44 2004 From: sigurd at 12move.de (=?iso-8859-1?q?Karl_Pfl=E4sterer?=) Date: Thu Apr 22 15:20:01 2004 Subject: [Tutor] how best to store and process varriable ammounts of paired data In-Reply-To: <40880221.2070003@po-box.mcgill.ca> (Brian van den Broek's message of "Thu, 22 Apr 2004 13:34:25 -0400") References: <40880221.2070003@po-box.mcgill.ca> Message-ID: On 22 Apr 2004, Brian van den Broek <- bvande@po-box.mcgill.ca wrote: > I can think of three main methods for storing and using the extracted data. > 1) Iterate over the file and build a dictionary as I go, using the > identified numerical ids as the keys, and the title strings as the > values. Then work by iteration over the dictionary keys. > 2) Iterate the file and build two lists, one of the id's and one of > the title strings. Then: > a) make a dictionary from the lists and work with the dictionary, or > b) Just work from the lists themselves, iterating over the indices. > 3) Parse the file, building tuples (id, string title) as I go and > putting them in a list. Then iterate over the list, and read each > tupple value as needed. > So, since there may be 1000's of (id, title) pairs, I am wanting to > choose the best method -- best here being defined as some compromise > between high speed and small memory footprint. I think method 3 should best match your wishes. If you build a dictionary and want to iterate afterwards over the values a list has to be built. If you use two lists you could zip() them and you would get a new list with tuples. So if you can build the tuples from start on why not doing it that way? > Pointers as to which method here listed would be the way to go? Or > some other way I've overlooked? Or, I am worrying about something that > doesn't really matter? A test will only show if it really matters (perhaps you spend more time thinking about it than your PC needs to process the data). A fourth method would be to write a generator function which gives you an iterator which yields those tuples. So you neeedn't build a list of tuples to iterate over them and it's also pretty fast. Karl -- Please do *not* send copies of replies to me. I read the list From klappnase at freenet.de Thu Apr 22 15:21:36 2004 From: klappnase at freenet.de (Michael Lange) Date: Thu Apr 22 15:37:48 2004 Subject: [Tutor] Standard library modules not installed In-Reply-To: <20040422182444.34404.qmail@web13422.mail.yahoo.com> References: <20040422182444.34404.qmail@web13422.mail.yahoo.com> Message-ID: <20040422212136.30b0d2e6.klappnase@freenet.de> On Thu, 22 Apr 2004 11:24:44 -0700 (PDT) Rex wrote: > Hi, > > I'm a newbie to Python, but proficient in Perl. Loving it so far :) > > I wrote a basic program that uses the comma-separated values standard library csv to work on files. I use a Gentoo Linux box as my main developing environment and csv is included as it is supposed to be. > > However, I am going to run this program in a RedHat 9 machine, and for some strange reason some libraries are not included in this python installation (ver. 2.2.2). I have looked at several library locations (e.g. Vaults of Parnassus) but the standard libraries are not there. > > Where can I find and install these libraries that should, AFAIK, be included in the standard installation of Python? > Why would these libraries be missing from the RPM python package? Do you know if there is any RPM package that includes these libraries? Might be even easier to get. > Which libraries do you mean? Is it possible that they are included in some other RPM from your distribution you have not installed? Sometimes they split up the standard library into a couple of RPMs ( for example Tkinter is usually a seperate RPM). Maybe you should just try to search your distro's CDs for RPMs containing something with "python". Michael From klappnase at freenet.de Thu Apr 22 15:37:07 2004 From: klappnase at freenet.de (Michael Lange) Date: Thu Apr 22 15:37:55 2004 Subject: [Tutor] Python development-moving from Windows to Linux (finally) In-Reply-To: <20040422113053.S78102-100000@yamato.yamato.com> References: <4088060A.6080406@chrislott.org> <20040422113053.S78102-100000@yamato.yamato.com> Message-ID: <20040422213707.512b5b33.klappnase@freenet.de> On Thu, 22 Apr 2004 11:32:34 -0700 (PDT) Tony Cappellini wrote: > > > On Thu, 22 Apr 2004, Chris Lott wrote: > > > Tony Cappellini wrote: > > > > > > > > I've installed Python on a linux system, and now I'm trying to understand > > > how to better configure my environment for executing python scripts that > > > I've written. > > > > I think you have two paths confused. As I understand it, $PYTHONPATH is > > just for the location of Python executables, modules, etc. > > > > If you want to run your scripts without specifying the location, they > > need to be somewhere in your $PATH, which specifies where the shell > > looks for executables when you try to run them. So just add > > /home/tony/bin to your $PATH variable. > > > > This is already in the path. It was a default, I didn't add it. > This is why I don't understand why I need to use > /home/tony/bin/myscript.py to run my scripts. > > That's really strange. Anyway, if you don't want to mess around with your PATH you might link your files to /usr/local/bin which is usually a good place for locally installed stuff. Just do ln -s /home/tony/bin/myscript.py /usr/local/bin/myscript as root , and you should be able to start it from any directory. Michael From alan.gauld at blueyonder.co.uk Thu Apr 22 16:15:07 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Apr 22 16:14:55 2004 Subject: [Tutor] Python development-moving from Windows to Linux (finally) References: <20040422093845.S75398-100000@yamato.yamato.com> Message-ID: <002901c428a6$81c1a410$6401a8c0@xp> > Just like a binary exectuable, I would like to have all of my executable > python scripts in one directory (ie /home/tony/bin - or whatever I > decide). > > However, when I'm not in the directory where my python scripts are, I find > that I need to add the explicit path to the python script, in order to be > able to run it > /home/tony/bin/myscript.py You just need to add the python script directory to your PATH variable. PYTHONPATH controls where python looks for modules. PATH controls where the Unix shell looks for executables. So once you add the home/tony/bin directory to PATH in your .profile or .login or .cshrc (or whatever for the shell you use) it should all just work. HTH, Alan G. From alan.gauld at blueyonder.co.uk Thu Apr 22 16:17:43 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Apr 22 16:17:30 2004 Subject: [Tutor] Python development-moving from Windows to Linux (finally) References: <20040422113053.S78102-100000@yamato.yamato.com> Message-ID: <003201c428a6$dec410d0$6401a8c0@xp> > > need to be somewhere in your $PATH, which specifies where the shell > > looks for executables when you try to run them. So just add > > /home/tony/bin to your $PATH variable. > > This is already in the path. It was a default, I didn't add it. > This is why I don't understand why I need to use > /home/tony/bin/myscript.py to run my scripts. Have you changed the mode to executable with chmod? Is Python in the PATH - ie if you type python does the >>> prompt come up OK? If yes to both the above what error exactly does the shell give? Can you cut n paste a sample? Alan G From alan.gauld at blueyonder.co.uk Thu Apr 22 16:24:05 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Apr 22 16:23:54 2004 Subject: [Tutor] Python development-moving from Windows to Linux (finally) References: Message-ID: <003901c428a7$c27f2b20$6401a8c0@xp> > If you type "script" on a line by itself at the Linux/Unix > shell prompt, all things you type and see on the screen will > be saved in a text file called "typescript" until you type > Ctrl-D on a line of its own. The things you learn. 15 years of Unix experience and I never knew about that one... I just turn on logging in the xterm window or use cut n paste with the mouse. But those don;t work if its a native terminal sssion. Thanks Magnus. Alan G From chidorex-pytutor at yahoo.com Thu Apr 22 16:30:01 2004 From: chidorex-pytutor at yahoo.com (Rex) Date: Thu Apr 22 16:30:11 2004 Subject: [Tutor] Standard library modules not installed Message-ID: <20040422203001.64992.qmail@web13426.mail.yahoo.com> > > On Thu, 22 Apr 2004 11:24:44 -0700 (PDT) > Rex wrote: > > > Hi, > > > > I'm a newbie to Python, but proficient in Perl. Loving it so far :) > > > > I wrote a basic program that uses the comma-separated values > standard > library csv to work on files. I use a Gentoo Linux box as my main > developing environment and csv is included as it is supposed to be. > > > > However, I am going to run this program in a RedHat 9 machine, and > for some strange reason some libraries are not included in this > python > installation (ver. 2.2.2). I have looked at several library locations > (e.g. Vaults of Parnassus) but the standard libraries are not there. > > > > Where can I find and install these libraries that should, AFAIK, be > included in the standard installation of Python? > > Why would these libraries be missing from the RPM python package? > Do > you know if there is any RPM package that includes these libraries? > Might be even easier to get. > > > > Which libraries do you mean? Is it possible that they are included in > some other RPM from your > distribution you have not installed? Sometimes they split up the > standard library into > a couple of RPMs ( for example Tkinter is usually a seperate RPM). > Maybe you should just try > to search your distro's CDs for RPMs containing something with > "python". > > Michael Hi Michael, Well, I am looking for the libraries that are in the Python web site under the Standard libraries. In particular the comma-separated values one named simply 'csv'. It is described under: http://docs.python.org/lib/module-csv.html I looked into freshrpms.net and the redhat network. I also have yum and apt as package managers, and when searching in all these repositories I find a bunch of libraries, but none including the 'csv' one I need. Oddly enough, if I enter the python interactive environment i can issue a 'import Tkinter' and get the module loaded. Not so when issuing a 'import csv', in which case I get >>> import csv Traceback (most recent call last): File "", line 1, in ? ImportError: No module named csv Any suggestions. I am sure I can probably find it and download it, but I am wondering why I need to do this. Thanks again. Rex From dyoo at hkn.eecs.berkeley.edu Thu Apr 22 16:40:22 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Apr 22 16:40:27 2004 Subject: [Tutor] Standard library modules not installed In-Reply-To: <20040422203001.64992.qmail@web13426.mail.yahoo.com> Message-ID: > > > However, I am going to run this program in a RedHat 9 > machine, and for some strange reason some libraries are not included in > this python installation (ver. 2.2.2). I have looked at several library > locations [some text cut] > Well, I am looking for the libraries that are in the Python web site > under the Standard libraries. In particular the comma-separated values > one named simply 'csv'. It is described under: > > http://docs.python.org/lib/module-csv.html Hi Rex, Yes, 'csv' was added in Python 2.3, so it's not present in older versions of Python. But the PEP that introduced the CSV module: http://www.python.org/peps/pep-0305.html mentions other third-party implementations of a CVS parser that you can use. Here are links to them: http://www.object-craft.com.au/projects/csv/ http://sourceforge.net/projects/python-dsv/ http://tratt.net/laurie/python/asv/ If you need to maintain compatibility with other version of Python, using one of those third-party modules may be a good choice. Good luck! From chidorex-pytutor at yahoo.com Thu Apr 22 16:45:23 2004 From: chidorex-pytutor at yahoo.com (Rex) Date: Thu Apr 22 16:45:31 2004 Subject: [Tutor] Standard library modules not installed In-Reply-To: Message-ID: <20040422204523.68818.qmail@web13426.mail.yahoo.com> --- Danny Yoo wrote: > > > > > > However, I am going to run this program in a RedHat 9 > > machine, and for some strange reason some libraries are not > included in > > this python installation (ver. 2.2.2). I have looked at several > library > > locations > > [some text cut] > > > Well, I am looking for the libraries that are in the Python web > site > > under the Standard libraries. In particular the comma-separated > values > > one named simply 'csv'. It is described under: > > > > http://docs.python.org/lib/module-csv.html > > > Hi Rex, > > > Yes, 'csv' was added in Python 2.3, so it's not present in older > versions > of Python. But the PEP that introduced the CSV module: > > http://www.python.org/peps/pep-0305.html > > mentions other third-party implementations of a CVS parser that you > can > use. Here are links to them: > > http://www.object-craft.com.au/projects/csv/ > http://sourceforge.net/projects/python-dsv/ > http://tratt.net/laurie/python/asv/ > > If you need to maintain compatibility with other version of Python, > using > one of those third-party modules may be a good choice. > > > Good luck! > Hi Danny, Thanks for the advice. No wonder the on-line reference has this module and not my previous version. Gentoo Linux is always "bleeding-edge stable" so that is always an advantage other other distros. I'll look up these other library options for my "older" Python :) Thanks again to all. Rex From bintangkurniawan at yahoo.com Thu Apr 22 19:19:39 2004 From: bintangkurniawan at yahoo.com (bintang kurniawan) Date: Thu Apr 22 19:19:45 2004 Subject: [Tutor] GUI component Message-ID: <20040422231939.23588.qmail@web20724.mail.yahoo.com> Dear all, im new beginer in python laguage, and would like to now more on GUI programming (TK inter). my question is : 1. how to inherrit component and add some additional function to it. 2. where can i find Combobox and DataGrid component? and how to install to the python environtment? thank you rgds, bintang --------------------------------- Do you Yahoo!? Yahoo! Photos: High-quality 4x6 digital prints for 25¢ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040422/de628161/attachment.html From tony at tcapp.com Thu Apr 22 19:26:03 2004 From: tony at tcapp.com (Tony Cappellini) Date: Thu Apr 22 19:26:17 2004 Subject: [Tutor] Python development-moving from Windows to Linux (finally) In-Reply-To: <003201c428a6$dec410d0$6401a8c0@xp> Message-ID: <20040422162222.X84562-100000@yamato.yamato.com> On Thu, 22 Apr 2004, Alan Gauld wrote: > > > need to be somewhere in your $PATH, which specifies where the > shell > > > looks for executables when you try to run them. So just add > > > /home/tony/bin to your $PATH variable. > > > > This is already in the path. It was a default, I didn't add it. > > This is why I don't understand why I need to use > > /home/tony/bin/myscript.py to run my scripts. > > Have you changed the mode to executable with chmod? > Is Python in the PATH - ie if you type python does > the >>> prompt come up OK? > > If yes to both the above what error exactly does the > shell give? Can you cut n paste a sample? > it looks like I didn't type the file extension, of the script I was trying to execute. so /home/bin/myscript.py now executes when I type myscript.py - from any directory to simplify things for the future I've put all the files needed for this program, in a subdir, under bin, and put a symbolic link in /home/tony/bin, so I don't need the extension to invoke the script. thanks to all who helped with this From pan at uchicago.edu Thu Apr 22 23:22:58 2004 From: pan at uchicago.edu (pan@uchicago.edu) Date: Thu Apr 22 23:23:07 2004 Subject: [Tutor] py cgi can't show up correctly in Netscape In-Reply-To: References: Message-ID: <1082690578.40888c1205b25@webmail.uchicago.edu> Hi all, I have some cgi scripts having some problems with Netscape: -- If the py cgi called by MSIE, it works fine; -- If called by Opera, it works fine; -- If called by Netscape, it displays the cgi output code (the html tags), in plain text, but not html-formatted. For example, will be shown on the Netscape. -- If I save the output document (view source in Netscape) into a ???.html file and re-open it with Netscape, it shows up with html-formatted text correctly. I tried Netscape 4.79 and 7.1, on both Window and Linux, both have the same problem. Does anyone know what's wrong and how to solve it ? You can test it by clicking: http://runsun.info/cgi-bin/cgiTest.py thx pan From Simonjthecat at aol.com Thu Apr 22 23:13:43 2004 From: Simonjthecat at aol.com (Simonjthecat@aol.com) Date: Thu Apr 22 23:23:20 2004 Subject: [Tutor] use while loop Message-ID: <87.a06028e.2db9e3e7@aol.com> Ok. I know this is really simple, but it's my first program so anybody can pobably answer it for me. This program finds the area of different shapes. Right now, however, it only goes through one time and then exits the program. I want to put it in a loop so that after one area is given it will start over and ask what shape you want again. I figured out how to put it in a for loop and get it to execute a given number of times. I'm assuming I need it in a while loop but just can't do it. So anyway, here's what I've got so far. import sys #for exit command print """ Choose a shape from the list: 1) Triangle 2) Square 3) Circle """ shape = raw_input("Which shape[1,2,3,quit]? ") # note must now test for character '1' not # number 1 coz raw_input returns strings not numbers if shape == '1': # a triangle ht = input('What is the height of your triangle? ') base = input('How long is the base? ') print "The triangle's area is: ", 0.5*base*ht elif shape == '2': # square side = input("How long are the square's sides? ") print "The square's area is: ", side*side elif shape == '3': # a circle rad = input('What radius is your circle? ') print "The circle's area is: ", 3.14159*rad*rad elif shape == 'quit': sys.exit() else: print "Sorry, You didn't enter a valid choice" I know this has a real simple fix. Thanx for the help Simon the Cat -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040422/f546cf2e/attachment.html From rick at niof.net Thu Apr 22 23:38:24 2004 From: rick at niof.net (Rick Pasotto) Date: Thu Apr 22 23:38:39 2004 Subject: [Tutor] py cgi can't show up correctly in Netscape In-Reply-To: <1082690578.40888c1205b25@webmail.uchicago.edu> References: <1082690578.40888c1205b25@webmail.uchicago.edu> Message-ID: <20040423033824.GN28675@niof.net> On Thu, Apr 22, 2004 at 10:22:58PM -0500, pan@uchicago.edu wrote: > Hi all, > > I have some cgi scripts having some problems with Netscape: > > -- If the py cgi called by MSIE, it works fine; > -- If called by Opera, it works fine; > -- If called by Netscape, it displays the cgi output code (the html tags), > in plain text, but not html-formatted. For example, will be shown > on the Netscape. > -- If I save the output document (view source in Netscape) into a ???.html > file and re-open it with Netscape, it shows up with html-formatted text > correctly. > > I tried Netscape 4.79 and 7.1, on both Window and Linux, both have the > same problem. > > Does anyone know what's wrong and how to solve it ? > > You can test it by clicking: > http://runsun.info/cgi-bin/cgiTest.py You're not outputting any nor sections so the document you send to the browser is invalid. Some browsers overlook some html errors and make guesses and some just get confused. -- "FIJA is not a double-edged sword -- it is a shield against the sword of government." -- Tom Glass Rick Pasotto rick@niof.net http://www.niof.net From Simonjthecat at aol.com Fri Apr 23 00:21:49 2004 From: Simonjthecat at aol.com (Simonjthecat@aol.com) Date: Fri Apr 23 00:21:59 2004 Subject: [Tutor] figured it out Message-ID: <15a.332185e4.2db9f3dd@aol.com> Ok... with a little trial and error I figured it out by myself (yay! this is my first working program!) I'll go ahead and put what I came up w/.... Is this the most efficient way? It seemed kinda weird to define shape as the same thing twice but it works. Here it is. import sys #for exit command shape = raw_input("Which shape[1,2,3,quit]? ") while shape != 'quit': print """ Choose a shape from the list: 1) Triangle 2) Square 3) Circle """ # note must now test for character '1' not # number 1 coz raw_input returns strings not numbers if shape == '1': # a triangle ht = input('What is the height of your triangle? ') base = input('How long is the base? ') print "The triangle's area is: ", 0.5*base*ht elif shape == '2': # square side = input("How long are the square's sides? ") print "The square's area is: ", side*side elif shape == '3': # a circle rad = input('What radius is your circle? ') print "The circle's area is: ", 3.14159*rad*rad elif shape == 'quit': sys.exit() else: print "Sorry, You didn't enter a valid choice" shape = raw_input("Which shape[1,2,3,quit]? ") -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040423/6aad1896/attachment.html From alan.gauld at blueyonder.co.uk Fri Apr 23 01:34:54 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Apr 23 01:34:33 2004 Subject: [Tutor] Python development-moving from Windows to Linux (finally) References: <20040422162222.X84562-100000@yamato.yamato.com> Message-ID: <005e01c428f4$b50a5120$6401a8c0@xp> > I've put all the files needed for this program, in a subdir, under bin, > and put a symbolic link in /home/tony/bin, so I don't need the extension > to invoke the script. You an just omit the extension on the script itself. Provided you use the shebabg trick you don;t need the .py extension in *nix - although its a useful reminder to you what language its written in... Alan g From alan.gauld at blueyonder.co.uk Fri Apr 23 01:38:32 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Apr 23 01:38:13 2004 Subject: [Tutor] Standard library modules not installed References: <20040422203001.64992.qmail@web13426.mail.yahoo.com> Message-ID: <008101c428f5$36d95d90$6401a8c0@xp> > >>> import csv > Traceback (most recent call last): > File "", line 1, in ? > ImportError: No module named csv > > Any suggestions. I am sure I can probably find it and > download it, but I am wondering why I need to do this. The csv module is a very recent addition. I thought it was added in v2.2 but maybe it was v2.3... Can anyone else with 2.2 check to see if they have it? Alan G. From alan.gauld at blueyonder.co.uk Fri Apr 23 01:47:22 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Apr 23 01:47:01 2004 Subject: [Tutor] GUI component References: <20040422231939.23588.qmail@web20724.mail.yahoo.com> Message-ID: <009101c428f6$72c8e1d0$6401a8c0@xp> > 1. how to inherrit component and add some additional function to it. Just inherit as usual class MyNewWidget(ListBox): ... will subclass the Tkinter LIstBox widget. > 2. where can i find Combobox and DataGrid component? There is no such beast in Tkinter but the PMW free add-on widget set has a ComboBox widget. There is no DataGrid available so far as I know, you have to use a normal grid and fill the data yourself. PMW also has a basic grid for Tkinter I believe. HTH, Alan G. From carroll at tjc.com Fri Apr 23 01:49:47 2004 From: carroll at tjc.com (Terry Carroll) Date: Fri Apr 23 01:49:54 2004 Subject: [Tutor] Standard library modules not installed In-Reply-To: <008101c428f5$36d95d90$6401a8c0@xp> Message-ID: On Fri, 23 Apr 2004, Alan Gauld wrote: > The csv module is a very recent addition. I thought it was > added in v2.2 but maybe it was v2.3... > > Can anyone else with 2.2 check to see if they have it? It was definitely added in 2.3. I started in Python in 2.2 and used one of the third-party CSV modules; when I upgraded to 2.3 I switched to the new one. From magnus at thinkware.se Fri Apr 23 06:06:29 2004 From: magnus at thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Fri Apr 23 06:03:04 2004 Subject: [Tutor] Standard library modules not installed In-Reply-To: References: <20040422203001.64992.qmail@web13426.mail.yahoo.com> Message-ID: <5.2.1.1.0.20040423120405.02448570@www.thinkware.se> At 13:40 2004-04-22 -0700, Danny Yoo wrote: >mentions other third-party implementations of a CVS parser that you can >use. Here are links to them: > > http://www.object-craft.com.au/projects/csv/ IIRC this is (more or less) the one that got included in the Std Lib. Another option would be to install Python 2.3 on the RH box. I think RH needs Py 2.2 for admin tools, but you can always install Py 2.3 under /usr/local... -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From magnus at thinkware.se Fri Apr 23 06:15:07 2004 From: magnus at thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Fri Apr 23 06:11:51 2004 Subject: [Tutor] GUI component In-Reply-To: <20040422231939.23588.qmail@web20724.mail.yahoo.com> Message-ID: <5.2.1.1.0.20040423121037.024486b8@www.thinkware.se> At 16:19 2004-04-22 -0700, bintang kurniawan wrote: >2. where can i find Combobox and DataGrid component? and how to install to >the python environtment? My tip of the day would be to use wxPython instead of Tkinter. See http://www.wxpython.org/ The only disadvantage with wxPython in my opinion is that it's not included in the standard Python distribution, but neither are the things you need, so let's forget about the old and clunky Tkinter. "wxPython is the best and most mature cross-platform GUI toolkit, given a number of constraints. The only reason wxPython isn't the standard Python GUI toolkit is that Tkinter was there first." -- Guido van Rossum -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From Janssen at rz.uni-frankfurt.de Fri Apr 23 06:18:51 2004 From: Janssen at rz.uni-frankfurt.de (Michael Janssen) Date: Fri Apr 23 06:19:03 2004 Subject: [Tutor] figured it out In-Reply-To: <15a.332185e4.2db9f3dd@aol.com> References: <15a.332185e4.2db9f3dd@aol.com> Message-ID: On Fri, 23 Apr 2004 Simonjthecat@aol.com wrote: > Ok... with a little trial and error I figured it out by myself (yay! this is > my first working program!) fine! >I'll go ahead and put what I came up w/.... Is > this the most efficient way? It seemed kinda weird to define shape as the same > thing twice but it works. it's quite ok. Another possibility you will often see/use in code is to start an infinite while-loop and "break" it later: while 1: # loop forever shape = raw_input("Which shape[1,2,3,quit]? ") if shape == 'quit': # step out of the while loop break # further ifs and elses Instead of keyword 'break' you can use sys.exit(), when you want to terminate the whole programm. Hey, your code contains a minor mistake that's might be useful for learning. Rewrite the "elif shape == 'quit'" part this way: elif shape == 'quit': print "okey, got a 'quit' - now terminate programm" sys.exit() and tell us why the text doesn't get printed out, when typing quit! What happens instead? Michael > Here it is. > > import sys #for exit command > shape = raw_input("Which shape[1,2,3,quit]? ") > > while shape != 'quit': > print """ > Choose a shape from the list: > 1) Triangle > 2) Square > 3) Circle > """ > # note must now test for character '1' not > # number 1 coz raw_input returns strings not numbers > if shape == '1': # a triangle > ht = input('What is the height of your triangle? ') > base = input('How long is the base? ') > print "The triangle's area is: ", 0.5*base*ht > > elif shape == '2': # square > side = input("How long are the square's sides? ") > print "The square's area is: ", side*side > > elif shape == '3': # a circle > rad = input('What radius is your circle? ') > print "The circle's area is: ", 3.14159*rad*rad > > elif shape == 'quit': > sys.exit() > > else: > print "Sorry, You didn't enter a valid choice" > > shape = raw_input("Which shape[1,2,3,quit]? ") > From magnus at thinkware.se Fri Apr 23 06:22:45 2004 From: magnus at thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Fri Apr 23 06:19:20 2004 Subject: [Tutor] figured it out In-Reply-To: <15a.332185e4.2db9f3dd@aol.com> Message-ID: <5.2.1.1.0.20040423121936.0242a798@www.thinkware.se> At 00:21 2004-04-23 -0400, Simonjthecat@aol.com wrote: >Ok... with a little trial and error I figured it out by myself (yay! this >is my first working program!) I'll go ahead and put what I came up >w/.... Is this the most efficient way? It seemed kinda weird to define >shape as the same thing twice but it works. >Here it is. > >import sys #for exit command >shape = raw_input("Which shape[1,2,3,quit]? ") > >while shape != 'quit': [snip] > shape = raw_input("Which shape[1,2,3,quit]? ") A common Python idiom is to do it like this: while True: shape = raw_input("Which shape[1,2,3,quit]? ") if shape == 'quit': break ...rest of the code... -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From magnus at thinkware.se Fri Apr 23 06:37:28 2004 From: magnus at thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Fri Apr 23 06:34:08 2004 Subject: [Tutor] how best to store and process varriable ammounts of paired data In-Reply-To: <40880221.2070003@po-box.mcgill.ca> Message-ID: <5.2.1.1.0.20040423122322.0247c6a8@www.thinkware.se> At 13:34 2004-04-22 -0400, Brian van den Broek wrote: >I'm starting a project to write a bunch of functions for parsing the >datafiles of a particular application I use. Thanks to help from the group >I now understand how to work with files :-) but I have a question about >efficient storage of the information I extract. Are you just asking about data structures during program execution, or are you asking about persistent storage? >So, since there may be 1000's of (id, title) pairs, I am wanting to choose >the best method -- best here being defined as some compromise between high >speed and small memory footprint. Thousands doesn't sound very big on modern hardware... As a better measure, how big are the biggest files you need to process? As Don Knuth says, premature optimization is the root of all evil. Unless the file sizes get bigger than maybe 10% of the amount of RAM in your machine, I wouldn't worry about performance until I actually experienced performance problems. Try to solve the problem in the simplest and most logical way, and worry about performance if there is a problem. Don't chase ghosts. Try either of the approaches you suggested, implement it (that should be fairly quick, and if you do it well, most of the code will be reusable if you want to change approach) and see if it works well. If you get the performance you need, you are done. It seems to me that a dictionary or a list of (key, value) tuples is better than two separate lists (I imagine the scenario where your two lists are suddenly of different lenghts...). With the list, you retain order of input. With the dictionary, you get very fast access to data if you know the exact key. You know what you need, I don't... -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From denis.spir at free.fr Fri Apr 23 06:29:09 2004 From: denis.spir at free.fr (denis) Date: Fri Apr 23 06:59:14 2004 Subject: [Tutor] use while loop References: <87.a06028e.2db9e3e7@aol.com> Message-ID: <006601c42921$ef938aa0$0342933e@spir> ----- Original Message ----- From: To: Sent: Friday, April 23, 2004 5:13 AM Subject: [Tutor] use while loop > Ok. I know this is really simple, but it's my first program so anybody can > pobably answer it for me. This program finds the area of different shapes. > Right now, however, it only goes through one time and then exits the program. I > want to put it in a loop so that after one area is given it will start over > and ask what shape you want again. I figured out how to put it in a for loop > and get it to execute a given number of times. I'm assuming I need it in a > while loop but just can't do it. So anyway, here's what I've got so far. (Nobody else answers ? I'll try to be clear...) This is the typical case where a code section has to be executed once, and only then a condition will tell if it should be repeted or not. In pseudo-code it looks like : loop until exit_condition or : loop while continue_condition (where each condition is the logical negation (logical NOT) of the other one.) As python doesn't provide such a loop form with an end test, you need to use the one you've got -- that is : the 'while' loop with a start test. And use a double trick to transform it into what you want do : while True : # (1) switch off start test if exit_condition : break # (2) handmade end test > import sys #for exit command > > print """ > Choose a shape from the list: > 1) Triangle > 2) Square > 3) Circle > """ > shape = raw_input("Which shape[1,2,3,quit]? ") > > # note must now test for character '1' not > # number 1 coz raw_input returns strings not numbers > if shape == '1': # a triangle > ht = input('What is the height of your triangle? ') > base = input('How long is the base? ') > print "The triangle's area is: ", 0.5*base*ht > > elif shape == '2': # square > side = input("How long are the square's sides? ") > print "The square's area is: ", side*side > > elif shape == '3': # a circle > rad = input('What radius is your circle? ') > print "The circle's area is: ", 3.14159*rad*rad > > elif shape == 'quit': > sys.exit() > > else: > print "Sorry, You didn't enter a valid choice" Either to simplify your loop or (logical inclusive OR) for trainig purpose, you may put your area calculations into functions. > I know this has a real simple fix. > Thanx for the help > > Simon the Cat > ---------------------------------------------------------------------------- ---- > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From denis.spir at free.fr Fri Apr 23 06:56:32 2004 From: denis.spir at free.fr (denis) Date: Fri Apr 23 06:59:19 2004 Subject: [Tutor] figured it out References: <15a.332185e4.2db9f3dd@aol.com> Message-ID: <006801c42921$f08f4fc0$0342933e@spir> ----- Original Message ----- From: To: Sent: Friday, April 23, 2004 6:21 AM Subject: [Tutor] figured it out > Ok... with a little trial and error I figured it out by myself (yay! this is > my first working program!) I'll go ahead and put what I came up w/.... Is > this the most efficient way? It seemed kinda weird to define shape as the same > thing twice but it works. > Here it is. > > import sys #for exit command > shape = raw_input("Which shape[1,2,3,quit]? ") > > while shape != 'quit': > print """ > Choose a shape from the list: > 1) Triangle > 2) Square > 3) Circle > """ > # note must now test for character '1' not > # number 1 coz raw_input returns strings not numbers > if shape == '1': # a triangle > ht = input('What is the height of your triangle? ') > base = input('How long is the base? ') > print "The triangle's area is: ", 0.5*base*ht > > elif shape == '2': # square > side = input("How long are the square's sides? ") > print "The square's area is: ", side*side > > elif shape == '3': # a circle > rad = input('What radius is your circle? ') > print "The circle's area is: ", 3.14159*rad*rad > > elif shape == 'quit': > sys.exit() > > else: > print "Sorry, You didn't enter a valid choice" > > shape = raw_input("Which shape[1,2,3,quit]? ") In fact here your start condition "shape != 'quit'" will never be tested True, even if looks like it is what lets the program exit the loop. As soon as the user chooses 'quit', the program sys.exits . All right ? You could have written "while True" or "while 1" instead. You force a hard loop exit whit the program end. Thus, you have to choose between sys.exit or standard program ending with the last instruction in the file ; and between loop exit by testing shape != 'quit' at the start. Two more notes : * fix the user interaction default(s) * find a way of cancelling the first shape = raw_input() outside the loop > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From jason at smileproject.com Fri Apr 23 09:13:53 2004 From: jason at smileproject.com (Jason Van Anden) Date: Fri Apr 23 09:14:27 2004 Subject: [Tutor] vim python syntax settings? Message-ID: <11EB105A-9528-11D8-A6C5-0003930488EC@smileproject.com> Hi, I am an experienced Windows developer who is taking the plunge to the "other side". I dig Python, and Vim, and I have decided this is what I want to focus on for the moment since it makes for an easy transition for me. I have noticed that the documentation for either can be a bit spotty - I am learning with Google, Books and Lists. Someone out there must have the perfect color terminal vim config for Python 2.3. Would you mind sharing it with me? Thanks! J From chris at chrislott.org Fri Apr 23 10:10:26 2004 From: chris at chrislott.org (Chris Lott) Date: Fri Apr 23 10:10:46 2004 Subject: [Tutor] math question Message-ID: <408923D2.6020605@chrislott.org> Given below, why isn't the answer ever "right"? >>> math.sqrt(2) * math.sqrt(2) 2.0000000000000004 >>> (math.sqrt(2))**2 2.0000000000000004 c -- Chris Lott From sigurd at 12move.de Fri Apr 23 11:16:04 2004 From: sigurd at 12move.de (=?iso-8859-1?q?Karl_Pfl=E4sterer?=) Date: Fri Apr 23 11:17:45 2004 Subject: [Tutor] math question In-Reply-To: <408923D2.6020605@chrislott.org> (Chris Lott's message of "Fri, 23 Apr 2004 06:10:26 -0800") References: <408923D2.6020605@chrislott.org> Message-ID: On 23 Apr 2004, Chris Lott <- chris@chrislott.org wrote: > Given below, why isn't the answer ever "right"? > >>> math.sqrt(2) * math.sqrt(2) > 2.0000000000000004 > >>> (math.sqrt(2))**2 > 2.0000000000000004 Here are several problems: (a) sqrt(2) can't be written as exact value (neither base 10 nor base 2). So Python uses a floating point approximation (b) you see the internal representation of the numbers (repr()) (c) most floating point numbers can't be represented exactly in the way Python stores them A very good explanation of the problems with floating point numbers can be found in the Python tutorial in the official documentation. You should read it. A simple example from it which shows the problem: ,----[ Python tutorial: Floating Point Arithmetic: Issues and Limitations] | | The problem is easier to understand at first in base 10. Consider the | fraction 1/3. You can approximate that as a base 10 fraction: | | 0.3 | | or, better, | | 0.33 | | or, better, | | 0.333 | | and so on. No matter how many digits you're willing to write down, the | result will never be exactly 1/3, but will be an increasingly better | approximation to 1/3. | | In the same way, no matter how many base 2 digits you're willing to | use, the decimal value 0.1 cannot be represented exactly as a base 2 | fraction. In base 2, 1/10 is the infinitely repeating fraction | | 0.0001100110011001100110011001100110011001100110011... | | Stop at any finite number of bits, and you get an approximation. This | is why you see things like: | | >>> 0.1 | 0.10000000000000001 `---- Karl -- Please do *not* send copies of replies to me. I read the list From chris at chrislott.org Fri Apr 23 11:53:03 2004 From: chris at chrislott.org (Chris Lott) Date: Fri Apr 23 11:57:44 2004 Subject: [Tutor] math question In-Reply-To: References: <408923D2.6020605@chrislott.org> Message-ID: <40893BDF.9090401@chrislott.org> Karl Pfl?sterer wrote: > Here are several problems: > (a) sqrt(2) can't be written as exact value (neither base 10 nor base > 2). So Python uses a floating point approximation > (b) you see the internal representation of the numbers (repr()) > (c) most floating point numbers can't be represented exactly in the way > Python stores them > > A very good explanation of the problems with floating point numbers can > be found in the Python tutorial in the official documentation. You > should read it. > > A simple example from it which shows the problem: I understand and I don't understand. I've read that section in the tutorial. I understand that the sqrt(2) can't be written as an exact value. But the sqrt(2)^2 certainly can be written in an exact value. It seems strange to me (I'm no mathematician and I suspect this is a philosophy question rather than a Python question) that the language can't figure this out-- similarly, if I add up 1/3 + 1/3 + 1/3 there is no reason (to my layperson's mind) that it doesn't come out to 1, regardless of the individual values. I guess it seems like something should see the code and know a difference between adding .33 + .33 + .333 and 1/3 + 1/3 + 1/3 I can't conceive of why it would *matter* in anything I do, but I had a hard time explaining to my daughter when I was helping her with a math/geometry problem and showed her how to use the Python shell as a kind of calculator and was demonstrating to her and got 2.000000004 here :) c -- Chris Lott From Chad.Crabtree at nationalcity.com Fri Apr 23 12:13:08 2004 From: Chad.Crabtree at nationalcity.com (Crabtree, Chad) Date: Fri Apr 23 12:13:26 2004 Subject: FW: [Tutor] math question Message-ID: <66F587DFDD46D511B65200508B6F8DD612B9940C@nt-kalopsapp07.ntl-city.com> -----Original Message----- From: Crabtree, Chad Sent: Friday, April 23, 2004 12:04 PM To: 'Chris Lott' Subject: RE: [Tutor] math question > > I can't conceive of why it would *matter* in anything I do, > but I had a > hard time explaining to my daughter when I was helping her with a > math/geometry problem and showed her how to use the Python shell as a > kind of calculator and was demonstrating to her and got > 2.000000004 here :) > I have been thinking about this quite a bit. Maybe you could simulate this by checking if there's a variance out to 1E-9 if it's that close to the number then it is that number. I was thinking alot about it because I was wondering how my calculator does it. It only carries out the 14th significant digit. Perhaps a subclass of float and int could do this? ------------------------------------------------------------------------------------------- ***National City made the following annotations ------------------------------------------------------------------------------------------- This communication is a confidential and proprietary business communication. It is intended solely for the use of the designated recipient(s). If this communication is received in error, please contact the sender and delete this communication. =========================================================================================== From fuzzydav at wcoil.com Fri Apr 23 13:15:22 2004 From: fuzzydav at wcoil.com (yak) Date: Fri Apr 23 12:13:39 2004 Subject: [Tutor] math question In-Reply-To: <40893BDF.9090401@chrislott.org> References: <408923D2.6020605@chrislott.org> <40893BDF.9090401@chrislott.org> Message-ID: <20040423131522.09879953@aphrodite.pantheon.home> On Fri, 23 Apr 2004 07:53:03 -0800 Chris Lott wrote: > Karl Pfl?sterer wrote: > > > Here are several problems: > > (a) sqrt(2) can't be written as exact value (neither base 10 nor base > > 2). So Python uses a floating point approximation > > (b) you see the internal representation of the numbers (repr()) > > (c) most floating point numbers can't be represented exactly in the way > > Python stores them > > > > A very good explanation of the problems with floating point numbers can > > be found in the Python tutorial in the official documentation. You > > should read it. > > > > A simple example from it which shows the problem: > > I understand and I don't understand. I've read that section in the > tutorial. I understand that the sqrt(2) can't be written as an exact > value. But the sqrt(2)^2 certainly can be written in an exact value. It > seems strange to me (I'm no mathematician and I suspect this is a > philosophy question rather than a Python question) that the language > can't figure this out-- similarly, if I add up 1/3 + 1/3 + 1/3 there is > no reason (to my layperson's mind) that it doesn't come out to 1, > regardless of the individual values. I guess it seems like something > should see the code and know a difference between adding .33 + .33 + > .333 and 1/3 + 1/3 + 1/3 > > I can't conceive of why it would *matter* in anything I do, but I had a > hard time explaining to my daughter when I was helping her with a > math/geometry problem and showed her how to use the Python shell as a > kind of calculator and was demonstrating to her and got 2.000000004 here :) > > c > -- > Chris Lott > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > Heres something interesting: >>> print math.sqrt(2) * math.sqrt(2) 2.0 >>> math.sqrt(2) * math.sqrt(2) 2.0000000000000004 >>> print math.sqrt(2) ** 2 2.0 >>> math.sqrt(2) ** 2 2.0000000000000004 >>> I'm not sure how it gets from the internal representation to what is printed though. From orbitz at ezabel.com Fri Apr 23 12:26:02 2004 From: orbitz at ezabel.com (orbitz@ezabel.com) Date: Fri Apr 23 12:27:15 2004 Subject: [Tutor] math question In-Reply-To: <40893BDF.9090401@chrislott.org> References: <408923D2.6020605@chrislott.org> <40893BDF.9090401@chrislott.org> Message-ID: <20040423122602.6e7d33a9.orbitz@ezabel.com> Python does what you tell it. sqrt(2)^2, take the square root of 2, which is am aproximation, then multiply it by itself, which is still an aproximation. Python isn't a symbolic computer, it isn't meant to guess that "oh, you want to square what i just took the square root of, that is itself then". but since python is a programming language, you can certinaly do that on your own. On Fri, 23 Apr 2004 07:53:03 -0800 Chris Lott wrote: > Karl Pfl?sterer wrote: > > > Here are several problems: > > (a) sqrt(2) can't be written as exact value (neither base 10 nor base > > 2). So Python uses a floating point approximation > > (b) you see the internal representation of the numbers (repr()) > > (c) most floating point numbers can't be represented exactly in the way > > Python stores them > > > > A very good explanation of the problems with floating point numbers can > > be found in the Python tutorial in the official documentation. You > > should read it. > > > > A simple example from it which shows the problem: > > I understand and I don't understand. I've read that section in the > tutorial. I understand that the sqrt(2) can't be written as an exact > value. But the sqrt(2)^2 certainly can be written in an exact value. It > seems strange to me (I'm no mathematician and I suspect this is a > philosophy question rather than a Python question) that the language > can't figure this out-- similarly, if I add up 1/3 + 1/3 + 1/3 there is > no reason (to my layperson's mind) that it doesn't come out to 1, > regardless of the individual values. I guess it seems like something > should see the code and know a difference between adding .33 + .33 + > .333 and 1/3 + 1/3 + 1/3 > > I can't conceive of why it would *matter* in anything I do, but I had a > hard time explaining to my daughter when I was helping her with a > math/geometry problem and showed her how to use the Python shell as a > kind of calculator and was demonstrating to her and got 2.000000004 here :) > > c > -- > Chris Lott > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From tim.one at comcast.net Fri Apr 23 12:55:00 2004 From: tim.one at comcast.net (Tim Peters) Date: Fri Apr 23 12:55:02 2004 Subject: [Tutor] math question In-Reply-To: <40893BDF.9090401@chrislott.org> Message-ID: [Chris Lott] > I understand and I don't understand. I've read that section in the > tutorial. I understand that the sqrt(2) can't be written as an exact > value. But the sqrt(2)^2 certainly can be written in an exact value. Suppose you had a decimal hand calculator, with 3 digits of precision. If you computed sqrt(2) on that, you would get 1.41 This is an approximation to the square root of 2, but is the best approximation the calculator is capable of giving you. If you go on to square 1.41, the exact result is 1.9881. But, again, since your calculator has only 3 digits of precision, the best possible approximation it can give you to 1.9881 is 1.99. So, in all, on that calculator the result of sqrt(2)**2 will be 1.99 -- and all assuming it's giving the best possible approximation at every step. You lose information at each step, and the more steps there are the more that information loss can compound. Exactly the same kinds of things happen in binary floating-point arithmetic, but they're harder to picture at first because people aren't accustomed to using base 2. Note that when you see "sqrt(2)**2" and think "ah, that must be 2!", you're not doing arithmetic at all in your head: you're doing symbolic algebra, building on your knowledge about how the square root and square functions relate to each other (as inverses). If you were doing arithmetic on paper instead, one operation at a time, you'd have exactly the same problem with losing information at each step (unless you had enough spare time to write down an infinite number of digits at each step ). From dyoo at hkn.eecs.berkeley.edu Fri Apr 23 13:36:19 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Apr 23 13:36:37 2004 Subject: [Tutor] vim python syntax settings? In-Reply-To: <11EB105A-9528-11D8-A6C5-0003930488EC@smileproject.com> Message-ID: On Fri, 23 Apr 2004, Jason Van Anden wrote: > I am an experienced Windows developer who is taking the plunge to the > "other side". I dig Python, and Vim, and I have decided this is what I > want to focus on for the moment since it makes for an easy transition > for me. I have noticed that the documentation for either can be a bit > spotty - I am learning with Google, Books and Lists. Someone out there > must have the perfect color terminal vim config for Python 2.3. Would > you mind sharing it with me? Hi Jason, The Python Wiki has a sample configuration: http://www.python.org/cgi-bin/moinmoin/ViImproved Good luck to you! From dyoo at hkn.eecs.berkeley.edu Fri Apr 23 13:48:43 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Apr 23 13:48:49 2004 Subject: [Tutor] math question In-Reply-To: Message-ID: On Fri, 23 Apr 2004, Tim Peters wrote: > Note that when you see "sqrt(2)**2" and think "ah, that must be 2!", > you're not doing arithmetic at all in your head: you're doing symbolic > algebra, building on your knowledge about how the square root and square > functions relate to each other (as inverses). If you were doing > arithmetic on paper instead, one operation at a time, you'd have exactly > the same problem with losing information at each step (unless you had > enough spare time to write down an infinite number of digits at each > step ). Hi Chris, There are some specialized systems that allow computers to do symbolic algebra. Mathematica is one of these: http://www.wolfram.com/ and there's a Python library that can interface with Mathematica called PYML: http://py-ml.sourceforge.net/ Mathematica isn't free, unfortunately. There was another Python project to do symbolic algebra called Pythonica: http://www.strout.net/python/pythonica.html but I'm not so sure if it's still actively developed. Good luck to you! From bvande at po-box.mcgill.ca Fri Apr 23 14:58:00 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Fri Apr 23 14:59:56 2004 Subject: [Tutor] how best to store and process varriable ammounts of paired data In-Reply-To: <5.2.1.1.0.20040423122322.0247c6a8@www.thinkware.se> References: <5.2.1.1.0.20040423122322.0247c6a8@www.thinkware.se> Message-ID: <40896738.60701@po-box.mcgill.ca> Thanks for the reply, Magnus. Magnus Lyck? said unto the world upon 23/04/2004 06:37: > At 13:34 2004-04-22 -0400, Brian van den Broek wrote: > >> I'm starting a project to write a bunch of functions for parsing the >> datafiles of a particular application I use. Thanks to help from the >> group I now understand how to work with files :-) but I have a >> question about efficient storage of the information I extract. > > > Are you just asking about data structures during program > execution, or are you asking about persistent storage? The first. But seeing you ask this, I wonder if I've misunderstood other things, too. I'd thought that whichever I picked, I could pickle if I wanted to. (Maybe that's a topic for another day though.) >> So, since there may be 1000's of (id, title) pairs, I am wanting to >> choose the best method -- best here being defined as some compromise >> between high speed and small memory footprint. > > > Thousands doesn't sound very big on modern hardware... As a > better measure, how big are the biggest files you need to > process? Some are in the 30 MB range. But I've got the function worked out and when I saw how fast it was on a 4 MB file I saw the wisdom of: "Don't chase ghosts". > As Don Knuth says, premature optimization is the root of all evil. > > Unless the file sizes get bigger than maybe 10% of the amount of > RAM in your machine, I wouldn't worry about performance until I > actually experienced performance problems. > > Try to solve the problem in the simplest and most logical way, and > worry about performance if there is a problem. Don't chase ghosts. As I said, I see your point about ghosts. Driving much of my fretting is the fear that, if I do it wrong now, it will mean much work re-doing things later. But obviously at my current level of knowledge, I don't have a good sense for where those pitfalls might be. In essence, I'm trying the impossible, I guess: to get the benefits of knowing how to avoid costly design mistakes without paying the costs of having made them. > With the list, you retain order of input. With the dictionary, > you get very fast access to data if you know the exact key. You > know what you need, I don't... > If only your reasonable assumption here were true ;-) > -- > Magnus Lycka (It's really Lyckå), magnus@thinkware.se > Thinkware AB, Sweden, www.thinkware.se > I code Python ~ The Agile Programming Language Thanks for the advice! Best, Brian vdB From chidorex-pytutor at yahoo.com Fri Apr 23 16:33:13 2004 From: chidorex-pytutor at yahoo.com (Rex) Date: Fri Apr 23 16:33:24 2004 Subject: [Tutor] py cgi can't show up correctly in Netscape In-Reply-To: <20040423033824.GN28675@niof.net> Message-ID: <20040423203313.43266.qmail@web13424.mail.yahoo.com> --- Rick Pasotto wrote: > On Thu, Apr 22, 2004 at 10:22:58PM -0500, pan@uchicago.edu wrote: > > Hi all, > > > > I have some cgi scripts having some problems with Netscape: > > > > -- If the py cgi called by MSIE, it works fine; > > -- If called by Opera, it works fine; > > -- If called by Netscape, it displays the cgi output code (the html > tags), > > in plain text, but not html-formatted. For example, will be > shown > > on the Netscape. > > -- If I save the output document (view source in Netscape) into a > ???.html > > file and re-open it with Netscape, it shows up with html-formatted > text > > correctly. > > > > I tried Netscape 4.79 and 7.1, on both Window and Linux, both have > the > > same problem. > > > > Does anyone know what's wrong and how to solve it ? > > > > You can test it by clicking: > > http://runsun.info/cgi-bin/cgiTest.py > > You're not outputting any nor sections so > the document you send to the browser is invalid. Some browsers > overlook > some html errors and make guesses and some just get confused. > > -- > "FIJA is not a double-edged sword -- it is a shield against the sword > of > government." -- Tom Glass > Rick Pasotto rick@niof.net http://www.niof.net > > _______________________________________________ I got a correct output on my Windows machine on both IE and Mozilla Firefox 0.8. But Rick is right, you are missing most initial tags. Rex From alan.gauld at blueyonder.co.uk Fri Apr 23 16:41:34 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Apr 23 16:41:08 2004 Subject: [Tutor] math question References: <408923D2.6020605@chrislott.org> <40893BDF.9090401@chrislott.org> Message-ID: <004501c42973$5dced370$6401a8c0@xp> > tutorial. I understand that the sqrt(2) can't be written as an exact > value. But the sqrt(2)^2 certainly can be written in an exact value. No it can't. The mathematically correct result can be but not the evaluation of the expression. Thats because to evaluate the expression Python must work out each factor. In other words, Python knows how to do arithmetic it doesn't know how to do math. > seems strange to me (I'm no mathematician and I suspect > this is a philosophy question rather than a Python question) > that the language can't figure this out Python is just a program like any other. Sit down and try to figure out how you would write that kind of knowledge into a python program. Then try to figure out how to write it such that it didn't slow down arith,metic operations to a crawl. > should see the code and know a difference between adding > .33 + .33 + .333 and 1/3 + 1/3 + 1/3 The only way the computer can do that is to parse the values, apply some expert system rules: If the inverse of a number, x, is added to itself x times then the result is x. Now try writing a program to implement that one rule. Now extend it to cover: A) If a number, x, has its square root multiplied by its square root, anywhere within an expression, substitute x for the result. B) If the square root of a number, x, is raised to the power 2 return x. Check your solution caters for sqrt(2) * sqrt(2) => 2 sqrt(2) * 3 * sqrt(2) => 2*3 = 6 Now extend it for the zillions of other "obvious" mathematical rules, (and don't forget to keep the performance real snappy for number crunching apps) You'll find it is much easier (and faster) to just evaluate each term as you come to it (taking account of precedence and parentheses etc) and produce a final result that way. > hard time explaining to my daughter when I was helping her > with a math/geometry problem and showed her how to use the > Python shell as a kind of calculator This is not a Python issue its a binary storage issue... But if you *print* the results (which uses the str() function) instead of relying on the Python repr() function you should find it all looks ok: >>> from math import sqrt >>> print sqrt(2) * sqrt(2) 2.0 >>> sqrt(2) * sqrt(2) 2.0000000000000004 See the difference? (This is one reason I use print in all the examples in my online tutor despite the extra typing - it mostly avoids revealing these nasty issues early on!) HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From sigurd at 12move.de Fri Apr 23 18:01:51 2004 From: sigurd at 12move.de (=?iso-8859-1?q?Karl_Pfl=E4sterer?=) Date: Fri Apr 23 18:03:20 2004 Subject: [Tutor] math question In-Reply-To: <004501c42973$5dced370$6401a8c0@xp> (Alan Gauld's message of "Fri, 23 Apr 2004 21:41:34 +0100") References: <408923D2.6020605@chrislott.org> <40893BDF.9090401@chrislott.org> <004501c42973$5dced370$6401a8c0@xp> Message-ID: On 23 Apr 2004, Alan Gauld <- alan.gauld@blueyonder.co.uk wrote: >> should see the code and know a difference between adding >> .33 + .33 + .333 and 1/3 + 1/3 + 1/3 > The only way the computer can do that is to parse the values, > apply some expert system rules: No. The above could be solved easily if Python knew how to handle rational numbers (IIRc there has been some discussion about it on clp and there may also have been a PEP but I'm not sure). First in Python: >>> 1/3 0.33333333333333331 >>> _ * 2 0.66666666666666663 That's what we know; rationals are coerced into floats (with all problems). Now the same in Scheme: > (/ 1 3) 1/3 > (* 1/3 2) 2/3 > So if Python had rationals some problems with floats would be easier (of course irrational numbers like sqrt(2) still couldn't be stored exactly and for the question of the OP we needed symbolic computing). > If the inverse of a number, x, is added to itself x times > then the result is x. With rationals no problem. Karl -- Please do *not* send copies of replies to me. I read the list From denis.spir at free.fr Fri Apr 23 15:57:40 2004 From: denis.spir at free.fr (denis) Date: Fri Apr 23 18:12:17 2004 Subject: [Tutor] math question References: <408923D2.6020605@chrislott.org><40893BDF.9090401@chrislott.org> <20040423131522.09879953@aphrodite.pantheon.home> Message-ID: <004e01c4297f$f687d920$5843933e@spir> >Heres something interesting: > > >>> print math.sqrt(2) * math.sqrt(2) > 2.0 > >>> math.sqrt(2) * math.sqrt(2) > 2.0000000000000004 > >>> print math.sqrt(2) ** 2 > 2.0 > >>> math.sqrt(2) ** 2 > 2.0000000000000004 > >>> > > I'm not sure how it gets from the internal representation to what is printed though. Like every language probably, python uses some more decimals for inner computing (what repr()returns and is shown by Idle without statement) than for output (what str() returns and is displayed by 'print'), precisely for that case, as whatever the number of decimals is, the last will always be wrong. If they are cancelled before output, in the present cases one gets : 2.0000000.....0 which is then written 2.0. cqfd, denis ______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From pan at uchicago.edu Fri Apr 23 18:19:24 2004 From: pan at uchicago.edu (pan@uchicago.edu) Date: Fri Apr 23 18:19:29 2004 Subject: [Tutor] py cgi can't show up correctly in Netscape In-Reply-To: References: Message-ID: <1082758764.4089966c21e40@webmail.uchicago.edu> Dear all, Thx for all who responded. At the same time that I asked the question on this list, I also sent the question to the server manager. He modified the file for me by adding the line: print "Content-Type: text/html" right after #!/usr/bin/python, which solved the problem. That's why some of you guys didn't get any incorrect output. It turns out that IE and Opera doesn't need this line for a python cgi to behave correctly. pan From alan.gauld at blueyonder.co.uk Fri Apr 23 18:44:15 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Apr 23 18:43:43 2004 Subject: [Tutor] math question References: <408923D2.6020605@chrislott.org><40893BDF.9090401@chrislott.org> <004501c42973$5dced370$6401a8c0@xp> Message-ID: <007a01c42984$8173ac40$6401a8c0@xp> > >> should see the code and know a difference between adding > >> .33 + .33 + .333 and 1/3 + 1/3 + 1/3 > > > The only way the computer can do that is to parse the values, > > apply some expert system rules: > > No. The above could be solved easily if Python knew how to handle > rational numbers OK, I admit it. Its not the only way the computer could do it. But even here its only making the aritmetic more accurate, Python still evaluates each term in turn, its just that it no longer sees the 1/3 as a math operation but as a math representation (like complex numbers). > So if Python had rationals some problems with floats would be easier (of > course irrational numbers like sqrt(2) still couldn't be stored exactly > and for the question of the OP we needed symbolic computing). Which was the point I was trying to make that basically Python does arithmetic not math. Alan G. From dyoo at hkn.eecs.berkeley.edu Fri Apr 23 20:56:00 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Apr 23 20:56:14 2004 Subject: [Tutor] GUI component In-Reply-To: <20040422231939.23588.qmail@web20724.mail.yahoo.com> Message-ID: On Thu, 22 Apr 2004, bintang kurniawan wrote: > im new beginer in python laguage, and would like to now more on GUI > programming (TK inter). my question is : Hi Bintang, Ah! Ok, there's a lot of tutorials on Tkinter here: http://www.python.org/topics/tkinter/doc.html > 1. how to inherrit component and add some additional function to it. The example here: http://www.python.org/doc/current/lib/node633.html shows how to inherit from a Tkinter frame; we can do the same extension to other widgets by inheritance. > 2. where can i find Combobox and DataGrid component? and how to install > to the python environtment? Those two widgets are part of an Tkinter extention called the Python Megawidgets (PMW). You can find the PMW here: http://pmw.sourceforge.net/ If you have more questions, please feel free to ask! From carroll at tjc.com Fri Apr 23 21:13:42 2004 From: carroll at tjc.com (Terry Carroll) Date: Sat Apr 24 07:21:08 2004 Subject: [Tutor] Standard library modules not installed In-Reply-To: <5.2.1.1.0.20040423120405.02448570@www.thinkware.se> Message-ID: On Fri, 23 Apr 2004, Magnus Lyck? wrote: > Another option would be to install Python 2.3 on the RH box. I think > RH needs Py 2.2 for admin tools, but you can always install Py 2.3 > under /usr/local... I would second this. I'm not much of a unix guy, or much of a small systems syasdmin (I'm a lawyer, former sysprog on IBM mainframes many years ago), and I just installed my own copy of Python 2.3 on my ISP's Linux box (they're pretty back level, and I seem to be the only big Python user), and it was a piece of cake. Anyone comfortable with installing a third-party module should be comfortable installing Python 2.3; they're of about equal complexity. It was maybe a half-hour project for me. From dyoo at hkn.eecs.berkeley.edu Sat Apr 24 03:19:45 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Apr 24 07:33:50 2004 Subject: [Tutor] math question [off-topic: Macsyma/Maxima] In-Reply-To: Message-ID: > There are some specialized systems that allow computers to do symbolic > algebra. Mathematica is one of these: > > http://www.wolfram.com/ > > and there's a Python library that can interface with Mathematica called > PYML: > > http://py-ml.sourceforge.net/ > > Mathematica isn't free, unfortunately. Hi Chris, [my post isn't really Python related; my apologies!] I just found that there is another symbolic algebra system that is freely available. The program is called Maxima: http://maxima.sourceforge.net/index.shtml and is actually an offshoot of one of the original symbolic algebra systems (Macsyma) Here's an example of what it does: ### (C1) sqrt(2) * 5 * sqrt(8); (D1) 20 [a few commands later] (C6) factor(x**5 + x**2 + x); 4 (D6) x (x + x + 1) (C7) 5/2 + 3/2; (D7) 4 ### Cool! It has algebraic capabilities that are very sophisticated. Try it out; I think you'll have fun with the program. Python itself does not implement such a computer-algebra system. As others on the list have mentioned, Python provides the tools for doing arithmetic, but anything that's in the realm of mathematical reasoning is stuff that we'll probably have to develop on our own. It's technically feasible to write some Python module that talks to Maxima, and someone appears to already have started this: http://cens.ioc.ee/~pearu/misc/maxima/talkto.py Good luck to you! From jason at smileproject.com Sat Apr 24 12:16:04 2004 From: jason at smileproject.com (Jason Van Anden) Date: Sat Apr 24 12:16:39 2004 Subject: [Tutor] Flip Book Animation without GUI? Message-ID: Hi All, I am looking to do a simple flip-book style animation from a Linux command line - no x11, just run from the blinking cursor. 640 x 480. Any thoughts? J From missive at hotmail.com Sat Apr 24 14:01:52 2004 From: missive at hotmail.com (Lee Harr) Date: Sat Apr 24 14:02:00 2004 Subject: [Tutor] Re: Flip Book Animation without GUI? Message-ID: >I am looking to do a simple flip-book style animation from a Linux >command line - no x11, just run from the blinking cursor. 640 x 480. >Any thoughts? > http://aa-project.sourceforge.net/ _________________________________________________________________ Tired of spam? Get advanced junk mail protection with MSN 8. http://join.msn.com/?page=features/junkmail From rantek at pacific.net.sg Sun Apr 25 00:29:59 2004 From: rantek at pacific.net.sg (William Rance) Date: Sun Apr 25 00:31:44 2004 Subject: [Tutor] math question References: <408923D2.6020605@chrislott.org> <40893BDF.9090401@chrislott.org> Message-ID: <003101c42a7d$f8abbe20$6a4718d2@pcmaster> These type of problems surfaced over 30 years ago when introducing digital LCD readouts to replace the analogue. The analogue precision was such that if for example you are reading a temperature visually, if you could read within 0.5degc you were doing pretty good, also two people would probably give it a different reading. Along came the digital LCD with reading to two deciaml places and expectations were magnified, even if your sensor was only accurate to with 1degC.This stiil true today. And so it is with programming. We now expect perfection, why? Just because we believe the computer should be; it is man made remember. For floating point arithmetic computation IEEE standard applies. I also cannot understand the eduction system which insists on absolute correctness; to me (a professional engineer) the method is more important-tell a 9 year old that water always boils at 100degC and he believes you, tell a mature student and he will laugh -knowing pressure and other factors come into the equation? Unfortunately I also find (in general)a female's mind works differently /they seem to expect absoluteness/perfection -whereas a male is much more tolerant looking more at the overall problem (mind you I can't recall any female Noble Prize winner in maths/physics). And so life goes on..... Bill Rance ----- Original Message ----- From: "Chris Lott" To: Sent: Friday, April 23, 2004 11:53 PM Subject: Re: [Tutor] math question Karl Pfl?sterer wrote: > Here are several problems: > (a) sqrt(2) can't be written as exact value (neither base 10 nor base > 2). So Python uses a floating point approximation > (b) you see the internal representation of the numbers (repr()) > (c) most floating point numbers can't be represented exactly in the way > Python stores them > > A very good explanation of the problems with floating point numbers can > be found in the Python tutorial in the official documentation. You > should read it. > > A simple example from it which shows the problem: I understand and I don't understand. I've read that section in the tutorial. I understand that the sqrt(2) can't be written as an exact value. But the sqrt(2)^2 certainly can be written in an exact value. It seems strange to me (I'm no mathematician and I suspect this is a philosophy question rather than a Python question) that the language can't figure this out-- similarly, if I add up 1/3 + 1/3 + 1/3 there is no reason (to my layperson's mind) that it doesn't come out to 1, regardless of the individual values. I guess it seems like something should see the code and know a difference between adding .33 + .33 + .333 and 1/3 + 1/3 + 1/3 I can't conceive of why it would *matter* in anything I do, but I had a hard time explaining to my daughter when I was helping her with a math/geometry problem and showed her how to use the Python shell as a kind of calculator and was demonstrating to her and got 2.000000004 here :) c -- Chris Lott _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From tony at tcapp.com Sun Apr 25 00:34:07 2004 From: tony at tcapp.com (Tony Cappellini) Date: Sun Apr 25 00:34:11 2004 Subject: [Tutor] Problems with ConfigParser Message-ID: <20040424212453.B49363-100000@yamato.yamato.com> I'm using the ConfigParser for the first time. While it does seem to work- that is I can set the options in the section to the value that I want, when the ini file is written back out, the case of the option text is forced to lower case (as opposed to the natural case of the text as it was read in) and the Sections are in a very unusual order Here is a snippet of what the orginal file looks like [GPIB0] AUTOPOLL=Yes BoardName=PCI-GPIB BoardType=0x5B CICPROT=No CompatibleType=0xFF EOSchar=0 EOScmp=7-bit EOSrd=No EOSwrt=No EOT=Yes HSCableLength=Off IPAddress=xxx.xxx.xxx.xxx PAD=22 PPollTime=Default SAD=None SC=Yes SerialNumber=0x010823C3 SRE=NO TIMING=500nsec TMO=10sec [GPIB1] AUTOPOLL=Yes BoardName=None BoardType=0xFF CICPROT=No CompatibleType=0xFF EOSchar=0 EOScmp=7-bit EOSrd=No EOSwrt=No EOT=Yes HSCableLength=Off IPAddress=xxx.xxx.xxx.xxx PAD=0 PPollTime=Default SAD=None SC=Yes SerialNumber=0xFFFFFFFF SRE=No TIMING=500nsec TMO=10sec Here is what is written out by the ConfigParser [GPIB0] eosrd = No boardtype = 0x5B compatibletype = 0xFF hscablelength = Off cicprot = No serialnumber = 0x010823C3 eoschar = 0 ppolltime = Default boardname = PCI-GPIB sre = NO sc = off autopoll = Yes pad = 22 eot = Yes timing = 500nsec eoswrt = No sad = None ipaddress = xxx.xxx.xxx.xxx tmo = 10sec eoscmp = 7-bit [GPIB3] eosrd = No boardtype = 0xFF compatibletype = 0xFF hscablelength = Off cicprot = No serialnumber = 0xFFFFFFFF eoschar = 0 ppolltime = Default boardname = None sre = No sc = Yes autopoll = Yes pad = 0 eot = Yes timing = 500nsec eoswrt = No sad = None ipaddress = xxx.xxx.xxx.xxx tmo = 10sec eoscmp = 7-bit Note - these two sections are sequential in the output file, but are not in the same order as the original file. While the program that needs to read this can still read the file, after the COnfigParser has done it's mangling, I would very much prefer to keep the file looking like the original. If there is no built-in way to do this (pasing some kind of arg, or setting a flag) I'll just throw away the config parser and do it myself. The optionsform method talks about the case of the text- but it's pretty confuing the way it's written. Has anyone else seen this behaviour with ConfigParser ? From carroll at tjc.com Sun Apr 25 01:26:44 2004 From: carroll at tjc.com (Terry Carroll) Date: Sun Apr 25 01:26:49 2004 Subject: [Tutor] math question In-Reply-To: <003101c42a7d$f8abbe20$6a4718d2@pcmaster> Message-ID: On Sun, 25 Apr 2004, William Rance wrote: > (mind you I can't recall any > female Noble Prize winner in maths/physics). I can't recall any *male* Nobel prize winner in math, either. From idiot1 at netzero.net Sun Apr 25 01:34:44 2004 From: idiot1 at netzero.net (Kirk Bailey) Date: Sun Apr 25 01:33:40 2004 Subject: [Tutor] Series of pages on introductory scripting Message-ID: <408B4DF4.7020005@netzero.net> I am working on writing a series of pages introducing the gentle art of scripting with an eye to web and other Internet applications. This series thus far is a first draft, but I invite the community to clicking and see what is there. This link points at the first of a series of pages. I INVITE YOU TO PARTICIPATE AND CONTRIBUTE. And if you find a typo, that buried treasure is yours to fix if you wish. After all, it's a wiki. http://www.tinylist.org/cgi-bin/wikinehesa.py/WebPageCoding -- Respectfully, Kirk D Bailey, Pinellas county Florida USA think http://www.tinylist.org/ - $FREE$ Liberating software +-------+ http://www.pinellasintergroupsociety.org/ - NeoPagan | BOX | http://www.listville.net/ - $FREE$ list hosting! +-------+ http://www.howlermonkey.net/ - $FREE$ email Accounts kniht http://www.sacredelectron.org/ - My personal site From magnus at thinkware.se Sun Apr 25 06:13:23 2004 From: magnus at thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sun Apr 25 06:09:47 2004 Subject: [Tutor] math question In-Reply-To: <003101c42a7d$f8abbe20$6a4718d2@pcmaster> References: <408923D2.6020605@chrislott.org> <40893BDF.9090401@chrislott.org> Message-ID: <5.2.1.1.0.20040425115604.024b94f0@www.thinkware.se> At 12:29 2004-04-25 +0800, William Rance wrote: >Unfortunately I also find (in general)a female's mind works differently >/they seem to expect absoluteness/perfection -whereas a male is much more >tolerant looking more at the overall problem On the other hand, it seems we men are more prone to say really stupid and degrading things about others. >(mind you I can't recall any female Noble Prize winner in maths/physics). You can visit www.nobel.se if you want to refresh your memory (or learn something new). (Marie Curie got both the Physics (1903) and the Chemistry prize (1911)? ) While generalizations are sometimes very useful, gender, race etc are in general poor predictors for their logical ability of a certain individual. Can we please keep this mailing list free from from male chauvinism in the future? -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From pythontut at pusspaws.net Sun Apr 25 07:38:40 2004 From: pythontut at pusspaws.net (Dave S) Date: Sun Apr 25 07:38:52 2004 Subject: [Tutor] wierd error in comment string Message-ID: <408BA340.8010803@pusspaws.net> Hi all, my python learning curve continues :-) I have a comment at the start of some experimental code ... 1 #!/usr/bin/env python 2 3 """ 4 ...... blah blah 5 ....... blah blah 6 7 The ftse trades from 8:15 to 16:30 8 Expenses ?8.50 per transaction + 1/2% on buying ... this equates 9 to 1.4% on a ?2000 fund 10 11 This logger is v2 ... pulls less data to avoid being blacklisted 12 by the server. 13 """ 14 15 import urllib,time,os,re 16 17 todaysdate=time.strftime('%Y%m%d') 18 old_ftsedata='' 19 It appears to run OK but I get a warning message ... sys:1: DeprecationWarning: Non-ASCII character '\xa3' in file ./ftseloggerv2.py on line 9, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details I looked up the web page .... got confused. I thought all characters inside """...""" were ignored ? Anyhow I deleted line 9, same error, deleted line 9 again, same error. Can anyone tell me in simple speak what has gone wrong ? :-\ Thanks Dave From pythontut at pusspaws.net Sun Apr 25 08:42:44 2004 From: pythontut at pusspaws.net (Dave S) Date: Sun Apr 25 08:42:58 2004 Subject: [Tutor] wierd error in comment string In-Reply-To: <408BA340.8010803@pusspaws.net> References: <408BA340.8010803@pusspaws.net> Message-ID: <408BB244.1010201@pusspaws.net> Dave S wrote: > Hi all, my python learning curve continues :-) > > I have a comment at the start of some experimental code ... > 1 #!/usr/bin/env python > 2 > 3 """ > 4 ...... blah blah > 5 ....... blah blah > 6 > 7 The ftse trades from 8:15 to 16:30 > 8 Expenses ?8.50 per transaction + 1/2% on buying ... this equates > 9 to 1.4% on a ?2000 fund > 10 > 11 This logger is v2 ... pulls less data to avoid being blacklisted > 12 by the server. > 13 """ > 14 > 15 import urllib,time,os,re > 16 > 17 todaysdate=time.strftime('%Y%m%d') > 18 old_ftsedata='' > 19 > > It appears to run OK but I get a warning message ... > > sys:1: DeprecationWarning: Non-ASCII character '\xa3' in file > ./ftseloggerv2.py on line 9, but no encoding declared; see > http://www.python.org/peps/pep-0263.html for details > > I looked up the web page .... got confused. I thought all characters > inside """...""" were ignored ? > Anyhow I deleted line 9, same error, deleted line 9 again, same error. > > Can anyone tell me in simple speak what has gone wrong ? :-\ > > Thanks Dave > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > By a method of elimination it is the ? it does not like .... I have to tell python to use a character set which includes a ? ? Dave From n.a.vogelpoel at chello.nl Sun Apr 25 09:18:22 2004 From: n.a.vogelpoel at chello.nl (Jeroen Vogelpoel) Date: Sun Apr 25 09:21:00 2004 Subject: [Tutor] Python socket programming Message-ID: <408BBA9E.2060704@chello.nl> Good day, Recently I began to poke around a bit with python and I've stumbled upon a problem with socket programming. It doesn't make allot of sense to me anymore, so I hope someone around here can shed some light on this matter. Anyways, here's the code that I have: from socket import * testsocket = socket( AF_INET, SOCK_STREAM ) testsocket.connect( ( "192.168.0.1", 80 ) ) testsocket.settimeout( 3 ) HTTPReq = "GET / HTTP/1.1" bytesSent = testsocket.send( HTTPReq ) print len( HTTPReq ) print bytesSent testsocket.recv( 1024 ) testsocket.close() The socket.settimeout() has been used to stop the code from blocking indefinitely, which would otherwise require me to shut down the running process using Windows Task Manager. That also sums up the main problem, this code doesn't actually receive anything. What is odd, though, is the fact that socket.send() does return 14, the same value of len( HTTPReq ) so it did send something. However, if I look at the logs of the webserver, it shows no incoming request from my IP at all, which would explain why this script would block. What's also odd is that when I try the socket examples given in the documentation, it works perfectly. However, it only works as long as both the client and server are on the local machine. I changed the host and port values of the example to my webserver's host and port 80 and it blocked again, while it should have come up with "HTTP/1.1 500 Bad Request", etcetera. Now I'm stuck on this... :( As for some nescesarry details reagarding the situation, the target host does run a webserver which responds to request from the internal network. Granted, it responds with a 403 code but that should not be an issue, because it should receive something anyways. There are no odd TCP settings or encryptions in use on the internal network either and the socket system works nicely in various other languages, except for Python in this case. I'm aware of some nifty specialized classes for HTTP client use, but I intend to use sockets for something else later on so this is mainly to learn how to work with sockets. From godoy at ieee.org Sun Apr 25 11:11:25 2004 From: godoy at ieee.org (Jorge Godoy) Date: Sun Apr 25 11:15:36 2004 Subject: [Tutor] Parallel port interface Message-ID: <811tl1-mk2.ln1@wintermute.g2ctech> Hi! We're doing a research project that involves controlling mini-windtrap speeds and we're reading/writing data from the parallel port. What I've found so far on a fast Google search for "python parallel port" showed me some stuff that I'd have to interface with Python through SWIG. If the program could be portable in Windows and Linux it would be a big plus. We're thinking --- if it can't be written entirely in Python or with modules that already have binaries for Windows --- in using a Linux only approach (we, the programmers, use Linux only). Any hints for modules I should take a look at? TIA, -- Godoy. From magnus at thinkware.se Sun Apr 25 11:21:23 2004 From: magnus at thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sun Apr 25 11:17:45 2004 Subject: [Tutor] wierd error in comment string In-Reply-To: <408BB244.1010201@pusspaws.net> References: <408BA340.8010803@pusspaws.net> <408BA340.8010803@pusspaws.net> Message-ID: <5.2.1.1.0.20040425170943.02470880@www.thinkware.se> At 13:42 2004-04-25 +0100, Dave S wrote: >By a method of elimination it is the ? it does not like .... Yes, that's the only non-ASCII character in your file. >I have to tell python to use a character set which includes a ? ? If you use IDLE, it will tell you what to do, and even fix the file for you if you wish. Otherwaise, add something like # -*- coding: cp1252 -*- or # -*- coding: iso8859_1 -*- as the first or second line in the file. (This is a new inconvenience from Python 2.3. I'm happy to see it bite English speaking people as well! ;) -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From pythontut at pusspaws.net Sun Apr 25 11:46:02 2004 From: pythontut at pusspaws.net (Dave S) Date: Sun Apr 25 11:46:13 2004 Subject: [Tutor] wierd error in comment string In-Reply-To: <5.2.1.1.0.20040425170943.02470880@www.thinkware.se> References: <408BA340.8010803@pusspaws.net> <408BA340.8010803@pusspaws.net> <5.2.1.1.0.20040425170943.02470880@www.thinkware.se> Message-ID: <408BDD3A.4070600@pusspaws.net> Magnus Lyck? wrote: > At 13:42 2004-04-25 +0100, Dave S wrote: > >> By a method of elimination it is the ? it does not like .... > > > Yes, that's the only non-ASCII character in your file. > >> I have to tell python to use a character set which includes a ? ? > > > If you use IDLE, it will tell you what to do, and even fix the > file for you if you wish. Otherwaise, add something like > > # -*- coding: cp1252 -*- > > or > > # -*- coding: iso8859_1 -*- > > as the first or second line in the file. > > (This is a new inconvenience from Python 2.3. I'm happy > to see it bite English speaking people as well! ;) > > > -- > Magnus Lycka (It's really Lyckå), magnus@thinkware.se > Thinkware AB, Sweden, www.thinkware.se > I code Python ~ The Agile Programming Language > > It works :-) ! Ive re-introduced my ? signs now, its a lot more readable. Many thanks Dave From alan.gauld at blueyonder.co.uk Sun Apr 25 15:06:46 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Apr 25 15:06:16 2004 Subject: [Tutor] math question References: <408923D2.6020605@chrislott.org><40893BDF.9090401@chrislott.org> <003101c42a7d$f8abbe20$6a4718d2@pcmaster> Message-ID: <003a01c42af8$74ae9130$6401a8c0@xp> > female Noble Prize winner in maths/physics). I think Marie Curie? :-) Alan G. From alan.gauld at blueyonder.co.uk Sun Apr 25 15:10:41 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Apr 25 15:10:09 2004 Subject: [Tutor] wierd error in comment string References: <408BA340.8010803@pusspaws.net> Message-ID: <004301c42af9$007b9960$6401a8c0@xp> > I have a comment at the start of some experimental code ... > 1 #!/usr/bin/env python THis is a comment > 2 > 3 """ > 4 ...... blah blah > 5 ....... blah blah > 6 This is a documentation string stored as the __doc__ variable for the module. > sys:1: DeprecationWarning: Non-ASCII character '\xa3' in file > ./ftseloggerv2.py on line 9, but no encoding declared; see > http://www.python.org/peps/pep-0263.html for details So Python correctly tells you that you are storing a strangeness. > I looked up the web page .... got confused. I thought all characters > inside """...""" were ignored ? No, they are not ignored they are stored as the doc string. As such they act like a comment, but one which is available at run time... > Can anyone tell me in simple speak what has gone wrong ? :-\ Change it to a true comment (# at all the line starts) or make the string unicode. HTH Alan G. From alan.gauld at blueyonder.co.uk Sun Apr 25 15:15:30 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Apr 25 15:15:00 2004 Subject: [Tutor] Parallel port interface References: <811tl1-mk2.ln1@wintermute.g2ctech> Message-ID: <004c01c42af9$acedb7a0$6401a8c0@xp> > We're doing a research project that involves controlling mini-windtrap > speeds and we're reading/writing data from the parallel port. For DOS?WIndows have you tried just writing to the LPT: on PRN: files? > If the program could be portable in Windows and Linux it would be a big > plus. I doubt that it will be possible, low level I/O is always one of the least portable things in an OS, its down at the level of device drivers. Logical devices like printers can be controlled via a high lrevel protocol like lpr but if its the actual port you are controlling then I suspect you'll need to write your own interfaces and switch according to OS... > Any hints for modules I should take a look at? If you do find a platform neutral module I'd be interested in hearing about it though... Alan G From godoy at ieee.org Sun Apr 25 15:30:26 2004 From: godoy at ieee.org (Jorge Godoy) Date: Sun Apr 25 15:35:32 2004 Subject: [Tutor] Re: Parallel port interface References: <811tl1-mk2.ln1@wintermute.g2ctech> <004c01c42af9$acedb7a0$6401a8c0@xp> Message-ID: On Dom 25 Abr 2004 16:15, Alan Gauld wrote: >> We're doing a research project that involves controlling > mini-windtrap >> speeds and we're reading/writing data from the parallel port. > > For DOS?WIndows have you tried just writing to the LPT: on PRN: > files? No, I haven't. And from my previous research, it won't work on all flavours of Windows. I don't know which one I'll have to run the system on, if I run it on Windows... > I doubt that it will be possible, low level I/O is always one of > the least portable things in an OS, its down at the level of device > drivers. I dunno if it's all that hard. There could be some modules that handle the correct calls on each system. Even something to wrap reads and writes from the correct ports on the OS would do it. It just need to access those the right way. I just read that there's need for using DLLs on certain versions of Windows (e.g. 2000, NT) while you can, as you suggested, read/write directly to PRN: on other (e.g. 95, 98). > Logical devices like printers can be controlled via a high lrevel > protocol like lpr but if its the actual port you are controlling > then I suspect you'll need to write your own interfaces and switch > according to OS... I'm just willing to read and set bits as done with inportb and outportb on C. I'm not willing to have all the work of writing code for each one. :-) This is some laziness of myself, I admit it, but I can't also test on the several different flavours of Windows... :-) >> Any hints for modules I should take a look at? > > If you do find a platform neutral module I'd be interested in > hearing about it though... This is just why I've sent the message :-) I don't imagine that there aren't any modules like that around. If I find something, I'll let you know. Thanks for your answer, -- Godoy. From denis.spir at free.fr Sun Apr 25 18:25:59 2004 From: denis.spir at free.fr (denis) Date: Sun Apr 25 18:34:58 2004 Subject: [Tutor] wierd error in comment string References: <408BA340.8010803@pusspaws.net><408BA340.8010803@pusspaws.net> <5.2.1.1.0.20040425170943.02470880@www.thinkware.se> Message-ID: <00a301c42b15$73c1ba00$ce25933e@spir> Dave : >I have to tell python to use a character set which includes a ? ? Magnus : If you use IDLE, it will tell you what to do, and even fix the file for you if you wish. Otherwaise, add something like # -*- coding: cp1252 -*- or # -*- coding: iso8859_1 -*- as the first or second line in the file. (This is a new inconvenience from Python 2.3. I'm happy to see it bite English speaking people as well! ;) Denis : Would you add some contents on this ? Why doesn't python accept iso8859-1 character set anymore ? I just did a test on french weird characters, which were previously processed and, as you suggest : '???????' '\xe9\xe8\xe0\xf9\xeb\xea\xe7' they're not anymore more :-( The standard 8-bit extended ASCII / ANSI set holds af them, as well as the iso 8859-1 set and the first unicode page of 256 characters. From magnus at thinkware.se Sun Apr 25 19:38:20 2004 From: magnus at thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sun Apr 25 19:34:43 2004 Subject: [Tutor] wierd error in comment string In-Reply-To: <00a301c42b15$73c1ba00$ce25933e@spir> References: <408BA340.8010803@pusspaws.net> <408BA340.8010803@pusspaws.net> <5.2.1.1.0.20040425170943.02470880@www.thinkware.se> Message-ID: <5.2.1.1.0.20040426011035.024f5310@www.thinkware.se> At 00:25 2004-04-26 +0200, denis wrote: >Denis : >Would you add some contents on this ? Why doesn't python accept iso8859-1 >character set anymore ? It does! It just wants you to be explicit, which is very Pythonic... ;) >I just did a test on french weird characters, which were previously >processed and, as you suggest : >'???????' >'\xe9\xe8\xe0\xf9\xeb\xea\xe7' >they're not anymore more :-( I'm not sure what you did. What is the problem? This is on my Python 2.3 installation on Windows 2000: >>> print '\xe9\xe8\xe0\xf9\xeb\xea\xe7' ??????? >>> '\xe9\xe8\xe0\xf9\xeb\xea\xe7' '\xe9\xe8\xe0\xf9\xeb\xea\xe7' I think it's always been like this. repr() returns hex representation for non-ASCII values, but str() translates them if it can. >The standard 8-bit extended ASCII / ANSI set holds af them, as well as the >iso 8859-1 set and the first unicode page of 256 characters. I don't know all the details around this. I think that Mark-Andr? Lemburg and Martin L?vis might be the experts in this field (but I don't think they follow tutor). Perhaps Tim Peters who is sometimes seen here knows more about how the Python developers discussed around these issues. It seems to me that in versions up to and including 2.2, Python just let you as a programmer take responsibility for the interpretation of characters in the 128-255 range of normal strings. It would just output bytes as provided, and if you wrote a program assuming ISO 8859-1, and someone ran that script in a computer with Japanese or Russian settings, they would see garbage on the screen. From version 2.3, it seems Python is more and more adopting Unicode, and an awareness that not all the world uses the same 8 bit code page, and that the 128-255 range for strings is ambious unless you declare what codepage you are using. In a long term perspective, I hope that all strings will be Unicode in some future, and that this will all be transparent, but right now, we can't really ignore Unicode any longer if we use anything but US ASCII, and it's not as transparent as one might wish. Of course, the big disadvantage is that Python programs have to get a little more cluttered to work right now, but it has some advantages, for instance, something like... # -*- coding: iso8859_1 -*- print u'Magnus Lyck?' ...will print my name right both in Linux, in a Windows GUI window and in a Windows command line prompt. Without unicode strings, I had to convert it to cp850 (or possibly cp437) to get it to display right at a "DOS prompt". It's not without problems though. I've had plenty of problems at my current client, which still uses Windows NT 4.0. For instance, I get an exception if I try something like raw_input(u'???'). It works in Windows 2000 though, so I guess it's just a problem in ancient Windows versions. (Microsoft is dropping support for NT 4.0 right?) -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From pythonTutor at venix.com Sun Apr 25 21:02:20 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Sun Apr 25 21:02:30 2004 Subject: [Tutor] Python socket programming In-Reply-To: <408BBA9E.2060704@chello.nl> References: <408BBA9E.2060704@chello.nl> Message-ID: <1082941339.13653.74.camel@laptop.venix.com> This may not be relevant, but you are not actually passing an HTTP/1.1 request, since there are no headers. I would try a simple: GET / which is HTTP .9 and see if that gets a response from the webserver. In other words, you may really be debugging a webserver failure rather than a socket program error. (Yes an invalid HTTP/1.1 request should provoke an invalid request response, but your request may to too invalid for the server.) Alternatively, if ONLY local connections work, that raises the possibility of some kind of network issue. Could your internal network enforce the use of a web proxy server for all outside access? Were the working socket programs in other languages executing the same test to the same webserver? On Sun, 2004-04-25 at 09:18, Jeroen Vogelpoel wrote: > Good day, > > Recently I began to poke around a bit with python and I've stumbled upon > a problem with socket programming. It doesn't make allot of sense to me > anymore, so I hope someone around here can shed some light on this > matter. Anyways, here's the code that I have: > > from socket import * > testsocket = socket( AF_INET, SOCK_STREAM ) > testsocket.connect( ( "192.168.0.1", 80 ) ) > testsocket.settimeout( 3 ) > HTTPReq = "GET / HTTP/1.1" > bytesSent = testsocket.send( HTTPReq ) > print len( HTTPReq ) > print bytesSent > testsocket.recv( 1024 ) > testsocket.close() > > The socket.settimeout() has been used to stop the code from blocking > indefinitely, which would otherwise require me to shut down the running > process using Windows Task Manager. That also sums up the main problem, > this code doesn't actually receive anything. What is odd, though, is the > fact that socket.send() does return 14, the same value of len( HTTPReq ) > so it did send something. However, if I look at the logs of the > webserver, it shows no incoming request from my IP at all, which would > explain why this script would block. What's also odd is that when I try > the socket examples given in the documentation, it works perfectly. > However, it only works as long as both the client and server are on the > local machine. I changed the host and port values of the example to my > webserver's host and port 80 and it blocked again, while it should have > come up with "HTTP/1.1 500 Bad Request", etcetera. Now I'm stuck on > this... :( > > As for some nescesarry details reagarding the situation, the target host > does run a webserver which responds to request from the internal > network. Granted, it responds with a 403 code but that should not be an > issue, because it should receive something anyways. There are no odd TCP > settings or encryptions in use on the internal network either and the > socket system works nicely in various other languages, except for Python > in this case. I'm aware of some nifty specialized classes for HTTP > client use, but I intend to use sockets for something else later on so > this is mainly to learn how to work with sockets. > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From n.a.vogelpoel at chello.nl Sun Apr 25 22:20:55 2004 From: n.a.vogelpoel at chello.nl (Jeroen Vogelpoel) Date: Sun Apr 25 22:23:34 2004 Subject: [Tutor] Python socket programming In-Reply-To: <1082941339.13653.74.camel@laptop.venix.com> References: <408BBA9E.2060704@chello.nl> <1082941339.13653.74.camel@laptop.venix.com> Message-ID: <408C7207.3010302@chello.nl> Lloyd Kvam wrote: > This may not be relevant, but you are not actually passing an HTTP/1.1 > request, since there are no headers. I would try a simple: > GET / > which is HTTP .9 and see if that gets a response from the webserver. > > In other words, you may really be debugging a webserver failure rather > than a socket program error. (Yes an invalid HTTP/1.1 request should > provoke an invalid request response, but your request may to too invalid > for the server.) > > Alternatively, if ONLY local connections work, that raises the > possibility of some kind of network issue. Could your internal network > enforce the use of a web proxy server for all outside access? Were the > working socket programs in other languages executing the same test to > the same webserver? > Hmm, got a few interesting points there. I've just tried to connect to my webserver using plain old telnet and I got responses on both "GET /\n" and "GET / HTTP/1.1\n\n", so I assume the error handling on my webserver works fine and looking at the reports in the logs, so does the logging mechanism. Thus as far as that is concerned, the webserver itself is operating normally. The misformed HTTP/1.1 request, well... I don't have an excuse for that other then sloppy coding while trying to make this sockets idea work. Actually, I've just found out what is is... A bit more experimenting with poking around on port 80 on my local server revealed the rather embarrasing cause: A simple missing newline. It should have been "GET /\n" instead of just "GET /". Sloppy coding indeed. Sorry to have wasted everyone's time, I'll go smash my head against the wall a few times. Thank you for trying to help though! :) From tony at tcapp.com Mon Apr 26 01:06:26 2004 From: tony at tcapp.com (Tony Cappellini) Date: Mon Apr 26 01:06:50 2004 Subject: re[Tutor] Parallel port interface Message-ID: <6.0.0.22.0.20040425220340.03867008@smtp.sbcglobal.net> For a linux-only solution, take a look at what Drew Pertulla did, at BigAsterisk.com http://bigasterisk.com/parallel It's C-based, but you *may* be able to use it from Python Message: 11 Date: Sun, 25 Apr 2004 12:11:25 -0300 From: Jorge Godoy Subject: [Tutor] Parallel port interface To: tutor@python.org Message-ID: <811tl1-mk2.ln1@wintermute.g2ctech> Content-Type: text/plain; charset=us-ascii Hi! We're doing a research project that involves controlling mini-windtrap speeds and we're reading/writing data from the parallel port. What I've found so far on a fast Google search for "python parallel port" showed me some stuff that I'd have to interface with Python through SWIG. If the program could be portable in Windows and Linux it would be a big plus. We're thinking --- if it can't be written entirely in Python or with modules that already have binaries for Windows --- in using a Linux only approach (we, the programmers, use Linux only). Any hints for modules I should take a look at? From magnus at thinkware.se Mon Apr 26 08:25:34 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Mon Apr 26 08:25:51 2004 Subject: [Tutor] EuroPython Conference in June? Message-ID: Hi! I just thought I'd inform/remind people on the tutor list about the Europython Conference June 7-9. This year it takes place in G?teborg, Sweden, and it's a really good time to learn more about Python and to meet other Python programmers. Early bird registration ends on May 1st, so it's a good idea to register now to avoid paying 50-60 Euros extra. It seems the pre-booked budget rooms are running out too, and you might need to be fairly early to get good accomodations elsewhere as well, so don't wait too long. You can fly cheaply to G?teborg with Ryanair from London and a few other places. There is more info about how to get there and where to stay etc at http://www.europython.org/ Only a few talks have been accepted so far, but the deadline for submitting talks is today, so I hope to see many more accepted and scheduled talks soon. If you want to peek at the talk submissions, go to the search page and uncheck all item types except "Plone Conference Talk", and search (perhaps without a search text). -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From godoy at ieee.org Mon Apr 26 10:01:36 2004 From: godoy at ieee.org (Jorge Godoy) Date: Mon Apr 26 10:06:00 2004 Subject: [Tutor] Re: reParallel port interface References: <6.0.0.22.0.20040425220340.03867008@smtp.sbcglobal.net> Message-ID: <6chvl1-om8.ln1@wintermute.g2ctech> On Seg 26 Abr 2004 02:06, Tony Cappellini wrote: > > > For a linux-only solution, take a look at what Drew Pertulla did, at > BigAsterisk.com > http://bigasterisk.com/parallel > > It's C-based, but you *may* be able to use it from Python Thanks Tony! It was one of the results from Google that I got... It looks interesting but is Linux only (not that it is a problem, as I said yesterday :-)). -- Godoy. From dyoo at hkn.eecs.berkeley.edu Mon Apr 26 11:19:57 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Apr 26 11:20:06 2004 Subject: [Tutor] Flip Book Animation without GUI? In-Reply-To: Message-ID: On Sat, 24 Apr 2004, Jason Van Anden wrote: > I am looking to do a simple flip-book style animation from a Linux > command line - no x11, just run from the blinking cursor. 640 x 480. > Any thoughts? Hi Jason, Have you tried curses yet? It provides terminal access: http://www.python.org/doc/lib/module-curses.html Here's a small example of curses in action: http://hkn.eecs.berkeley.edu/~dyoo/python/circularwriting.py and you can probably do some kind of flip-book animation with this. When you mentioned no-GUI as a requirement, do you mean no graphics altogeter, or just no GUI widgets? If you want to access a graphics library, the pygame library might be useful: http://pygame.org/ Lee Harr mentioned the 'aalib' project. I wonder: is aalib is accessible from pygame? According to: http://www.libsdl.org/faq.php?action=listentries&category=3#30 it might be possible to do this. Good luck to you! From godoy at ieee.org Mon Apr 26 12:17:07 2004 From: godoy at ieee.org (Jorge Godoy) Date: Mon Apr 26 12:20:47 2004 Subject: [Tutor] Re: Parallel port interface References: <811tl1-mk2.ln1@wintermute.g2ctech> <004c01c42af9$acedb7a0$6401a8c0@xp> Message-ID: <3cpvl1-04b.ln1@wintermute.g2ctech> On Dom 25 Abr 2004 16:15, Alan Gauld wrote: > If you do find a platform neutral module I'd be interested in > hearing about it though... Alan, Peter Hansen sent me this at the comp.lang.python newsgroup on Usenet: http://pyserial.sourceforge.net/pyparallel.html It might be worth for you to take a look at it too :-) Thanks for your prior help, -- Godoy. From adam at monkeez.org Mon Apr 26 15:43:57 2004 From: adam at monkeez.org (Adam) Date: Mon Apr 26 15:45:30 2004 Subject: [Tutor] Problems importing random on linux Message-ID: <408D667D.4020205@monkeez.org> I use a linux machine and win machine at work. My win machine has no problem importing random and then using the randint(x,y) module. However, when I try and do this on my linux debian machine, I get: adam@debian:~/python$ ./autoguess.py Traceback (most recent call last): File "./autoguess.py", line 49, in ? generatenumber() File "./autoguess.py", line 6, in generatenumber target = random.randint(0,100) AttributeError: 'module' object has no attribute 'randint' from the code: import random def generatenumber(): target = random.randint(0,100) What is going on here? I've tried the same small piece of code : import random target = random.randing(0,100) at the interpreter and it works, but if I try this as an application in a file, it fails. Any ideas ? adam From orbitz at ezabel.com Mon Apr 26 15:51:02 2004 From: orbitz at ezabel.com (orbitz@ezabel.com) Date: Mon Apr 26 15:52:04 2004 Subject: [Tutor] Problems importing random on linux In-Reply-To: <408D667D.4020205@monkeez.org> References: <408D667D.4020205@monkeez.org> Message-ID: <20040426155102.0fb2dbc0.orbitz@ezabel.com> Sounds like you might have 2 version of python on your system. Check for multiple python binaries. also try running your script with: python autoguess.py and see what happens. On Mon, 26 Apr 2004 20:43:57 +0100 Adam wrote: > I use a linux machine and win machine at work. My win machine has no > problem importing random and then using the randint(x,y) module. > However, when I try and do this on my linux debian machine, I get: > > adam@debian:~/python$ ./autoguess.py > Traceback (most recent call last): > File "./autoguess.py", line 49, in ? > generatenumber() > File "./autoguess.py", line 6, in generatenumber > target = random.randint(0,100) > AttributeError: 'module' object has no attribute 'randint' > > from the code: > import random > > def generatenumber(): > target = random.randint(0,100) > > What is going on here? I've tried the same small piece of code : > import random > target = random.randing(0,100) at the interpreter and it works, but if I > try this as an application in a file, it fails. > > Any ideas ? > > adam > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From adam at monkeez.org Mon Apr 26 17:01:30 2004 From: adam at monkeez.org (Adam) Date: Mon Apr 26 17:01:42 2004 Subject: [Tutor] Problems importing random on linux In-Reply-To: <20040426155102.0fb2dbc0.orbitz@ezabel.com> References: <408D667D.4020205@monkeez.org> <20040426155102.0fb2dbc0.orbitz@ezabel.com> Message-ID: <408D78AA.2000109@monkeez.org> orbitz@ezabel.com wrote: > Sounds like you might have 2 version of python on your system. Check for > multiple python binaries. also try running your script with: python > autoguess.py and see what happens. > > > On Mon, 26 Apr 2004 20:43:57 +0100 > Adam wrote: > > >>I use a linux machine and win machine at work. My win machine has no >>problem importing random and then using the randint(x,y) module. >>However, when I try and do this on my linux debian machine, I get: >> >>adam@debian:~/python$ ./autoguess.py >>Traceback (most recent call last): >> File "./autoguess.py", line 49, in ? >> generatenumber() >> File "./autoguess.py", line 6, in generatenumber >> target = random.randint(0,100) >>AttributeError: 'module' object has no attribute 'randint' >> >>from the code: >>import random >> >>def generatenumber(): >> target = random.randint(0,100) >> >>What is going on here? I've tried the same small piece of code : >>import random >>target = random.randing(0,100) at the interpreter and it works, but if I >>try this as an application in a file, it fails. >> >>Any ideas ? >> >>adam >> A 'which python' shows just one version in /usr/bin. Running the command 'python autoguess.py' gives the same error. I'm still puzzled. Adam From kalle at lysator.liu.se Mon Apr 26 17:13:58 2004 From: kalle at lysator.liu.se (Kalle Svensson) Date: Mon Apr 26 17:13:34 2004 Subject: [Tutor] Problems importing random on linux In-Reply-To: <408D78AA.2000109@monkeez.org> References: <408D667D.4020205@monkeez.org> <20040426155102.0fb2dbc0.orbitz@ezabel.com> <408D78AA.2000109@monkeez.org> Message-ID: <20040426211358.GG1038@i92.ryd.student.liu.se> [Adam] > I use a linux machine and win machine at work. My win machine > has no problem importing random and then using the randint(x,y) > module. However, when I try and do this on my linux debian > machine, I get: > > adam@debian:~/python$ ./autoguess.py > Traceback (most recent call last): > File "./autoguess.py", line 49, in ? > generatenumber() > File "./autoguess.py", line 6, in generatenumber > target = random.randint(0,100) > AttributeError: 'module' object has no attribute 'randint' > > from the code: > import random > > def generatenumber(): > target = random.randint(0,100) > > What is going on here? I've tried the same small piece of code: > import random > target = random.randing(0,100) > at the interpreter and it works, but if I try this as an > application in a file, it fails. > > Any ideas ? Do you perhaps have a file named random.py in the same directory as autoguess.py? To me, it sounds like the random module imported is different from the standard library module. Peace, Kalle -- Kalle Svensson, http://www.juckapan.org/~kalle/ Student, root and saint in the Church of Emacs. From adam at monkeez.org Tue Apr 27 02:21:53 2004 From: adam at monkeez.org (adam@monkeez.org) Date: Tue Apr 27 02:21:58 2004 Subject: [Tutor] Problems importing random on linux In-Reply-To: <20040426211358.GG1038@i92.ryd.student.liu.se> References: <408D667D.4020205@monkeez.org><20040426155102.0fb2dbc0.orbitz@ezabel.com><408D78AA.2000109@monkeez.org> <20040426211358.GG1038@i92.ryd.student.liu.se> Message-ID: <19029.81.168.52.182.1083046913.spork@webmail.monkeez.org> > [Adam] >> I use a linux machine and win machine at work. My win machine >> has no problem importing random and then using the randint(x,y) >> module. However, when I try and do this on my linux debian >> machine, I get: >> >> adam@debian:~/python$ ./autoguess.py >> Traceback (most recent call last): >> File "./autoguess.py", line 49, in ? >> generatenumber() >> File "./autoguess.py", line 6, in generatenumber >> target = random.randint(0,100) >> AttributeError: 'module' object has no attribute 'randint' >> >> from the code: >> import random >> >> def generatenumber(): >> target = random.randint(0,100) >> >> What is going on here? I've tried the same small piece of code: >> import random >> target = random.randing(0,100) >> at the interpreter and it works, but if I try this as an >> application in a file, it fails. >> >> Any ideas ? > > Do you perhaps have a file named random.py in the same directory as > autoguess.py? To me, it sounds like the random module imported is > different from the standard library module. > > Peace, > Kalle > -- Thanks Kalle - that was exactly it - I've also removed the .pyc files and it works fine now. That's one mistake I'll try to avoid again. Thanks once again. adam From magnus at thinkware.se Tue Apr 27 06:03:50 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Tue Apr 27 06:04:04 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gUHJvYmxlbXMgaW1wb3J0aW5nIHJhbmRvbSBvbiBsaW51eA==?= Message-ID: adam@monkeez.org wrote: > Thanks Kalle - that was exactly it - I've also removed the .pyc files and > it works fine now. That's one mistake I'll try to avoid again. You're certainly not the first one to import something else than the file you expected... If an imported module doesn't behave as expected, it's easy to verify that it's the module you think it is... >>> import random >>> print random See? It tells you what file you imported. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From thorsten at thorstenkampe.de Tue Apr 27 07:15:29 2004 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Tue Apr 27 07:15:44 2004 Subject: [Tutor] Re: recursion and power sets References: <200403071130.25672.RobinHood42@clickta.com> Message-ID: <5i10zpymtykz$.dlg@thorstenkampe.de> * alice (2004-03-07 06:30 +0100) > I was trying to write a function that would take a set - represented as a list > with non repeating elements - and return the power set, so given: > > [1,2,3] > > it should return: > > [[],[1],[2],[3],[1,2],[1,3],[2,3],[1,2,3]] > > After much general confusion, this is what I eventually came up with: > > def foo(pool,head,result,n): > """ pool, head and result should be lists, n a positive integer """ > if (n == 0): > while (pool != []): > head.append(pool.pop()) > result.append(head[:]) > head.pop() > else: > while (pool != []): > head.append(pool.pop()) > foo(pool[:],head,result,n-1) > head.pop() > > def power(set): > head = [] > result = [[]] > for i in range(len(set)): > foo(set[:],head,result,i) > return result > > This gives the subsets in a simmilar order to the one in which I would find > them if I was doing it by hand, but its kind of difficult to think about, so > I thought about it a bit more and came up with: > > def power(set): > result = [] > bits = len(set) > for string in range(2**bits): > subset = [] > position = 0 > while (string > 0): > if (string % 2 != 0): > subset.append(set[position]) > string /= 2 > position += 1 > result.append(subset) > return result > > Even though this algorithm gives the subsets in a completely different order > to the way I'd normally find them by hand, I'm guessing its closer to the > "canonical" algorithm for finding power sets than my recursive attempt, am I > right? or is there a third, completely different way of doing this? Catching up... def powerset(seq): if len(seq): head = powerset(seq[:-1]) return head + [item + [seq[-1]] for item in head] else: return [[]] Do not mix the sorting task with the plain "powersetting"! If you want to have the powerset sorted like you prefer, you should use a multipurpose "function sort": first by value and then by length. The standard Python sort() already sort sequences by value. def funcsort(seq, func): """ sort seq by func(item) """ seq = seq[:] seq.sort(lambda x, y: cmp(func(x), func(y))) return seq With these two functions your task is trivial: >>> power_set = powerset([1, 2, 3]) # create the powerset >>> power_set.sort() # sort the powerset by value >>> funcsort(power_set, lambda x: len(x)) # sort the powerset by length Thorsten From python at dhumketu.cjb.net Tue Apr 27 11:13:14 2004 From: python at dhumketu.cjb.net (Shantanoo) Date: Tue Apr 27 11:14:15 2004 Subject: [Tutor] Re: Parallel port interface In-Reply-To: <811tl1-mk2.ln1@wintermute.g2ctech> References: <811tl1-mk2.ln1@wintermute.g2ctech> Message-ID: <20040427151314.GA759@dhumketu.homeunix.net> +++ Jorge Godoy [25-04-04 12:11 -0300]: | Hi! | | | We're doing a research project that involves controlling mini-windtrap | speeds and we're reading/writing data from the parallel port. | | What I've found so far on a fast Google search for "python parallel port" | showed me some stuff that I'd have to interface with Python through SWIG. | | If the program could be portable in Windows and Linux it would be a big | plus. We're thinking --- if it can't be written entirely in Python or with | modules that already have binaries for Windows --- in using a Linux only | approach (we, the programmers, use Linux only). | | | Any hints for modules I should take a look at? google for "pyparallel" Shantanoo From lbblair at adaptisinc.com Tue Apr 27 11:32:52 2004 From: lbblair at adaptisinc.com (Larry Blair) Date: Tue Apr 27 11:34:30 2004 Subject: [Tutor] convert to dict Message-ID: I have been doing Python for only about 2 weeks so sorry for the beginners question. I have looked in the archives, etc. and suspect I don't know enough python vocabulary to ask the correct questions. I am converting some Jython programs I inherited and I think there are built-ins to do this easier in Python. I have a string (below) that I want to convert to a dictionary. I think I can do it with a for loop and using split but just don't quite have the skills to manipulate the data. I am getting the data from a text properties file I read into the program. Thanks for any help Larry lb = ['TEMP01.DBF : 1024', 'TEMP02.DBF : 1024', 'TEMP03.DBF : 1024', 'TEMP04.DBF : 1024', 'TEMP05.DBF : 1024', 'TEMP06.DBF : 1024'] __________________________________ Confidentiality Notice: This e-mail message, including any attachments, is for the sole use of the intended recipient(s) and may contain information that is confidential privileged and/or exempt from disclosure under applicable law. Any unauthorized review, use, disclosure or distribution is prohibited. If you are not the intended recipient, please contact the sender by reply e-mail and destroy all copies of the original message. Thank you. From adam at monkeez.org Tue Apr 27 09:21:57 2004 From: adam at monkeez.org (Adam) Date: Tue Apr 27 11:53:19 2004 Subject: [Tutor] Generating random in a user specified range. Message-ID: <408E5E75.1020707@monkeez.org> I'm trying to develop an app where the user can specify the range in which a random number will be generated from. So far, I have two functions; range collects the range in which the random number is to be generated from and generate number is the one which creates the number. Range produces a list, which holds the top and bottom number which is returned and then is passed to generatenumber to create a number. However, I seem to have a problem - I get an error using random.randint(a,b) and with random.randrange(a,b). It seems that it might be fussy accepting parts of a list as the argument. I've tried converting them to integers and then passing the interger, but it still complains. Any advice on what I can do to fix this? Thanks. The driving code is: range = range() print range raw_input("click ok to carry ok") target = generatenumber(range) #kicks the whole thing off def range(): strtop = raw_input("What is your top number?") strbottom = raw_input("What is your bottom number?") top = int(strtop) bottom = int(strbottom) range = [bottom, top] print "range top is ", range[0] print "range bottom is ", range[1] return range def generatenumber(range): top = int (range[0]) bottom = int (range[1]) target = random.randrange(range[1], range[0]) # and I've also tried (bottom,top) print "Target is ", target ok = raw_input("please press enter to continue") return target From Chad.Crabtree at nationalcity.com Tue Apr 27 11:59:10 2004 From: Chad.Crabtree at nationalcity.com (Crabtree, Chad) Date: Tue Apr 27 11:59:22 2004 Subject: [Tutor] convert to dict Message-ID: <66F587DFDD46D511B65200508B6F8DD612B9940D@nt-kalopsapp07.ntl-city.com> I know there is a more spiffy way to do this but I can never remember them this is how I would do it. IDLE 1.0.2 >>> lb = ['TEMP01.DBF : 1024', 'TEMP02.DBF : 1024', 'TEMP03.DBF : 1024', 'TEMP04.DBF : 1024', 'TEMP05.DBF : 1024', 'TEMP06.DBF : 1024'] >>> def makeDict(adict): result={} for x in adict: key,value=x.split(':') result[key]=value return result >>> makeDict(lb) {'TEMP02.DBF ': ' 1024', 'TEMP01.DBF ': ' 1024', 'TEMP06.DBF ': ' 1024', 'TEMP05.DBF ': ' 1024', 'TEMP04.DBF ': ' 1024', 'TEMP03.DBF ': ' 1024'} >>> If you need the values to be integers just int() them. > -----Original Message----- > From: Larry Blair [mailto:lbblair@adaptisinc.com] > Sent: Tuesday, April 27, 2004 11:33 AM > To: tutor@python.org > Subject: [Tutor] convert to dict > > > I have been doing Python for only about 2 weeks so sorry for > the beginners > question. I have looked in the archives, etc. and suspect I don't know > enough python vocabulary to ask the correct questions. I am > converting some > Jython programs I inherited and I think there are built-ins to do this > easier in Python. > > I have a string (below) that I want to convert to a > dictionary. I think I > can do it with a for loop and using split but just don't > quite have the > skills to manipulate the data. I am getting the data from a > text properties > file I read into the program. > > Thanks for any help > Larry > > > lb = ['TEMP01.DBF : 1024', 'TEMP02.DBF : 1024', 'TEMP03.DBF : 1024', > 'TEMP04.DBF : 1024', 'TEMP05.DBF : 1024', 'TEMP06.DBF : 1024'] > > > > > > > > __________________________________ > Confidentiality Notice: This e-mail message, including any > attachments, is > for the sole use of the intended recipient(s) and may contain > information > that is confidential privileged and/or exempt from disclosure under > applicable law. Any unauthorized review, use, disclosure or > distribution is > prohibited. If you are not the intended recipient, please contact the > sender by reply e-mail and destroy all copies of the original message. > Thank you. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ------------------------------------------------------------------------------------------- ***National City made the following annotations ------------------------------------------------------------------------------------------- This communication is a confidential and proprietary business communication. It is intended solely for the use of the designated recipient(s). If this communication is received in error, please contact the sender and delete this communication. =========================================================================================== From Chad.Crabtree at nationalcity.com Tue Apr 27 12:16:24 2004 From: Chad.Crabtree at nationalcity.com (Crabtree, Chad) Date: Tue Apr 27 12:16:46 2004 Subject: [Tutor] Generating random in a user specified range. Message-ID: <66F587DFDD46D511B65200508B6F8DD612B9940E@nt-kalopsapp07.ntl-city.com> > > However, I seem to have a problem - I get an error using > random.randint(a,b) and with random.randrange(a,b). It seems that it > might be fussy accepting parts of a list as the argument. I've tried > converting them to integers and then passing the interger, > but it still > complains. > > Any advice on what I can do to fix this? > Thanks. > > The driving code is: > > range = range() > print range > raw_input("click ok to carry ok") > target = generatenumber(range) #kicks the whole thing off You will hear this several times range is a built in function when you assign to it you erase this function. This in practice is a bad thing. > > def range(): > strtop = raw_input("What is your top number?") > strbottom = raw_input("What is your bottom number?") > top = int(strtop) > bottom = int(strbottom) > range = [bottom, top] > print "range top is ", range[0] > print "range bottom is ", range[1] > return range you need to strip the stuff from this. I would do it thus. import string bottom=int(string.strip(strbottom)) top=int(string.strip(strtop)) this gets ride of any string whitespace strangeness that canot be converted to an integer. > def generatenumber(range): > top = int (range[0]) > bottom = int (range[1]) > target = random.randrange(range[1], range[0]) # and I've > also tried > (bottom,top) > print "Target is ", target > ok = raw_input("please press enter to continue") > return target > with random.randrange(x,y) x must be smaller than y if not range will act funny. >>> random.choice(range(10,1)) Traceback (most recent call last): File "", line 1, in -toplevel- random.choice(range(10,1)) File "c:\python\lib\random.py", line 231, in choice return seq[int(self.random() * len(seq))] IndexError: list index out of range >>> range(10,1) [] >>> range(10,1,-1) [10, 9, 8, 7, 6, 5, 4, 3, 2] >>> range(1,10) [1, 2, 3, 4, 5, 6, 7, 8, 9] The decending example you need to put the step in there or else it won't work as above. Please rename all you range things except for in your strings. I know that those are meaningful variable names but it will cause you problems in the future. Check out this tutorial. It has all the basics in it. lists,dicts,range,strings and other stuff. http://docs.python.org/tut/tut.html ------------------------------------------------------------------------------------------- ***National City made the following annotations ------------------------------------------------------------------------------------------- This communication is a confidential and proprietary business communication. It is intended solely for the use of the designated recipient(s). If this communication is received in error, please contact the sender and delete this communication. =========================================================================================== From dbroadwell at mindspring.com Tue Apr 27 12:17:56 2004 From: dbroadwell at mindspring.com (David Broadwell) Date: Tue Apr 27 12:18:32 2004 Subject: [Tutor] Generating random in a user specified range. In-Reply-To: <408E5E75.1020707@monkeez.org> Message-ID: > However, I seem to have a problem - I get an error using > random.randint(a,b) and with random.randrange(a,b). It seems that it > might be fussy accepting parts of a list as the argument. I've tried > converting them to integers and then passing the integer, but it still > complains. Can you post in those tracebacks? > Any advice on what I can do to fix this? well, let's look over the program; > range = range() >>> range = range() Traceback (most recent call last): File "", line 1, in ? range = range() TypeError: range() requires 1-3 int arguments I think you should be asking for a list here. try: range = [] instead. > print range > raw_input("click ok to carry ok") > target = generatenumber(range) #kicks the whole thing off > > def range(): > strtop = raw_input("What is your top number?") > strbottom = raw_input("What is your bottom number?") > top = int(strtop) > bottom = int(strbottom) > range = [bottom, top] > print "range top is ", range[0] > print "range bottom is ", range[1] > return range line by line ... > strtop = raw_input("What is your top number?") > strbottom = raw_input("What is your bottom number?") What you have above, is very readable, but can also be expressed as without really sacraficing readability; top = int(raw_input("What is your top number?")) bottom = int(raw_input("What is your bottom number?")) range = [bottom, top] You are trying to use your 'range = range()' as if it were a list range = [bottom, top] ... if you WANT a list, then ask for with a 'range = []' statement as shown above. print "range top is ", range[0] print "range bottom is ", range[1] return range and you are using range like a range ... so as a recomndation your variable being named 'range' is bad namespace ettiquitte. how about rangelist = [] instead? > def generatenumber(range): > top = int (range[0]) > bottom = int (range[1]) > target = random.randrange(range[1], range[0]) # and I've also tried (bottom,top) # and probably gotten bad results too, range isn;t really a list > print "Target is ", target > ok = raw_input("please press enter to continue") > return target -- Programmer's mantra; Observe, Brainstorm, Prototype, Repeat David Broadwell From sigurd at 12move.de Tue Apr 27 12:18:09 2004 From: sigurd at 12move.de (=?iso-8859-1?q?Karl_Pfl=E4sterer?=) Date: Tue Apr 27 12:19:01 2004 Subject: [Tutor] convert to dict In-Reply-To: (Larry Blair's message of "Tue, 27 Apr 2004 08:32:52 -0700") References: Message-ID: On 27 Apr 2004, Larry Blair <- lbblair@adaptisinc.com wrote: > I have a string (below) that I want to convert to a dictionary. I think I > can do it with a for loop and using split but just don't quite have the > skills to manipulate the data. I am getting the data from a text properties > file I read into the program. > lb = ['TEMP01.DBF : 1024', 'TEMP02.DBF : 1024', 'TEMP03.DBF : 1024', > 'TEMP04.DBF : 1024', 'TEMP05.DBF : 1024', 'TEMP06.DBF : 1024'] Using a for loop and splitting the data is one approach. dic = {} for kv in lb: key, val = kv.split(':') dic[key] = val You initialize an empty dictionary, iterate over the list and split the entries with split(':'). A bit shorter (but maybe less clear): dic = {} for kv in lb: dic.setdefault(* kv.split(':')) setdefault() sets dic[key] =value if key is not already in dic and returns value. The `*' splices the list in the argument list; that means it takes away the outermost pair of brackets of the list (or parens of a tuple). So f(* [a, b]) is the same as f(a, b). It's nice but if you just start to use Python you shouldn't maybe use it too often. If you like it even shorter you could use a list comprehension (but it uses more memory) dic = dict([kv.split(':') for kv in lb]) Here you build a list of lists; each of the inner lists has two entries where the first acts as key and the second as value in the dictionary. So pick your favorite. Karl -- Please do *not* send copies of replies to me. I read the list From nick at javacat.f2s.com Tue Apr 27 12:20:52 2004 From: nick at javacat.f2s.com (Nick Lunt) Date: Tue Apr 27 12:20:50 2004 Subject: [Tutor] Generating random in a user specified range. In-Reply-To: <408E5E75.1020707@monkeez.org> Message-ID: Hi Adam, im not sure of line 'range = range()' . That errors when I try it here at home. Are you aware that range() is a built in keyword ? Regards Nick. -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org]On Behalf Of Adam Sent: 27 April 2004 14:22 To: tutor@python.org Subject: [Tutor] Generating random in a user specified range. I'm trying to develop an app where the user can specify the range in which a random number will be generated from. So far, I have two functions; range collects the range in which the random number is to be generated from and generate number is the one which creates the number. Range produces a list, which holds the top and bottom number which is returned and then is passed to generatenumber to create a number. However, I seem to have a problem - I get an error using random.randint(a,b) and with random.randrange(a,b). It seems that it might be fussy accepting parts of a list as the argument. I've tried converting them to integers and then passing the interger, but it still complains. Any advice on what I can do to fix this? Thanks. The driving code is: range = range() print range raw_input("click ok to carry ok") target = generatenumber(range) #kicks the whole thing off def range(): strtop = raw_input("What is your top number?") strbottom = raw_input("What is your bottom number?") top = int(strtop) bottom = int(strbottom) range = [bottom, top] print "range top is ", range[0] print "range bottom is ", range[1] return range def generatenumber(range): top = int (range[0]) bottom = int (range[1]) target = random.randrange(range[1], range[0]) # and I've also tried (bottom,top) print "Target is ", target ok = raw_input("please press enter to continue") return target _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From magnus at thinkware.se Tue Apr 27 12:32:29 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Tue Apr 27 12:32:41 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gR2VuZXJhdGluZyByYW5kb20gaW4gYSB1c2VyIHNwZWNpZmllZCByYW5nZS4g?= Message-ID: Adam wrote: > However, I seem to have a problem - I get an error using > random.randint(a,b) and with random.randrange(a,b). It's *much* easier to help you if you tell us exactly the error messages you get. Can't you copy the traceback directly to the mail? Btw, used with two integers as arguments, random.randint(x,y) is exactly the same thing as random.randrange(x,y+1). You can expect them to behave fairly similarly from an error point of view, but note that your "top" value will never be returned from randrange(bottom, top). See below: >>> import random >>> random.randint(1,1) 1 >>> random.randrange(1,2) 1 >>> random.randrange(1,1) Traceback (most recent call last): File "", line 1, in -toplevel- random.randrange(1,1) File "D:\Python23\lib\random.py", line 171, in randrange raise ValueError, "empty range for randrange()" ValueError: empty range for randrange() > It seems that it > might be fussy accepting parts of a list as the argument. I've tried If "x = [5, 20]", then x[0] and x[1] are integers, not "parts of a list", so this isn't your problem. >>> x = [5, 20] >>> random.randint(x[0], x[1]) 15 >>> random.randrange(x[0], x[1]) 14 No problems! > converting them to integers and then passing the interger, but it still > complains. You *should* provide integers as parameters with random.randrange(). Never strings. Python is not a toy language that tries to guess what the programmer meant and corrects him silently when he made a mistake. In the long run, the Python tenet: "In the face of ambiguity, refuse the temptation to guess" is very helpful when we try to build robust applications. > range = range() I assume you have this *after* your function definition in your actual program, otherwise it will not call your not yet defined function, but rather to the standard built in Python function called range. E.g. Traceback (most recent call last): File "C:/TEMP/temp.py", line 1, in -toplevel- range = range() TypeError: range expected at least 1 arguments, got 0 > def range(): As I said, range is the name of a builtin function. It's not a good idea to hide builtin functions with user defined ones. If I take your code, add "import random" at the top, and move the initial lines to the end of the program, after the functions, it works as expected, with no errors. (Well, I guess you actually want randint rather than randrange as explained above.) -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From bvande at po-box.mcgill.ca Tue Apr 27 12:33:49 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Tue Apr 27 12:34:24 2004 Subject: [Tutor] [FYI] Good source of info on relative efficency of various string, list, etc. methods (and much more) Message-ID: <408E8B6D.6080507@po-box.mcgill.ca> Hi all, I have a recommendation for other's learning Python. Last week I posted a query essentially asking about the relative efficiency of several approaches to dealing with some data. (http://mail.python.org/pipermail/tutor/2004-April/029329.html) I received helpful advice, but I've since found a very handy presentation of these sorts of issues. The 15pp or so section on Optimization in Chapter 17 of Python in a Nutshell (http://www.oreilly.com/catalog/pythonian/) provides a very readable survey of the computational costs of a number of methods for processing Python objects. The math and computing theory involved is very low level (no NP-completeness or anything like that :-) ). While it quotes the Knuth nugget about premature optimization and evil, it provides what seems to me to be enough information to guide rational choice without so much detail as to make you likely to spend time chasing a 0.41% performance gain. Beyond the particular section mentioned, I recommend this text in the strongest terms. I'd worked through Learning Python and while great in that is is discursive, it is not too good as a "quick, how's that work again?" text. (No slight; that's not its job.) If, like me, you prefer a physical book to reading docs on the screen, Nutshell is a great text -- for a quick reference it is remarkably readable! (In the few days since amazon finally came through, several queries that might well have ended up as tutor posts were quickly resolved by the text.) Hope that helps some other newbies. Best to all, Brian vdB From magnus at thinkware.se Tue Apr 27 12:57:35 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Tue Apr 27 12:57:42 2004 Subject: =?ISO-8859-1?B?UmU6IFJFOiBbVHV0b3JdIEdlbmVyYXRpbmcgcmFuZG9tIGluIGEgdXNlciBzcGVjaWZpZWQgcmFuZ2Uu?= Message-ID: Chad Crabtree wrote: > you need to strip the stuff from this. I would do it thus. > import string > bottom=int(string.strip(strbottom)) > top=int(string.strip(strtop)) > > this gets ride of any string whitespace strangeness that canot be converted > to an integer. There is no need to do that: >>> 2 * int(' 45 \n') 90 Besides, the string module is more or less made redundant since several python versions back. Use " a string ".strip() instead of string.strip(" a string ") -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From askoose at sandia.gov Tue Apr 27 13:01:54 2004 From: askoose at sandia.gov (Kooser, Ara S) Date: Tue Apr 27 13:02:08 2004 Subject: [Tutor] Unix commands python Message-ID: <9A4B2157EFDBE546BECD68C62AC3B1C81738F113@es05snlnt.sandia.gov> Hello all, I am new at python and I am working on a file conversion program. Thank you for all the advice that got me to this point. Is it possible to invoke unix commands in python, such as awk or cut? I am trying to cut some columns of text and then transform one of those columns with user input. Thanks. Ara -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040427/3c00e4e9/attachment.html From Chad.Crabtree at nationalcity.com Tue Apr 27 13:02:57 2004 From: Chad.Crabtree at nationalcity.com (Crabtree, Chad) Date: Tue Apr 27 13:03:19 2004 Subject: FW: RE: [Tutor] Generating random in a user specified range. Message-ID: <66F587DFDD46D511B65200508B6F8DD612B99410@nt-kalopsapp07.ntl-city.com> -----Original Message----- From: Crabtree, Chad Sent: Tuesday, April 27, 2004 1:02 PM To: 'Magnus Lycka' Subject: RE: RE: [Tutor] Generating random in a user specified range. > Chad Crabtree wrote: > > you need to strip the stuff from this. I would do it thus. > > import string > > bottom=int(string.strip(strbottom)) > > top=int(string.strip(strtop)) > > > > this gets ride of any string whitespace strangeness that > canot be converted > > to an integer. > > There is no need to do that: > > >>> 2 * int(' 45 \n') > 90 > > Besides, the string module is more or less made redundant > since several > python versions back. Use " a string ".strip() instead of > string.strip(" a string ") > Thank you. I always have a hard time with remembering the string methods. I can only remember the string module. IN addition I've had more troulbe with the class methods than with the module. I however cannot think of a specific example. IIRC it was with split not doing what I wanted it to. Interestingly "".srtip() returns a new string instead of inplaceing the change. Is this because strings are immutable? I'm thinking of lists [].sort() method being inplace but lists are happily very mutable. ------------------------------------------------------------------------------------------- ***National City made the following annotations ------------------------------------------------------------------------------------------- This communication is a confidential and proprietary business communication. It is intended solely for the use of the designated recipient(s). If this communication is received in error, please contact the sender and delete this communication. =========================================================================================== From Andy at joslin.isa-geek.com Tue Apr 27 13:04:01 2004 From: Andy at joslin.isa-geek.com (Andy Joslin) Date: Tue Apr 27 13:04:17 2004 Subject: [Tutor] Generating random in a user specified range. In-Reply-To: <408E5E75.1020707@monkeez.org> References: <408E5E75.1020707@monkeez.org> Message-ID: <408E9281.7060507@joslin.isa-geek.com> Adam wrote: > I'm trying to develop an app where the user can specify the range in > which a random number will be generated from. > > [..snip..] > > The driving code is: > You need to define your functions before you call them... try moving these four lines after the functions are defined... > range = range() > print range > raw_input("click ok to carry ok") > target = generatenumber(range) #kicks the whole thing off > > def range(): > strtop = raw_input("What is your top number?") > strbottom = raw_input("What is your bottom number?") Your interface is confusing... I would expect to enter the lower number first. Since all the data should be represented as a valid range: (x, y) where x top = int(strtop) > bottom = int(strbottom) > range = [bottom, top] > print "range top is ", range[0] > print "range bottom is ", range[1] > return range > > def generatenumber(range): > top = int (range[0]) > bottom = int (range[1]) > target = random.randrange(range[1], range[0]) # and I've also tried Keep in mind that your top number will NEVER be selected... you may want to add 1 to the top number if you want it to be a valid number > (bottom,top) > print "Target is ", target > ok = raw_input("please press enter to continue") > return target > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor I got the following code to work without issue... (It is essentially your code, but compressed a bit) --------------------------------------------------- #!/usr/bin/python import random import string from string import strip def promptRange(): return [int(strip(raw_input("What is your bottom number? "))), \ int(strip(raw_input("What is your top number? ")))] ref generatenumber(range): return random.randrange(range[0], range[1] + 1) target = generatenumber(promptRange()) #kicks the whole thing off print "Target is ", target -- [Imagine a witty sig here] From denis.spir at free.fr Tue Apr 27 13:03:59 2004 From: denis.spir at free.fr (denis) Date: Tue Apr 27 13:05:18 2004 Subject: [Tutor] Generating random in a user specified range. References: Message-ID: <005801c42c79$b730a520$fa41933e@spir> ----- Original Message ----- From: David Broadwell To: Sent: Tuesday, April 27, 2004 6:17 PM Subject: RE: [Tutor] Generating random in a user specified range. > well, let's look over the program; > > > range = range() > >>> range = range() > Traceback (most recent call last): > File "", line 1, in ? > range = range() > TypeError: range() requires 1-3 int arguments > > I think you should be asking for a list here. > try: > range = [] instead. > > > print range > > raw_input("click ok to carry ok") > > target = generatenumber(range) #kicks the whole thing off > > > > def range(): > > strtop = raw_input("What is your top number?") > > strbottom = raw_input("What is your bottom number?") > > top = int(strtop) > > bottom = int(strbottom) > > range = [bottom, top] > > print "range top is ", range[0] > > print "range bottom is ", range[1] > > return range > You are trying to use your 'range = range()' as if it were a list range = > [bottom, top] ... if you WANT a list, then ask for with a 'range = []' > statement as shown above. > > print "range top is ", range[0] > print "range bottom is ", range[1] > return range > > and you are using range like a range ... so as a recomndation your variable > being named 'range' is bad namespace ettiquitte. how about rangelist = [] > instead? Well, It seems you confuse things, Adam, in fact notation and content of a variable. Python has a built-in function called range() which generates a full sequence of integers : >>> range(5,8) [5, 6, 7] Now if we iterate on it, we'll loop for 5 and 6 and 7 : >>> for n in range (5,8) : print '*%i*' %n *5* *6* *7* Let's do the same with a 'custom' range like yours, that I will temporarily call R : R = [5,8] >>> for i in R : print '*%i*' %i *5* *8* R is a raw list of two values, holding what we interpret as range border. That's good reason to call it e.g. RangeBorders. > > top = int(strtop) > > bottom = int(strbottom) > > range = [bottom, top] # indexes are : 0 <-> bottom , 1 <-> top > > print "range top is ", range[0] > > print "range bottom is ", range[1] Here, your print statements swap bottom (first --> index 0) and top (second --> index 1). You do the same mistake in the generatenumber function : > > def generatenumber(range): > > top = int (range[0]) > > bottom = int (range[1]) > > target = random.randrange(range[1], range[0]) It shouldn't work, it doesn't. (As Alan writes : 'hope it help') denis From askoose at sandia.gov Tue Apr 27 13:30:47 2004 From: askoose at sandia.gov (Kooser, Ara S) Date: Tue Apr 27 13:31:07 2004 Subject: [Tutor] Unix commands python Message-ID: <9A4B2157EFDBE546BECD68C62AC3B1C81738F116@es05snlnt.sandia.gov> Thank you very much. I will try that out. Ara -----Original Message----- From: Andrew Fant [mailto:andrew.fant@tufts.edu] Sent: Tuesday, April 27, 2004 11:29 AM To: 'tutor@python.org' Cc: Kooser, Ara S Subject: Re: [Tutor] Unix commands python Ara, It is possible to use unix commands from within python, but I would suggest that you would get further in this case by using the split method in the strings module. If you are reading lines from a file into a string called 'foo', you can write something like: splitfoo=foo.split() and then reference each column as splitfoo[x] where x is some number between zero and the number of fields. I've been doing the same sort of thing for parsing performance data to pass into our web-graphing software, and it's much faster to chop it up in python than to spawn child processes to do it in awk. HTH Andy --On Tuesday, April 27, 2004 11:01:54 -0600 "Kooser, Ara S" wrote: > > Hello all, > > I am new at python and I am working on a file conversion program. > Thank you for all the advice that got me to this point. Is it possible > to invoke unix commands in python, such as awk or cut? I am trying to > cut some columns of text and then transform one of those columns with > user input. Thanks. > > Ara From sigurd at 12move.de Tue Apr 27 13:42:39 2004 From: sigurd at 12move.de (=?iso-8859-1?q?Karl_Pfl=E4sterer?=) Date: Tue Apr 27 13:46:46 2004 Subject: [Tutor] Unix commands python In-Reply-To: <9A4B2157EFDBE546BECD68C62AC3B1C81738F113@es05snlnt.sandia.gov> (Ara S. Kooser's message of "Tue, 27 Apr 2004 11:01:54 -0600") References: <9A4B2157EFDBE546BECD68C62AC3B1C81738F113@es05snlnt.sandia.gov> Message-ID: On 27 Apr 2004, Kooser, Ara S <- askoose@sandia.gov wrote: > I am new at python and I am working on a file conversion program. Thank > you for all the advice that got me to this point. Is it possible to invoke > unix commands in python, such as awk or cut? I am trying to cut some columns > of text and then transform one of those columns with user input. Thanks. Yes it's possible. Look for os.popen, os.popen2, os.popen3, os.popen4 E.g to view only the first column of a ls -l (a silly example): >>> ls = os.popen('ls -l|cut -d " " -f 1') >>> for line in ls: ... sys.stdout.write(line) ... total -rw-r--r-- >>> os.popen() returns the output from the command as file object; reading is the default mode but you can also open it for writing (if it makes sense) the same way you do it with files. Perhaps the best is you look it up in the library documentation. Karl -- Please do *not* send copies of replies to me. I read the list From magnus at thinkware.se Tue Apr 27 13:52:48 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Tue Apr 27 13:52:56 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gVW5peCBjb21tYW5kcyBweXRob24=?= Message-ID: Kooser, Ara S wrote: > I am new at python and I am working on a file conversion program. Thank > you for all the advice that got me to this point. Is it possible to invoke > unix commands in python, such as awk or cut? Sure, but since it's easy to do things purely in Python, you will notice that Python programmers try to avoid "mixing metaphors" and losing portability. If you need to do this, you can use os.popen and friends, or possibly the wrappers in the commands module. See http://docs.python.org/lib/os-newstreams.html#os-newstreams > I am trying to cut some columns > of text and then transform one of those columns with user input. This sounds like something which is easy to do in Python. Here is an example of both some Python string handling and cooperation with the OS under Windows (What I'm doing is roughly "ls -l ~/tmp" in Unix): >>> import os >>> listing = os.popen("DIR H:\\tmp").readlines() os.popen(X) executes X, and behaves like a Unix pipe. You can read the pipe just as a file. Here I read it with readlines to get a list containing a line each. >>> for row in listing: print row.rstrip().decode('cp850') Volymen i enhet H har etiketten Home Volymens serienummer ?r 5011-6C98 Inneh?ll i katalogen H:\tmp 04-03-02 13:45 . 04-03-02 13:45 .. 03-12-11 13:55 GRU_R1C12 04-03-02 14:01 53 pnr.txt 03-12-11 18:21 POS_20031211 03-12-11 11:07 PRM_R1C07 03-12-11 18:10 PRM_R1C08 7 fil(er) 53 byte 6?830?682?112 byte ledigt Since the lines read from readlines() retain their newline characters in the end, I strip them away with .rstrip(). Otherwise I'd get empty lines, since the print statement adds newlines on its own. I also decode the text I read using code page 850, since these old DOS commands in Windows behave in an ancient way. (Not an issue for people using only US ascii...) By the way, you might notice that the interesting lines are the ones that have some text in the first column. In this case, it's always '0' in the first column, but we don't want to count on that. (The program might be used in six years from now...) it Swedish for . Let's print the names of the directories. If we split each line (on whitespace) we can simply print the last element (indexed -1 for convenience) of each line that contains '': >>> for row in listing: if '' in row: print row.split()[-1] # print directory names . . GRU_R1C12 POS_20031211 PRM_R1C07 PRM_R1C08 Maybe we want to find all the dates and times in the directory listing? >>> for row in listing: if row.strip() and row[0] != ' ': # Line is not empty and doesn't start with space print row.split()[:2] # print first two columns, dates and times ['04-03-02', '13:45'] ['04-03-02', '13:45'] ['03-12-11', '13:55'] ['04-03-02', '14:01'] ['03-12-11', '18:21'] ['03-12-11', '11:07'] ['03-12-11', '18:10'] Perhaps we want to know how old the items in the catalog are? >>> import datetime >>> now = datetime.datetime.now() >>> for row in listing: if row.strip() and row[0] != ' ': mdate, mtime = row.split()[:2] yy,mm,dd = mdate.split('-') hour, minute = mtime.split(':') timestamp = datetime.datetime(2000+int(yy),int(mm),int(dd),int(hour), int(minute), 0) name = row.split()[-1] print name, 'is', (now-timestamp).days, 'days old' is 56 days old . is 56 days old GRU_R1C12 is 138 days old pnr.txt is 56 days old POS_20031211 is 138 days old PRM_R1C07 is 138 days old PRM_R1C08 is 138 days old Or, if you want to work with the character positions on the line, and not use split. (row.split()[-1] fails if there is whitespace in the file name): >>> for row in listing: if row.strip() and row[0] != ' ': print row[39:], # This time I suppress the newline added by print . . GRU_R1C12 pnr.txt POS_20031211 PRM_R1C07 PRM_R1C08 -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From python at dhumketu.cjb.net Tue Apr 27 11:13:14 2004 From: python at dhumketu.cjb.net (Shantanoo) Date: Tue Apr 27 17:00:26 2004 Subject: [Tutor] Re: Parallel port interface Message-ID: <20040427151314.GA759@dhumketu.homeunix.net> +++ Jorge Godoy [25-04-04 12:11 -0300]: | Hi! | | | We're doing a research project that involves controlling mini-windtrap | speeds and we're reading/writing data from the parallel port. | | What I've found so far on a fast Google search for "python parallel port" | showed me some stuff that I'd have to interface with Python through SWIG. | | If the program could be portable in Windows and Linux it would be a big | plus. We're thinking --- if it can't be written entirely in Python or with | modules that already have binaries for Windows --- in using a Linux only | approach (we, the programmers, use Linux only). | | | Any hints for modules I should take a look at? google for "pyparallel" Shantanoo _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From glingl at aon.at Tue Apr 27 18:11:14 2004 From: glingl at aon.at (Gregor Lingl) Date: Tue Apr 27 18:11:29 2004 Subject: [Tutor] EuroPython Conference in June? In-Reply-To: References: Message-ID: <408EDA82.6060206@aon.at> Magnus Lycka schrieb: >Hi! > >I just thought I'd inform/remind people on the tutor list about >the Europython Conference June 7-9. This year it takes place in >G?teborg, Sweden, and it's a really good time to learn more >about Python and to meet other Python programmers. > > > Hi Magnus! Thanks for the reminder! A few weeks ago I thought about going there, because it am really interested to meet all those guys I know anly electronically until now. However there are some (minor) obstacles there for me, as for instance that the conference takes place during the school year and it is not so easy to get free days. There is also no sponsor or financial supporter, so it will become a rather expensive adventure. I certainly would have mastered those obstacles if there had been some real chance for a well attended "education track". (That's what I'm interested in, as a teacher and as author of "Python f?r Kids"). Alas, there seems to be a strong resistance among the "educational Pythonistas" in Europe to organize themselves, to meet each other or even to communicate. (For instance there seem to participate no teachers at all in the German Python-mailing-lit) So until now there is not a single accepted talk for this track and I expect that it will be cancelled as it happened last year. That's the reason I won't go there. I find this a very bad situation and I not only would like to attend the conference next year but I also would try to contribute to the education track if there were chances to meet some people with similar interests. In order that this can happen, it would be necessary - I think - to have some planning/contacting activities concerning this track already in winter. Perhaps you could listen around a bit there at G?teborg, if there are people interested in educational topics, and if there are comments/statements in the community about the role of Python in the educational sector. I'm sure, you will give a short report about the conference somewhere in the net. (Didn't you so last year?) So perhaps - in thi scontext - you can give a few comments about this topic. Regards, Gregor > > > From magnus at thinkware.se Tue Apr 27 19:21:05 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Tue Apr 27 19:21:14 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gRXVyb1B5dGhvbiBDb25mZXJlbmNlIGluIEp1bmU/?= Message-ID: Gregor Lingl wrote: > I certainly would have mastered those obstacles if there had > been some real chance for a well attended "education track". (That's > what I'm interested in, as a teacher and as author of "Python f?r Kids"). I don't expect to see a huge gathering of teachers... I know that Anna Ravenscroft and Steve Alexander have shown interest in educational issues, and there were four education-related talks at PyCon in Washinton, but I don't know if any of the PyCon speakers are coming here. "Well attended" would probably be stretching it... Actually, if you look through the europython mailing list archives, you will even see the odd austrian (Jodok Batlogg) involved in the Education track. And, both keynote speakers, Guido van Rossum and Mark Shuttleworth, have shown significant interest in the use of Python in education. > So until now there is not a single accepted talk for this track and I > expect that it will be cancelled as it happened last year. You could make a difference if you submitted a talk... ;) There are several talks submitted, but a most of them are about using Python or Zope for administration in the educational system, rather than about the concept of using Python as an educational tool, so I guess you are right, in a way, although I think people involved in developing software for the educational system do have some interests in common with the Python educators as well. > That's the reason I won't go there. I find this a very bad situation > and I not only would like to attend the conference next year but I also > would try to contribute to the education track if there were chances to > meet some people with similar interests. A typical chicken and egg problem it seems. I wonder if there are many people out there thinking like you, but anyway, I hope to see you among the speakers next year then. (It's also an opportunity to sell some books!) > In order that this can happen, it would be necessary - I think - to have > some planning/contacting activities concerning this track already in winter. Yep. There is an ongoing discussion on these things in the europython mailing list, but you might need to > Perhaps you could listen around a bit there at G?teborg, if there are people > interested in educational topics, and if there are comments/statements > in the community about the role of Python in the educational sector. As I said, Anna *is* interested, not mainly in academic Python education as far as I know, but in teaching Python as trainer/menter. So am I. Steve has mainly been involved in developing Python/Zope tools for educational institutions as far as I know. There are also a few companies that do commercial Python training (such as Logilab) who comes to EPC. There were also people looking for trainers at EPC 2003. I was approached by a representative of a large corporation who wanted me to do Python training for their employees, but unfortunately, this collided with another assignment for me, so I couldn't do it. I can see that both you, Anna and Laura Creighton (who is one of the main EPC organizers) are active on the edu-sig mailing list. Haven't there been any discussions about EPC there? Even if it doesn't happen very rapidly, it seems that Python is getting used more and more in education (just as elsewhere). I imagine it could well be possible to reach a critical mass for Python educators in Europe, and to get a substancial meeting at EPC 2005 if not this year. I imagine it might be a good idea to join forces between educations in the academical sphere and trainers in the private sector though. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From arkamir at softhome.net Tue Apr 27 20:22:29 2004 From: arkamir at softhome.net (Conrad) Date: Tue Apr 27 20:22:48 2004 Subject: [Tutor] matrixes Message-ID: <1083023450.2094.21.camel@conradpc> Hello, I have to recreate a text-based game 'visually' for school and I was hoping you could help me with things I've run into. One of the first things I've run into is how to deal with matrixes in python. If I have the following matrix with 'glade' being location (0,0): forest river desert woods creak dunes glade stream mountains I was thinking of representing like this: matrix = (('glade', 'stream', 'mountains'),('woods', 'creak', 'dunes'), ('forest', 'river', 'desert')) Is this the correct way and 'pythonic' way of doing it, or am I missing a module or something. The starting location would be glade, and I would represent that in the location variable: location = [0, 0] and then north would be: north = [0, 1] and then if the input would be north. I would do something like this: location = [location[0] + north[0], location[1] + location[1]] The problem is if you went south for your first 'move' how would i make it wrap and end up at forest? This seems like a real roundabout way of doing things, is there a better/faster way of doing this? As for my visual part, I was thinking of having a command line prompt to take input and a seperate window which shows a picture depending on which place you would be. This picture would have to dynamically change and pretty rapidly. I'll do a little research before asking about it. Thanks a lot!! Conrad P.S. The teachers want me to make this in Flash or html, or any tools found in our computer labs. But I think python would be appropriate for the job. *grin* I'm not sure I could use pygame because im either going to have to boot knoppix to demonstrate the game or find a small python distrobution that can go on the labs, without adminstrative priveleges since they only use windows. I relize this is homework but I do not think the questions detract from the assignment. From carroll at tjc.com Wed Apr 28 02:28:48 2004 From: carroll at tjc.com (Terry Carroll) Date: Wed Apr 28 02:28:57 2004 Subject: [Tutor] [FYI] Good source of info on relative efficency of various string, list, etc. methods (and much more) In-Reply-To: <408E8B6D.6080507@po-box.mcgill.ca> Message-ID: On Tue, 27 Apr 2004, Brian van den Broek wrote: > Beyond the particular section mentioned, I recommend [Python in a > Nutshell] strongest terms. Second. This book rocks. Since I got my copy, I rarely refer to any other book. Terry Carroll Santa Clara, CA carroll@tjc.com Modell delendus est From pythontut at pusspaws.net Wed Apr 28 04:48:59 2004 From: pythontut at pusspaws.net (Dave S) Date: Wed Apr 28 04:49:15 2004 Subject: [Tutor] exception question Message-ID: <408F6FFB.80308@pusspaws.net> Is it possible, for the code after except to know the exception type. I know I can do multiple "except"s for each condition but this is not realy what I want. try: .... ...code... .... except: ...code .... Cheers Dave From pythontut at pusspaws.net Wed Apr 28 06:09:24 2004 From: pythontut at pusspaws.net (Dave S) Date: Wed Apr 28 06:09:34 2004 Subject: [Tutor] makeing '1' into a '01' neatly ? Message-ID: <408F82D4.2080609@pusspaws.net> I need strings of the form 01, 02, 03 ... ,10,11,12 ... for archiving files. Is there an neat way to format a '1' into a '01' ? I felt sure string methods or string formatting would help, but alas no. I could add an if statement to add a 0 but this seems awkward & I am sure there is a better way. Any ideas Dave From kalle at lysator.liu.se Wed Apr 28 06:17:20 2004 From: kalle at lysator.liu.se (Kalle Svensson) Date: Wed Apr 28 06:16:43 2004 Subject: [Tutor] makeing '1' into a '01' neatly ? In-Reply-To: <408F82D4.2080609@pusspaws.net> References: <408F82D4.2080609@pusspaws.net> Message-ID: <20040428101720.GJ1038@i92.ryd.student.liu.se> [Dave S] > I need strings of the form 01, 02, 03 ... ,10,11,12 ... for > archiving files. > > Is there an neat way to format a '1' into a '01' ? >>> for x in '1', '3', '30': ... print '%02d' % int(x) ... 01 03 30 Peace, Kalle -- Kalle Svensson, http://www.juckapan.org/~kalle/ Student, root and saint in the Church of Emacs. From pythontut at pusspaws.net Wed Apr 28 06:44:43 2004 From: pythontut at pusspaws.net (Dave S) Date: Wed Apr 28 06:44:54 2004 Subject: [Tutor] makeing '1' into a '01' neatly ? In-Reply-To: <20040428101720.GJ1038@i92.ryd.student.liu.se> References: <408F82D4.2080609@pusspaws.net> <20040428101720.GJ1038@i92.ryd.student.liu.se> Message-ID: <408F8B1B.2080501@pusspaws.net> Kalle Svensson wrote: >[Dave S] > > >>I need strings of the form 01, 02, 03 ... ,10,11,12 ... for >>archiving files. >> >>Is there an neat way to format a '1' into a '01' ? >> >> > > > >>>>for x in '1', '3', '30': >>>> >>>> >... print '%02d' % int(x) >... >01 >03 >30 > >Peace, > Kalle > > Cheers :-) Dave From klappnase at freenet.de Wed Apr 28 06:52:49 2004 From: klappnase at freenet.de (Michael Lange) Date: Wed Apr 28 06:51:35 2004 Subject: [Tutor] makeing '1' into a '01' neatly ? In-Reply-To: <20040428101720.GJ1038@i92.ryd.student.liu.se> References: <408F82D4.2080609@pusspaws.net> <20040428101720.GJ1038@i92.ryd.student.liu.se> Message-ID: <20040428125249.40902e6a.klappnase@freenet.de> On Wed, 28 Apr 2004 12:17:20 +0200 Kalle Svensson wrote: > [Dave S] > > I need strings of the form 01, 02, 03 ... ,10,11,12 ... for > > archiving files. > > > > Is there an neat way to format a '1' into a '01' ? > > >>> for x in '1', '3', '30': > ... print '%02d' % int(x) > ... > 01 > 03 > 30 > > Peace, > Kalle > -- Or just: >>> x = '1' >>> x.zfill(2) '01' >>> y = '11' >>> y.zfill(2) '11' >>> Regards Michael From op73418 at mail.telepac.pt Wed Apr 28 07:31:02 2004 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Wed Apr 28 07:40:10 2004 Subject: [Tutor] exception question In-Reply-To: <408F6FFB.80308@pusspaws.net> References: <408F6FFB.80308@pusspaws.net> Message-ID: Em Wed, 28 Apr 2004 09:48:59 +0100, Dave S atirou este peixe aos pinguins: >Is it possible, for the code after except to know the exception type. I >know I can do multiple "except"s for each condition but this is not >realy what I want. > >try: > .... > ...code... > .... >except: > ...code .... > Sure. The following is, I believe, self-explanatory: >>> try: ... raise TypeError ... except ValueError: ... print "Got a ValueError" ... except TypeError: ... print "Got a TypeError" ... Got a TypeError You can also "catch" the exception object itself: >>> try: ... raise TypeError("This is a type error") ... except TypeError, e: ... print "TypeError found!" ... print "Error: %r." % e ... print "Arguments of exception object: %r." % e.args ... TypeError found! Error: . Arguments of exception object: 'This is a type error'. >>> Hope it helps, with my best regards, G. Rodrigues From pythontut at pusspaws.net Wed Apr 28 07:59:46 2004 From: pythontut at pusspaws.net (Dave S) Date: Wed Apr 28 08:00:01 2004 Subject: [Tutor] exception question In-Reply-To: References: <408F6FFB.80308@pusspaws.net> Message-ID: <408F9CB2.101@pusspaws.net> Gonc,alo Rodrigues wrote: >Em Wed, 28 Apr 2004 09:48:59 +0100, Dave S >atirou este peixe aos pinguins: > > > >>Is it possible, for the code after except to know the exception type. I >>know I can do multiple "except"s for each condition but this is not >>realy what I want. >> >>try: >> .... >> ...code... >> .... >>except: >> ...code .... >> >> >> > >Sure. The following is, I believe, self-explanatory: > > > >>>>try: >>>> >>>> >... raise TypeError >... except ValueError: >... print "Got a ValueError" >... except TypeError: >... print "Got a TypeError" >... >Got a TypeError > >You can also "catch" the exception object itself: > > > >>>>try: >>>> >>>> >... raise TypeError("This is a type error") >... except TypeError, e: >... print "TypeError found!" >... print "Error: %r." % e >... print "Arguments of exception object: %r." % e.args >... >TypeError found! >Error: . >Arguments of exception object: 'This is a type error'. > > > >Hope it helps, with my best regards, >G. Rodrigues > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > My problem is I do not know what the exception error will be. I have a script that will run 247, If an error occurs I want it to e-mail me with the exception error that caused the crash. Is this possible ? Dave From pythontut at pusspaws.net Wed Apr 28 08:06:54 2004 From: pythontut at pusspaws.net (Dave S) Date: Wed Apr 28 08:08:00 2004 Subject: [Tutor] makeing '1' into a '01' neatly ? In-Reply-To: <20040428125249.40902e6a.klappnase@freenet.de> References: <408F82D4.2080609@pusspaws.net> <20040428101720.GJ1038@i92.ryd.student.liu.se> <20040428125249.40902e6a.klappnase@freenet.de> Message-ID: <408F9E5E.7090808@pusspaws.net> Michael Lange wrote: >On Wed, 28 Apr 2004 12:17:20 +0200 >Kalle Svensson wrote: > > > >>[Dave S] >> >> >>>I need strings of the form 01, 02, 03 ... ,10,11,12 ... for >>>archiving files. >>> >>>Is there an neat way to format a '1' into a '01' ? >>> >>> >>>>>for x in '1', '3', '30': >>>>> >>>>> >>... print '%02d' % int(x) >>... >>01 >>03 >>30 >> >>Peace, >> Kalle >>-- >> >> > >Or just: > > > >>>>x = '1' >>>>x.zfill(2) >>>> >>>> >'01' > > >>>>y = '11' >>>>y.zfill(2) >>>> >>>> >'11' > > > >Regards > >Michael > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > zfill is cool, :-) Its not even in my learning python book ! Dave From magnus at thinkware.se Wed Apr 28 09:03:13 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Wed Apr 28 09:05:10 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gbWF0cml4ZXM=?= Message-ID: Conrad wrote: > matrix = (('glade', 'stream', 'mountains'),('woods', 'creak', 'dunes'), > ('forest', 'river', 'desert')) > > Is this the correct way and 'pythonic' way of doing it, or am I missing > a module or something. This would work, at least if the map is static. If you want to be able to change the matrix in runtime, it might be better to use a dictionary with coordinate tuples as keys. > The starting location would be glade, and I would represent that in the > location variable: > > location = [0, 0] > > and then north would be: > > north = [0, 1] > > and then if the input would be north. I would do something like this: > > location = [location[0] + north[0], location[1] + location[1]] > > The problem is if you went south for your first 'move' how would i make > it wrap and end up at forest? Are you telling us that this matrix is really a small, warped globe? ;) If you think it's too boring with if statements, you can have a look at the modulo operator (%). If there are things that you feel clutter the code in many places, put that "clutter" in one place, and make it a fuction or a class etc. > This seems like a real roundabout way of doing things, is there a > better/faster way of doing this? A programmer should be lazy, but that doesn't mean that he can avoid *all* work! ;) > As for my visual part, I was thinking of having a command line prompt to > take input and a seperate window which shows a picture depending on > which place you would be. This picture would have to dynamically change > and pretty rapidly. I'll do a little research before asking about it. > > Thanks a lot!! > > Conrad > > P.S. The teachers want me to make this in Flash or html, or any tools > found in our computer labs. But I think python would be appropriate for > the job. *grin* I'm not sure I could use pygame because im either going > to have to boot knoppix to demonstrate the game or find a small python > distrobution that can go on the labs, without adminstrative priveleges > since they only use windows. I relize this is homework but I do not > think the questions detract from the assignment. No, I think you will have some work with this, even if we give you a few nudges... ;) Thanks for being open about this. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From dyoo at hkn.eecs.berkeley.edu Wed Apr 28 09:11:04 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Apr 28 09:12:07 2004 Subject: [Tutor] Problems importing random on linux In-Reply-To: <19029.81.168.52.182.1083046913.spork@webmail.monkeez.org> Message-ID: > >> def generatenumber(): > >> target = random.randint(0,100) > >> > >> What is going on here? I've tried the same small piece of code: > >> import random target = random.randing(0,100) at the interpreter and > >> it works, but if I try this as an application in a file, it fails. > >> > >> Any ideas ? > > > > Do you perhaps have a file named random.py in the same directory as > > autoguess.py? To me, it sounds like the random module imported is > > different from the standard library module. There's just something about the 'random' module that makes people want to name their own programs 'random'... *grin* http://hkn.eecs.berkeley.edu/~dyoo/python/__std__/ From dyoo at hkn.eecs.berkeley.edu Wed Apr 28 09:38:37 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Apr 28 09:38:56 2004 Subject: [Tutor] exception question In-Reply-To: <408F9CB2.101@pusspaws.net> Message-ID: > My problem is I do not know what the exception error will be. I have a > script that will run 247, If an error occurs I want it to e-mail me with > the exception error that caused the crash. Hi Dave, According to: http://www.python.org/doc/lib/module-exceptions.html there's a top-level Exception class that we can use: ### >>> try: ... foobar ... except Exception, e: ... print repr(e) ... ### We can get a better stack trace out of the error by using the 'traceback' module: http://www.python.org/doc/lib/module-traceback.html So we can probably just trap all "Exception" things, and then use traceback to extract more specific information out of the exception. When you have time, you may also want to look at the source code to the 'cgitb' standard library module, http://www.python.org/doc/current/lib/module-cgitb.html as it traps all errors that come out of a CGI, and returns a nicely formatted error message (as well as optionally writing to a log file). [Completely off tangent: by the way, near the bottom of the 'cgitb' code, something looks really weird: if self.logdir is not None: import os, tempfile suffix = ['.html', '.txt'][self.format=="html"] Is the condition for 'suffix' backwards, or am I reading this wrong?] Hope this helps! From op73418 at mail.telepac.pt Wed Apr 28 09:23:42 2004 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Wed Apr 28 09:41:21 2004 Subject: [Tutor] exception question In-Reply-To: <408F9CB2.101@pusspaws.net> References: <408F6FFB.80308@pusspaws.net> <408F9CB2.101@pusspaws.net> Message-ID: Em Wed, 28 Apr 2004 12:59:46 +0100, Dave S atirou este peixe aos pinguins: Forwarding to the list, since by mistake sent it only to Dave. [text snipped] >My problem is I do not know what the exception error will be. >I have a script that will run 247, If an error occurs I want it to >e-mail me with the exception >error that caused the crash. > >Is this possible ? Does the following help? >>> try: ... raise TypeError ... except Exception, e: ... print repr(e) ... The Exception (old-style) class is the mother of all exception classes, so the above will catch *every* error. This is usually bad policy because it can mask error that you may want to propagate. By your description, this is not a problem. Still if you want to filter out some "errors" like KeyboardInterrupt for example do the following: >>> try: ... raise TypeError ... except KeyboardInterrupt: ... raise ... except Exception, e: ... print repr(e) ... Hope it helps, with my best regards, G. Rodrigues From magnus at thinkware.se Wed Apr 28 09:51:12 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Wed Apr 28 09:51:58 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gZXhjZXB0aW9uIHF1ZXN0aW9u?= Message-ID: Dave S wrote: > Is it possible, for the code after except to know the exception type. I > know I can do multiple "except"s for each condition but this is not > realy what I want. But that's usually the right thing to do! ;) > try: > .... > ...code... > .... > except: You should avoid these kinds of unqualified except blocks, since you can't really treat errors you never thought would occur. If you must have one except block, make sure to do "raise" without any arguments if you didn't figure out what error you had and how to handle it. Silencing error that you aren't really in control of is a quick way of making programming slow and difficult... > ...code .... >>> def expr(f): try: f() except Exception, e: print "I got a", e.__class__, "which said:" print e print "It has these attributes:", dir(e) print "And it was called with", e.args >>> def z(): 1/0 >>> expr(z) I got a exceptions.ZeroDivisionError which said: integer division or modulo by zero It has these attributes: ['__doc__', '__getitem__', '__init__', '__module__', '__str__', 'args'] And it was called with ('integer division or modulo by zero',) >>> def x(): [][9] >>> expr(x) I got a exceptions.IndexError which said: list index out of range It has these attributes: ['__doc__', '__getitem__', '__init__', '__module__', '__str__', 'args'] And it was called with ('list index out of range',) >>> def r(): raise StandardError("Python", "is", "nice") >>> expr(r) I got a exceptions.StandardError which said: ('Python', 'is', 'nice') It has these attributes: ['__doc__', '__getitem__', '__init__', '__module__', '__str__', 'args'] And it was called with ('Python', 'is', 'nice') Notice that Python exceptions used to be strings on ancient times, and string exceptions are still allowed for backward compatibility reasons. The expr function won't work right with those. You can also play with traceback objects! :) >>> import traceback, sys >>> def more_fun(f): try: f() except: cls, inst, tb = sys.exc_info() print "Exception class:", cls print "Exeption instance:", inst return tb >>> tb = more_fun(z) Exception class: exceptions.ZeroDivisionError Exeption instance: integer division or modulo by zero >>> traceback.print_tb(tb) File "", line 3, in more_fun f() File "", line 2, in z 1/0 More info in the Library manual, chapters for modules "sys" and "traceback". -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From magnus at thinkware.se Wed Apr 28 09:57:47 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Wed Apr 28 09:58:09 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gbWFrZWluZyAnMScgaW50byBhICcwMScgbmVhdGx5ID8=?= Message-ID: Dave wrote: > zfill is cool, :-) Its not even in my learning python book ! Try >>> help(str) For text processing of all kinds, David Metz's book covers most that you might need. I'm surprised if this isn't in Learning Python. It's in Chris Fehily's "Python Visual Quickstart Guide". I think that's a rather good book, and so is his book on SQL. (They're also fairly cheap.) -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From alan.gauld at blueyonder.co.uk Wed Apr 28 09:59:45 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Apr 28 09:59:36 2004 Subject: [Tutor] makeing '1' into a '01' neatly ? References: <408F82D4.2080609@pusspaws.net> Message-ID: <008b01c42d29$10195060$6401a8c0@xp> > Is there an neat way to format a '1' into a '01' ? >>> print "%02d" % int('1') 01 >>> HTH, Alan G From Janssen at rz.uni-frankfurt.de Wed Apr 28 11:29:12 2004 From: Janssen at rz.uni-frankfurt.de (Michael Janssen) Date: Wed Apr 28 11:29:33 2004 Subject: [Tutor] exception question In-Reply-To: References: Message-ID: On Wed, 28 Apr 2004, Danny Yoo wrote: > [Dave] > > My problem is I do not know what the exception error will be. I have a > > script that will run 247, If an error occurs I want it to e-mail me with > > the exception error that caused the crash. > We can get a better stack trace out of the error by using the 'traceback' > module: > > http://www.python.org/doc/lib/module-traceback.html > > So we can probably just trap all "Exception" things, and then use > traceback to extract more specific information out of the exception. The traceback-module is the way to do it. Otherwise one will lose all this "line XX, in foo" information. Since traceback is somewhat complicated (too much slightly different functions to choose from) I feel like it's okey, when I post a more or less complete solution. Assuming you have done your best catching possible errors but you can't be shure which errors else might show up. The programm is running automatically or via web, so the printed traceback isn't of that much help. Then you put your "main" function (i.e. the function that contains all of your programm - it's allways good to organize your scripts that way) within a catchall try-except clause: if __name__ == "__main__": try: main() except: import traceback, sys tb_list = traceback.format_exception(*sys.exc_info()) body = "Script: %s\n" % sys.argv[0] body += ''.join(tb_list) mail(body, subject="Script Error", addr="Your address") # give it back to console in case somebody is watching raise Explanations: 'if __name__ == "__main__"' is just a ward against running the code when *importing* the file as a module. It's nice to have when you ever want to import the script (to reuse its tricky functions). Has nothing to do with our topic ;-) "sys.exc_info()": this is where the traceback-object comes from. There is a warning on http://www.python.org/doc/lib/module-sys.html about problems with garbage collection. Nevertheless above code should be save (at least because the programm will terminate soon ;-). "*sys.exc_info()": sys.exc_info returns a tuple. "*" unfolds the tuple as arguments to format_exception. This special syntax is described in: http://docs.python.org/tut/ Section 4.7.4 traceback.format_exception: from all those functions from the traceback-module this seems proper to me. "mail": I hope you got your own mail-function? Use smtplib. The result looks very much like a traceback as written to console. Adding the hostname into the mail might be a good idea (with socket.gethostname). Michael From adam at monkeez.org Wed Apr 28 11:35:49 2004 From: adam at monkeez.org (Adam) Date: Wed Apr 28 11:37:27 2004 Subject: [Tutor] Generating random in a user specified range. In-Reply-To: References: Message-ID: <408FCF55.6010907@monkeez.org> Magnus Lycka wrote: > Adam wrote: > >>However, I seem to have a problem - I get an error using >>random.randint(a,b) and with random.randrange(a,b). > > > It's *much* easier to help you if you tell us exactly the error > messages you get. Can't you copy the traceback directly to the mail? > > Btw, used with two integers as arguments, random.randint(x,y) is > exactly the same thing as random.randrange(x,y+1). You can expect > them to behave fairly similarly from an error point of view, but > note that your "top" value will never be returned from > randrange(bottom, top). See below: > > >>>>import random >>>>random.randint(1,1) > > 1 > >>>>random.randrange(1,2) > > 1 > >>>>random.randrange(1,1) > > > Traceback (most recent call last): > File "", line 1, in -toplevel- > random.randrange(1,1) > File "D:\Python23\lib\random.py", line 171, in randrange > raise ValueError, "empty range for randrange()" > ValueError: empty range for randrange() > > >>It seems that it >>might be fussy accepting parts of a list as the argument. I've tried > > > If "x = [5, 20]", then x[0] and x[1] are integers, not "parts of a list", > so this isn't your problem. > > >>>>x = [5, 20] >>>>random.randint(x[0], x[1]) > > 15 > >>>>random.randrange(x[0], x[1]) > > 14 > > No problems! > > >>converting them to integers and then passing the interger, but it still >>complains. > > > You *should* provide integers as parameters with random.randrange(). > Never strings. > > Python is not a toy language that tries to guess what the programmer > meant and corrects him silently when he made a mistake. In the long > run, the Python tenet: "In the face of ambiguity, refuse the temptation > to guess" is very helpful when we try to build robust applications. > > >>range = range() > > > I assume you have this *after* your function definition in your actual > program, otherwise it will not call your not yet defined function, but > rather to the standard built in Python function called range. E.g. > > Traceback (most recent call last): > File "C:/TEMP/temp.py", line 1, in -toplevel- > range = range() > TypeError: range expected at least 1 arguments, got 0 > > >>def range(): > > > As I said, range is the name of a builtin function. It's not a good idea > to hide builtin functions with user defined ones. > > If I take your code, add "import random" at the top, and move the > initial lines to the end of the program, after the functions, it works > as expected, with no errors. (Well, I guess you actually want randint > rather than randrange as explained above.) > Just a quick thanks to everyone who replied - I got this working. Adam From duncan at thermal.esa.int Wed Apr 28 12:32:23 2004 From: duncan at thermal.esa.int (Duncan Gibson) Date: Wed Apr 28 12:32:37 2004 Subject: [Tutor] multiline regular expressions on endless data stream Message-ID: <200404281632.i3SGWNo21289@watt28.thermal.esa.int> I have a Perl utility which needs to be rewritten in something readable :-) What I'm currently doing is: read a line into a string if line contains start of regular expression marker read more lines until end of regular expression marker join lines into strin extract data from string repeat Unfortunately this piecemeal approach to matching the regular expression makes the logic very messy, which in Perl means that its very very messy. Is there a simpler way of doing this in Python without just duplicating the messy logic? I've been searching through the books and archives but haven't quite seen what I want, which is more along the lines of: discard lines until multiline regular expression matches extract data from regular expression repeat All the examples either read a line and try to match within the line, or read the whole file and ignore end of line when matching. I can't slurp the whole data into memory using read() because it might be a data stream rather than a fixed length file. The regular expression is relatively simple. It's just the buffering around it and writing a full parser/scanner that I'm trying to avoid. Does anyone have any hints or tips? Will I kick myself for overlooking the obvious? Cheers Duncan From reggie at merfinllc.com Wed Apr 28 12:45:15 2004 From: reggie at merfinllc.com (Reggie Dugard) Date: Wed Apr 28 12:57:16 2004 Subject: [Tutor] exception question In-Reply-To: References: Message-ID: <1083170715.6154.6.camel@pika> On Wed, 2004-04-28 at 06:38, Danny Yoo wrote: > [Completely off tangent: by the way, near the bottom of the 'cgitb' code, > something looks really weird: > > if self.logdir is not None: > import os, tempfile > suffix = ['.html', '.txt'][self.format=="html"] > > Is the condition for 'suffix' backwards, or am I reading this wrong?] >From this fragment, it looks backwards to me as well (the list should be ['.txt', '.html']) -- Reggie Dugard Merfin, LLC From firephreek at earthlink.net Wed Apr 28 14:02:18 2004 From: firephreek at earthlink.net (firephreek) Date: Wed Apr 28 14:11:06 2004 Subject: [Tutor] wxPython Gui notebook Message-ID: <001201c42d4a$f2c71660$6f01010a@Rachel> Hey all, hoping someone can help me with this... I want to start putting some of my apps into a GUI format so I can pass them around the office etc.. Trying to learn wxPython, but I'm kinda confused on some of the class implementation and window building. If I want to put a 'notebook' into my window, do I first create a wxFrame object to stick it into? Or does the notebook come first, with a frame inside it? Which is higher up on the totem pole? Or are they the same? Are there any other good tutorials? I'm going through the wiki, and that's fine, but it leaves some questions when I go through the demo code that comes with wxPython. Stryder From klappnase at freenet.de Wed Apr 28 14:15:03 2004 From: klappnase at freenet.de (Michael Lange) Date: Wed Apr 28 14:16:18 2004 Subject: [Tutor] makeing '1' into a '01' neatly ? In-Reply-To: <408F9E5E.7090808@pusspaws.net> References: <408F82D4.2080609@pusspaws.net> <20040428101720.GJ1038@i92.ryd.student.liu.se> <20040428125249.40902e6a.klappnase@freenet.de> <408F9E5E.7090808@pusspaws.net> Message-ID: <20040428201503.3767b29c.klappnase@freenet.de> On Wed, 28 Apr 2004 13:06:54 +0100 Dave S wrote: > >>>>x = '1' > >>>>x.zfill(2) > >>>> > >>>> > >'01' > > > > zfill is cool, :-) Its not even in my learning python book ! > > Dave > > _______________________________________________ I think it was new in Python2.1 or Python2.2 (at least in Python2.2.2 it works), in older version you only have access to zfill() through the string module: >>> import string >>> x='2' >>> string.zfill(x, 2) '02' >>> Michael From John.Ertl at fnmoc.navy.mil Wed Apr 28 14:37:06 2004 From: John.Ertl at fnmoc.navy.mil (Ertl, John) Date: Wed Apr 28 14:32:26 2004 Subject: [Tutor] Makeing a logfile Message-ID: I am trying to make a single log file for a program that uses several modules. Now when I run the program I open a file and redirect standard out to a file. This works fine for the main program and each of the modules do the same thing but to there own files. I would like to have just one file containing my log output. How can I get the print statements from the modules to output to the file opened in the main program? I would like to be able to run the modules individually and have the output go to the screen but when run from the main program the prints go to the opened log file. Thanks John Ertl -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040428/bde9f49b/attachment.html From magnus at thinkware.se Wed Apr 28 14:48:01 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Wed Apr 28 14:48:10 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gbXVsdGlsaW5lIHJlZ3VsYXIgZXhwcmVzc2lvbnMgb24gZW5kbGVzcyBkYXRhIHN0cmVhbQ==?= Message-ID: Duncan Gibson wrote: > I have a Perl utility which needs to be rewritten in something readable :-) Hey, that's what originally brought me to Python in 1996! :) > What I'm currently doing is: > read a line into a string > if line contains start of regular expression marker > read more lines until end of regular expression marker > join lines into strin > extract data from string > repeat > > Unfortunately this piecemeal approach to matching the regular expression > makes the logic very messy, which in Perl means that its very very messy. Would it be impossible to load all the data into the program before you start working on it instead of using a line-by-line approach? In other words, are you working with more than a few tens of MB, or do you work with a stream of data that you need to start processing before all is read? With "normal" files, you could do something like this: Let's make a file first. >>> x = """bla bla START in first block STOP outside block START in second block STOP bla bla""" >>> file('tmp.txt', 'w').write(x) Now, we read the file and process it: >>> data = file('tmp.txt').read() >>> import re >>> pat = r"(?ms)(^START$.*?^STOP$)" >>> re.findall(pat, data) ['START\nin first block\nSTOP', 'START\nin second block\nSTOP'] If you can't read all of the data at once, I guess you could use an approach where you read, let's say 1 MB at a time, extracts all relevant data as above, and finally, you check for a start-marker after your last processed block. (You might not want to use findall then, but rather something that let's you keep track of where in your data your last end marker was.) If you didn't find a new start marker after your processed blocks, you can throw away all data read so far. If there is a start marker (i.e. you stopped reading input inside a relevant block) you will only remove the data before that start marker. Then you read in more data and continue processing as before. At least that should be faster than doing one line at a time. Ouch! I just realized that you might have read in half a new start marker. I guess you'd better always keep at least as much of your old data as the length of a start marker - 1. :) > Is there a simpler way of doing this in Python without just duplicating > the messy logic? I've been searching through the books and archives but > haven't quite seen what I want, which is more along the lines of: > > discard lines until multiline regular expression matches > extract data from regular expression > repeat > > All the examples either read a line and try to match within the line, or > read the whole file and ignore end of line when matching. I can't slurp > the whole data into memory using read() because it might be a data stream > rather than a fixed length file. Aha. I should have read all the way before responding. :) As I said: You can use something like .read(1000000) and work on that. Or can you? Is there an urgency in processing data quickly if the stream is open, but not providing more data quickly? Oh, well, you can experiment with how many bytes to read at a time... > The regular expression is relatively simple. It's just the buffering > around it and writing a full parser/scanner that I'm trying to avoid. > > Does anyone have any hints or tips? > Will I kick myself for overlooking the obvious? I don't think so, but it doesn't seem very difficult either... Assuming you have compiled RE objects for start and stop patterns, you can use a function like this: def getBlocks(data, start_pat, stop_pat): ''' Feed with a text and two compiled patterns for start and stop markers in a block. Returns data that might need further processing and a list of blocks with the texts between pairs of start/stop markers. ''' blocks = [] pos = 0 # Determines where we'll cut remaining data while True: mo = start_pat.search(data, pos) if not mo: return data[pos:], blocks pos = mo.start() start = mo.end() # Beginning of a data block mo = stop_pat.search(data, start) if not mo: return data[pos:], blocks pos = mo.end() stop = mo.start() # End of a data block blocks.append(data[start:stop]) You would use this like this: start = re.compile(...) stop = re.compile(...) text = '' while True: more_text = your_data_stream.read(1000) # Whatever... if not more_text: break text += more_text text, blocks = getBlocks(text, start, stop) for block in blocks: ...do something ... Would this work? -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From magnus at thinkware.se Wed Apr 28 15:51:23 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Wed Apr 28 15:51:33 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gTWFrZWluZyBhIGxvZ2ZpbGU=?= Message-ID: John Ertl wrote: > I am trying to make a single log file for a program that uses several > modules. Now when I run the program I open a file and redirect standard out > to a file. This works fine for the main program and each of the modules do > the same thing but to there own files. I would like to have just one file > containing my log output. > > How can I get the print statements from the modules to output to the file > opened in the main program? I would like to be able to run the modules > individually and have the output go to the screen but when run from the main > program the prints go to the opened log file. First of all, I suggest that you consider using the standard library logging module. Don't reinvent the wheel... Please look at PEP 282 and the chapter on the logging module in the library reference. It does exactly what you want. From the docs: ======================================= Here's a simple logging example that just logs to a file. In order, it creates a Logger instance, then a FileHandler and a Formatter. It attaches the Formatter to the FileHandler, then the FileHandler to the Logger. Finally, it sets a debug level for the logger. import logging logger = logging.getLogger('myapp') hdlr = logging.FileHandler('/var/tmp/myapp.log') formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s') hdlr.setFormatter(formatter) logger.addHandler(hdlr) logger.setLevel(logging.WARNING) We can use this logger object now to write entries to the log file: logger.error('We have a problem') logger.info('While this is just chatty') If we look in the file that was created, we'll see something like this: 2003-07-08 16:49:45,896 ERROR We have a problem ======================================= You can do "logger = logging.getLogger('myapp')" anywhere in you application (in any module), and it will find the same log. (Of course, you should only format the logger in one place. :) If you absolutely don't want to use the logging module, you could do something like: ======module x.py======== import sys LOG = sys.stdout def test_log(msg): print >> LOG, msg ========================= >>> import x >>> x.test_log('Hello') Hello >>> import cStringIO as StringIO >>> log = StringIO.StringIO() >>> x.LOG = log >>> x.test_log('How do you do?') >>> log.seek(0) >>> log.read() 'How do you do?\n' You see? You have redirected x.LOG to some other kind of stream. (A file would work as well of course.) But this is very primitive compared to the logging module. (After all, you don't really want your main program to mess with global variables in various modules, and you certainly don't want your main program to know if x in turn imports another module, if that has logging, and if that in turn import some other module... So, use the standard solution! It's only a standard module since version 2.3, but if you need your code to work with earlier Python versions, the logging module will still work with them if you just install it. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From godoy at ieee.org Wed Apr 28 17:48:45 2004 From: godoy at ieee.org (Jorge Godoy) Date: Wed Apr 28 17:50:59 2004 Subject: [Tutor] Re: wxPython Gui notebook References: <001201c42d4a$f2c71660$6f01010a@Rachel> Message-ID: On Qua 28 Abr 2004 15:02, firephreek wrote: > If I want to put a 'notebook' into my window, do I first create a > wxFrame object to stick it into? Or does the notebook come first, with > a frame inside it? Which is higher up on the totem pole? Or are they > the same? Are there any other good tutorials? I'm going through the > wiki, and that's fine, but it leaves some questions when I go through > the demo code that comes with wxPython. You should create the App, then the Frame, then add a sizer to the Frame, then add the Notebook to the sizer, then add pages to the notebook, then add panels then sizers, then objects to the sizers. Try using something like Boa Constructor or wxGlade. It will make your starting easier. With regard to starting with wxPython, try the wiki: http://wiki.wxpython.org/ -- Godoy. From missive at hotmail.com Wed Apr 28 17:59:06 2004 From: missive at hotmail.com (Lee Harr) Date: Wed Apr 28 17:59:12 2004 Subject: [Tutor] Re: matrixes Message-ID: >I have to recreate a text-based game 'visually' for school and I was >hoping you could help me with things I've run into. > >One of the first things I've run into is how to deal with matrixes in >python. If I have the following matrix with 'glade' being location >(0,0): > >forest river desert > >woods creak dunes > >glade stream mountains > >I was thinking of representing like this: > >matrix = (('glade', 'stream', 'mountains'),('woods', 'creak', 'dunes'), >('forest', 'river', 'desert')) > >Is this the correct way and 'pythonic' way of doing it, or am I missing >a module or something. > That seems reasonable. Though I might suggest formatting your tuple like this ... matrix = (('glade', 'stream', 'mountains'), ('woods', 'creak', 'dunes'), ('forest', 'river', 'desert'), ) Just so that it looks more like your sketch, and is easier to add on to. >location = [0, 0] > >and then north would be: > >north = [0, 1] > >and then if the input would be north. I would do something like this: > >location = [location[0] + north[0], location[1] + location[1]] > >The problem is if you went south for your first 'move' how would i make >it wrap and end up at forest? > I'd like to see what code you are actually using, but how about something like ... if location[0] < 0: location[0] = 2 You will probably want to take in to account the fact that your matrix of locations could change size in the future. >This seems like a real roundabout way of doing things, is there a >better/faster way of doing this? > I would probably opt for an object-oriented approach myself. (each location would be an object instead of just a string... they could have links to the locations around them instead of putting them in to a matrix.) >As for my visual part, I was thinking of having a command line prompt to >take input and a seperate window which shows a picture depending on >which place you would be. This picture would have to dynamically change >and pretty rapidly. I'll do a little research before asking about it. > Sounds like fun. Let us know what you come up with. _________________________________________________________________ Help STOP SPAM with the new MSN 8 and get 2 months FREE* http://join.msn.com/?page=features/junkmail From flaxeater at yahoo.com Thu Apr 29 01:37:37 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Thu Apr 29 01:37:42 2004 Subject: [Tutor] FTP Binary Mode. Message-ID: <20040429053737.75051.qmail@web11607.mail.yahoo.com> I am modifying the thumbnail.py file from useless python to connect via ftp and make thumbnails. I'm the snag I've ran in to is that ftp.FTP.retrbinar(cmd,callback,blockisize) on does things through the callback function. I would like to create a file object with it somehow but I'm stumped. I know I could make it into a big string but then I would need to turn it into a file object. I'm really stumped. __________________________________ Do you Yahoo!? Win a $20,000 Career Makeover at Yahoo! HotJobs http://hotjobs.sweepstakes.yahoo.com/careermakeover From magnus at thinkware.se Thu Apr 29 05:36:46 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Thu Apr 29 05:36:59 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gRlRQIEJpbmFyeSBNb2RlLiAg?= Message-ID: Chad Crabtree wrote: > I am modifying the thumbnail.py file from useless > python to connect via ftp and make thumbnails. I'm > the snag I've ran in to is that > ftp.FTP.retrbinar(cmd,callback,blockisize) > on does things through the callback function. I would > like to create a file object with it somehow but I'm > stumped. I know I could make it into a big string but > then I would need to turn it into a file object. I'm > really stumped. Open a file (f) for writing (binary). Supply f.write as callback function for retrbinary. That's basically it! >>> import ftplib >>> import os.path >>> host = 'ftp.sunet.se' >>> path = '/pub/comics/comics/Snoopy/snoopy.gif' >>> local_dir = 'H:\\' >>> ftp = ftplib.FTP(host) >>> ftp.login() '230 Login successful. Have fun.' >>> dir, fn = os.path.split(path) >>> local_path = os.path.join(local_dir, fn) >>> ftp.cwd(dir) '250 Directory successfully changed.' >>> f = file(local_path, 'wb') >>> ftp.retrbinary('RETR '+fn, f.write) '226 File send OK.' >>> f.close() >>> ftp.close() It worked! :) -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From scarab at transwitch.co.za Thu Apr 29 06:01:07 2004 From: scarab at transwitch.co.za (scarab@transwitch.co.za) Date: Thu Apr 29 06:01:25 2004 Subject: [Tutor] Book recommendations Message-ID: <20040429100107.GE5454@scarab.transwitch.co.za> can anyone suggest good/great python newbie books? i use to own Alan Gauld's excellent book, but i'm also looking for others. many thanks! From magnus at thinkware.se Thu Apr 29 07:25:55 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Thu Apr 29 07:26:08 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gQm9vayByZWNvbW1lbmRhdGlvbnM=?= Message-ID: > can anyone suggest good/great python newbie books? i use to own Alan > Gauld's excellent book, but i'm also looking for others. I think Chris Fehily's book is rather nice. http://www.amazon.com/exec/obidos/tg/detail/-/0201748843/ It's also fairly cheap and reasonably brief. Of course, any paper book is bound to be a little out of date rather soon. Most of the examples in the book (and there are plenty) use the interactive interpreter to explore various features of Python. I think that's a good idea--the interpreter *is* very useful for learning Python, so getting used to exploring Python like this is probably a good idea. It might be a bit of a hurdle for the programmer to figure out how to actually apply these things in a normal program though... But there are plenty of online tutorials and code resources to complement this book with. E.g. http://www.diveintopython.org/ (also published on paper now) http://www.uselesspython.com/ http://www.activestate.com/ASPN/Python/Cookbook/ (Do you need to register for this now? Stupid Sophos!) -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From bvande at po-box.mcgill.ca Thu Apr 29 11:14:31 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Thu Apr 29 11:23:00 2004 Subject: [Tutor] Book recommendations In-Reply-To: <20040429100107.GE5454@scarab.transwitch.co.za> References: <20040429100107.GE5454@scarab.transwitch.co.za> Message-ID: <40911BD7.7030408@po-box.mcgill.ca> scarab@transwitch.co.za said unto the world upon 29/04/2004 06:01: > can anyone suggest good/great python newbie books? i use to own Alan > Gauld's excellent book, but i'm also looking for others. > > many thanks! > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > Hi, For the true newbie, I thought Think Like a Computer Scientist was very good. It's written for high school students and thus starts slow. Full text is free at http://www.ibiblio.org/obp/thinkCSpy/ For more detail, the almost-canonical source seems to be Lutz and Ascher's Learning Python. http://www.oreilly.com/catalog/lpython2/. One that I've looked at some is Magnus Lie Hetland's Practical Python. It seems to use substantial example programs more than most books I found. It thus seems very useful for the "OK, but how do I glue this all together to do something non-trivial? sort of question. Hetland's page for his book is http://hetland.org/writing/practical-python/. I found both Hetland's book and Learning Python available on-line, but this was through services that my uni library subscribes to. None of these 3 books are very well suited to looking things up in a hurry. For that, Python in a Nutshell -- http://www.oreilly.com/catalog/pythonian/. Last, for the "batteries", Fredrik Lundh's Python Standard Library is available in print http://www.oreilly.com/catalog/pythonsl/ or in a different (and downloadable) edition from Lundh himself at http://effbot.org/zone/librarybook-index.htm. Whichever way you go, Magnus Lycka's advice to use the interactive interpreter as you read is spot on. (The archives of tutor have more than one example-post from me demonstrating the shortfalls of trying to learn by book alone.) Hope these are of use. Best, Brian vdB From dtalaga at novodynamics.com Thu Apr 29 12:58:56 2004 From: dtalaga at novodynamics.com (David Talaga) Date: Thu Apr 29 12:58:17 2004 Subject: [Tutor] Listbox insertion In-Reply-To: Message-ID: Hi all, How would I go about inserting text from a file into a listbox. I was thinking that maybe a listbox is not what I am wanting. See, I have a file that I have created and it inserts a file name from an askopenfilename dialog when selected. I then want to put the information into that listbox (or maybe a label?). I am not finding much documentation about inserting information into a list box. What would you suggest as far as putting the data? How would I go about inserting the data from that file into the list box? From tpc at csua.berkeley.edu Thu Apr 29 14:54:51 2004 From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu) Date: Thu Apr 29 14:54:56 2004 Subject: [Tutor] ": No such file or directory" Message-ID: <20040429114621.P62116-100000@localhost.name> Hi everybody, has anybody gotten the strange message above when trying to execute a Python script from command line ? I wrote it on a Linux box and ported it to Windows by adding and commenting out a few lines. It was working fine then today it started to behave strangely by not completely finishing executing all the lines of code. I decided to bring the script back to Linux to see if I could get error messages from the command line to see where the problem was. When I made the necessary changes and executed it, I got: nike:/var/www/html# ./parseDonations.py : No such file or directory I then tried a diff between the two scripts (i.e, the script before I ported it to Windows, and the script after I ported it back to Linux), and for some strange reason diff gave me the entire two files, as if there was nothing in common between the two, even though my eyes could see clearly chunks of code that were exactly the same. Am I doing something wrong ? From bwinton at latte.ca Thu Apr 29 15:03:59 2004 From: bwinton at latte.ca (Blake Winton) Date: Thu Apr 29 15:04:15 2004 Subject: [Tutor] ": No such file or directory" In-Reply-To: <20040429114621.P62116-100000@localhost.name> Message-ID: <00ca01c42e1c$c05fc3c0$6401a8c0@phantomfiber.com> > I then tried a diff between the two scripts (i.e, the script before I > ported it to Windows, and the script after I ported it back to Linux), > and for some strange reason diff gave me the entire two files, as if > there was nothing in common between the two, even though my eyes > could see clearly chunks of code that were exactly the same. Am I > doing something wrong ? Perhaps the changes are something your eyes can't see... ("Do you think that's air you're breathing?") On your linux box, try typing "vi -b parseDonations.py", and let us know if anything looks out of place. Later, Blake. From godoy at ieee.org Thu Apr 29 15:23:14 2004 From: godoy at ieee.org (Jorge Godoy) Date: Thu Apr 29 15:26:13 2004 Subject: [Tutor] Re: ": No such file or directory" References: <20040429114621.P62116-100000@localhost.name> Message-ID: On Qui 29 Abr 2004 15:54, tpc@csua.berkeley.edu wrote: > > Hi everybody, has anybody gotten the strange message above when trying to > execute a Python script from command line ? I wrote it on a Linux box and > ported it to Windows by adding and commenting out a few lines. It was > working fine then today it started to behave strangely by not completely > finishing executing all the lines of code. I decided to bring the script > back to Linux to see if I could get error messages from the command line > to see where the problem was. When I made the necessary changes and > executed it, I got: > > > nike:/var/www/html# ./parseDonations.py > : No such file or directory > > > I then tried a diff between the two scripts (i.e, the script before I > ported it to Windows, and the script after I ported it back to Linux), > and for some strange reason diff gave me the entire two files, as if > there was nothing in common between the two, even though my eyes could see > clearly chunks of code that were exactly the same. Am I doing something > wrong ? Run 'dos2unix' on such a script. I had the same error due to the char that represents EOLs on each OS. -- Godoy. From mhansen at cso.atmel.com Thu Apr 29 15:36:00 2004 From: mhansen at cso.atmel.com (Mike Hansen) Date: Thu Apr 29 15:36:41 2004 Subject: [Tutor] cgi, fastcgi, mod_python Message-ID: <40915920.40009@cso.atmel.com> Hello, I've recently started experimenting with Python to write web apps. My first app did a little form processing using the cgi module. Performance isn't a huge issue, but I'm curious on how to pep it up if the need should arise. I'm a bit confused on other solutions like FastCGI and Mod_Python. If I decided to use FastCGI, would I need to significantly change my code? I didn't get the impression that you just install it, modify your apache config, and import FastCGI in your code instead of the cgi module. The same with Mod_Python. Could someone briefly explain the differences in coding cgi, FastCGI, or Mod_Python if there are any differences? Thanks, Mike Hansen From olavi at city.ee Thu Apr 29 15:44:14 2004 From: olavi at city.ee (olavi@city.ee) Date: Thu Apr 29 15:44:21 2004 Subject: [Tutor] Tkinter Message-ID: <20040429194414.5354.qmail@city.ee> Hi everybody! Can anybody tell, what is the difference between label = Label(root, text="Label1").grid() and label = Label(root, text="Label1") label.grid() Which method is better to use? Regards Olavi Ivask From david at graniteweb.com Thu Apr 29 16:03:15 2004 From: david at graniteweb.com (David Rock) Date: Thu Apr 29 16:03:21 2004 Subject: [Tutor] ": No such file or directory" In-Reply-To: <20040429114621.P62116-100000@localhost.name> References: <20040429114621.P62116-100000@localhost.name> Message-ID: <20040429200315.GA21154@wdfs.graniteweb.com> * tpc@csua.berkeley.edu [2004-04-29 11:54]: > > Hi everybody, has anybody gotten the strange message above when trying to > execute a Python script from command line ? I wrote it on a Linux box and > ported it to Windows by adding and commenting out a few lines. It was > working fine then today it started to behave strangely by not completely > finishing executing all the lines of code. I decided to bring the script > back to Linux to see if I could get error messages from the command line > to see where the problem was. When I made the necessary changes and > executed it, I got: > > > nike:/var/www/html# ./parseDonations.py > : No such file or directory > > > I then tried a diff between the two scripts (i.e, the script before I > ported it to Windows, and the script after I ported it back to Linux), > and for some strange reason diff gave me the entire two files, as if > there was nothing in common between the two, even though my eyes could see > clearly chunks of code that were exactly the same. Am I doing something > wrong ? Make sure if you are doing this that the file is executable and also make sure there is an invocation line for the interpreter on the first line of the file. Windows does NOT require this, but unix-type systems do. This should be the first line in the file: #!/usr/local/bin/python (or whatever your path to python is) And make the file executable: chmod 755 ./parseDonations.py -- David Rock david@graniteweb.com From david at graniteweb.com Thu Apr 29 16:07:10 2004 From: david at graniteweb.com (David Rock) Date: Thu Apr 29 16:07:15 2004 Subject: [Tutor] Tkinter In-Reply-To: <20040429194414.5354.qmail@city.ee> References: <20040429194414.5354.qmail@city.ee> Message-ID: <20040429200710.GB21154@wdfs.graniteweb.com> * olavi@city.ee [2004-04-29 19:44]: > Hi everybody! > > Can anybody tell, what is the difference between > > label = Label(root, text="Label1").grid() > > and > > label = Label(root, text="Label1") > label.grid() > > Which method is better to use? label = Label(root, text="Label1").grid() assigns the grid object to the variable label, while label = Label(root, text="Label1") assigns the LABEL object to label. The second one is probably better because you are working with the primary object that you can call ALL methods for, not just grid(), while the first is limited to JUST grid() -- David Rock david@graniteweb.com -------------- 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/20040429/4a859c43/attachment.bin From olavi at city.ee Thu Apr 29 16:14:12 2004 From: olavi at city.ee (Olavi Ivask) Date: Thu Apr 29 16:16:39 2004 Subject: [Tutor] Tkinter In-Reply-To: <20040429200710.GB21154@wdfs.graniteweb.com> References: <20040429194414.5354.qmail@city.ee> <20040429200710.GB21154@wdfs.graniteweb.com> Message-ID: <40916214.1070907@city.ee> David Rock wrote: >* olavi@city.ee [2004-04-29 19:44]: > > >>Hi everybody! >> >>Can anybody tell, what is the difference between >> >> label = Label(root, text="Label1").grid() >> >>and >> >> label = Label(root, text="Label1") >> label.grid() >> >>Which method is better to use? >> >> > >label = Label(root, text="Label1").grid() > >assigns the grid object to the variable label, while > >label = Label(root, text="Label1") > >assigns the LABEL object to label. The second one is probably better >because you are working with the primary object that you can call ALL >methods for, not just grid(), while the first is limited to JUST grid() > > can i do something like that: I "define" several widgets: label = Label(root, text="text") label = Label(root, text="text2") ... label.grid() right now, it shows only second widget. Olavi >------------------------------------------------------------------------ > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > From david at graniteweb.com Thu Apr 29 16:20:10 2004 From: david at graniteweb.com (David Rock) Date: Thu Apr 29 16:20:51 2004 Subject: [Tutor] Tkinter In-Reply-To: <40916214.1070907@city.ee> References: <20040429194414.5354.qmail@city.ee> <20040429200710.GB21154@wdfs.graniteweb.com> <40916214.1070907@city.ee> Message-ID: <20040429202010.GE21154@wdfs.graniteweb.com> * Olavi Ivask [2004-04-29 23:14]: > David Rock wrote: > > > >label = Label(root, text="Label1").grid() > > > >assigns the grid object to the variable label, while > > > >label = Label(root, text="Label1") > > > >assigns the LABEL object to label. The second one is probably better > >because you are working with the primary object that you can call ALL > >methods for, not just grid(), while the first is limited to JUST grid() > > > > > can i do something like that: > I "define" several widgets: > label = Label(root, text="text") > label = Label(root, text="text2") > ... > label.grid() > > right now, it shows only second widget. No. you are overwriting the first assignment with the second. You would have to use label1, label2, etc. Ideally, label would be something vaguely descriptive so you could tell at a glance _which_ label it is and what it's for. -- David Rock david@graniteweb.com -------------- 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/20040429/676e8ac4/attachment.bin From olavi at city.ee Thu Apr 29 16:21:56 2004 From: olavi at city.ee (Olavi Ivask) Date: Thu Apr 29 16:24:22 2004 Subject: [Tutor] Tkinter In-Reply-To: <20040429202010.GE21154@wdfs.graniteweb.com> References: <20040429194414.5354.qmail@city.ee> <20040429200710.GB21154@wdfs.graniteweb.com> <40916214.1070907@city.ee> <20040429202010.GE21154@wdfs.graniteweb.com> Message-ID: <409163E4.3080602@city.ee> David Rock wrote: >* Olavi Ivask [2004-04-29 23:14]: > > >>David Rock wrote: >> >> >>>label = Label(root, text="Label1").grid() >>> >>>assigns the grid object to the variable label, while >>> >>>label = Label(root, text="Label1") >>> >>>assigns the LABEL object to label. The second one is probably better >>>because you are working with the primary object that you can call ALL >>>methods for, not just grid(), while the first is limited to JUST grid() >>> >>> >>> >>> >>can i do something like that: >>I "define" several widgets: >> label = Label(root, text="text") >> label = Label(root, text="text2") >> ... >> label.grid() >> >> right now, it shows only second widget. >> >> > >No. you are overwriting the first assignment with the second. You would >have to use label1, label2, etc. Ideally, label would be something >vaguely descriptive so you could tell at a glance _which_ label it is >and what it's for. > > > > > Thanks David for your help Best Regards Olavi Ivask >------------------------------------------------------------------------ > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > From firephreek at earthlink.net Thu Apr 29 16:19:03 2004 From: firephreek at earthlink.net (firephreek) Date: Thu Apr 29 16:27:46 2004 Subject: FW: [Tutor] Re: wxPython Gui notebook Message-ID: <006501c42e27$37980b50$6f01010a@Rachel> -----Original Message----- From: firephreek [mailto:firephreek@earthlink.net] Sent: Thursday, April 29, 2004 8:04 AM To: 'Jorge Godoy' Subject: RE: [Tutor] Re: wxPython Gui notebook Thanks for the help. I actually got it working shortly after sending that out. I guess I was doing something wrong with the parent references. Or something. Can't get the combo box to work though. I have indeed read the wiki and that helped some too. Sorry if I posted in the wrong place, I've done been told to go elsewhere, and well, I tried that link but it was broken. Anybody know where I can suscribe to the wxPython list? "http://www.wxpython.org/maillist.php --> suscribe to List" doesn't work. Stryder -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On Behalf Of Jorge Godoy Sent: Wednesday, April 28, 2004 2:49 PM To: tutor@python.org Subject: [Tutor] Re: wxPython Gui notebook On Qua 28 Abr 2004 15:02, firephreek wrote: > If I want to put a 'notebook' into my window, do I first create a > wxFrame object to stick it into? Or does the notebook come first, > with a frame inside it? Which is higher up on the totem pole? Or are > they the same? Are there any other good tutorials? I'm going through > the wiki, and that's fine, but it leaves some questions when I go > through the demo code that comes with wxPython. You should create the App, then the Frame, then add a sizer to the Frame, then add the Notebook to the sizer, then add pages to the notebook, then add panels then sizers, then objects to the sizers. Try using something like Boa Constructor or wxGlade. It will make your starting easier. With regard to starting with wxPython, try the wiki: http://wiki.wxpython.org/ -- Godoy. _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From alan.gauld at blueyonder.co.uk Thu Apr 29 16:56:06 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Apr 29 16:56:11 2004 Subject: [Tutor] Re: matrixes References: Message-ID: <002a01c42e2c$641b83a0$6401a8c0@xp> > >location = [location[0] + north[0], location[1] + location[1]] > > > >The problem is if you went south for your first 'move' how would i make > >it wrap and end up at forest? > > I've missed the start of the thread but normally the way to do this is to use modulo arithmetic. result = item + change % matrixSize So for a 3x3 matrix the matrixSize is 3 and 0 + 0 % 3 = 0 0 + 1 % 3 = 1 0 + 2 % 3 = 2 1 + 0 % 3 = 1 1 + 1 % 3 = 2 1 + 2 % 3 = 0 ---- We wrapped around! 2 + 0 % 3 = 2 2 + 1 % 3 = 0 ---- We wrapped around! 2 + 2 % 3 = 1 ---- We wrapped around! Does that solve your problem? Of course this is easily done by just storing the results in a table but the beauty of this approach is that it is easily extended to much bigger matrices, or even variably sized matrices. If not my apologies for introducing confusion! :-) Alan G From alan.gauld at blueyonder.co.uk Thu Apr 29 16:59:34 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Apr 29 16:59:26 2004 Subject: [Tutor] Book recommendations References: <20040429100107.GE5454@scarab.transwitch.co.za> Message-ID: <002f01c42e2c$e06b3ea0$6401a8c0@xp> > can anyone suggest good/great python newbie books? i use to own Alan > Gauld's excellent book, but i'm also looking for others. Thanks for the kind words, but as you know my book is strictly an introduction. My curent "next steps" book recommendations are: Either of: Python in a Nutshell - O'Reilly Python Essential Reference - New riders Optionally: Programming Python 2nd edition - O'Reilly (big!) and if on a Windows box: Python Programming on Win32 - O'Reilly Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From pythontut at pusspaws.net Thu Apr 29 16:59:53 2004 From: pythontut at pusspaws.net (Dave S) Date: Thu Apr 29 17:00:10 2004 Subject: [Tutor] makeing '1' into a '01' neatly ? In-Reply-To: References: Message-ID: <40916CC9.50106@pusspaws.net> Magnus Lycka wrote: >Dave wrote: > > >>zfill is cool, :-) Its not even in my learning python book ! >> >> > >Try > > > >>>>help(str) >>>> >>>> > >For text processing of all kinds, David Metz's book covers >most that you might need. > >I'm surprised if this isn't in Learning Python. It's in Chris >Fehily's "Python Visual Quickstart Guide". I think that's a >rather good book, and so is his book on SQL. (They're also >fairly cheap.) > > > I may have to invest .. Im finding 'learning python' - o'reilly a bit heavy going in places Dave From pythontut at pusspaws.net Thu Apr 29 17:06:28 2004 From: pythontut at pusspaws.net (Dave S) Date: Thu Apr 29 17:06:37 2004 Subject: [Tutor] exception question In-Reply-To: References: Message-ID: <40916E54.4010301@pusspaws.net> Michael Janssen wrote: >On Wed, 28 Apr 2004, Danny Yoo wrote: > > > >>[Dave] >> >> >>>My problem is I do not know what the exception error will be. I have a >>>script that will run 247, If an error occurs I want it to e-mail me with >>>the exception error that caused the crash. >>> >>> > > > >>We can get a better stack trace out of the error by using the 'traceback' >>module: >> >> http://www.python.org/doc/lib/module-traceback.html >> >>So we can probably just trap all "Exception" things, and then use >>traceback to extract more specific information out of the exception. >> >> > >The traceback-module is the way to do it. Otherwise one will lose all this >"line XX, in foo" information. Since traceback is somewhat complicated >(too much slightly different functions to choose from) I feel like it's >okey, when I post a more or less complete solution. > >Assuming you have done your best catching possible errors but you can't be >shure which errors else might show up. The programm is running >automatically or via web, so the printed traceback isn't of that much >help. > >Then you put your "main" function (i.e. the function that contains all of >your programm - it's allways good to organize your scripts that way) >within a catchall try-except clause: > > >if __name__ == "__main__": > try: main() > except: > import traceback, sys > tb_list = traceback.format_exception(*sys.exc_info()) > body = "Script: %s\n" % sys.argv[0] > body += ''.join(tb_list) > mail(body, subject="Script Error", addr="Your address") > # give it back to console in case somebody is watching > raise > > >Explanations: > >'if __name__ == "__main__"' is just a ward against running the code when >*importing* the file as a module. It's nice to have when you ever want to >import the script (to reuse its tricky functions). Has nothing to do with >our topic ;-) > >"sys.exc_info()": this is where the traceback-object comes from. There is >a warning on http://www.python.org/doc/lib/module-sys.html about problems >with garbage collection. Nevertheless above code should be save (at least >because the programm will terminate soon ;-). > >"*sys.exc_info()": sys.exc_info returns a tuple. "*" unfolds the tuple as >arguments to format_exception. This special syntax is described in: >http://docs.python.org/tut/ Section 4.7.4 > >traceback.format_exception: from all those functions from the >traceback-module this seems proper to me. > >"mail": I hope you got your own mail-function? Use smtplib. > > >The result looks very much like a traceback as written to console. Adding >the hostname into the mail might be a good idea (with socket.gethostname). > > >Michael > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > This is invaluable stuff. Thank you so much for taking the time to explain. You have given me some new ideas - and explained the __name__ == "__main__" thing ! Cheers again Dave :-) :-) :-) :-) From tpc at csua.berkeley.edu Thu Apr 29 17:07:02 2004 From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu) Date: Thu Apr 29 17:07:21 2004 Subject: [Tutor] ": No such file or directory" In-Reply-To: <00ca01c42e1c$c05fc3c0$6401a8c0@phantomfiber.com> Message-ID: <20040429140605.H62116-100000@localhost.name> Great, thanks guys. Now I feel like such a fool. On Thu, 29 Apr 2004, Blake Winton wrote: > Perhaps the changes are something your eyes can't see... > ("Do you think that's air you're breathing?") > > On your linux box, try typing "vi -b parseDonations.py", and let us > know if anything looks out of place. > > Later, > Blake. > > From alan.gauld at blueyonder.co.uk Thu Apr 29 17:08:27 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Apr 29 17:08:13 2004 Subject: [Tutor] Listbox insertion References: Message-ID: <004801c42e2e$1decad80$6401a8c0@xp> > How would I go about inserting text from a file into a listbox. I was > thinking that maybe a listbox is not what I am wanting. See, I have a file > that I have created and it inserts a file name from an askopenfilename > dialog when selected. I then want to put the information into that listbox > (or maybe a label?). The description isn't specific enough to answer, but it sounds like maybe you want the listbox to hold a list of filenames and a Text widget to hold the contents of the highlighted filename? The Tkinter Text widget is a powerful widget capable of displaying a lot more than text, it can also hold images etc. > I am not finding much documentation about inserting > information into a list box. A Listbox takes a data item and inserts it at the specified position. The easiest being END: L = Listbox(root, width=20) L.pack() for item in [1,2,3,4,5] L.insert(END, item) # appends item at the end L.insert(0, 0) # inserts at front That's it... not too hard is it? Alan G. From alan.gauld at blueyonder.co.uk Thu Apr 29 17:10:34 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Apr 29 17:11:11 2004 Subject: [Tutor] ": No such file or directory" References: <20040429114621.P62116-100000@localhost.name> Message-ID: <004d01c42e2e$69842de0$6401a8c0@xp> > > nike:/var/www/html# ./parseDonations.py > : No such file or directory > Dunno about this but... > I then tried a diff between the two scripts (i.e, the script before I > ported it to Windows, and the script after I ported it back to Linux), > and for some strange reason diff gave me the entire two files, I suspect this is just the DOS line ending characters. Did you remember to run dos2unix on the file after porting it back? Alan G From alan.gauld at blueyonder.co.uk Thu Apr 29 17:14:28 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Apr 29 17:14:16 2004 Subject: [Tutor] Tkinter References: <20040429194414.5354.qmail@city.ee> Message-ID: <005801c42e2e$f4d0e280$6401a8c0@xp> > Can anybody tell, what is the difference between > > label = Label(root, text="Label1").grid() This creates a widget and calls the grid method. It stores the result of the grid method('None' as it happens) in the variable label. > label = Label(root, text="Label1") This creates a Label widget and stores it in the variable label > label.grid() And this places the widget called 'label' in the UI using the grid() method. > Which method is better to use? Assuming you want to refer to 'label' in the future the second is the only one that makes sense. The first one will always result in 'label' being None, which is not very useful. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at blueyonder.co.uk Thu Apr 29 17:17:46 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Apr 29 17:17:36 2004 Subject: [Tutor] Tkinter References: <20040429194414.5354.qmail@city.ee><20040429200710.GB21154@wdfs.graniteweb.com> <40916214.1070907@city.ee> Message-ID: <006a01c42e2f$6b37dbe0$6401a8c0@xp> > can i do something like that: > I "define" several widgets: > label = Label(root, text="text") This creates a widget and calls it 'label' > label = Label(root, text="text2") This creates a second widget and calls it 'label' At this point we no longer have a reference to the first widget (except by interrogating the root object for its children) > ... > label.grid() This pushes the currently referenced widget onto the GUI. > right now, it shows only second widget. Correct, because that's what we told 'label' to point to most recently. Python does exactly what you ask it to do and no more... Alan G. From lumbricus at gmx.net Thu Apr 29 18:37:34 2004 From: lumbricus at gmx.net (Joerg Woelke) Date: Thu Apr 29 18:44:42 2004 Subject: [Tutor] ": No such file or directory" In-Reply-To: <00ca01c42e1c$c05fc3c0$6401a8c0@phantomfiber.com> References: <20040429114621.P62116-100000@localhost.name> <00ca01c42e1c$c05fc3c0$6401a8c0@phantomfiber.com> Message-ID: <20040429223734.GA1237@linux.local> On Thu, Apr 29, 2004 at 03:03:59PM -0400, Blake Winton wrote: > > I then tried a diff between the two scripts (i.e, the script before I > > ported it to Windows, and the script after I ported it back to Linux), > > and for some strange reason diff gave me the entire two files, as if > > there was nothing in common between the two, even though my eyes > > could see clearly chunks of code that were exactly the same. Am I > > doing something wrong ? > > Perhaps the changes are something your eyes can't see... > ("Do you think that's air you're breathing?") > > On your linux box, try typing "vi -b parseDonations.py", and let us > know if anything looks out of place. Or try: cat -v diff -w man cat man diff man dos2unix > Later, > Blake. HTH and Greetings, J"o! -- Sie duerfen diesen Satz zitieren. From thorsten at thorstenkampe.de Thu Apr 29 19:13:12 2004 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Thu Apr 29 19:13:18 2004 Subject: [Tutor] env shebang with options Message-ID: <1cau2djhoe168$.dlg@thorstenkampe.de> I'm trying to set up a Python script with a shebang with options: % cat test.py #! /usr/bin/env python -Ot print 11 % chmod 700 test.py; ./test.py /usr/bin/env: python -Ot: No such file or directory % env --version env (coreutils) 5.0.91 According to Alex Martelli in "Python in a Nutshell" this should work: "On Unix-like systems, you can make a Python script directly executable by setting the file's permission bits /x/ and /r/ and beginning the script with a so called /shebang/ line, which is a first line of the form: #!/usr/bin/env python {options} providing a path to the /python/ program." I've already tried all variations of the shebang I can think of. None work except the trivial "#! /usr/bin/python -Ot". % env --help Usage: env [OPTION]... [-] [NAME=VALUE]... [COMMAND [ARG]...] So it /should/ work... Why not? Thorsten From pythonTutor at venix.com Thu Apr 29 21:42:14 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Thu Apr 29 21:42:28 2004 Subject: [Tutor] cgi, fastcgi, mod_python In-Reply-To: <40915920.40009@cso.atmel.com> References: <40915920.40009@cso.atmel.com> Message-ID: <1083289333.3955.35.camel@laptop.venix.com> On Thu, 2004-04-29 at 15:36, Mike Hansen wrote: > Hello, > > I've recently started experimenting with Python to write web apps. My > first app did a little form processing using the cgi module. Performance > isn't a huge issue, but I'm curious on how to pep it up if the need > should arise. I'm a bit confused on other solutions like FastCGI and > Mod_Python. If I decided to use FastCGI, would I need to significantly > change my code? The main impetus for using fastCGI or Mod_Python is to avoid starting a whole new process for each HTTP transaction. This becomes an issue on very high traffic sites OR where your script needs to go through elaborate initialization routines. The jonpy module (from sourceforge) can simplify a fastCGI script. Jonpy provides a different interface to the parameters and environment as compared to the cgi module. However, it is easy to feed the jonpy parameters into the cgi module so that most of a fastCGI script is similar to a regular cgi script. Only the "startup logic" needs to be different. In a simple case, the startup logic is the call to cgi.fieldstorage which gets replaced by a jonpy cgihandler class which accepts the jonpy parameter objects. These can be fed to cgi.fieldstorage. Make the rest of the cgi script into a function that gets the cgi.fieldstorage object as a parameter. (I hope that made sense.) I have found that most web sites will work quite nicely through the regular cgi interface. Even establishing database connections each time the script is run normally works OK. The jonpy module provides a simple set of tools to handle the creation and re-use of resources such as database connections. > I didn't get the impression that you just install it, > modify your apache config, and import FastCGI in your code instead of > the cgi module. The same with Mod_Python. Could someone briefly explain > the differences in coding cgi, FastCGI, or Mod_Python if there are any > differences? fastCGI and Mod_python require more configuration of the web (apache) server. Mod_python allows for much tighter integration with the apache server. Each HTTP request goes through a series of steps within apache. Mod_python gives you the means to add scripting at each step. I have NOT done any mod_python scripting. I have not found fastCGI to be necessary. I keep a test server configured so that I can run fastCGI scripts and I practiced converting a couple of cgi scripts to fastCGI. It was NEVER necessary to actually deploy a fastCGI script into production. > > Thanks, > > Mike Hansen > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From david at graniteweb.com Thu Apr 29 21:47:27 2004 From: david at graniteweb.com (David Rock) Date: Thu Apr 29 21:47:30 2004 Subject: [Tutor] env shebang with options In-Reply-To: <1cau2djhoe168$.dlg@thorstenkampe.de> References: <1cau2djhoe168$.dlg@thorstenkampe.de> Message-ID: <20040430014726.GA22236@wdfs.graniteweb.com> * Thorsten Kampe [2004-04-30 01:13]: > I'm trying to set up a Python script with a shebang with options: > > % cat test.py > #! /usr/bin/env python -Ot > > % chmod 700 test.py; ./test.py > /usr/bin/env: python -Ot: No such file or directory Make sure that python is in your path. /usr/bin/env python should resolve to an actual location. Try doing this on the commandline and make sure you get what you think you should get: bash-2.05b$ echo $PATH /bin:/usr/bin:/usr/local/bin:/opt/bin:/usr/i686-pc-linux-gnu/gcc-bin/3.3:/usr/X11R6/bin:/opt/blackdown-jre-1.4.1/bin:/usr/qt/3/bin:/home/drock/bin bash-2.05b$ which python /usr/bin/python bash-2.05b$ env python Python 2.3.3 (#1, Jan 24 2004, 19:16:27) [GCC 3.2.3 20030422 (Gentoo Linux 1.4 3.2.3-r3, propolice)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> bash-2.05b$ export PATH=/bin bash-2.05b$ which python bash: which: command not found bash-2.05b$ env python env: python: No such file or directory -- David Rock david@graniteweb.com -------------- 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/20040429/ecc7c557/attachment.bin From arkamir at softhome.net Fri Apr 30 00:57:28 2004 From: arkamir at softhome.net (Conrad) Date: Fri Apr 30 00:57:36 2004 Subject: [Tutor] matrixes In-Reply-To: References: Message-ID: <1083301048.1781.48.camel@conradpc> Thanks for all the responses. I opted to solve the problem before I read the responses, so I'm a bit late getting back, but it was a lot of help. I'll get back to you with any more difficulties I encounter Thanks a lot p.s. No confusion Alan G :) From dyoo at hkn.eecs.berkeley.edu Fri Apr 30 01:28:38 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Apr 30 01:28:43 2004 Subject: [Tutor] exception question [submitting a bug fix to SF] In-Reply-To: <1083170715.6154.6.camel@pika> Message-ID: On Wed, 28 Apr 2004, Reggie Dugard wrote: > On Wed, 2004-04-28 at 06:38, Danny Yoo wrote: > > [Completely off tangent: by the way, near the bottom of the 'cgitb' code, > > something looks really weird: > > > > if self.logdir is not None: > > import os, tempfile > > suffix = ['.html', '.txt'][self.format=="html"] > > > > Is the condition for 'suffix' backwards, or am I reading this wrong?] > > >From this fragment, it looks backwards to me as well (the list should be > ['.txt', '.html']) Hi Reggie, Ok, thanks. I've sent a bug report to Sourceforge: https://sourceforge.net/tracker/index.php?func=detail&aid=945063&group_id=5470&atid=105470 So not only did Dave's question get answered, but we also did some work to squash a 'cgitb' bug. Not bad at all. *grin* Talk to you later! From dyoo at hkn.eecs.berkeley.edu Fri Apr 30 01:50:18 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Apr 30 01:50:26 2004 Subject: [Tutor] env shebang with options In-Reply-To: <1cau2djhoe168$.dlg@thorstenkampe.de> Message-ID: > According to Alex Martelli in "Python in a Nutshell" this should work: > > "On Unix-like systems, you can make a Python script directly > executable by setting the file's permission bits /x/ and /r/ and > beginning the script with a so called /shebang/ line, which is a first > line of the form: > #!/usr/bin/env python {options} > providing a path to the /python/ program." Hi Thorsten, Unfortunately, it looks like this may need to be a stronger condition: I think that only BSD-ish systems support passing extra arguments through the shebang. Are you running on a Linux system? Let me check something... http://homepages.cwi.nl/~aeb/std/shebang/ Ok, after reading this a bit, I'm guessing that #!/usr/bin/env python {options} might not be so portable, as the shebang feature seems to behave subtly different between all the the Unices. Good luck to you! From firephreek at earthlink.net Fri Apr 30 13:28:59 2004 From: firephreek at earthlink.net (firephreek) Date: Fri Apr 30 13:37:50 2004 Subject: [Tutor] Coding philosophy Message-ID: <000d01c42ed8$9f8c6b50$6f01010a@Rachel> Is it 'wrong' to add fucntions to your program that only make the code 'easier' to read and write? For example, I'm working on that wxPython program, and rather than create a different name for each 'row' in the notebook layout, or even a numbered array, I 'enumerated' a dictionary so that I can reference a row by the name I give it. def RowEnum(self, parent, *args): parent.row = {} for i in args: parent.row[i] = wxBoxSizer(wxHORIZONTAL) return parent.row Instead of: parent.VendorId = wxBoxSizer(wxHORIZONTAL) parent.VendorName = wxBoxSizer(wxHORIZONTAL) parent.RowSpacer = wxBoxSizer(wxHORIZONTAL) parent.VendorItemID = wxBoxSizer(wxHORIZONTAL) Etc... The idea (imo-head) was that each time I wanted to add or remove a 'row' of stuff, I could just add the name to the caller, and not worry about typing everything out. I figured it'd make my code more readable and make more sense. Is that 'ethical'? Silly question I suppose, but I guess it's kinda in my head that I shouldn't waste resources just so I can be lazy. So sue me, I'm an american. Hah. Stryder The rest of the specifc function that uses this is below. Hope that's ok. Figured that'd help the context of this question a bit more. There will be other notebook pages, so I can reuse this function. ************************************************************************ ********************************* def OnInput(self, e): panel = wxPanel(self.itemInput, -1) panel.column = wxBoxSizer(wxVERTICAL) row = self.RowEnum(panel, 'VendorID', 'VendorName', 'RowSpacer') VendorID_list = ['1','2','3','4','5','6','7'] #these two lines will consolidate to a dictionary. VendorName_list = ['one', 'two', 'three', 'four', 'five', 'six', 'seven'] row['RowSpacer'].Add((60, 7), 0, wxEXPAND) #an empty spacer # TEXT: |Combo Box| row['VendorID'].Add(wxStaticText(panel, -1, "Vendor ID#: "), flag = wxTOP, border = 4) row['VendorID'].Add(wxComboBox(panel, ID_VENDOR_ID, "123456", None,(70,-1), VendorID_list, wxCB_DROPDOWN #|wxTE_PROCESS_ENTER )) # TEXT: |COMBOBOX| |BUTTON| row['VendorName'].Add(wxStaticText(panel,-1, "Vendor Name: "), flag = wxTOP, border = 4) row['VendorName'].Add(wxComboBox(panel, ID_VENDOR_NAME, "", None, (150, -1), VendorName_list, wxCB_DROPDOWN )) b_moreInfo = wxButton(panel, ID_MORE_INFO_BUTTON, "More Info...") b_moreInfo.SetToolTipString("Get More Info On This Vendor...") row['VendorName'].Add((15,10),0,wxEXPAND) row['VendorName'].Add(b_moreInfo, flag = wxTOP) #put it all together panel.column.Add(panel.row['RowSpacer'], 0, wxALIGN_LEFT) panel.column.Add(panel.row['VendorID'], 0, wxALIGN_LEFT) panel.column.Add(panel.row['RowSpacer'], 0, wxALIGN_LEFT) panel.column.Add(panel.row['VendorName'], 0, wxALIGN_LEFT) panel.column.Add(panel.row['RowSpacer'], 0, wxALIGN_LEFT) panel.SetSizer(panel.column) panel.SetAutoLayout(1) self.Show(1) self.itemInput.AddPage(panel, "Item Input") From david at graniteweb.com Fri Apr 30 17:08:55 2004 From: david at graniteweb.com (David Rock) Date: Fri Apr 30 17:09:03 2004 Subject: [Tutor] Coding philosophy In-Reply-To: <000d01c42ed8$9f8c6b50$6f01010a@Rachel> References: <000d01c42ed8$9f8c6b50$6f01010a@Rachel> Message-ID: <20040430210855.GA24676@wdfs.graniteweb.com> * firephreek [2004-04-30 10:28]: > Is it 'wrong' to add fucntions to your program that only make the code > 'easier' to read and write? > > For example, I'm working on that wxPython program, and rather than > create a different name for each 'row' in the notebook layout, or even a > numbered array, I 'enumerated' a dictionary so that I can reference a > row by the name I give it. Nothing wrong with it at all. Actually, it's very Pythonic to make something more readable. -- David Rock david@graniteweb.com -------------- 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/20040430/4dcdf755/attachment.bin From mhansen at cso.atmel.com Fri Apr 30 17:47:01 2004 From: mhansen at cso.atmel.com (Mike Hansen) Date: Fri Apr 30 17:46:52 2004 Subject: [Tutor] cgi, fastcgi, mod_python In-Reply-To: <1083289333.3955.35.camel@laptop.venix.com> References: <40915920.40009@cso.atmel.com> <1083289333.3955.35.camel@laptop.venix.com> Message-ID: <4092C955.9070309@cso.atmel.com> Thanks for the info. It's good to hear that cgi does the job and that the other options might not be necessary. I'll also keep jonpy in mind if it becomes necessary to use FastCGI. Next up, I'm going to experiment with htmltemplate. Mike Lloyd Kvam wrote: >On Thu, 2004-04-29 at 15:36, Mike Hansen wrote: > > >>Hello, >> >>I've recently started experimenting with Python to write web apps. My >>first app did a little form processing using the cgi module. Performance >>isn't a huge issue, but I'm curious on how to pep it up if the need >>should arise. I'm a bit confused on other solutions like FastCGI and >>Mod_Python. If I decided to use FastCGI, would I need to significantly >>change my code? >> >> > >The main impetus for using fastCGI or Mod_Python is to avoid starting a >whole new process for each HTTP transaction. This becomes an issue on >very high traffic sites OR where your script needs to go through >elaborate initialization routines. The jonpy module (from sourceforge) >can simplify a fastCGI script. Jonpy provides a different interface to >the parameters and environment as compared to the cgi module. However, >it is easy to feed the jonpy parameters into the cgi module so that most >of a fastCGI script is similar to a regular cgi script. Only the >"startup logic" needs to be different. In a simple case, the startup >logic is the call to cgi.fieldstorage which gets replaced by a jonpy >cgihandler class which accepts the jonpy parameter objects. These can >be fed to cgi.fieldstorage. Make the rest of the cgi script into a >function that gets the cgi.fieldstorage object as a parameter. (I hope >that made sense.) > >I have found that most web sites will work quite nicely through the >regular cgi interface. Even establishing database connections each time >the script is run normally works OK. > >The jonpy module provides a simple set of tools to handle the creation >and re-use of resources such as database connections. > > > >>I didn't get the impression that you just install it, >>modify your apache config, and import FastCGI in your code instead of >>the cgi module. The same with Mod_Python. Could someone briefly explain >>the differences in coding cgi, FastCGI, or Mod_Python if there are any >>differences? >> >> > >fastCGI and Mod_python require more configuration of the web (apache) >server. Mod_python allows for much tighter integration with the apache >server. Each HTTP request goes through a series of steps within >apache. Mod_python gives you the means to add scripting at each step. > >I have NOT done any mod_python scripting. I have not found fastCGI to >be necessary. I keep a test server configured so that I can run fastCGI >scripts and I practiced converting a couple of cgi scripts to fastCGI. >It was NEVER necessary to actually deploy a fastCGI script into >production. > > > >>Thanks, >> >>Mike Hansen >> >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor >> >> From project5 at redrival.net Fri Apr 30 17:48:51 2004 From: project5 at redrival.net (Andrei) Date: Fri Apr 30 17:48:59 2004 Subject: [Tutor] Re: Coding philosophy References: <000d01c42ed8$9f8c6b50$6f01010a@Rachel> Message-ID: <6rdbgdqxc6fh$.hcivry7j123h.dlg@40tude.net> firephreek wrote on Fri, 30 Apr 2004 10:28:59 -0700: > Is it 'wrong' to add fucntions to your program that only make the code > 'easier' to read and write? It's wrong NOT to add them and make your program hard to read and maintain because of it. :) > For example, I'm working on that wxPython program, and rather than > create a different name for each 'row' in the notebook layout, or even a > numbered array, I 'enumerated' a dictionary so that I can reference a > row by the name I give it. I'm not sure the change in this particular case will save you a lot of time or maintenance worries, but I don't think it's wrong. > The idea (imo-head) was that each time I wanted to add or remove a 'row' > of stuff, I could just add the name to the caller, and not worry about > typing everything out. The reason I don't think it will make much of a difference is that IMO the function you wrote could do a little bit more work :). As it stands, it just creates the rows and then you still have to do all that manual work of adding labels, sizers, etc. to them. You could devise a system which lets you pass certain parameters to the function and then creates the rows with all appropriate contents already in place. In that way, when you need to add new rows, you just modify the one function call and are done. > I figured it'd make my code more readable and make more sense. Is that > 'ethical'? Silly question I suppose, but I guess it's kinda in my head > that I shouldn't waste resources just so I can be lazy. So sue me, I'm > an american. Hah. Waste computer resources all you like when it saves human resources :). As long as the result doesn't perform badly from a human's POV (and humans really are quite slow, they'll never notice a few microseconds at startup), there's really no point in worrying over performance. In fact, you can fool humans into thinking something is fast when it's not by distracting their attention with shiny objects, like splash screens, dynamic progress bars and labels with captions changing too quickly for us to read :). -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From dyoo at hkn.eecs.berkeley.edu Fri Apr 30 18:42:32 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Apr 30 18:42:40 2004 Subject: [Tutor] GUI component (fwd) Message-ID: [I'm forwarding Bintang's request to tutor@python.org. I currently don't have Tkinter installed on my laptop, so I can't show Bintang an example PMW install. Can anyone else help? Thanks!] ---------- Forwarded message ---------- Date: Fri, 30 Apr 2004 03:26:40 -0700 (PDT) From: bintang kurniawan To: Danny Yoo Subject: Re: [Tutor] GUI component thank you for your guide, i have the file but icant install (load) it to my python please give advise thanks, rgds, bintang Danny Yoo wrote: On Thu, 22 Apr 2004, bintang kurniawan wrote: > im new beginer in python laguage, and would like to now more on GUI > programming (TK inter). my question is : Hi Bintang, Ah! Ok, there's a lot of tutorials on Tkinter here: http://www.python.org/topics/tkinter/doc.html > 1. how to inherrit component and add some additional function to it. The example here: http://www.python.org/doc/current/lib/node633.html shows how to inherit from a Tkinter frame; we can do the same extension to other widgets by inheritance. > 2. where can i find Combobox and DataGrid component? and how to install > to the python environtment? Those two widgets are part of an Tkinter extention called the Python Megawidgets (PMW). You can find the PMW here: http://pmw.sourceforge.net/ If you have more questions, please feel free to ask! --------------------------------- Do you Yahoo!? Win a $20,000 Career Makeover at Yahoo! HotJobs From tpc at csua.berkeley.edu Fri Apr 30 19:21:34 2004 From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu) Date: Fri Apr 30 19:21:40 2004 Subject: [Tutor] double backslash in Windows paths Message-ID: <20040430162118.N70165-100000@localhost.name> hi everybody, what do you guys use to convert a Windows path, with single backslash, to double backslash ? I ask this because I've been using os.path.normpath, and it leaves A LOT to be desired. If you pass it a path, and say some directory in the path starts with a number, os.path.normpath WILL mangle the path by inserting a '\x{hex value}' instead of the desired behavior, '\\{dirname}'. Then you have to go back and clean up and add in the extra backslash in the string before using it. From klappnase at freenet.de Fri Apr 30 19:38:05 2004 From: klappnase at freenet.de (Michael Lange) Date: Fri Apr 30 19:39:17 2004 Subject: [Tutor] GUI component (fwd) In-Reply-To: References: Message-ID: <20040501013805.584e1314.klappnase@freenet.de> > ---------- Forwarded message ---------- > Date: Fri, 30 Apr 2004 03:26:40 -0700 (PDT) > From: bintang kurniawan > To: Danny Yoo > Subject: Re: [Tutor] GUI component > > thank you for your guide, > i have the file but icant install (load) it to my python > please give advise > > thanks, > > rgds, > > bintang > Hi Bintang, I am not sure if I understand your problem correctly, does the installation of Pmw fail or is it installed and does not work? If it is the installation I think you just need to unzip the archive and copy the Pmw folder to your site-packages directory ( something like c:\python2.3\site-packages on windows or /usr/lib/python2.3/site-packages on linux/unix systems ). After that you can try at the python prompt: >>> import Pmw >>> root = Pmw.initialise() >>> If this works and an empty window pops up everything is fine and you are ready to use the Pmw widgets. I hope this helps Michael From pythonTutor at venix.com Fri Apr 30 20:00:55 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Fri Apr 30 20:01:09 2004 Subject: [Tutor] double backslash in Windows paths In-Reply-To: <20040430162118.N70165-100000@localhost.name> References: <20040430162118.N70165-100000@localhost.name> Message-ID: <1083369655.2115.12.camel@laptop.venix.com> >>> x = r'\a\b\c\d\e' >>> x '\\a\\b\\c\\d\\e' >>> print x \a\b\c\d\e >>> repr(x) "'\\\\a\\\\b\\\\c\\\\d\\\\e'" >>> str(x) '\\a\\b\\c\\d\\e' The doubled backslashes are a convention for Python string literals. They are NOT actually part of the string. normpath will give you exactly what you really want. The problem comes from the grief you (and Python) go through when interpreting string literals for evaluation into the desired internal string. As you can see from the above examples, it can be pretty tricky to relate the actual contents of a string that contains backslashes and the way the string gets displayed. x is initialized with single back slashes just the way you would want for DOS paths. x is never changed. All of the various appearances come from different display options that are available in Python. On Fri, 2004-04-30 at 19:21, tpc@csua.berkeley.edu wrote: > hi everybody, what do you guys use to convert a Windows path, with single > backslash, to double backslash ? I ask this because I've been using > os.path.normpath, and it leaves A LOT to be desired. If you pass it a > path, and say some directory in the path starts with a number, > os.path.normpath WILL mangle the path by inserting a '\x{hex value}' > instead of the desired behavior, '\\{dirname}'. Then you have to go back > and clean up and add in the extra backslash in the string before using it. > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582