From linuxasking at netscape.net Mon Feb 2 01:03:56 2004 From: linuxasking at netscape.net (Xuer) Date: Sat Jan 31 01:05:14 2004 Subject: [Tutor] "=" invalid syntax ? Message-ID: <401DE84C.8030707@netscape.net> print all lines of a simple file test.py ----------------------------------------------- #!/usr/bin/python try: fi = open('test.py', 'r') except IOError: print 'Can\'t open file for reading.' sys.exit(0) while (line=fi.readline()): print line ----------------------------------------------- then run it $./test.py File "./test.py", line 8 while (line=fi.readline()): ^ SyntaxError: invalid syntax what's the problem? thanks and regards :) From dyoo at hkn.eecs.berkeley.edu Sun Feb 1 00:03:02 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Feb 1 00:03:09 2004 Subject: [Tutor] "=" invalid syntax ? In-Reply-To: <20040131173532.GI5205@johnsons-web.com> Message-ID: <Pine.LNX.4.44.0401312041540.29043-100000@hkn.eecs.berkeley.edu> On Sat, 31 Jan 2004, Tim Johnson wrote: > > File "./test.py", line 8 > > while (line=fi.readline()): > > ^ > > SyntaxError: invalid syntax > > > > what's the problem? > > while (line=fi.readline()): > > '=' is an assignment operator in python. > '==' is the comparison operator in python. > use '==' > > happens to me all the time .... Hi Tim, Changing '=' to '==' will make it syntactically correct, but it won't preserve the intended meaning. Xuer appears to be using a C-ish syntax: in the C language, it's legal to say something like: while((ch = getc(stdin)) != EOF) { ... } In the C language, assignment is treated as an "expression" that can be nested within other expressions, so the above C code mixes together an assigment with a comparison. Very succinct, but also very error prone. In Python, assignment is treated as a "statement". The thing that distinguishes a "statement" from an "expression" is that a statement isn't very nestable within another statement. This prevents certain mistakes (like using 'assignment' on accident, when we really mean 'equality test'), but at the cost of being more verbose. That should explain why we're getting a SyntaxError out of: > > File "./test.py", line 8 > > while (line=fi.readline()): > > ^ > > SyntaxError: invalid syntax because the assignment statement can't nest within the while statement. How do we fix this? To get the direct effect of ### while (line=fi.readline()): ## pseudo-C/Python ... ### with the 'while' loop, we must break it up into separate statements: ### while 1: line = fi.readline() if not line: break ... ### But this ends up being longer than the equivalent code in C! Is there a better way to say this? There's actually an alternative that's available in recent versions of Python, if we use the 'for' loop: ### for line in fi: ... ### This has almost the same effect as the original code, and it scans well too. It takes advantage of the widespread support of 'iterators' into the Python language, and here, we treat the file as an iterable object that we can loop across. Hope this helps! From dyoo at hkn.eecs.berkeley.edu Sun Feb 1 00:19:44 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Feb 1 00:19:49 2004 Subject: [Tutor] "=" invalid syntax ? [Assignment grammar stuff] In-Reply-To: <20040131162728.2908c5fb.orbitz@ezabel.com> Message-ID: <Pine.LNX.4.44.0401312107270.29043-100000@hkn.eecs.berkeley.edu> On Sat, 31 Jan 2004 orbitz@ezabel.com wrote: > I just learned this recently, but if you say = is a statement then you > would imagine: > > a = b = 2 to not work. = is actually special cased for this to work. > however > a = (b = 2) does not work. There is some 'magic' some people might say > to =, but I think a = b = .. is the only excpetion to the = is a > statement operator rule. Hi orbitz, If people are interested in how it's special cased, the Reference Manual has the gory details. *grin* The grammar definition in: http://www.python.org/doc/ref/assignment.html shows that assignment_stmt ::= (target_list "=")+ expression_list That is, an assignment statement is made up of a number of targets, followed by the expression that will be assigned to those targets. Usually, we define a single target, but nothing stops us from defining multiple targets. If we're looking at somthing like: a = b = 2 then we can see that a = b = matches (target_list "=")+ and 2 matches expression_list If we look at the grammar, we can also see that assignment allows for a limited form of pattern matching --- it's possible to say something like: ### >>> p1 = (x1, y1) = (3, 17) >>> p1 (3, 17) >>> x1 3 >>> y1 17 ### Hope this helps! From isrgish at fusemail.com Sun Feb 1 01:03:31 2004 From: isrgish at fusemail.com (Isr Gish) Date: Sun Feb 1 01:03:36 2004 Subject: [Tutor] Converting string or list to sum Message-ID: <E1AnAhf-0008N5-GB@fuse1.fusemail.net> Thanks I had rebound the variable str. Isr -----Original Message----- >From: "Terry Carroll"<carroll@tjc.com> >Sent: 1/31/04 9:47:23 PM >To: "tutor@python.org"<tutor@python.org> >Subject: Re: Re: [Tutor] Converting string or list to sum > >On Sat, 31 Jan 2004, Isr Gish wrote: > >> When I try doing. >> map(str, a) >> I got a traceback >> TypeError: 'str' object is not callable >> But when I do, >> map(__builtin__.str, a) >> It works fine. > >did you rebind the variable name str elsewhere in your program, e.g., > >>>> a=['1','2','3'] >>>> a >['1', '2', '3'] >>>> d=''.join(map(str,a)) >>>> d >'123' >>>> str="xyz" >>>> d=''.join(map(str,a)) >Traceback (most recent call last): > File "<stdin>", line 1, in ? >TypeError: 'str' object is not callable >>>> > > > > > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > From project5 at redrival.net Sun Feb 1 07:10:00 2004 From: project5 at redrival.net (Andrei) Date: Sun Feb 1 07:13:07 2004 Subject: [Tutor] Re: .tar.gz in Py References: <401B2AE4.5090107@netzero.net> <18j8mrbjmj000$.ireckbqsmp5u.dlg@40tude.net> <20040131222126.15808966@phatbox.local> Message-ID: <z6h249jb2dgs.tp256rle53jr.dlg@40tude.net> Nick Lunt wrote on Sat, 31 Jan 2004 22:21:26 +0000: Thanks, Nick. That's a lot easier than I expected. The possible errors aren't a problem for me because I am pretty certain that my dirs and their contents are "safe" since the script where I'll use it creates those dirs and files itself. > I asked a tar question myself yesterday and included my problematic program. Here it is - > > # CODE > > """ > tar.py: > Usage: > tar.py filetocreate.tar list_of_files_to_tar > > imports: > tarfile - to do the tarring > sys - to manipulate command line args > """ > > # Fails in the if block on os.access when dirs are submitted as args. > # ie the dir submitted is readable but some files below it may not be, > # which the if os.access() does not pick up. > # So create a new function to walk the dir and only return the files it can > # backup successfully, but print a list of the ones it cant. > > <snip> > As you can see from the comments in my code it is not perfect yet, but it will hopefully show you how to use the tar module, and it will create a tar file for you. > > There is also a gzip module you can import to gzip the tar file, but I've not got my head round that yet as the tar part is not 100%, but that is my plans for it. Then it's going to write it to CD. Then I'd like to make a GUI for it, just to learn how to ;) Oh yeah, the final version is also gonna be OOP. > -- Yours, Andrei ===== Mail address in header catches spam. 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 red_necks25 at yahoo.com Sun Feb 1 16:11:08 2004 From: red_necks25 at yahoo.com (moore william) Date: Sun Feb 1 16:13:26 2004 Subject: [Tutor] Activating a box Message-ID: <20040201211108.15838.qmail@web13609.mail.yahoo.com> I am adding boxes to my program and am looking for informatioin to get my box to activate diffrent parts of my program. Anyone have a toutorial on this? Example: (BOX) # File: toolbar1.py from Tkinter import * root = Tk() def Deposite(): print "Amount:" # create a toolbar toolbar = Frame(root) b = Button(toolbar, text="Deposite", width=10, command=Deposite) b.pack(side=LEFT, padx=2, pady=2) b = Button(toolbar, text="Withdraw", width=10, command=Deposite) b.pack(side=LEFT, padx=2, pady=2) toolbar.pack(side=TOP, fill=X) mainloop() (Action) # I added the exception line so that negartive numbers woudl not be added. if choice == 1: amount = raw_input ('Amount: ') elif amount < 0: raise ValueError, 'Deposites must be positive' elif self.balance - amount < 0: raise ValueError, 'The account only holds $' + str(self.balance) self._perform_transaction(-amount) date = raw_input ('Date: ') numbers[amount] = date __________________________________ Do you Yahoo!? Yahoo! SiteBuilder - Free web site building tool. Try it! http://webhosting.yahoo.com/ps/sb/ From alan.gauld at blueyonder.co.uk Sun Feb 1 18:05:37 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Feb 1 18:07:24 2004 Subject: [Tutor] Buttons References: <20040201023500.51351.qmail@web13608.mail.yahoo.com> Message-ID: <00f901c3e917$e7f24600$6401a8c0@xp> > I have a cash program that I am trying to create > buttons for instead of a simple number menu. I > understand that I need to import the Tkinter, create > and position the widgets, and enter the main loop Yes, but of course you aren't doing any of that here... > (Python in a nut shell). But I am still having > problems. I have attached the code It would help if you gave us a clue as to what the problems were? They obviously are not related to the Buttons since there is no Tkinter code here. I'll try to add some comments.... > class AccountTransaction(object): > def __init__(self, amount, time): > self.amount = amount > self.time = time Not sure why you are using a new style class here, especially given that you use old stuyle classes later on. But it shouldn't cause any real problems. > def __repr__(self): > description = time.ctime(self.time) + ' ' > if self.amount < 0: > description += '-' > description += '$' + str(abs(self.amount)) > return description This would be much easier with a format string, something like: description += "%s$%05.2s" % (sign, self.amount) Set the sign using the code above or the simpler(IMHO!): sign = (sign < 0 and '-') or '' > def __init__(self, initial): > self.balance = amount Not sure why we have two init methods? This will replace the first one. If you come from Java or C++ maybe you are used to multiple constructors but you can't do that in Python, sorry. > while 1: > print > print > print 'Show Me The Money' > print '1. Deposite' > print '2. Withdraw' > print '3. Getbalance' > print '9. Quit' > print > choice = int(raw_input('Enter your choice: ')) Lots of print statements are usually better done with a triple quoted string and/or a format string. In this case: print ''' Show Me The Money 1. Deposit 2. Withdraw 3. Getbalance 9. Quit ''' > # I added the exception line so that negartive > numbers woudl not be added. > > if choice == 1: > amount = raw_input ('Amount: ') > elif amount < 0: > raise ValueError, 'Deposites must be positive' This only gets called if choice is not 1. That is it will not check the value input by the user. Even if it did you would be comparing a string and a number, you need to convert the raw_input() value to an int. > elif self.balance - amount < 0: Again, this only gets called if choice is not 1 and amount is positive. I suspect you want these tests all to be plain if statements nested under the if choice === 1?. > date = raw_input ('Date: ') > numbers[amount] = date If you are storing a date why not convert it to a date and store that? Its probably easier to manipulate later. There is a third party date module (mxdate?) that you might find easier to use that the standard time module. > elif choice == 2: > amount = raw_input ('Amount: ') > if amount < 0: > raise ValueError, 'Withdrawals must be This will mostly work as you expect, but mainly by accident. If none of the tests above are true then you will do the choice test, then because the elif chain is stopped ypu will do the 'if amount' test I suspect the structure you really want is: if choice == 1: # get the amount # if amount < 0 : raise error # elif balance-amount < 0 : raise error elif choice == 2: # get amount # if amount < 0: raise error # etc elif choice == 3: # and so on. elif choice == 9: # and here else: # finally... > class Account: > def Deposit(self, amt): > self.balance = self.balance + amt > def Withdraw(self,amt): > self.balance = self.balance - amt > def getbalance(self): > return self.balance You never set balance(no init method?) so any attempt to call the methods will fail because self.balance has not been defined before use. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From Harm_Kirchhoff at mail.digital.co.jp Sun Feb 1 19:54:07 2004 From: Harm_Kirchhoff at mail.digital.co.jp (Harm_Kirchhoff@mail.digital.co.jp) Date: Sun Feb 1 19:55:00 2004 Subject: [Tutor] How to close a file opened with csv.write Message-ID: <OFC083489C.8447E81D-ON49256E2E.00046FF1-49256E2E.0004C622@jp.schneider-electric.com> Thanks Gerrit, that was a good tip. I had been wondering about this for some time and I know others, too. Is there a way this could be included into the python docu for the csv module ? From python at keep-trying.com Sun Feb 1 20:31:56 2004 From: python at keep-trying.com (richard) Date: Sun Feb 1 20:32:26 2004 Subject: [Tutor] Piping stdout to external Program Message-ID: <6.0.0.22.0.20040202011856.01eaf8b8@192.168.5.1> Folks, Having given up on my dialog box problem for moment. I have progressed onto other things. I am attempting to create and preview pdf reports. I have no problems creating the pdf saving it to disk then manually opening it using reportlabs.What I wish to do is pipe the pdf straight to acrobat reader. This is what I have so far: (To get the pdf output -> c.save() ) The function is to escape the spaces correctly. (taken for the newsgroups) >>> def _quote(*args): ... fmt = max(map(lambda s: len(string.split(s)), args))>1 and '"%s"' or '%s' ... return fmt % string.join(map(lambda s: len(string.split(s))>1 and '"%s"' % s or s, args),' ') os.system(_quote(r'C:\Program Files\Adobe\Acrobat 6.0\Reader\AcroRd32.exe', c.save())) This gets me the following: (1) A new command/dos box which locks python (2) After waiting a minute dismissing the dos box results in Acrobat coming up minus the document (3) The pdf document is simply outputted to the screen. Similar problems with popen. Is it possible to do this?? XP,Python 2.3 Regards Richard From littledanehren at yahoo.com Sun Feb 1 21:00:27 2004 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Sun Feb 1 21:00:32 2004 Subject: [Tutor] "=" invalid syntax ? In-Reply-To: <401C201B.9060403@venix.com> Message-ID: <20040202020027.66211.qmail@web41813.mail.yahoo.com> > try/except and try/finally are two different forms. > There is no try/except/finally. > > (thanks to Alex Martelli) it should look more like: > > try: > try: > fi = open('test.py', 'r') > except IOError: > print "Can't open file for reading." > else: > for line in fi: > print line > finally: > fi.close() > > The else is a convenient to limit the scope of the > try statement. > > The exceptions chapter of "Python in a Nutshell" has > very lucid descriptions > of exception handling strategies. I'm probably making some big mistake again, but if you're using both except and else, why not just write: try: fi = open('test.py', 'r') except IOError: print "Can't open file for reading." else: for line in fi: print line fi.close() Daniel Ehrenberg __________________________________ Do you Yahoo!? Yahoo! SiteBuilder - Free web site building tool. Try it! http://webhosting.yahoo.com/ps/sb/ From littledanehren at yahoo.com Sun Feb 1 21:05:06 2004 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Sun Feb 1 21:05:14 2004 Subject: [Tutor] Visitor Pattern Message-ID: <20040202020506.31323.qmail@web41803.mail.yahoo.com> What is a visitor pattern? I've heard that it shows how good a language is, and that Lisp is really good because it can be done in two (cryptic) lines. How can a visitor pattern be implimented in Python? Daniel Ehrenberg __________________________________ Do you Yahoo!? Yahoo! SiteBuilder - Free web site building tool. Try it! http://webhosting.yahoo.com/ps/sb/ From pythontutor at venix.com Sun Feb 1 21:36:31 2004 From: pythontutor at venix.com (Lloyd Kvam) Date: Sun Feb 1 21:36:29 2004 Subject: [Tutor] "=" invalid syntax ? In-Reply-To: <20040202020013.30010.qmail@web41802.mail.yahoo.com> References: <20040202020013.30010.qmail@web41802.mail.yahoo.com> Message-ID: <401DB7AF.3050202@venix.com> Daniel Ehrenberg wrote: >>try/except and try/finally are two different forms. >>There is no try/except/finally. >> >>(thanks to Alex Martelli) it should look more like: >> >>try: >> try: >> fi = open('test.py', 'r') >> except IOError: >> print "Can't open file for reading." >> else: >> for line in fi: >> print line >>finally: >> fi.close() >> >>The else is a convenient to limit the scope of the >>try statement. >> >>The exceptions chapter of "Python in a Nutshell" has >>very lucid descriptions >>of exception handling strategies. > > > I'm probably making some big mistake again, but if > you're using both except and else, why not just write: > > try: > fi = open('test.py', 'r') > except IOError: > print "Can't open file for reading." > else: > for line in fi: > print line > > fi.close() > > Daniel Ehrenberg In actual practise, that is what I'd write. I was just showing the general approach to having finally and except for the same block of code. Typically try/finally encloses a "logically" large block of cade and simply guarantees that a log entry will get written or that a file or other resource will get closed. try/except usually covers small blocks of code. It also provides general recovery control for applications that must continue after an exception is raised. -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From littledanehren at yahoo.com Mon Feb 2 12:52:13 2004 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Mon Feb 2 12:52:19 2004 Subject: [Tutor] "=" invalid syntax ? In-Reply-To: <20040131162728.2908c5fb.orbitz@ezabel.com> Message-ID: <20040202175213.58433.qmail@web41808.mail.yahoo.com> orbitz@ezabel.com wrote: > I just learned this recently, but if you say = is a > statement then you > would imagine: > > a = b = 2 to not work. = is actually special cased > for this to work. > however > a = (b = 2) does not work. There is some 'magic' > some people might say > to =, but I think a = b = .. is the only excpetion > to the = is a > statement operator rule. Yeah, it's just an exception to the rule. Daniel Ehrenberg __________________________________ Do you Yahoo!? Yahoo! SiteBuilder - Free web site building tool. Try it! http://webhosting.yahoo.com/ps/sb/ From darnold02 at sprynet.com Mon Feb 2 12:42:14 2004 From: darnold02 at sprynet.com (don arnold) Date: Mon Feb 2 12:56:26 2004 Subject: [Tutor] Activating a box References: <20040201211108.15838.qmail@web13609.mail.yahoo.com> Message-ID: <038f01c3e9b3$e68db410$7210ba3f@don2uvsu54fwiq> ----- Original Message ----- From: "moore william" <red_necks25@yahoo.com> To: "Python" <Tutor@python.org> Sent: Sunday, February 01, 2004 3:11 PM Subject: [Tutor] Activating a box > I am adding boxes to my program and am looking for > informatioin to get my box to activate diffrent parts > of my program. Anyone have a toutorial on this? > > Example: > <snip> Well, I was hoping someone more knowledgeable than I in Tkinter (i.e.: just about anyone) would field this, but here goes: First, we'll import the modules we need: from Tkinter import * from tkSimpleDialog import askfloat from tkMessageBox import showinfo We'll be using the askfloat and showinfo functions to create simple dialogs. The tkSimpleDialog and tkMessageBox modules are given just a passing mention in the Python Library Reference under Tkinter, but you can use the online help system to get more info on them (type 'help(modulename)' at the interactive prompt). When using Tkinter, all input and output is done through widgets. So we want to isolate the actual program logic from the user input/output routines. We'll create a simple Account class that represents an account, and an App class that provides the user interface. Here's the Account class: class Account: def __init__(self): self.balance = 0.0 def deposit(self, amount): self.balance += amount def withdraw(self, amount): self.balance -= amount def getBalance(self): return self.balance The App class contains the interface logic, and an Account instance that its widgets will interact with. It's pretty straightforward, so commenting is minimal: class App: def __init__(self, master): ''' creates an Account instance and presents the button menu ''' self.account = Account() ## menu button texts and the actions they invoke buttons = (('Deposit', self.doDeposit), ('Withdraw', self.doWithdraw), ('Get Balance', self.showBalance), ('Exit',root.destroy) ) f = Frame(master) for bText, bCommand in buttons: Button(f,text=bText,command=bCommand).pack(fill=X, side=TOP) f.pack() def doDeposit(self): ''' prompt user for amount of deposit. don't allow negative values. apply amount to the account. ''' retval = askfloat('Deposit', 'Amount of deposit:', minvalue = 0) if retval != None: self.account.deposit(retval) def doWithdraw(self): ''' prompt user for amount of withdrawal. don't allow negative values or an amount greater than the current balance. apply amount to the account. ''' retval = askfloat('Withdrawal', 'Amount of withdrawal:', minvalue = 0, maxvalue = self.account.getBalance()) if retval != None: self.account.withdraw(retval) def showBalance(self): ''' show the current balance ''' showinfo('Account Balance', 'Current account balance is $%12.2f' % self.account.getBalance()) And finally, the logic to initialise Tkinter and start the application: root = Tk() theApp = App(root) root.mainloop() Since some long lines will probably get mangled in the mail, I've also attached the source code. Hopefully, that will give you something to work with. HTH, Don -------------- next part -------------- from Tkinter import * from tkSimpleDialog import askfloat from tkMessageBox import showinfo class Account: def __init__(self): self.balance = 0.0 def deposit(self, amount): self.balance += amount def withdraw(self, amount): self.balance -= amount def getBalance(self): return self.balance class App: def __init__(self, master): ''' creates an Account instance and presents the button menu ''' self.account = Account() ## menu button texts and the actions they invoke buttons = (('Deposit', self.doDeposit), ('Withdraw', self.doWithdraw), ('Get Balance', self.showBalance), ('Exit',root.destroy) ) f = Frame(master) for bText, bCommand in buttons: Button(f,text=bText,command=bCommand).pack(fill=X, side=TOP) f.pack() def doDeposit(self): ''' prompt user for amount of deposit. don't allow negative values. apply amount to the account. ''' retval = askfloat('Deposit', 'Amount of deposit:', minvalue = 0) if retval != None: self.account.deposit(retval) def doWithdraw(self): ''' prompt user for amount of withdrawal. don't allow negative values or an amount greater than the current balance. apply amount to the account. ''' retval = askfloat('Withdrawal', 'Amount of withdrawal:', minvalue = 0, maxvalue = self.account.getBalance()) if retval != None: self.account.withdraw(retval) def showBalance(self): ''' show the current balance ''' showinfo('Account Balance', 'Current account balance is $%12.2f' % self.account.getBalance()) root = Tk() theApp = App(root) root.mainloop() From xthereal at bigfoot.com Mon Feb 2 13:12:08 2004 From: xthereal at bigfoot.com (steve) Date: Mon Feb 2 13:14:04 2004 Subject: [Tutor] Concatenating Strings into Variable Names? Message-ID: <20040202131208.F4F781C0.xthereal@bigfoot.com> Hello, I'm a day 1 complete newcomer to python and programming in general, so I apologize in advance for any stupid questions or code butchering that may follow... I'm trying to write my first program besides good old hello world. Is there a way to concatenate strings into a variable name? Here's a brief example of what i'm trying to do: choiceA_option1= 2.0 choiceA_option2= 3.0 choiceB_option1= 4.0 choiceB_option2= 5.0 choice=raw_input("Do you want choice A or B?") option=raw_input("Do you want option 1 or 2?") the_answer="choice" + choice + "_option" + option print the_answer When i run this, and type in A and 2, it sets the_answer as choiceA_ option2 and prints "choiceA_option2" as another string instead of the value 3.0. Is there a way to set the resulting concatenation of the_ answer as the variable name that i set previously, and not a literal string? Hope this question makes some sense, and sorry for any misuse of terms. Gotta start somewhere lol Thanks for any help! From darnold02 at sprynet.com Mon Feb 2 13:37:11 2004 From: darnold02 at sprynet.com (don arnold) Date: Mon Feb 2 13:37:44 2004 Subject: [Tutor] Concatenating Strings into Variable Names? References: <20040202131208.F4F781C0.xthereal@bigfoot.com> Message-ID: <040e01c3e9bb$94a36c00$7210ba3f@don2uvsu54fwiq> ----- Original Message ----- From: "steve" <xthereal@bigfoot.com> To: <tutor@python.org> Sent: Monday, February 02, 2004 12:12 PM Subject: [Tutor] Concatenating Strings into Variable Names? > Hello, > I'm a day 1 complete newcomer to python and programming in general, > so I apologize in advance for any stupid questions or code butchering > that may follow... > I'm trying to write my first program besides good old hello world. Is > there a way to concatenate strings into a variable name? Here's a > brief example of what i'm trying to do: > > choiceA_option1= 2.0 > choiceA_option2= 3.0 > choiceB_option1= 4.0 > choiceB_option2= 5.0 > > choice=raw_input("Do you want choice A or B?") > option=raw_input("Do you want option 1 or 2?") > > the_answer="choice" + choice + "_option" + option > > print the_answer > > > When i run this, and type in A and 2, it sets the_answer as choiceA_ > option2 and prints "choiceA_option2" as another string instead of the > value 3.0. Is there a way to set the resulting concatenation of the_ > answer as the variable name that i set previously, and not a literal > string? > This seems to be a very common question. Instead of using a 'regular' variable, you create a dictionary to hold your data. Then you use a string representing the variable's name as the key to that dictionary: myvars = {} myvars['choiceA_option1'] = 2.0 myvars['choiceA_option2'] = 3.0 myvars['choiceB_option1'] = 4.0 myvars['choiceB_option2'] = 5.0 choice=raw_input("Do you want choice A or B?") option=raw_input("Do you want option 1 or 2?") the_answer = "choice" + choice + "_option" + option if the_answer in myvars: print 'answer:', myvars[the_answer] else: print 'invalid choice/option combination' > Hope this question makes some sense, and sorry for any misuse of terms. > Gotta start somewhere lol > > Thanks for any help! HTH, Don From rmkrauter at yahoo.com Mon Feb 2 14:06:34 2004 From: rmkrauter at yahoo.com (Rich Krauter) Date: Mon Feb 2 14:11:30 2004 Subject: [Tutor] Concatenating Strings into Variable Names? In-Reply-To: <20040202131208.F4F781C0.xthereal@bigfoot.com> References: <20040202131208.F4F781C0.xthereal@bigfoot.com> Message-ID: <1075748793.4059.43.camel@vaio> > > print the_answer > You can test these out: try: print eval('the_answer') except: "Invalid choice" or print globals()['the_answer'] or print locals()['the_answer'] or print globals().get('the_answer',"Not a valid choice") or print locals().get('the_answer',"Not a valid choice") I hope others comment on the right way - I'm interested in which is considered the best, if any. The dictionary method posted by Don is good too. The first and last two examples above provide a check for invalid entries, similar to Don's method. Good luck. Rich From dyoo at hkn.eecs.berkeley.edu Mon Feb 2 14:13:38 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Feb 2 14:13:56 2004 Subject: [Tutor] Concatenating Strings into Variable Names? In-Reply-To: <040e01c3e9bb$94a36c00$7210ba3f@don2uvsu54fwiq> Message-ID: <Pine.LNX.4.44.0402021101230.25843-100000@hkn.eecs.berkeley.edu> > This seems to be a very common question. Instead of using a 'regular' > variable, you create a dictionary to hold your data. Then you use a > string representing the variable's name as the key to that dictionary: > > myvars = {} > myvars['choiceA_option1'] = 2.0 > myvars['choiceA_option2'] = 3.0 > myvars['choiceB_option1'] = 4.0 > myvars['choiceB_option2'] = 5.0 > > choice=raw_input("Do you want choice A or B?") > option=raw_input("Do you want option 1 or 2?") > > the_answer = "choice" + choice + "_option" + option > > if the_answer in myvars: > print 'answer:', myvars[the_answer] > else: > print 'invalid choice/option combination' Hi Steve, I agree with Don; a "dictionary" seems like a good way to represent these choices. All of these choices are related, so using a single dictionary container to hold them is probably a good idea to show that intent. Here's a variation on Don's program: ### all_choices = {} all_choices['A', '1'] = 2.0 all_choices['A', '2'] = 3.0 all_choices['B', '1'] = 4.0 all_choices['B', '2'] = 5.0 choice = raw_input("Do you want choice A or B?") option = raw_input("Do you want option 1 or 2?") if (choice, option) in all_choices: print 'answer:', all_choices[choice, option] else: print 'invalid choice/option combination' ### Python's dictionaries are versatile, because not only can we use numbers and strings as keys, but we're even allowed to use tuples! The code above does the same thing as Don's program, but instead of using strings as keys into the dictionary, we use the (choice, option) pair. Hope this helps! From tim at johnsons-web.com Mon Feb 2 15:57:55 2004 From: tim at johnsons-web.com (Tim Johnson) Date: Mon Feb 2 15:53:42 2004 Subject: [Tutor] lstrip() question In-Reply-To: <Pine.LNX.4.44.0402021101230.25843-100000@hkn.eecs.berkeley.edu> References: <040e01c3e9bb$94a36c00$7210ba3f@don2uvsu54fwiq> <Pine.LNX.4.44.0402021101230.25843-100000@hkn.eecs.berkeley.edu> Message-ID: <20040202205755.GB13611@johnsons-web.com> Hello All: I'd like to remove all leading occurance of a html break tag in a string such that "<br><br>test" => "test" and "<br>test<br>this" =>"test<br>this" It appears that lstrip() will not do this as this console session using version 2.2.2 seems to demonstrate: >>> tmp1 = 'real estate broker courtesy' >>> tmp2 = tmp1.lstrip('<br>') >>> tmp2 'eal estate broker courtesy' It looks like '<br>' is being treated as a set rather than a substring. (that's why the 'r' was removed) Is there a builtin python method to strip leading substrings? Or do I have to do something using startswidth()? Before I re-invent an existing wheel.... TIA tim -- Tim Johnson <tim@johnsons-web.com> http://www.alaska-internet-solutions.com From sigurd at 12move.de Mon Feb 2 16:17:14 2004 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Mon Feb 2 16:19:35 2004 Subject: [Tutor] lstrip() question In-Reply-To: <20040202205755.GB13611@johnsons-web.com> (Tim Johnson's message of "Mon, 2 Feb 2004 11:57:55 -0900") References: <040e01c3e9bb$94a36c00$7210ba3f@don2uvsu54fwiq> <Pine.LNX.4.44.0402021101230.25843-100000@hkn.eecs.berkeley.edu> <20040202205755.GB13611@johnsons-web.com> Message-ID: <m37jz52nlk.fsf@hamster.pflaesterer.de> On 2 Feb 2004, Tim Johnson <- tim@johnsons-web.com wrote: > It appears that lstrip() will not do this > as this console session using version 2.2.2 > seems to demonstrate: >>>> tmp1 = 'real estate broker courtesy' >>>> tmp2 = tmp1.lstrip('<br>') >>>> tmp2 > 'eal estate broker courtesy' > It looks like '<br>' is being treated as > a set rather than a substring. > (that's why the 'r' was removed) Yes; strip works with characters. > Is there a builtin > python method to strip leading substrings? Or do > I have to do something using startswidth()? I would use a regexp. >>> tmp1 = '<br>real estate broker courtesy' >>> import re >>> re.sub('^<br>*', '', tmp1) 'real estate broker courtesy' >>> tmp1 = 'real estate broker courtesy' >>> re.sub('^<br>*', '', tmp1) 'real estate broker courtesy' Karl -- Please do *not* send copies of replies to me. I read the list From WRSimoni at MAPLLC.com Mon Feb 2 16:16:15 2004 From: WRSimoni at MAPLLC.com (Simoni, Bill) Date: Mon Feb 2 16:30:16 2004 Subject: [Tutor] lstrip() question Message-ID: <DD0F81089B11A54A83A3270D9E1125E8646AD9@FDYEXC213.mgroupnet.com> > Hello All: > I'd like to remove all leading occurance of a html break tag > in a string such that > "<br><br>test" => "test" > and > "<br>test<br>this" =>"test<br>this" Hi Tim, off the top of my head, I came up with this: >>> def repstrip(s, sub): if s.startswith(sub): s = repstrip(s[len(sub):], sub) #strip the leading characters that match and try it again return s >>> print repstrip('real estate broker courtesy', '<br>') real estate broker courtesy >>> print repstrip('<br>real estate broker courtesy', '<br>') real estate broker courtesy >>> print repstrip('<br><br>real estate broker courtesy', '<br>') real estate broker courtesy >>> print repstrip('<br><br>real estate <br> broker courtesy', '<br>') real estate <br> broker courtesy There may be a better way to do this - if so, I'm sure someone else will post it soon. Bill From tim at johnsons-web.com Mon Feb 2 16:54:22 2004 From: tim at johnsons-web.com (Tim Johnson) Date: Mon Feb 2 16:50:13 2004 Subject: [Tutor] lstrip() question In-Reply-To: <m37jz52nlk.fsf@hamster.pflaesterer.de> References: <040e01c3e9bb$94a36c00$7210ba3f@don2uvsu54fwiq> <Pine.LNX.4.44.0402021101230.25843-100000@hkn.eecs.berkeley.edu> <20040202205755.GB13611@johnsons-web.com> <m37jz52nlk.fsf@hamster.pflaesterer.de> Message-ID: <20040202215422.GC13611@johnsons-web.com> Things Karl. Right on the money! * Karl Pfl?sterer <sigurd@12move.de> [040202 12:31]: > On 2 Feb 2004, Tim Johnson <- tim@johnsons-web.com wrote: > > > It appears that lstrip() will not do this > > as this console session using version 2.2.2 > > seems to demonstrate: > >>>> tmp1 = 'real estate broker courtesy' > >>>> tmp2 = tmp1.lstrip('<br>') > >>>> tmp2 > > 'eal estate broker courtesy' > > > It looks like '<br>' is being treated as > > a set rather than a substring. > > (that's why the 'r' was removed) > > Yes; strip works with characters. > > > Is there a builtin > > python method to strip leading substrings? Or do > > I have to do something using startswidth()? > > I would use a regexp. > > >>> tmp1 = '<br>real estate broker courtesy' > >>> import re > >>> re.sub('^<br>*', '', tmp1) > 'real estate broker courtesy' > >>> tmp1 = 'real estate broker courtesy' > >>> re.sub('^<br>*', '', tmp1) > 'real estate broker courtesy' > > > > Karl > -- > Please do *not* send copies of replies to me. > I read the list > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Tim Johnson <tim@johnsons-web.com> http://www.alaska-internet-solutions.com From darnold02 at sprynet.com Mon Feb 2 17:11:22 2004 From: darnold02 at sprynet.com (don arnold) Date: Mon Feb 2 17:12:04 2004 Subject: [Tutor] lstrip() question References: <040e01c3e9bb$94a36c00$7210ba3f@don2uvsu54fwiq><Pine.LNX.4.44.0402021101230.25843-100000@hkn.eecs.berkeley.edu><20040202205755.GB13611@johnsons-web.com> <m37jz52nlk.fsf@hamster.pflaesterer.de> Message-ID: <04fd01c3e9d9$817fd780$7210ba3f@don2uvsu54fwiq> ----- Original Message ----- From: "Karl Pfl?sterer" <sigurd@12move.de> To: <tutor@python.org> Sent: Monday, February 02, 2004 3:17 PM Subject: Re: [Tutor] lstrip() question > On 2 Feb 2004, Tim Johnson <- tim@johnsons-web.com wrote: > > > It appears that lstrip() will not do this > > as this console session using version 2.2.2 > > seems to demonstrate: > >>>> tmp1 = 'real estate broker courtesy' > >>>> tmp2 = tmp1.lstrip('<br>') > >>>> tmp2 > > 'eal estate broker courtesy' > > > It looks like '<br>' is being treated as > > a set rather than a substring. > > (that's why the 'r' was removed) > > Yes; strip works with characters. > > > Is there a builtin > > python method to strip leading substrings? Or do > > I have to do something using startswidth()? > > I would use a regexp. > > >>> tmp1 = '<br>real estate broker courtesy' > >>> import re > >>> re.sub('^<br>*', '', tmp1) > 'real estate broker courtesy' > >>> tmp1 = 'real estate broker courtesy' > >>> re.sub('^<br>*', '', tmp1) > 'real estate broker courtesy' > > Karl But this doesn't seem to quite work if there are multiple leading <br>'s. >>> tmp = '<br><br>real estate<br>broker<br>' >>> import re >>> re.sub('^<br>*','',tmp) '<br>real estate<br>broker<br>' I don't know much about regexes, but is this because only the very first occurrence is considered to be at the beginning of the line? I'm sure there is a regex way to do it, but you could just use a simple loop and startswith(): >>> tmp2 = tmp >>> while tmp2.startswith('<br>'): tmp2 = tmp2[4:] >>> tmp2 'real estate<br>broker<br>' >>> tmp2 = '<br><br><br>' >>> while tmp2.startswith('<br>'): tmp2 = tmp2[4:] >>> tmp2 '' >>> HTH, Don From tim at johnsons-web.com Mon Feb 2 17:29:33 2004 From: tim at johnsons-web.com (Tim Johnson) Date: Mon Feb 2 17:25:22 2004 Subject: [Tutor] lstrip() question In-Reply-To: <04fd01c3e9d9$817fd780$7210ba3f@don2uvsu54fwiq> References: <040e01c3e9bb$94a36c00$7210ba3f@don2uvsu54fwiq> <Pine.LNX.4.44.0402021101230.25843-100000@hkn.eecs.berkeley.edu> <20040202205755.GB13611@johnsons-web.com> <m37jz52nlk.fsf@hamster.pflaesterer.de> <04fd01c3e9d9$817fd780$7210ba3f@don2uvsu54fwiq> Message-ID: <20040202222933.GE13611@johnsons-web.com> * don arnold <darnold02@sprynet.com> [040202 13:22]: > ----- Original Message ----- > From: "Karl Pfl?sterer" <sigurd@12move.de> > To: <tutor@python.org> > Sent: Monday, February 02, 2004 3:17 PM > Subject: Re: [Tutor] lstrip() question > > > > > > I would use a regexp. > > > > >>> tmp1 = '<br>real estate broker courtesy' > > >>> import re > > >>> re.sub('^<br>*', '', tmp1) > > 'real estate broker courtesy' > > >>> tmp1 = 'real estate broker courtesy' > > >>> re.sub('^<br>*', '', tmp1) > > 'real estate broker courtesy' > > > > Karl > '<br>real estate<br>broker<br>' > > I don't know much about regexes, but is this because only the very first > occurrence is considered to be at the beginning of the line? I'm sure there > is a regex way to do it, but you could just use a simple loop and > startswith(): > > >>> tmp2 = tmp > >>> while tmp2.startswith('<br>'): tmp2 = tmp2[4:] > >>> tmp2 > 'real estate<br>broker<br>' > >>> tmp2 = '<br><br><br>' > >>> while tmp2.startswith('<br>'): tmp2 = tmp2[4:] > >>> tmp2 Actually what I am *really* looking for is a way to strip either specific tags (like '<br>' from the left *or* any number of tags. I'm a regex dunce myself, so am researching patterns as we speak, but your iteration is kind of what I have in mind. thanks! tj -- Tim Johnson <tim@johnsons-web.com> http://www.alaska-internet-solutions.com From sigurd at 12move.de Mon Feb 2 18:27:37 2004 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Mon Feb 2 18:27:57 2004 Subject: [Tutor] lstrip() question In-Reply-To: <04fd01c3e9d9$817fd780$7210ba3f@don2uvsu54fwiq> (don arnold's message of "Mon, 2 Feb 2004 16:11:22 -0600") References: <040e01c3e9bb$94a36c00$7210ba3f@don2uvsu54fwiq> <Pine.LNX.4.44.0402021101230.25843-100000@hkn.eecs.berkeley.edu> <20040202205755.GB13611@johnsons-web.com> <m37jz52nlk.fsf@hamster.pflaesterer.de> <04fd01c3e9d9$817fd780$7210ba3f@don2uvsu54fwiq> Message-ID: <m3y8rl13a0.fsf@hamster.pflaesterer.de> On 2 Feb 2004, don arnold <- darnold02@sprynet.com wrote: > But this doesn't seem to quite work if there are multiple leading <br>'s. >>>> tmp = '<br><br>real estate<br>broker<br>' >>>> import re >>>> re.sub('^<br>*','',tmp) > '<br>real estate<br>broker<br>' What Python version do you have; it seems to be broken. $ 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. >>> import re >>> s = '<br><br>foobar' >>> re.sub('<br>*', '', s) 'foobar' >>> tmp = '<br><br>real estate<br>broker<br>' >>> re.sub('<br>*', '', tmp) 'real estatebroker' >>> I can't reproduce your observation here. The regexp could be made better since a <br/ > tag should be written like this (HTML 4.01 and XHTML) >>> re.sub('<br( */ *)?>*', '', tmp) 'real estatebroker' >>> > I don't know much about regexes, but is this because only the very first > occurrence is considered to be at the beginning of the line? I'm sure there No that can't be. There is something other wrong. Did you type it in exactly the way you posted it here? > is a regex way to do it, but you could just use a simple loop and > startswith(): That's possible but IMO extremly inefficient. Also with tags written as a mixture of <br> and <br/ > your loop couldn't be written so simple. Karl -- Please do *not* send copies of replies to me. I read the list From darnold02 at sprynet.com Mon Feb 2 18:48:02 2004 From: darnold02 at sprynet.com (don arnold) Date: Mon Feb 2 18:48:35 2004 Subject: [Tutor] lstrip() question References: <040e01c3e9bb$94a36c00$7210ba3f@don2uvsu54fwiq><Pine.LNX.4.44.0402021101230.25843-100000@hkn.eecs.berkeley.edu><20040202205755.GB13611@johnsons-web.com><m37jz52nlk.fsf@hamster.pflaesterer.de><04fd01c3e9d9$817fd780$7210ba3f@don2uvsu54fwiq> <m3y8rl13a0.fsf@hamster.pflaesterer.de> Message-ID: <058a01c3e9e6$ffc7f430$7210ba3f@don2uvsu54fwiq> ----- Original Message ----- From: "Karl Pfl?sterer" <sigurd@12move.de> To: <tutor@python.org> Sent: Monday, February 02, 2004 5:27 PM Subject: Re: [Tutor] lstrip() question > On 2 Feb 2004, don arnold <- darnold02@sprynet.com wrote: > > > But this doesn't seem to quite work if there are multiple leading <br>'s. > > >>>> tmp = '<br><br>real estate<br>broker<br>' > >>>> import re > >>>> re.sub('^<br>*','',tmp) > > '<br>real estate<br>broker<br>' > > > What Python version do you have; it seems to be broken. > > $ 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. > >>> import re > >>> s = '<br><br>foobar' > >>> re.sub('<br>*', '', s) > 'foobar' > >>> tmp = '<br><br>real estate<br>broker<br>' > >>> re.sub('<br>*', '', tmp) > 'real estatebroker' > >>> > Yes, but this regex doesn't have the initial caret ('^') that your original did. As a result, it removes all occurrences of the tag, not just the leading one(s). > I can't reproduce your observation here. > > The regexp could be made better since a <br/ > tag should be written > like this (HTML 4.01 and XHTML) > > >>> re.sub('<br( */ *)?>*', '', tmp) > 'real estatebroker' > >>> > > > > I don't know much about regexes, but is this because only the very first > > occurrence is considered to be at the beginning of the line? I'm sure there > > No that can't be. There is something other wrong. Did you type it in > exactly the way you posted it here? > > > is a regex way to do it, but you could just use a simple loop and > > startswith(): > > That's possible but IMO extremly inefficient. Also with tags written as > a mixture of <br> and <br/ > your loop couldn't be written so simple. > > Karl No argument there. But the truth of the matter is that neither string methods nor regexes are very well-suited for parsing full-blown HTML. For that, you're probably better off using the HTMLParser module. Don From dyoo at hkn.eecs.berkeley.edu Mon Feb 2 18:58:27 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Feb 2 18:58:33 2004 Subject: [Tutor] lstrip() question In-Reply-To: <m3y8rl13a0.fsf@hamster.pflaesterer.de> Message-ID: <Pine.LNX.4.44.0402021548590.10383-100000@hkn.eecs.berkeley.edu> > > But this doesn't seem to quite work if there are multiple leading <br>'s. > > >>>> tmp = '<br><br>real estate<br>broker<br>' > >>>> import re > >>>> re.sub('^<br>*','',tmp) > > '<br>real estate<br>broker<br>' > > > What Python version do you have; it seems to be broken. > > $ 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. > >>> import re > >>> s = '<br><br>foobar' > >>> re.sub('<br>*', '', s) > 'foobar' > >>> tmp = '<br><br>real estate<br>broker<br>' > >>> re.sub('<br>*', '', tmp) > 'real estatebroker' Hi Karl, No, the regular expression itself is broken. Here is one counterexample that should clearly show the problem: "<br>>>>hello" Try running that regular expression on this string, and see what gets replaced. The problem with the regex should be a little clearer then. To fix the problem, take a look at: http://www.amk.ca/python/howto/regex/ and look at section 4.2 on "Groups" --- using groups properly should fix the issue. Hope this helps! From sigurd at 12move.de Mon Feb 2 19:00:20 2004 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Mon Feb 2 19:02:46 2004 Subject: [Tutor] lstrip() question In-Reply-To: <m3y8rl13a0.fsf@hamster.pflaesterer.de> (Karl =?iso-8859-1?q?Pfl=E4sterer's?= message of "Tue, 03 Feb 2004 00:27:37 +0100") References: <040e01c3e9bb$94a36c00$7210ba3f@don2uvsu54fwiq> <Pine.LNX.4.44.0402021101230.25843-100000@hkn.eecs.berkeley.edu> <20040202205755.GB13611@johnsons-web.com> <m37jz52nlk.fsf@hamster.pflaesterer.de> <04fd01c3e9d9$817fd780$7210ba3f@don2uvsu54fwiq> <m3y8rl13a0.fsf@hamster.pflaesterer.de> Message-ID: <m3r7xd11bl.fsf@hamster.pflaesterer.de> On 3 Feb 2004, Karl Pfl?sterer <- sigurd@12move.de wrote: > On 2 Feb 2004, don arnold <- darnold02@sprynet.com wrote: >> But this doesn't seem to quite work if there are multiple leading <br>'s. >>>>> tmp = '<br><br>real estate<br>broker<br>' >>>>> import re >>>>> re.sub('^<br>*','',tmp) >> '<br>real estate<br>broker<br>' > What Python version do you have; it seems to be broken. No what I wrote was broken; sorry. I forgot the parentheses around the regexp. I should be: re.sub('^(<br[^<>]*>)*','',tmp) See my other posting <m3u12912q2.fsf@hamster.pflaesterer.de> for a better approach. Karl -- Please do *not* send copies of replies to me. I read the list From tim at johnsons-web.com Mon Feb 2 19:14:49 2004 From: tim at johnsons-web.com (Tim Johnson) Date: Mon Feb 2 19:10:35 2004 Subject: [Tutor] lstrip() question In-Reply-To: <m3y8rl13a0.fsf@hamster.pflaesterer.de> References: <040e01c3e9bb$94a36c00$7210ba3f@don2uvsu54fwiq> <Pine.LNX.4.44.0402021101230.25843-100000@hkn.eecs.berkeley.edu> <20040202205755.GB13611@johnsons-web.com> <m37jz52nlk.fsf@hamster.pflaesterer.de> <04fd01c3e9d9$817fd780$7210ba3f@don2uvsu54fwiq> <m3y8rl13a0.fsf@hamster.pflaesterer.de> Message-ID: <20040203001449.GH13611@johnsons-web.com> This is what I have come up with thus far: Note: I need to reconstruct the 'stripped' breaks tags, thus the returned tuple, and I'm also stripping leading spaces from the original string. # ==================================================================================== # seperate leading break tags from rest of string. Ignore case def lparse_br(self,st): pattern = '\<[br|BR|Br|bR]+\>' #for br tag tmp = st.lstrip() # remove leading spaces found = re.match(pattern,st) if found: brks = 1 tmp1 = tmp[4:] while 1: found = re.match(pattern,tmp1) if found: brks = brks + 1 tmp1 = tmp1[4:] else: break return brks * '<BR>',''.join(tmp1) else: return '',tmp I've run a couple of tests that appear to succeed, but observations are welcome. All help so far has been greatly appreciated. Regards tim -- Tim Johnson <tim@johnsons-web.com> http://www.alaska-internet-solutions.com From tim at johnsons-web.com Mon Feb 2 20:08:08 2004 From: tim at johnsons-web.com (Tim Johnson) Date: Mon Feb 2 20:03:55 2004 Subject: [Tutor] lstrip() question In-Reply-To: <DD0F81089B11A54A83A3270D9E1125E8646AD9@FDYEXC213.mgroupnet.com> References: <DD0F81089B11A54A83A3270D9E1125E8646AD9@FDYEXC213.mgroupnet.com> Message-ID: <20040203010808.GI13611@johnsons-web.com> * Simoni, Bill <WRSimoni@MAPLLC.com> [040202 13:22]: > > Hello All: > > I'd like to remove all leading occurance of a html break tag > > in a string such that > > "<br><br>test" => "test" > > and > > "<br>test<br>this" =>"test<br>this" > > > Hi Tim, > off the top of my head, I came up with this: > > >>> def repstrip(s, sub): > if s.startswith(sub): > s = repstrip(s[len(sub):], sub) #strip the leading characters that match and try it again > return s > > >>> print repstrip('real estate broker courtesy', '<br>') > real estate broker courtesy > > >>> print repstrip('<br>real estate broker courtesy', '<br>') > real estate broker courtesy > > >>> print repstrip('<br><br>real estate broker courtesy', '<br>') > real estate broker courtesy > > >>> print repstrip('<br><br>real estate <br> broker courtesy', '<br>') > real estate <br> broker courtesy Hi Bill: I liked that, so I modified it to the following: # ========================================================================================================== def repstrip(st, substr, reps=0): s = st.lower() sub = substr.lower() if s.startswith(sub): reps = reps + 1 # keep track of number of replacements reps,s = repstrip(s[len(sub):], sub, reps) #strip the leading characters that match and try it again return reps,st[(reps * len(sub)):] # This allows me to reconstruct the leading tags. -- Tim Johnson <tim@johnsons-web.com> http://www.alaska-internet-solutions.com From sigurd at 12move.de Mon Feb 2 20:38:00 2004 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Mon Feb 2 20:40:24 2004 Subject: [Tutor] lstrip() question In-Reply-To: <20040202222933.GE13611@johnsons-web.com> (Tim Johnson's message of "Mon, 2 Feb 2004 13:29:33 -0900") References: <040e01c3e9bb$94a36c00$7210ba3f@don2uvsu54fwiq> <Pine.LNX.4.44.0402021101230.25843-100000@hkn.eecs.berkeley.edu> <20040202205755.GB13611@johnsons-web.com> <m37jz52nlk.fsf@hamster.pflaesterer.de> <04fd01c3e9d9$817fd780$7210ba3f@don2uvsu54fwiq> <20040202222933.GE13611@johnsons-web.com> Message-ID: <m3u12912q2.fsf@hamster.pflaesterer.de> On 2 Feb 2004, Tim Johnson <- tim@johnsons-web.com wrote: > Actually what I am *really* looking for is a way to > strip either specific tags (like '<br>' from the > left *or* any number of tags. I'm a regex dunce I think I forgot the parentheses in my first example. But as you describe your problem now a simple regexp won't suffice. To strip off all tags is simple; As a function (now also case-insensitive and includes line breaks): def strip_tags (string): return re.sub('^(?is)(<[^<>]*>)*', '', string) But to strip specific tags you need e.g.: def strip_tags (string, tag=''): L = re.split('(<[^<>]*>)', string) for token in L[:]: if re.match('<.*>', token, re.S) or token == '': if re.search(tag, token, re.I|re.S): L.remove(token) else: return ''.join(L) >>> tmp = '<br/ ><br><foo><bar>real estate<br>broker<br>' >>> strip_tags(tmp, 'foo') '<br/ ><br><bar>real estate<br>broker<br>' >>> strip_tags(tmp, 'foo|bar') '<br/ ><br>real estate<br>broker<br>' >>> strip_tags(tmp) 'real estate<br>broker<br>' Above will split your string with the tags as seperators. Then the code iterates over the list, looks if the next token is a tag (if not all tags from the left have been processed and the joined list is returned) or an empty string, tries to match the code against the tag names to be removed and if it finds a match removes exactly that token from the list. Above code iterates over a copy of the list since it's not good to change the list which is iterated over. If you don't give a tag name (actually a regexp) the empty string is used which matches every tag. Karl -- Please do *not* send copies of replies to me. I read the list From sigurd at 12move.de Mon Feb 2 20:39:58 2004 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Mon Feb 2 20:40:27 2004 Subject: [Tutor] lstrip() question In-Reply-To: <Pine.LNX.4.44.0402021548590.10383-100000@hkn.eecs.berkeley.edu> (Danny Yoo's message of "Mon, 2 Feb 2004 15:58:27 -0800 (PST)") References: <Pine.LNX.4.44.0402021548590.10383-100000@hkn.eecs.berkeley.edu> Message-ID: <m3llnl0wng.fsf@hamster.pflaesterer.de> On 3 Feb 2004, Danny Yoo <- dyoo@hkn.eecs.berkeley.edu wrote: > No, the regular expression itself is broken. Here is one counterexample > that should clearly show the problem: Yea I know; I wrote it yet in another posting *blush*. I forgot the parentheses. Karl -- Please do *not* send copies of replies to me. I read the list From sigurd at 12move.de Mon Feb 2 21:00:06 2004 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Mon Feb 2 21:00:41 2004 Subject: [Tutor] lstrip() question In-Reply-To: <20040203001449.GH13611@johnsons-web.com> (Tim Johnson's message of "Mon, 2 Feb 2004 15:14:49 -0900") References: <040e01c3e9bb$94a36c00$7210ba3f@don2uvsu54fwiq> <Pine.LNX.4.44.0402021101230.25843-100000@hkn.eecs.berkeley.edu> <20040202205755.GB13611@johnsons-web.com> <m37jz52nlk.fsf@hamster.pflaesterer.de> <04fd01c3e9d9$817fd780$7210ba3f@don2uvsu54fwiq> <m3y8rl13a0.fsf@hamster.pflaesterer.de> <20040203001449.GH13611@johnsons-web.com> Message-ID: <m3ektd0w9p.fsf@hamster.pflaesterer.de> On 3 Feb 2004, Tim Johnson <- tim@johnsons-web.com wrote: > This is what I have come up with thus far: > Note: I need to reconstruct the 'stripped' breaks tags, > thus the returned tuple, and I'm also stripping leading spaces > from the original string. Could you explain what exactly you want to achieve and which kind of input you expect? In another posting you wrote you wanted to strip specific tags from the left. That here is completely different. > # ==================================================================================== > # seperate leading break tags from rest of string. Ignore case > def lparse_br(self,st): > pattern = '\<[br|BR|Br|bR]+\>' #for br tag That's not necessary. Regexps can be declared case-insensitive. Why the backslashes? I'm not sure that this pattern does what you want it to do. Could you explain (in words) what you want to find?. For e.g the above matches: >>> re.match(pattern, '<bbbbr>') <_sre.SRE_Match object at 0xb08ad8> I think you meant: pattern = '(?i)<(br)>' >>> pattern = '(?i)<(br)>' >>> re.match(pattern, '<bbbbr>') >>> re.match(pattern, '<Br>') <_sre.SRE_Match object at 0xaf7120> But that won't find all kind of <br> tags (XHTML tags won't be found). See my other posting for an example. But since you need the tags you have to change that code. The best is you explain what you want to achieve. > tmp = st.lstrip() # remove leading spaces > found = re.match(pattern,st) Did you mean st here? Do you know about the difference betwenn `match' and `search'? HTH Karl -- Please do *not* send copies of replies to me. I read the list From dyoo at hkn.eecs.berkeley.edu Mon Feb 2 21:47:48 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Feb 2 21:47:54 2004 Subject: [Tutor] lstrip() question In-Reply-To: <20040202205755.GB13611@johnsons-web.com> Message-ID: <Pine.LNX.4.44.0402021819500.11108-100000@hkn.eecs.berkeley.edu> On Mon, 2 Feb 2004, Tim Johnson wrote: > I'd like to remove all leading occurance of a html break tag in a > string such that "<br><br>test" => "test" and "<br>test<br>this" > =>"test<br>this" Hi Tim, Just out of curiosity, why are you trying to do this? Would it be possible to use something like HTMLParser? http://www.python.org/doc/lib/module-HTMLParser.html I know it sounds like using the library might be overkill, but HTMLParser is meant to deal with the ugliness that is HTML. It can handle some strange situations like ### s = """<br ><Br/><bR class="f<o><o>!">this is a test""" ### where a regular expression for this might be more subtle than we might expect. (The example above is meant to be a nightmare case. *grin*) Using a real HTML parser normalizes this wackiness so that we don't see it. Here's a subclass of HTMLParser that shows how we might use it for the problem: ### from HTMLParser import HTMLParser class IgnoreLeadingBreaksParser(HTMLParser): def __init__(self): HTMLParser.__init__(self) self.seen_nonbreak_tag = False self.text = [] def get_text(self): return ''.join(self.text) def handle_starttag(self, tag, attrs): if tag != 'br': self.seen_nonbreak_tag = True if self.seen_nonbreak_tag: self.text.append(self.get_starttag_text()) def handle_endtag(self, tag): if tag != 'br': self.seen_nonbreak_tag = True if self.seen_nonbreak_tag: self.text.append('</%s>' % tag) def handle_data(self, data): self.seen_nonbreak_tag = True self.text.append(data) def ignore_leading_breaks(text): parser = IgnoreLeadingBreaksParser() parser.feed(text) return parser.get_text() ### Note: this is not quite production-quality yet. In particular, it doesn't handle comments or character references, so we may need to add more methods to the IgnoreLeadingBreaksParser so that it handles those cases too. Hope this helps! From dyoo at hkn.eecs.berkeley.edu Mon Feb 2 22:10:27 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Feb 2 22:10:31 2004 Subject: [Tutor] "=" invalid syntax ? [Assignment grammar stuff] (fwd) Message-ID: <Pine.LNX.4.44.0402021909470.17229-100000@hkn.eecs.berkeley.edu> [Forwarding to Tutor --- slightly busy at the moment. Sorry!] ---------- Forwarded message ---------- Date: Sun, 1 Feb 2004 12:02:11 -0500 From: orbitz@ezabel.com To: Danny Yoo <dyoo@hkn.eecs.berkeley.edu> Subject: Re: [Tutor] "=" invalid syntax ? [Assignment grammar stuff] Hey thanks, i just learned it was special cased recently and didn't really understand it that well. Thanks for putting some work into explaining it. Do you know, off the top of your head, any other special cased things like that. Another one someone showed me was: x, y = [1,2] Also, in an lvalue, if i do (x, y) = [1,2] The () don't make it a tuple in such a situtaion do they? Thanks On Sat, 31 Jan 2004 21:19:44 -0800 (PST) Danny Yoo <dyoo@hkn.eecs.berkeley.edu> wrote: > > > On Sat, 31 Jan 2004 orbitz@ezabel.com wrote: > > > I just learned this recently, but if you say = is a statement then > > you would imagine: > > > > a = b = 2 to not work. = is actually special cased for this to work. > > however > > a = (b = 2) does not work. There is some 'magic' some people might > > say to =, but I think a = b = .. is the only excpetion to the = is a > > statement operator rule. > > Hi orbitz, > > > If people are interested in how it's special cased, the Reference > Manual has the gory details. *grin* > > > The grammar definition in: > > http://www.python.org/doc/ref/assignment.html > > shows that > > assignment_stmt ::= (target_list "=")+ expression_list > > > That is, an assignment statement is made up of a number of targets, > followed by the expression that will be assigned to those targets. > Usually, we define a single target, but nothing stops us from defining > multiple targets. If we're looking at somthing like: > > a = b = 2 > > then we can see that > > a = b = matches (target_list "=")+ > > and > > 2 matches expression_list > > > > If we look at the grammar, we can also see that assignment allows for > a limited form of pattern matching --- it's possible to say something > like: > > ### > >>> p1 = (x1, y1) = (3, 17) > >>> p1 > (3, 17) > >>> x1 > 3 > >>> y1 > 17 > ### > > > Hope this helps! > From matthewmhoffman at hotmail.com Mon Feb 2 23:36:50 2004 From: matthewmhoffman at hotmail.com (Matthew Hoffman) Date: Mon Feb 2 23:36:56 2004 Subject: [Tutor] Simple ROT-13 Script Message-ID: <BAY9-F5VGI8x2wFlyNl00002a8f@hotmail.com> Hello all! I have been reading this list for a goodly amount of time and have never felt worthy to submit a question until now. I just wrote a quick one-off script and I would like your opinions on any Python-isms. It's just a ROT-13 script (I got a Neal Stephenson book for xmas). I would just like to entertain your thoughts about what I could have done better, etc. Cheers! ~Matt #! /usr/bin/python encrypt = lambda s: chr(ord(s) + 13) decrypt = lambda s: chr(ord(s) - 13) s = 'guido' r = map(encrypt, s) t = map(decrypt, r) >>>r ['t', '\x82', 'v', 'q', '|'] >>>t ['g', 'u', 'i', 'd', 'o'] _________________________________________________________________ Find high-speed ‘net deals — comparison-shop your local providers here. https://broadband.msn.com From alan.gauld at blueyonder.co.uk Tue Feb 3 01:31:08 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Feb 3 01:32:31 2004 Subject: [Tutor] Concatenating Strings into Variable Names? References: <20040202131208.F4F781C0.xthereal@bigfoot.com> Message-ID: <016f01c3ea1f$4f53e5d0$6401a8c0@xp> > I'm trying to write my first program besides good old hello world. Is > there a way to concatenate strings into a variable name? There is, but it's nearly always the wrong thing to do. Instead use a dictionary. > Here's a > brief example of what i'm trying to do: > options = {} options['choiceA_option1']= 2.0 options['choiceA_option2']= 3.0 etc... > choice=raw_input("Do you want choice A or B?") > option=raw_input("Do you want option 1 or 2?") > > the_answer="choice" + choice + "_option" + option > > print options[the_answer] There is another example of this at the end of the OOP topic on my web site. 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 Tue Feb 3 01:34:06 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Feb 3 01:35:29 2004 Subject: [Tutor] Concatenating Strings into Variable Names? References: <20040202131208.F4F781C0.xthereal@bigfoot.com> <1075748793.4059.43.camel@vaio> Message-ID: <017601c3ea1f$b90eb360$6401a8c0@xp> > You can test these out: > > try: > print eval('the_answer') > except: > "Invalid choice" But using eval() on user input is potentially dangerous since it could be a malicious value. In this case because we add the "Choice" string etc its probably safe, but in general eval() is a risky choice. Alan G. From alan.gauld at blueyonder.co.uk Tue Feb 3 01:35:57 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Feb 3 01:37:20 2004 Subject: [Tutor] lstrip() question References: <040e01c3e9bb$94a36c00$7210ba3f@don2uvsu54fwiq><Pine.LNX.4.44.0402021101230.25843-100000@hkn.eecs.berkeley.edu> <20040202205755.GB13611@johnsons-web.com> Message-ID: <017d01c3ea1f$fb51e580$6401a8c0@xp> > Is there a builtin > python method to strip leading substrings? Or do > I have to do something using startswidth()? Try the string.replace() function? Just replace the substring with an empty string. Alan G. From alan.gauld at blueyonder.co.uk Tue Feb 3 01:37:53 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Feb 3 01:39:16 2004 Subject: [Tutor] lstrip() question References: <040e01c3e9bb$94a36c00$7210ba3f@don2uvsu54fwiq><Pine.LNX.4.44.0402021101230.25843-100000@hkn.eecs.berkeley.edu><20040202205755.GB13611@johnsons-web.com><m37jz52nlk.fsf@hamster.pflaesterer.de> <20040202215422.GC13611@johnsons-web.com> Message-ID: <018601c3ea20$407728f0$6401a8c0@xp> Things Karl. Right on the money! > I would use a regexp. > > >>> tmp1 = '<br>real estate broker courtesy' > >>> import re > >>> re.sub('^<br>*', '', tmp1) > 'real estate broker courtesy' > >>> tmp1 = 'real estate broker courtesy' > >>> re.sub('^<br>*', '', tmp1) > 'real estate broker courtesy' A simple string replace is cheaper than a regex in this case - you know the string in advance. But in practice the difference isn't likely to be serious! Alan G. From dyoo at hkn.eecs.berkeley.edu Tue Feb 3 02:31:08 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Feb 3 02:31:13 2004 Subject: [Tutor] Simple ROT-13 Script In-Reply-To: <BAY9-F5VGI8x2wFlyNl00002a8f@hotmail.com> Message-ID: <Pine.LNX.4.44.0402022325400.19197-100000@hkn.eecs.berkeley.edu> On Mon, 2 Feb 2004, Matthew Hoffman wrote: > I just wrote a quick one-off script and I would like your opinions on > any Python-isms. It's just a ROT-13 script (I got a Neal Stephenson book > for xmas). I would just like to entertain your thoughts about what I > could have done better, etc. Cheers! ~Matt > encrypt = lambda s: chr(ord(s) + 13) > decrypt = lambda s: chr(ord(s) - 13) > > s = 'guido' > r = map(encrypt, s) > t = map(decrypt, r) > > >>>r > ['t', '\x82', 'v', 'q', '|'] > >>>t > ['g', 'u', 'i', 'd', 'o'] Hi Matt, Cool! Can you make the character rotation wrap around? At the moment, the letter 'u' is getting rotated to '\x82', but it should really wrap around to 'h'. You may find the remainder operator '%' useful to do the wrap-around: ### >>> for i in range(10): ... print i % 3 ... 0 1 2 0 1 2 0 1 2 0 ### Good luck! From dyoo at hkn.eecs.berkeley.edu Tue Feb 3 02:58:50 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Feb 3 02:58:54 2004 Subject: [Tutor] "=" invalid syntax ? [Assignment grammar stuff] (fwd) In-Reply-To: <Pine.LNX.4.44.0402021909470.17229-100000@hkn.eecs.berkeley.edu> Message-ID: <Pine.LNX.4.44.0402022332350.19197-100000@hkn.eecs.berkeley.edu> > Do you know, off the top of your head, any other special cased things > like that. Hi orbitz, Nope... Can't remember a thing. *grin* Thank goodness for Google. > Another one someone showed me was: > > x, y = [1,2] Yes, this works too, because [1, 2] is treated as a sequence. Here's the official word from the reference docs: """If the target is a target list enclosed in parentheses or in square brackets: The object must be a sequence with the same number of items as there are targets in the target list, and its items are assigned, from left to right, to the corresponding targets.""" (http://www.python.org/doc/ref/assignment.html) So that part of the definition covers the case when we say: x, y = [1, 2] Hmmm... I wonder, though... ### >>> def test_iterator(): ... yield 1 ... yield 2 ... >>> x, y = test_iterator() >>> x 1 >>> y 2 ### It looks like tuple unpacking works even on iterators. If we know exactly how many things are coming out of an iteration, we can use tuple assignment. Not that we'd ever do this, but still neat. *grin* > Also, in an lvalue, if i do > > (x, y) = [1,2] > > The () don't make it a tuple in such a situtaion do they? The documentation implies that it treats the left hand side as a bunch of targets, so I don't think it constructs an intermediate tuple with them. But that's just a guess. We can check this! ### >>> l = [1, 2] >>> def t1(): ... x = l[1] ... y = l[2] ... >>> def t2(): ... x, y = l[1], l[2] ... >>> def t3(): ... x, y = l ... >>> import dis ### The 'dis' module provides a very low-level "disassembly" view of what Python really thinks a function is doing. Here's some sample output: ### >>> dis.dis(t1) 2 0 LOAD_GLOBAL 0 (l) 3 LOAD_CONST 1 (1) 6 BINARY_SUBSCR 7 STORE_FAST 1 (x) 3 10 LOAD_GLOBAL 0 (l) 13 LOAD_CONST 2 (2) 16 BINARY_SUBSCR 17 STORE_FAST 0 (y) 20 LOAD_CONST 0 (None) 23 RETURN_VALUE >>> dis.dis(t2) 2 0 LOAD_GLOBAL 0 (l) 3 LOAD_CONST 1 (1) 6 BINARY_SUBSCR 7 LOAD_GLOBAL 0 (l) 10 LOAD_CONST 2 (2) 13 BINARY_SUBSCR 14 BUILD_TUPLE 2 17 UNPACK_SEQUENCE 2 20 STORE_FAST 1 (x) 23 STORE_FAST 0 (y) 26 LOAD_CONST 0 (None) 29 RETURN_VALUE >>> dis.dis(t3) 2 0 LOAD_GLOBAL 0 (l) 3 UNPACK_SEQUENCE 2 6 STORE_FAST 1 (x) 9 STORE_FAST 0 (y) 12 LOAD_CONST 0 (None) 15 RETURN_VALUE ### You don't have to understand everything here. But just from casual comparison, we can see that the disassembly of t1() and t3() shows that Python isn't constructing a tuple, so we can definitively say that tuple assignment doesn't make a tuple for the lvalue. Whew; I had felt a little uncomfortable about guessing. *grin* By the way, in t2(), Python does construct a tuple, but that's because Python's evaluating the right hand side of: x, y = l[1], l[2] and constructing the tuple (l[1], l[2]) before doing the tuple assignment. So Python has to fully evaluate the right hand side before doing assignments, and if it means it needs to create an intermediate tuple, it does so. This explains why we can do swapping like this: x, y = y, x because Python first creates an intermediate tuple with the values of 'y' and 'x', and then assigns that rvalue tuple to 'x' and 'y'. Hope this helps! From darnold02 at sprynet.com Tue Feb 3 07:24:54 2004 From: darnold02 at sprynet.com (don arnold) Date: Tue Feb 3 07:25:06 2004 Subject: [Tutor] Simple ROT-13 Script References: <Pine.LNX.4.44.0402022325400.19197-100000@hkn.eecs.berkeley.edu> Message-ID: <06ff01c3ea50$bbfc6730$7210ba3f@don2uvsu54fwiq> ----- Original Message ----- From: "Danny Yoo" <dyoo@hkn.eecs.berkeley.edu> To: "Matthew Hoffman" <matthewmhoffman@hotmail.com> Cc: <tutor@python.org> Sent: Tuesday, February 03, 2004 1:31 AM Subject: Re: [Tutor] Simple ROT-13 Script > > > On Mon, 2 Feb 2004, Matthew Hoffman wrote: > > > I just wrote a quick one-off script and I would like your opinions on > > any Python-isms. It's just a ROT-13 script (I got a Neal Stephenson book > > for xmas). I would just like to entertain your thoughts about what I > > could have done better, etc. Cheers! ~Matt > > > encrypt = lambda s: chr(ord(s) + 13) > > decrypt = lambda s: chr(ord(s) - 13) > > > > s = 'guido' > > r = map(encrypt, s) > > t = map(decrypt, r) > > > > >>>r > > ['t', '\x82', 'v', 'q', '|'] > > >>>t > > ['g', 'u', 'i', 'd', 'o'] > > > Hi Matt, > > Cool! Can you make the character rotation wrap around? At the moment, > the letter 'u' is getting rotated to '\x82', but it should really wrap > around to 'h'. > <snip> And in case you didn't know, the reason you want it to wrap around is so that you only need a single rot13() function, not individual encrypt() and decrypt() functions: >>> print rot13('abc') nop >>> print rot13('nop') abc HTH, Don From sigurd at 12move.de Tue Feb 3 09:13:09 2004 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Tue Feb 3 09:18:21 2004 Subject: [Tutor] Simple ROT-13 Script In-Reply-To: <06ff01c3ea50$bbfc6730$7210ba3f@don2uvsu54fwiq> (don arnold's message of "Tue, 3 Feb 2004 06:24:54 -0600") References: <Pine.LNX.4.44.0402022325400.19197-100000@hkn.eecs.berkeley.edu> <06ff01c3ea50$bbfc6730$7210ba3f@don2uvsu54fwiq> Message-ID: <m31xpcuud8.fsf@hamster.pflaesterer.de> On 3 Feb 2004, don arnold <- darnold02@sprynet.com wrote: > And in case you didn't know, the reason you want it to wrap around is so > that you only need a single rot13() function, not individual encrypt() and > decrypt() functions: >>>> print rot13('abc') > nop >>>> print rot13('nop') > abc Right. And you should take care, that only characters are moved. Numbers or punctuation signs e.g. are not touched. >>> s = "Guido 123; Tim 456" >>> s.encode('rot13') 'Thvqb 123; Gvz 456' >>> _.encode('rot13') 'Guido 123; Tim 456' >>> Karl -- Please do *not* send copies of replies to me. I read the list From python.tutorial at jarava.org Tue Feb 3 11:09:22 2004 From: python.tutorial at jarava.org (Javier JJ) Date: Tue Feb 3 11:09:28 2004 Subject: [Tutor] Simple ROT-13 Script In-Reply-To: <m31xpcuud8.fsf@hamster.pflaesterer.de> References: <Pine.LNX.4.44.0402022325400.19197-100000@hkn.eecs.berkeley.edu> <06ff01c3ea50$bbfc6730$7210ba3f@don2uvsu54fwiq> <m31xpcuud8.fsf@hamster.pflaesterer.de> Message-ID: <401FC7B2.9040008@jarava.org> And the reason that it wont' work on other than ASCII.- strings ?? I mean: >>> s = "asasas" >>> s.encode("rot13") 'nfnfnf' >>> type(s) <type 'str'> >>> s = "aaa???aaaaaaaa" >>> s 'aaa\xf1\xf1\xf1aaaaaaaa' >>> type(s) <type 'str'> >>> s.encode("rot13") Traceback (most recent call last): File "<interactive input>", line 1, in ? File "C:\Python23\lib\encodings\rot_13.py", line 18, in encode return codecs.charmap_encode(input,errors,encoding_map) UnicodeDecodeError: 'ascii' codec can't decode byte 0xf1 in position 3: ordinal not in range(128) >>> ???????? Thanks a lot... Javier Jarava On this day, 03/02/2004 15:13, Karl Pfl?sterer wrote: >On 3 Feb 2004, don arnold <- darnold02@sprynet.com wrote: > > > >>And in case you didn't know, the reason you want it to wrap around is so >>that you only need a single rot13() function, not individual encrypt() and >>decrypt() functions: >> >> > > > >>>>>print rot13('abc') >>>>> >>>>> >>nop >> >> >>>>>print rot13('nop') >>>>> >>>>> >>abc >> >> > >Right. And you should take care, that only characters are moved. >Numbers or punctuation signs e.g. are not touched. > > > >>>>s = "Guido 123; Tim 456" >>>>s.encode('rot13') >>>> >>>> >'Thvqb 123; Gvz 456' > > >>>>_.encode('rot13') >>>> >>>> >'Guido 123; Tim 456' > > > > > > Karl > > From tim at johnsons-web.com Tue Feb 3 11:42:45 2004 From: tim at johnsons-web.com (Tim Johnson) Date: Tue Feb 3 11:38:30 2004 Subject: [Tutor] lstrip() question(Thanks all!) In-Reply-To: <Pine.LNX.4.44.0402021819500.11108-100000@hkn.eecs.berkeley.edu> References: <20040202205755.GB13611@johnsons-web.com> <Pine.LNX.4.44.0402021819500.11108-100000@hkn.eecs.berkeley.edu> Message-ID: <20040203164245.GJ13611@johnsons-web.com> Hello All: I wish I had that time to thank every one on this topic and respond to all your comments, but I'm laboring over a hot keyboard and trying to beat a deadline. I solved my problem and got a very large amount of informative input. My thanks to all of you! Regards tim * Danny Yoo <dyoo@hkn.eecs.berkeley.edu> [040202 18:00]: > Just out of curiosity, why are you trying to do this? Would it be > possible to use something like HTMLParser? > > http://www.python.org/doc/lib/module-HTMLParser.html > > I know it sounds like using the library might be overkill, but HTMLParser > is meant to deal with the ugliness that is HTML. It can handle some > strange situations like > > > ### > s = """<br > ><Br/><bR class="f<o><o>!">this is a test""" > ### > > > where a regular expression for this might be more subtle than we might > expect. (The example above is meant to be a nightmare case. *grin*) > > > Using a real HTML parser normalizes this wackiness so that we don't see > it. Here's a subclass of HTMLParser that shows how we might use it for > the problem: > > > ### > from HTMLParser import HTMLParser > > class IgnoreLeadingBreaksParser(HTMLParser): > def __init__(self): > HTMLParser.__init__(self) > self.seen_nonbreak_tag = False > self.text = [] > > def get_text(self): > return ''.join(self.text) > > def handle_starttag(self, tag, attrs): > if tag != 'br': > self.seen_nonbreak_tag = True > if self.seen_nonbreak_tag: > self.text.append(self.get_starttag_text()) > > def handle_endtag(self, tag): > if tag != 'br': > self.seen_nonbreak_tag = True > if self.seen_nonbreak_tag: > self.text.append('</%s>' % tag) > > def handle_data(self, data): > self.seen_nonbreak_tag = True > self.text.append(data) > > > def ignore_leading_breaks(text): > parser = IgnoreLeadingBreaksParser() > parser.feed(text) > return parser.get_text() > ### > > > Note: this is not quite production-quality yet. In particular, it doesn't > handle comments or character references, so we may need to add more > methods to the IgnoreLeadingBreaksParser so that it handles those cases > too. > > > Hope this helps! -- Tim Johnson <tim@johnsons-web.com> http://www.alaska-internet-solutions.com From barrys at datatree.co.uk Mon Feb 2 09:50:17 2004 From: barrys at datatree.co.uk (Barry Smithers) Date: Tue Feb 3 12:40:19 2004 Subject: [Tutor] Using Python with VI Message-ID: <00a801c3e99b$dfb52820$b364a8c0@datatree> Hello everyone. I'm having difficulty with a program call from inside of VI. What I basically need to do is get the line numbers input in the ex command. Or maybe even get the text on those lines to go into a list. For example the ex command ":20,21!xxx.py" would run xxx.py as a whole, but I need the data currently on lines 20 and 21 for modification. Can anyone help?? Cheers Barry From ganjeali at hotmail.com Mon Feb 2 03:16:10 2004 From: ganjeali at hotmail.com (Meisam Ganjeali darani) Date: Tue Feb 3 12:42:51 2004 Subject: [Tutor] (no subject) Message-ID: <Sea2-DAV23UA51HLvsq0002f67a@hotmail.com> Hi Thanks for your help. I have some question about python. How I can run python in my system? My system platform is windows Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040202/fb2b50f6/attachment.html From dyoo at hkn.eecs.berkeley.edu Tue Feb 3 12:56:23 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Feb 3 12:56:30 2004 Subject: [Tutor] (no subject) In-Reply-To: <3119.63.225.172.24.1075552557.squirrel@mail.zoper.com> Message-ID: <Pine.LNX.4.44.0402030945570.18668-100000@hkn.eecs.berkeley.edu> > Also, this is my first email to a list like this one, so I'm wondering > if I'm observing proper social conventions. This message feels kind of > long to me. What do you think? Hi Dana, Welcome aboard! Your message is fine, but make sure to add a "subject line" on your email, so that it's easier for people to find your message. (Also, if you haven't already, you may want to subscribe to Tutor --- otherwise, your messages will be held until one of the lazy admins here gets a chance to validate the message for non-spaminess. The page: http://mail.python.org/mailman/listinfo/tutor explains how to subscribe to Python-Tutor.) Let's take a look at the InteractiveURLParser: > class InteractiveURLParser(HTMLParser.HTMLParser): > def open(self, URL): > page = getPage(URL) > page = flattenPage(page) > self.feed(page) > def newURL(self, URL): > __init__(self, URL) > def handle_starttag(self, tag, attrs): > print "tag is %s with attributes %s." %(self, tag, attrs) > def handle_data(self, data): > print data There are two issues I can see so far: the newURL method looks a little weird, and there's a bug in handle_starttag(). Let's cover the newURL() method briefly: > def newURL(self, URL): > __init__(self, URL) This looks a little weird because no __init__ method has yet been defined. Can you explain what newURL is trying to do? And do you need it? I don't see anything in the code that uses it, so maybe it can be removed? Let's take a look at handle_starttag(): > def handle_starttag(self, tag, attrs): > print "tag is %s with attributes %s." %(self, tag, attrs) ^^ ^^ ^^^^ ^^^ ^^^^^ There are two formatting positions in the string, but the code is trying to fill it up with three things. Given that, does the error message: > File "r.py", line 31, in handle_starttag > print "tag is %s with attributes %s." %(self, tag, attrs) > TypeError: not all arguments converted during string formatting make sense now? Talk to you later! From sigurd at 12move.de Tue Feb 3 12:59:32 2004 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Tue Feb 3 13:03:55 2004 Subject: [Tutor] Simple ROT-13 Script In-Reply-To: <401FC7B2.9040008@jarava.org> (Javier JJ's message of "Tue, 03 Feb 2004 17:09:22 +0100") References: <Pine.LNX.4.44.0402022325400.19197-100000@hkn.eecs.berkeley.edu> <06ff01c3ea50$bbfc6730$7210ba3f@don2uvsu54fwiq> <m31xpcuud8.fsf@hamster.pflaesterer.de> <401FC7B2.9040008@jarava.org> Message-ID: <m3oesgt661.fsf@hamster.pflaesterer.de> On 3 Feb 2004, Javier JJ <- python.tutorial@jarava.org wrote: > And the reason that it wont' work on other than ASCII.- strings ?? [...] > Traceback (most recent call last): > File "<interactive input>", line 1, in ? > File "C:\Python23\lib\encodings\rot_13.py", line 18, in encode > return codecs.charmap_encode(input,errors,encoding_map) > UnicodeDecodeError: 'ascii' codec can't decode byte 0xf1 in position > 3: ordinal not in range(128) > >>> ^^^^^^^^^^^ The reason is here ; the error code says that that function only works for characters in the ASCII range. If you see how you do rot13 with pen and paer it's clear why it's so: >>> alph = ''.join(map(chr, range(ord('a'), ord('z')+1))) >>> alphrot = alph[13:] + alph[:13] >>> alph 'abcdefghijklmnopqrstuvwxyz' >>> alphrot 'nopqrstuvwxyzabcdefghijklm' >>> Look at the alphabet and how it's mapped: a b c d e f g h i j k l m n o p q r s t u v w x y z | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | n o p q r s t u v w x y z a b c d e f g h i j k l m The same is true capitals. Now if you wanted to include other characters you (the sender == encrypting person) and the reader (== decrypting person) must agree where to place these additional characters. Since this is most of the time not possible normally rot13 is only applied to characters in the ASCII range. I found it interesting to write a small Python solution on how to do a caesar chiffre and came up with the following (rot13 encrypted): qrs znxr_gnoyr (*netf): gnoyr = {} sbe ghc va netf: fgp, raqp, qvf = ghc nycu = ''.wbva(znc(pue, enatr(beq(fgp), beq(raqp)+1))) nycuebg = nycu[qvf:] + nycu[:qvf] gnoyr.hcqngr(qvpg(mvc(nycu, nycuebg))) erghea gnoyr qrs znxr_gnoyr (*netf): gnoyr = {} sbe ghc va netf: fgp, raqp, qvf = ghc fga, raqa = beq(fgp), beq(raqp) jvqgu = raqa - fga + 1 sbe p va enatr(fga, raqa + 1): gnoyr[pue(p)] = pue((p - fga + qvf) % jvqgu + fga) erghea gnoyr qrs ebg_a (frd, goy): erghea ''.wbva(znc(ynzoqn p: goy.trg(p, p), frd)) qrs ebg13 (frd, goy = znxr_gnoyr(('n', 'm', 13), ('N', 'M', 13))): erghea ebg_a(frd, goy) There are two alternative functions to generate a table; that table is used to find a substitution for a character in the rot13 function. You could add in that table mappings for additional characters if you liked. Karl -- Please do *not* send copies of replies to me. I read the list From philip at pacer.co.za Tue Feb 3 13:08:59 2004 From: philip at pacer.co.za (philip gilchrist) Date: Tue Feb 3 13:09:00 2004 Subject: [Tutor] Maths (slightly OT) Message-ID: <598B5E93DCDC614C9C1FE22406A0F5BE36CD@pacer-server.pacer.local> Hi Pythoners My Son has challenged me to name a few careers that would use Maths exponents and all the calculations in them as a way of getting out of learning them. Obviously, programming and basically anything to do with Computers is foremost in the answer, but I was hoping that you studious types would be able to supply me with more than the obvious answer. Hoping to hear from all the career people that can use Mathematical Calculations on a regular basis. regards, Philip -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040203/b09d268e/attachment.html From gerrit at nl.linux.org Tue Feb 3 13:18:43 2004 From: gerrit at nl.linux.org (Gerrit Holl) Date: Tue Feb 3 13:20:46 2004 Subject: [Tutor] Maths (slightly OT) In-Reply-To: <598B5E93DCDC614C9C1FE22406A0F5BE36CD@pacer-server.pacer.local> References: <598B5E93DCDC614C9C1FE22406A0F5BE36CD@pacer-server.pacer.local> Message-ID: <20040203181843.GA5060@nl.linux.org> philip gilchrist wrote: > My Son has challenged me to name a few careers that would use Maths > exponents and all the calculations in them as a way of getting out of > learning them. Obviously, programming and basically anything to do with > Computers is foremost in the answer, but I was hoping that you studious > types would be able to supply me with more than the obvious answer. > > Hoping to hear from all the career people that can use Mathematical > Calculations on a regular basis. Physists use a lot more math than computer people. I'm only in my first year of a Physics course, but to name a popular example, you can't send a rocket into the space without a **lot** of mathematics. Gerrit. -- PrePEP: Builtin path type http://people.nl.linux.org/~gerrit/creaties/path/pep-xxxx.html Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From littledanehren at yahoo.com Tue Feb 3 13:43:48 2004 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Tue Feb 3 13:43:53 2004 Subject: [Tutor] Simple ROT-13 Script In-Reply-To: <401FC7B2.9040008@jarava.org> Message-ID: <20040203184348.54136.qmail@web41803.mail.yahoo.com> Javier JJ wrote: > And the reason that it wont' work on other than > ASCII.- strings ?? > > I mean: > > >>> s = "asasas" > >>> s.encode("rot13") > 'nfnfnf' > >>> type(s) > <type 'str'> > > >>> s = "aaañññaaaaaaaa" > >>> s > 'aaa\xf1\xf1\xf1aaaaaaaa' > >>> type(s) > <type 'str'> > >>> s.encode("rot13") > Traceback (most recent call last): > File "<interactive input>", line 1, in ? > File "C:\Python23\lib\encodings\rot_13.py", line > 18, in encode > return > codecs.charmap_encode(input,errors,encoding_map) > UnicodeDecodeError: 'ascii' codec can't decode byte > 0xf1 in position 3: > ordinal not in range(128) > >>> > > ¿¿¿????? > > Thanks a lot... > > Javier Jarava What would you expect that to be encoded as? There's no a with a ~ over it. rot13 is only made to work with ASCII. If you wanted the accent marks to just be removed, you might want to define your own rot13 function. Daniel Ehrenberg __________________________________ Do you Yahoo!? Yahoo! SiteBuilder - Free web site building tool. Try it! http://webhosting.yahoo.com/ps/sb/ From op73418 at mail.telepac.pt Tue Feb 3 14:19:03 2004 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Tue Feb 3 14:16:40 2004 Subject: [Tutor] Maths (slightly OT) In-Reply-To: <598B5E93DCDC614C9C1FE22406A0F5BE36CD@pacer-server.pacer.local> References: <598B5E93DCDC614C9C1FE22406A0F5BE36CD@pacer-server.pacer.local> Message-ID: <2ksv1090cbgemb7m8grftehtbu5c8tvcfh@4ax.com> Em Tue, 3 Feb 2004 20:08:59 +0200, "philip gilchrist" <philip@pacer.co.za> atirou este peixe aos pinguins: >Hi Pythoners > >My Son has challenged me to name a few careers that would use Maths >exponents and all the calculations in them as a way of getting out of >learning them. Obviously, programming and basically anything to do with >Computers is foremost in the answer, but I was hoping that you studious >types would be able to supply me with more than the obvious answer. > >Hoping to hear from all the career people that can use Mathematical >Calculations on a regular basis. > The obvious answer to your question is: a mathematician. Physicists also use a lot of mathematics, in fact a lot of mathematical research is motivated by problems in physics. Having said this, let me add that mathematics is being applied to various subjects. People studying DNA use knot theory, biologists model the evolution of populations using differential equations, economists use game theory, sociologists make heavy use of statistics, research in computer science makes heavy use of category theory, and the list goes on. With my best regards, G. Rodrigues From nullpointer at heartoftn.net Tue Feb 3 14:28:06 2004 From: nullpointer at heartoftn.net (Null Pointer) Date: Tue Feb 3 14:28:27 2004 Subject: [Tutor] Maths (slightly OT) In-Reply-To: <598B5E93DCDC614C9C1FE22406A0F5BE36CD@pacer-server.pacer.local> References: <598B5E93DCDC614C9C1FE22406A0F5BE36CD@pacer-server.pacer.local> Message-ID: <200402031428.06645.nullpointer@heartoftn.net> On Tuesday 03 February 2004 13:08, philip gilchrist wrote: > Hi Pythoners > > My Son has challenged me to name a few careers that would use > Maths exponents and all the calculations in them as a way of > getting out of learning them. Obviously, programming and > basically anything to do with Computers is foremost in the > answer, but I was hoping that you studious types would be able to > supply me with more than the obvious answer. Not my particular career path, but . . . . Men's Room Attendant at an international airport You have to think about it a bit. <g> N.P. From CwiklaJ at diebold.com Tue Feb 3 15:03:20 2004 From: CwiklaJ at diebold.com (Cwikla, Joe) Date: Tue Feb 3 15:03:56 2004 Subject: [Tutor] Maths (slightly OT) Message-ID: <8711C7B083FE6F4FBD07F622FF8217EB0111C6FD@msexch14.diebold.com> Electrical Engineering. AC circuit analysis, Electromagnetics ... the list goes on. Without a solid knowledge of logs/exponents it's just impossible. And, when it comes to larger numbers, I find it easier to do everyday mental math with exponents. Let's see ... this yard is about 400 feet x 80 feet=(4x8)x(10**2)x(10**1)=32x10**3 sq feet Each bag of fertilizer covers 16,000 =16x10**3 sq feet per bag 32 10**3 -- X ----- = 'I'll take two bags please' 16 10**3 Good luck with your son, mine is 9 :-) Joe >Date: Tue, 3 Feb 2004 20:08:59 +0200 >From: "philip gilchrist" <philip@pacer.co.za> >Subject: [Tutor] Maths (slightly OT) >To: <Tutor@python.org> >Message-ID: > <598B5E93DCDC614C9C1FE22406A0F5BE36CD@pacer-server.pacer.local> >Content-Type: text/plain; charset="us-ascii" > >Hi Pythoners > >My Son has challenged me to name a few careers that would use Maths >exponents and all the calculations in them as a way of getting out of >learning them. Obviously, programming and basically anything to do with >Computers is foremost in the answer, but I was hoping that you studious >types would be able to supply me with more than the obvious answer. > >Hoping to hear from all the career people that can use Mathematical >Calculations on a regular basis. > > >regards, >Philip From abli at freemail.hu Tue Feb 3 15:09:15 2004 From: abli at freemail.hu (Abel Daniel) Date: Tue Feb 3 15:09:10 2004 Subject: [Tutor] Finding things in the docs, was: Re: special call for deleted objects? In-Reply-To: <200401302240.09010.thomi@thomi.imail.net.nz> (Thomas Clive Richards's message of "Fri, 30 Jan 2004 22:40:09 +1300") References: <200401301333.23303.thomi@thomi.imail.net.nz> <00f201c3e70b$63fa7240$6401a8c0@xp> <200401302240.09010.thomi@thomi.imail.net.nz> Message-ID: <E1Ao6rD-0000Es-00@hooloovoo> Thomas Clive Richards writes: > BTW, where can I find this information? Am I missing some documentation > somewhere? (I'm looking in the documentation distributed with python2.3)... __del__ is mentioned in the Language reference, section 3.3.1 Basic customization an online version is at: http://python.org/doc/2.3.3/ref/customization.html the non-official Python reference might come handy when looking for stuff ( its basically and index of the official docs ) : http://www.ferg.org/pyref/index.html -- Abel Daniel From abli at freemail.hu Tue Feb 3 15:52:27 2004 From: abli at freemail.hu (Abel Daniel) Date: Tue Feb 3 15:52:23 2004 Subject: [Tutor] Re: Using Python with VI In-Reply-To: <00a801c3e99b$dfb52820$b364a8c0@datatree> (Barry Smithers's message of "Mon, 2 Feb 2004 14:50:17 -0000") References: <00a801c3e99b$dfb52820$b364a8c0@datatree> Message-ID: <E1Ao7X2-00008H-00@hooloovoo> "Barry Smithers" writes: > I'm having difficulty with a program call from inside of VI. What I > basically need to do is get the line numbers input in the ex command. Or > maybe even get the text on those lines to go into a list. For example the > ex command ":20,21!xxx.py" would run xxx.py as a whole, but I need the data > currently on lines 20 and 21 for modification. This ex command expects the program you run (xxx.py) to be a filter: it should read on stdin and write to stdout. Something like this: --- import sys l=sys.stdin.readlines() # this l will be the list you need print "l:", l # print writes to stdout by default. Or you can use # sys.stdout.write() # (and .flush(), and .close(), just to be safe) --- I don't know how you could pass the _line_numbers_ (instead of the contents of the lines). -- Abel Daniel From david at graniteweb.com Tue Feb 3 17:04:37 2004 From: david at graniteweb.com (David Rock) Date: Tue Feb 3 17:04:43 2004 Subject: [Tutor] (no subject) In-Reply-To: <Sea2-DAV23UA51HLvsq0002f67a@hotmail.com> References: <Sea2-DAV23UA51HLvsq0002f67a@hotmail.com> Message-ID: <20040203220437.GA16943@wdfs.graniteweb.com> * Meisam Ganjeali darani <ganjeali@hotmail.com> [2004-02-02 11:46]: > Hi > > Thanks for your help. > > I have some question about python. > > How I can run python in my system? > > My system platform is windows The simplest thing is to go to http://www.python.org/download/ There you will find downloads for all kinds of platforms. -- David Rock david at graniteweb dot 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/20040203/26010670/attachment.bin From dana at momerath.us Tue Feb 3 20:53:57 2004 From: dana at momerath.us (dana@momerath.us) Date: Tue Feb 3 20:54:03 2004 Subject: [Tutor] HTMLParser, (no subject) In-Reply-To: <Pine.LNX.4.44.0402030945570.18668-100000@hkn.eecs.berkeley.edu> References: <3119.63.225.172.24.1075552557.squirrel@mail.zoper.com> <Pine.LNX.4.44.0402030945570.18668-100000@hkn.eecs.berkeley.edu> Message-ID: <2359.63.225.172.24.1075859637.squirrel@mail.zoper.com> > Welcome aboard! Your message is fine, but make sure to add a "subject > line" on your email, so that it's easier for people to find your message. > Yeah, I noticed that right after I sent the message and felt dumb about it. I'll do better next time. :) > (Also, if you haven't already, you may want to subscribe to Tutor --- > otherwise, your messages will be held until one of the lazy admins here > gets a chance to validate the message for non-spaminess. The page: > > http://mail.python.org/mailman/listinfo/tutor > > explains how to subscribe to Python-Tutor.) I was subscribed, but at a different address. Fixed. > There are two issues I can see so far: the newURL method looks a little > weird, and there's a bug in handle_starttag(). Let's cover the newURL() > method briefly: > >> def newURL(self, URL): >> __init__(self, URL) > > > This looks a little weird because no __init__ method has yet been defined. > Can you explain what newURL is trying to do? And do you need it? I don't > see anything in the code that uses it, so maybe it can be removed? > > > Let's take a look at handle_starttag(): > >> def handle_starttag(self, tag, attrs): >> print "tag is %s with attributes %s." %(self, tag, attrs) > ^^ ^^ ^^^^ ^^^ ^^^^^ > > There are two formatting positions in the string, but the code is trying > to fill it up with three things. Given that, does the error message: > > >> File "r.py", line 31, in handle_starttag >> print "tag is %s with attributes %s." %(self, tag, attrs) >> TypeError: not all arguments converted during string formatting > > make sense now? I found and fixed the main problem while I was waiting for you "lazy admins" to approve my post. :) As for the newURL() method, when I wrote it I was thinking that I would need to call the same InteractiveURLParser instance again for different URLs and that it was necessary to call the __init__() method to do that. Now I see that calling the close() method and then the open() method again would be the way to do that. I think. I'll have to play with it. Thank you! Dana From missive at hotmail.com Tue Feb 3 21:28:24 2004 From: missive at hotmail.com (Lee Harr) Date: Tue Feb 3 21:28:29 2004 Subject: [Tutor] Re: Maths (slightly OT) Message-ID: <BAY2-F148aK7QlhSEVN000133f0@hotmail.com> >My Son has challenged me to name a few careers that would use Maths >exponents and all the calculations in them as a way of getting out of >learning them. Obviously, programming and basically anything to do with >Computers is foremost in the answer, but I was hoping that you studious >types would be able to supply me with more than the obvious answer. > >Hoping to hear from all the career people that can use Mathematical >Calculations on a regular basis. > Pretty much any business... Think about the people sitting around a boardroom table looking at a bunch of "charts". Presumably those charts were created by plotting numbers and applying different statistical methods to try to make out what the charts "mean". They say that something like 90% of all new businesses fail. My feeling is that many of them fail not because their owners are not good at what they do, but because they do not have a good handle on the numbers --- ie. "am I able to make a profit?" Exponents are particularly import to business people because of compound interest and the way you can make a serious fortune by investing your money wisely. _________________________________________________________________ STOP MORE SPAM with the new MSN 8 and get 2 months FREE* http://join.msn.com/?page=features/junkmail From isrgish at fusemail.com Tue Feb 3 22:47:47 2004 From: isrgish at fusemail.com (Isr Gish) Date: Tue Feb 3 22:48:16 2004 Subject: [Tutor] glob module Message-ID: <E1AoE18-0004is-IP@fuse1.fusemail.net> I want to get a list of all files from a folder with a certain pattern. But I want to look in sub folders also Example: Lets say I have this dir tree Docs recipes new old help all ... I want to find all files with "a*.txt" from whole tree of Docs how would I do that. I understand that I could iterate the whole tree. But what I would like to know, if it can be done, with the glob module. Thanks for any help Isr From david at graniteweb.com Wed Feb 4 00:05:48 2004 From: david at graniteweb.com (David Rock) Date: Wed Feb 4 00:06:15 2004 Subject: [Tutor] glob module In-Reply-To: <E1AoE18-0004is-IP@fuse1.fusemail.net> References: <E1AoE18-0004is-IP@fuse1.fusemail.net> Message-ID: <40207DAC.70300@graniteweb.com> Isr Gish wrote: > I want to get a list of all files from a folder with a certain pattern. > But I want to look in sub folders also > > Example: > Lets say I have this dir tree > > Docs > recipes > new > old > help > all > ... You are probably looking for something like this: http://www.python.org/doc/current/lib/os-file-dir.html#l2h-1473 -- David Rock david@graniteweb.com -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 254 bytes Desc: OpenPGP digital signature Url : http://mail.python.org/pipermail/tutor/attachments/20040203/e1994d0f/signature.bin From dyoo at hkn.eecs.berkeley.edu Wed Feb 4 01:26:41 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Feb 4 01:27:02 2004 Subject: [Tutor] Maths (slightly OT) In-Reply-To: <2ksv1090cbgemb7m8grftehtbu5c8tvcfh@4ax.com> Message-ID: <Pine.LNX.4.44.0402031404130.19100-100000@hkn.eecs.berkeley.edu> > >Hoping to hear from all the career people that can use Mathematical > >Calculations on a regular basis. Hi Philip, Math is not an artificial construct, but a very human endeavor: http://perso.unifr.ch/rafael.nunez/ The reason people reason with exponentials is because they're part of our common human experience. People have mentioned compound interest to appeal to the financial side of things. Maybe your son isn't that much into finance. But perhaps your son is into fairy tales. Show him the story about A Grain of Rice: http://www.lhsgems.org/MAWConx.html#grain The story goes that there's a beggar who once does a favor to a king. The king owes him, so he asks the beggar to choose his own reward. The beggar asks for a single grain of rice, and to have his amount of rice double every day, for one hundred days. The king, not knowing much about exponentials, foolishly agrees. ### >>> def count_grains_of_rice(day): ... if day == 1: return 1 ... else: return 2 * count_grains_of_rice(day - 1) ... >>> count_grains_of_rice(1) 1 >>> count_grains_of_rice(2) 2 >>> count_grains_of_rice(3) 4 >>> count_grains_of_rice(4) 8 ### Not too scary so far. 8 grains of rice? Bah, that's nothing. What do things look like on the hundredth day? ### >>> count_grains_of_rice(100) 633825300114114700748351602688L ### That's a honking large number. *grin* What does this have to do with exponentials? It turns out that the function we've written is equivalent to: ### >>> def f(x): ... return 2**(x-1) ... >>> f(1) 1 >>> f(2) 2 >>> f(100) 633825300114114700748351602688L ### That's exponential growth. We use exponentials because they're one of the standard ways we can describe such tremendous rates of change. And these things happen in real life, in both natural and unnatural situations. > The obvious answer to your question is: a mathematician. Physicists also > use a lot of mathematics, in fact a lot of mathematical research is > motivated by problems in physics. Computer science is one of those "unnatural" sciences, and computer scientists use math very heavily. The kind of mathematics that CS students use, though, might be much different than one might expect --- unlike Physics, CS depends less on calculus, and more on discrete math. Programmers eventually need to understand exponentials, because programs that take exponential time to complete are pretty useless programs. We need to know about exponentials in order to recognize (and avoid writing) programs that take exponential time to solve problems. > Having said this, let me add that mathematics is being applied to > various subjects. People studying DNA use knot theory, biologists model > the evolution of populations using differential equations, economists > use game theory, sociologists make heavy use of statistics, research in > computer science makes heavy use of category theory, and the list goes > on. Biologists also use discrete math quite a bit. As a concrete example of the kind of mathematics involved in molecular biology and computer science, you might want to browse 'Algorithms on Strings, Trees, and Sequences: Computer Science and Computational Biology': http://wwwcsif.cs.ucdavis.edu/~gusfield/paperlist.html The kind of mathematics that's used there is heavy on proof techniques and reasoning about recursive data structures. The book may not use many exponents or integral signs, but it does have sigma summation signs everywhere. But computer scientists do use calculus --- in particular, it provides very useful tools in the analysis of recurrence relations: http://www.math.upenn.edu/~wilf/DownldGF.html (The program at the very top, the count_grains_of_sand() function, is an implementation of a "recurrence relation" as code.) Anyway, that link to the 'Literature Connections to Math Around the World' from the very top of this post may be useful. http://www.lhsgems.org/MAWConx.html Your son may still doubt you after reading some of the books listed there, but at least he'll be mildly entertained for a few minutes. *grin* Talk to you later! From janwillem.maaskant at planet.nl Wed Feb 4 10:47:28 2004 From: janwillem.maaskant at planet.nl (jan willem maaskant) Date: Wed Feb 4 11:23:52 2004 Subject: [Tutor] comparing lists of strings with each other Message-ID: <LMEHIMHHOPJPEDCPCOLFAECJCCAA.janwillem.maaskant@planet.nl> Hello, i have a problem, with comparison of two strings in a list using the filter function. and i really don't know the solution. Here is the problem. i have two lists filled with strings and i want to filter the strings from one list out of the other. for example: listOne = [ 'a','b','c'] listTwo = ['a','c'] i want to remove the strings in listOne which are equal to the strings in listTwo. So the list i want to have must look like this. listThree = ['b'] i tried it with the following code: >>> def removeStrings(list): for key in listTwo: if key != list: return list >>> listThree = filter(removeStrings, listOne) however this results in >>> listThree ['a', 'b', 'c'] >>> so this is wrong, but what i really don't understand, is why the opposite seems to work quite fine if I put this code in >>> def removeStrings(list): for key in listTwo: if key == list: # i changed the comparison operator return list than the function gives exactly what i expected: >>> listThree = filter(removeStrings, listOne) >>> listThree ['a', 'c'] So i'm obviously missing something here, but i'm out of solutions and i am not able to find it in any of my books. I would be very much helped if somebody could explain this to me jan willem maaskant From gerrit at nl.linux.org Wed Feb 4 11:30:08 2004 From: gerrit at nl.linux.org (Gerrit) Date: Wed Feb 4 11:30:18 2004 Subject: [Tutor] glob module In-Reply-To: <E1AoE18-0004is-IP@fuse1.fusemail.net> References: <E1AoE18-0004is-IP@fuse1.fusemail.net> Message-ID: <20040204163008.GA5327@nl.linux.org> Isr Gish wrote: > Docs > recipes > new > old > help > all > ... > I want to find all files with "a*.txt" from whole tree of Docs how would I do that. I understand that I could iterate the whole tree. But what I would like to know, if it can be done, with the glob module. If it's always 3 levels deep, you can use '*/*/a*.txt'. That makes using os.walk unnecesary. Gerrit. -- PrePEP: Builtin path type http://people.nl.linux.org/~gerrit/creaties/path/pep-xxxx.html Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From pythontutor at venix.com Wed Feb 4 12:37:12 2004 From: pythontutor at venix.com (Lloyd Kvam) Date: Wed Feb 4 12:37:30 2004 Subject: [Tutor] comparing lists of strings with each other In-Reply-To: <LMEHIMHHOPJPEDCPCOLFAECJCCAA.janwillem.maaskant@planet.nl> References: <LMEHIMHHOPJPEDCPCOLFAECJCCAA.janwillem.maaskant@planet.nl> Message-ID: <40212DC8.4000304@venix.com> > for key in listTwo: > if key != list: # this is line is not what you really want > return list You really wanted: if key not in list: In Python2.3 there is now a sets module. I've been going wild using it in my unit testing scripts. The sets module makes it VERY easy to convert lists to Sets and determine the differences between Sets. jan willem maaskant wrote: > Hello, > i have a problem, with comparison of two strings in a list using the filter > function. > and i really don't know the solution. > > Here is the problem. > > i have two lists filled with strings and i want to filter the strings from > one list out of the other. > > for example: > > listOne = [ 'a','b','c'] > listTwo = ['a','c'] > > i want to remove the strings in listOne which are equal to the strings in > listTwo. > So the list i want to have must look like this. > > listThree = ['b'] > > i tried it with the following code: > > >>>>def removeStrings(list): > > for key in listTwo: > if key != list: > return list > > > >>>>listThree = filter(removeStrings, listOne) > > however this results in > >>>>listThree > > ['a', 'b', 'c'] > > > so this is wrong, but what i really don't understand, is why the opposite > seems to work quite fine > if I put this code in > > >>>>def removeStrings(list): > > for key in listTwo: > if key == list: # i changed the comparison operator > return list > > than the function gives exactly what i expected: > > >>>>listThree = filter(removeStrings, listOne) >>>>listThree > > ['a', 'c'] > > So i'm obviously missing something here, but i'm out of solutions and i am > not able to find it in any of my books. > I would be very much helped if somebody could explain this to me > > jan willem maaskant > > > _______________________________________________ > 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 rmkrauter at yahoo.com Wed Feb 4 12:38:46 2004 From: rmkrauter at yahoo.com (Rich Krauter) Date: Wed Feb 4 12:38:55 2004 Subject: [Tutor] comparing lists of strings with each other Message-ID: <20040204173847.54392.qmail@web40106.mail.yahoo.com> If you trace out each step of what filter is doing, you'll see why you are getting what you are getting. By using filter, you are passing each element of the first list into your comparison function. Your comparison function compares the passed-in item with each item in the second list, and returns the item (a true value) when the two are not equal: 'a' in list1 != 'c' in list2, so 'a' is returned 'b' in list1 != 'a' in list2, so 'b' is returned 'c' in list1 != 'a' in list2, so 'c' is returned Filter is documented here: http://www.python.org/doc/current/lib/built-in-funcs.html#l2h-26 You can do this without filter, using list membership tests: >>> newlist = [] >>> for x in list1: ... if x not in list2: ... newlist.append(x) or >>> f = lambda i: i not in list2 >>> filter(f,list1) >>> ['b'] One way you can do what you want in python 2.3 is with sets: >>> import sets >>> a1 = ['a','b','c'] >>> a2 = ['a','c'] >>> s1 = sets.Set(a1) >>> s2 = sets.Set(a2) #find all elements of s1 not in s2 >>> list(s1-s2) ['b'] Rich __________________________________ Do you Yahoo!? Yahoo! SiteBuilder - Free web site building tool. Try it! http://webhosting.yahoo.com/ps/sb/ From pythontutor at venix.com Wed Feb 4 12:56:20 2004 From: pythontutor at venix.com (Lloyd Kvam) Date: Wed Feb 4 12:56:27 2004 Subject: [Tutor] comparing lists of strings with each other In-Reply-To: <20040204173847.54392.qmail@web40106.mail.yahoo.com> References: <20040204173847.54392.qmail@web40106.mail.yahoo.com> Message-ID: <40213244.7030002@venix.com> Good thing you are watching Rich. I scanned right past the use of filter. The variable name "list" convinced me I was looking at a list. (Actually list is also a bad choice for variable name because it hides the builtin list.) Rich Krauter wrote: > If you trace out each step of what filter is doing, > you'll see why you are getting what you are getting. > > By using filter, you are passing each element of the > first list into your comparison function. Your > comparison function compares the passed-in item with > each item in the second list, and returns the item (a > true value) when the two are not equal: > > 'a' in list1 != 'c' in list2, so 'a' is returned > 'b' in list1 != 'a' in list2, so 'b' is returned > 'c' in list1 != 'a' in list2, so 'c' is returned > > Filter is documented here: > http://www.python.org/doc/current/lib/built-in-funcs.html#l2h-26 > > You can do this without filter, using list membership > tests: > >>>>newlist = [] >>>>for x in list1: > > ... if x not in list2: > ... newlist.append(x) > > or > > >>>>f = lambda i: i not in list2 >>>>filter(f,list1) >>>>['b'] > > > One way you can do what you want in python 2.3 is with > sets: > >>>>import sets >>>>a1 = ['a','b','c'] >>>>a2 = ['a','c'] >>>>s1 = sets.Set(a1) >>>>s2 = sets.Set(a2) > > > #find all elements of s1 not in s2 > >>>>list(s1-s2) > > ['b'] > > Rich > > __________________________________ > Do you Yahoo!? > Yahoo! SiteBuilder - Free web site building tool. Try it! > http://webhosting.yahoo.com/ps/sb/ > > _______________________________________________ > 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 idiot1 at netzero.net Wed Feb 4 12:55:27 2004 From: idiot1 at netzero.net (Kirk Bailey) Date: Wed Feb 4 12:56:38 2004 Subject: [Tutor] globbing and sorting and dating, oh my! Message-ID: <4021320F.8090608@netzero.net> Ok, I want to write a WHAT'S NEW function for wikinehesa the wikiwikiweb system I wrote in python. This is something to sort through available pages, organize/sort according to date, chop off that portion of the list which is older than FOO days old, and concert the date to something mere normals will comprehend, then print each item as a line in a web page- as a link of course. NATURALLY I grok the html part. converting data data to calendar is a little odd to me, and I am considering several ways to organize the data- and as arrays are not inherent to python, I am going to use several parallel lists instead. I throw open the front door to discussion, suggestions, ON TOPIC BAUDY HUMOR, and anything else that fits in through the door. If the dates are a list, and I sort the list, the corresponding list of filenames no longer corresponds. THIS is an issue which looms large in my army surplus used brain. -- end think http://www.tinylist.org/ - $FREE$ software for liberty +-------+ http://www.pinellasintergroupsociety.org/ - In Her Service | BOX | http://www.listville.net/ - $FREE$ list hosting services +-------+ http://www.howlermonkey.net/ - $FREE$ email service kniht http://www.sacredelectron.org/ - My personal SCREED pit (C)2004 Kirk D Bailey, all rights reserved- but ask! From sigurd at 12move.de Wed Feb 4 13:04:33 2004 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Wed Feb 4 13:06:12 2004 Subject: [Tutor] comparing lists of strings with each other In-Reply-To: <LMEHIMHHOPJPEDCPCOLFAECJCCAA.janwillem.maaskant@planet.nl> (jan willem maaskant's message of "Wed, 04 Feb 2004 16:47:28 +0100") References: <LMEHIMHHOPJPEDCPCOLFAECJCCAA.janwillem.maaskant@planet.nl> Message-ID: <m3d68ud9cj.fsf@hamster.pflaesterer.de> jan willem maaskant <- janwillem.maaskant@planet.nl wrote: > i have a problem, with comparison of two strings in a list using the filter > function. > and i really don't know the solution. [...] > for example: > listOne = [ 'a','b','c'] > listTwo = ['a','c'] > i want to remove the strings in listOne which are equal to the strings in > listTwo. > So the list i want to have must look like this. > listThree = ['b'] > i tried it with the following code: >>>> def removeStrings(list): > for key in listTwo: > if key != list: > return list Do not use list as parameter; it's a builtin. Did you read what the filter function does? It iterates over a sequence and returns those elemenst for which the functions returns a true value. Above function will always return True for the values you gave; e.g: a != c => True b != a => True c != a => True >>>> listThree = filter(removeStrings, listOne) > however this results in >>>> listThree > ['a', 'b', 'c'] So the result is exactly that what you asked for. > seems to work quite fine > if I put this code in >>>> def removeStrings(list): > for key in listTwo: > if key == list: # i changed the comparison operator > return list > than the function gives exactly what i expected: >>>> listThree = filter(removeStrings, listOne) >>>> listThree > ['a', 'c'] Above you wrote you wanted the difference between the two lists. Now you write the intersection is what you want? Which one is true? Anyway I assume you meant what you first wrote. First a solution nearly the same as yours. What you need is a function which returns *False* if a value from one list is not in the other list. Python has something like that builtin; `in' >>> L = [1,2,3] >>> 1 in L True >>> 4 in L False >>> So you simply have to call `in' for the elements of list1 with list2 and negate the result. >>> listOne = [ 'a','b','c'] >>> listTwo = ['a','c'] >>> filter(lambda el: not el in listTwo, listOne) ['b'] >>> If you wanted the intersection just don't negate the result. If you have longer lists it might be better to use the new set module (it works with dictionaries) otherwise the code might be to slow. Karl -- Please do *not* send copies of replies to me. I read the list From littledanehren at yahoo.com Wed Feb 4 15:13:10 2004 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Wed Feb 4 15:13:16 2004 Subject: [Tutor] globbing and sorting and dating, oh my! In-Reply-To: <4021320F.8090608@netzero.net> Message-ID: <20040204201310.30288.qmail@web41812.mail.yahoo.com> Kirk Bailey wrote: > Ok, I want to write a WHAT'S NEW function for > wikinehesa the > wikiwikiweb system I wrote in python. This is > something to sort > through available pages, organize/sort according to > date, chop off > that portion of the list which is older than FOO > days old, and concert > the date to something mere normals will comprehend, > then print each > item as a line in a web page- as a link of course. > NATURALLY I grok > the html part. converting data data to calendar is a > little odd to me, > and I am considering several ways to organize the > data- and as arrays > are not inherent to python, I am going to use > several parallel lists > instead. I throw open the front door to discussion, > suggestions, ON > TOPIC BAUDY HUMOR, and anything else that fits in > through the door. > > If the dates are a list, and I sort the list, the > corresponding list > of filenames no longer corresponds. THIS is an issue > which looms large > in my army surplus used brain. > -- > > > end > > > think http://www.tinylist.org/ - $FREE$ > software for liberty > +-------+ http://www.pinellasintergroupsociety.org/ > - In Her Service > | BOX | http://www.listville.net/ - $FREE$ list > hosting services > +-------+ http://www.howlermonkey.net/ - $FREE$ > email service > kniht http://www.sacredelectron.org/ - My > personal SCREED pit > (C)2004 Kirk D Bailey, all rights > reserved- but ask! Try zipping the lists together and then sorting it. Be sure that the one you want to sort by is first. Daniel Ehrenberg __________________________________ Do you Yahoo!? Yahoo! SiteBuilder - Free web site building tool. Try it! http://webhosting.yahoo.com/ps/sb/ From anna at aleax.it Wed Feb 4 15:37:12 2004 From: anna at aleax.it (Anna Ravenscroft) Date: Wed Feb 4 15:37:21 2004 Subject: [Tutor] globbing and sorting and dating, oh my! In-Reply-To: <4021320F.8090608@netzero.net> References: <4021320F.8090608@netzero.net> Message-ID: <200402042137.12960.anna@aleax.it> On Wednesday 04 February 2004 06:55 pm, Kirk Bailey wrote: > If the dates are a list, and I sort the list, the corresponding list > of filenames no longer corresponds. THIS is an issue which looms large > in my army surplus used brain. I'd consider using a dict. Python dicts are fast, easy to use, and highly useful. mydict = {key1:value1, key2:value2} You can use dates as the keys (and any lists or strings or combination thereof as the values), pull a list of the keys using d.keys(), sort them, remove any that are old, then use the remaining list to pull the corresponding values into a new dict or list for display. Or, use a list comprehension directly on the dict to get a list of new items (since you don't really *have* to sort them by date, do you?). It'll give you a new list of tuples, which you can pass to a new dict if you want to: newstuph = dict( [(date, mydict[date]) for date in mydict if date > olddate] ) Hope this helps. Anna -- There is a type 3 error in which your mind goes totally blank whenever you try to remember which is which of type 1 and type 2. -Richard Dawkins -- There is a type 3 error in which your mind goes totally blank whenever you try to remember which is which of type 1 and type 2. -Richard Dawkins From anna at aleax.it Wed Feb 4 15:39:32 2004 From: anna at aleax.it (Anna Ravenscroft) Date: Wed Feb 4 15:39:42 2004 Subject: [Tutor] comparing lists of strings with each other In-Reply-To: <LMEHIMHHOPJPEDCPCOLFAECJCCAA.janwillem.maaskant@planet.nl> References: <LMEHIMHHOPJPEDCPCOLFAECJCCAA.janwillem.maaskant@planet.nl> Message-ID: <200402042139.32255.anna@aleax.it> On Wednesday 04 February 2004 04:47 pm, jan willem maaskant wrote: > i have two lists filled with strings and i want to filter the strings from > one list out of the other. You'd be better off with a list comprehension. threelist = [i for i in onelist if i not in twolist] But, if you really must use filter for some reason....: > for example: > > listOne = [ 'a','b','c'] > listTwo = ['a','c'] > > i want to remove the strings in listOne which are equal to the strings in > listTwo. > So the list i want to have must look like this. > > listThree = ['b'] > > i tried it with the following code: > >>> def removeStrings(list): > > for key in listTwo: > if key != list: > return list > > >>> listThree = filter(removeStrings, listOne) First, you really really don't want to use "list" as an argument or variable name. list is one of the built-in types in Python, and you *REALLY* don't want to use it as a variable name. > however this results in > > >>> listThree > > ['a', 'b', 'c'] > > > so this is wrong, but what i really don't understand, is why the opposite > seems to work quite fine > if I put this code in Okay, in order to see what's happening, I added some print statements to the function. then ran the whole thing again. alist = ['d', 'b', 'c'] blist = ['d', 'f', 'b'] def remstring(item): print 'filter passes item', item for key in blist: print "key is ", key if key != item: print "key != item. returning", item return item clist = filter(remstring, alist) print clist >>> filter passes item d key is d key is f key != item. returning d filter passes item b key is d key != item. returning b filter passes item c key is d key != item. returning c ['d', 'b', 'c'] >>> Does this help you see what's happening? HTH, Anna -- There is a type 3 error in which your mind goes totally blank whenever you try to remember which is which of type 1 and type 2. -Richard Dawkins From michel.belanger at seidel.ca Wed Feb 4 16:35:34 2004 From: michel.belanger at seidel.ca (=?ISO-8859-1?Q?Michel_B=E9langer?=) Date: Wed Feb 4 17:11:07 2004 Subject: [Tutor] Executable file version in windows Message-ID: <402165A6.90301@seidel.ca> Hi, How can I query a file executable (exe, dll, com)for its version including the revision, i.e. exemple: >>>queryVersion("someprog.exe") 5.1.2 Michel Belanger From kim.branson at csiro.au Wed Feb 4 08:34:12 2004 From: kim.branson at csiro.au (Kim Branson) Date: Wed Feb 4 17:45:02 2004 Subject: [Tutor] reg exps Message-ID: <D15BFACA-5716-11D8-A603-000A9579AE94@csiro.au> Hi all, i'm trying to get my head around regexps in python. i've now found the difference between the .match and the .search methods. (i'm used to perl :) i have a program which will spit out data like so: % ~/Desktop/Dock4_osx/bin/scorer 1rx3.pdb dock_nrg.mol2 PK= 6.08 Qual= 2.12 PMF= -159.15 PMF_rb= -144.15 SMoG= -161.27 SMoG_H= -7.68 ChemScore= -23.86 Clash= 0.85 Int= 2.58 DockNRG= -24.51 AutoDock= -20.14 so i'm working on a script which has a function (below) that checks for this data (the program called can spit out other data when inputs are bad) then grabs the matches. so now i'm making dictionaries for each field, using the line number as a key. my pattern match does not return the first match in the list in position 0. i.e [' ', ' 6.08', ' 2.12', '-159.15', '-144.15', '-161.27', '-7.68', '-23.86', ' 0.85', ' 2.58', '-24.51', '-20.14', '\n'] so i'm grabbing the data from position 1 in the list etc, and working from there. Why is this, is this a default behaviour? note the values in the output can be negative or really large, as in PK= -6.08 etc, or Qual= 12.12 so i use (.*) to grab the region. Oh one more thing, if you declare a global, can i simply add dictionary content, or should one declare and then initialise? def score_orientations(): counter = 1 global score_dict global qual_dict global pmf_dict global pmf_rb_dict global smog_dict global smog_h_dict global chemscore_dict global clash_dict global int_dict global docknrg_dict global autodock_dict score_dict = {} qual_dict = {} pmf_dict = {} pmf_rb_dict = {} smog_dict = {} smog_h_dict = {} chemscore_dict = {} clash_dict = {} int_dict = {} docknrg_dict = {} autodock_dict = {} score_lines = re.compile('PK= (.*) Qual= (.*) PMF= (.*) PMF_rb= (.*) SMoG= (.*) SMoG_H= (.*) ChemScore= (.*) Clash= (.*) Int= (.*) DockNRG= (.*) AutoDock= (.*)') results = os.popen2('/Users/kbranson/Desktop/Dock4_osx/bin/scorer %s dock_nrg.mol2' % receptor_pdb) results_data = results[1].readlines() for line in results_data: if (score_lines.search(line)): line = re.split(score_lines, line) score_dict[counter] = line[1] qual_dict[counter] = line[2] pmf_dict[counter] = line[3] pmf_rb_dict[counter] = line[4] smog_dict[counter] = line[5] smog_h_dict[counter] = line[6] chemscore_dict[counter] = line[7] clash_dict[counter] = line[8] int_dict[counter] = line[9] docknrg_dict[counter] = line[10] autdock_dict[counter] = line[11] counter = counter + 1 print score_dict score_orientations() From janwillem.maaskant at planet.nl Wed Feb 4 17:59:20 2004 From: janwillem.maaskant at planet.nl (jan willem maaskant) Date: Wed Feb 4 18:07:51 2004 Subject: [Tutor] RE: comparing list of strings with each other In-Reply-To: <E1AoVla-0006Nj-C8@mail.python.org> Message-ID: <LMEHIMHHOPJPEDCPCOLFMECKCCAA.janwillem.maaskant@planet.nl> thanks every one, for your quick response. i have still some more studying to do. with all the answers that i got. greetings, jan willem. -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org]On Behalf Of tutor-request@python.org Sent: woensdag 4 februari 2004 23:45 To: tutor@python.org Subject: Tutor Digest, Vol 7, Issue 10 Send Tutor mailing list submissions to tutor@python.org To subscribe or unsubscribe via the World Wide Web, visit http://mail.python.org/mailman/listinfo/tutor or, via email, send a message with subject or body 'help' to tutor-request@python.org You can reach the person managing the list at tutor-owner@python.org When replying, please edit your Subject line so it is more specific than "Re: Contents of Tutor digest..." Today's Topics: 1. Re: comparing lists of strings with each other (Lloyd Kvam) 2. comparing lists of strings with each other (Rich Krauter) 3. Re: comparing lists of strings with each other (Lloyd Kvam) 4. globbing and sorting and dating, oh my! (Kirk Bailey) 5. Re: comparing lists of strings with each other (Karl Pfl?sterer ) 6. Re: globbing and sorting and dating, oh my! (Daniel Ehrenberg) 7. Re: globbing and sorting and dating, oh my! (Anna Ravenscroft) 8. Re: comparing lists of strings with each other (Anna Ravenscroft) 9. Executable file version in windows (Michel B?langer) 10. reg exps (Kim Branson) ---------------------------------------------------------------------- Message: 1 Date: Wed, 04 Feb 2004 12:37:12 -0500 From: Lloyd Kvam <pythontutor@venix.com> Subject: Re: [Tutor] comparing lists of strings with each other To: jan willem maaskant <janwillem.maaskant@planet.nl> Cc: tutor@python.org Message-ID: <40212DC8.4000304@venix.com> Content-Type: text/plain; charset=us-ascii; format=flowed > for key in listTwo: > if key != list: # this is line is not what you really want > return list You really wanted: if key not in list: In Python2.3 there is now a sets module. I've been going wild using it in my unit testing scripts. The sets module makes it VERY easy to convert lists to Sets and determine the differences between Sets. jan willem maaskant wrote: > Hello, > i have a problem, with comparison of two strings in a list using the filter > function. > and i really don't know the solution. > > Here is the problem. > > i have two lists filled with strings and i want to filter the strings from > one list out of the other. > > for example: > > listOne = [ 'a','b','c'] > listTwo = ['a','c'] > > i want to remove the strings in listOne which are equal to the strings in > listTwo. > So the list i want to have must look like this. > > listThree = ['b'] > > i tried it with the following code: > > >>>>def removeStrings(list): > > for key in listTwo: > if key != list: > return list > > > >>>>listThree = filter(removeStrings, listOne) > > however this results in > >>>>listThree > > ['a', 'b', 'c'] > > > so this is wrong, but what i really don't understand, is why the opposite > seems to work quite fine > if I put this code in > > >>>>def removeStrings(list): > > for key in listTwo: > if key == list: # i changed the comparison operator > return list > > than the function gives exactly what i expected: > > >>>>listThree = filter(removeStrings, listOne) >>>>listThree > > ['a', 'c'] > > So i'm obviously missing something here, but i'm out of solutions and i am > not able to find it in any of my books. > I would be very much helped if somebody could explain this to me > > jan willem maaskant > > > _______________________________________________ > 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 ------------------------------ Message: 2 Date: Wed, 4 Feb 2004 09:38:46 -0800 (PST) From: Rich Krauter <rmkrauter@yahoo.com> Subject: [Tutor] comparing lists of strings with each other To: tutor@python.org Message-ID: <20040204173847.54392.qmail@web40106.mail.yahoo.com> Content-Type: text/plain; charset=us-ascii If you trace out each step of what filter is doing, you'll see why you are getting what you are getting. By using filter, you are passing each element of the first list into your comparison function. Your comparison function compares the passed-in item with each item in the second list, and returns the item (a true value) when the two are not equal: 'a' in list1 != 'c' in list2, so 'a' is returned 'b' in list1 != 'a' in list2, so 'b' is returned 'c' in list1 != 'a' in list2, so 'c' is returned Filter is documented here: http://www.python.org/doc/current/lib/built-in-funcs.html#l2h-26 You can do this without filter, using list membership tests: >>> newlist = [] >>> for x in list1: ... if x not in list2: ... newlist.append(x) or >>> f = lambda i: i not in list2 >>> filter(f,list1) >>> ['b'] One way you can do what you want in python 2.3 is with sets: >>> import sets >>> a1 = ['a','b','c'] >>> a2 = ['a','c'] >>> s1 = sets.Set(a1) >>> s2 = sets.Set(a2) #find all elements of s1 not in s2 >>> list(s1-s2) ['b'] Rich __________________________________ Do you Yahoo!? Yahoo! SiteBuilder - Free web site building tool. Try it! http://webhosting.yahoo.com/ps/sb/ ------------------------------ Message: 3 Date: Wed, 04 Feb 2004 12:56:20 -0500 From: Lloyd Kvam <pythontutor@venix.com> Subject: Re: [Tutor] comparing lists of strings with each other To: tutor@python.org Message-ID: <40213244.7030002@venix.com> Content-Type: text/plain; charset=us-ascii; format=flowed Good thing you are watching Rich. I scanned right past the use of filter. The variable name "list" convinced me I was looking at a list. (Actually list is also a bad choice for variable name because it hides the builtin list.) Rich Krauter wrote: > If you trace out each step of what filter is doing, > you'll see why you are getting what you are getting. > > By using filter, you are passing each element of the > first list into your comparison function. Your > comparison function compares the passed-in item with > each item in the second list, and returns the item (a > true value) when the two are not equal: > > 'a' in list1 != 'c' in list2, so 'a' is returned > 'b' in list1 != 'a' in list2, so 'b' is returned > 'c' in list1 != 'a' in list2, so 'c' is returned > > Filter is documented here: > http://www.python.org/doc/current/lib/built-in-funcs.html#l2h-26 > > You can do this without filter, using list membership > tests: > >>>>newlist = [] >>>>for x in list1: > > ... if x not in list2: > ... newlist.append(x) > > or > > >>>>f = lambda i: i not in list2 >>>>filter(f,list1) >>>>['b'] > > > One way you can do what you want in python 2.3 is with > sets: > >>>>import sets >>>>a1 = ['a','b','c'] >>>>a2 = ['a','c'] >>>>s1 = sets.Set(a1) >>>>s2 = sets.Set(a2) > > > #find all elements of s1 not in s2 > >>>>list(s1-s2) > > ['b'] > > Rich > > __________________________________ > Do you Yahoo!? > Yahoo! SiteBuilder - Free web site building tool. Try it! > http://webhosting.yahoo.com/ps/sb/ > > _______________________________________________ > 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 ------------------------------ Message: 4 Date: Wed, 04 Feb 2004 12:55:27 -0500 From: Kirk Bailey <idiot1@netzero.net> Subject: [Tutor] globbing and sorting and dating, oh my! To: tutor@python.org Message-ID: <4021320F.8090608@netzero.net> Content-Type: text/plain; charset=us-ascii; format=flowed Ok, I want to write a WHAT'S NEW function for wikinehesa the wikiwikiweb system I wrote in python. This is something to sort through available pages, organize/sort according to date, chop off that portion of the list which is older than FOO days old, and concert the date to something mere normals will comprehend, then print each item as a line in a web page- as a link of course. NATURALLY I grok the html part. converting data data to calendar is a little odd to me, and I am considering several ways to organize the data- and as arrays are not inherent to python, I am going to use several parallel lists instead. I throw open the front door to discussion, suggestions, ON TOPIC BAUDY HUMOR, and anything else that fits in through the door. If the dates are a list, and I sort the list, the corresponding list of filenames no longer corresponds. THIS is an issue which looms large in my army surplus used brain. -- end think http://www.tinylist.org/ - $FREE$ software for liberty +-------+ http://www.pinellasintergroupsociety.org/ - In Her Service | BOX | http://www.listville.net/ - $FREE$ list hosting services +-------+ http://www.howlermonkey.net/ - $FREE$ email service kniht http://www.sacredelectron.org/ - My personal SCREED pit (C)2004 Kirk D Bailey, all rights reserved- but ask! ------------------------------ Message: 5 Date: Wed, 04 Feb 2004 19:04:33 +0100 From: sigurd@12move.de (Karl Pfl?sterer ) Subject: Re: [Tutor] comparing lists of strings with each other To: tutor@python.org Message-ID: <m3d68ud9cj.fsf@hamster.pflaesterer.de> Content-Type: text/plain; charset=us-ascii jan willem maaskant <- janwillem.maaskant@planet.nl wrote: > i have a problem, with comparison of two strings in a list using the filter > function. > and i really don't know the solution. [...] > for example: > listOne = [ 'a','b','c'] > listTwo = ['a','c'] > i want to remove the strings in listOne which are equal to the strings in > listTwo. > So the list i want to have must look like this. > listThree = ['b'] > i tried it with the following code: >>>> def removeStrings(list): > for key in listTwo: > if key != list: > return list Do not use list as parameter; it's a builtin. Did you read what the filter function does? It iterates over a sequence and returns those elemenst for which the functions returns a true value. Above function will always return True for the values you gave; e.g: a != c => True b != a => True c != a => True >>>> listThree = filter(removeStrings, listOne) > however this results in >>>> listThree > ['a', 'b', 'c'] So the result is exactly that what you asked for. > seems to work quite fine > if I put this code in >>>> def removeStrings(list): > for key in listTwo: > if key == list: # i changed the comparison operator > return list > than the function gives exactly what i expected: >>>> listThree = filter(removeStrings, listOne) >>>> listThree > ['a', 'c'] Above you wrote you wanted the difference between the two lists. Now you write the intersection is what you want? Which one is true? Anyway I assume you meant what you first wrote. First a solution nearly the same as yours. What you need is a function which returns *False* if a value from one list is not in the other list. Python has something like that builtin; `in' >>> L = [1,2,3] >>> 1 in L True >>> 4 in L False >>> So you simply have to call `in' for the elements of list1 with list2 and negate the result. >>> listOne = [ 'a','b','c'] >>> listTwo = ['a','c'] >>> filter(lambda el: not el in listTwo, listOne) ['b'] >>> If you wanted the intersection just don't negate the result. If you have longer lists it might be better to use the new set module (it works with dictionaries) otherwise the code might be to slow. Karl -- Please do *not* send copies of replies to me. I read the list ------------------------------ Message: 6 Date: Wed, 4 Feb 2004 12:13:10 -0800 (PST) From: Daniel Ehrenberg <littledanehren@yahoo.com> Subject: Re: [Tutor] globbing and sorting and dating, oh my! To: pytutor <tutor@python.org> Message-ID: <20040204201310.30288.qmail@web41812.mail.yahoo.com> Content-Type: text/plain; charset=us-ascii Kirk Bailey wrote: > Ok, I want to write a WHAT'S NEW function for > wikinehesa the > wikiwikiweb system I wrote in python. This is > something to sort > through available pages, organize/sort according to > date, chop off > that portion of the list which is older than FOO > days old, and concert > the date to something mere normals will comprehend, > then print each > item as a line in a web page- as a link of course. > NATURALLY I grok > the html part. converting data data to calendar is a > little odd to me, > and I am considering several ways to organize the > data- and as arrays > are not inherent to python, I am going to use > several parallel lists > instead. I throw open the front door to discussion, > suggestions, ON > TOPIC BAUDY HUMOR, and anything else that fits in > through the door. > > If the dates are a list, and I sort the list, the > corresponding list > of filenames no longer corresponds. THIS is an issue > which looms large > in my army surplus used brain. > -- > > > end > > > think http://www.tinylist.org/ - $FREE$ > software for liberty > +-------+ http://www.pinellasintergroupsociety.org/ > - In Her Service > | BOX | http://www.listville.net/ - $FREE$ list > hosting services > +-------+ http://www.howlermonkey.net/ - $FREE$ > email service > kniht http://www.sacredelectron.org/ - My > personal SCREED pit > (C)2004 Kirk D Bailey, all rights > reserved- but ask! Try zipping the lists together and then sorting it. Be sure that the one you want to sort by is first. Daniel Ehrenberg __________________________________ Do you Yahoo!? Yahoo! SiteBuilder - Free web site building tool. Try it! http://webhosting.yahoo.com/ps/sb/ ------------------------------ Message: 7 Date: Wed, 4 Feb 2004 21:37:12 +0100 From: Anna Ravenscroft <anna@aleax.it> Subject: Re: [Tutor] globbing and sorting and dating, oh my! To: Kirk Bailey <idiot1@netzero.net>, tutor@python.org Message-ID: <200402042137.12960.anna@aleax.it> Content-Type: text/plain; charset="iso-8859-1" On Wednesday 04 February 2004 06:55 pm, Kirk Bailey wrote: > If the dates are a list, and I sort the list, the corresponding list > of filenames no longer corresponds. THIS is an issue which looms large > in my army surplus used brain. I'd consider using a dict. Python dicts are fast, easy to use, and highly useful. mydict = {key1:value1, key2:value2} You can use dates as the keys (and any lists or strings or combination thereof as the values), pull a list of the keys using d.keys(), sort them, remove any that are old, then use the remaining list to pull the corresponding values into a new dict or list for display. Or, use a list comprehension directly on the dict to get a list of new items (since you don't really *have* to sort them by date, do you?). It'll give you a new list of tuples, which you can pass to a new dict if you want to: newstuph = dict( [(date, mydict[date]) for date in mydict if date > olddate] ) Hope this helps. Anna -- There is a type 3 error in which your mind goes totally blank whenever you try to remember which is which of type 1 and type 2. -Richard Dawkins -- There is a type 3 error in which your mind goes totally blank whenever you try to remember which is which of type 1 and type 2. -Richard Dawkins ------------------------------ Message: 8 Date: Wed, 4 Feb 2004 21:39:32 +0100 From: Anna Ravenscroft <anna@aleax.it> Subject: Re: [Tutor] comparing lists of strings with each other To: tutor@python.org Message-ID: <200402042139.32255.anna@aleax.it> Content-Type: text/plain; charset="iso-8859-1" On Wednesday 04 February 2004 04:47 pm, jan willem maaskant wrote: > i have two lists filled with strings and i want to filter the strings from > one list out of the other. You'd be better off with a list comprehension. threelist = [i for i in onelist if i not in twolist] But, if you really must use filter for some reason....: > for example: > > listOne = [ 'a','b','c'] > listTwo = ['a','c'] > > i want to remove the strings in listOne which are equal to the strings in > listTwo. > So the list i want to have must look like this. > > listThree = ['b'] > > i tried it with the following code: > >>> def removeStrings(list): > > for key in listTwo: > if key != list: > return list > > >>> listThree = filter(removeStrings, listOne) First, you really really don't want to use "list" as an argument or variable name. list is one of the built-in types in Python, and you *REALLY* don't want to use it as a variable name. > however this results in > > >>> listThree > > ['a', 'b', 'c'] > > > so this is wrong, but what i really don't understand, is why the opposite > seems to work quite fine > if I put this code in Okay, in order to see what's happening, I added some print statements to the function. then ran the whole thing again. alist = ['d', 'b', 'c'] blist = ['d', 'f', 'b'] def remstring(item): print 'filter passes item', item for key in blist: print "key is ", key if key != item: print "key != item. returning", item return item clist = filter(remstring, alist) print clist >>> filter passes item d key is d key is f key != item. returning d filter passes item b key is d key != item. returning b filter passes item c key is d key != item. returning c ['d', 'b', 'c'] >>> Does this help you see what's happening? HTH, Anna -- There is a type 3 error in which your mind goes totally blank whenever you try to remember which is which of type 1 and type 2. -Richard Dawkins ------------------------------ Message: 9 Date: Wed, 04 Feb 2004 16:35:34 -0500 From: Michel B?langer <michel.belanger@seidel.ca> Subject: [Tutor] Executable file version in windows To: tutor@python.org Message-ID: <402165A6.90301@seidel.ca> Content-Type: text/plain; charset=us-ascii; format=flowed Hi, How can I query a file executable (exe, dll, com)for its version including the revision, i.e. exemple: >>>queryVersion("someprog.exe") 5.1.2 Michel Belanger ------------------------------ Message: 10 Date: Thu, 5 Feb 2004 00:34:12 +1100 From: Kim Branson <kim.branson@csiro.au> Subject: [Tutor] reg exps To: tutor@python.org Message-ID: <D15BFACA-5716-11D8-A603-000A9579AE94@csiro.au> Content-Type: text/plain; charset=US-ASCII; format=flowed Hi all, i'm trying to get my head around regexps in python. i've now found the difference between the .match and the .search methods. (i'm used to perl :) i have a program which will spit out data like so: % ~/Desktop/Dock4_osx/bin/scorer 1rx3.pdb dock_nrg.mol2 PK= 6.08 Qual= 2.12 PMF= -159.15 PMF_rb= -144.15 SMoG= -161.27 SMoG_H= -7.68 ChemScore= -23.86 Clash= 0.85 Int= 2.58 DockNRG= -24.51 AutoDock= -20.14 so i'm working on a script which has a function (below) that checks for this data (the program called can spit out other data when inputs are bad) then grabs the matches. so now i'm making dictionaries for each field, using the line number as a key. my pattern match does not return the first match in the list in position 0. i.e [' ', ' 6.08', ' 2.12', '-159.15', '-144.15', '-161.27', '-7.68', '-23.86', ' 0.85', ' 2.58', '-24.51', '-20.14', '\n'] so i'm grabbing the data from position 1 in the list etc, and working from there. Why is this, is this a default behaviour? note the values in the output can be negative or really large, as in PK= -6.08 etc, or Qual= 12.12 so i use (.*) to grab the region. Oh one more thing, if you declare a global, can i simply add dictionary content, or should one declare and then initialise? def score_orientations(): counter = 1 global score_dict global qual_dict global pmf_dict global pmf_rb_dict global smog_dict global smog_h_dict global chemscore_dict global clash_dict global int_dict global docknrg_dict global autodock_dict score_dict = {} qual_dict = {} pmf_dict = {} pmf_rb_dict = {} smog_dict = {} smog_h_dict = {} chemscore_dict = {} clash_dict = {} int_dict = {} docknrg_dict = {} autodock_dict = {} score_lines = re.compile('PK= (.*) Qual= (.*) PMF= (.*) PMF_rb= (.*) SMoG= (.*) SMoG_H= (.*) ChemScore= (.*) Clash= (.*) Int= (.*) DockNRG= (.*) AutoDock= (.*)') results = os.popen2('/Users/kbranson/Desktop/Dock4_osx/bin/scorer %s dock_nrg.mol2' % receptor_pdb) results_data = results[1].readlines() for line in results_data: if (score_lines.search(line)): line = re.split(score_lines, line) score_dict[counter] = line[1] qual_dict[counter] = line[2] pmf_dict[counter] = line[3] pmf_rb_dict[counter] = line[4] smog_dict[counter] = line[5] smog_h_dict[counter] = line[6] chemscore_dict[counter] = line[7] clash_dict[counter] = line[8] int_dict[counter] = line[9] docknrg_dict[counter] = line[10] autdock_dict[counter] = line[11] counter = counter + 1 print score_dict score_orientations() ------------------------------ _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor End of Tutor Digest, Vol 7, Issue 10 ************************************ From dyoo at hkn.eecs.berkeley.edu Wed Feb 4 18:08:35 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Feb 4 18:08:44 2004 Subject: [Tutor] Executable file version in windows In-Reply-To: <402165A6.90301@seidel.ca> Message-ID: <Pine.LNX.4.44.0402041458170.17223-100000@hkn.eecs.berkeley.edu> On Wed, 4 Feb 2004, [ISO-8859-1] Michel B=E9langer wrote: > How can I query a file executable (exe, dll, com)for its version > including the revision, i.e. > > exemple: > >>>queryVersion("someprog.exe") > 5.1.2 Hi Michel, Hmmm... This is a very specific question to the Win32 platform; you might have better luck asking on the Python-Win32 list for this one. From=20some initial Googling, it appears that you may need to get access to the VERSION.DLL Windows library: http://support.microsoft.com/default.aspx?scid=3Dkb;EN-US;139491 We can get access to such DLLs through the Dynwin package: http://www.nightmare.com/~rushing/dynwin/ Unfortunately, that's as far as I can go; I don't run Windows. *grin* Talk to the Win32 folks at: http://mail.python.org/mailman/listinfo/python-win32 The folks there should be better able to help you get this working. Good luck to you! From alan.gauld at blueyonder.co.uk Wed Feb 4 19:23:34 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Feb 4 19:24:29 2004 Subject: [Tutor] Maths (slightly OT) References: <598B5E93DCDC614C9C1FE22406A0F5BE36CD@pacer-server.pacer.local> Message-ID: <005501c3eb7e$4af25cf0$6401a8c0@xp> > My Son has challenged me to name a few careers that would > use Maths exponents and all the calculations in them as a > way of getting out of learning them. Anything vaguely scientific. Including architects, electrical engineering, building trades, draughtsmen, chemists, meteorologists etc Also anything vaguely numeric like: statistician, accountant, businessman, stocks trader. Almost any kind of graphics type thing including animators, graphics artists etc. Navigators either on boats or planes. In fact its kind of hard for me to think of a reasonably well paid career out side of entertainment (including sports in that) that doesn't involve exponentiation somewhere. Its so fundamental to everything in our world and iniverse that you can't hope to understand any physical, chemical or natural phenomenon without it! You might as well as what careers use the ability to read... > Hoping to hear from all the career people that can use > Mathematical Calculations on a regular basis. Depends on what you mean by use them. I use my understanding of exponentiation every day, but I actually do exponential "sums" maybe 6 or 7 times a year... But every time I discuss the "law of diminishing returns", or radiation half life, or electronic timing circuits (important in my job!) I am relying on an understanding of exponentiation. In fact every time I adjust the volume onmy TV or HiFi I am using that same understanding, and when I hit the gas pedal in my car... Every time I listen to a CD or talk on my cell phone, I'm using exponentiation... its everywhere. Alan G. From michel.belanger at seidel.ca Wed Feb 4 20:05:32 2004 From: michel.belanger at seidel.ca (=?ISO-8859-1?Q?Michel_B=E9langer?=) Date: Wed Feb 4 20:05:45 2004 Subject: [Tutor] file transfered through ftplib not the right size Message-ID: <402196DC.7000106@seidel.ca> Hi all, I open an ftp channel with my web site from the following commands: ftp = ftplib.FTP("Host.com") ftp.login("User","Password") then the transfer call for a download is as follow: getbinary(ftp, row[0], row[0]) but the file received is not the right size (larger), i.e. 5150 kb received vs 5136 kb Any idea why? def getbinary(ftp, filename, outfile=None): # fetch a binary file if outfile is None: outfile = sys.stdout f = open(outfile, "w") ftp.retrbinary("RETR " + filename, f.write) f.flush() f.close() Many thanks Michel Belanger From sigurd at 12move.de Wed Feb 4 20:22:30 2004 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Wed Feb 4 20:26:25 2004 Subject: [Tutor] reg exps In-Reply-To: <D15BFACA-5716-11D8-A603-000A9579AE94@csiro.au> (Kim Branson's message of "Thu, 5 Feb 2004 00:34:12 +1100") References: <D15BFACA-5716-11D8-A603-000A9579AE94@csiro.au> Message-ID: <m34qu6ct0d.fsf@hamster.pflaesterer.de> On 4 Feb 2004, Kim Branson <- kim.branson@csiro.au wrote: > i have a program which will spit out data like so: > % ~/Desktop/Dock4_osx/bin/scorer 1rx3.pdb dock_nrg.mol2 > PK= 6.08 Qual= 2.12 PMF= -159.15 PMF_rb= -144.15 SMoG= -161.27 > SMoG_H= -7.68 ChemScore= -23.86 Clash= 0.85 Int= 2.58 DockNRG= > -24.51 AutoDock= -20.14 > so i'm working on a script which has a function (below) that checks > for this data (the program called can spit out other data when inputs > are bad) then grabs the matches. so now i'm making dictionaries for > each field, using the line number as a key. my pattern match does not > return the first match in the list in position 0. > i.e > [' ', ' 6.08', ' 2.12', '-159.15', '-144.15', '-161.27', '-7.68', > '-23.86', ' 0.85', ' 2.58', '-24.51', '-20.14', '\n'] > so i'm grabbing the data from position 1 in the list etc, and working > from there. Why is this, is this a default behaviour? That's the default behaviour if you split the way you do it. > note the values in the output can be negative or really large, as in > PK= -6.08 etc, or Qual= 12.12 so i use (.*) to grab the region. Why not `.+' so not to match an empty string? > Oh one more thing, if you declare a global, can i simply add > dictionary content, or should one declare and then initialise? The latter; but do you really want such a lot of globals? That's ugly IMO. Here a class with the dictionaries as attributes seems to me to be the right thing. Furthermore you can use in Python named groups for your regexps; that's sometimes very convenient (and you needn't split here). [Code] What do you think about: ******************************************************************** class ScoreOrient (object): score_lines = re.compile('''PK= (?P<score>.*) Qual= (?P<qual>.*) PMF= (?P<pmf>.*)\ PMF_rb= (?P<pmf_rb>.*) SMoG= (?P<smog>.*) SMoG_H= (?P<smog_h>.*) \ ChemScore= (?P<chemscore>.*) Clash= (?P<clash>.*) Int= (?P<int>.*) \ DockNRG= (?P<docknrg>.*) AutoDock= (?P<autodock>.*)''') def __init__(self): self.counter = 1 self.tables = dict(\ [(name , {}) for name in ["score", "qual", "pmf", "pmf_rb", "smog", "smog_h", "chemscore", "clash", "int", "docknrg", "autodock"]]) results = False def __str__(self): s = [] for key in self.tables: s.append(key + '\n') s.append("-" * len(key) + '\n') items = self.tables[key].items() items.sort() for key, val in items: s.append(str(key) + ' -> ' + val + '\n') return ''.join(s) def _pull (self, prog = '/Users/kbranson/Desktop/Dock4_osx/bin/scorer'): self.results = os.popen2("%s %s dock_nrg" % (prog, receptor_pdb)) return self.results[1].readlines() def update (self): for line in self._pull(): m = self.score_lines.search(line) if m: for grp, val in m.groupdict().items(): table = self.tables[grp] table[counter] = val self.counter += 1 ******************************************************************** What is convenient here is the usage of the tables as entries in an dictionary; the names are the same names as the names of the named groups. This makes it extremly easy to access the right table for the right value. You just create an instanze of the class and call its update method to fill the tables. If you use named groups within a regexp a match object has an attribute: its groupdict. The key is the name you gave the group, the value is the matched string. That is here convenient since we can use the name of the group to find the right table in the dictionary with the tables since that name gets used as key. The __str__ method is more a bit fun. You can now just print the instance and the values in the tables are printed in a more or less nice fashion. I couldn't really test the code since I don't have yourt programm here so there may be little bugs in the code (but I hope not). Karl -- Please do *not* send copies of replies to me. I read the list From sigurd at 12move.de Wed Feb 4 20:48:29 2004 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Wed Feb 4 20:50:32 2004 Subject: [Tutor] reg exps In-Reply-To: <m34qu6ct0d.fsf@hamster.pflaesterer.de> (Karl =?iso-8859-1?q?Pfl=E4sterer's?= message of "Thu, 05 Feb 2004 02:22:30 +0100") References: <D15BFACA-5716-11D8-A603-000A9579AE94@csiro.au> <m34qu6ct0d.fsf@hamster.pflaesterer.de> Message-ID: <m3znbyb8ni.fsf@hamster.pflaesterer.de> On 5 Feb 2004, Karl Pfl?sterer <- sigurd@12move.de wrote: The first error :-( > for grp, val in m.groupdict().items(): > table = self.tables[grp] > table[counter] = val That^^^^^^^ must be self.counter > self.counter += 1 Karl -- Please do *not* send copies of replies to me. I read the list From sigurd at 12move.de Wed Feb 4 20:53:58 2004 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Wed Feb 4 20:55:49 2004 Subject: [Tutor] file transfered through ftplib not the right size In-Reply-To: <402196DC.7000106@seidel.ca> (Michel =?iso-8859-1?q?B=E9langer's?= message of "Wed, 04 Feb 2004 20:05:32 -0500") References: <402196DC.7000106@seidel.ca> Message-ID: <m3vfmmb8gj.fsf@hamster.pflaesterer.de> On 5 Feb 2004, Michel B?langer <- michel.belanger@seidel.ca wrote: > but the file received is not the right size (larger), i.e. 5150 kb > received vs 5136 kb > Any idea why? I'm not sure but you open the file for writing in text mode. Try it with binary mode. Karl -- Please do *not* send copies of replies to me. I read the list From hans at zephyrfalcon.org Wed Feb 4 21:05:23 2004 From: hans at zephyrfalcon.org (Hans Nowak) Date: Wed Feb 4 21:00:54 2004 Subject: [Tutor] Re: file transfered through ftplib not the right size In-Reply-To: <402196DC.7000106@seidel.ca> References: <402196DC.7000106@seidel.ca> Message-ID: <4021A4E3.1060009@zephyrfalcon.org> Michel B?langer wrote: > then the transfer call for a download is as follow: > > getbinary(ftp, row[0], row[0]) > > but the file received is not the right size (larger), i.e. 5150 kb > received vs 5136 kb > Any idea why? > > > def getbinary(ftp, filename, outfile=None): > # fetch a binary file > if outfile is None: > outfile = sys.stdout > f = open(outfile, "w") Try: f = open(outfile, "wb") This opens the output file in binary mode rather than text mode. HTH, -- Hans (hans@zephyrfalcon.org) http://zephyrfalcon.org/ From michel.belanger at seidel.ca Wed Feb 4 21:10:13 2004 From: michel.belanger at seidel.ca (=?ISO-8859-1?Q?Michel_B=E9langer?=) Date: Wed Feb 4 21:10:21 2004 Subject: [Tutor] file transfered through ftplib not the right size In-Reply-To: <m3vfmmb8gj.fsf@hamster.pflaesterer.de> References: <402196DC.7000106@seidel.ca> <m3vfmmb8gj.fsf@hamster.pflaesterer.de> Message-ID: <4021A605.1040101@seidel.ca> As you suggested, I open the file in binary and it did it i.e. before: f = open(outfile, "w") after: f = open(outfile, "wb") Thank you very much. I am new in Python and find this usergroup very efficient. I posted several requests this past week, and always received very useful information. michel belanger Karl Pfl?sterer wrote: >On 5 Feb 2004, Michel B?langer <- michel.belanger@seidel.ca wrote: > > > >>but the file received is not the right size (larger), i.e. 5150 kb >>received vs 5136 kb >>Any idea why? >> >> > >I'm not sure but you open the file for writing in text mode. Try it >with binary > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040204/d3d15106/attachment.html From isrgish at fusemail.com Thu Feb 5 00:15:40 2004 From: isrgish at fusemail.com (Isr Gish) Date: Thu Feb 5 00:16:20 2004 Subject: [Tutor] glob module Message-ID: <E1Aobrs-00031B-4I@fuse1.fusemail.net> -----Original Message----- >From: "Gerrit"<gerrit@nl.linux.org> >Sent: 2/4/04 11:30:08 AM >To: "Isr Gish"<isrgish@fusemail.com> >Cc: "tutor@python.org"<tutor@python.org> >Subject: Re: [Tutor] glob module >Isr Gish wrote: >> Docs >> recipes >> new >> old >> help >> all >> ... >> I want to find all files with "a*.txt" from whole tree of Docs how would I do that. I understand that I could iterate the whole tree. But what I would like to know, if it can be done, with the glob module. > >If it's always 3 levels deep, you can use '*/*/a*.txt'. >That makes using os.walk unnecesary. Thanks Gerrit, This was only an example in realty I want to get files from all levels. I guess I'll have to do a walk. Isr From gerrit at nl.linux.org Thu Feb 5 08:31:21 2004 From: gerrit at nl.linux.org (Gerrit) Date: Thu Feb 5 08:31:39 2004 Subject: [Tutor] Maths (slightly OT) In-Reply-To: <Pine.LNX.4.44.0402031404130.19100-100000@hkn.eecs.berkeley.edu> References: <2ksv1090cbgemb7m8grftehtbu5c8tvcfh@4ax.com> <Pine.LNX.4.44.0402031404130.19100-100000@hkn.eecs.berkeley.edu> Message-ID: <20040205133121.GA3822@nl.linux.org> Danny Yoo wrote: > Math is not an artificial construct, but a very human endeavor: Aren't artificial contructs especially human? ;-) Gerrit. -- PrePEP: Builtin path type http://people.nl.linux.org/~gerrit/creaties/path/pep-xxxx.html Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From Janssen at rz.uni-frankfurt.de Thu Feb 5 09:51:08 2004 From: Janssen at rz.uni-frankfurt.de (Michael Janssen) Date: Thu Feb 5 09:51:23 2004 Subject: [Tutor] reg exps (fwd) Message-ID: <Pine.A41.4.56.0402051541580.92592@hermes-22.rz.uni-frankfurt.de> On Thu, 5 Feb 2004, Kim Branson wrote: > i have a program which will spit out data like so: > % ~/Desktop/Dock4_osx/bin/scorer 1rx3.pdb dock_nrg.mol2 > PK= 6.08 Qual= 2.12 PMF= -159.15 PMF_rb= -144.15 SMoG= -161.27 > SMoG_H= -7.68 ChemScore= -23.86 Clash= 0.85 Int= 2.58 DockNRG= -24.51 > AutoDock= -20.14 > score_lines = re.compile('PK= (.*) Qual= (.*) PMF= (.*) PMF_rb= > (.*) SMoG= (.*) SMoG_H= (.*) ChemScore= (.*) Clash= (.*) Int= (.*) > DockNRG= (.*) AutoDock= (.*)') The regular expression seems a bit to long for my taste. When you only want to retrieve the numerical values you can much easier do: # untestet reg_values = re.compile('[-0-9.]+') values = re.findall(reg_values, line) for name, val in zip(a_list_of_all_names_in_order, values): print name, val A long regexp is bad, when something in the line changes (you wont' get any output at all then). OTOH Karl's suggestions with named groups has the advantages that you only need to change the regexp, when the output changes. Michael From syn_ack at comcast.net Thu Feb 5 12:53:45 2004 From: syn_ack at comcast.net (Joshua Banks) Date: Thu Feb 5 12:58:12 2004 Subject: [Tutor] Looking for some guidance. Message-ID: <200402050953.48519.syn_ack@comcast.net> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hello, I've embarked upon the Python journey. Running Python 2.3.3 on Gentoo linux. Wahoo... I've been running Linux for almost a yr now and this proves to be a never-ending learning experience. I have absolutely no programming experience at all. Not even shell scripting. Right now I feel it little overwhelmed with all the documentation that I have. I'm sure that I'm not the only one that has felt this way. The frustrating part of my initial step towards learning Python is, almost all of the tutorials that I have seem to wiz through all of the concepts and symantics without reinforcing the newly learned concepts with exercises, exercises, exercises....examples, examples and then the examples explained. I'm finding myself jumping from book to book, tutorial to tutorial feeling like I'll find something eventually that will fit. This is why I'm asking for guidance. At this point I don't know if I'm being to anal retentive thinking that I need to understand every little thing I read, or that maybe there's a tutorial that I'm missing. Is there a proven structured path to Enlightenment?? I guess what I'm asking for is a suggestion of how a non-programmer can best progress from a non-programmer to starting to put these Python concepts to use. Do I just plow through a tutorial and goto the next eventually at some point slowly understanding? Thanks, -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (GNU/Linux) iD8DBQFAIoMqp9X7q/XgeyYRAjmXAJ4mVaJ0aOl39x6fGC3lNGs0jcO6yACgmPB/ 6jyEFRxojGZHOVFjhbl5jPc= =OGlf -----END PGP SIGNATURE----- From Christian.Wyglendowski at greenville.edu Thu Feb 5 13:05:56 2004 From: Christian.Wyglendowski at greenville.edu (Christian Wyglendowski) Date: Thu Feb 5 13:06:04 2004 Subject: [Tutor] RE: [python-win32] Executable file version in windows Message-ID: <CE1475C007B563499EDBF8CDA30AB45B0A38BA@empex.greenville.edu> > -----Original Message----- > How can I query a file executable (exe, dll, com)for its version > including the revision, i.e. > > exemple: > >>>queryVersion("someprog.exe") > 5.1.2 Here is another way: >>> from win32com.client import Dispatch >>> fso = Dispatch('Scripting.FileSystemObject') >>> fso.GetFileVersion(r'c:\windows\system32\cacls.exe') u'5.1.2600.0' >>> fso.GetFileVersion(r'c:\windows\system32\ntdll.dll') u'5.1.2600.1217' > Many thanks You're welcome! Christian http://www.dowski.com From Janssen at rz.uni-frankfurt.de Thu Feb 5 13:59:32 2004 From: Janssen at rz.uni-frankfurt.de (Michael Janssen) Date: Thu Feb 5 13:59:44 2004 Subject: [Tutor] Looking for some guidance. In-Reply-To: <200402050953.48519.syn_ack@comcast.net> References: <200402050953.48519.syn_ack@comcast.net> Message-ID: <Pine.A41.4.56.0402051931380.141742@hermes-22.rz.uni-frankfurt.de> On Thu, 5 Feb 2004, Joshua Banks wrote: > Right now I feel it little overwhelmed with all the documentation that I > have. I'm sure that I'm not the only one that has felt this way. After reading the "official tutorial" I felt more like "such few concepts can't be programming already, can them?". Indeed it took me some time to accept, that doing a little for-loop, some if-thingies and firing up string and list methods is already the half way to write a script that actually do something what one might expect a script to do. Learnig how to do functions a week after has greatly improven my style ;-) > The > frustrating part of my initial step towards learning Python is, almost > all of the tutorials that I have seem to wiz through all of the > concepts and symantics without reinforcing the newly learned concepts > with exercises, exercises, exercises....examples, examples and then the > examples explained. So you probably can make up the examples for yourself. Just fire up interpreter and do something. In my first month I spent a lot of time with the interpreter cutting&pasting code between it and editor and testing every step I take. Perhaps not the most efficient way to code, but my script I wrote in my second week still do some valueable stuff (and would cost me some hours to write nowadays...) > I'm finding myself jumping from book to book, tutorial to tutorial > feeling like I'll find something eventually that will fit. This is why > I'm asking for guidance. At this point I don't know if I'm being to > anal retentive thinking that I need to understand every little thing I > read, or that maybe there's a tutorial that I'm missing. Is there a > proven structured path to Enlightenment?? > > I guess what I'm asking for is a suggestion of how a non-programmer can > best progress from a non-programmer to starting to put these Python > concepts to use. Do I just plow through a tutorial and goto the next > eventually at some point slowly understanding? I would suggest after reading two or three tutorials look out for a small task and try to code it down. The good thing is that python isn't that hard. Another good thing is that the python community is known as newbie friendly :-) So, whenever you're stuck ask for help. Such a "small task" is an important step on the path to programming, because you won't learn it well without actually trying. One tricky thing is to determine, which task is small but the rest is done with functions, for- and while-loops, if-clauses, string-, lists- and dicts-methods and some helpful functions from os, time, re and sys modul. Michael From marilyn at deliberate.com Thu Feb 5 14:19:46 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Thu Feb 5 14:20:25 2004 Subject: [Tutor] Looking for some guidance. In-Reply-To: <200402050953.48519.syn_ack@comcast.net> Message-ID: <Pine.LNX.4.44.0402051110510.11161-100000@Kuna> On Thu, 5 Feb 2004, Joshua Banks wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Hello, > > I've embarked upon the Python journey. Running Python 2.3.3 on Gentoo > linux. Wahoo... Indeed! Congratulations. Do you have idle running too? > > I've been running Linux for almost a yr now and this proves to be a > never-ending learning experience. I have absolutely no programming > experience at all. Not even shell scripting. > > Right now I feel it little overwhelmed with all the documentation that I > have. I'm sure that I'm not the only one that has felt this way. The > frustrating part of my initial step towards learning Python is, almost > all of the tutorials that I have seem to wiz through all of the > concepts and symantics without reinforcing the newly learned concepts > with exercises, exercises, exercises....examples, examples and then the > examples explained. > > I'm finding myself jumping from book to book, tutorial to tutorial > feeling like I'll find something eventually that will fit. This is why > I'm asking for guidance. At this point I don't know if I'm being to I'm aware of 2 books that are aimed at people with no previous programming experience. Neither covers everything. The tutorial covers everything, I think. "Python How to Program" by Deitel, et. al. "Python Programming An Introduction to Computer Science" by Zelle. Although they don't provide solutions to the exercises, I'll bet, if you posted your trial solutions, you'd get lots of help here. > anal retentive thinking that I need to understand every little thing I > read, or that maybe there's a tutorial that I'm missing. Is there a > proven structured path to Enlightenment?? Ha ha. Follow your nose? :^) > > I guess what I'm asking for is a suggestion of how a non-programmer can > best progress from a non-programmer to starting to put these Python > concepts to use. Do I just plow through a tutorial and goto the next > eventually at some point slowly understanding? No. Like you say, a beginner needs practice at every step of the way. Good luck. And prepare to be blown away with your new powers. Marilyn Davis > > Thanks, > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.2.3 (GNU/Linux) > > iD8DBQFAIoMqp9X7q/XgeyYRAjmXAJ4mVaJ0aOl39x6fGC3lNGs0jcO6yACgmPB/ > 6jyEFRxojGZHOVFjhbl5jPc= > =OGlf > -----END PGP SIGNATURE----- > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- From syn_ack at comcast.net Thu Feb 5 14:20:58 2004 From: syn_ack at comcast.net (Joshua Banks) Date: Thu Feb 5 14:25:25 2004 Subject: [Tutor] Looking for some guidance. In-Reply-To: <Pine.A41.4.56.0402051931380.141742@hermes-22.rz.uni-frankfurt.de> References: <200402050953.48519.syn_ack@comcast.net> <Pine.A41.4.56.0402051931380.141742@hermes-22.rz.uni-frankfurt.de> Message-ID: <200402051121.00634.syn_ack@comcast.net> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Thursday 05 February 2004 10:59 am, Michael Janssen wrote: > I would suggest after reading two or three tutorials look out for a > small task and try to code it down. The good thing is that python > isn't that hard. Another good thing is that the python community is > known as newbie friendly :-) So, whenever you're stuck ask for help. > > Such a "small task" is an important step on the path to programming, > because you won't learn it well without actually trying. One tricky > thing is to determine, which task is small but the rest is done with > functions, for- and while-loops, if-clauses, string-, lists- and > dicts-methods and some helpful functions from os, time, re and sys > modul. > > Michael Great. Thanks Michael. I'll keep pounding away then. I've looked at the FAQ's and unless I've overlooked something, is there a preferred directory that I can store my Python scripts. I would like to have the ability to place the scripts somewhere where I have the ability to execute them from any directory that I happen to be in. E.G. If I make my *.py scripts executable and place them in /usr/local/bin I can execute them from any directory as a normal user just by name, from eterm or a console shell, instead of having to put in the full path to the file/script. >>> import sys >>> sys.path ['', '/usr/lib/python23.zip', '/usr/lib/python2.3', '/usr/lib/python2.3/plat-linux2', '/usr/lib/python2.3/lib-tk', '/usr/lib/python2.3/lib-dynload', '/usr/lib/python2.3/site-packages', '/usr/lib/portage/pym'] Thanks, Joshua Banks -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (GNU/Linux) iD8DBQFAIpeap9X7q/XgeyYRAsb+AJ9EPQwLteyKB+uv21AcBn/GHt7zlACgjQU2 a7thI103j8Ou9Y0YahqGaUc= =EliO -----END PGP SIGNATURE----- From renderpipe at speedpost.net Thu Feb 5 14:31:24 2004 From: renderpipe at speedpost.net (RenderPipe) Date: Thu Feb 5 14:31:30 2004 Subject: [Tutor] Newbie trying to understand modules and code reuse Message-ID: <20040205193124.8A286154DF0@mail.messagingengine.com> Hello, I'm having a difficult time trying to understand modules with python. I used to write php applications and am used to including files in the header of the document(include "file.php"). This also makes code reuse easier. I'm under the impression modules in python work this way. My problem is, I don't know how to write a module. I have read the manuals and it just doesn't make sense yet. Ultimately I'd like to create 2 "include files". 1 will be a class file that I plan to reuse throughout my application and 1 file will be a list of variables. I tried create a file and putting it in my /python/lib directory and importing it. Surprisingly I was able to import it but I was unable to access the variables or methods in the file. Am I seeking modules incorrectly? Perhaps I should use something else for code reuse? I'm using WindowsXP with ActivePython tia Bobby -- http://www.fastmail.fm - Same, same, but different From zmerch at 30below.com Thu Feb 5 15:17:59 2004 From: zmerch at 30below.com (Roger Merchberger) Date: Thu Feb 5 15:17:45 2004 Subject: [Tutor] Looking for some guidance. In-Reply-To: <200402051121.00634.syn_ack@comcast.net> References: <Pine.A41.4.56.0402051931380.141742@hermes-22.rz.uni-frankfurt.de> <200402050953.48519.syn_ack@comcast.net> <Pine.A41.4.56.0402051931380.141742@hermes-22.rz.uni-frankfurt.de> Message-ID: <5.1.0.14.2.20040205150702.04cbe728@mail.30below.com> Rumor has it that Joshua Banks may have mentioned these words: >I've looked at the FAQ's and unless I've overlooked something, is there >a preferred directory that I can store my Python scripts. Nope. Stick 'em anywhere you want... ;-) > I would like >to have the ability to place the scripts somewhere where I have the >ability to execute them from any directory that I happen to be in. E.G. >If I make my *.py scripts executable and place them in /usr/local/bin I >can execute them from any directory as a normal user just by name, from >eterm or a console shell, instead of having to put in the full path to >the file/script. /usr/local/bin is good, but it can get cluttered as you start installing more software on the system... If you want a centralized place to put your scripts in your home directory, you can, like this: /home/zmerch/pyscripts and if you cd to /home/zmerch/pyscripts normally to work on the scripts anyway, all you have to type in is: ./samplescript.py and it will execute, if: 1) you remember to put the bangpath line as the first line of the script, like: #!/usr/bin/python -or- #!/bin/env /usr/bin/python (I think, I don't use this method myself) 2) make sure you set the script executible: chmod 755 samplescript.py --if you want *any* userid to run it, or chmod 744 samplescript.py --if you want only your userid to run it. =-=-=-=-=-=-=-=-=-=-= If you wanted to make a directory for your scripts that's world findable, but not /usr/local/bin for clarity, make one up, like: /usr/local/pyscripts and edit your /etc/profile to say something like this: PATH=${PATH}:/usr/local/pyscripts export PATH [[ the previous line is heavily dependant on the flavor of shell you run. If you're running bash, this *should* work, but it is untested, so YMMV. ;-) ]] 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!" From project5 at redrival.net Thu Feb 5 15:16:47 2004 From: project5 at redrival.net (Andrei) Date: Thu Feb 5 15:20:15 2004 Subject: [Tutor] Re: Newbie trying to understand modules and code reuse References: <20040205193124.8A286154DF0@mail.messagingengine.com> Message-ID: <cnnpa2ez1t6j$.kguiq7qb5mjv$.dlg@40tude.net> RenderPipe wrote on Thu, 05 Feb 2004 14:31:24 -0500: > I'm having a difficult time trying to understand modules with python. I > used to write php applications and am used to including files in the > header of the document(include "file.php"). This also makes code reuse > easier. I'm under the impression modules in python work this way. I don't know about PHP, but modules in Python are not quite the same as copy-pasting the code in that module into your main app. > My problem is, I don't know how to write a module. I have read the > manuals and it just doesn't make sense yet. Ultimately I'd like to create > 2 "include files". Make a file <something.py> and write some Python in it. It's a module! Write in your <main.py> "import something" (with <something.py> being in some path where Python can find it, e.g. in the same folder as <main.py> or in Python's lib) and that's it. > 1 will be a class file that I plan to reuse throughout my application and > 1 file will be a list of variables. I wouldn't put variables in a seaparate file unless it really makes sense for them to be separated from the main code. Not quite likely I think. > I tried create a file and putting it in my /python/lib directory and > importing it. Surprisingly I was able to import it but I was unable to > access the variables or methods in the file. It depends on how you import. (1) If you do "from somemodule import *" you get its entire contents in your current name. This is a lot like a verbatim copy-pasting of the module contens in your application. You should NOT use this method because it can cause you a lot of problems (e.g. if two modules contain variables or whatever with identical names). (2) If you do "import somemodule", you'll have to access that module's contents by using the dot-notation, e.g. "somemodule.myclass". This is the preferred method of importing modules. (3) Now if your module has some really long name, you can do "import somemodule as m". Then you can access its contents using e.g. "m.myclass". > Am I seeking modules incorrectly? Perhaps I should use something else for > code reuse? No, modules are fine, but they're not as special as you think. ANY Python file is a module and any module is a script (it might just not do anything particularly interesting on its own). Many modules in fact even come with some test code which is only executed if the module is started on its own (not imported). That code is then used by the author of the script/module to demonstrate its uses. -- Yours, Andrei ===== Mail address in header catches spam. 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 karl.fast at pobox.com Thu Feb 5 15:25:17 2004 From: karl.fast at pobox.com (Karl Fast) Date: Thu Feb 5 15:27:04 2004 Subject: [Tutor] Newbie trying to understand modules and code reuse In-Reply-To: <20040205193124.8A286154DF0@mail.messagingengine.com>; from renderpipe@speedpost.net on Thu, Feb 05, 2004 at 02:31:24PM -0500 References: <20040205193124.8A286154DF0@mail.messagingengine.com> Message-ID: <20040205142517.D11400@signal.lights.com> > I tried create a file and putting it in my /python/lib directory and > importing it. Surprisingly I was able to import it but I was unable > to access the variables or methods in the file. Namespaces are an important concept in Python and I suspect that is what's tripping you up. If it gets imported then you should be fine. When you import something all of the variables and functions (or classes) are available in that namespace. Suppose you've for a module called "mymodule.py" and it looks kinda like this: myvar = "something" def myfunction(): print "something else" Now suppose you've got that module somewhere in your python library path (that is, when you importy mymodule, python can find it). So now you write a script called "myscript.py" and you import that module. It looks like this: import mymodule print mymodule.myvar mymodolue.myfunction() When you run this the output should be: something something else The trick is that python imports everything into the mymodule namespace and that's how you access it. You can import them directly into the main namespace by doing something like this: from mymodule import * print myvar myfunction() Note the difference. Now the variable and the function are not qualified as being part of the mymodule namespace. Namespaces are really important in python. They are in most programming languages actually. The syntax is different and some behaviours are slightly different, but the basic concept is pretty universally consistent. --karl From cspears2002 at yahoo.com Thu Feb 5 16:18:07 2004 From: cspears2002 at yahoo.com (Christopher Spears) Date: Thu Feb 5 16:18:14 2004 Subject: [Tutor] printing answers Message-ID: <20040205211807.99141.qmail@web12406.mail.yahoo.com> I'm writing a function that takes a list of strings and finds any identical strings. Case should not matter. For example, in ['one','One', 'two', 'three', 'ThrEE'], one and One and three and ThrEE should be recognized as pairs. I wrote the following code: def findMatch(list_of_strings): import re answers = [] for i in range(len(list_of_strings)): pattern = re.compile(list_of_strings[i], re.I) for i in range(len(list_of_strings)): match = re.match(pattern, list_of_strings[i]) if match != None: answers = answers + [list_of_strings[i]] print answers My problem is printing out the correct answers. When I ran a test, I got the following result: >>> findMatch(['one', 'two', 'One']) ['one', 'One', 'two', 'one', 'One'] What am I doing wrong? I think my logic is correct. -Chris From syn_ack at comcast.net Thu Feb 5 15:41:04 2004 From: syn_ack at comcast.net (Joshua Banks) Date: Thu Feb 5 16:34:10 2004 Subject: [Tutor] Looking for some guidance. In-Reply-To: <Pine.LNX.4.44.0402051110510.11161-100000@Kuna> References: <Pine.LNX.4.44.0402051110510.11161-100000@Kuna> Message-ID: <200402051241.06627.syn_ack@comcast.net> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Thursday 05 February 2004 11:19 am, Marilyn Davis wrote: > Indeed! Congratulations. Do you have idle running too? Yes. > I'm aware of 2 books that are aimed at people with no previous > programming experience. Neither covers everything. The tutorial > covers everything, I think. > > "Python How to Program" by Deitel, et. al. > > "Python Programming An Introduction to Computer Science" by Zelle. > > Although they don't provide solutions to the exercises, I'll bet, if > you posted your trial solutions, you'd get lots of help here. Thanks. Thats good to know. Right now I've got 2 books. "Learning Python" by Oreilly. This is a pretty good book. And "Learn to Program Using Python" by Alan Gauld. > Ha ha. > > Follow your nose? :^) It was a shot in the dark. :P > No. Like you say, a beginner needs practice at every step of the > way. > > Good luck. And prepare to be blown away with your new powers. > > Marilyn Davis Thanks. That proved to be good moral boost and then some. Joshua Banks -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (GNU/Linux) iD8DBQFAIqpgp9X7q/XgeyYRAnKvAJ9EsUsv7K5l7+YdKC7299l7GiFgogCgjlPj YecSEXybPCW4EwqDT+s/+5A= =aXen -----END PGP SIGNATURE----- From alan.gauld at blueyonder.co.uk Thu Feb 5 16:43:52 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Feb 5 16:45:30 2004 Subject: [Tutor] printing answers References: <20040205211807.99141.qmail@web12406.mail.yahoo.com> Message-ID: <006201c3ec31$25874300$6401a8c0@xp> > for i in range(len(list_of_strings)): > pattern = re.compile(list_of_strings[i], re.I) > for i in range(len(list_of_strings)): You are using the same name for both counters so you will overwrite the fist loop value with the second each time. Very confusing. But why use indexing, you could just use for aString in list_of_strings: pattern = re.compile(aString,re.I) for item in list_of_strings: .... Its clearer and more efficient. Of course you still need two loop variable names to avoid your overwriting issue. Alan G. From brian at connellyman.com Thu Feb 5 16:46:56 2004 From: brian at connellyman.com (Brian Connelly) Date: Thu Feb 5 16:46:54 2004 Subject: [Tutor] Zope and Python... Message-ID: <!~!AAAAAO+KsFSrp5dMkqFBazggdHSE6CAA@connellyman.com> Hey guys and Gals... Just looking for peoples experience on Zope --- What is the tutor thoughts on it ? Those that use it what are your gripes or praises and if you don't like Zope is there something else you would recommend to give a similar functionality. I am finding it hard to find good "easy" beginner documentation on application building in Zope. I've gone through the Devshed documents and the zope book but I have found many problems in the examples and just the version diffs in Zope. Are there any good resources that anyone would suggest for Learning to develop apps under Zope ? Thanks BCC -------------- next part -------------- A non-text attachment was scrubbed... Name: winmail.dat Type: application/ms-tnef Size: 3502 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20040205/c03bcef0/winmail.bin From rmkrauter at yahoo.com Thu Feb 5 16:49:19 2004 From: rmkrauter at yahoo.com (Rich Krauter) Date: Thu Feb 5 16:49:25 2004 Subject: [Tutor] printing answers Message-ID: <20040205214919.7756.qmail@web40109.mail.yahoo.com> I think you are saying you want to eliminate duplicates, without regard to case. That's what I do below. I think you're making it much harder than it needs to be by using regexes and nested loops. Notice I use answers as a dict, not a list. Dicts are nice when you want to get rid of repeats. def findMatch(list_of_strings): answers = {} for s in list_of_strings: try: answers[s.lower()] += 1 except: answers[s.lower()] = 1 print answers.keys() print answers if __name__ == '__main__': list_of_strings = ['one','One', 'two', 'three','ThrEE'] findMatch(list_of_strings) Rich __________________________________ Do you Yahoo!? Yahoo! Finance: Get your refund fast by filing online. http://taxes.yahoo.com/filing.html From alan.gauld at blueyonder.co.uk Thu Feb 5 17:23:31 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Feb 5 17:25:14 2004 Subject: [Tutor] Newbie trying to understand modules and code reuse References: <20040205193124.8A286154DF0@mail.messagingengine.com> Message-ID: <006b01c3ec36$afe4c360$6401a8c0@xp> > I'm having a difficult time trying to understand modules > with python. I used to write php applications and am used > to including files In Python you don't include files you import names. This is an important distinction. > My problem is, I don't know how to write a module. > I have read the manuals and it just doesn't make sense yet. OK, I dunno which bits you read but a module in Python is just a file full of python code. Lets call it mymodule.py If you do import mymodule you make the name of the module available in your file. At the same time Python will execute the file and thus any function or class definitions will be executed and the functions and classes will be available for use. BUT their names will be inside the mymodule object. To access anything inside the module you need to prepend it with the module object name: mymodule.myfunction() If the file name is long you might like to rename the module by importing it like this: import mymodule as m Now we can access the function like this: m.myfunction() The module object remains the same we have just given it a shorter name. The other way to get at the contents of a module is to do this: from mymodule import myfunction This brings the name myfunction into your file but not the name mymodule nor any of the other names within mymodule. You can also "from mymodule import *" but that's usually a bad idea since it brings all the names from mymodule into your file, potentially overwriting some of them. > Ultimately I'd like to create 2 "include files". Two modules > 1 will be a class file that I plan to reuse throughout my application This is a good idea. > 1 file will be a list of variables. THis is an extremely bad idea. The whole idea of modules controlling names is to avoid global variables spilling over from one module to another. Its much better to keep the variables within the modules where they are needed. You can access them by prefixing with the parent module's name. > I tried create a file and putting it in my /python/lib > directory and importing it. Surprisingly I was able to > import it but I was unable to access the variables or > methods in the file. AS I described above you import the name of the module into your local namespace. You do not import the file itself. Thats why we "import mymodule" and not "mymodule.py" > Perhaps I should use something else for code reuse? You have the right idea but just need to adapt from the C/C++/PHP style of copy n paste include to the more theoretically sound importing of names. You might like to read both the modules and namespaces topics in my tutorial. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From syn_ack at comcast.net Thu Feb 5 15:55:52 2004 From: syn_ack at comcast.net (Joshua Banks) Date: Thu Feb 5 17:27:13 2004 Subject: [Tutor] Looking for some guidance. In-Reply-To: <5.1.0.14.2.20040205150702.04cbe728@mail.30below.com> References: <Pine.A41.4.56.0402051931380.141742@hermes-22.rz.uni-frankfurt.de> <5.1.0.14.2.20040205150702.04cbe728@mail.30below.com> Message-ID: <200402051255.54521.syn_ack@comcast.net> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Thursday 05 February 2004 12:17 pm, Roger Merchberger wrote: > /usr/local/bin is good, but it can get cluttered as you start > installing more software on the system... Ahhhhh.. I was wondering why this directory was bone dry. All exec's are in "/usr/bin" for normal software that gets installed. It's been like this for 6 mnths. I believe this happend because of the way that I intially partioned my drive..... Anyways, thanks though.. One less think I have to curious about know. Heh.. > 1) you remember to put the bangpath line as the first line of the > script, like: > > #!/usr/bin/python -or- > #!/bin/env /usr/bin/python (I think, I don't use this method myself) Yup. I just use #!/usr/bin/python > 2) make sure you set the script executible: > > chmod 755 samplescript.py --if you want *any* userid to run it, or > chmod 744 samplescript.py --if you want only your userid to run it. I've been using "chmod +x file.py" But I understand what your saying here. > If you wanted to make a directory for your scripts that's world > findable, but not /usr/local/bin for clarity, make one up, like: > > /usr/local/pyscripts > > and edit your /etc/profile to say something like this: > > PATH=${PATH}:/usr/local/pyscripts > export PATH > > [[ the previous line is heavily dependant on the flavor of shell you > run. If you're running bash, this *should* work, but it is untested, > so YMMV. ;-) ]] Ahhhhhh Yesssss. YOU ROCK... that's what I was looking for. Cool. ...... Thanks Roger. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (GNU/Linux) iD8DBQFAIq3Yp9X7q/XgeyYRAha+AKCYxWUoyYjhZr9HY1syrE02M5sI9QCghMx7 fMoSBCXIQeZNv2zeUFIFaiE= =vLFP -----END PGP SIGNATURE----- From from_python_tutor at SSokolow.com Thu Feb 5 17:34:57 2004 From: from_python_tutor at SSokolow.com (SSokolow) Date: Thu Feb 5 17:35:06 2004 Subject: [Tutor] Newbie trying to understand modules and code reuse In-Reply-To: <006b01c3ec36$afe4c360$6401a8c0@xp> References: <20040205193124.8A286154DF0@mail.messagingengine.com> <006b01c3ec36$afe4c360$6401a8c0@xp> Message-ID: <4022C511.3040605@SSokolow.com> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040205/32087573/attachment.html From alan.gauld at blueyonder.co.uk Thu Feb 5 16:36:26 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Feb 5 17:39:25 2004 Subject: [Tutor] Looking for some guidance. References: <Pine.LNX.4.44.0402051110510.11161-100000@Kuna> Message-ID: <002e01c3ec30$1c3f1f30$6401a8c0@xp> > I'm aware of 2 books that are aimed at people with no previous > programming experience. Neither covers everything. The tutorial > covers everything, I think. > > "Python How to Program" by Deitel, et. al. > > "Python Programming An Introduction to Computer Science" by Zelle. I'll add Teach Yourself Python in 24 Hours by Ivan van Lanningham and my own effort Learn to Program using Python Ivan's book focusses on teaching Python, mine focusses on teching programming and just happens (although not by accident!) to use Python to demonstate the concepts. None of the 4 will make you an expert although the Dietel book will cover more topics than the others - and costs a lot more... > > read, or that maybe there's a tutorial that I'm missing. Is there a > > proven structured path to Enlightenment?? Yes, its called practice! Seriously the best way to learn to program is to take the examples in the boooks and extend them in diffreent ways. If the example prints the 12 times table, change it to print the 9 times table, then to do it in a different format, then to print the squares from 1 to 12 instead. Just little changes but by making those changes you reinforce the ideas and prove to yourself that you really understand what's happening. Finally don't try to run before you walk. A GUI interface may look nice but trying to add one too soon will simply distract you from the fundamentals. Alan G. From renderpipe at speedpost.net Thu Feb 5 17:39:40 2004 From: renderpipe at speedpost.net (RenderPipe) Date: Thu Feb 5 17:39:52 2004 Subject: [Tutor] Newbie trying to understand modules and code reuse In-Reply-To: <006b01c3ec36$afe4c360$6401a8c0@xp> References: <20040205193124.8A286154DF0@mail.messagingengine.com> <006b01c3ec36$afe4c360$6401a8c0@xp> Message-ID: <20040205223940.34881152F51@mail.messagingengine.com> Cool! Now I understand. I'll read up on that tutorial too. Thanks to everyone for their helpful response. Bobby On Thu, 5 Feb 2004 22:23:31 -0000, "Alan Gauld" <alan.gauld@blueyonder.co.uk> said: > > I'm having a difficult time trying to understand modules > > with python. I used to write php applications and am used > > to including files > > In Python you don't include files you import names. > This is an important distinction. > > > My problem is, I don't know how to write a module. > > I have read the manuals and it just doesn't make sense yet. > > OK, I dunno which bits you read but a module in Python is > just a file full of python code. Lets call it mymodule.py > > If you do > > import mymodule > > you make the name of the module available in your file. > At the same time Python will execute the file and thus > any function or class definitions will be executed and > the functions and classes will be available for use. > BUT their names will be inside the mymodule object. > > To access anything inside the module you need to prepend > it with the module object name: > > mymodule.myfunction() > > If the file name is long you might like to rename the module > by importing it like this: > > import mymodule as m > > Now we can access the function like this: > > m.myfunction() > > The module object remains the same we have just given it a > shorter name. > > The other way to get at the contents of a module is to do this: > > from mymodule import myfunction > > This brings the name myfunction into your file but not the > name mymodule nor any of the other names within mymodule. > You can also "from mymodule import *" but that's usually > a bad idea since it brings all the names from mymodule into > your file, potentially overwriting some of them. > > > Ultimately I'd like to create 2 "include files". > > Two modules > > > 1 will be a class file that I plan to reuse throughout my > application > > This is a good idea. > > > 1 file will be a list of variables. > > THis is an extremely bad idea. The whole idea of modules > controlling names is to avoid global variables spilling > over from one module to another. Its much better to keep > the variables within the modules where they are needed. > You can access them by prefixing with the parent module's > name. > > > I tried create a file and putting it in my /python/lib > > directory and importing it. Surprisingly I was able to > > import it but I was unable to access the variables or > > methods in the file. > > AS I described above you import the name of the module > into your local namespace. You do not import the file itself. > Thats why we "import mymodule" and not "mymodule.py" > > > Perhaps I should use something else for code reuse? > > You have the right idea but just need to adapt from > the C/C++/PHP style of copy n paste include to the more > theoretically sound importing of names. > > You might like to read both the modules and namespaces topics > in my tutorial. > > Alan G > Author of the Learn to Program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld > -- http://www.fastmail.fm - Choose from over 50 domains or use your own From aschmidt at fredericksburg.com Thu Feb 5 17:55:13 2004 From: aschmidt at fredericksburg.com (Allen) Date: Thu Feb 5 17:55:42 2004 Subject: [Tutor] Zope and Python... In-Reply-To: <!~!AAAAAO+KsFSrp5dMkqFBazggdHSE6CAA@connellyman.com> References: <!~!AAAAAO+KsFSrp5dMkqFBazggdHSE6CAA@connellyman.com> Message-ID: <4022C9D1.4070205@fredericksburg.com> Brian Connelly wrote: > Those that use it what are your gripes or praises and if you don't like Zope I hang out here for Python nuggets to help make my work with Zope more meaningful. I love it and we have had fantastic success with it. Zope is going through some great changes and is improving all the time. Sure it's a lot of work to get going and there is a steep learning curve...but the results are well worth the effort. I will toot our horn here.. take a look at www.fredericksburg.com It is all built with Zope and Python and MySQL for some of the data chunks. It is a newspaper website with a ton more. The new ZPT or zope page templates are really slick. ZPT is used for presentation and all the logic is in Python! Works out well. Most of what we have now is the older DTML which is slowing going away. And some of the new products for Zope like Plone and their CMF for content management are amazing. The Zope Corporation lives right down the street from us here in Fredericksburg, Virginia. And for those that don't know, Zope also 'owns' PythonLabs. (not sure if owns is the right word, hence the quotes) Hope that helps. Would love to discuss Zope off this list with anyone, anytime. The Zope mailing list is very active 24 hours a day. But do Google for answers first, as many newbie issues have been beaten to death. But do feel free to ask... good bunch of folks there. Allen From alan.gauld at blueyonder.co.uk Thu Feb 5 18:00:39 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Feb 5 18:02:15 2004 Subject: [Tutor] Looking for some guidance. References: <Pine.A41.4.56.0402051931380.141742@hermes-22.rz.uni-frankfurt.de><5.1.0.14.2.20040205150702.04cbe728@mail.30below.com> <200402051255.54521.syn_ack@comcast.net> Message-ID: <008901c3ec3b$df93b210$6401a8c0@xp> > /usr/local/bin is good, but it can get cluttered as you start > installing more software on the system... Ahhhhh.. I was wondering why this directory was bone dry. All exec's are in "/usr/bin" for normal software that gets installed. usr/bin is usually for system software that users can execute (as opposed to daemons and sys admin type stuff which is uisally in sbin) /usr/local/bin is for stuff you create or install locally. The naming and assumption comes from the days that most computers were running code that was written locally for a specific purpose - ie before shrinkwrap applications were commonplace. Nowadays applications can be found all over the place and it gets confusing :-( > #!/usr/bin/python -or- > #!/bin/env /usr/bin/python (I think, I don't use this method myself) I beliebe that should be /usr/env python which is more portable since it will find python even if its not in the same place as on your machine. > Yup. I just use #!/usr/bin/python But, confession time, so do I formy own programs! :-) Alan G. From alan.gauld at blueyonder.co.uk Thu Feb 5 18:04:51 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Feb 5 18:06:33 2004 Subject: [Tutor] Newbie trying to understand modules and code reuse References: <20040205193124.8A286154DF0@mail.messagingengine.com><006b01c3ec36$afe4c360$6401a8c0@xp> <4022C511.3040605@SSokolow.com> Message-ID: <008d01c3ec3c$75d91620$6401a8c0@xp> > Although the more recent versions of the C++ language > do have a limited implementation of namespaces. Actually its quite a sophisticated namespace mechanism, and in some ways is better than Pythons(IMHO) - you can add names to a namespace retrospectively, modify the scope of namespaces, have multiple namespaces within a file, even within a function etc. But it is entirely separated from the prinitive #include functionality borrowed from C which is what I was referring to. > #include <iostream.h> > cout << "Hello World!\n" > is now deprecated in favor of > #include <iostream> > std::cout << "Hello World!\n" Indeed, although you can work some magic to remove the need for the std:: but it has similar issues to using from module import * in Python. Alan G. From marilyn at deliberate.com Thu Feb 5 18:14:08 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Thu Feb 5 18:14:28 2004 Subject: [Tutor] fancy list things Message-ID: <Pine.LNX.4.44.0402051502260.11161-100000@Kuna> I'm trying to solidify my understanding of list comprehensions and other fancies. Is it true that you can *always* replace map() and filter() with a list comprehension? But you can never replace reduce()? Can anyone give me a reasonable example of lambda? Thank you for any help. Marilyn Davis From syn_ack at comcast.net Thu Feb 5 18:14:12 2004 From: syn_ack at comcast.net (Joshua Banks) Date: Thu Feb 5 18:18:31 2004 Subject: [Tutor] Looking for some guidance. In-Reply-To: <002e01c3ec30$1c3f1f30$6401a8c0@xp> References: <Pine.LNX.4.44.0402051110510.11161-100000@Kuna> <002e01c3ec30$1c3f1f30$6401a8c0@xp> Message-ID: <200402051514.14108.syn_ack@comcast.net> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Thursday 05 February 2004 01:36 pm, Alan Gauld wrote: > Yes, its called practice! > Seriously the best way to learn to program is to take the examples > in the boooks and extend them in diffreent ways. > > If the example prints the 12 times table, change it to print > the 9 times table, then to do it in a different format, then to > print the squares from 1 to 12 instead. Just little changes but > by making those changes you reinforce the ideas and prove to > yourself that you really understand what's happening. > > Finally don't try to run before you walk. A GUI interface may > look nice but trying to add one too soon will simply distract > you from the fundamentals. Great. Thanks for the suggestions Alan. Well it looks like I might have found a book thats right up my alley. It looks really good. Its doing Python by example through the whole book.. Called "Python Programming for the absolute beginner" by Michael Dawson I'm running Python 2.3.3 on both Windows and Linux and this book comes with 2.2.3. I'll just make sure that I check out the "Whats New in Python 2.3 .pdf" that came with Python 2.3.3. Joshua Banks -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (GNU/Linux) iD8DBQFAIs5Ep9X7q/XgeyYRAvKAAJ9ik+zntRVmLIJpUuQoO/QACwV/SwCdHjU1 mw8EBWz8UrpDfp8t6YG2qmk= =fQWC -----END PGP SIGNATURE----- From cspears2002 at yahoo.com Thu Feb 5 18:44:48 2004 From: cspears2002 at yahoo.com (Christopher Spears) Date: Thu Feb 5 18:44:53 2004 Subject: [Tutor] help with regular expressions Message-ID: <20040205234448.9911.qmail@web12401.mail.yahoo.com> I'm trying to figure out regular expressions and am completely baffled! I understand the concept because there is something similar in UNIX, but for some reason, Python regular expressions don't make any sense to me! Are there some good tutorials that can help explain this subject to me? -Chris From sigurd at 12move.de Thu Feb 5 18:55:29 2004 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Thu Feb 5 18:56:05 2004 Subject: [Tutor] printing answers In-Reply-To: <20040205214919.7756.qmail@web40109.mail.yahoo.com> (Rich Krauter's message of "Thu, 5 Feb 2004 13:49:19 -0800 (PST)") References: <20040205214919.7756.qmail@web40109.mail.yahoo.com> Message-ID: <m3ad3xw13j.fsf@hamster.pflaesterer.de> On 5 Feb 2004, Rich Krauter <- rmkrauter@yahoo.com wrote: > I think you're making it much harder than it needs to > be by using regexes and nested loops. > Notice I use answers as a dict, not a list. Dicts are > nice when you want to get rid of repeats. ACK. [Code] But you lose information the way you wrote the code. In the example of the OP the case didn't matter but didn't get lost. Furthermore try / except without an explicit error condition is dangerous. You also catch errors you perhaps didn't think about. So the code should be written a bit different IMO. def find_match(lst): answers = {} res = [] for s in lst: sl = s.lower() answers.setdefault(sl,[]).append(s) for key, val in answers.items(): if len(val) > 1: res.extend(val) return res The lowered string is used as key and a list with the original strings gets used as value. Each value list which has a length > 1 gets pushed into the result list which is finally returned. The setdefault method of dictionaries is very handy here. If called with an existing key it returns the appendant value or the second argument (which is the empty list here); the append method then adds the string to the list. Karl -- Please do *not* send copies of replies to me. I read the list From sigurd at 12move.de Thu Feb 5 19:17:01 2004 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Thu Feb 5 19:21:21 2004 Subject: [Tutor] fancy list things In-Reply-To: <Pine.LNX.4.44.0402051502260.11161-100000@Kuna> (Marilyn Davis's message of "Thu, 5 Feb 2004 15:14:08 -0800 (PST)") References: <Pine.LNX.4.44.0402051502260.11161-100000@Kuna> Message-ID: <m365elw061.fsf@hamster.pflaesterer.de> On 6 Feb 2004, Marilyn Davis <- marilyn@deliberate.com wrote: > Is it true that you can *always* replace map() and filter() with a > list comprehension? But you can never replace reduce()? Yes. No (well it is possible but extremly ugly): >>> class Foo: ... def __init__(self, x): ... self.x = x ... def set (self, v): ... self.x += v ... return self.x ... >>> [f.set(e) for e in range(10)].pop() 45 >>> reduce(lambda m, n: m+n, range(10), 0) 45 So with some side effects you get something which looks a bit like reduce (but has nothing to do with it). map() and filter() on the other hand can be replaced by list comprehensions. > Can anyone give me a reasonable example of lambda? What do you mean exactly? Lambda calculus? Lambda in Python? In Python lambda can be used to build simple (very simple sadly) anonymous expressions (no statements) which can get used at places where you think it's not worth writing a function with a name. But their usage is very weakly in Python, you can't compare it with languages like Lisp (CL, Scheme) or Haskell. But that's no bug it's a feature :-) Karl -- Please do *not* send copies of replies to me. I read the list From rmkrauter at yahoo.com Thu Feb 5 19:21:47 2004 From: rmkrauter at yahoo.com (Rich Krauter) Date: Thu Feb 5 19:26:42 2004 Subject: [Tutor] printing answers In-Reply-To: <m3ad3xw13j.fsf@hamster.pflaesterer.de> References: <20040205214919.7756.qmail@web40109.mail.yahoo.com> <m3ad3xw13j.fsf@hamster.pflaesterer.de> Message-ID: <1076026907.4424.136.camel@vaio> On Thu, 2004-02-05 at 18:55, Karl Pfl=C3=A4sterer wrote: > ACK. > That bad, huh? I've made much worse posts than this one. > > But you lose information the way you wrote the code > Well, actually you don't lose any information because you still have list_of_strings available. If you want to append items to arrays in the dict instead of keeping a count in the dict, that's fine too. I guess I misunderstood; I thought he just wanted a list of unique entries, regardless of case.=20 > Furthermore try / except without an explicit error condition is > dangerous. You also catch errors you perhaps didn't think about. >=20 Good point. That was sloppy. I figured I could get away with it in a 5 line program, but you're right.=20 Thanks for the feedback. Rich From pythontutor at venix.com Thu Feb 5 19:29:33 2004 From: pythontutor at venix.com (Lloyd Kvam) Date: Thu Feb 5 19:29:38 2004 Subject: [Tutor] help with regular expressions In-Reply-To: <20040205234448.9911.qmail@web12401.mail.yahoo.com> References: <20040205234448.9911.qmail@web12401.mail.yahoo.com> Message-ID: <4022DFED.9060202@venix.com> I believe that much of David Mertz's book, "Text Processing in PYTHON" is available on-line. He has a good section on regular expressions. Most of the other general Python books including Martelli's and Christopher's cover regular expressions. I believe that Python regular expression syntax matches pretty closely to the extended syntax in egrep, etc and also to Perl's. Google should also be able to help. I've stumbled across lots of regular expression articles over the years. Christopher Spears wrote: > I'm trying to figure out regular expressions and am > completely baffled! I understand the concept because > there is something similar in UNIX, but for some > reason, Python regular expressions don't make any > sense to me! Are there some good tutorials that can > help explain this subject to me? > > -Chris > > _______________________________________________ > 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 Thu Feb 5 19:34:25 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Feb 5 19:34:33 2004 Subject: [Tutor] help with regular expressions In-Reply-To: <20040205234448.9911.qmail@web12401.mail.yahoo.com> Message-ID: <Pine.LNX.4.44.0402051617310.27575-100000@hkn.eecs.berkeley.edu> On Thu, 5 Feb 2004, Christopher Spears wrote: > I'm trying to figure out regular expressions and am completely baffled! > I understand the concept because there is something similar in UNIX, but > for some reason, Python regular expressions don't make any sense to me! > Are there some good tutorials that can help explain this subject to me? Hi Chris, Yes, there's a tutorial-style Regular Expression HOWTO by A.M. Kuchling: http://www.amk.ca/python/howto/regex/ Regular expressions allow us to define text patterns. For example, we can define a pattern of a bunch of 'a's: ### >>> import re >>> pattern = re.compile('a+') >>> pattern <_sre.SRE_Pattern object at 0x8126060> ### 'pattern' is a regular expression that can recognize all continuous patterns of the letter 'a'. That is, if we give it a string with 'a's, it'll recognize exactly where they are. Let's see what it does on a simple example: ### >>> pattern.findall('this is a test') ['a'] ### Here, it found the letter 'a'. Let's try something else: ### >>> pattern.findall('aaabaracccaaaadaabraaaa') ['aaa', 'a', 'a', 'aaaa', 'aa', 'aaaa'] ### And here, it found all 'a' sequences in that string. Does this make sense so far? The pattern above is deliberately simple, but regular expressions can get a little more complicated. For example, here's a regular expression that tries to detect date strings of the form '2/5/2004' (like date strings): ### >>> date_regex = re.compile('[0-9]+/[0-9]+/[0-9]+') >>> date_regex.findall("this is a test on 02/05/2004, right?") ['02/05/2004'] ### The regular expression is trying to say "a bunch of digits, followed by a a slash, followed by another bunch of digits, followed by a slash, and then topped with another bunch of digits". Whew. *grin* Caveat: the pattern above is too lenient for catching date strings. It also catches stuff like 2005/2/5, or even things like: ### >>> date_regex.findall("looky 1/2/3 or /4/5/6/") ['1/2/3', '4/5/6'] ### So there's something of an art to writing good regular expressions that are both general and specific. If you have questions, please feel free to ask. From arkamir at softhome.net Thu Feb 5 19:17:34 2004 From: arkamir at softhome.net (Conrad Koziol) Date: Thu Feb 5 19:35:22 2004 Subject: [Tutor] Sets module/Removing duplicates Message-ID: <1076026653.3792.5.camel@conradpc> Hello, I've been doing some research on the sets module,and everywhere it says its great from removing duplicates from a list, but nowhere actually tells you how (or am i just not looking in the right spot?). Can anyone show me how :) Thanks a lot From dyoo at hkn.eecs.berkeley.edu Thu Feb 5 19:42:59 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Feb 5 19:43:32 2004 Subject: [Tutor] Sets module/Removing duplicates In-Reply-To: <1076026653.3792.5.camel@conradpc> Message-ID: <Pine.LNX.4.44.0402051640020.27575-100000@hkn.eecs.berkeley.edu> On Thu, 5 Feb 2004, Conrad Koziol wrote: > I've been doing some research on the sets module, and everywhere it says > its great from removing duplicates from a list, but nowhere actually > tells you how (or am i just not looking in the right spot?). Can anyone > show me how :) Hi Conrad, The examples from: http://www.python.org/doc/lib/set-example.html will construct a few sets out of lists of unique elements. But try putting duplicates elements in the lists and see what happens. Good luck! From marilyn at deliberate.com Thu Feb 5 19:48:57 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Thu Feb 5 19:49:16 2004 Subject: [Tutor] fancy list things In-Reply-To: <m365elw061.fsf@hamster.pflaesterer.de> Message-ID: <Pine.LNX.4.44.0402051642490.11161-100000@Kuna> On Fri, 6 Feb 2004, Karl Pfl?sterer wrote: > On 6 Feb 2004, Marilyn Davis <- marilyn@deliberate.com wrote: > > > Is it true that you can *always* replace map() and filter() with a > > list comprehension? But you can never replace reduce()? > > Yes. No (well it is possible but extremly ugly): > > >>> class Foo: > ... def __init__(self, x): > ... self.x = x > ... def set (self, v): > ... self.x += v > ... return self.x > ... > >>> [f.set(e) for e in range(10)].pop() > 45 > >>> reduce(lambda m, n: m+n, range(10), 0) > 45 > > So with some side effects you get something which looks a bit like > reduce (but has nothing to do with it). I'm sorry, I meant that you can't replace it with a list comprehension of any sort? And zip() can't be replaced with any sort of list comprehension. Right? > > map() and filter() on the other hand can be replaced by list > comprehensions. > > > > Can anyone give me a reasonable example of lambda? > > What do you mean exactly? Lambda calculus? Lambda in Python? > > In Python lambda can be used to build simple (very simple sadly) > anonymous expressions (no statements) which can get used at places where > you think it's not worth writing a function with a name. But their > usage is very weakly in Python, you can't compare it with languages like > Lisp (CL, Scheme) or Haskell. But that's no bug it's a feature :-) Is it only useful in map() and filter() and reduce()? And other places where you want to hand a little function to a function? comp() for example. Is there another class of examples? I'm teaching python for the first time and want to be as solid as possible on this stuff. Thank you. Marilyn > > > > Karl > -- From dyoo at hkn.eecs.berkeley.edu Thu Feb 5 20:22:50 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Feb 5 20:33:00 2004 Subject: [Tutor] fancy list things In-Reply-To: <Pine.LNX.4.44.0402051642490.11161-100000@Kuna> Message-ID: <Pine.LNX.4.44.0402051653400.20604-100000@hkn.eecs.berkeley.edu> > > In Python lambda can be used to build simple (very simple sadly) > > anonymous expressions (no statements) which can get used at places > > where you think it's not worth writing a function with a name. But > > their usage is very weakly in Python, you can't compare it with > > languages like Lisp (CL, Scheme) or Haskell. But that's no bug it's a > > feature :-) > > Is it only useful in map() and filter() and reduce()? And other places > where you want to hand a little function to a function? comp() for > example. Is there another class of examples? Hi Marilyn, lambda's can also be useful whenever we want to create simpler versions of functions that already have some parameters filled in. Here is a simple example: ### >>> def add(x, y): ... return x + y ... >>> add1 = lambda y: add(1, y) >>> >>> >>> add1(42) 43 ### Another way of saying this is: ### def add1(y): return add(1, y) ### The 'def' statement in Python is sort of a combination of lambda-function-making plus name-binding. > I'm teaching python for the first time and want to be as solid as > possible on this stuff. Hmmm... you may want to avoid talking about lambda, then. Concentrate on what you're comfortable talking about. I'd recommend focusing on the things that people will usually do with Python, so show how to construct functions with 'def'. The advantage that 'lambda' has over 'def' is that it doesn't force us to bind the function value with a name. But Python programmers usually want to give good names our functions to express human intent, anyway. And function values are just function values. *grin* def'ed functions can also be passed around just as easily as values from lambdas: ### >>> def compose(f, g): ... def composed_function(x): ... return f(g(x)) ... return composed_function ... >>> def square(x): ... return x * x ... >>> def sqrt(x): ... return x ** (0.5) ... >>> quad_power = compose(square, square) >>> quad_power(17) 83521 >>> identity = compose(square, sqrt) >>> identity(17) 17.0 ### So there's no need to concentrate on the foreignness of the word 'lambda': lambda just creates function values. But we can get the value of anything by just naming it: ### >>> x = 42 >>> x 42 >>> def square(x): return x * x ... >>> square <function square at 0x8157bfc> ### Just for reference: the same thing that we did with 'def' here can be done exclusively with lambda's. ### >>> compose = lambda f, g: lambda x: f(g(x)) >>> square = lambda x: x*x >>> sqrt = lambda x: x**(0.5) >>> quad_power = compose(square, square) >>> quad_power(17) 83521 >>> quarter_power = compose(sqrt, sqrt) ## with cheese? >>> quarter_power(16) 2.0 ### The advantage of lambda here is that it's concise, so this kind of function-fiddling code ends up being really short to write. To a eye trained in functional languages, it looks neater. But there's little that we're doing here that we couldn't do already with 'def'. Hope this helps! From missive at hotmail.com Thu Feb 5 20:45:59 2004 From: missive at hotmail.com (Lee Harr) Date: Thu Feb 5 20:46:05 2004 Subject: [Tutor] Re: Zope and Python... Message-ID: <BAY2-F141Tx44qNAPsJ00009b74@hotmail.com> > Just looking for peoples experience on Zope --- What is the >tutor thoughts on it ? > >Those that use it what are your gripes or praises and if you don't like >Zope >is there something else you would recommend to give a > >similar functionality. I am finding it hard to find good "easy" beginner >documentation on application building in Zope. I've gone through the >Devshed > >documents and the zope book but I have found many problems in the examples >and just the version diffs in Zope. > > > >Are there any good resources that anyone would suggest for Learning to >develop apps under Zope ? > I really like zope. We use it for our school website. Some say it has a steep learning curve, but I say it is more of an oddly shaped learning curve. To get started and do simple things with pre-made "products" is really pretty simple. More complex things like creating your own products can take a while to master. Things I really like about zope are zope page templates (zpt) which can actually be used outside of zope, and the ease with which I can delegate different sections of the site to different users/developers. _________________________________________________________________ The new MSN 8: smart spam protection and 2 months FREE* http://join.msn.com/?page=features/junkmail From Harm_Kirchhoff at mail.digital.co.jp Thu Feb 5 21:42:04 2004 From: Harm_Kirchhoff at mail.digital.co.jp (Harm_Kirchhoff@mail.digital.co.jp) Date: Thu Feb 5 21:41:48 2004 Subject: [Tutor] Zope and Python... Message-ID: <OFBE4FF570.9E487A63-ON49256E32.000D746F-49256E32.000E9CCC@jp.schneider-electric.com> I am using ZOPE under Win2000 purely as a database and not as a web-based application. I fully concur with your observation that it is difficult to get started. The mailing list on zope is very very high level and the answers you get to beginner questions are sometimes/often too high to understand. I basically bought all books available on ZOPE, but they all focus on the web aspects. There is little available on (mis)-using ZOPE simply as a DB. However, once you find out how to use ZOPE's ZODB purely as a giant python dictionary it becomes really easy to use and is quite fast (at least for my limited amount of data). Regarding the books on ZOPE as a web tool, I personally got started with 2: Zope Bible and Zope: Web Application Development and Content Management, which I found interesting because it discusses many add-in you can use (web-mail, ExternalFS, ...) and, fo course the ZOPE book (which I had to read twice). To my knowledge there is no resource on the net that focuses on absolute ZOPE beginners. It is pretty much a specialists circle that takes some time to get it. I had a frustrating couple of months, but afterwards I could at least do some basic stuff. Regarding ZODB: I do not want to miss it. If you need some code to get started on ZODB, I can post it. From shaleh at speakeasy.net Fri Feb 6 00:38:06 2004 From: shaleh at speakeasy.net (Sean 'Shaleh' Perry) Date: Fri Feb 6 00:38:21 2004 Subject: [Tutor] Visitor Pattern In-Reply-To: <20040202020506.31323.qmail@web41803.mail.yahoo.com> References: <20040202020506.31323.qmail@web41803.mail.yahoo.com> Message-ID: <200402052138.06081.shaleh@speakeasy.net> On Sunday 01 February 2004 18:05, Daniel Ehrenberg wrote: > What is a visitor pattern? I've heard that it shows > how good a language is, and that Lisp is really good > because it can be done in two (cryptic) lines. How can > a visitor pattern be implimented in Python? > It is from the original "Desgin Patterns" book which is one of the bibles of OO coding. An excerpt: <quote> Intent Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the class of the elements on which it operates. </quote> The idea here is you have an object with "visits" another object and in some way interacts with it. Common example: for window in windowList: display.draw(window) which in functional terms shows up as: map(display.draw, windowList) or in new terms [display.draw(window) for window in windowList] Visitor is a very, very common idiom in functional languages. From isrgish at fusemail.com Fri Feb 6 02:07:57 2004 From: isrgish at fusemail.com (Isr Gish) Date: Fri Feb 6 02:09:11 2004 Subject: [Tutor] How to get variable name from its id() Message-ID: <E1Ap06l-000600-Ik@fuse1.fusemail.net> Is it possible to get the variable name or its contents if we know its I?d. Name = 'Isr Gish' ID = id(Name) Now use I?D to either find the variable name (Name), or get the contents of Name. If someone can point me where to find this info. It would be greatly appreciated. All the best Isr From anna at aleax.it Fri Feb 6 03:29:41 2004 From: anna at aleax.it (Anna Ravenscroft) Date: Fri Feb 6 03:29:48 2004 Subject: [Tutor] Looking for some guidance. In-Reply-To: <200402051514.14108.syn_ack@comcast.net> References: <Pine.LNX.4.44.0402051110510.11161-100000@Kuna> <002e01c3ec30$1c3f1f30$6401a8c0@xp> <200402051514.14108.syn_ack@comcast.net> Message-ID: <200402060929.41209.anna@aleax.it> On Friday 06 February 2004 12:14 am, Joshua Banks wrote: > Well it looks like I might have found a book thats right up my alley. It > looks really good. Its doing Python by example through the whole book.. > Called "Python Programming for the absolute beginner" by Michael Dawson Thanks for letting us know what works for you. This is one of those common questions, and getting an idea of what people like and *why* they find them valuable is really helpful! Anna -- There is a type 3 error in which your mind goes totally blank whenever you try to remember which is which of type 1 and type 2. -Richard Dawkins From RobinHood42 at clickta.com Fri Feb 6 05:17:10 2004 From: RobinHood42 at clickta.com (alice) Date: Fri Feb 6 05:15:57 2004 Subject: [tutor] Tkinter 101 In-Reply-To: <00f901c3e917$e7f24600$6401a8c0@xp> References: <20040201023500.51351.qmail@web13608.mail.yahoo.com> <00f901c3e917$e7f24600$6401a8c0@xp> Message-ID: <200402061717.10361.RobinHood42@clickta.com> I don't really know very much about Python or computer programming, but I didn't think that was a good enough reason not to give it a try. Anyway, I've written this program. Its basicially a simulation of Conway's "game of life" It seems to work fine and all, but I'm sure there are better ways of doing what I've done than the way I did it, so I'm posting it to this list in the hope of recieving some constructive criticism. Here it is (sorry, its a bit long): import Tkinter as Tk import random class Menu: def __init__(self, parent): # appearance (inherit from parent): self._background = parent.background self._activebackground = parent.activebackground self._font = parent.font # essential initialization: self._root = parent.root self._menubar = Tk.Menu(self._root) self._root.config(menu=self._menubar) # store all the user created menus in a dictionary: self._menus = {} # appearance self._menubar["background"] = self._background self._menubar["activebackground"] = self._activebackground self._menubar["font"] = self._font def add_menu(self, menu_name): # use the name of the menu as key into menus dict: self._menus[menu_name] = Tk.Menu(self._root) self._menubar.add_cascade(label=menu_name, \ menu=self._menus[menu_name]) # appearance: self._menus[menu_name]["background"] = self._background self._menus[menu_name]["activebackground"] = self._activebackground self._menus[menu_name]["font"] = self._font def add_command(self, menu_name, command_name, command): self._menus[menu_name].add_command(label=command_name, \ command=command) class PopConfig: def __init__(self,parent): # appearance (inherit from parent): self._foreground = parent.foreground self._background = parent.background self._activebackground = parent.activebackground self._font = parent.font self._white = parent.white # pop up a dialog: self._pop = Tk.Toplevel(parent.root) self._pop.grab_set() # make some dictionaries to store user created widgets: self._frames = {} self._labels = {} self._buttons = {} self._entries = {} self._scales = {} # make a frame for user defined buttons: self._frames["buttons"] = Tk.Frame(self._pop) self._frames["buttons"].pack(side=Tk.BOTTOM,padx=5,pady=5) # appearance: self._pop["background"] = self._background def make_button(self, name, command): # use the text on the button as the key into buttons dict: self._buttons[name] = Tk.Button(self._frames["buttons"]) self._buttons[name]["text"] = name self._buttons[name]["command"] = command self._buttons[name].pack(side=Tk.LEFT) # appearance: self._buttons[name]["background"] = self._foreground self._buttons[name]["activebackground"] = self._activebackground self._buttons[name]["font"] = self._font def make_entrybox(self, id, label): # create a label widget and an entry widget # nested inside a frame widget # use user defined id as key into widget dicts: self._frames[id] = Tk.Frame(self._pop) self._frames[id].pack(side=Tk.TOP) self._labels[id] = Tk.Label(self._frames[id]) self._labels[id]["text"] = label self._labels[id].pack(side = Tk.LEFT) self._entries[id] = Tk.Entry(self._frames[id]) self._entries[id].pack(side=Tk.LEFT, padx = 10, pady = 10) # appearance: self._frames[id]["background"] = self._background self._labels[id]["background"] = self._background self._entries[id]["background"] = self._white self._labels[id]["font"] = self._font def make_scale(self, id, label): # create a label widget and a scale widget # nested inside a frame widget # use user defined id as key into widget dicts: self._frames[id] = Tk.Frame(self._pop) self._frames[id].pack(side=Tk.TOP) self._labels[id] = Tk.Label(self._frames[id]) self._labels[id]["text"] = label self._labels[id].pack(side = Tk.LEFT) self._scales[id] = Tk.Scale(self._frames[id]) self._scales[id].pack(side=Tk.LEFT, padx = 10, pady = 10) # appearance: self._frames[id]["background"] = self._background self._labels[id]["background"] = self._background self._scales[id]["background"] = self._background self._scales[id]["activebackground"] = self._activebackground self._scales[id]["troughcolor"] = self._white self._scales[id]["orient"] = "horizontal" self._labels[id]["font"] = self._font def get_entry(self, id): return self._entries[id].get() def get_scale(self, id): return self._scales[id].get() def close(self): self._pop.destroy() class Canvas: def __init__(self, parent, width, height): # inherit from parent: self._root = parent.root self.bg = parent.white self.fg = parent.foreground # make canvas: self.canvas = Tk.Canvas(self._root) self.canvas.pack() # initial dimensions: self._width = width self._height = height # clear canvas: self.clear() def clear(self): self.canvas.destroy() self.canvas = Tk.Canvas(self._root) self.canvas.pack() self.canvas["background"] = self.bg self.canvas["width"] = self._width self.canvas["height"] = self._height def get_width(self): return self._width def get_height(self): return self._height def change_dimensions(self, new_width, new_height): self._width = new_width self._height = new_height self.clear() class GUI: def __init__(self): self.root = Tk.Tk() self.set_colours() def set_colours(self): # default colours: self.foreground = "turquoise" self.background = "aquamarine" self.activebackground = "pale green" self.white = "alice blue" self.font = "courier" def loop(self): self.root.mainloop() def quit(self): self.root.destroy() class Cells: def __init__(self, canvas, x, y): # cell dimensions self._x = x self._y = y # canvas dimensions self._width = canvas.get_width() self._height = canvas.get_height() # canvas and colours: self.canvas = canvas.canvas self.fg = canvas.fg self.bg = canvas.bg # event binding: self.canvas.focus_set() self.canvas.bind("<Button 1>", self.handle_mouse) self.canvas.bind("<Return>", self.handle_return) # initialize internal state self._make_state() self.clear_state def _make_state(self): self._state = [] self._temp_state = [] for i in range(self._x): self._state.append([]) self._temp_state.append([]) for j in range(self._y): self._state[i].append([]) self._temp_state[i].append([]) def clear_state(self): for i in range(self._x): for j in range(self._y): self._state[i][j] = "off" def show_state(self): print self._state def show_temp_state(self): print self._temp_state def cell_on(self,i,j): self._state[i][j] = "on" def cell_off(self,i,j): self._state[i][j] = "off" def get_x(self): return self._x def get_y(self): return self._y def change_dimensions(self, new_x, new_y): self._x = new_x self._y = new_y self._make_state() self.clear_state() def _neighbours(self,i,j): n = [] for row in ((i-1) % self._x, i, (i+1) % self._x): for column in ((j-1) % self._y, j, (j+1) % self._y): n.append((row,column)) n.remove((i,j)) return n def _count_neighbours(self,i,j): count = 0 n = self._neighbours(i,j) for cell in n: if (self._state[cell[0]][cell[1]] == "on"): count += 1 return count def iterate(self): for i in range(self._x): for j in range(self._y): n = self._count_neighbours(i,j) if (n == 3): self._temp_state[i][j] = "on" else: if (n == 2): self._temp_state[i][j] = self._state[i][j] else: self._temp_state[i][j] = "off" for i in range(self._x): for j in range(self._y): self._state[i][j] = self._temp_state[i][j] def display(self): self.cell_width = self._width / self._x self.cell_height = self._height / self._y for i in range(self._x): for j in range(self._y): left = i*self.cell_width right = (i+1)*self.cell_width bottom = j*self.cell_height top = (j+1)*self.cell_height if (self._state[i][j] == "on"): self.canvas.create_rectangle(left,bottom,right,top, \ fill=self.fg) else: self.canvas.create_rectangle(left,bottom,right,top, \ fill=self.bg) def random_state(self, density): c = [] for i in range(density): c.append(True) for i in range(100 - density): c.append(False) for i in range(self._x): for j in range(self._y): if random.choice(c): self.cell_on(i,j) else: self.cell_off(i,j) def handle_mouse(self,event): i = event.x / self.cell_width j = event.y / self.cell_height if (self._state[i][j] == "on"): self.cell_off(i,j) else: self.cell_on(i,j) self.display() def handle_return(self,event): self.iterate() self.display() class Game: def __init__(self): self.gui = GUI() self.canvas = Canvas(self.gui, 300, 300) self.cells = Cells(self.canvas, 30, 30) self.cells.display() self.menu = Menu(self.gui) self.menu.add_menu("main") self.menu.add_command("main", "clear", self.menu_clear) self.menu.add_command("main", "quit", self.gui.quit) self.menu.add_menu("config") self.menu.add_command("config", "cells", self.menu_cells) self.menu.add_command("config", "canvas", self.menu_canvas) self.menu.add_command("config", "random", self.menu_random) self.gui.loop() def menu_clear(self): self.cells.clear_state() self.cells.display() def menu_cells(self): self.p = PopConfig(self.gui) self.p.make_entrybox("x", " How many columns: ") self.p.make_entrybox("y", " How many rows: ") self.p.make_button(" OK ", self.config_cells) self.p.make_button("CANCEL", self.p.close) def menu_canvas(self): self.p = PopConfig(self.gui) self.p.make_entrybox("h", " How many pixels high: ") self.p.make_entrybox("w", " How many pixels wide: ") self.p.make_button(" OK ", self.config_canvas) self.p.make_button("CANCEL", self.p.close) def menu_random(self): self.p = PopConfig(self.gui) self.p.make_scale("density", " Percentage of cells alive: ") self.p.make_button(" OK ", self.config_random) self.p.make_button("CANCEL",self.p.close) def config_cells(self): try: new_x = int(self.p.get_entry("x")) new_y = int(self.p.get_entry("y")) self.cells.change_dimensions(new_x,new_y) self.cells.display() except ValueError: pass self.p.close() def config_canvas(self): try: new_w = int(self.p.get_entry("w")) new_h = int(self.p.get_entry("h")) self.canvas.change_dimensions(new_w,new_h) self.cells = Cells(self.canvas, self.cells.get_x(), \ self.cells.get_y()) self.cells.display() except ValueError: pass self.p.close() def config_random(self): d = self.p.get_scale("density") self.cells.random_state(d) self.cells.display() self.p.close() life = Game() From syn_ack at comcast.net Fri Feb 6 05:32:57 2004 From: syn_ack at comcast.net (Joshua Banks) Date: Fri Feb 6 05:37:16 2004 Subject: [Tutor] Looking for some guidance. In-Reply-To: <200402060929.41209.anna@aleax.it> References: <Pine.LNX.4.44.0402051110510.11161-100000@Kuna> <200402051514.14108.syn_ack@comcast.net> <200402060929.41209.anna@aleax.it> Message-ID: <200402060232.58880.syn_ack@comcast.net> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Friday 06 February 2004 12:29 am, Anna Ravenscroft wrote: > On Friday 06 February 2004 12:14 am, Joshua Banks wrote: > > Well it looks like I might have found a book thats right up my > > alley. It looks really good. Its doing Python by example through > > the whole book.. Called "Python Programming for the absolute > > beginner" by Michael Dawson > > Thanks for letting us know what works for you. This is one of those > common questions, and getting an idea of what people like and *why* > they find them valuable is really helpful! > > Anna No problem Anna. It just happened to be exactly what I was looking for. That hardly ever happens, so I really lucked out. The only thing is I can't seem to find any Errata links on the publishers web site. And I've ran into a couple things that are obvious print mistakes. Python was able to point right to where the mistake was though. Cool.. I like it, I luv it.. Heh.. Joshua Banks -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (GNU/Linux) iD8DBQFAI21Zp9X7q/XgeyYRAvLJAKCS9/K19uD0MpN5dIxEX2b1lbZ3KgCfa43n H2HEq2ptacWUIm5lrP6bwB0= =vMeb -----END PGP SIGNATURE----- From bgailer at alum.rpi.edu Fri Feb 6 06:13:01 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri Feb 6 06:12:41 2004 Subject: [Tutor] printing answers In-Reply-To: <20040205211807.99141.qmail@web12406.mail.yahoo.com> References: <20040205211807.99141.qmail@web12406.mail.yahoo.com> Message-ID: <6.0.0.22.0.20040206040915.03e8d958@mail.mric.net> At 02:18 PM 2/5/2004, Christopher Spears wrote: >I'm writing a function that takes a list of strings >and finds any identical strings. Case should not >matter. For example, in ['one','One', 'two', 'three', >'ThrEE'], one and One and three and ThrEE should be >recognized as pairs. >I wrote the following code: > >def findMatch(list_of_strings): > > import re > answers = [] > > for i in range(len(list_of_strings)): > pattern = re.compile(list_of_strings[i], re.I) > for i in range(len(list_of_strings)): > match = re.match(pattern, >list_of_strings[i]) > if match != None: > answers = answers + >[list_of_strings[i]] > > print answers > >My problem is printing out the correct answers. When >I ran a test, I got the following result: > > >>> findMatch(['one', 'two', 'One']) >['one', 'One', 'two', 'one', 'One'] > >What am I doing wrong? I think my logic is correct. There have been a number of good replies to this post. But none of them explain what Christopher was wanting to know - what am I dong wrong. Well, as you might guess the program is doing exactly what you told it to do. Take each string and see if it matches (ignoring case) any of the strings. In the process each string will match itself. Therefore you get each string at least once in the output. Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.577 / Virus Database: 366 - Release Date: 2/3/2004 From pythontutor at venix.com Fri Feb 6 08:17:46 2004 From: pythontutor at venix.com (Lloyd Kvam) Date: Fri Feb 6 08:18:28 2004 Subject: [Tutor] fancy list things In-Reply-To: <Pine.LNX.4.44.0402051642490.11161-100000@Kuna> References: <Pine.LNX.4.44.0402051642490.11161-100000@Kuna> Message-ID: <402393FA.4030809@venix.com> Marilyn Davis wrote: > On Fri, 6 Feb 2004, Karl Pfl?sterer wrote: > (SNIPPED) > > Is it only useful in map() and filter() and reduce()? And other > places where you want to hand a little function to a function? comp() > for example. Is there another class of examples? > > I'm teaching python for the first time and want to be as solid as > possible on this stuff. You probably do NOT want to inflict this on your class, But David Mertz made heavy use of lambda's in building a set of functions for combining functions: (from "Text Processing in Python") #------------------- combinatorial.py -------------------# from operator import mul, add, truth apply_each = lambda fns, args=[]: map(apply, fns, [args]*len(fns)) bools = lambda lst: map(truth, lst) bool_each = lambda fns, args=[]: bools(apply_each(fns, args)) conjoin = lambda fns, args=[]: reduce(mul, bool_each(fns, args)) all = lambda fns: lambda arg, fns=fns: conjoin(fns, (arg,)) both = lambda f,g: all((f,g)) all3 = lambda f,g,h: all((f,g,h)) and_ = lambda f,g: lambda x, f=f, g=g: f(x) and g(x) disjoin = lambda fns, args=[]: reduce(add, bool_each(fns, args)) some = lambda fns: lambda arg, fns=fns: disjoin(fns, (arg,)) either = lambda f,g: some((f,g)) anyof3 = lambda f,g,h: some((f,g,h)) compose = lambda f,g: lambda x, f=f, g=g: f(g(x)) compose3 = lambda f,g,h: lambda x, f=f, g=g, h=h: f(g(h(x))) ident = lambda x: x It was done for the same reason lambda is used with map, etc., creating named versions of the expressions is more confusing than simply showing the expression. the first function could have been written: def apply_each( fns, args=[]): return map(apply, fns, [args]*len(fns)) Written either way, you will probably need to expend some thought before you really understand how to use a function like this. The book does include explanations and examples. -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From orbitz at ezabel.com Fri Feb 6 08:49:44 2004 From: orbitz at ezabel.com (orbitz@ezabel.com) Date: Fri Feb 6 08:51:04 2004 Subject: [Tutor] How to get variable name from its id() In-Reply-To: <E1Ap06l-000600-Ik@fuse1.fusemail.net> References: <E1Ap06l-000600-Ik@fuse1.fusemail.net> Message-ID: <20040206084944.582231aa.orbitz@ezabel.com> I don't quite follow what you mean here. If you just do ID = Name, then ID and Name will point to the same object. Strings are immutable though so if you change one it wont' be reflected in the other. For example: >>> Name = 'blah' >>> ID = Name >>> ID is Name True >>> ID = 'zing' >>> ID is Name False I hope this answers your question. On Fri, 6 Feb 2004 02:07:57 -0500 "Isr Gish" <isrgish@fusemail.com> wrote: > Is it possible to get the variable name or its contents if we know its I?d. > > Name = 'Isr Gish' > ID = id(Name) > Now use I?D to either find the variable name (Name), or get the contents of > Name. > > If someone can point me where to find this info. It would be greatly > appreciated. > > All the best > Isr > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From gerrit at nl.linux.org Fri Feb 6 09:10:23 2004 From: gerrit at nl.linux.org (Gerrit Holl) Date: Fri Feb 6 09:10:27 2004 Subject: [Tutor] How to get variable name from its id() In-Reply-To: <20040206084944.582231aa.orbitz@ezabel.com> References: <E1Ap06l-000600-Ik@fuse1.fusemail.net> <20040206084944.582231aa.orbitz@ezabel.com> Message-ID: <20040206141023.GA13972@nl.linux.org> <quote name="orbitz@ezabel.com" date="1076053784" email="orbitz@ezabel.com"> > I don't quite follow what you mean here. If you just do ID = Name, then ID and > Name will point to the same object. Strings are immutable though so if you > change one it wont' be reflected in the other. For example: > >>> Name = 'blah' > >>> ID = Name > >>> ID is Name > True > >>> ID = 'zing' > >>> ID is Name > False I think he means: >>> name = 'blah' >>> id(name) -1085830240 ...and then get 'blah' back from the ID. I don't think it's possible. I'm not sure what deep ways into the interpreter Python offers, however, so I may be wrong. Weird, however, a negative ID.. Gerrit. -- Mozilla _is_ the web: it grows faster than you can download it. 1011001 1101111 1110101 1110010 1110011 0101100 1000111 1100101 1110010 1110010 1101001 1110100 From op73418 at mail.telepac.pt Fri Feb 6 09:29:16 2004 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Fri Feb 6 09:26:55 2004 Subject: [Tutor] How to get variable name from its id() In-Reply-To: <E1Ap06l-000600-Ik@fuse1.fusemail.net> References: <E1Ap06l-000600-Ik@fuse1.fusemail.net> Message-ID: <ts8720h0biisn3uuaru18po0pihogtb41p@4ax.com> Em Fri, 6 Feb 2004 02:07:57 -0500, "Isr Gish" <isrgish@fusemail.com> atirou este peixe aos pinguins: >Is it possible to get the variable name or its contents if we know its I?d. > >Name = 'Isr Gish' >ID = id(Name) >Now use I?D to either find the variable name (Name), or get the contents of Name. > >If someone can point me where to find this info. It would be greatly appreciated. > You can't. Think about it: >>> a = [] >>> id(a) 15662288 >>> b = a >>> id(b) 15662288 >>> The same object can be referenced by several names. What name should your-would-be-function return? But suppose there was just one name: >>> id(c) 17640432 >>> reference = id(c) >>> reference 17640432 >>> del c >>> See the problem? id(<object>) is a unique id associated to each *live* object. Currently it is implemented as returning the memory address. If you kept the id, but later the object is destroyed, the id no longer makes any sense. With my best regards, G. Rodrigues From cspears2002 at yahoo.com Fri Feb 6 11:22:36 2004 From: cspears2002 at yahoo.com (Christopher Spears) Date: Fri Feb 6 11:22:41 2004 Subject: [Tutor] printing answers In-Reply-To: <6.0.0.22.0.20040206040915.03e8d958@mail.mric.net> Message-ID: <20040206162236.76470.qmail@web12402.mail.yahoo.com> > There have been a number of good replies to this > post. But none of them > explain what Christopher was wanting to know - what > am I dong wrong. > > Well, as you might guess the program is doing > exactly what you told it to do. > Take each string and see if it matches (ignoring > case) any of the strings. > In the process each string will match itself. > Therefore you get each string > at least once in the output. > Hmmm...Now that I look at the program, I see you are right! Thanks for the reply! The question now is how do I fix it? Any hints? -Chris From vicki at thepenguin.org Fri Feb 6 11:49:50 2004 From: vicki at thepenguin.org (Vicki Stanfield) Date: Fri Feb 6 12:47:39 2004 Subject: [Tutor] Help with appropriate looping and logic Message-ID: <38383.206.53.226.235.1076086190.squirrel@www.thepenguin.org> I have some code that I have written which should rightly be one section of code, but which I have had to code in three separate sections to get it to work right. I am hoping that someone on this list can help me get it right. I have written some pseudo-code to post here. The problem is that there are a few loops and several if/elif statements. For some reason I have not been able to work it out in Python. Here is the pseudo-code: send <STX> IF 1: send [AA][AA] IF 2: send [AB][AB] IF 3: send [AC][AC] send <TAB> IF 1 or 2: send [BB][BB] 16 times IF 3: send [BB][BB] once send <TAB> IF 1: send [CA][CA] IF 2: send [CB][CB] IF 3: send [CC][CC] IF 1 or 2: send <ETX> receive <ACK> IF 3: SEND <EOT> receive <ACK> IF 1: Repeat whole sequence 12 times IF 2: send <STX> send [DA][DA] send <TAB> send [BB][BB] 4 more times send <TAB> send [EA][EA] send <EOT> receive <ACK> receive <ACK> IF 3: receive <ACK> IF 1: send <STX> send [FA][FA] send <TAB> send [BB][BB] 8 more times send <TAB> send [FB] send <EOT> receive <ACK> receive <ACK> I would appreciate someone helping me map this out as one unit of code. --vicki From sigurd at 12move.de Fri Feb 6 11:42:38 2004 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Fri Feb 6 12:49:57 2004 Subject: [Tutor] fancy list things In-Reply-To: <Pine.LNX.4.44.0402051642490.11161-100000@Kuna> (Marilyn Davis's message of "Thu, 5 Feb 2004 16:48:57 -0800 (PST)") References: <Pine.LNX.4.44.0402051642490.11161-100000@Kuna> Message-ID: <m3vfmki3zt.fsf@hamster.pflaesterer.de> On 6 Feb 2004, Marilyn Davis <- marilyn@deliberate.com wrote: > I'm sorry, I meant that you can't replace it with a list comprehension > of any sort? And zip() can't be replaced with any sort of list > comprehension. Right? maybe I understood you wrong but the example I gave was indeed a list comp (also a weird one). So it can be replaced (if you accept some additional side effects). zip() can be replaced by a list comp. That has to be so since we said before that we can repplace map() with a list comp. Since zip() can be written with map() we would have otherwise a contradiction. zip() written with map(): >>> L = range(5) >>> M = range(5,10) >>> N = range(10) >>> zip(L, M) [(0, 5), (1, 6), (2, 7), (3, 8), (4, 9)] >>> map(None, L, M) [(0, 5), (1, 6), (2, 7), (3, 8), (4, 9)] >>> Writing it as a list comp looks not so nice but is possible: >>> [(L[i], N[i]) for i in min(range(len(L)), range(len(M)))] [(0, 10), (1, 11), (2, 12), (3, 13), (4, 14)] >>> Above resembles the way zip() works: >>> zip(L,N) [(0, 10), (1, 11), (2, 12), (3, 13), (4, 14)] >>> For the way map() works with lists of different length we have to rewrite the expression: >>> map(None, L, N) [(0, 10), (1, 11), (2, 12), (3, 13), (4, 14), (None, 15), (None, 16), (None, 17), (None, 18), (None, 19)] >>> def lget (lst, i): ... try: ... return lst[i] ... except IndexError: ... return ... >>> [(lget(L, i), lget(N, i)) for i in max(range(len(L)), range(len(N)))] [(0, 10), (1, 11), (2, 12), (3, 13), (4, 14), (None, 15), (None, 16), (None, 17), (None, 18), (None, 19)] >>> Above does not mean that anyone with a sane mind would use it in real code; but it shoes that it is indeed possible to find solutions. > Is it only useful in map() and filter() and reduce()? And other > places where you want to hand a little function to a function? comp() > for example. Is there another class of examples? Others gave you good examples whre it can be used. > I'm teaching python for the first time and want to be as solid as > possible on this stuff. It's good that you try beforehand to gain as much information as possible but I'm not sure if lambda should be the first to show to students in Python. It can be very useful to write concise, clear and also nice looking (very important; you have to like the way your code is written) code but it's not crucial in Python (but others pointed you to the writings of e.g. David Mertz where he makes heavy use of lambda and friends in code; there you have an example that it can be extremly useful). Karl -- Please do *not* send copies of replies to me. I read the list From abeidson at sbcglobal.net Fri Feb 6 12:33:10 2004 From: abeidson at sbcglobal.net (Andrew Eidson) Date: Fri Feb 6 12:51:29 2004 Subject: [Tutor] Parsing large files Message-ID: <1076088789.4878.2.camel@localhost.localdomain> I have a text file that is tab delimited.. it has 321 columns with over 1000 rows.. I need to parse this out to 2 text files with roughly half the columns and the same number of rows. Just looking on some guidance on the best way of doing this (been working on a GUI so much lately my brain is toast) Thanks Andy From rmkrauter at yahoo.com Fri Feb 6 13:20:13 2004 From: rmkrauter at yahoo.com (Rich Krauter) Date: Fri Feb 6 13:25:09 2004 Subject: [Tutor] printing answers In-Reply-To: <20040206162236.76470.qmail@web12402.mail.yahoo.com> References: <20040206162236.76470.qmail@web12402.mail.yahoo.com> Message-ID: <1076091613.4424.251.camel@vaio> Hi Christopher, > Hmmm...Now that I look at the program, I see you are > right! Thanks for the reply! The question now is how > do I fix it? Any hints? > > -Chris Did you see Karl's reply? I thought that was a really good suggestion. If Karl's reply is not what you want, you need to be a little more explicit about your requirements, and the type of output you expect. It's easiest if you express what output you want in python, not in words: i.e. you can say something like """ My input is [...]. My function is [code]. I want to use regular expressions, and I want the output to be a list of tuples that looks like this: [('oNe','One'),('TWo'),('thREE','three')]. """ You said your function is outputting the wrong thing, but you forgot to say explicitly, in python, what the right thing is. And you didn't explicitly say you need to use regexes. I'm not meaning to sound critical. I'm new to this too, and I often have the same problem - until I remember that python can express what I mean better than my verbal explanation what I want python to do. Rich From karl.fast at pobox.com Fri Feb 6 13:25:01 2004 From: karl.fast at pobox.com (Karl Fast) Date: Fri Feb 6 13:25:55 2004 Subject: [Tutor] Parsing large files In-Reply-To: <1076088789.4878.2.camel@localhost.localdomain>; from abeidson@sbcglobal.net on Fri, Feb 06, 2004 at 12:33:10PM -0500 References: <1076088789.4878.2.camel@localhost.localdomain> Message-ID: <20040206122501.F17448@signal.lights.com> > I have a text file that is tab delimited.. it has 321 columns with > over 1000 rows.. I need to parse this out to 2 text files with > roughly half You might want to try the CSV module that is a standard module as of Python 2.3. I have not used it, but it should do the trick for you. The default separator is a comma but you can easily make it a tab. http://www.python.org/doc/current/lib/module-csv.html --karl From rick at niof.net Fri Feb 6 13:46:19 2004 From: rick at niof.net (Rick Pasotto) Date: Fri Feb 6 13:43:56 2004 Subject: [Tutor] Parsing large files In-Reply-To: <1076088789.4878.2.camel@localhost.localdomain> References: <1076088789.4878.2.camel@localhost.localdomain> Message-ID: <20040206184619.GL3504@niof.net> On Fri, Feb 06, 2004 at 12:33:10PM -0500, Andrew Eidson wrote: > I have a text file that is tab delimited.. it has 321 columns with > over 1000 rows.. I need to parse this out to 2 text files with roughly > half the columns and the same number of rows. Just looking on some > guidance on the best way of doing this (been working on a GUI so much > lately my brain is toast) Why does it matter how many columns there are? Are you rearranging them or using a subset? If not just write the first 500 lines to one file and then the rest to another. The unix 'split' command will do this. Don't make things more complicated than necessary. -- "All progress is based upon the universal innate desire on the part of every organism to live beyond its income." -- Samuel Butler *KH* Rick Pasotto rick@niof.net http://www.niof.net From GGent at healthcare-automation.com Fri Feb 6 14:08:44 2004 From: GGent at healthcare-automation.com (Greg Gent) Date: Fri Feb 6 14:09:15 2004 Subject: [Tutor] Parsing large files Message-ID: <415DC4E8A851324985C1C100C4569A11C100EF@CORP_NT2> RTFQ. The OP actaully stated that he was using a subset of columns into each of the two resulting files. Each resulting file would have the same number of rows as the original, not of each other (which since it was stated MORE THAN 1000 rows...your suggestion of 500 wouldn't accomplish same number of rows in each file either). As already stated the csv module seems appropriate. BTW, The unix split command will not simplify this task. It may split the file into N 500 line pieces (if you tell it to use -l 500). However, that is not what was asked. > -----Original Message----- > From: Rick Pasotto [mailto:rick@niof.net] > Sent: Friday, February 06, 2004 1:46 PM > To: tutor@python.org > Subject: Re: [Tutor] Parsing large files > > > On Fri, Feb 06, 2004 at 12:33:10PM -0500, Andrew Eidson wrote: > > I have a text file that is tab delimited.. it has 321 columns with > > over 1000 rows.. I need to parse this out to 2 text files > with roughly > > half the columns and the same number of rows. Just looking on some > > guidance on the best way of doing this (been working on a > GUI so much > > lately my brain is toast) > > Why does it matter how many columns there are? Are you > rearranging them > or using a subset? If not just write the first 500 lines to > one file and > then the rest to another. The unix 'split' command will do this. > > Don't make things more complicated than necessary. > > -- > "All progress is based upon the universal innate desire > on the part of every organism to live beyond its income." > -- Samuel Butler *KH* > Rick Pasotto rick@niof.net http://www.niof.net > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From marilyn at deliberate.com Fri Feb 6 15:38:30 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Fri Feb 6 15:39:03 2004 Subject: [Tutor] fancy list things In-Reply-To: <Pine.LNX.4.44.0402051653400.20604-100000@hkn.eecs.berkeley.edu> Message-ID: <Pine.LNX.4.44.0402052329090.11161-100000@Kuna> > > Hi Marilyn, > > > lambda's can also be useful whenever we want to create simpler versions of > functions that already have some parameters filled in. Here is a simple > example: > > ### > >>> def add(x, y): > ... return x + y > ... > >>> add1 = lambda y: add(1, y) > >>> > >>> > >>> add1(42) > 43 > ### Nice. > > > Another way of saying this is: > > ### > def add1(y): > return add(1, y) > ### > > The 'def' statement in Python is sort of a combination of > lambda-function-making plus name-binding. > > > > > I'm teaching python for the first time and want to be as solid as > > possible on this stuff. > > Hmmm... you may want to avoid talking about lambda, then. Concentrate on > what you're comfortable talking about. I'd recommend focusing on the Oh. I don't mind exposing my ignorance (obviously). It's a good teaching/learning technique. And it encourages students to expose their ignorance. > things that people will usually do with Python, so show how to construct > functions with 'def'. But if people don't actually use a particular feature, then I don't want to waste time with it. That's what I'm finding out. The Deitel book barely mentions lambda on page 1249!: "Python2.2's nested-scope behavior also makes it easier for programmers to write lambda expressions. A lambda expression-- when evaluated-- produces a function, in much the same way (some named function) produces a function. Many programmers use lambda expresson to define callbacks for GUI applications. In this text we have chosen to focus on object-orented programming in Python, rather than on functional or procedural programming." And that is all it says. So I'm asking here. > > The advantage that 'lambda' has over 'def' is that it doesn't force us to > bind the function value with a name. But Python programmers usually want > to give good names our functions to express human intent, anyway. > > > And function values are just function values. *grin* def'ed functions can > also be passed around just as easily as values from lambdas: > > ### > >>> def compose(f, g): > ... def composed_function(x): > ... return f(g(x)) > ... return composed_function > ... > >>> def square(x): > ... return x * x > ... > >>> def sqrt(x): > ... return x ** (0.5) > ... > >>> quad_power = compose(square, square) > >>> quad_power(17) > 83521 > >>> identity = compose(square, sqrt) > >>> identity(17) > 17.0 > ### > > > So there's no need to concentrate on the foreignness of the word 'lambda': > lambda just creates function values. But we can get the value of anything > by just naming it: > > ### > >>> x = 42 > >>> x > 42 > >>> def square(x): return x * x > ... > >>> square > <function square at 0x8157bfc> > ### > > > > Just for reference: the same thing that we did with 'def' here can be done > exclusively with lambda's. > > ### > >>> compose = lambda f, g: lambda x: f(g(x)) > >>> square = lambda x: x*x > >>> sqrt = lambda x: x**(0.5) > >>> quad_power = compose(square, square) > >>> quad_power(17) > 83521 > >>> quarter_power = compose(sqrt, sqrt) ## with cheese? > >>> quarter_power(16) > 2.0 > ### > > The advantage of lambda here is that it's concise, so this kind of > function-fiddling code ends up being really short to write. To a eye > trained in functional languages, it looks neater. But there's little that > we're doing here that we couldn't do already with 'def'. > > > Hope this helps! > It's a cool example. Some of my students are perl programmers. They might want to know that lambda exists, anyway. And some here have shown examples where it makes code easier to read. Anyway, I certainly appreciate all the generous help here. Marilyn Davis > -- From abeidson at sbcglobal.net Fri Feb 6 15:39:58 2004 From: abeidson at sbcglobal.net (Andrew Eidson) Date: Fri Feb 6 15:40:04 2004 Subject: [Tutor] Parsing large files In-Reply-To: <415DC4E8A851324985C1C100C4569A11C100EF@CORP_NT2> Message-ID: <20040206203958.98905.qmail@web80106.mail.yahoo.com> Ok.. I have the file being read by csvreader.. but it seams that csvwriter can only write rows.. the file does not have field names so I am having difficulty copying specific columns to the seperate files. any suggestions on place for documenation.. everything I am finding has no information on writing individual columns. Greg Gent <GGent@healthcare-automation.com> wrote:RTFQ. The OP actaully stated that he was using a subset of columns into each of the two resulting files. Each resulting file would have the same number of rows as the original, not of each other (which since it was stated MORE THAN 1000 rows...your suggestion of 500 wouldn't accomplish same number of rows in each file either). As already stated the csv module seems appropriate. BTW, The unix split command will not simplify this task. It may split the file into N 500 line pieces (if you tell it to use -l 500). However, that is not what was asked. > -----Original Message----- > From: Rick Pasotto [mailto:rick@niof.net] > Sent: Friday, February 06, 2004 1:46 PM > To: tutor@python.org > Subject: Re: [Tutor] Parsing large files > > > On Fri, Feb 06, 2004 at 12:33:10PM -0500, Andrew Eidson wrote: > > I have a text file that is tab delimited.. it has 321 columns with > > over 1000 rows.. I need to parse this out to 2 text files > with roughly > > half the columns and the same number of rows. Just looking on some > > guidance on the best way of doing this (been working on a > GUI so much > > lately my brain is toast) > > Why does it matter how many columns there are? Are you > rearranging them > or using a subset? If not just write the first 500 lines to > one file and > then the rest to another. The unix 'split' command will do this. > > Don't make things more complicated than necessary. > > -- > "All progress is based upon the universal innate desire > on the part of every organism to live beyond its income." > -- Samuel Butler *KH* > Rick Pasotto rick@niof.net http://www.niof.net > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > _______________________________________________ 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/20040206/c976d310/attachment-0001.html From abeidson at sbcglobal.net Fri Feb 6 15:40:00 2004 From: abeidson at sbcglobal.net (Andrew Eidson) Date: Fri Feb 6 15:40:11 2004 Subject: [Tutor] Parsing large files In-Reply-To: <415DC4E8A851324985C1C100C4569A11C100EF@CORP_NT2> Message-ID: <20040206204000.54457.qmail@web80109.mail.yahoo.com> Ok.. I have the file being read by csvreader.. but it seams that csvwriter can only write rows.. the file does not have field names so I am having difficulty copying specific columns to the seperate files. any suggestions on place for documenation.. everything I am finding has no information on writing individual columns. Greg Gent <GGent@healthcare-automation.com> wrote:RTFQ. The OP actaully stated that he was using a subset of columns into each of the two resulting files. Each resulting file would have the same number of rows as the original, not of each other (which since it was stated MORE THAN 1000 rows...your suggestion of 500 wouldn't accomplish same number of rows in each file either). As already stated the csv module seems appropriate. BTW, The unix split command will not simplify this task. It may split the file into N 500 line pieces (if you tell it to use -l 500). However, that is not what was asked. > -----Original Message----- > From: Rick Pasotto [mailto:rick@niof.net] > Sent: Friday, February 06, 2004 1:46 PM > To: tutor@python.org > Subject: Re: [Tutor] Parsing large files > > > On Fri, Feb 06, 2004 at 12:33:10PM -0500, Andrew Eidson wrote: > > I have a text file that is tab delimited.. it has 321 columns with > > over 1000 rows.. I need to parse this out to 2 text files > with roughly > > half the columns and the same number of rows. Just looking on some > > guidance on the best way of doing this (been working on a > GUI so much > > lately my brain is toast) > > Why does it matter how many columns there are? Are you > rearranging them > or using a subset? If not just write the first 500 lines to > one file and > then the rest to another. The unix 'split' command will do this. > > Don't make things more complicated than necessary. > > -- > "All progress is based upon the universal innate desire > on the part of every organism to live beyond its income." > -- Samuel Butler *KH* > Rick Pasotto rick@niof.net http://www.niof.net > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > _______________________________________________ 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/20040206/08d8aa69/attachment.html From marilyn at deliberate.com Fri Feb 6 15:45:40 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Fri Feb 6 15:45:59 2004 Subject: [Tutor] scope of a global dictionary? Message-ID: <Pine.LNX.4.44.0402052342450.11161-100000@Kuna> Making materials for this class exposes my ignorance to myself. Like they say, you never know a subject until you teach it. More ignorance exposed: My understanding is that a global variable can be accessed, but not altered in a function's code block, unless the global declaration is used: x = 3 def f(): print x <- is ok def g(): x += 1 <- not ok def h(): global x x *= 2 <- ok again But I wrote this little dictionary example and it doesn't need the global declaration to add new entries to the dictionary. I can't explain this. Can anyone help me? #! /usr/bin/python2.2 ''' A dictionary application, using a dictionary.''' dict = {'yield':'return, but start here with next next() call', 'pass':'do nothing'} def add_some(): while 1: word = raw_input('Word: ') if word == '': return meaning = raw_input('Meaning: ') dict[word.lower()] = meaning if __name__ == '__main__': add_some() words = dict.keys() words.sort() for word in words: print word, ':', dict[word] ################################################## # OUTPUT: # bash-2.05a$ ./scoped.py # Word: break # Meaning: jump out of loop and don't do an else # Word: # break : jump out of loop and don't do an else # pass : do nothing # yield : return, but start here with next next() call # bash-2.05a$ Thank you some more! Marilyn From alan.gauld at blueyonder.co.uk Fri Feb 6 16:30:36 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Feb 6 16:31:59 2004 Subject: [Tutor] fancy list things References: <Pine.LNX.4.44.0402051642490.11161-100000@Kuna> Message-ID: <005401c3ecf8$7578ee50$6401a8c0@xp> > > In Python lambda can be used to build simple (very simple sadly) > > anonymous expressions (no statements) which can get used at places where > > you think it's not worth writing a function with a name. > > Is it only useful in map() and filter() and reduce()? No. > And other places where you want to hand a little function to a > function? Yes. > comp() for example. Yes > Is there another class of examples? GUI programming where you want a widget to do something simple - like call another method with a predetermined set of values, eg: class MyGUI: def aFancyOne(self,x,y,z) #.... def buildGUI(self) # define lots of other widgets here self.doIt = Button(parent, text="Doit", command=lambda : self.aFancyOne(23,42,"DoIt called")) self.doAnother = Button(parent, ext = "Another", command = lambda : self.aFancyOne(1000,-3,"Help!")) So we see a method taking two parameters being called from the command functions of two separate widgets with two different sets of values. We could have defined two small functions and passed them instead but it gets messy: def DoItFunc(self): return self.aFancyOne(23,42,"DoIt called") def AnotherFunc(self): return self.aFancyOne(1000,-3,"Help!") then define the widgets like this: self.doIt = Button(parent, text="Doit", command=DoItFunc) self.doAnother = Button(parent, ext = "Another", command = AnotherFunc) lambda just saves a little typing and keeps the namespace from getting cluttered. It also meands the hard coding is kept at the point of use rather than requiring maintenance to be spread over two parts of the program... HTH, Alan G. From alan.gauld at blueyonder.co.uk Fri Feb 6 16:59:09 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Feb 6 17:00:30 2004 Subject: [Tutor] fancy list things References: <Pine.LNX.4.44.0402052329090.11161-100000@Kuna> Message-ID: <008a01c3ecfc$7278d0e0$6401a8c0@xp> > > Hmmm... you may want to avoid talking about lambda, then. Concentrate on > > what you're comfortable talking about. I'd recommend focusing on the > > Oh. I don't mind exposing my ignorance (obviously). It's a good > teaching/learning technique. And it encourages students to expose > their ignorance. It depends a bit on what your students are. If they are youngsters then I'd probably avoid lambda. But if they are adults with a smattering of math background then teaching lambda early is a valid thing to do because it will teach them a fundamental concept that is very important in programming - namely that executable bits of code (in Python's case restricted to expressions!) can be passed around like any other kind of programming object, and the proper name for such a chunk of code is a lambda. It depends how much you want to teach the theory of programming versus how to program to produce a working solution. If you understand the concepts of lambda then it helps you build better structured programs in some tricky situations. But 95% of the time you can live quite happily without lambda - and in Python its never needed, just nice to have as a shortcut. > "Python2.2's nested-scope behavior also makes it easier for > programmers to write lambda expressions. A lambda expression-- when > evaluated-- produces a function, in much the same way (some named > function) produces a function. Many programmers use lambda expresson > to define callbacks for GUI applications. In this text we have chosen > to focus on object-orented programming in Python, rather than on > functional or procedural programming." > > And that is all it says. So I'm asking here. If you know what they are talking about its a perfectly good explanation. But like so much of the Dietel books they only make sense after you understand them. Which rather defeats the object of the exercise! I often find thatchapters which I thought were hard to understand, once I've found out how to do it - usually from another book, when I go back to Dietel its obvious what they meant. > It's a cool example. Some of my students are perl programmers. Perl has its own equivalent to lambda (but I can't recall the arcane syntax - its Perl it must be arcane :-) so they may well grok lambda easily. A final plug, my functional programming topic covers lambdas as well as map(), filter(), reduce() and list comprehensions. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From GGent at healthcare-automation.com Fri Feb 6 17:00:34 2004 From: GGent at healthcare-automation.com (Greg Gent) Date: Fri Feb 6 17:01:07 2004 Subject: [Tutor] Parsing large files Message-ID: <415DC4E8A851324985C1C100C4569A11C100F0@CORP_NT2> Working from an example in the python-lists archives: Here's my simple csv file: ID,NAME,G1,G2,G3,SERIES 243,Darren,159,183,171,513 196,Greg,136,156,183,475 198,Chris D,153,168,151,472 35,Mike,210,187,197,594 200,Chris J,232,180,168,580 Here's my py file: #cvsread.py import csv dicts = [] inputFile = open("test.csv", "rb") parser = csv.reader(inputFile) firstRec = True for fields in parser: if firstRec: fieldNames = fields firstRec = False else: dicts.append({}) for i,f in enumerate(fields): dicts[-1][fieldNames[i]] = f print "Send this to file #1" for i,row in enumerate(dicts): print row["ID"], row["NAME"], row["SERIES"] print "Send this to file #2" for i,row in enumerate(dicts): print row["ID"], row["NAME"], row["G1"], row["G2"], row["G3"] #EOF This will display: >>> Send this to file #1 243 Darren 513 196 Greg 475 198 Chris D 472 35 Mike 594 200 Chris J 580 Send this to file #2 243 Darren 159 183 171 196 Greg 136 156 183 198 Chris D 153 168 151 35 Mike 210 187 197 200 Chris J 232 180 168 >>> This should get you pointed in the right direction... HTH, Greg -----Original Message----- From: Andrew Eidson [mailto:abeidson@sbcglobal.net] Sent: Friday, February 06, 2004 3:40 PM To: tutor@python.org Subject: RE: [Tutor] Parsing large files Ok.. I have the file being read by csvreader.. but it seams that csvwriter can only write rows.. the file does not have field names so I am having difficulty copying specific columns to the seperate files. any suggestions on place for documenation.. everything I am finding has no information on writing individual columns. Greg Gent <GGent@healthcare-automation.com> wrote: RTFQ. The OP actaully stated that he was using a subset of columns into each of the two resulting files. Each resulting file would have the same number of rows as the original, not of each other (which since it was stated MORE THAN 1000 rows...your suggestion of 500 wouldn't accomplish same number of rows in each file either). As already stated the csv module seems appropriate. BTW, The unix split command will not simplify this task. It may split the file into N 500 line pieces (if you tell it to use -l 500). However, that is not what was asked. > -----Original Message----- > From: Rick Pasotto [mailto:rick@niof.net] > Sent: Friday, February 06, 2004 1:46 PM > To: tutor@python.org > Subject: Re: [Tutor] Parsing large files > > > On Fri, Feb 06, 2004 at 12:33:10PM -0500, Andrew Eidson wrote: > > I have a text file that is tab delimited.. it has 321 columns with > > over 1000 rows.. I need to parse this out to 2 text files > with roughly > > half the columns and the same number of rows. Just looking on some > > guidance on the best way of doing this (been working on a > GUI so much > > lately my brain is toast) > > Why does it matter how many columns there are? Are you > rearranging them > or using a subset? If not just write the first 500 lines to > one file and > then the rest to another. The unix 'split' command will do this. > > Don't make things more complicated than necessary. > > -- > "All progress is based upon the universal innate desire > on the part of every organism to live beyond its income." > -- Samuel Butler *KH* > Rick Pasotto rick@niof.net http://www.niof.net > > _______________________________________________ > 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 marilyn at deliberate.com Fri Feb 6 16:49:43 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Fri Feb 6 17:05:59 2004 Subject: [Tutor] fancy list things In-Reply-To: <005401c3ecf8$7578ee50$6401a8c0@xp> Message-ID: <Pine.LNX.4.44.0402061348100.11161-100000@Kuna> YES! That's a great example! I feel much better about it now. Thank you again. Marilyn On Fri, 6 Feb 2004, Alan Gauld wrote: > > > In Python lambda can be used to build simple (very simple sadly) > > > anonymous expressions (no statements) which can get used at places > where > > > you think it's not worth writing a function with a name. > > > > Is it only useful in map() and filter() and reduce()? > > No. > > > And other places where you want to hand a little function to a > > function? > > Yes. > > > comp() for example. > > Yes > > > Is there another class of examples? > > GUI programming where you want a widget to do something simple > - like call another method with a predetermined set of values, eg: > > class MyGUI: > def aFancyOne(self,x,y,z) > #.... > def buildGUI(self) > # define lots of other widgets here > self.doIt = Button(parent, text="Doit", > command=lambda : self.aFancyOne(23,42,"DoIt > called")) > self.doAnother = Button(parent, ext = "Another", > command = lambda : > self.aFancyOne(1000,-3,"Help!")) > > > So we see a method taking two parameters being called from the > command functions of two separate widgets with two different > sets of values. > > We could have defined two small functions and passed them instead > but it gets messy: > > def DoItFunc(self): return self.aFancyOne(23,42,"DoIt called") > def AnotherFunc(self): return self.aFancyOne(1000,-3,"Help!") > > then define the widgets like this: > > > self.doIt = Button(parent, text="Doit", command=DoItFunc) > self.doAnother = Button(parent, ext = "Another", command = > AnotherFunc) > > lambda just saves a little typing and keeps the namespace from > getting cluttered. It also meands the hard coding is kept at the > point of use rather than requiring maintenance to be spread over > two parts of the program... > > HTH, > > Alan G. > > -- From marilyn at deliberate.com Fri Feb 6 17:39:37 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Fri Feb 6 17:39:47 2004 Subject: [Tutor] fancy list things In-Reply-To: <008a01c3ecfc$7278d0e0$6401a8c0@xp> Message-ID: <Pine.LNX.4.44.0402061425570.11161-100000@Kuna> On Fri, 6 Feb 2004, Alan Gauld wrote: > > > Hmmm... you may want to avoid talking about lambda, then. > Concentrate on > > > what you're comfortable talking about. I'd recommend focusing on > the > > > > Oh. I don't mind exposing my ignorance (obviously). It's a good > > teaching/learning technique. And it encourages students to expose > > their ignorance. > > It depends a bit on what your students are. If they are youngsters > then I'd probably avoid lambda. > > But if they are adults with a smattering of math background > then teaching lambda early is a valid thing to do because it > will teach them a fundamental concept that is very important > in programming - namely that executable bits of code (in > Python's case restricted to expressions!) can be passed around > like any other kind of programming object, and the proper > name for such a chunk of code is a lambda. My students are adult programmers, working in the Silicon Valley. I have to try to make the class efficient, useful, and fun. Many are sent to us by their employers. So far, they seem very happy and engaged with the class. Let's hope it lasts. In all my jillion years of teaching C, I never had all the students show up on time for the first class. But all 19 people made it to the first python class on time. What does this mean? A few were a little late to the second class but all were present. After the first class, I start on time. > Perl has its own equivalent to lambda (but I can't recall the > arcane syntax - its Perl it must be arcane :-) so they may well > grok lambda easily. YES. I learned Perl because I wanted something new to teach and it was so popular at the time. When I started learning the OO 'features' I dropped it like a hot rock and decided I could never teach something I disliked so much. Someone suggested I look at python, and like everyone else, I flipped. > > A final plug, my functional programming topic covers lambdas > as well as map(), filter(), reduce() and list comprehensions. > > Alan G > Author of the Learn to Program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld Great! I'll point my students to this. What a huge help this list is! Something about this language is like a generator of sense in a confused world. I'm almost a fanatic, and I'm not the fanatical type. Marilyn > > -- From sigurd at 12move.de Fri Feb 6 17:40:07 2004 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Fri Feb 6 17:54:58 2004 Subject: [Tutor] scope of a global dictionary? In-Reply-To: <Pine.LNX.4.44.0402052342450.11161-100000@Kuna> (Marilyn Davis's message of "Fri, 6 Feb 2004 12:45:40 -0800 (PST)") References: <Pine.LNX.4.44.0402052342450.11161-100000@Kuna> Message-ID: <m3r7x7j1gr.fsf@hamster.pflaesterer.de> On 6 Feb 2004, Marilyn Davis <- marilyn@deliberate.com wrote: > My understanding is that a global variable can be accessed, but not > altered in a function's code block, unless the global declaration is > used: That's not entirely true. > x = 3 > def f(): > print x <- is ok No binding of a name > def g(): > x += 1 <- not ok Here x gets bound to x+1. > def h(): > global x > x *= 2 <- ok again Here you declared x global. That short circuits the name resolving. > But I wrote this little dictionary example and it doesn't need the > global declaration to add new entries to the dictionary. Yes and no :-) > dict[word.lower()] = meaning Here again; you don't bind the name dict to a new value. A small example to make it clearer: >>> lst = [1] >>> def f (): return lst ... >>> def g(): ... lst.append(1) ... return f() ... >>> def h(): lst = lst + lst ... >>> f() [1] >>> g() [1, 1] >>> h() Traceback (most recent call last): File "<stdin>", line 1, in ? File "<stdin>", line 1, in h UnboundLocalError: local variable 'lst' referenced before assignment >>> So g() caused no problems but could change the value of lst. What is the difference to h()? In h() we made an assignment operation and assignment statements *bind* names. Now `lst' was the `lst' in the local function scope and no longer an arbitrary name which could be searched in the surrounding environment (or __builtin__). That whole issue is not trivial; if you want to know more about it read e.g. Pep 227 (which describes the lexical (statical) scoping rules and explains also these subtilities; furthermore you could read in the Python reference about `Naming and Binding' (in the section `Execution model'). On example from the Pep which shows a problem which can arise ,----[ pep 227 ] | An example from Tim Peters demonstrates the potential pitfalls of | nested scopes in the absence of declarations: | | i = 6 | def f(x): | def g(): | print i | # ... | # skip to the next page | # ... | for i in x: # ah, i *is* local to f, so this is what g sees | pass | g() | | The call to g() will refer to the variable i bound in f() by the for | loop. If g() is called before the loop is executed, a NameError will | be raised. `---- Since `i' gets bound in the function declaration (the for loop bounds also) a similar problem like yours happens. HTH Karl -- Please do *not* send copies of replies to me. I read the list From missive at hotmail.com Fri Feb 6 18:01:26 2004 From: missive at hotmail.com (Lee Harr) Date: Fri Feb 6 18:01:32 2004 Subject: [Tutor] Re: Tkinter 101 Message-ID: <BAY2-F136FNuYf2b4GM0002386f@hotmail.com> >I don't really know very much about Python or computer programming, >but I didn't think that was a good enough reason not to give it a try. > >Anyway, I've written this program. >Its basicially a simulation of Conway's "game of life" > >It seems to work fine and all, but I'm sure there are better ways of doing >what I've done than the way I did it, so I'm posting it to this list in the >hope of recieving some constructive criticism. > > That looks nice to me. I'd like to see a menu option for next generation (like pressing enter) and maybe one for "run" (ie, keep calling next generation automatically.) _________________________________________________________________ MSN 8 with e-mail virus protection service: 2 months FREE* http://join.msn.com/?page=features/virus From abeidson at sbcglobal.net Fri Feb 6 18:56:06 2004 From: abeidson at sbcglobal.net (Andrew Eidson) Date: Fri Feb 6 19:00:18 2004 Subject: [Tutor] Parsing large files In-Reply-To: <20040206204000.54457.qmail@web80109.mail.yahoo.com> References: <20040206204000.54457.qmail@web80109.mail.yahoo.com> Message-ID: <1076111766.5046.1.camel@localhost.localdomain> well thanks everyone.. I found a simple way of doing this through Linux.. cut -f1-86 infile > outfile I am still playing with the CSV import but still have not found decent documentation to help me with it. On Fri, 2004-02-06 at 15:40, Andrew Eidson wrote: > Ok.. I have the file being read by csvreader.. but it seams that > csvwriter can only write rows.. the file does not have field names so > I am having difficulty copying specific columns to the seperate files. > any suggestions on place for documenation.. everything I am finding > has no information on writing individual columns. > > Greg Gent <GGent@healthcare-automation.com> wrote: > RTFQ. > > The OP actaully stated that he was using a subset of columns > into each of > the two resulting files. Each resulting file would have the > same number of > rows as the original, not of each other (which since it was > stated MORE THAN > 1000 rows...your suggestion of 500 wouldn't accomplish same > number of rows > in each file either). > > As already stated the csv module seems appropriate. > > BTW, > > The unix split command will not simplify this task. It may > split the file > into N 500 line pieces (if you tell it to use -l 500). > However, that is not > what was asked. > > > > -----Original Message----- > > From: Rick Pasotto [mailto:rick@niof.net] > > Sent: Friday, February 06, 2004 1:46 PM > > To: tutor@python.org > > Subject: Re: [Tutor] Parsing large files > > > > > > On Fri, Feb 06, 2004 at 12:33:10PM -0500, Andrew Eidson > wrote: > > > I have a text file that is tab delimited.. it has 321 > columns with > > > over 1000 rows.. I need to parse this out to 2 text files > > with roughly > > > half the columns and the same number of rows. Just looking > on some > > > guidance on the best way of doing this (been working on a > > GUI so much > > > lately my brain is toast) > > > > Why does it matter how many columns there are? Are you > > rearranging them > > or using a subset? If not just write the first 500 lines to > > one file and > > then the rest to another. The unix 'split' command will do > this. > > > > Don't make things more complicated than necessary. > > > > -- > > "All progress is based upon the universal innate desire > > on the part of every organism to live beyond its income." > > -- Samuel Butler *KH* > > Rick Pasotto rick@niof.net http://www.niof.net > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > > ______________________________________________________________________ > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From marilyn at deliberate.com Fri Feb 6 19:21:10 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Fri Feb 6 19:21:35 2004 Subject: [Tutor] scope of a global dictionary? In-Reply-To: <m3r7x7j1gr.fsf@hamster.pflaesterer.de> Message-ID: <Pine.LNX.4.44.0402061619090.11161-100000@Kuna> On Fri, 6 Feb 2004, Karl Pfl?sterer wrote: > On 6 Feb 2004, Marilyn Davis <- marilyn@deliberate.com wrote: > > > My understanding is that a global variable can be accessed, but not > > altered in a function's code block, unless the global declaration is > > used: > > That's not entirely true. > > > x = 3 > > def f(): > > print x <- is ok > > No binding of a name > > > def g(): > > x += 1 <- not ok > > Here x gets bound to x+1. > > > def h(): > > global x > > x *= 2 <- ok again > > Here you declared x global. That short circuits the name resolving. > > > > But I wrote this little dictionary example and it doesn't need the > > global declaration to add new entries to the dictionary. > > Yes and no :-) > > > dict[word.lower()] = meaning > > Here again; you don't bind the name dict to a new value. > > > A small example to make it clearer: > >>> lst = [1] > >>> def f (): return lst > ... > >>> def g(): > ... lst.append(1) > ... return f() > ... > >>> def h(): lst = lst + lst > ... > >>> f() > [1] > >>> g() > [1, 1] > >>> h() > Traceback (most recent call last): > File "<stdin>", line 1, in ? > File "<stdin>", line 1, in h > UnboundLocalError: local variable 'lst' referenced before assignment > >>> > > > So g() caused no problems but could change the value of lst. What is > the difference to h()? In h() we made an assignment operation and > assignment statements *bind* names. Now `lst' was the `lst' in the > local function scope and no longer an arbitrary name which could be > searched in the surrounding environment (or __builtin__). > > That whole issue is not trivial; if you want to know more about it read No. Your example is clear and excellent. I get it now. > e.g. Pep 227 (which describes the lexical (statical) scoping rules and > explains also these subtilities; furthermore you could read in the > Python reference about `Naming and Binding' (in the section `Execution > model'). On example from the Pep which shows a problem which can arise > > ,----[ pep 227 ] > | An example from Tim Peters demonstrates the potential pitfalls of > | nested scopes in the absence of declarations: > | > | i = 6 > | def f(x): > | def g(): > | print i > | # ... > | # skip to the next page > | # ... > | for i in x: # ah, i *is* local to f, so this is what g sees > | pass > | g() > | > | The call to g() will refer to the variable i bound in f() by the for > | loop. If g() is called before the loop is executed, a NameError will > | be raised. > `---- > > Since `i' gets bound in the function declaration (the for loop bounds > also) a similar problem like yours happens. Woah. Interesting. > > HTH HAWL (Helps A Whole Lot!) Marilyn > > Karl > -- From sigurd at 12move.de Fri Feb 6 20:01:52 2004 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Fri Feb 6 20:02:40 2004 Subject: [Tutor] Parsing large files In-Reply-To: <1076111766.5046.1.camel@localhost.localdomain> (Andrew Eidson's message of "Fri, 06 Feb 2004 18:56:06 -0500") References: <20040206204000.54457.qmail@web80109.mail.yahoo.com> <1076111766.5046.1.camel@localhost.localdomain> Message-ID: <m37jyziue9.fsf@hamster.pflaesterer.de> On 7 Feb 2004, Andrew Eidson <- abeidson@sbcglobal.net wrote: > well thanks everyone.. I found a simple way of doing this through > Linux.. > cut -f1-86 infile > outfile > I am still playing with the CSV import but still have not found decent > documentation to help me with it. Maybe I overlooking something but you wrote the fields are tab separated. Why don't you simply write: def split_cols (infile, cols, outfile1, outfile2): inf = file(infile) of1 = file(outfile1, "w") of2 = file(outfile2, "w") for line in inf: line = line.split('\t') print >> of1, '\t'.join(line[:cols]) of2.write('\t'.join(line[cols:])) inf.close() of1.close() of2.close() That will write the columns to the two files. If you like generators you could also wrote: def split_cols (infile, cols, outfile1, outfile2): def splitter (fil, cols): for line in fil: line = line.split('\t') yield ('\t'.join(line[:cols]) + '\n', '\t'.join(line[cols:])) inf = file(infile) of1 = file(outfile1, "w") of2 = file(outfile2, "w") for left, right in splitter(inf, cols): of1.write(left) of2.write(right) inf.close() of1.close() of2.close() Karl -- Please do *not* send copies of replies to me. I read the list From bgailer at alum.rpi.edu Fri Feb 6 21:23:11 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri Feb 6 21:23:22 2004 Subject: {Spam?} Re: [Tutor] How to get variable name from its id() In-Reply-To: <ts8720h0biisn3uuaru18po0pihogtb41p@4ax.com> References: <E1Ap06l-000600-Ik@fuse1.fusemail.net> <ts8720h0biisn3uuaru18po0pihogtb41p@4ax.com> Message-ID: <6.0.0.22.0.20040206191521.040ae550@mail.mric.net> >Em Fri, 6 Feb 2004 02:07:57 -0500, "Isr Gish" <isrgish@fusemail.com> >atirou este peixe aos pinguins: > >Is it possible to get the variable name or its contents if we know its I'd. > > >Name = 'Isr Gish' >ID = id(Name) >Now use ID to either find the variable name (Name), or get the contents of >Name. > >If someone can point me where to find this info. It would be greatly >appreciated. After assigning some variables, run this code: for key, value in globals().items(): print key, value, id(value) Each line of output is one variable name, its contents, and its id. There is a lot of builtin stuff, but amongst it are the entries you created. Add a little search logic to compare each id to the desired one and you have your answer. Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.577 / Virus Database: 366 - Release Date: 2/3/2004 From bgailer at alum.rpi.edu Fri Feb 6 21:38:23 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri Feb 6 21:38:32 2004 Subject: {Spam?} [Tutor] Help with appropriate looping and logic In-Reply-To: <38383.206.53.226.235.1076086190.squirrel@www.thepenguin.or g> References: <38383.206.53.226.235.1076086190.squirrel@www.thepenguin.org> Message-ID: <6.0.0.22.0.20040206192518.03ff92b8@mail.mric.net> At 09:49 AM 2/6/2004, Vicki Stanfield wrote: >I have some code that I have written which should rightly be one section >of code, but which I have had to code in three separate sections to get it >to work right. I am hoping that someone on this list can help me get it >right. I have written some pseudo-code to post here. The problem is that >there are a few loops and several if/elif statements. For some reason I >have not been able to work it out in Python. I for one don't see what your problem is, and don't fully understand the pseudocode. So let's try this: first change IF to if. What does [AA] mean, Do you want to send left bracket, A, A, right bracket? If so you need a send function to do with an input string whatever send does. (What does it do?) Ditto receive. Repeat whole sequence 12 times. What sequence? All code above that line? All code? Codes in <> look like ASCII control codes, which are usually rendered in Python '\xnn' where nn is the hex value of the control code (<TAB> becomes '\x09'). If you want to use the <> syntax I'd create a dictionary to convert these codes to the hex equivalent. You use for loops to do things multiple times, or a string multipler e.g. ('[BB][BB]'*4) will expand to '[BB][BB][BB][BB][BB][BB][BB][BB]' >Here is the pseudo-code: > >send <STX> >IF 1: send [AA][AA] >IF 2: send [AB][AB] >IF 3: send [AC][AC] >send <TAB> >IF 1 or 2: send [BB][BB] 16 times >IF 3: send [BB][BB] once >send <TAB> >IF 1: send [CA][CA] >IF 2: send [CB][CB] >IF 3: send [CC][CC] >IF 1 or 2: send <ETX> > receive <ACK> >IF 3: SEND <EOT> > receive <ACK> >IF 1: Repeat whole sequence 12 times >IF 2: send <STX> > send [DA][DA] > send <TAB> > send [BB][BB] 4 more times > send <TAB> > send [EA][EA] > send <EOT> > receive <ACK> > receive <ACK> >IF 3: receive <ACK> >IF 1: send <STX> > send [FA][FA] > send <TAB> > send [BB][BB] 8 more times > send <TAB> > send [FB] > send <EOT> > receive <ACK> > receive <ACK> > >I would appreciate someone helping me map this out as one unit of code. What does "one unit/section of code" mean? Where do you see 3 units/sections? Will you take a stab at coding this in Python and let us see the results? The IF statements suggest that you are testing some variable. Should read if a == 3: etc. Does any of this help? Obviously we need more information. Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.577 / Virus Database: 366 - Release Date: 2/3/2004 From syn_ack at comcast.net Sat Feb 7 01:21:23 2004 From: syn_ack at comcast.net (Joshua Banks) Date: Sat Feb 7 01:25:51 2004 Subject: [Tutor] Simple Linux Admin1, New guy looking for some tips. Message-ID: <200402062221.26060.syn_ack@comcast.net> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hello, Sorry, I hope my long windedness doesn't scare you away from reading my thread. :) As I read, read, and re-read through allot of the python tutorials I'm finding some stuff is starting to sink in. Its only been a few days so I don't expect miricales. Putting Python to work is another story though. Heh. Heh. I have an idea of some of the simple linux admin things that I would like to do with Python. What I'm not finding is tutorials based on using python to do simple linux admin tasks. Maybe I shouldn't say "admin" I only use acouple of Gentoo linux machines on my local network. In an effort to best facilitate the way that "I learn" am asking for some help as well as any links that are geared towards using Python for some of the simple linux admin tasks with explanations of what the python code is doing from step A to Z when scripting those said tasks. Googling finds some stuff here and there but nothing with explanations or Python linux tutorial driven I guess. "As soon as I gain some more experience I plan on creating my own mini-Python linux tutorial for newbies like myself" In the mean time I would like to take some really small baby steps and put forth a few simple examples of the "admin" thingee's that I'm referring too and start learning. 1 example for now anyways. Example:........(And I know that this can be done very simply using other means besides Python) .......Everytime that Gentoo linux compiles a package there's a log file created of that said compilation for each package compiled. If a package breaks or fails I can reference that specific log and try and find out where it failed or broke or what caused the problem. These are also nice to have if an engineer would like to see them. These specific logs are stored in "/var/log/portage directory" This directory is going to become very big, fast. "ls -la in the /var/log directory shows portage with:" drwxrwsr-x 2 root portage 4872 Feb 5 08:16 portage root@fusion1 log # du -ah 7.1M ./portage Since these logs are "only occasionally" used for referencing I would like to compress all the log files in this directory when seen fit and have a subdirectory created in the "parent portage" directory to store compressed files. Kinda like a "Portage log Archive" I guess. So hopefully the following is a good starting baby step to learning some Python. :P Specifically, I would like to accomplish the following with a Python script. 1) Compress all files located in "/var/log/portage/" (not sure which compression utility is the best for this case) 2) Create a subdirectory located within the Parnet "portage" directory called "LogArchive", and place the compressed files from the "portage" directory into newly created subdirectory "LogArchive". #My Mental note: I would preferably like to compress all files together if possible instead of individually. Not sure how that is best done though. Maybe thats directory compression... Hmmmm.. never done that before. How do I do this with Python considering "#My Mental note:"? I will use this example as a building point instead of jumping into the wxPython stuff that my brother keeps trying to push on me.. I just don't want to learn the GUI stuff until I feel alot more comfortable with Python basic's. Concepts and Symantics. Thanks bunches. :D Joshua Banks -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (GNU/Linux) iD8DBQFAJIPjp9X7q/XgeyYRAsMjAJ9jnn5Jqa5R6CRnzEtxgx3CpnqyLwCgkABX kbrLIzF/5l+NokiHAyHOZ1I= =1cLE -----END PGP SIGNATURE----- From orbitz at ezabel.com Sat Feb 7 12:59:12 2004 From: orbitz at ezabel.com (orbitz@ezabel.com) Date: Sat Feb 7 13:00:29 2004 Subject: [Tutor] Simple Linux Admin1, New guy looking for some tips. In-Reply-To: <200402062221.26060.syn_ack@comcast.net> References: <200402062221.26060.syn_ack@comcast.net> Message-ID: <20040207125912.46295e4f.orbitz@ezabel.com> I doubt you will find a tutorial so specific, but you don't even need one. When createding anything there are a series of steps you follow to solve the problem. First you should define as specificially as you can what the problem is. Then look at what tools you will need to solve this problem. Read up on how to use the tols, and finally put them all together. A specific example of how to solve specific tasks wouldn't really do you much good in the long run, monkey see monkey do. If you learn to think for yourself you will be much better off. On Fri, 6 Feb 2004 22:21:23 -0800 Joshua Banks <syn_ack@comcast.net> wrote: > WARNING: Unsanitized content follows. > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Hello, > > Sorry, I hope my long windedness doesn't scare you away from reading my > thread. :) > > As I read, read, and re-read through allot of the python tutorials I'm > finding some stuff is starting to sink in. Its only been a few days so > I don't expect miricales. Putting Python to work is another story > though. Heh. Heh. > > I have an idea of some of the simple linux admin things that I would > like to do with Python. What I'm not finding is tutorials based on > using python to do simple linux admin tasks. > > Maybe I shouldn't say "admin" I only use acouple of Gentoo linux > machines on my local network. In an effort to best facilitate the way > that "I learn" am asking for some help as well as any links that are > geared towards using Python for some of the simple linux admin tasks > with explanations of what the python code is doing from step A to Z > when scripting those said tasks. Googling finds some stuff here and > there but nothing with explanations or Python linux tutorial driven I > guess. > "As soon as I gain some more experience I plan on creating my own > mini-Python linux tutorial for newbies like myself" > > In the mean time I would like to take some really small baby steps and > put forth a few simple examples of the "admin" thingee's that I'm > referring too and start learning. 1 example for now anyways. > > > > > > Example:........(And I know that this can be done very simply using > other means besides Python) > > .......Everytime that Gentoo linux compiles a package there's a log file > created of that said compilation for each package compiled. If a > package breaks or fails I can reference that specific log and try and > find out where it failed or broke or what caused the problem. These are > also nice to have if an engineer would like to see them. These specific > logs are stored in "/var/log/portage directory" > > This directory is going to become very big, fast. > > "ls -la in the /var/log directory shows portage with:" > drwxrwsr-x 2 root portage 4872 Feb 5 08:16 portage > > root@fusion1 log # du -ah > 7.1M ./portage > > Since these logs are "only occasionally" used for referencing I would > like to compress all the log files in this directory when seen fit and > have a subdirectory created in the "parent portage" directory to store > compressed files. Kinda like a "Portage log Archive" I guess. > > > > > > So hopefully the following is a good starting baby step to learning some > Python. :P > > Specifically, I would like to accomplish the following with a Python > script. > > 1) Compress all files located in "/var/log/portage/" (not sure which > compression utility is the best for this case) > > 2) Create a subdirectory located within the Parnet "portage" directory > called "LogArchive", and place the compressed files from the "portage" > directory into newly created subdirectory "LogArchive". > > #My Mental note: I would preferably like to compress all files together > if possible instead of individually. Not sure how that is best done > though. Maybe thats directory compression... Hmmmm.. never done that > before. > > How do I do this with Python considering "#My Mental note:"? I will use > this example as a building point instead of jumping into the wxPython > stuff that my brother keeps trying to push on me.. I just don't want to > learn the GUI stuff until I feel alot more comfortable with Python > basic's. Concepts and Symantics. > > Thanks bunches. :D > > Joshua Banks > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.2.3 (GNU/Linux) > > iD8DBQFAJIPjp9X7q/XgeyYRAsMjAJ9jnn5Jqa5R6CRnzEtxgx3CpnqyLwCgkABX > kbrLIzF/5l+NokiHAyHOZ1I= > =1cLE > -----END PGP SIGNATURE----- > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From shaleh at speakeasy.net Sat Feb 7 13:24:09 2004 From: shaleh at speakeasy.net (Sean 'Shaleh' Perry) Date: Sat Feb 7 13:24:25 2004 Subject: [Tutor] Simple Linux Admin1, New guy looking for some tips. In-Reply-To: <200402062221.26060.syn_ack@comcast.net> References: <200402062221.26060.syn_ack@comcast.net> Message-ID: <200402071024.09208.shaleh@speakeasy.net> On Friday 06 February 2004 22:21, Joshua Banks wrote: > Example:........(And I know that this can be done very simply using > other means besides Python) > like maybe logrotate (-: But hey, learning by reimplementing *CAN* be useful. > > Specifically, I would like to accomplish the following with a Python > script. > > 1) Compress all files located in "/var/log/portage/" (not sure which > compression utility is the best for this case) > standard gzip is the answer here. bzip2 might give you slightly higher compression but it also uses more cpu and for this case is not really worth it. > 2) Create a subdirectory located within the Parnet "portage" directory > called "LogArchive", and place the compressed files from the "portage" > directory into newly created subdirectory "LogArchive". > > #My Mental note: I would preferably like to compress all files together > if possible instead of individually. Not sure how that is best done > though. Maybe thats directory compression... Hmmmm.. never done that > before. > > How do I do this with Python considering "#My Mental note:"? I will use > this example as a building point instead of jumping into the wxPython > stuff that my brother keeps trying to push on me.. I just don't want to > learn the GUI stuff until I feel alot more comfortable with Python > basic's. Concepts and Symantics. > why put them in one archive? That means if you ever do need the file you have to go hunting for it. Ok, let's say you do want to store them in one archive. The standard tool to use is called 'tar' which stands for 'tape archive'. But most people use it to put lots of files into one file for easier network moving. So as the other commented on this thread says, first look at the problem and try to write it out completely in just English. "I want a script which ....". Then try to write an outline for the code, again in English. Just like you were going to write an essay. For this task, you probably want to look at the sys and os modules in Python. From alan.gauld at blueyonder.co.uk Sat Feb 7 16:15:00 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Feb 7 16:15:01 2004 Subject: [Tutor] Simple Linux Admin1, New guy looking for some tips. References: <200402062221.26060.syn_ack@comcast.net> Message-ID: <011201c3edbf$72121530$6401a8c0@xp> > Example:........(And I know that this can be done very > simply using other means besides Python) As an exercise for learning Python its fine but a simple shell script will be much more effective for this type of thing IMHO. > ... >Since these logs are "only occasionally" used for referencing I would > like to compress all the log files in this directory when seen fit and > have a subdirectory created in the "parent portage" directory to store > compressed files. Kinda like a "Portage log Archive" I guess. This is usually done more easily using a tar file. In fact so comon is it that tar takes a flag to force compression of the resultant archive. So something like this will do it... #! /usr/sh # archive files and compress the result # add some input checking and a usage message here tar -gzf $1 $# echo "archived " $1 > So hopefully the following is a good starting baby step to > learning some Python. :P But as a learning exrise its good and there are lots of admin type tools to learn. Go study the os, path, glob, tar and gzip modules. > #My Mental note: I would preferably like to compress > all files together if possible instead of individually. Usually thats done by tar followed by gzip (or bzip2) or more simply by justvspecifying the z flag to tar... > How do I do this with Python considering "#My Mental note:"? > I will use this example as a building point instead of jumping > into the wxPython For sys admin things GUIS are mostly redundant. Generally you should write a script then put it in your cron file to run automatically. If you have a standard approach to errors you can even write a cron job to check for errors and send you an email to alert you to failed jobs... Alan G. From syn_ack at comcast.net Sat Feb 7 16:26:53 2004 From: syn_ack at comcast.net (Joshua Banks) Date: Sat Feb 7 16:31:19 2004 Subject: [Tutor] Short Version, New guy looking for some tips, Revisited. In-Reply-To: <200402062221.26060.syn_ack@comcast.net> References: <200402062221.26060.syn_ack@comcast.net> Message-ID: <200402071326.55109.syn_ack@comcast.net> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hello, Ok. Long story short. > Specifically, I would like to accomplish the following with a Python > script. > > 1) Compress all files located in "/var/log/portage directory > > 2) Have the Python script create a subdirectory located within the >Parnet "portage" directory called (example) "LogArchive", and place >the compressed files from the "portage" directory into newly created >subdirectory "LogArchive". > > #My Mental note: I would preferably like to compress all files > together if possible instead of individually. Not sure how that is > best done though. Maybe thats directory compression... Hmmmm.. never > done that before. (Again any example will suffice) What am I REALLY asking for????????? What I'm really asking for is for someone to provide a simple script that accomplishes the goal above. """But Why"""" To Study....really """"Important part of this email"""" The important part of my email isn't to have a Python script compress a directory for me..NO...NO....NO I can do that with Tar or Bzip from the command line very easy. The important part is to look at """"How"""" a Python script could be written so that I can """"reference"""" the steps taken and research the Python documentation at each step of the way through the script. Im sure there are probably more than a few ways to accomplish my compression goal with a Python script. All I'm looking for is an example that I can reference. Again, the important part isn't file or directory compression with Python...... but the """steps""" taken. An example of """"""How"""""". Am I asking for a simple example. Nothing more than that. Thanks, Joshua Banks -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (GNU/Linux) iD8DBQFAJVgdp9X7q/XgeyYRAtE1AJ9tTJ+yS3FQNqxwbzU3FIFFRXiK4ACfWq/c h8Hhu0o4lotB2mvqYr3JsPo= =mnYV -----END PGP SIGNATURE----- From syn_ack at comcast.net Sat Feb 7 16:36:59 2004 From: syn_ack at comcast.net (Joshua Banks) Date: Sat Feb 7 16:41:23 2004 Subject: [Tutor] Simple Linux Admin1, New guy looking for some tips. In-Reply-To: <011201c3edbf$72121530$6401a8c0@xp> References: <200402062221.26060.syn_ack@comcast.net> <011201c3edbf$72121530$6401a8c0@xp> Message-ID: <200402071337.01711.syn_ack@comcast.net> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Saturday 07 February 2004 01:15 pm, Alan Gauld wrote: > Go study the os, path, glob, tar and gzip modules. Thankyou. I just found some good stuff pertaining to compression in the "Python 2.3.3 lib.pdf" > For sys admin things GUIS are mostly redundant. Agree'ed. > Generally you should write a script then put it in your cron > file to run automatically. If you have a standard approach to > errors you can even write a cron job to check for errors and > send you an email to alert you to failed jobs... Thanks for the response. I understand how to do all of these things with linux. Really. I just wanted to see an example of how this could be done with Python specifically so I could reference the steps taken. Then end result of "compression" isn't really what I'm looking for. It's the individual steps taken that's important. Just something to reference. Thanks, Joshua Banks -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (GNU/Linux) iD8DBQFAJVp7p9X7q/XgeyYRApEKAJwLjuPJoGjMdyw+GyGCBotfyBOXBACgjVxr PByBF8lk6eK4EHkitNiQrSA= =cEGA -----END PGP SIGNATURE----- From rmkrauter at yahoo.com Sat Feb 7 16:56:11 2004 From: rmkrauter at yahoo.com (Rich Krauter) Date: Sat Feb 7 17:01:16 2004 Subject: [Tutor] Short Version, New guy looking for some tips, Revisited. In-Reply-To: <200402071326.55109.syn_ack@comcast.net> References: <200402062221.26060.syn_ack@comcast.net> <200402071326.55109.syn_ack@comcast.net> Message-ID: <1076190971.14957.30.camel@vaio> On Sat, 2004-02-07 at 16:26, Joshua Banks wrote: > Am I asking for a simple example. Nothing more than that. Why don't you just take a stab at it? It doesn't have to be perfect. You should see how many dumb ideas I've posted in attempt to just take a stab at trying to solve something. Big deal. That's the whole point of the mailing list. Here's a quick example. It's bad and inflexible and very limited and likely to die very badly in many common situations, but maybe it'll get you started. <bad example> # requires python 2.3 import tarfile import sys import os,os.path if __name__ == '__main__': fname = 'test.tar' ext = '.gz' archive = '%s%s'%(fname,ext) if os.path.exists(archive): print 'gunzip-ing %s'%archive os.system('gunzip %s'%(archive)) tar = tarfile.open(fname,'a') for f in sys.argv[1:]: print 'adding %s to %s ...'%(f,fname) tar.add(f) tar.close() if os.path.exists(fname): print 'gzip-ing %s'%fname os.system('gzip %s'%fname) </bad example> Rich From shitizb at yahoo.com Sat Feb 7 17:09:00 2004 From: shitizb at yahoo.com (Shitiz Bansal) Date: Sat Feb 7 17:09:06 2004 Subject: [Tutor] win32com manual Message-ID: <20040207220900.66770.qmail@web41502.mail.yahoo.com> Hi, Can anybody please tell me where i can get a detailed manual of win32com module. I plan to use it extensively for some project, but find the information available on net very scanty. I would particularly like to know the objects supported by the Dispatch method and their methods. thank yo shitiz --------------------------------- Do you Yahoo!? Yahoo! Finance: Get your refund fast by filing online -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040207/9811946e/attachment.html From syn_ack at comcast.net Sat Feb 7 17:10:18 2004 From: syn_ack at comcast.net (Joshua Banks) Date: Sat Feb 7 17:14:43 2004 Subject: [Tutor] Short Version, New guy looking for some tips, Revisited. In-Reply-To: <1076190971.14957.30.camel@vaio> References: <200402062221.26060.syn_ack@comcast.net> <200402071326.55109.syn_ack@comcast.net> <1076190971.14957.30.camel@vaio> Message-ID: <200402071410.20487.syn_ack@comcast.net> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Saturday 07 February 2004 01:56 pm, Rich Krauter wrote: Absolutely perfect Rich. I don't care if its somewhat broken. My problem is I didn't even know how to start the script.. :P Sorry. But I've got all this documentation but I didn't even know how to start out the script. This is what was frustrating the heck out of me. It wasn't apparent to me to load all of these modules first. So this is perfect. Gets me researching in the right direction. Thanks for your understanding and taking the time to write this out. Much appreciated. Thanks, Joshua Banks > On Sat, 2004-02-07 at 16:26, Joshua Banks wrote: > > Am I asking for a simple example. Nothing more than that. > > Why don't you just take a stab at it? It doesn't have to be perfect. > You should see how many dumb ideas I've posted in attempt to just > take a stab at trying to solve something. Big deal. That's the whole > point of the mailing list. > > Here's a quick example. It's bad and inflexible and very limited and > likely to die very badly in many common situations, but maybe it'll > get you started. > > <bad example> > > # requires python 2.3 > import tarfile > > import sys > import os,os.path > > > if __name__ == '__main__': > fname = 'test.tar' > ext = '.gz' > archive = '%s%s'%(fname,ext) > > if os.path.exists(archive): > print 'gunzip-ing %s'%archive > os.system('gunzip %s'%(archive)) > > tar = tarfile.open(fname,'a') > for f in sys.argv[1:]: > print 'adding %s to %s ...'%(f,fname) > tar.add(f) > tar.close() > > if os.path.exists(fname): > print 'gzip-ing %s'%fname > os.system('gzip %s'%fname) > > </bad example> > > Rich > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (GNU/Linux) iD8DBQFAJWJKp9X7q/XgeyYRAnonAJ4yWaGPAwzo7XF+tD6WjYB+juaxxwCgk1c+ rHB2LgnMM7Tn9NKSHZB5++c= =qEMC -----END PGP SIGNATURE----- From nick at javacat.f2s.com Sat Feb 7 18:46:16 2004 From: nick at javacat.f2s.com (Nick Lunt) Date: Sat Feb 7 18:53:11 2004 Subject: [Tutor] Short Version, New guy looking for some tips, Revisited. In-Reply-To: <200402071326.55109.syn_ack@comcast.net> References: <200402062221.26060.syn_ack@comcast.net> <200402071326.55109.syn_ack@comcast.net> Message-ID: <20040207234616.3f30edbc@phatbox.local> Hi Joshua, I'm also a beginner at python, but I know what your saying. Also I'm working on a small compression/archive program and the list helped me out with that. However, in a bid to help you understand a little of the linux/python crossover here's a prog I wrote to give me a list off my currently installed gentoo apps. But do read the comments in it as it's not perfect and the way it does things could be better. Also, I no longer run gentoo so I am unable to test it at the moment although it did run fine last time I ran it on gentoo. The prog is attached as Im not sure how my formatting will turn out if I cut n paste it here. Also, I recently bought 2 python books, 'python text processing' and 'learning python 2nd edition'. The learning python book is excellent, and seen as how you already know shell scripts you will have no problems working your way through that book and understanding it. The text processing book Im not keen on, altho it is a recent book. Anyway, hope my little prog helps you out. Cheers Nick. On Sat, 7 Feb 2004 13:26:53 -0800 Joshua Banks <syn_ack@comcast.net> wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Hello, > > Ok. Long story short. > > > Specifically, I would like to accomplish the following with a Python > > script. > > > > 1) Compress all files located in "/var/log/portage directory > > > > 2) Have the Python script create a subdirectory located within the > >Parnet "portage" directory called (example) "LogArchive", and place > >the compressed files from the "portage" directory into newly created > >subdirectory "LogArchive". > > > > #My Mental note: I would preferably like to compress all files > > together if possible instead of individually. Not sure how that is > > best done though. Maybe thats directory compression... Hmmmm.. never > > done that before. (Again any example will suffice) > > What am I REALLY asking for????????? > > What I'm really asking for is for someone to provide a simple script > that accomplishes the goal above. """But Why"""" To Study....really > > """"Important part of this email"""" > > The important part of my email isn't to have a Python script compress a > directory for me..NO...NO....NO I can do that with Tar or Bzip from the > command line very easy. > > The important part is to look at """"How"""" a Python script could be > written so that I can """"reference"""" the steps taken and research > the Python documentation at each step of the way through the script. > > Im sure there are probably more than a few ways to accomplish my > compression goal with a Python script. All I'm looking for is an > example that I can reference. Again, the important part isn't file or > directory compression with Python...... but the """steps""" taken. An > example of """"""How"""""". > > Am I asking for a simple example. Nothing more than that. > > Thanks, > Joshua Banks > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.2.3 (GNU/Linux) > > iD8DBQFAJVgdp9X7q/XgeyYRAtE1AJ9tTJ+yS3FQNqxwbzU3FIFFRXiK4ACfWq/c > h8Hhu0o4lotB2mvqYr3JsPo= > =mnYV > -----END PGP SIGNATURE----- > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- A non-text attachment was scrubbed... Name: list_emerged.py Type: application/octet-stream Size: 1475 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20040207/629a24e3/list_emerged-0001.obj From syn_ack at comcast.net Sat Feb 7 19:40:23 2004 From: syn_ack at comcast.net (Joshua Banks) Date: Sat Feb 7 19:44:47 2004 Subject: [Tutor] Short Version, New guy looking for some tips, Revisited. In-Reply-To: <20040207234616.3f30edbc@phatbox.local> References: <200402062221.26060.syn_ack@comcast.net> <200402071326.55109.syn_ack@comcast.net> <20040207234616.3f30edbc@phatbox.local> Message-ID: <200402071640.25014.syn_ack@comcast.net> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Saturday 07 February 2004 03:46 pm, Nick Lunt wrote: > Hi Joshua, > > I'm also a beginner at python, but I know what your saying. > Also I'm working on a small compression/archive program and the list > helped me out with that. > > However, in a bid to help you understand a little of the linux/python > crossover here's a prog I wrote to give me a list off my currently > installed gentoo apps. But do read the comments in it as it's not > perfect and the way it does things could be better. Also, I no longer > run gentoo so I am unable to test it at the moment although it did > run fine last time I ran it on gentoo. > > The prog is attached as Im not sure how my formatting will turn out > if I cut n paste it here. > > Also, I recently bought 2 python books, 'python text processing' and > 'learning python 2nd edition'. The learning python book is excellent, > and seen as how you already know shell scripts you will have no > problems working your way through that book and understanding it. The > text processing book Im not keen on, altho it is a recent book. > > Anyway, hope my little prog helps you out. Thankyou very much Nick. Much appreciated. Joshua Banks -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (GNU/Linux) iD8DBQFAJYV3p9X7q/XgeyYRArrgAJ971JhR39Mm4hqoawlwUfifKXaJ2QCdFguH VoMJyH6QgSFFiqAoS+S+YHM= =NsLf -----END PGP SIGNATURE----- From alan.gauld at blueyonder.co.uk Sat Feb 7 19:51:07 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Feb 7 19:50:57 2004 Subject: [Tutor] win32com manual References: <20040207220900.66770.qmail@web41502.mail.yahoo.com> Message-ID: <013501c3eddd$a344b450$6401a8c0@xp> > Can anybody please tell me where i can get a detailed manual of win32com module. There is a Windows help file that ships with the winall package. But frankly it only helps if you already know what you are looking for - usually by having programmed using COM/MFC in Visual C++ previously. The best thing is to get Mark Hammond's excellent book Python Programming on Win32 This really is essential reading for anyone serious about Python on Windows. > I would particularly like to know the objects supported by the > Dispatch method and their methods. Dispatch will support any COM/ActiveX object. The problem is finding the methods for the objects and how to use them. The COM class browser in Pyhonwin helps as will the application help files(where they exist!) But this is by far the hardest part of COM programming and has nothing to do with Pyhon or Winall, and everything to do with the poorly documented object models in Windows applications! Little comfort but the sad truth, Alan G. From alan.gauld at blueyonder.co.uk Sat Feb 7 19:55:05 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Feb 7 19:54:54 2004 Subject: [Tutor] Short Version, New guy looking for some tips, Revisited. References: <200402062221.26060.syn_ack@comcast.net><200402071326.55109.syn_ack@comcast.net> <20040207234616.3f30edbc@phatbox.local> Message-ID: <014001c3edde$3138bb30$6401a8c0@xp> > Also, I recently bought 2 python books, 'python text processing' > and ... The text processing book Im not keen on, altho it is a recent book. This is an example of the recent wave of advanced python books. It pretty well dives straight in at the deep end and tackles a single specialised use of Python. Once you are fairly exprerienced with Python go back to it and I think you'll get much more out of it. Maybe someone will write a "Python and Operating Systems" book soon and that will be ideal for Joshua... Alan G. From syn_ack at comcast.net Sat Feb 7 20:04:43 2004 From: syn_ack at comcast.net (Joshua Banks) Date: Sat Feb 7 20:09:08 2004 Subject: [Tutor] Short Version, New guy looking for some tips, Revisited. In-Reply-To: <20040207234616.3f30edbc@phatbox.local> References: <200402062221.26060.syn_ack@comcast.net> <200402071326.55109.syn_ack@comcast.net> <20040207234616.3f30edbc@phatbox.local> Message-ID: <200402071704.45270.syn_ack@comcast.net> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Saturday 07 February 2004 03:46 pm, Nick Lunt wrote: This works great Nick. Awesome example as well. This is definitely allot faster than Gentoo's "etcat" or "qpkg" from the basis of the output. What distro are you running now? Why did you switch from Gentoo to what your currently using?? Thanks, Joshua Banks -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (GNU/Linux) iD8DBQFAJYsrp9X7q/XgeyYRAm8jAJsFc1i12D+eD3cXHdfHTPLOGiYzjwCcCriN jS0MPbrn8Y68b99NWkWlfyE= =NM38 -----END PGP SIGNATURE----- From syn_ack at comcast.net Sat Feb 7 20:06:48 2004 From: syn_ack at comcast.net (Joshua Banks) Date: Sat Feb 7 20:11:12 2004 Subject: [Tutor] Short Version, New guy looking for some tips, Revisited. In-Reply-To: <014001c3edde$3138bb30$6401a8c0@xp> References: <200402062221.26060.syn_ack@comcast.net> <20040207234616.3f30edbc@phatbox.local> <014001c3edde$3138bb30$6401a8c0@xp> Message-ID: <200402071706.50730.syn_ack@comcast.net> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Saturday 07 February 2004 04:55 pm, Alan Gauld wrote: > Maybe someone will write a "Python and Operating Systems" book > soon and that will be ideal for Joshua... LOL. Yes. All be the one writing the book probably. :D Joshua Banks -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (GNU/Linux) iD8DBQFAJYuop9X7q/XgeyYRAn6mAKCd6KGVUcQgVWsYaRKne6TA1XHZBwCdE4GL /lkikbZEzoQO9LU5lwR665M= =B6pK -----END PGP SIGNATURE----- From idiot1 at netzero.net Sat Feb 7 20:42:53 2004 From: idiot1 at netzero.net (Kirk Bailey) Date: Sat Feb 7 20:43:47 2004 Subject: [Tutor] aging files Message-ID: <4025941D.6090706@netzero.net> How to I read the age of a file? Un*x (FreeBSD) environment. -- end think http://www.tinylist.org/ - $FREE$ software for liberty +-------+ http://www.pinellasintergroupsociety.org/ - In Her Service | BOX | http://www.listville.net/ - $FREE$ list hosting services +-------+ http://www.howlermonkey.net/ - $FREE$ email service kniht http://www.sacredelectron.org/ - My personal SCREED pit (C)2004 Kirk D Bailey, all rights reserved- but ask! From rmkrauter at yahoo.com Sat Feb 7 20:45:07 2004 From: rmkrauter at yahoo.com (Rich Krauter) Date: Sat Feb 7 20:50:11 2004 Subject: [Tutor] aging files In-Reply-To: <4025941D.6090706@netzero.net> References: <4025941D.6090706@netzero.net> Message-ID: <1076204707.15359.6.camel@vaio> On Sat, 2004-02-07 at 20:42, Kirk Bailey wrote: > How to I read the age of a file? Un*x (FreeBSD) environment. > > > You can try os.path http://www.python.org/doc/current/lib/module-os.path.html See getatime, getmtime, getctime on this page. Rich From shaleh at speakeasy.net Sun Feb 8 01:10:14 2004 From: shaleh at speakeasy.net (Sean 'Shaleh' Perry) Date: Sun Feb 8 01:10:30 2004 Subject: [Tutor] aging files In-Reply-To: <4025941D.6090706@netzero.net> References: <4025941D.6090706@netzero.net> Message-ID: <200402072210.14176.shaleh@speakeasy.net> On Saturday 07 February 2004 17:42, Kirk Bailey wrote: > How to I read the age of a file? Un*x (FreeBSD) environment. the canonical answer is with 'stat'. In python this lives in os.stat(). From shitizb at yahoo.com Sun Feb 8 07:25:23 2004 From: shitizb at yahoo.com (Shitiz Bansal) Date: Sun Feb 8 07:25:28 2004 Subject: [Tutor] win32com manual In-Reply-To: <013501c3eddd$a344b450$6401a8c0@xp> Message-ID: <20040208122523.39055.qmail@web41510.mail.yahoo.com> Hi, How about everyone mailing in the objects they are familiar with and their methods( for the uninitiated we are talking about the objects supported by Dispatch method in win32com). Then perhaps we could compile them in a single place and post them at python homepage, it could be a great tool for python programmers on windows. cyao shitiz --------------------------------- Do you Yahoo!? Yahoo! Finance: Get your refund fast by filing online -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040208/ecbe38ac/attachment.html From nick at javacat.f2s.com Sun Feb 8 09:43:43 2004 From: nick at javacat.f2s.com (Nick Lunt) Date: Sun Feb 8 09:50:39 2004 Subject: [Tutor] Short Version, New guy looking for some tips, Revisited. In-Reply-To: <40262EB7.6000702@gentoo.org> References: <200402062221.26060.syn_ack@comcast.net> <200402071326.55109.syn_ack@comcast.net> <20040207234616.3f30edbc@phatbox.local> <40262EB7.6000702@gentoo.org> Message-ID: <20040208144343.64b136f8@phatbox.local> Hi, if you saw my script on gentoo forums a couple of months ago then that was when I first touched python, so yes the script is overkill for what it does, as I've explained to Joshua already. Your function - > def gen_list(somedir): > l = os.listdir(somedir).sort() > return l when I try that from the python interpreter it returns None. Im not sure why that is however. Also this does the same: > def list_from_dict(dict): > tempkeys = dict.keys().sort() > return tempkeys So maybe someone on the list can tell us why appending the sort method after creation of a tuple does not work as expected. Also Thomas there are other ways to create a dict that I did not know about at the time, such as - mydict = dict(zip(list1, list2)) which I would of used if I'd known about it at the time of writing the program. In fact on the gentoo forums one python programmer did the whole program in about 3 lines using 'dict' and 'lambda' ;) Cheers Nick On Sun, 08 Feb 2004 13:42:31 +0100 drstrange <strangedr@gentoo.org> wrote: > Nick Lunt wrote: > > >Hi Joshua, > > > >I'm also a beginner at python, but I know what your saying. > >Also I'm working on a small compression/archive program and the list > helped me out with that. > > > Hello Nick, > > I am also new to Python, programming in gneral, and this list (hello, > list...). > I'd like to comment/ask on your script (I believe I saw this on > forums.gentoo.org also). Specifically these two functions: > def gen_list(somedir): > l = [] > for arg in os.listdir(somedir): > l.append(arg) > l.sort() > return l > > and > > def list_from_dict(dict): > tempkeys = [] > for key in dict.keys(): > tempkeys.append(key) > tempkeys.sort() > return tempkeys > > are overkill, I think. If I know correctly, os.listdir() returns a list, > and dict.keys() also returns a list, so IMHO there is no need to iterate > over them to produce another list. Something like this would be enough: > > def gen_list(somedir): > l = os.listdir(somedir).sort() > return l > > and > > def list_from_dict(dict): > tempkeys = dict.keys().sort() > return tempkeys > > Am I correct in this? > > cheers, > > Thomas Ferencz From missive at hotmail.com Sun Feb 8 10:28:51 2004 From: missive at hotmail.com (Lee Harr) Date: Sun Feb 8 10:28:56 2004 Subject: [Tutor] Re: Short Version, New guy looking for some tips, Revisited. Message-ID: <BAY2-F30jOy8I9p64lf0003bfb2@hotmail.com> >Your function - >>def gen_list(somedir): >> l = os.listdir(somedir).sort() >> return l > >when I try that from the python interpreter it returns None. >Im not sure why that is however. > In python, a_list.sort() sorts the list in place and returns None >>>a_list = [4, 3, 5, 2, 1] >>>r = a_list.sort() >>>r >>>a_list [1, 2, 3, 4, 5] >>> so you would probably want ... def gen_list(somedir): l = os.listdir(somedir) l.sort() return l My understanding is that in python2.4 lists will have a sorted() method which will return the list sorted ... or maybe it will be a builtin like ... s = sorted(a_list) _________________________________________________________________ STOP MORE SPAM with the new MSN 8 and get 2 months FREE* http://join.msn.com/?page=features/junkmail From nick at javacat.f2s.com Sun Feb 8 11:57:07 2004 From: nick at javacat.f2s.com (Nick Lunt) Date: Sun Feb 8 12:23:06 2004 Subject: [Tutor] Re: Short Version, New guy looking for some tips, Revisited. In-Reply-To: <BAY2-F30jOy8I9p64lf0003bfb2@hotmail.com> References: <BAY2-F30jOy8I9p64lf0003bfb2@hotmail.com> Message-ID: <20040208165707.088c83d5@phatbox.local> Thanks for clearing that up ;) On Sun, 08 Feb 2004 15:28:51 +0000 "Lee Harr" <missive@hotmail.com> wrote: > >Your function - > >>def gen_list(somedir): > >> l = os.listdir(somedir).sort() > >> return l > > > >when I try that from the python interpreter it returns None. > >Im not sure why that is however. > > > > > In python, a_list.sort() sorts the list in place and returns None > > >>>a_list = [4, 3, 5, 2, 1] > >>>r = a_list.sort() > >>>r > >>>a_list > [1, 2, 3, 4, 5] > >>> > > > so you would probably want ... > > def gen_list(somedir): > l = os.listdir(somedir) > l.sort() > return l > > > My understanding is that in python2.4 lists will have a sorted() method > which will return the list sorted ... or maybe it will be a builtin like > ... > s = sorted(a_list) > > _________________________________________________________________ > STOP MORE SPAM with the new MSN 8 and get 2 months FREE* > http://join.msn.com/?page=features/junkmail > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From idiot1 at netzero.net Sun Feb 8 15:11:47 2004 From: idiot1 at netzero.net (Kirk Bailey) Date: Sun Feb 8 15:13:21 2004 Subject: [Tutor] globbing and aging and sorting, oh my! Message-ID: <40269803.9050507@netzero.net> First edition of the script is finished and working, sorts out what's new and what is not quite well. Here is the sourcecode: http;//www.tinylist.org/whatsnew.txt And here is the actual script at work: http://www.tinylist.org/cgi-bin/whatsnew.py first edition of the new feature. I invite correspondance about it on or off list. -- end think http://www.tinylist.org/ - $FREE$ software for liberty +-------+ http://www.pinellasintergroupsociety.org/ - In Her Service | BOX | http://www.listville.net/ - $FREE$ list hosting services +-------+ http://www.howlermonkey.net/ - $FREE$ email service kniht http://www.sacredelectron.org/ - My personal SCREED pit (C)2004 Kirk D Bailey, all rights reserved- but ask! From nick at javacat.f2s.com Sun Feb 8 15:17:35 2004 From: nick at javacat.f2s.com (Nick Lunt) Date: Sun Feb 8 15:24:24 2004 Subject: [Tutor] Possible Virus Warning Message-ID: <20040208201735.6da6ed1a@phatbox.local> Hi Folks, I dont want to be alarmist but today I've received 2 possible virus emails. The reason I'm telling the list is that there are only 3 instances of when I have given out this email address - 1. my Mrs 2. my Daughter 3. this list The emails were as follows - email 1. subject: hello sender: postman@bioinformatics.org No email message and a single 31.Kb zip attachment named file.zip email 2. subject: Mail Delivery System sender: python-docs@python.org Possibly a binary email message, along with a 33.7Kb zip attachment named data.zip I run linux so it's not an issue, but I thought it best to let you folks know in case you get similar unknown emails, and particularly if you run a windows OS. Email 2 has an encoded/binary message part that opens up directly in the email client regardless of whether or not the attacment is opened. Hopefully I'm wrong about it, but forewarned is forearmed... Cheers Nick. From shaleh at speakeasy.net Sun Feb 8 15:52:26 2004 From: shaleh at speakeasy.net (Sean 'Shaleh' Perry) Date: Sun Feb 8 15:52:51 2004 Subject: [Tutor] Possible Virus Warning In-Reply-To: <20040208201735.6da6ed1a@phatbox.local> References: <20040208201735.6da6ed1a@phatbox.local> Message-ID: <200402081252.26962.shaleh@speakeasy.net> On Sunday 08 February 2004 12:17, Nick Lunt wrote: > Hi Folks, > > I dont want to be alarmist but today I've received 2 possible virus emails. > The reason I'm telling the list is that there are only 3 instances of when > I have given out this email address - 1. my Mrs > 2. my Daughter > 3. this list > sounds like mydoom. It is very common for spammers and the like to pull email addresses from public mailing list archives. Some of them even subscribe to a list just to eat addresses. So consider that address public domain now )-: From phil at xfr.co.uk Sun Feb 8 21:04:03 2004 From: phil at xfr.co.uk (Philip Kilner) Date: Sun Feb 8 21:05:05 2004 Subject: [Tutor] Possible Virus Warning In-Reply-To: <200402081252.26962.shaleh@speakeasy.net> References: <20040208201735.6da6ed1a@phatbox.local> <200402081252.26962.shaleh@speakeasy.net> Message-ID: <4026EA93.4070105@xfr.co.uk> Hi List, Sean 'Shaleh' Perry wrote: > sounds like mydoom. > > It is very common for spammers and the like to pull email addresses from > public mailing list archives. Some of them even subscribe to a list just to > eat addresses. So consider that address public domain now )-: > Indeed - and this thing /always/ forges the "from" address, so the list itself is the once place it won't have come from. The list and the other addresses will /probably/ both be in the affected party's address book. -- Regards, PhilK Email: phil@xfr.co.uk / Voicemail & Facsimile: 07092 070518 ?The basic tool for the manipulation of reality is the manipulation of words. If you can control the meaning of words, you can control the people who must use the words.? Philip K. Dick From vse at srasys.co.in Mon Feb 9 00:50:13 2004 From: vse at srasys.co.in (V.Selvam) Date: Mon Feb 9 00:49:19 2004 Subject: [Tutor] need help on distrbuting python module in the user's path Message-ID: <011e01c3eed0$95ea14a0$0fa8a8c0@selvam> Hi all, I am new for the python - distutils. I am creating distribution for the windows platform. I want to get user's path option and put all my python file(modules and packages) in to the same path at the installation run time. Can any one help me in that?? Thanks in advance Regards V.Selvam -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040209/c3a1c9d9/attachment.html From jakieabraham at yahoo.com Mon Feb 9 06:02:50 2004 From: jakieabraham at yahoo.com (Jacob Abraham) Date: Mon Feb 9 06:02:59 2004 Subject: [Tutor] Segmentation Fault Message-ID: <20040209110250.2938.qmail@web11204.mail.yahoo.com> Dear Tutors, I have just begun building an application with PyQt and I keep getting a Segmentation fault error with no traceback. Could help me __________________________________ Do you Yahoo!? Yahoo! Finance: Get your refund fast by filing online. http://taxes.yahoo.com/filing.html From jakieabraham at yahoo.com Mon Feb 9 06:06:12 2004 From: jakieabraham at yahoo.com (Jacob Abraham) Date: Mon Feb 9 06:06:27 2004 Subject: [Tutor] Segmentation Fault Message-ID: <20040209110612.96097.qmail@web11203.mail.yahoo.com> Dear Tutors, I have just begun building an application with PyQt and I keep getting a Segmentation fault error with no traceback. Could help some one help understand how these Errors are generated and how to find the origin of these errors. Thanks Jacob Abraham p.s I am sorry if i sent 2 copies of this email. __________________________________ Do you Yahoo!? Yahoo! Finance: Get your refund fast by filing online. http://taxes.yahoo.com/filing.html From renderpipe at speedpost.net Mon Feb 9 10:13:23 2004 From: renderpipe at speedpost.net (RenderPipe) Date: Mon Feb 9 10:15:00 2004 Subject: [Tutor] Using python for building dynamic websites Message-ID: 1076339603.21853.180733548@webmail.messagingengine.com Hello, Yesterday I was looking around all of the options for building a database driven website with python and my head is spinning with all of the options. I installed mod_python on my linux computer and ran the test script in the manual and it works although it doesn't appear as straight forward as I thought. I'm starting to really like python and really don't want to go back to php unless I have to. Here's what I would like to do. Write my code in python. Call a template file Output the data from my python and template file to the browser Some areas of the site I would like to output static html files from my python/template code. I have no interest in learrning another language or complex framework like zope to do this. I would prefer to use just python. The problem I'm having is that this doesn't seem possible for me. From what I understand of mod_python I have to write special handlers for every script that I write. I may be understanding it wrong. I tried something like: for i in range(1,10): print i, #req.write() gave me undefined errors I saved this file as num.py. when i load this file in my webbrowser http://localhost/num.py. I get an error from the publisher. In the end I just want to build my site in a straight forward manner. I didn't bother with all the other frameworks like pmz because I'm not allowed to install software on the host server, I can only use the preinstalled mod_python. If it is too difficult to use python, then I was thinking of using php to interact with my database instead. I read somewhere that python can be used as a "backend" to a php site. What does this mean? Can you possibly give a scenario where python would be used as a "backend". Sorry for all of the web related questions but I'm madly confused. My whole purpose to learn python was mainly for building data driven websites with ease of modification. TIA Bobby -- http://www.fastmail.fm - Faster than the air-speed velocity of an unladen european swallow From pythontutor at venix.com Mon Feb 9 10:48:09 2004 From: pythontutor at venix.com (Lloyd Kvam) Date: Mon Feb 9 10:48:15 2004 Subject: [Tutor] Using python for building dynamic websites References: 1076339603.21853.180733548@webmail.messagingengine.com Message-ID: <4027ABB9.9020400@venix.com> I have not used mod_python, so I can't help you on that front. There are alternatives. cgi and fast-cgi are relatively easy to do in Python. The downside to cgi is the extra overhead of starting a process and making a new database connection for every request. However, for many applications this works fine. The cgi module can be used to collect form data. You need to provide the content header typically: print "Content-Type: text/html\n" The headers MUST be followed by a blnk line. owlfish.com provides a standalone version of the ZopePageTemplates. There are other template systems available. The Python string interpolation using the dictionary lookup syntax also works well for generating html. If you prefer fast-cgi, the jonpy modules provide a simple framework for fast-cgi scripting. This is my little function for sending static files to the browser. Note that sys.stdout is normally connected back to the web server in cgi programs so that it is simply a matter of copying the file contents to sys.stdout. def copy_snippet( filename, out_file=None): if out_file is None: out_file = sys.stdout if os.path.exists( filename): snip = open( filename, 'r') shutil.copyfileobj( snip, out_file) snip.close() Obviously, I have opted for a looser coupling with Apache than mod_python provides. You'll need to figure out what makes the most sense for your application. I hope this helps. RenderPipe wrote: > Hello, > > Yesterday I was looking around all of the options for building a database > driven website with python and my head is spinning with all of the > options. I installed mod_python on my linux computer and ran the test > script in the manual and it works although it doesn't appear as straight > forward as I thought. I'm starting to really like python and really don't > want to go back to php unless I have to. > > Here's what I would like to do. > > Write my code in python. > Call a template file > Output the data from my python and template file to the browser > Some areas of the site I would like to output static html files from my > python/template code. > > I have no interest in learrning another language or complex framework > like zope to do this. I would prefer to use just python. The problem I'm > having is that this doesn't seem possible for me. From what I understand > of mod_python I have to write special handlers for every script that I > write. I may be understanding it wrong. > > I tried something like: > > for i in range(1,10): > print i, > #req.write() gave me undefined errors > > I saved this file as num.py. when i load this file in my webbrowser > http://localhost/num.py. I get an error from the publisher. > In the end I just want to build my site in a straight forward manner. I > didn't bother with all the other frameworks like pmz because I'm not > allowed to install software on the host server, I can only use the > preinstalled mod_python. > > If it is too difficult to use python, then I was thinking of using php to > interact with my database instead. I read somewhere that python can be > used as a "backend" to a php site. What does this mean? Can you possibly > give a scenario where python would be used as a "backend". > > Sorry for all of the web related questions but I'm madly confused. My > whole purpose to learn python was mainly for building data driven > websites with ease of modification. > > TIA > > Bobby > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From orbitz at ezabel.com Mon Feb 9 11:47:47 2004 From: orbitz at ezabel.com (orbitz@ezabel.com) Date: Mon Feb 9 11:49:16 2004 Subject: [Tutor] Using python for building dynamic websites Message-ID: <20040209114747.26dcfe8a.orbitz@ezabel.com> Nevow, a replacement for Woven in twisted is coming along quite well. It allows for easy templating. You can find information at: http://divmod.org/users/dp.twistd/wiki/ Nevow is very powerful and allows for templating from disktemplates or providing a template in your code. On Mon, 09 Feb 2004 10:13:23 -0500 "RenderPipe" <renderpipe@speedpost.net> wrote: > Hello, > > Yesterday I was looking around all of the options for building a database > driven website with python and my head is spinning with all of the > options. I installed mod_python on my linux computer and ran the test > script in the manual and it works although it doesn't appear as straight > forward as I thought. I'm starting to really like python and really don't > want to go back to php unless I have to. > > Here's what I would like to do. > > Write my code in python. > Call a template file > Output the data from my python and template file to the browser > Some areas of the site I would like to output static html files from my > python/template code. > > I have no interest in learrning another language or complex framework > like zope to do this. I would prefer to use just python. The problem I'm > having is that this doesn't seem possible for me. From what I understand > of mod_python I have to write special handlers for every script that I > write. I may be understanding it wrong. > > I tried something like: > > for i in range(1,10): > print i, > #req.write() gave me undefined errors > > I saved this file as num.py. when i load this file in my webbrowser > http://localhost/num.py. I get an error from the publisher. > In the end I just want to build my site in a straight forward manner. I > didn't bother with all the other frameworks like pmz because I'm not > allowed to install software on the host server, I can only use the > preinstalled mod_python. > > If it is too difficult to use python, then I was thinking of using php to > interact with my database instead. I read somewhere that python can be > used as a "backend" to a php site. What does this mean? Can you possibly > give a scenario where python would be used as a "backend". > > Sorry for all of the web related questions but I'm madly confused. My > whole purpose to learn python was mainly for building data driven > websites with ease of modification. > > TIA > > Bobby > > -- > http://www.fastmail.fm - Faster than the air-speed velocity of an > unladen european swallow > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From barrys at datatree.co.uk Wed Feb 4 04:16:39 2004 From: barrys at datatree.co.uk (Barry Smithers) Date: Mon Feb 9 12:32:00 2004 Subject: [Tutor] Re: Using Python with VI References: <00a801c3e99b$dfb52820$b364a8c0@datatree> <E1Ao7X2-00008H-00@hooloovoo> Message-ID: <002d01c3eaff$98b0f5c0$b364a8c0@datatree> Thanks for that Abel, exactly what I needed. Cheers Barry ----- Original Message ----- From: "Abel Daniel" <abli@freemail.hu> To: "Barry Smithers" <barrys@datatree.co.uk> Cc: <tutor@python.org> Sent: Tuesday, February 03, 2004 8:52 PM Subject: Re: Using Python with VI > "Barry Smithers" writes: > > > I'm having difficulty with a program call from inside of VI. What I > > basically need to do is get the line numbers input in the ex command. Or > > maybe even get the text on those lines to go into a list. For example the > > ex command ":20,21!xxx.py" would run xxx.py as a whole, but I need the data > > currently on lines 20 and 21 for modification. > > This ex command expects the program you run (xxx.py) to be a filter: it should > read on stdin and write to stdout. Something like this: > > --- > import sys > l=sys.stdin.readlines() # this l will be the list you need > print "l:", l # print writes to stdout by default. Or you can use > # sys.stdout.write() > # (and .flush(), and .close(), just to be safe) > --- > > I don't know how you could pass the _line_numbers_ (instead of the contents > of the lines). > > -- > Abel Daniel From d.sohner007 at freenet.de Mon Feb 9 09:02:18 2004 From: d.sohner007 at freenet.de (Dennis) Date: Mon Feb 9 12:32:24 2004 Subject: [Tutor] question Message-ID: <001401c3ef15$557098a0$8c1d06d5@r5u0m4> Hello, I work with Python 2.3.3 and I try to make a programme that saves words in a dictionary. And because I'm not a Python expert I don't know how to do it or witch command I need. Could you please send me an example of this case? Thanks. d.sohner007@freenet.de -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040209/795a9818/attachment.html From loper at ananzi.co.za Fri Feb 6 11:23:21 2004 From: loper at ananzi.co.za (Gerhard Venter) Date: Mon Feb 9 12:32:41 2004 Subject: [Tutor] all the slashes Message-ID: <4023BF79.9060106@ananzi.co.za> Hi all I use the code below in Python 2.3, but in 2.2 it says: TypeError: 'in <string>' requires character as left operand I have tried r'//', and '////' (to escape the slashes) to no avail. How can I make this work in 2.2? myfile=open(r'/etc/sitelist','a') if "//" in mystring: Thanks Gerhard From nadinerioux at yahoo.ca Fri Feb 6 10:35:58 2004 From: nadinerioux at yahoo.ca (=?iso-8859-1?q?Nadine=20Rioux?=) Date: Mon Feb 9 12:33:39 2004 Subject: [Tutor] Question Message-ID: <20040206153558.10180.qmail@web20204.mail.yahoo.com> Hi! Python has been installed by default when we installed Linux RedHad. We try to execute a .py file and we get this message : " Failed to import modules, reason : No module named _omnipy". NOTE : this our first expercience with Linux and Python... Could you help us? Nadzine --------------------------------- L?che-vitrine ou l?che-?cran ? Yahoo! Magasinage. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040206/8a8740b2/attachment.html From magnus at thinkware.se Mon Feb 9 12:33:28 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Mon Feb 9 12:33:50 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gVXNpbmcgcHl0aG9uIGZvciBidWlsZGluZyBkeW5hbWljIHdlYnNpdGVz?= Message-ID: <think001_4027c10cbd1d4@webmail.thinkware.se> > Yesterday I was looking around all of the options for building a database > driven website with python and my head is spinning with all of the > options. I installed mod_python on my linux computer and ran the test > script in the manual and it works So far, so good. I assume you mean this: http://www.modpython.org/live/current/doc-html/inst-testing.html > I tried something like: > > for i in range(1,10): > print i, > #req.write() gave me undefined errors How did you configure mod_python to support that kind of code? I think you need to use the cgihandler to be able to use "print" to show data, but your attempt to use the request object, which you don't seem to have defined, makes me guess that you have misunderstood something fundamental. Try to follow the examples in the docs verbatim, and try to understand what is happening and why. -- 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 NAuther at lacare.org Tue Feb 3 19:42:53 2004 From: NAuther at lacare.org (NAuther@lacare.org) Date: Mon Feb 9 12:34:07 2004 Subject: [Tutor] python newbie help Message-ID: <OFA8D163A9.B8FD09C8-ON88256E30.0003B5B3@lacare.org> Hello, I'm a Project Manager who's not interested in programming (mercifully). However, I do like the canned added macros python/tcl provides for WinCVS. We're using CVS and all I really need are the simple commands to view the repository (I did it once w/ the (.) to go back a level) when accessing from WinCVS menu: Admin\Admin Macro\list macro modules. Now, I just get pathname errors? Is there a short list of characters or commands to navigate the repository? Thanks a million! - 'newbie' Norman V. Auther II, Critical Processes Coordinator Information Services LA Care Health Plan (213) 694-1250 ext. 4181 nauther@lacare.org From shitizb at yahoo.com Wed Feb 4 19:19:21 2004 From: shitizb at yahoo.com (bansal shitiz) Date: Mon Feb 9 12:36:15 2004 Subject: [Tutor] Printing problem Message-ID: <20040205001921.44029.qmail@web41503.mail.yahoo.com> hello, I am developing a printing program in python for printing msoffice documents using win32com.client. My question is: How do i specify the various printoptions. Im aware of PrintOptions method. For example: to print a ppt presentation:i specify ppt.ActivePresentation.PrintOptions.RangeType = 1 ppt.ActivePresentation.PrintOptions.NumberOfCopies = 3 ppt.ActivePresentation.PrintOptions.Collate = msoTrue What are the other options which i can specify using PrinOptions(i need many more like duplexing, no of pages per sheet etc.) Can somebody provide me with a complete list. Unfortunately its not there in the manuals/internet. You can mail me at shitizb@yahoo.com Thanking you. Shitiz --------------------------------- Do you Yahoo!? Yahoo! SiteBuilder - Free web site building tool. Try it! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040204/dafece8c/attachment.html From mdmazzola at charter.net Thu Feb 5 19:26:55 2004 From: mdmazzola at charter.net (matthew mazzola) Date: Mon Feb 9 12:36:31 2004 Subject: [Tutor] Can you help me figure out what the problem is? Message-ID: <000801c3ec47$eeb8d6b0$eb316b18@yourgv9eh6ors1> I am trying to make a web page editor program. It's really simple so i think someone experience would be able to fix it easily. The file is attached and copied on the bottom of this email but make sure your window is maximized or it'll ruin formatting. It complains with: Traceback (most recent call last): File "<string>", line 1, in ? File "C:\Python22\webpage_editor.py", line 82, in ? matts_template = ["<html>", TypeError: cannot concatenate 'str' and 'NoneType' objects The File Source: --------------------------------------------------------------------------------------------------------------------------------------- # Make Your Own Webpage # THIS IS MINE I MADE IT ALL MINE # Matt Mazzola - 2/4/04 #Welcome User print "\t Welcome to Matt Mazzola's\n\t\t-----------\n\t\tWeb Page Editor" #Ask them what they want to have on their Page by main elemts raw_input("press enter to see the layout of the page...") print \ """ Here is the layout of your page. (Pay attention to the sections of the page because you will later be asked what you want in those sectoins.) Also, rember title is the what you want the window title bar to display and background is the color of the web page backgroud. """ layout = """ title/background +----------------------------------------------------------------------+ | Header | +----------------------------------------------------------------------+ +-----------------+ +-----------------------------+ +------------------+ | Navigation | | Main Topic Title | | Interaction | +-----------------+ +-----------------------------+ +------------------+ |link 1 | | Sub Title | | Questoin for poll| |link 2 | | paragraph | | form for poll | +-----------------+ +-----------------------------+ +------------------+ +----------------------------------------------------------------------+ | Footer | +----------------------------------------------------------------------+ """ print layout raw_input("Press enter to continue on to the building part...") title = None bgcolor = None header = None link_1 = None link_1_src = None link_2 = None link_2_src = None main_topic_title = None sub_title = None paragraph = None question = None footer = None title = raw_input("What would you like the Title to display? ") bgcolor = raw_input("What would you like the background to be? ") header = raw_input("What would you like the Header to display? ") link_1 = raw_input("What would you like the Link 1 to display? ") link_1_src = raw_input("Where would you like the link to go?"+ "\n\tYou need to type the whole URL ie: http://www.google.com ") link_2 = raw_input("What would you like the Link 2 to display? ") link_1_src = raw_input("Where would you like the link to go?"+ "\n\tYou need to type the whole URL ie: http://www.google.com ") main_topic_title = raw_input("What would you like the Main Topic Title to display? ") sub_title = raw_input("What would you like the Sub Title to display? ") paragraph = raw_input("How would you like the Paragraph to read? ") question = raw_input("What would you like the Question to ask? ") option_1 = raw_input("What would you like Option 1 to be?") option_2 = raw_input("What would you like Option 2 to be?") footer = raw_input("What would you like the Footer to display? ") print """ Now we are going to create a text file which you need to open in notepad then save as a *.html file so you cab open it in a webrowser and view it """ name = raw_input("what would you like to name the file?"+ "( it should be something you can remember"+ " since you will have to reopen it several times.)"+ "*** It must end in .txt ***") matts_template = ["<html>", "<head>", "<title>" + title + "</title>", "</head>", "<body>", "<table width=\"100%\">", " <tr>", " <td>", " <table width=\"75%\" align=\"center\">", " <tr>", " <th bgcolor=\"66CCCC\">", "<h2>" + header + "</h2>", " </th>", " </tr>", " </table>", " </td>", " </tr>", " <tr>", " <td>", " <table width=\"20%\" align=\"left\">", " <tr>", " <td>", " <table width=\"100%\" align=\"top\" cellspacing=\"1\" bgcolor=\"#009999\">", " <tr>", " <td bgcolor=\"#66CCCC\">", "Navigation", " </td>", " </tr>", " <tr>", " <td bgcolor=\"#ACE6E6\">", "<a href=\"" + link_1_src + "\">" + link_1 +"</a><br>", "<a href=\"" + link_2_src + "\">" + link_2 +"</a><br>", " </td>", " </tr>", " </table>", " </td>", " </tr>", " </table>", " <table width=\"58%\" align=\"left\">", " <tr>", " <td>", " <table width=\"100%\" align=\"left\" cellspacing=\"1\" bgcolor=\"#009999\">", " <tr>", " <td bgcolor=\"#66CCCC\">", "<h3>" + main_topic_title + "</h3>", " </td>", " </tr>", " <tr>", " <td bgcolor=\"#ACE6E6\">", "" + sub_title + "<br><br>", "" + paragraph + "", " </td>", " </tr>", " </table>", " </td>", " </tr>", " </table>", " <table width=\"20%\" align=\"left\">", " <tr>", " <td>", " <table width=\"100%\" align=\"left\" cellspacing=\"1\" bgcolor=\"#009999\">", " <tr>", " <td bgcolor=\"#66CCCC\">", "Interact", " </td>", " </tr>", " <tr>", " <td bgcolor=\"#ACE6E6\">", ""+ question + "<br>", "<form>", "<input type=\"radio\" name=\"hot\">--" + option_1 + "<br>", "<input type=\"radio\" name=\"hot\">--" + option_2 + "<br>", "</form>", " </td>", " </tr>", " </table>", " </td>", " </tr>", " </table>", " </td>", " </tr>", " <tr>", " <td>", " <table width=\"75%\" align=\"center\">", " <tr>", " <th bgcolor=\"66CCCC\">", "<h2>" + footer + "</h2>", " </th>", " </tr>", " </table>", " </td>", " </tr>", "</table>", "</body>", "</html>"] text_file = open( name , "w") text_file.writelines(matts_template) text_file.close() raw_input("Thank You for making your own" \ +"proffessional web site with my editor.") --------------------------------------------------------------------------------------------------------------------------------------- Thank you for your help. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040205/418560db/attachment-0001.html From mdmazzola at charter.net Thu Feb 5 19:30:50 2004 From: mdmazzola at charter.net (matthew mazzola) Date: Mon Feb 9 12:36:39 2004 Subject: [Tutor] It's the webpage_editor file i forgot to attach to previous message Message-ID: <001101c3ec48$857c1d50$eb316b18@yourgv9eh6ors1> Skipped content of type multipart/alternative-------------- next part -------------- # Make Your Own Webpage # THIS IS MINE I MADE IT ALL MINE # Matt Mazzola - 2/4/04 #Welcome User print "\t Welcome to Matt Mazzola's\n\t\t-----------\n\t\tWeb Page Editor" #Ask them what they want to have on their Page by main elemts raw_input("press enter to see the layout of the page...") print \ """ Here is the layout of your page. (Pay attention to the sections of the page because you will later be asked what you want in those sectoins.) Also, rember title is the what you want the window title bar to display and background is the color of the web page backgroud. """ layout = """ title/background +----------------------------------------------------------------------+ | Header | +----------------------------------------------------------------------+ +-----------------+ +-----------------------------+ +------------------+ | Navigation | | Main Topic Title | | Interaction | +-----------------+ +-----------------------------+ +------------------+ |link 1 | | Sub Title | | Questoin for poll| |link 2 | | paragraph | | form for poll | +-----------------+ +-----------------------------+ +------------------+ +----------------------------------------------------------------------+ | Footer | +----------------------------------------------------------------------+ """ print layout raw_input("Press enter to continue on to the building part...") title = None bgcolor = None header = None link_1 = None link_1_src = None link_2 = None link_2_src = None main_topic_title = None sub_title = None paragraph = None question = None footer = None title = raw_input("What would you like the Title to display? ") bgcolor = raw_input("What would you like the background to be? ") header = raw_input("What would you like the Header to display? ") link_1 = raw_input("What would you like the Link 1 to display? ") link_1_src = raw_input("Where would you like the link to go?"+ "\n\tYou need to type the whole URL ie: http://www.google.com ") link_2 = raw_input("What would you like the Link 2 to display? ") link_1_src = raw_input("Where would you like the link to go?"+ "\n\tYou need to type the whole URL ie: http://www.google.com ") main_topic_title = raw_input("What would you like the Main Topic Title to display? ") sub_title = raw_input("What would you like the Sub Title to display? ") paragraph = raw_input("How would you like the Paragraph to read? ") question = raw_input("What would you like the Question to ask? ") option_1 = raw_input("What would you like Option 1 to be?") option_2 = raw_input("What would you like Option 2 to be?") footer = raw_input("What would you like the Footer to display? ") print """ Now we are going to create a text file which you need to open in notepad then save as a *.html file so you cab open it in a webrowser and view it """ name = raw_input("what would you like to name the file?"+ "( it should be something you can remember"+ " since you will have to reopen it several times.)"+ "*** It must end in .txt ***") matts_template = ["<html>", "<head>", "<title>" + title + "</title>", "</head>", "<body>", "<table width=\"100%\">", " <tr>", " <td>", " <table width=\"75%\" align=\"center\">", " <tr>", " <th bgcolor=\"66CCCC\">", "<h2>" + header + "</h2>", " </th>", " </tr>", " </table>", " </td>", " </tr>", " <tr>", " <td>", " <table width=\"20%\" align=\"left\">", " <tr>", " <td>", " <table width=\"100%\" align=\"top\" cellspacing=\"1\" bgcolor=\"#009999\">", " <tr>", " <td bgcolor=\"#66CCCC\">", "Navigation", " </td>", " </tr>", " <tr>", " <td bgcolor=\"#ACE6E6\">", "<a href=\"" + link_1_src + "\">" + link_1 +"</a><br>", "<a href=\"" + link_2_src + "\">" + link_2 +"</a><br>", " </td>", " </tr>", " </table>", " </td>", " </tr>", " </table>", " <table width=\"58%\" align=\"left\">", " <tr>", " <td>", " <table width=\"100%\" align=\"left\" cellspacing=\"1\" bgcolor=\"#009999\">", " <tr>", " <td bgcolor=\"#66CCCC\">", "<h3>" + main_topic_title + "</h3>", " </td>", " </tr>", " <tr>", " <td bgcolor=\"#ACE6E6\">", "" + sub_title + "<br><br>", "" + paragraph + "", " </td>", " </tr>", " </table>", " </td>", " </tr>", " </table>", " <table width=\"20%\" align=\"left\">", " <tr>", " <td>", " <table width=\"100%\" align=\"left\" cellspacing=\"1\" bgcolor=\"#009999\">", " <tr>", " <td bgcolor=\"#66CCCC\">", "Interact", " </td>", " </tr>", " <tr>", " <td bgcolor=\"#ACE6E6\">", ""+ question + "<br>", "<form>", "<input type=\"radio\" name=\"hot\">--" + option_1 + "<br>", "<input type=\"radio\" name=\"hot\">--" + option_2 + "<br>", "</form>", " </td>", " </tr>", " </table>", " </td>", " </tr>", " </table>", " </td>", " </tr>", " <tr>", " <td>", " <table width=\"75%\" align=\"center\">", " <tr>", " <th bgcolor=\"66CCCC\">", "<h2>" + footer + "</h2>", " </th>", " </tr>", " </table>", " </td>", " </tr>", "</table>", "</body>", "</html>"] text_file = open( name , "w") text_file.writelines(matts_template) text_file.close() raw_input("Thank You for making your own" \ +"proffessional web site with my editor.") From dyoo at hkn.eecs.berkeley.edu Mon Feb 9 12:39:20 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Feb 9 12:39:25 2004 Subject: [Tutor] question In-Reply-To: <001401c3ef15$557098a0$8c1d06d5@r5u0m4> Message-ID: <Pine.LNX.4.44.0402090935320.3569-100000@hkn.eecs.berkeley.edu> On Mon, 9 Feb 2004, Dennis wrote: > I work with Python 2.3.3 and I try to make a programme that saves words > in a dictionary. Hi Dennis, Have you looked at one of the tutorials in: http://www.python.org/topics/learn/non-prog.html yet? In particular, have you looked at Alan Gauld's "Learn to Program" tutorial site? http://www.freenetpages.co.uk/hp/alan.gauld/ He has a whole section on doing the sort of things that you're asking, with examples that should help you get started. If you have more questions, please feel free to ask. From Christian.Wyglendowski at greenville.edu Mon Feb 9 12:41:46 2004 From: Christian.Wyglendowski at greenville.edu (Christian Wyglendowski) Date: Mon Feb 9 12:41:51 2004 Subject: [Tutor] win32com manual Message-ID: <CE1475C007B563499EDBF8CDA30AB45B0A38BD@empex.greenville.edu> You already have somewhat of a list at your disposal. Alan mentioned the Object Browser in PythonWin. Once you have the display name (for lack of a better/correct term) of the COM interface you want to use, fire up "regedit" (at your own risk, of course ;-) and do a search for that string. For example, here is a COM interface I have never used and know nothing about (except what can be gathered from the name) that shows up in the PythonWin object browser: COM MakeCab 1.0 Type Library So how to access this via Python? Well, I search the registry hive HKEY_CLASSES_ROOT for values and data containing the term makecab. In a key named for the CLSID {8E17FFF3-...you get the picture} the ProgID key contains a default value with the following data: MakeCab.MakeCab.1 Two keys down there is a VersionIndependentProgID key with default value data of MakeCab.MakeCab. That's the one we want. In PythonWin, I try: >>> from win32com.client import Dispatch >>> c = Dispatch('MakeCab.MakeCab') >>> Success! But now, what do I do with it? If I really wanted to use this interface, I would have ran makepy on the MakeCab library so that I would get auto completion of methods/attributes and then do a google search for the interface's documentation. For Microsoft COM interfaces, http://msdn.microsoft.com is your friend. I hope this helps out. Christian http://www.dowski.com -----Original Message----- From: Shitiz Bansal [mailto:shitizb@yahoo.com] Sent: Sunday, February 08, 2004 6:25 AM To: tutor@python.org Subject: Re: [Tutor] win32com manual Hi, How about everyone mailing in the objects they are familiar with and their methods( for the uninitiated we are talking about the objects supported by Dispatch method in win32com). Then perhaps we could compile them in a single place and post them at python homepage, it could be a great tool for python programmers on windows. cyao shitiz Do you Yahoo!? Yahoo! Finance: Get your refund fast by filing online From project5 at redrival.net Mon Feb 9 12:38:58 2004 From: project5 at redrival.net (Andrei) Date: Mon Feb 9 12:42:08 2004 Subject: [Tutor] Re: question References: <001401c3ef15$557098a0$8c1d06d5@r5u0m4> Message-ID: <16nmvh88jsyut$.h2v1fcwmnkwh.dlg@40tude.net> Dennis wrote on Mon, 9 Feb 2004 15:02:18 +0100: > I work with Python 2.3.3 and I try to make a programme that saves > words in a dictionary. And because I'm not a Python expert I don't know > how to do it or witch command I need. Could you please send me an example > of this case? A dictionary looks like this: mydict = {} You can add a key-value pair to it like this: mydit["key"] = "value" For storing you should look into file(), str() and eval() - not particulary safe, but ok for private use - or something with pickle. Otherwise this sounds somewhat like a homework assignment, so I won't give full working code :). -- Yours, Andrei ===== Mail address in header catches spam. 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 magnus at thinkware.se Mon Feb 9 12:42:11 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Mon Feb 9 12:42:21 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gVXNpbmcgcHl0aG9uIGZvciBidWlsZGluZyBkeW5hbWljIHdlYnNpdGVz?= Message-ID: <think001_4027c610e42fe@webmail.thinkware.se> > Nevow, a replacement for Woven in twisted is coming along quite well. > > I > > didn't bother with all the other frameworks like pmz because I'm not > > allowed to install software on the host server, I can only use the > > preinstalled mod_python. I don't think Nevow will be useful unless you can set up a twisted server. -- 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 project5 at redrival.net Mon Feb 9 12:42:33 2004 From: project5 at redrival.net (Andrei) Date: Mon Feb 9 12:51:04 2004 Subject: [Tutor] Re: Question References: <20040206153558.10180.qmail@web20204.mail.yahoo.com> Message-ID: <7z2y1ys86iav$.1dvnkcw2bnyhu$.dlg@40tude.net> Nadine Rioux wrote on Fri, 6 Feb 2004 10:35:58 -0500 (EST): > We try to execute a .py file and we get this message : " Failed to import modules, reason : No module named _omnipy". > > NOTE : this our first expercience with Linux and Python... > > Could you help us? It means the script you're trying to execute tries to import (= use) a module (that's a Python file really) called _omnipy. I don't know what this is, but you should look in the docs of the program you're trying to run for where you can get it. -- Yours, Andrei ===== Mail address in header catches spam. 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 Mon Feb 9 12:41:00 2004 From: project5 at redrival.net (Andrei) Date: Mon Feb 9 13:00:45 2004 Subject: [Tutor] Re: all the slashes References: <4023BF79.9060106@ananzi.co.za> Message-ID: <1gc1res20bzu2.a7wjmtyoxi6s.dlg@40tude.net> Gerhard Venter wrote on Fri, 06 Feb 2004 16:23:21 +0000: > I use the code below in Python 2.3, but in 2.2 it says: > TypeError: 'in <string>' requires character as left operand > I have tried r'//', and '////' (to escape the slashes) to no avail. > How can I make this work in 2.2? > > myfile=open(r'/etc/sitelist','a') > if "//" in mystring: Use the find() method of mystring. -- Yours, Andrei ===== Mail address in header catches spam. 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 jmillr at umich.edu Mon Feb 9 13:10:13 2004 From: jmillr at umich.edu (John Miller) Date: Mon Feb 9 13:09:52 2004 Subject: [Tutor] Using python for building dynamic websites In-Reply-To: <E1AqEb0-0005Yz-N1@mail.python.org> References: <E1AqEb0-0005Yz-N1@mail.python.org> Message-ID: <3488F58A-5B2B-11D8-BF40-00039303967A@umich.edu> I suggest looking at Spyce, which works with modpython & fastcgi, and uses Cheetah for the templating: http://spyce.sourceforge.net/ John Miller On Feb 9, 2004, at 11:49 AM, "RenderPipe" <renderpipe@speedpost.net> wrote: > Yesterday I was looking around all of the options for building a > database > driven website with python and my head is spinning with all of the > options. I installed mod_python on my linux computer and ran the test > script in the manual and it works although it doesn't appear as > straight > forward as I thought. I'm starting to really like python and really > don't > want to go back to php unless I have to. > > Here's what I would like to do. > > Write my code in python. > Call a template file > Output the data from my python and template file to the browser > Some areas of the site I would like to output static html files from my > python/template code. From abli at freemail.hu Mon Feb 9 13:41:14 2004 From: abli at freemail.hu (Abel Daniel) Date: Mon Feb 9 13:42:07 2004 Subject: [Tutor] Re: all the slashes In-Reply-To: <4023BF79.9060106@ananzi.co.za> (Gerhard Venter's message of "Fri, 06 Feb 2004 16:23:21 +0000") References: <4023BF79.9060106@ananzi.co.za> Message-ID: <E1AqGLU-0000Pq-00@hooloovoo> Gerhard Venter writes: > Hi all > > I use the code below in Python 2.3, but in 2.2 it says: > TypeError: 'in <string>' requires character as left operand > I have tried r'//', and '////' (to escape the slashes) to no avail. > > myfile=open(r'/etc/sitelist','a') > if "//" in mystring: > Why would you need to escape it? >>> '/' in 'ab/c' True >>> '/' in 'abc' False >>> OTOH, if you would be looking for \ -s (backslashes) you would need to escape it: >>> '\' in 'ab\c' File "<stdin>", line 1 '\' in 'ab\c' ^ SyntaxError: invalid syntax >>> '\\' in 'ab\c' True >>> Plus, if you do use the code you showed, then you have a bug: your version is looking for '//' (two slashes) and not '/' (one slash). -- Abel Daniel From arkamir at softhome.net Mon Feb 9 14:02:32 2004 From: arkamir at softhome.net (Conrad Koziol) Date: Mon Feb 9 14:20:15 2004 Subject: [Tutor] regular expression/ reading a directory Message-ID: <1076353352.4954.5.camel@conradpc> I need to write a cross platform script which reads the directory and spits out files which only have 1 underscore and end in html. Equivelent to this in the bash shell: ll | grep ^[^_]*_[^_]*.css How would I do this? Is there anyway to specifically select only those files from a directory, something similiar to os.listdir() or is there a grep tool for python to match items in a list or dictionary to a regular expression. Also how would I run a shell script or another python program from inside another program. Thanks a lot!! Conrad From hcohen2 at comcast.net Mon Feb 9 15:06:49 2004 From: hcohen2 at comcast.net (hcohen2) Date: Mon Feb 9 15:09:47 2004 Subject: [Tutor] regular expression/ reading a directory In-Reply-To: <1076353352.4954.5.camel@conradpc> References: <1076353352.4954.5.camel@conradpc> Message-ID: <4027E859.7090404@comcast.net> Conrad, Not sure I should be answering this, but along the lines suggested: import re and at least part of the os module. [I used a series of files with extensions like: py* and I only had a couple with a '_' >>> for i in range(lenL): ... m = re.findall('_', dirList[i]) ... if len(m) == 1: ... print dirList[i] ... simple_qt.py~ simple_qt.py I believe findall gives a list of matching patterns in a list, hence, the use of len() to be assured none with 0 or greater than 1 appear. Remember to you have to set up your list of files: >>> dirList = listdir('/home/prime_dev/python_prog/chap18') >>> lenL = len(dirList) Herschel PS You should check the code carefully, though I did put an example with two underscores I still had a number of dumb flaws before it worked properly. Also your regular expression did not work the shell command line even removing the '.css'. Conrad Koziol wrote: >I need to write a cross platform script which reads the directory and >spits out files which only have 1 underscore and end in html. Equivelent >to this in the bash shell: > >ll | grep ^[^_]*_[^_]*.css > >How would I do this? Is there anyway to specifically select only those >files from a directory, something similiar to os.listdir() or is there a >grep tool for python to match items in a list or dictionary to a regular >expression. Also how would I run a shell script or another python >program from inside another program. > >Thanks a lot!! > Conrad > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > From magnus at thinkware.se Mon Feb 9 15:24:34 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Mon Feb 9 15:24:42 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gYWxsIHRoZSBzbGFzaGVzIA==?= Message-ID: <think001_4027eb5ade88e@webmail.thinkware.se> > I use the code below in Python 2.3, but in 2.2 it says: > TypeError: 'in <string>' requires character as left operand In python versions before 2.3, the in-operator required a character, i.e. a string of length 1, on the left hand side, if it had a string on the right hand side. Escaping is only relevant for back-slashes "\", since they have a special meaning, such as '\t' meaning the tab character. The traditional check for substring idiom before 2.3 was: if long_string.find(sub_string) != -1: # 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 magnus at thinkware.se Mon Feb 9 15:39:15 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Mon Feb 9 15:39:23 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gUHJpbnRpbmcgcHJvYmxlbQ==?= Message-ID: <think001_4027ecd0f21ac@webmail.thinkware.se> > Im aware of PrintOptions method. > For example: > to print a ppt presentation:i specify > ppt.ActivePresentation.PrintOptions.RangeType = 1 > ppt.ActivePresentation.PrintOptions.NumberOfCopies = 3 > ppt.ActivePresentation.PrintOptions.Collate = msoTrue > > What are the other options which i can specify using PrinOptions(i need many more like duplexing, no of pages per sheet etc.) > Can somebody provide me with a complete list. > Unfortunately its not there in the manuals/internet. These don't exist in Python or any Pytohn extension. They are part of the PowerPoint object model. You can probably find them in the Object Browser of the Visual Basic editor. Choose, Tools => Macro => Visual Basic Editor in PowerPoint. You find more help the usual way... (F1) Unfortunately, Macros seem to be disabled in PP where I am now, so that's as far as I get... -- 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 renderpipe at speedpost.net Mon Feb 9 16:53:10 2004 From: renderpipe at speedpost.net (RenderPipe) Date: Mon Feb 9 17:10:21 2004 Subject: [Tutor] Using python for building dynamic websites In-Reply-To: <think001_4027c10cbd1d4@webmail.thinkware.se> References: <think001_4027c10cbd1d4@webmail.thinkware.se> Message-ID: <1076363590.7286.180758440@webmail.messagingengine.com> > So far, so good. I assume you mean this: > http://www.modpython.org/live/current/doc-html/inst-testing.html Yeah, that's it. > How did you configure mod_python to support that kind of > code? I think you need to use the cgihandler to be able to > use "print" to show data, but your attempt to use the > request object, which you don't seem to have defined, makes > me guess that you have misunderstood something fundamental. I sure did misunderstand the fundamentals. I'm having a difficult time understanding the mod_python docs. I'll read it a couple of more times and pray that it sinks in. I found something that does almost what I want: http://htmltmpl.sourceforge.net/python.html I was able to create a python file and output the contents to html via a template. All I have left to do is figure out how I can grab data from a form, cookies and create paginated database results and I think I'll be all set. I think this is where mod_python comes into play. I did check out the other web applications like spyce and stuff. I'm not sure it's what I'm looking for but I'll try them out to be sure. Thanks to everyone for your feedback. Bobby -- http://www.fastmail.fm - Same, same, but different From amonroe at columbus.rr.com Mon Feb 9 17:43:55 2004 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Mon Feb 9 17:39:06 2004 Subject: [Tutor] question In-Reply-To: <001401c3ef15$557098a0$8c1d06d5@r5u0m4> References: <001401c3ef15$557098a0$8c1d06d5@r5u0m4> Message-ID: <4419127323.20040209174355@columbus.rr.com> > I work with Python 2.3.3 and I try to make a programme that saves > words in a dictionary. And because I'm not a Python expert I don't know > how to do it or witch command I need. Could you please send me an example > of this case? The only command you need is the good old equal sign. mydict = {} mydict['myword'] = 'myword' Alan From hcohen2 at comcast.net Mon Feb 9 17:59:04 2004 From: hcohen2 at comcast.net (hcohen2) Date: Mon Feb 9 18:02:08 2004 Subject: [Tutor] question In-Reply-To: <4419127323.20040209174355@columbus.rr.com> References: <001401c3ef15$557098a0$8c1d06d5@r5u0m4> <4419127323.20040209174355@columbus.rr.com> Message-ID: <402810B8.2090908@comcast.net> R. Alan Monroe wrote: >>I work with Python 2.3.3 and I try to make a programme that saves >>words in a dictionary. And because I'm not a Python expert I don't know >>how to do it or witch command I need. Could you please send me an example >>of this case? >> >> > >The only command you need is the good old equal sign. > >mydict = {} > >mydict['myword'] = 'myword' > > > > Alan, Nearly got it, but in a dictionary it is the dictionary key that is related to the value: mydict[ myKey] = 'myword', try this >>> mydict = {} >>> mydict['key_to_my'] = "myword or anybody's word" >>> mydict {'key_to_my': "myword or anybody's word"} Notice I used the double quote, because I used the single quote in the string. That should help. Herschel PS Read a bit about dictionaries: http://www.freenetpages.co.uk/hp/alan.gauld/ and check out http://www.python.org/topics/learn and a book I can suggest that will keep you busy: 'Learning Python - Second Edition' (I think I will be buying a copy soon though I own a coy of the first ed.). From bgailer at alum.rpi.edu Mon Feb 9 19:56:53 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon Feb 9 19:57:06 2004 Subject: {Spam?} [Tutor] Can you help me figure out what the problem is? In-Reply-To: <000801c3ec47$eeb8d6b0$eb316b18@yourgv9eh6ors1> References: <000801c3ec47$eeb8d6b0$eb316b18@yourgv9eh6ors1> Message-ID: <6.0.0.22.0.20040209125127.01d9b260@mail.mric.net> Skipped content of type multipart/alternative-------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.580 / Virus Database: 367 - Release Date: 2/6/2004 From kiran at mhowlinux.org Tue Feb 10 02:51:31 2004 From: kiran at mhowlinux.org (kiran@mhowlinux.org) Date: Tue Feb 10 02:52:06 2004 Subject: [Tutor] Can you help me figure out what the problem is? Message-ID: <004701c3efaa$b76da1c0$5b2fe2dc@VULCAN> hi, you haven't defined " link_2_src" you have taken the input for link_1_src but not link_2_src its none type u shud be initialising all strings to " " rather than None to check simply put link_2_src="" -kiran > > Message: 8 > Date: Thu, 5 Feb 2004 18:26:55 -0600 > From: "matthew mazzola" <mdmazzola@charter.net> > Subject: > To: <tutor@python.org> > Message-ID: <000801c3ec47$eeb8d6b0$eb316b18@yourgv9eh6ors1> > Content-Type: text/plain; charset="iso-8859-1" > > I am trying to make a web page editor program. It's really simple so i think someone experience would be able to fix it easily. The file is attached and copied on the bottom of this email but make sure your window is maximized or it'll ruin formatting. It complains with: > > Traceback (most recent call last): > File "<string>", line 1, in ? > File "C:\Python22\webpage_editor.py", line 82, in ? > matts_template = ["<html>", > TypeError: cannot concatenate 'str' and 'NoneType' objects > > > The File Source: > > -------------------------------------------------------------------------- ------------------------------------------------------------- > > # Make Your Own Webpage > # THIS IS MINE I MADE IT ALL MINE > # Matt Mazzola - 2/4/04 > > #Welcome User > print "\t Welcome to Matt Mazzola's\n\t\t-----------\n\t\tWeb Page Editor" > > #Ask them what they want to have on their Page by main elemts > raw_input("press enter to see the layout of the page...") > print \ > """ > Here is the layout of your page. > > (Pay attention to the sections of the page > because you will later be asked what you > want in those sectoins.) > Also, rember title is the what you want the window title bar to display > and background is the color of the web page backgroud. > """ > > layout = """ > title/background > +----------------------------------------------------------------------+ > | Header | > +----------------------------------------------------------------------+ > +-----------------+ +-----------------------------+ +------------------+ > | Navigation | | Main Topic Title | | Interaction | > +-----------------+ +-----------------------------+ +------------------+ > |link 1 | | Sub Title | | Questoin for poll| > |link 2 | | paragraph | | form for poll | > +-----------------+ +-----------------------------+ +------------------+ > +----------------------------------------------------------------------+ > | Footer | > +----------------------------------------------------------------------+ > """ > print layout > > > > Beware the lollipop of mediocrity: lick it once and you suck forever www.mhowlinux.org Helping Linux users in Mhow hi, you haven't defined " link_2_src" you have taken the input for link_1_src but not link_2_src its none type u shud be initialising all strings to " " rather than None to check simply put link_2_src="" -kiran > > Message: 8 > Date: Thu, 5 Feb 2004 18:26:55 -0600 > From: "matthew mazzola" <mdmazzola@charter.net> > Subject: > To: <tutor@python.org> > Message-ID: <000801c3ec47$eeb8d6b0$eb316b18@yourgv9eh6ors1> > Content-Type: text/plain; charset="iso-8859-1" > > I am trying to make a web page editor program. It's really simple so i think someone experience would be able to fix it easily. The file is attached and copied on the bottom of this email but make sure your window is maximized or it'll ruin formatting. It complains with: > > Traceback (most recent call last): > File "<string>", line 1, in ? > File "C:\Python22\webpage_editor.py", line 82, in ? > matts_template = ["<html>", > TypeError: cannot concatenate 'str' and 'NoneType' objects > > > The File Source: > > -------------------------------------------------------------------------- ------------------------------------------------------------- > > # Make Your Own Webpage > # THIS IS MINE I MADE IT ALL MINE > # Matt Mazzola - 2/4/04 > > #Welcome User > print "\t Welcome to Matt Mazzola's\n\t\t-----------\n\t\tWeb Page Editor" > > #Ask them what they want to have on their Page by main elemts > raw_input("press enter to see the layout of the page...") > print \ > """ > Here is the layout of your page. > > (Pay attention to the sections of the page > because you will later be asked what you > want in those sectoins.) > Also, rember title is the what you want the window title bar to display > and background is the color of the web page backgroud. > """ > > layout = """ > title/background > +----------------------------------------------------------------------+ > | Header | > +----------------------------------------------------------------------+ > +-----------------+ +-----------------------------+ +------------------+ > | Navigation | | Main Topic Title | | Interaction | > +-----------------+ +-----------------------------+ +------------------+ > |link 1 | | Sub Title | | Questoin for poll| > |link 2 | | paragraph | | form for poll | > +-----------------+ +-----------------------------+ +------------------+ > +----------------------------------------------------------------------+ > | Footer | > +----------------------------------------------------------------------+ > """ > print layout > > > > Beware the lollipop of mediocrity: lick it once and you suck forever www.mhowlinux.org Helping Linux users in Mhow From roypython at hotmail.com Tue Feb 10 16:03:21 2004 From: roypython at hotmail.com (roy ollis) Date: Tue Feb 10 16:03:30 2004 Subject: [Tutor] python homework Message-ID: <BAY2-F255MAXrrUeAlT00008029@hotmail.com> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040210/e8b8f9d6/attachment.html From hcohen2 at comcast.net Tue Feb 10 15:59:08 2004 From: hcohen2 at comcast.net (hcohen2) Date: Tue Feb 10 16:06:54 2004 Subject: [Tutor] How can I search the Tutor archives when I do not know the ... Message-ID: <4029461C.40608@comcast.net> Problem: I would like to find a tutor question I probably deleted and since I have been cleaning my email folder from more than 700 to significantly less than 300 in the past few days (and keeping it there). I am unsure how old this message really was. I tried using the suggested Active Python Docs, but as usual the results were problematical, i.e. too old and not from the Tutor. Going directly to python.org search was really not much better. I think the message had a question about PyQt, but I do not now remember that being in the title. Hence, trying to find the single message by search by eye on the subject line will probably fail. [I was doing that a few days ago by thread and subject and still missed finding (until just now!) a thread on regular expressions. My email seems only to support by subject or sender not content. Thanks for whatever suggestions you have. From pythontutor at venix.com Tue Feb 10 16:19:01 2004 From: pythontutor at venix.com (Lloyd Kvam) Date: Tue Feb 10 16:19:11 2004 Subject: [Tutor] How can I search the Tutor archives when I do not know the ... In-Reply-To: <4029461C.40608@comcast.net> References: <4029461C.40608@comcast.net> Message-ID: <40294AC5.1000101@venix.com> pyqt site:mail.python.org used this on Google and got back 1490 results. presumably adding another word or two would get this down to something manageable. it will return more than just the tutor list, but should be pretty well focused on the python lists. hcohen2 wrote: > Problem: I would like to find a tutor question I probably deleted and > since I have been cleaning my email folder from more than 700 to > significantly less than 300 in the past few days (and keeping it > there). I am unsure how old this message really was. > > I tried using the suggested Active Python Docs, but as usual the results > were problematical, i.e. too old and not from the Tutor. Going directly > to python.org search was really not much better. > > I think the message had a question about PyQt, but I do not now remember > that being in the title. Hence, trying to find the single message by > search by eye on the subject line will probably fail. [I was doing that > a few days ago by thread and subject and still missed finding (until > just now!) a thread on regular expressions. > > My email seems only to support by subject or sender not content. > > Thanks for whatever suggestions you have. > > > _______________________________________________ > 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 from_python_tutor at SSokolow.com Tue Feb 10 16:26:15 2004 From: from_python_tutor at SSokolow.com (SSokolow) Date: Tue Feb 10 16:26:20 2004 Subject: [Tutor] python homework In-Reply-To: <BAY2-F255MAXrrUeAlT00008029@hotmail.com> References: <BAY2-F255MAXrrUeAlT00008029@hotmail.com> Message-ID: <40294C77.7040101@SSokolow.com> The language doesn't change that quickly and once you know one, it's a lot easier to learn more if you so choose. You just have to get used to the concepts and methods of thinking which they all have in common. It's really simple after that. In my experience, the biggest problem is deciding what kind of thing to practice. All the little exercises are so useless that I find myself setting too big a challenge. If you can solve that problem, then it doesn't matter how little time you have to learn. roy ollis wrote: > i notice quite a few requests are answered "study more. you dont > learn by someone else doing your work" etc. where are all these > classes and how can i find one to sign up for? self learning with > little time isn't going very well, and it'll probably take me so long > to learn the python language it will have changed so that all i know > is how it used to work. thanks for any help. > > ------------------------------------------------------------------------ > Check out the great features of the new MSN 9 Dial-up, with the MSN > Dial-up Accelerator. <http://g.msn.com/8HMAENUS/2734??PS=> > >------------------------------------------------------------------------ > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > From hcohen2 at comcast.net Tue Feb 10 16:30:47 2004 From: hcohen2 at comcast.net (hcohen2) Date: Tue Feb 10 16:41:39 2004 Subject: [Tutor] How can I search the Tutor archives when I do not know the ... In-Reply-To: <40294AC5.1000101@venix.com> References: <4029461C.40608@comcast.net> <40294AC5.1000101@venix.com> Message-ID: <40294D87.9040907@comcast.net> Lloyd Kvam wrote: > pyqt site:mail.python.org > > used this on Google and got back 1490 results. presumably adding another > word or two would get this down to something manageable. it will > return more than just the tutor list, but should be pretty well focused > on the python lists. > Thanks - down to 129, which is much less than reading through the threads on the archive by each month as I was doing! From eculpepper at hcc-care.com Tue Feb 10 17:26:11 2004 From: eculpepper at hcc-care.com (Eric Culpepper) Date: Tue Feb 10 17:23:20 2004 Subject: [Tutor] newbie question about grep in Python Message-ID: <48CA63C679F03D4187762B7CE066AAD2767AE3@hccexchange.hcccorp.hcc-care.com> I'm trying my best to learn Python and I'm going through some shell scripts attempting to write Python versions of these scripts. I stumbled on this piece of a script and I'm struggling to figure out a method of doing this in Python. #!/bin/sh o_date=`strings /shc1/$1/$2 2> /dev/null | grep Date | egrep "\#V\#|\@\(\#\)" \ | sed 's/^\\$//' | awk 'BEGIN {FS="$"} {printf("%s\n",substr($2,6))}'` echo "o_date is $o_date" This hack-job script is used to look at compiled programs and get pull the last modified date from them. Here's a sample output from strings parsing one of these files. (In particular the date field between the #V# and #V# is the date I'm interested in.) cAModule $Header:rxrmon.s, 59, 1/8/04 3:38:55 PM, Roxanne Curtiss$ c SCCS Library $Workfile:rxrmon.s$ Version $Revision:59$ Date $Date:1/8/04 3:38:55 PM$ #V#$Revision:59$#V# #V#$Date:1/8/04 3:38:55 PM$#V# - RXRMON - 2jan87 - RM I've looked through the Regular Expression HOWTO, python.org's searchable website and I must be missing the forest because of the trees because I can't seem to wrap my mind around doign this in Python. Any tips or suggestions would be very very helpful! Thanks Eric Culpepper -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040210/ef8c55d5/attachment.html From hcohen2 at comcast.net Tue Feb 10 17:26:43 2004 From: hcohen2 at comcast.net (hcohen2) Date: Tue Feb 10 17:29:54 2004 Subject: [Tutor] How can I search the Tutor archives when I do not know the ... In-Reply-To: <40295A03.8000608@venix.com> References: <4029461C.40608@comcast.net> <40294AC5.1000101@venix.com> <40294D87.9040907@comcast.net> <40295A03.8000608@venix.com> Message-ID: <40295AA3.5060800@comcast.net> Lloyd Kvam wrote: > I discovered (after posting) that adding tutor, will catch the [tutor] in > the subjects so that you stay mostly in the tutor list. > Thanks, that's what I have been doing. So far not finding the message I am seeking nor running across those that might be using PyQt under Linux. May just combine the latter two and see what that gets me. Lloyd - thanks again for your suggestions. From rmkrauter at yahoo.com Tue Feb 10 18:52:14 2004 From: rmkrauter at yahoo.com (Rich Krauter) Date: Tue Feb 10 18:57:20 2004 Subject: [Tutor] newbie question about grep in Python In-Reply-To: <48CA63C679F03D4187762B7CE066AAD2767AE3@hccexchange.hcccorp.hcc-care.com> References: <48CA63C679F03D4187762B7CE066AAD2767AE3@hccexchange.hcccorp.hcc-care.com> Message-ID: <1076457134.8127.31.camel@vaio> On Tue, 2004-02-10 at 17:26, Eric Culpepper wrote: > I'm trying my best to learn Python and I'm going through some shell > scripts attempting to write Python versions of these scripts. I > stumbled on this piece of a script and I'm struggling to figure out a > method of doing this in Python. > > #!/bin/sh > o_date=`strings /shc1/$1/$2 2> /dev/null | grep Date | egrep > "\#V\#|\@\(\#\)" \ > | sed 's/^\\$//' | awk 'BEGIN {FS="$"} > {printf("%s\n",substr($2,6))}'` > echo "o_date is $o_date" > Here's a first attempt. Others will have better ideas: import re import struct import sys if __name__ == '__main__': pat = re.compile(r'#V#\$Date:(.+?)\$#V#') for f in sys.argv[1:]: mystr = '' fobj = open(f,'r') while 1: buf = fobj.read(1024) if not buf: break fmt = '%ss'%len(buf) mystr += str(struct.unpack(fmt,buf)) fobj.close() mobj = re.search(pat,mystr) if mobj is not None: print 'Found %s in %s'%(mobj.group(1),f) In words: I construct my pattern (which may be too restrictive). I then loop over the input files, opening each. While I can read bytes into a buffer, I see how long the buffer is and use that length as my format string argument to sruct.unpack, along with the 's' format specifier. I build up mystr, using concatenation, from the unpacked chucks of the file I read in. Once I have my complete string, I close the file and try to create a match object. If the match succeeds, I print out what I find. Probably not the best way to do it, but perhaps it's a starting point. I'd appreciate suggestions for improvement. Thanks. Rich From sigurd at 12move.de Tue Feb 10 19:25:10 2004 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Tue Feb 10 19:25:56 2004 Subject: [Tutor] newbie question about grep in Python In-Reply-To: <48CA63C679F03D4187762B7CE066AAD2767AE3@hccexchange.hcccorp.hcc-care.com> (Eric Culpepper's message of "Tue, 10 Feb 2004 16:26:11 -0600") References: <48CA63C679F03D4187762B7CE066AAD2767AE3@hccexchange.hcccorp.hcc-care.com> Message-ID: <m34qtyikj3.fsf@hamster.pflaesterer.de> On 10 Feb 2004, Eric Culpepper <- eculpepper@hcc-care.com wrote: > I'm trying my best to learn Python and I'm going through some shell scripts > attempting to write Python versions of these scripts. I stumbled on this piece > of a script and I'm struggling to figure out a method of doing this in Python. You know that sometimes a shell script is the best tool for such jobs so Python won't show all its beauty there. > #!/bin/sh > o_date=`strings /shc1/$1/$2 2> /dev/null | grep Date | egrep "\#V\#|\@\(\#\)" \ > | sed 's/^\\$//' | awk 'BEGIN {FS="$"} {printf("%s\n",substr($2,6))}'` > echo "o_date is $o_date" That has nothing to do with Python but the script is unnecessary complicated: just pipe the output from strings directly to awk; use a pattern like awk -F "$" /^\#V\#\$Date:.*\$\#V\#/ { print substr(gensub(/[a-zA-Z]+/, "", "g", $2), 2) } might do the job (it might possible to write it shorter if I knew better which kind of patterns may arise but that's not the point here). Write it as shell function and you're fine. Back to Python: [...] > cAModule $Header:rxrmon.s, 59, 1/8/04 3:38:55 PM, Roxanne Curtiss$ > c SCCS Library $Workfile:rxrmon.s$ > Version $Revision:59$ > Date $Date:1/8/04 3:38:55 PM$ > #V#$Revision:59$#V# > #V#$Date:1/8/04 3:38:55 PM$#V# > - RXRMON - 2jan87 - RM If the output looks always like that (beginning with #V# and ending with it) you could write: ******************************************************************** import os, sys, re fil = sys.argv[1] reg = re.compile('#V#\$Date:(.*)#V#') strings = os.popen('strings ' + fil) for line in strings: m = reg.search(line) if m: print re.sub('[a-zA-Z$]', '', m.groups()[0]) break strings.close() ******************************************************************** Above opens a pipe to the output from strings (you call that script with one argument: the name of the file to parse); it iterates over the lines, tries to find one which matches the given regexp (it looks a bit like the one you used for egrep); if a match is found, we have a match object; its groups() method returns a tuple with the matching groups of the regexp (we have here only one group, the part in parentheses). The group encloses some strings we don't want; they are replaced and the changed string is printed. If a more specifical regexp is possible the need to change the group may escape. But again: that's not the primary target of Python. Hacking on he command line is sometimes better with awk, sed and friends. Karl -- Please do *not* send copies of replies to me. I read the list From csm1 at academicplanet.com Wed Feb 11 00:03:58 2004 From: csm1 at academicplanet.com (Chuck Marshall) Date: Wed Feb 11 00:03:39 2004 Subject: [Tutor] very basic question from a newbie Message-ID: <001201c3f05c$76a3a740$afac5a42@oemcomputer> I just read "IDLE Introduction --- One Day of IDLE Toying". It was great because it was so basic and helped me get started. My first couple of test "modules" ran just fine, but all of a sudden IDLE started "hanging" for a long time every time I click on "Run Module". Just running the following module seems to freeze the video on my computer for about 15 seconds. print "hello world" print "here are the ten numbers from 0 to 9" for i in range(10): print i, print "I'm done!" Even the menus in the Python Shell window and the new file window seem to sort of open slowly and "unsmoothly". One thing I noticed is that every time I run the module the shell displays this: >>> ================================ RESTART ================================ >>> hello world here are the ten numbers from 0 to 9 0 1 2 3 4 5 6 7 8 9 I'm done! >>> I only ran the module a few times before this problem started, but I don't think the -----RESTART---- line was appearing at first, but I could be wrong. I read (http://www.python.org/doc/faq/windows.html) that anti-virus software might cause Python to start slowly. I disabled my anti-virus software, but I'm still having the same problem. I've even rebooted my PC a couple of times. Any suggestions? Late-breaking development..... Just as I was finishing this email I tried running the scripts again, and now they're running normally! And I was right, the ---RESTART---- thing isn't happening now, *and* the menus are opening normally too! Can someone please explain to me what is going on? Thanks, Chuck -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040210/b3bc81aa/attachment-0001.html From aluticus at gmx.net Wed Feb 11 05:14:50 2004 From: aluticus at gmx.net (Andrei) Date: Wed Feb 11 05:15:10 2004 Subject: [Tutor] killing processes on win xp Message-ID: <001601c3f087$e4f30990$e90f07c3@home6nvijh5cxa> Hi, I'm using: import win32pdh junk, instances = win32pdh.EnumObjectItem(None,None,"Process",win32pdh.PERF_DETAIL_WIZARD) print instances to get a list of the running process on my PC. Then I try to kill a process using the function I found python\lib\site-packages\win32\scripts\killprocName: import win32api, win32pdhutil, win32con, sys def killProcName(procname): # Change suggested by Dan Knierim, who found that this performed a # "refresh", allowing us to kill processes created since this was run # for the first time. try: win32pdhutil.GetPerformanceAttributes('Process','ID Process',procname) except: pass pids = win32pdhutil.FindPerformanceAttributesByName(procname) # If _my_ pid in there, remove it! try: pids.remove(win32api.GetCurrentProcessId()) except ValueError: pass if len(pids)==0: result = "Can't find %s" % procname elif len(pids)>1: result = "Found too many %s's - pids=`%s`" % (procname,pids) else: handle = win32api.OpenProcess(win32con.PROCESS_TERMINATE, 0,pids[0]) win32api.TerminateProcess(handle,0) win32api.CloseHandle(handle) result = "" return result The problem is that if there are many users logged on and I try to kill a process launched by other user, inactive in that moment I get this error: Traceback (most recent call last): File "<pyshell#1>", line 1, in ? killProcName('notepad') File "C:\Python23\Lib\site-packages\win32\scripts\killProcName.py", line 38, in killProcName handle = win32api.OpenProcess(win32con.PROCESS_TERMINATE, 0,pids[0]) error: (5, 'OpenProcess', 'Access is denied.') Is there a way to kill a process on win xp indifferently which user started that process and without being active as that user? Thank you and sorry for the poor English -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040211/9d1ab906/attachment.html From eculpepper at hcc-care.com Wed Feb 11 10:59:10 2004 From: eculpepper at hcc-care.com (Eric Culpepper) Date: Wed Feb 11 10:56:20 2004 Subject: [Tutor] newbie question about grep in Python Message-ID: <48CA63C679F03D4187762B7CE066AAD2767AEF@hccexchange.hcccorp.hcc-care.com> -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org]On Behalf Of Karl Pfl?sterer Sent: Tuesday, February 10, 2004 6:25 PM To: tutor@python.org Subject: Re: [Tutor] newbie question about grep in Python Thanks for the replies everyone! I really appreciate the direction >You know that sometimes a shell script is the best tool for such jobs so >Python won't show all its beauty there. I totally agree with this, the Company is wanting to take these scripts and take them cross-platform, the thought was at first to use Cygwin on the Windows platforms and leaving the scripts as is, but now Management is wanting the scripts to do more and more so Python started to look as a possible solution for a cross-platform scripting/programming language. I took your script and changed it slightly to parse the entire directory in one go, granted I'm still learning this, but I'm getting the output I wanted and can move forward now. Here's my version of the script incase anyone can suggest further improvements ------------------------------- #!/usr/local/bin/python import os, re path = "/shc1/p" reg = re.compile('#V#\$Date:(.*)#V#') for root,dirs,files in os.walk(path): for name in files: ffile = path + "/" + name strings = open(ffile,'r').read() m = reg.search(strings) if m: print ffile, "Date:", re.sub('[a-zA-Z$]', '', m.groups()[0]) Thanks again! Eric Culpepper From rha207 at worldnet.att.net Wed Feb 11 11:31:14 2004 From: rha207 at worldnet.att.net (Ron Alvarado) Date: Wed Feb 11 11:27:40 2004 Subject: [Tutor] very basic question from a newbie Message-ID: <000501c3f0bc$7bb54120$0b394b0c@computer> Even the menus in the Python Shell window and the new file window seem to sort of open slowly and "unsmoothly". One thing I noticed is that every time I run the module the shell displays this: >>> ================================ RESTART ================================ >>>>>>>>>>>>>>>>>>>>>>>>>> I'm having the same problem. I tried disabling antivirus but it didn't help. If anyone has any other ideas let me know. Ron A From magnus at thinkware.se Wed Feb 11 12:49:44 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Wed Feb 11 12:50:04 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gdmVyeSBiYXNpYyBxdWVzdGlvbiBmcm9tIGEgbmV3Ymll?= Message-ID: <think001_402a65b94a316@webmail.thinkware.se> > I just read "IDLE Introduction --- One Day of IDLE Toying". It was great because it was so basic and helped me get started. My first couple of test "modules" ran just fine, but all of a sudden IDLE started "hanging" for a long time every time I click on "Run Module". Just running the following module seems to freeze the video on my computer for about 15 seconds. In my experience, IDLE gets slow if there is a lot of data, particularly long lines of text, in the interactive interpreter window. It doesn't matter if this text is far out of sight. I assume this is a "feature" of the underlying Tk GUI. I.e. if you have done something like calculated the factorial of large numbers over and over again, or done prints in long loops etc, you can expect IDLE to be slow until you restart it. >From Python 2.3 under Windows I also feel that I've had problems with dead (or at least lost) python or pythonw processes floating around. If you are using Windows NT / 2000 / XP you can use the task manager to see these (under the processes tab) and kill them. Just don't kill your current IDLE editor window if you have unsaved work. :) There are other Python IDEs and editors than IDLE. The selection depends on your OS. For instance, on Windows there is PythonWin which comes with the win32all extensions, and is included in ActivePython. See http://www.python.org/cgi-bin/moinmoin/PythonEditors and http://www.python.org/cgi-bin/moinmoin/IntegratedDevelopmentEnvironments for plenty of other examples. You probably get the best performance if you run Python scripts from your command line. I often have a Command Prompt (cmd.exe) open in Windows and start my program from there after having saved in the editor. Restarting after a new editing cycle is just a matter of saving in the editor, swapping to the command prompt with Alt-Tab and pressing Up-Arrow follows by Enter. > >>> ================================ RESTART ================================ This is a feature! Previous versions of IDLE ran your script in the same process as the IDLE GUI, and this caused a lot of problems. For instance, it was impossible to run most Python GUI programs from inside IDLE, and modified modules used by your script wouldn't be reloaded as expected etc. Restart is your friend! :) > I only ran the module a few times before this problem started, but I don't think the -----RESTART---- line was appearing at first, but I could be wrong. If you start IDLE by right-clicking a file in the explorer, and choose "Edit with IDLE", you will get a single process version of IDLE, where the restart thing doesn't work. I don't know why they have done it like that. If you start IDLE from the Start menu, and open your programs from within IDLE, you will get the restart behaviour. It seems you have a real resource problem on your computer if it seems expensive to start a new process when you run a script, but check with the task manager to see if there are old python processes hanging around... -- 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 abeidson at sbcglobal.net Wed Feb 11 13:13:56 2004 From: abeidson at sbcglobal.net (Andrew Eidson) Date: Wed Feb 11 13:14:11 2004 Subject: [Tutor] Pulling data from a DBaseIV file Message-ID: <20040211181356.89318.qmail@web80105.mail.yahoo.com> Ok.. I have search the web and can not seem to find my answer.. I want to pull data from a DBaseIV file and convert it to a tab delimited file.. I have found PyxBase but it will not install for me.. is this functionality built into 2.3.3 or is there another way of accessing a DBF file in python?? I found an old thead in the Tutor archive but the link that was presented was dead.. Thanks Andy -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040211/c818f3a9/attachment.html From pythontutor at venix.com Wed Feb 11 14:23:07 2004 From: pythontutor at venix.com (Lloyd Kvam) Date: Wed Feb 11 14:23:16 2004 Subject: [Tutor] Pulling data from a DBaseIV file In-Reply-To: <20040211181356.89318.qmail@web80105.mail.yahoo.com> References: <20040211181356.89318.qmail@web80105.mail.yahoo.com> Message-ID: <402A811B.5040504@venix.com> I needed to do something similar a couple of years ago. I downloaded a module from (I think) Vaults of Parnassus. It decoded the dBase header structure OK, but was clumsy to use. I reworked it for my purposes. I'll send you my reworked code (off-list). You should be able to turn it into something useful without too much grief. Andrew Eidson wrote: > Ok.. I have search the web and can not seem to find my answer.. I want > to pull data from a DBaseIV file and convert it to a tab delimited > file.. I have found PyxBase but it will not install for me.. is this > functionality built into 2.3.3 or is there another way of accessing a > DBF file in python?? I found an old thead in the Tutor archive but the > link that was presented was dead.. > > Thanks > Andy > > > > > ------------------------------------------------------------------------ > > _______________________________________________ > 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 bgailer at alum.rpi.edu Wed Feb 11 14:32:02 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed Feb 11 14:32:17 2004 Subject: [Tutor] Pulling data from a DBaseIV file In-Reply-To: <20040211181356.89318.qmail@web80105.mail.yahoo.com> References: <20040211181356.89318.qmail@web80105.mail.yahoo.com> Message-ID: <6.0.0.22.0.20040211113154.036afc00@mail.mric.net> At 10:13 AM 2/11/2004, Andrew Eidson wrote: >Ok.. I have search the web and can not seem to find my answer.. I want to >pull data from a DBaseIV file and convert it to a tab delimited file.. I >have found PyxBase but it will not install for me.. is this functionality >built into 2.3.3 or is there another way of accessing a DBF file in >python?? I found an old thead in the Tutor archive but the link that was >presented was dead.. ODBC? >Thanks >Andy > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From abeidson at sbcglobal.net Wed Feb 11 14:33:36 2004 From: abeidson at sbcglobal.net (Andrew Eidson) Date: Wed Feb 11 14:33:41 2004 Subject: [Tutor] Pulling data from a DBaseIV file In-Reply-To: <402A811B.5040504@venix.com> Message-ID: <20040211193336.73898.qmail@web80106.mail.yahoo.com> Thanks.. I will take a look and see if I can get it to do what I want.. be ready for a flurry of questions though since I am still relatively new to programming as well as python. From jtk at yahoo.com Wed Feb 11 14:59:51 2004 From: jtk at yahoo.com (Jeff Kowalczyk) Date: Wed Feb 11 14:58:53 2004 Subject: [Tutor] time arithmetic with 2.3 datetime module Message-ID: <pan.2004.02.11.19.59.50.926090@yahoo.com> Embarrassing to ask, but I can't quite figure 'time differences' with the 2.3 datetime module. Every google link points to a copy of the docs, no tutorials on the new functionality. Every effort I make with timedelta or time arithmetic eventually goes awry with TypeError: unsupported type for timedelta seconds component: datetime.time I have a simple timecard input of strings: date, start, end = '20040206', '10:30', '17:45' After I parse out the date string: y,m,d = d[:4],d[4:6],d[6:] I want to make two times from the 24h time strings, combining with the shared parsed date if necessary, and return the difference in floating point (e.g. 7.25). Can anyone suggest the most expedient way to do this? Thanks. From abeidson at sbcglobal.net Wed Feb 11 15:09:12 2004 From: abeidson at sbcglobal.net (Andrew Eidson) Date: Wed Feb 11 15:09:18 2004 Subject: [Tutor] Pulling data from a DBaseIV file In-Reply-To: <6.0.0.22.0.20040211113154.036afc00@mail.mric.net> Message-ID: <20040211200912.23283.qmail@web80105.mail.yahoo.com> The ODBC information I find only pertains to SQL based systems.. I have not been able to find any information for a DbaseIV file.. From bgailer at alum.rpi.edu Wed Feb 11 16:43:21 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed Feb 11 16:43:24 2004 Subject: {Spam?} Re: [Tutor] Pulling data from a DBaseIV file In-Reply-To: <20040211200912.23283.qmail@web80105.mail.yahoo.com> References: <6.0.0.22.0.20040211113154.036afc00@mail.mric.net> <20040211200912.23283.qmail@web80105.mail.yahoo.com> Message-ID: <6.0.0.22.0.20040211131711.01d51870@mail.mric.net> At 12:09 PM 2/11/2004, Andrew Eidson wrote: >The ODBC information I find only pertains to SQL based >systems.. I have not been able to find any information >for a DbaseIV file.. What operating system? If windows, you can set up an ODBC for dBase using the data sources applet. Let's say you call it "boreland". Then: import odbc conn = odbc.odbc('boreland') cursor = conn.cursor() cursor.execute('select * from table') rows = cursor.fetchall() Now you have a sequence of rows, each row being a sequence of columnvalues There is, as I recall, a CSV module that will create CSV files. Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From rha207 at worldnet.att.net Wed Feb 11 17:25:18 2004 From: rha207 at worldnet.att.net (Ron Alvarado) Date: Wed Feb 11 17:21:37 2004 Subject: [Tutor] readline() problem Message-ID: <000501c3f0ed$eeb28c60$4a394b0c@computer> Here's what I'm getting when I try readline(). What an I doing wrong? >>> data = open('bData.csv', 'r') >>> num = True >>> while num != "": data = data.readline() print data Part number Description Item Cost 1104 1105 1118 Traceback (most recent call last): File "<pyshell#7>", line 2, in -toplevel- data = data.readline() AttributeError: 'str' object has no attribute 'readline' >>> From hcohen2 at comcast.net Wed Feb 11 17:28:50 2004 From: hcohen2 at comcast.net (hcohen2) Date: Wed Feb 11 17:32:02 2004 Subject: [Tutor] readline() problem In-Reply-To: <000501c3f0ed$eeb28c60$4a394b0c@computer> References: <000501c3f0ed$eeb28c60$4a394b0c@computer> Message-ID: <402AACA2.8080901@comcast.net> Ron Alvarado wrote: >Here's what I'm getting when I try readline(). What an I doing wrong? > > > >>>>data = open('bData.csv', 'r') >>>>num = True >>>>while num != "": >>>> >>>> > data = data.readline() > print data > > When you openned the file, data was the file handle which you have confused it with a string value of the same name. Since data types are dynamic in Python your file handle value is lost. try str_data = data.readline() print str_data both that line and the print should be to the right of the 'while ...' > >Part number Description Item Cost 1104 1105 1118 > > >Traceback (most recent call last): > File "<pyshell#7>", line 2, in -toplevel- > data = data.readline() >AttributeError: 'str' object has no attribute 'readline' > > > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > From marilyn at deliberate.com Wed Feb 11 17:33:49 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Wed Feb 11 17:33:55 2004 Subject: [Tutor] readline() problem In-Reply-To: <000501c3f0ed$eeb28c60$4a394b0c@computer> Message-ID: <Pine.LNX.4.44.0402111426250.11161-100000@Kuna> On Wed, 11 Feb 2004, Ron Alvarado wrote: > Here's what I'm getting when I try readline(). What an I doing wrong? > > >>> data = open('bData.csv', 'r') > >>> num = True > >>> while num != "": > data = data.readline() > print data The first call to data.readline() will read the first line of the file, make a string of it, and then rename 'data' to be that string/line. From then on, all is lost because you have lost your identifier that points to the file. Next time around the loop, 'data' is that last line/string and it doesn't know anything about the file or 'readline'. The best solution is to rename the file: file = open('bData.csv', 'r') num = True while num != "": data = file.readline() print data However, this will cause an infinite loop because num never becomes "". So you still have a problem to work out. Good luck! Marilyn Davis > > > Part number Description Item Cost 1104 1105 1118 > > > Traceback (most recent call last): > File "<pyshell#7>", line 2, in -toplevel- > data = data.readline() > AttributeError: 'str' object has no attribute 'readline' > >>> > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- From sigurd at 12move.de Wed Feb 11 17:24:03 2004 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Wed Feb 11 17:38:10 2004 Subject: [Tutor] time arithmetic with 2.3 datetime module In-Reply-To: <pan.2004.02.11.19.59.50.926090@yahoo.com> (Jeff Kowalczyk's message of "Wed, 11 Feb 2004 14:59:51 -0500") References: <pan.2004.02.11.19.59.50.926090@yahoo.com> Message-ID: <m3hdxxi88a.fsf@hamster.pflaesterer.de> On 11 Feb 2004, Jeff Kowalczyk <- jtk@yahoo.com wrote: > no tutorials on the new functionality. Every effort I make with timedelta > or time arithmetic eventually goes awry with TypeError: unsupported type > for timedelta seconds component: datetime.time > I have a simple timecard input of strings: > date, start, end = '20040206', '10:30', '17:45' > After I parse out the date string: y,m,d = d[:4],d[4:6],d[6:] > I want to make two times from the 24h time strings, combining with the > shared parsed date if necessary, and return the difference in floating > point (e.g. 7.25). Can anyone suggest the most expedient way to do this? You could do it like that >>> import datetime as dt >>> date, start, end = '20040206', '10:30', '17:45' >>> d, start, end = '20040206', '10:30', '17:45' >>> y,m,d = d[:4],d[4:6],d[6:] >>> starthr, startmin = map(int,start.split(':')) >>> endhr, endmin = map(int,end.split(':')) >>> d1 = dt.datetime(int(y), int(m), int(d), starthr, startmin) >>> d2 = dt.datetime(int(y), int(m), int(d), endhr, endmin) >>> delta = d2 - d1 >>> delta datetime.timedelta(0, 26100) >>> delta.seconds 26100 >>> Now you just need a function to convert the seconds in a format you like. E.g. like that: >>> def secs_to_float (s): ... divs = [60, 60, 24, 365] ... res = [] ... for div in divs: ... s, r = divmod(s, div) ... res.append(r) ... res[1] = res[1] / 60.0 ... res[0] = res[0] / 3600.0 ... res.reverse() ... return res ... >>> secs_to_float(delta.seconds) [0, 7, 0.25, 0.0] >>> Above should be combined in one ore two functions. Karl -- Please do *not* send copies of replies to me. I read the list From sigurd at 12move.de Wed Feb 11 17:37:59 2004 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Wed Feb 11 17:39:10 2004 Subject: [Tutor] readline() problem In-Reply-To: <000501c3f0ed$eeb28c60$4a394b0c@computer> (Ron Alvarado's message of "Wed, 11 Feb 2004 17:25:18 -0500") References: <000501c3f0ed$eeb28c60$4a394b0c@computer> Message-ID: <m3d68li6wl.fsf@hamster.pflaesterer.de> On 11 Feb 2004, Ron Alvarado <- rha207@worldnet.att.net wrote: > Here's what I'm getting when I try readline(). What an I doing wrong? >>>> data = open('bData.csv', 'r') >>>> num = True >>>> while num != "": > data = data.readline() > print data > Part number Description Item Cost 1104 1105 1118 > Traceback (most recent call last): > File "<pyshell#7>", line 2, in -toplevel- > data = data.readline() > AttributeError: 'str' object has no attribute 'readline' Several things here are wrong. (a) You have an endless loop (or do you set num somewhere in your code) (b) First data is file object; then you assign to data (the same name!) the value of date.readline() which is a string. data gets printed and the second calls causes this error (since data is now a string). (c) Nowadays there is a better idiom in Python to iterate over the lines of a file: for var in file: .... So your code could be written as: data = file('bData.csv') for line in data: print line Karl -- Please do *not* send copies of replies to me. I read the list From missive at hotmail.com Wed Feb 11 17:51:46 2004 From: missive at hotmail.com (Lee Harr) Date: Wed Feb 11 17:51:52 2004 Subject: [Tutor] Re: time arithmetic with 2.3 datetime module Message-ID: <BAY2-F153SVhGOD6gx300019e54@hotmail.com> >I have a simple timecard input of strings: > >date, start, end = '20040206', '10:30', '17:45' > >After I parse out the date string: y,m,d = d[:4],d[4:6],d[6:] >I want to make two times from the 24h time strings, combining with the >shared parsed date if necessary, and return the difference in floating >point (e.g. 7.25). Can anyone suggest the most expedient way to do this? Make sure the values you pass to the datetime constructor are numbers (not strings) ... >>>from datetime import datetime >>>date, start, end = '20040206', '10:30', '17:45' >>>y,m,d = date[:4],date[4:6],date[6:] >>>sh,sm = start.split(':') >>>eh,em = end.split(':') >>>sdt = datetime(y, m, d, sh, sm) Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: an integer is required >>>y, m, d = map(int, (y, m, d)) >>>y 2004 >>>sh, sm = map(int, (sh, sm)) >>>eh, em = map(int, (eh, em)) >>>sdt = datetime(y, m, d, sh, sm) >>>sdt datetime.datetime(2004, 2, 6, 10, 30) >>>edt = datetime(y, m, d, eh, em) >>>tdelta = edt - sdt >>>tdelta datetime.timedelta(0, 26100) >>>tdelta.days 0 >>>tdelta.seconds 26100 >>>tdelta.seconds/60.0 435.0 _________________________________________________________________ Click here for a FREE online computer virus scan from McAfee. http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963 From cspears2002 at yahoo.com Wed Feb 11 19:04:17 2004 From: cspears2002 at yahoo.com (Christopher Spears) Date: Wed Feb 11 19:04:23 2004 Subject: [Tutor] Unix shell vs Python shell Message-ID: <20040212000417.80075.qmail@web12401.mail.yahoo.com> What is the main difference between the Unix shell and Idle? I'm asking this because I discovered the os module, which has commands that look suspiciously like utilities in Unix. In Unix, the shell acts like a traffic cop and calls up needed utilities. Does Idle do the same? -Chris ===== "I'm the last person to pretend that I'm a radio. I'd rather go out and be a color television set." -David Bowie "Who dares wins" -British military motto "Far more creativity, today, goes into the marketing of products than into the products themselves..." -"Pattern Recognition" by William Gibson From gustabares at verizon.net Wed Feb 11 19:56:49 2004 From: gustabares at verizon.net (Gus Tabares) Date: Wed Feb 11 19:57:05 2004 Subject: [Tutor] Unix shell vs Python shell In-Reply-To: <20040212000417.80075.qmail@web12401.mail.yahoo.com> References: <20040212000417.80075.qmail@web12401.mail.yahoo.com> Message-ID: <200402111956.59944.gustabares@verizon.net> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Wednesday 11 February 2004 19:04, Christopher Spears wrote: > What is the main difference between the Unix shell and > Idle? I'm asking this because I discovered the os > module, which has commands that look suspiciously like > utilities in Unix. In Unix, the shell acts like a > traffic cop and calls up needed utilities. Does Idle > do the same? > The IDLE shell is mainly used for experimenting with pieces of Python code. You can use os.system function to make calls to the operating system, but you probably wouldn't want to replace this with actually using a Unix shell because that would be slow (for the user) and just silly. - -- Gus Tabares -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (GNU/Linux) iD8DBQFAKs9XlBrctWk2LusRAsAUAKDCvVN5+tp0YJ0m1xfZrtPNE2lRgQCdG7zR 8kPooBVXPsmHKqO7JlZ7OMo= =eA9Z -----END PGP SIGNATURE----- From marilyn at deliberate.com Wed Feb 11 18:03:16 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Wed Feb 11 20:04:05 2004 Subject: [Tutor] introspecting exceptions? Message-ID: <Pine.LNX.4.44.0402111453280.11161-100000@Kuna> Hello Python Experts, I'm looking for a way to introspect exceptions. dir() gives, amongst other things, a list of exceptions. I can do these things: >>> ZeroDivisionError.__doc__ 'Second argument to a division or modulo operation was zero.' >>> dir(ZeroDivisionError) ['__doc__', '__getitem__', '__init__', '__module__', '__str__'] >>> ZeroDivisionError.__module__ 'exceptions' >>> exceptions.__doc__ Traceback (most recent call last): File "<stdin>", line 1, in ? NameError: name 'exceptions' is not defined >>> I'm hoping to find the hierarchy of exceptions somehow. Thank you in advance. Marilyn Davis From rha207 at worldnet.att.net Wed Feb 11 20:39:36 2004 From: rha207 at worldnet.att.net (Ron Alvarado) Date: Wed Feb 11 20:35:55 2004 Subject: [Tutor] readline() problem - Thanks to all - Message-ID: <000501c3f109$13b2f200$1e394b0c@computer> Wow! I really messed that up. Thanks to everybody for their help. I think I have it all straightened out now. Ron A From csm1 at academicplanet.com Wed Feb 11 22:00:29 2004 From: csm1 at academicplanet.com (Chuck) Date: Wed Feb 11 22:00:09 2004 Subject: [Tutor] Re: Tutor Digest, Vol 7, Issue 30 References: <E1Ar31K-0001W1-5X@mail.python.org> Message-ID: <008a01c3f114$612bb480$92af5a42@oemcomputer> Magnus, Thank you for replying. I don't understand it, but you were right! When I start IDLE by double-clicking on the shortcut to it (C:\Python23\pythonw.exe "C:\PYTHON23\Lib\idlelib\idle.pyw"), the shell opens with this: IDLE 1.0.2 >>> If I then open a .py file and select "Run Module", it "hangs" as I described previously, and shows ----- RESTART-----. However, if I open the .py file by right-clicking on it and selecting "Edit with IDLE", the shell opens with this: IDLE 1.0.2 ==== No Subprocess ==== >>> ...and when I click on "Run Module", it runs fine - without "-----RESTART-----" Incidentally, I am running Windows 98 SE on a computer with a 333 MHz Celeron, so that could be part of the problem. Regarding running scripts from a command prompt, how do you do that? I tried entering the path to the .py file, in the RUN line, but that ran the script quickly and closed the MS-DOS window. What DOS command do you use to run a .py file? Thanks, Chuck ----- Original Message ----- From: <tutor-request@python.org> To: <tutor@python.org> Sent: Wednesday, February 11, 2004 4:39 PM Subject: Tutor Digest, Vol 7, Issue 30 > Send Tutor mailing list submissions to > tutor@python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request@python.org > > You can reach the person managing the list at > tutor-owner@python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. Re: very basic question from a newbie (Magnus Lycka) > 2. Pulling data from a DBaseIV file (Andrew Eidson) > 3. Re: Pulling data from a DBaseIV file (Lloyd Kvam) > 4. Re: Pulling data from a DBaseIV file (Bob Gailer) > 5. Re: Pulling data from a DBaseIV file (Andrew Eidson) > 6. time arithmetic with 2.3 datetime module (Jeff Kowalczyk) > 7. Re: Pulling data from a DBaseIV file (Andrew Eidson) > 8. Re: {Spam?} Re: [Tutor] Pulling data from a DBaseIV file > (Bob Gailer) > 9. readline() problem (Ron Alvarado) > 10. Re: readline() problem (hcohen2) > 11. Re: readline() problem (Marilyn Davis) > 12. Re: time arithmetic with 2.3 datetime module (Karl Pfl?sterer ) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Wed, 11 Feb 2004 18:49:44 +0100 > From: Magnus Lycka <magnus@thinkware.se> > Subject: Re: [Tutor] very basic question from a newbie > To: Chuck Marshall <csm1@academicplanet.com>, tutor@python.org > Message-ID: <think001_402a65b94a316@webmail.thinkware.se> > Content-Type: TEXT/plain; CHARSET=iso-8859-1 > > > I just read "IDLE Introduction --- One Day of IDLE Toying". It was great because it was so basic and helped me get started. My first couple of test "modules" ran just fine, but all of a sudden IDLE started "hanging" for a long time every time I click on "Run Module". Just running the following module seems to freeze the video on my computer for about 15 seconds. > > In my experience, IDLE gets slow if there is a lot of data, particularly > long lines of text, in the interactive interpreter window. It doesn't > matter if this text is far out of sight. I assume this is a "feature" > of the underlying Tk GUI. > > I.e. if you have done something like calculated the factorial of large > numbers over and over again, or done prints in long loops etc, you can > expect IDLE to be slow until you restart it. > > >From Python 2.3 under Windows I also feel that I've had problems with > dead (or at least lost) python or pythonw processes floating around. If > you are using Windows NT / 2000 / XP you can use the task manager to see > these (under the processes tab) and kill them. Just don't kill your > current IDLE editor window if you have unsaved work. :) > > There are other Python IDEs and editors than IDLE. The selection depends > on your OS. For instance, on Windows there is PythonWin which comes with > the win32all extensions, and is included in ActivePython. See > http://www.python.org/cgi-bin/moinmoin/PythonEditors and > http://www.python.org/cgi-bin/moinmoin/IntegratedDevelopmentEnvironments > for plenty of other examples. > > You probably get the best performance if you run Python scripts from your > command line. I often have a Command Prompt (cmd.exe) open in Windows and > start my program from there after having saved in the editor. Restarting > after a new editing cycle is just a matter of saving in the editor, swapping > to the command prompt with Alt-Tab and pressing Up-Arrow follows by Enter. > > > > >>> ================================ RESTART ================================ > > This is a feature! Previous versions of IDLE ran your script in the > same process as the IDLE GUI, and this caused a lot of problems. For > instance, it was impossible to run most Python GUI programs from > inside IDLE, and modified modules used by your script wouldn't be > reloaded as expected etc. Restart is your friend! :) > > > I only ran the module a few times before this problem started, but I don't think the -----RESTART---- line was appearing at first, but I could be wrong. > > If you start IDLE by right-clicking a file in the explorer, and > choose "Edit with IDLE", you will get a single process version of > IDLE, where the restart thing doesn't work. I don't know why they > have done it like that. > > If you start IDLE from the Start menu, and open your programs from > within IDLE, you will get the restart behaviour. It seems you have > a real resource problem on your computer if it seems expensive to > start a new process when you run a script, but check with the task > manager to see if there are old python processes hanging around... > > > -- > 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 > > > > ------------------------------ > > Message: 2 > Date: Wed, 11 Feb 2004 10:13:56 -0800 (PST) > From: Andrew Eidson <abeidson@sbcglobal.net> > Subject: [Tutor] Pulling data from a DBaseIV file > To: tutor@python.org > Message-ID: <20040211181356.89318.qmail@web80105.mail.yahoo.com> > Content-Type: text/plain; charset="us-ascii" > > Ok.. I have search the web and can not seem to find my answer.. I want to pull data from a DBaseIV file and convert it to a tab delimited file.. I have found PyxBase but it will not install for me.. is this functionality built into 2.3.3 or is there another way of accessing a DBF file in python?? I found an old thead in the Tutor archive but the link that was presented was dead.. > > Thanks > Andy > > > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: http://mail.python.org/pipermail/tutor/attachments/20040211/c818f3a9/attachment-0001.html > > ------------------------------ > > Message: 3 > Date: Wed, 11 Feb 2004 14:23:07 -0500 > From: Lloyd Kvam <pythontutor@venix.com> > Subject: Re: [Tutor] Pulling data from a DBaseIV file > To: Andrew Eidson <abeidson@sbcglobal.net> > Cc: tutor@python.org > Message-ID: <402A811B.5040504@venix.com> > Content-Type: text/plain; charset=us-ascii; format=flowed > > I needed to do something similar a couple of years ago. I downloaded > a module from (I think) Vaults of Parnassus. It decoded the > dBase header structure OK, but was clumsy to use. I reworked it for > my purposes. I'll send you my reworked code (off-list). You should be able to > turn it into something useful without too much grief. > > Andrew Eidson wrote: > > > Ok.. I have search the web and can not seem to find my answer.. I want > > to pull data from a DBaseIV file and convert it to a tab delimited > > file.. I have found PyxBase but it will not install for me.. is this > > functionality built into 2.3.3 or is there another way of accessing a > > DBF file in python?? I found an old thead in the Tutor archive but the > > link that was presented was dead.. > > > > Thanks > > Andy > > > > > > > > > > ------------------------------------------------------------------------ > > > > _______________________________________________ > > 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 > > > > > ------------------------------ > > Message: 4 > Date: Wed, 11 Feb 2004 11:32:02 -0800 > From: Bob Gailer <bgailer@alum.rpi.edu> > Subject: Re: [Tutor] Pulling data from a DBaseIV file > To: Andrew Eidson <abeidson@sbcglobal.net>, tutor@python.org > Message-ID: <6.0.0.22.0.20040211113154.036afc00@mail.mric.net> > Content-Type: text/plain; charset="us-ascii"; format=flowed > > At 10:13 AM 2/11/2004, Andrew Eidson wrote: > >Ok.. I have search the web and can not seem to find my answer.. I want to > >pull data from a DBaseIV file and convert it to a tab delimited file.. I > >have found PyxBase but it will not install for me.. is this functionality > >built into 2.3.3 or is there another way of accessing a DBF file in > >python?? I found an old thead in the Tutor archive but the link that was > >presented was dead.. > > ODBC? > > >Thanks > >Andy > > > > > >_______________________________________________ > >Tutor maillist - Tutor@python.org > >http://mail.python.org/mailman/listinfo/tutor > > Bob Gailer > bgailer@alum.rpi.edu > 303 442 2625 home > 720 938 2625 cell > > > > > ------------------------------ > > Message: 5 > Date: Wed, 11 Feb 2004 11:33:36 -0800 (PST) > From: Andrew Eidson <abeidson@sbcglobal.net> > Subject: Re: [Tutor] Pulling data from a DBaseIV file > To: tutor@python.org > Message-ID: <20040211193336.73898.qmail@web80106.mail.yahoo.com> > Content-Type: text/plain; charset=us-ascii > > Thanks.. I will take a look and see if I can get it to > do what I want.. be ready for a flurry of questions > though since I am still relatively new to programming > as well as python. > > > > ------------------------------ > > Message: 6 > Date: Wed, 11 Feb 2004 14:59:51 -0500 > From: Jeff Kowalczyk <jtk@yahoo.com> > Subject: [Tutor] time arithmetic with 2.3 datetime module > To: tutor@python.org > Message-ID: <pan.2004.02.11.19.59.50.926090@yahoo.com> > Content-Type: text/plain; charset=ISO-8859-1 > > Embarrassing to ask, but I can't quite figure 'time differences' with the > 2.3 datetime module. Every google link points to a copy of the docs, > no tutorials on the new functionality. Every effort I make with timedelta > or time arithmetic eventually goes awry with TypeError: unsupported type > for timedelta seconds component: datetime.time > > I have a simple timecard input of strings: > > date, start, end = '20040206', '10:30', '17:45' > > After I parse out the date string: y,m,d = d[:4],d[4:6],d[6:] > I want to make two times from the 24h time strings, combining with the > shared parsed date if necessary, and return the difference in floating > point (e.g. 7.25). Can anyone suggest the most expedient way to do this? > Thanks. > > > > > > > ------------------------------ > > Message: 7 > Date: Wed, 11 Feb 2004 12:09:12 -0800 (PST) > From: Andrew Eidson <abeidson@sbcglobal.net> > Subject: Re: [Tutor] Pulling data from a DBaseIV file > To: Tutor@python.org > Message-ID: <20040211200912.23283.qmail@web80105.mail.yahoo.com> > Content-Type: text/plain; charset=us-ascii > > The ODBC information I find only pertains to SQL based > systems.. I have not been able to find any information > for a DbaseIV file.. > > > > ------------------------------ > > Message: 8 > Date: Wed, 11 Feb 2004 13:43:21 -0800 > From: Bob Gailer <bgailer@alum.rpi.edu> > Subject: Re: {Spam?} Re: [Tutor] Pulling data from a DBaseIV file > To: Andrew Eidson <abeidson@sbcglobal.net>, Tutor@python.org > Message-ID: <6.0.0.22.0.20040211131711.01d51870@mail.mric.net> > Content-Type: text/plain; charset="us-ascii"; format=flowed > > At 12:09 PM 2/11/2004, Andrew Eidson wrote: > >The ODBC information I find only pertains to SQL based > >systems.. I have not been able to find any information > >for a DbaseIV file.. > > What operating system? If windows, you can set up an ODBC for dBase using > the data sources applet. Let's say you call it "boreland". > > Then: > import odbc > conn = odbc.odbc('boreland') > cursor = conn.cursor() > cursor.execute('select * from table') > rows = cursor.fetchall() > > Now you have a sequence of rows, each row being a sequence of columnvalues > > There is, as I recall, a CSV module that will create CSV files. > > Bob Gailer > bgailer@alum.rpi.edu > 303 442 2625 home > 720 938 2625 cell > > > > > ------------------------------ > > Message: 9 > Date: Wed, 11 Feb 2004 17:25:18 -0500 > From: "Ron Alvarado" <rha207@worldnet.att.net> > Subject: [Tutor] readline() problem > To: <tutor@python.org> > Message-ID: <000501c3f0ed$eeb28c60$4a394b0c@computer> > Content-Type: text/plain; charset="iso-8859-1" > > Here's what I'm getting when I try readline(). What an I doing wrong? > > >>> data = open('bData.csv', 'r') > >>> num = True > >>> while num != "": > data = data.readline() > print data > > > Part number Description Item Cost 1104 1105 1118 > > > Traceback (most recent call last): > File "<pyshell#7>", line 2, in -toplevel- > data = data.readline() > AttributeError: 'str' object has no attribute 'readline' > >>> > > > > > ------------------------------ > > Message: 10 > Date: Wed, 11 Feb 2004 17:28:50 -0500 > From: hcohen2 <hcohen2@comcast.net> > Subject: Re: [Tutor] readline() problem > To: Ron Alvarado <rha207@worldnet.att.net> > Cc: tutor@python.org > Message-ID: <402AACA2.8080901@comcast.net> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Ron Alvarado wrote: > > >Here's what I'm getting when I try readline(). What an I doing wrong? > > > > > > > >>>>data = open('bData.csv', 'r') > >>>>num = True > >>>>while num != "": > >>>> > >>>> > > data = data.readline() > > print data > > > > > When you openned the file, data was the file handle which you have > confused it with a string value of the same name. Since data types are > dynamic in Python your file handle value is lost. > > try > > str_data = data.readline() > print str_data > > both that line and the print should be to the right of the 'while ...' > > > > >Part number Description Item Cost 1104 1105 1118 > > > > > >Traceback (most recent call last): > > File "<pyshell#7>", line 2, in -toplevel- > > data = data.readline() > >AttributeError: 'str' object has no attribute 'readline' > > > > > > > > > >_______________________________________________ > >Tutor maillist - Tutor@python.org > >http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > > > > ------------------------------ > > Message: 11 > Date: Wed, 11 Feb 2004 14:33:49 -0800 (PST) > From: Marilyn Davis <marilyn@deliberate.com> > Subject: Re: [Tutor] readline() problem > To: tutor@python.org > Message-ID: <Pine.LNX.4.44.0402111426250.11161-100000@Kuna> > Content-Type: TEXT/PLAIN; charset=US-ASCII > > On Wed, 11 Feb 2004, Ron Alvarado wrote: > > > Here's what I'm getting when I try readline(). What an I doing wrong? > > > > >>> data = open('bData.csv', 'r') > > >>> num = True > > >>> while num != "": > > data = data.readline() > > print data > > The first call to data.readline() will read the first line of the > file, make a string of it, and then rename 'data' to be that > string/line. From then on, all is lost because you have lost your > identifier that points to the file. Next time around the loop, 'data' > is that last line/string and it doesn't know anything about the file > or 'readline'. > > The best solution is to rename the file: > > file = open('bData.csv', 'r') > num = True > while num != "": > data = file.readline() > print data > > However, this will cause an infinite loop because num never becomes > "". So you still have a problem to work out. > > Good luck! > > Marilyn Davis > > > > > > > > > Part number Description Item Cost 1104 1105 1118 > > > > > > Traceback (most recent call last): > > File "<pyshell#7>", line 2, in -toplevel- > > data = data.readline() > > AttributeError: 'str' object has no attribute 'readline' > > >>> > > > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > -- > > > > > > ------------------------------ > > Message: 12 > Date: Wed, 11 Feb 2004 23:24:03 +0100 > From: sigurd@12move.de (Karl Pfl?sterer ) > Subject: Re: [Tutor] time arithmetic with 2.3 datetime module > To: tutor@python.org > Message-ID: <m3hdxxi88a.fsf@hamster.pflaesterer.de> > Content-Type: text/plain; charset=us-ascii > > On 11 Feb 2004, Jeff Kowalczyk <- jtk@yahoo.com wrote: > > > no tutorials on the new functionality. Every effort I make with timedelta > > or time arithmetic eventually goes awry with TypeError: unsupported type > > for timedelta seconds component: datetime.time > > > I have a simple timecard input of strings: > > > date, start, end = '20040206', '10:30', '17:45' > > > After I parse out the date string: y,m,d = d[:4],d[4:6],d[6:] > > I want to make two times from the 24h time strings, combining with the > > shared parsed date if necessary, and return the difference in floating > > point (e.g. 7.25). Can anyone suggest the most expedient way to do this? > > > You could do it like that > >>> import datetime as dt > >>> date, start, end = '20040206', '10:30', '17:45' > >>> d, start, end = '20040206', '10:30', '17:45' > >>> y,m,d = d[:4],d[4:6],d[6:] > >>> starthr, startmin = map(int,start.split(':')) > >>> endhr, endmin = map(int,end.split(':')) > >>> d1 = dt.datetime(int(y), int(m), int(d), starthr, startmin) > >>> d2 = dt.datetime(int(y), int(m), int(d), endhr, endmin) > >>> delta = d2 - d1 > >>> delta > datetime.timedelta(0, 26100) > >>> delta.seconds > 26100 > >>> > > Now you just need a function to convert the seconds in a format you > like. > E.g. like that: > > >>> def secs_to_float (s): > ... divs = [60, 60, 24, 365] > ... res = [] > ... for div in divs: > ... s, r = divmod(s, div) > ... res.append(r) > ... res[1] = res[1] / 60.0 > ... res[0] = res[0] / 3600.0 > ... res.reverse() > ... return res > ... > >>> secs_to_float(delta.seconds) > [0, 7, 0.25, 0.0] > >>> > > Above should be combined in one ore two functions. > > > Karl > -- > Please do *not* send copies of replies to me. > I read the list > > > > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > > End of Tutor Digest, Vol 7, Issue 30 > ************************************ > From thomi at imail.net.nz Wed Feb 11 23:45:32 2004 From: thomi at imail.net.nz (Thomas Clive Richards) Date: Wed Feb 11 23:45:33 2004 Subject: [Tutor] custom types question Message-ID: <200402121745.32789.thomi@imail.net.nz> Hi guys, I'm building an application which uses both 2D points, and row,col indexes a lot. It would be really cool if I could create a few custom types, and then create operators for them. For example, a 2D point could be represented by a tuple, or list: >>> [23,48] However, I frequently need to add or subtract these points. If I try this as-is, I get this: >>> [10,10] + [23,20] [10, 10, 23, 20] What I'd like to be able to do, is something like this: >>> [10,10] + [10,12] [20,22] >>>[10,10] - [20,25] [-10,-15] I believe you do this by subclassing existing types, am I correct? I tried this: >>> class point2D(list): ... def __init__(self,X,Y): ... self.x = X ... self.y = Y ... >>> point2D(10,10) [] A few problems with this... It doesn't actually give me any additional functionality.. I still can't add points... I'm sure I've seen soem documentation somewhere about how to do this. I guess I should start bookmarking interesting pages.. Anyway, any pointers would be very helpful, thanks ;) -- Thomi Richards, thomi@once.net.nz From isrgish at fusemail.com Thu Feb 12 00:01:01 2004 From: isrgish at fusemail.com (Isr Gish) Date: Thu Feb 12 00:00:44 2004 Subject: [Tutor] introspecting exceptions? Message-ID: <E1Ar8xe-0003JX-4G@fuse1.fusemail.net> -----Original Message----- >From: "Marilyn Davis"<marilyn@deliberate.com> >Sent: 2/11/04 6:03:16 PM >To: "tutor@python.org"<tutor@python.org> >Subject: [Tutor] introspecting exceptions? > >Hello Python Experts, > >I'm looking for a way to introspect exceptions. > >dir() gives, amongst other things, a list of exceptions. > >I can do these things: > >>>> ZeroDivisionError.__doc__ >'Second argument to a division or modulo operation was zero.' >>>> dir(ZeroDivisionError) >['__doc__', '__getitem__', '__init__', '__module__', '__str__'] >>>> ZeroDivisionError.__module__ >'exceptions' >>>> exceptions.__doc__ >Traceback (most recent call last): > File "<stdin>", line 1, in ? >NameError: name 'exceptions' is not defined The problem here is that you don't have exceptions in you're namespace. Do this: >>> import exceptions >>> print exceptions.__doc__ Python's standard exception class hierarchy. Before Python 1.5, the standard exceptions [sniped the output] >>>> > >I'm hoping to find the hierarchy of exceptions somehow. Checkout the tutorial chapter 8. > >Thank you in advance. > >Marilyn Davis > > > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > From from_python_tutor at SSokolow.com Thu Feb 12 00:12:17 2004 From: from_python_tutor at SSokolow.com (SSokolow) Date: Thu Feb 12 00:12:23 2004 Subject: [Tutor] custom types question In-Reply-To: <200402121745.32789.thomi@imail.net.nz> References: <200402121745.32789.thomi@imail.net.nz> Message-ID: <402B0B31.7080404@SSokolow.com> Thomas Clive Richards wrote: >Hi guys, > > >I'm building an application which uses both 2D points, and row,col indexes a >lot. It would be really cool if I could create a few custom types, and then >create operators for them. > >For example, a 2D point could be represented by a tuple, or list: > > > >>>>[23,48] >>>> >>>> > >However, I frequently need to add or subtract these points. If I try this >as-is, I get this: > > > >>>>[10,10] + [23,20] >>>> >>>> >[10, 10, 23, 20] > >What I'd like to be able to do, is something like this: > > > >>>>[10,10] + [10,12] >>>> >>>> >[20,22] > > >>>>[10,10] - [20,25] >>>> >>>> >[-10,-15] > >I believe you do this by subclassing existing types, am I correct? I tried >this: > > >>>>class point2D(list): >>>> >>>> >... def __init__(self,X,Y): >... self.x = X >... self.y = Y >... > > >>>>point2D(10,10) >>>> >>>> >[] > > >A few problems with this... It doesn't actually give me any additional >functionality.. I still can't add points... > > > Would a function in the class be good enough for you? Something like this? >>> class point2D(list): ... def __init__(self,X,Y): ... self.x = X ... self.y = Y ... def add(self,p2D): ... self.x += p2D.x ... self.y += p2D.y ... >>> a = point2D(10,10) >>> b = point2D(5,10) >>> a.add(b) >>> a.x 15 >>> a.y 20 >I'm sure I've seen soem documentation somewhere about how to do this. I guess >I should start bookmarking interesting pages.. > >Anyway, any pointers would be very helpful, thanks ;) > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040212/8b1b86e2/attachment.html From thomi at imail.net.nz Thu Feb 12 00:19:24 2004 From: thomi at imail.net.nz (Thomas Clive Richards) Date: Thu Feb 12 00:19:23 2004 Subject: [Tutor] custom types question In-Reply-To: <402B0B31.7080404@SSokolow.com> References: <200402121745.32789.thomi@imail.net.nz> <402B0B31.7080404@SSokolow.com> Message-ID: <200402121819.24981.thomi@imail.net.nz> > Would a function in the class be good enough for you? > Something like this? > > >>> class point2D(list): > > ... def __init__(self,X,Y): > ... self.x = X > ... self.y = Y > ... def add(self,p2D): > ... self.x += p2D.x > ... self.y += p2D.y > ... > > >>> a = point2D(10,10) > >>> b = point2D(5,10) > >>> a.add(b) > >>> a.x > > 15 > > >>> a.y > > 20 > Well..... at a pinch. I sort of feel like you *should* be able to do it, and it should be simple...but most of my programming work has been in C/C++, where is is very simple.. so maybe that's the way to do it... still... -- Thomi Richards, thomi@once.net.nz From isrgish at fusemail.com Thu Feb 12 00:29:52 2004 From: isrgish at fusemail.com (Isr Gish) Date: Thu Feb 12 00:29:41 2004 Subject: [Tutor] custom types question Message-ID: <E1Ar9PX-0001q0-W7@fuse1.fusemail.net> -----Original Message----- >From: "Thomas Clive Richards"<thomi@imail.net.nz> >Sent: 2/11/04 11:45:32 PM >To: "tutor@python.org"<tutor@python.org> >Subject: [Tutor] custom types question > > >Hi guys, > > >I'm building an application which uses both 2D points, and row,col indexes a >lot. It would be really cool if I could create a few custom types, and then >create operators for them. > >For example, a 2D point could be represented by a tuple, or list: > >>>> [23,48] > >However, I frequently need to add or subtract these points. If I try this >as-is, I get this: > >>>> [10,10] + [23,20] >[10, 10, 23, 20] > >What I'd like to be able to do, is something like this: > >>>> [10,10] + [10,12] >[20,22] >>>>[10,10] - [20,25] >[-10,-15] > >I believe you do this by subclassing existing types, am I correct? I tried >this: >>>> class point2D(list): >... def __init__(self,X,Y): >... self.x = X >... self.y = Y >... >>>> point2D(10,10) >[] > I'm not an expert put lets try. >>> class Point2D(list): ... def __init__(self, x, y): ... self.data = [x, y] ... def __repr__(self): ... return repr(self.data) ... def __add__(self, other): ... temp = self.data ... temp[0] += other.data[0] ... temp[1] += other.data[1] ... return self.__class__(temp[0], temp[1]) ... Here is a test output: >>> p = Point2D(10, 15) >>> q = Point2D(5, 20) >>> p + q [15, 35] The only thing about this is that "p" is also getting changed. I'm sure it has to do with the return of __add__ but I'm not sure what it is. Maybe someone else can help with that. But this would be a start. > >A few problems with this... It doesn't actually give me any additional >functionality.. I still can't add points... > >I'm sure I've seen soem documentation somewhere about how to do this. I guess >I should start bookmarking interesting pages.. > >Anyway, any pointers would be very helpful, thanks ;) > >-- > >Thomi Richards, >thomi@once.net.nz > > All the be t, Isr From thomi at imail.net.nz Thu Feb 12 01:48:17 2004 From: thomi at imail.net.nz (Thomas Clive Richards) Date: Thu Feb 12 01:48:14 2004 Subject: [Tutor] custom types question In-Reply-To: <E1Ar9PX-0001q0-W7@fuse1.fusemail.net> References: <E1Ar9PX-0001q0-W7@fuse1.fusemail.net> Message-ID: <200402121948.17663.thomi@imail.net.nz> > > I'm not an expert put lets try. > > >>> class Point2D(list): > > ... def __init__(self, x, y): > ... self.data = [x, y] > ... def __repr__(self): > ... return repr(self.data) > ... def __add__(self, other): > ... temp = self.data > ... temp[0] += other.data[0] > ... temp[1] += other.data[1] > ... return self.__class__(temp[0], temp[1]) > ... > > Here is a test output: > >>> p = Point2D(10, 15) > >>> q = Point2D(5, 20) > >>> p + q > > [15, 35] > > The only thing about this is that "p" is also getting changed. I'm sure it > has to do with the return of __add__ but I'm not sure what it is. Maybe > someone else can help with that. But this would be a start. > Ahaaa... that's a lot better... so we can add a __subtract__ as well I guess? something like: def __subtract__(self,other): temp = self.data temp[0] -= other.data[0] temp[1] -= other.data[0] return self.__class__(temp[0],temp[1]) looks good to me ;) Now we just need to fix the rather strange behaivour with the other variable... ahh.. just an idea.. is this happening because we're not really copying the other data? would this fix it? def __subtract__(self,other): temp = self.data[:] #<-----change here! temp[0] -= other.data[0] temp[1] -= other.data[0] return self.__class__(temp[0],temp[1]) lets see: >>> class point2D(list): ... def __init__(self, x, y): ... self.data = [x,y] ... def __repr__(self): ... return repr(self.data) ... def __add__(self, other): ... temp = self.data[:] ... temp[0] += other.data[0] ... temp[1] += other.data[1] ... return self.__class__(temp[0], temp[1]) ... >>> a = point2D(2,3) >>> b = point2D(22,33) >>> a + b [24, 36] >>> a [2, 3] >>> b [22, 33] yes!!! that's exactly what I need.. Thanks a lot for your help.. most appreciated ;) -- Thomi Richards, thomi@once.net.nz From thomi at imail.net.nz Thu Feb 12 02:04:07 2004 From: thomi at imail.net.nz (Thomas Clive Richards) Date: Thu Feb 12 02:04:01 2004 Subject: [Tutor] custom types question In-Reply-To: <200402121948.17663.thomi@imail.net.nz> References: <E1Ar9PX-0001q0-W7@fuse1.fusemail.net> <200402121948.17663.thomi@imail.net.nz> Message-ID: <200402122004.07286.thomi@imail.net.nz> Hehe.. never happy with what I've got, I'd like to try something else.. with other types, you can create them by using certain symbols. For example, to create a string, you'd do something like: >>> s = 'this is a string' the "'" symbols identify that the characters between them are to be treated as a string, correct? dictionaries use the '{' symbol, lists use '[', tuples use '(' etc. etc. Is there any easy way to bind a symbol to a custom type? so far, teh code for my 2D point type is as follows: class point2D(list): def __init__(self,x,y): self.__data = [x,y] def __repr__(self): return repr(self.__data) def __add__(self,other): temp = other[:] temp[0] += self.__data[0] temp[1] += self.__data[1] return self.__class__(temp[0], temp[1]) def __sub__(self,other): temp = other[:] temp[0] -= self.__data[0] temp[1] -= self.__data[1] return self.__class__(temp[0],temp[1]) def __nonzero__(self): if self.__data == [0,0]: return False else: return True I'm guessing that this isn't really possible, without editing the python source code itself.. but still, it'd be pretty cool... Also, does anyone know if there are any builtin python types which are written in python, or are they all in C? It'd be good to be able to look through the source code to the builtin types and see how they're done. I guess they'll be in C for the extra speed though. Anyway, thanks ;) -- Thomi Richards, thomi@once.net.nz From glingl at aon.at Thu Feb 12 02:44:14 2004 From: glingl at aon.at (Gregor Lingl) Date: Thu Feb 12 02:43:20 2004 Subject: [Tutor] custom types question In-Reply-To: <E1Ar9PX-0001q0-W7@fuse1.fusemail.net> References: <E1Ar9PX-0001q0-W7@fuse1.fusemail.net> Message-ID: <402B2ECE.9000606@aon.at> Isr Gish schrieb: > >I'm not an expert put lets try. > > >>>>class Point2D(list): >>>> >>>> >... def __init__(self, x, y): >... self.data = [x, y] >... def __repr__(self): >... return repr(self.data) >... def __add__(self, other): >... temp = self.data >... temp[0] += other.data[0] >... temp[1] += other.data[1] >... return self.__class__(temp[0], temp[1]) >... > >Here is a test output: > > >>>>p = Point2D(10, 15) >>>>q = Point2D(5, 20) >>>>p + q >>>> >>>> >[15, 35] > > > This has the property that it changes p, which may be considered a disadvantage: >>> p=Point2D(10,15) >>> q=Point2D(5,20) >>> p [10, 15] >>> q [5, 20] >>> p+q [15, 35] >>> p [15, 35] >>> I recently asked for help concerning a similar problem and finally came up with a Vector class as a subclass of class tuple, which looks like this: class Vec(tuple): def __new__(cls, *args): return tuple.__new__(cls, args) def __add__(self, other): return Vec(*[x+y for (x,y) in zip(self,other)]) def __mul__(self, other): if isinstance(other, Vec): return sum([x*y for x,y in zip(self,other)]) else: return Vec(*[x*other for x in self]) # ... and many more methods Here, for instance, __repr__ doesn't need to be defined as it is inherited from tuple ... Moreover you have the advantage, that many convenient features of the tuple class, as slicing, tuple-unpacking etc. also work for Vec ... Hope this helps, just as a suggestion ... Gregor From dyoo at hkn.eecs.berkeley.edu Thu Feb 12 03:18:35 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Feb 12 03:19:02 2004 Subject: [Tutor] Unix shell vs Python shell In-Reply-To: <20040212000417.80075.qmail@web12401.mail.yahoo.com> Message-ID: <Pine.LNX.4.44.0402120004450.15850-100000@hkn.eecs.berkeley.edu> On Wed, 11 Feb 2004, Christopher Spears wrote: > What is the main difference between the Unix shell and Idle? I'm asking > this because I discovered the os module, which has commands that look > suspiciously like utilities in Unix. In Unix, the shell acts like a > traffic cop and calls up needed utilities. Does Idle do the same? Conceptually, yes, it's possible to make an analogy here. Let's see: (Unix : /bin/sh) :: (Python : IDLE) I think it might go something like this. *grin* IDLE is an interactive environment for playing around with the Python system. It's a little more, because it also includes a text editor, but otherwise, it's very analogous to the way Unix provides access through shells. It's a layer that we work on top of, and that layer gives us a more pleasant view of things. To take advantage of the "shell" analogy even further: you can replace IDLE with other environments as you get more familiar with Python. There's a whole bunch of them listed here: http://www.python.org/cgi-bin/moinmoin/PythonEditors (I personally use either the "toplevel" bare environment that Python provides if you run it directly off a terminal (no windows, just the '>>>' prompt), and I also use the "python-mode" within the 'Emacs' text editor.) We can think of Python as a system that lives on top of the native operating system. IDLE ======== /bin/sh Python ======= vs. ======== Unix Unix And the 'os' module allows us to dig closer into the territory claimed by the native operating system. But the 'os' module should also work well on Windows systems. Hope this makes sense! From dyoo at hkn.eecs.berkeley.edu Thu Feb 12 03:29:48 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Feb 12 03:29:54 2004 Subject: [Tutor] introspecting exceptions? In-Reply-To: <Pine.LNX.4.44.0402111453280.11161-100000@Kuna> Message-ID: <Pine.LNX.4.44.0402120018500.15850-100000@hkn.eecs.berkeley.edu> On Wed, 11 Feb 2004, Marilyn Davis wrote: > I'm looking for a way to introspect exceptions. > > I'm hoping to find the hierarchy of exceptions somehow. Hy Marilyn, Here's a link to the documentation on the exception hierarchy: http://www.python.org/doc/current/lib/module-exceptions.html It is possible to query for the superclasses of an object. A quick-and-dirty way is to use the 'inspect' module: http://www.python.org/doc/current/lib/module-inspect.html ### >>> import inspect >>> inspect.getmro(ValueError) (<class exceptions.ValueError at 0x1ccc0>, <class exceptions.StandardError at 0x1c480>, <class exceptions.Exception at 0x1c420>) ### In cases where there's a single path to the top of the class hierarchy (that is, if the hierarchy is a tree), then doing 'getmro()' should show us the direct path to the root. By the way, if we have a class, and we're looking for its subclasses, we can also look at the '__bases__' attribute: ### >>> ValueError.__bases__ (<class exceptions.StandardError at 0x1c480>,) ### and if we're methodical about it, you can recover the exception hierarchy by tracing down the __bases__. But since the documentation already draws it out, you may just want to use it. *grin* Hope this helps! From dyoo at hkn.eecs.berkeley.edu Thu Feb 12 03:44:56 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Feb 12 03:45:20 2004 Subject: [Tutor] custom types question In-Reply-To: <200402122004.07286.thomi@imail.net.nz> Message-ID: <Pine.LNX.4.44.0402120031520.15850-100000@hkn.eecs.berkeley.edu> On Thu, 12 Feb 2004, Thomas Clive Richards wrote: > >>> s = 'this is a string' > > the "'" symbols identify that the characters between them are to be treated as > a string, correct? > > dictionaries use the '{' symbol, lists use '[', tuples use '(' etc. etc. > > Is there any easy way to bind a symbol to a custom type? [some code cut] > I'm guessing that this isn't really possible, without editing the python > source code itself.. Hi Thomas, I agree: I don't think it's possible in standard Python. One can hack the grammar to make it work, but it might take some work. There are languages out there that do allow for extensible syntax, but Python's not one of them. I'm still undecided if that's a bad thing or not. *grin* An alternative approach is to "preprocess" a piece of "extended Python" so that it automagically translates an back to regular Python. Some projects do take this preprocessing approach. For example: http://www.freenet.org.nz/python/pyp/ Doing a google search on "python preprocessor" picks up quite a few hits, so if you're really determined to do this, then the preprocessor approach would be a practical way to do it. > Also, does anyone know if there are any builtin python types which are > written in python, or are they all in C? Most of them are written in C. One I can think of that might become more builtin in the future is the 'Set' class from the 'sets' module from the Standard Library. I'm sure it won't be long before it gets the C treatment. *grin* > It'd be good to be able to look through the source code to the builtin > types and see how they're done. I guess they'll be in C for the extra > speed though. Another one you can take a look at is the StringIO class in the StringIO module. StringIO can disguise a string as a 'file-like' object, and is surprisingly useful. It's written in pure Python, and there's also a C version of it in the 'cStringIO' module. Hope this helps! From Janssen at rz.uni-frankfurt.de Thu Feb 12 04:25:26 2004 From: Janssen at rz.uni-frankfurt.de (Michael Janssen) Date: Thu Feb 12 04:25:57 2004 Subject: [Tutor] custom types question In-Reply-To: <200402122004.07286.thomi@imail.net.nz> References: <E1Ar9PX-0001q0-W7@fuse1.fusemail.net> <200402121948.17663.thomi@imail.net.nz> <200402122004.07286.thomi@imail.net.nz> Message-ID: <Pine.A41.4.56.0402120955200.62808@hermes-22.rz.uni-frankfurt.de> On Thu, 12 Feb 2004, Thomas Clive Richards wrote: > Also, does anyone know if there are any builtin python types which are written > in python, or are they all in C? It'd be good to be able to look through the > source code to the builtin types and see how they're done. I guess they'll be > in C for the extra speed though. they're C code and live in the instalation dir under Objects as listobject.c and so forth. But you needn't to wade trough C code because list, string and dict are available in python moduls: UserList, UserString, UserDict. Here you find (old-style) classes that reimplement all (most of?) the special methods (__somewhat__) in python. Those UserX Classes are probably not worth to subclass now where we have new-style classes but give's you mutch infos about how the C objects work. Special methods are described here: http://www.python.org/doc/current/ref/specialnames.html > > Anyway, thanks ;) > > > -- > > Thomi Richards, > thomi@once.net.nz > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From Janssen at rz.uni-frankfurt.de Thu Feb 12 05:41:10 2004 From: Janssen at rz.uni-frankfurt.de (Michael Janssen) Date: Thu Feb 12 05:41:18 2004 Subject: [Tutor] custom types question In-Reply-To: <200402122004.07286.thomi@imail.net.nz> References: <E1Ar9PX-0001q0-W7@fuse1.fusemail.net> <200402121948.17663.thomi@imail.net.nz> <200402122004.07286.thomi@imail.net.nz> Message-ID: <Pine.A41.4.56.0402121039520.34152@hermes-22.rz.uni-frankfurt.de> On Thu, 12 Feb 2004, Thomas Clive Richards wrote: > class point2D(list): > def __init__(self,x,y): > self.__data = [x,y] You derives your class from "list", which results in "self" being a list-like object (for all I've understand from new-style classes...). Then you attach an attribute "__data" on self with the result of having two lists objects: self and self.__data . You should decide to either derive from list and work on self from then on or you should derive from nothing, do "self.__data = [x,y]" and work on __data from then on (Since you don't want to reimplement all list-methods on your own you should derive from UserList and overwrite __add__ and __sub__ ). [Hmm, enough hints? Perhaps a last one: when you want the new-style-derive-from-object solution you have to understand why you can't simply overwrite the __init__ method. You must use the builtin function super] Michael From cspears2002 at yahoo.com Thu Feb 12 13:07:22 2004 From: cspears2002 at yahoo.com (Christopher Spears) Date: Thu Feb 12 13:07:56 2004 Subject: [Tutor] tutorial and functional programming Message-ID: <20040212180722.51720.qmail@web12404.mail.yahoo.com> Is there a good tutorial on functional programming and anonymous functions in Python? -Chris ===== "I'm the last person to pretend that I'm a radio. I'd rather go out and be a color television set." -David Bowie "Who dares wins" -British military motto "Far more creativity, today, goes into the marketing of products than into the products themselves..." -"Pattern Recognition" by William Gibson From marilyn at deliberate.com Thu Feb 12 15:35:08 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Thu Feb 12 15:35:15 2004 Subject: [Tutor] tutorial and functional programming In-Reply-To: <20040212180722.51720.qmail@web12404.mail.yahoo.com> Message-ID: <Pine.LNX.4.44.0402121230570.11161-100000@Kuna> On Thu, 12 Feb 2004, Christopher Spears wrote: > Is there a good tutorial on functional programming and > anonymous functions in Python? > > -Chris Yes. You want Alan Gauld's online tutorial. Also he has pointers to other references on the subject: http://www.freenetpages.co.uk/hp/alan.gauld "Functional Programming" is in the "Advanced Topics" list. Marilyn > > ===== > "I'm the last person to pretend that I'm a radio. I'd rather go out and be a color television set." > -David Bowie > > "Who dares wins" > -British military motto > > "Far more creativity, today, goes into the marketing of products than into the products themselves..." > -"Pattern Recognition" by William Gibson > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- From Dionysos2 at cox.net Thu Feb 12 16:08:15 2004 From: Dionysos2 at cox.net (Dionysos2) Date: Thu Feb 12 16:12:26 2004 Subject: [Tutor] Need Help Message-ID: <000c01c3f1ac$54e57a60$052e0144@pn.at.cox.net> Ok this is my first time programming and I just stated an intro to programming class. This there anyone out the that can give me a point in the write direction to this assignment listed below. I have read more then I care to about Python yet I am still stuck in the begin. I can not believe that they would make the first assignment this hard. Maybe there is something simple that I am missing. Any please help. For this assignment I have been asked by my supervisor to program a small application to monitor the current status of the cash account in the firm's petty cash fund (the amount of cash kept on hand in the office for incidental purchases). The requirements for the program are to allow users to input the amount of cash deposited, the amount of cash withdrawn and to get a report of the balance at any given time. I am also asked to add the date of each deposit and the date of each withdrawal and provide a date with the balance returned upon a given query. The program should be able to provide a printed report and support a command line query. I am to use the object oriented properties of Python to accomplish this task. I was given some hints to get me started: First, define a class. The example below is just an example, you will need to enhance it to make it more realistic. class Account: def __init__(self, initial): self.balance = initial def deposit(self, amt): self.balance = self.balance + amt def withdraw(self,amt): self.balance = self.balance - amt def getbalance(self): return self.balance Using a the sample class above: a = Account(1000.00) a.deposit(550.23) a.deposit(100) a.withdraw(50) print a.getbalance() Write the a program to accomplish the above requirements and submit a 3 to 5 page report on how to use and modify the program if necessary. The above page count should include the source code for your program. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040212/efdb04e3/attachment.html From chouyiyu at hotmail.com Tue Feb 10 15:50:04 2004 From: chouyiyu at hotmail.com (Yi-Yu Chou) Date: Thu Feb 12 16:37:09 2004 Subject: [Tutor] Lots of Actors Message-ID: <BAY8-F106xi6Q4GYOcr0002d4ab@hotmail.com> Dear all, I would like to us line segments to display a 3D vector filed. However the program becomes very slow when displaying this vector field if the number of line segments is huge. Is there any better method to do it ? Thanks in advance !!! Below is my code : line = [] line_mapper = [] self.line_actor = [] for i in range(0, vf_points.num): line.append(vtkLineSource()) line[i].SetPoint1(vf_points.x[i],vf_points.y[i],vf_points.z[i]) line[i].SetPoint2(vf_points.x[i] + vf.vx[i],vf_points.y[i] + vf.vy[i],vf_points.z[i] + vf.vz[i]) line_mapper.append(vtkPolyDataMapper()) line_mapper[i].SetInput(line[i].GetOutput()) self.line_actor.append(vtkActor()) self.line_actor[i].SetMapper(line_mapper[i]) self.line_actor[i].GetProperty().SetLineWidth(1) self.line_actor[i].GetProperty().SetColor(0,1,1) self.line_actor[i].PickableOff() self.tar_renderer.AddActor(self.line_actor[i]) _________________________________________________________________ ·QÅÊ·R¡H¥æªB¤Í¡HMSN ½u¤W¥æ¤Í¡G¥Ñ Match.com ´£¨Ñ¡A¥þ¥@¬É³Ì¨üÅwªïªº½u¤W¥æ¤ÍªA °È http://match.msn.com.tw From loper at ananzi.co.za Tue Feb 10 04:06:26 2004 From: loper at ananzi.co.za (Gerhard Venter) Date: Thu Feb 12 16:37:37 2004 Subject: [Tutor] Re: all the slashes In-Reply-To: <E1AqGLU-0000Pq-00@hooloovoo> References: <4023BF79.9060106@ananzi.co.za> <E1AqGLU-0000Pq-00@hooloovoo> Message-ID: <40289F12.6000800@ananzi.co.za> Hi I was not trying to escape it, I was testing for two slashes as in http://www.ripe.net So I ended up using: if DomainName.find(r'//') > -1: as was also suggested by Andrei Thanks Gerhard Abel Daniel wrote: >Gerhard Venter writes: > > > >>Hi all >> >>I use the code below in Python 2.3, but in 2.2 it says: >>TypeError: 'in <string>' requires character as left operand >>I have tried r'//', and '////' (to escape the slashes) to no avail. >> >> myfile=open(r'/etc/sitelist','a') >> if "//" in mystring: >> >> >> >Why would you need to escape it? > > > >>>>'/' in 'ab/c' >>>> >>>> >True > > >>>>'/' in 'abc' >>>> >>>> >False > > > >OTOH, if you would be looking for \ -s (backslashes) you would need to escape >it: > > >>>>'\' in 'ab\c' >>>> >>>> > File "<stdin>", line 1 > '\' in 'ab\c' > ^ >SyntaxError: invalid syntax > > >>>>'\\' in 'ab\c' >>>> >>>> >True > > > >Plus, if you do use the code you showed, then you have a bug: your version >is looking for '//' (two slashes) and not '/' (one slash). > > > From mdmazzola at charter.net Tue Feb 10 22:02:19 2004 From: mdmazzola at charter.net (matthew mazzola) Date: Thu Feb 12 16:37:49 2004 Subject: [Tutor] webpage editor with GUI, i still have a NoneType error Message-ID: <000e01c3f04b$78a8fce0$eb316b18@yourgv9eh6ors1> Python file is attached. I created this same thing without GUI and it worked with the help of Bob G. but when i tried to convert it to GUI i get a- Traceback (most recent call last): File "C:\Python22\lib\lib-tk\Tkinter.py", line 1316, in __call__ return apply(self.func, args) File "C:\Python22\webpage_editor_GUI.py", line 162, in create_file_onSubmit title = self.title AttributeError: 'NoneType' object has no attribute 'get' -error and i didn't assign variables that are strings to None so i didn't think i had any NoneType objects. Another thing is that the error pops up as soon as i run it so my submit button might not be working. 1 more thing, i keep gettin these auto replys because i'm not a member and they think i'm spammer so if you know a way to find my news server name besides callin ISP that would be great? hope i'm not bothering you guys with these stupid questions but you got to start somewhere. python wannabe, -Matt -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040210/ce063368/attachment-0001.html From met at hbcse.tifr.res.in Thu Feb 12 01:28:23 2004 From: met at hbcse.tifr.res.in (Mumbai Education Trust Student Login) Date: Thu Feb 12 16:38:28 2004 Subject: [Tutor] wanna ur help! Message-ID: <20040212062615.M58910@hbcse.tifr.res.in> i am here facing some problem. i am working for execution of classinstance methods on runtime by accepting input from user. For which i need to know the arguments of the function which user has selected. & getargspec() method from inspect is not working for that. coz it takes argument as function & not as instance method. can anybody please guide me for this? -- Open WebMail Project (http://openwebmail.org) Debian Project (http://www.debian.org) From joshua at marktwain.net Thu Feb 12 16:55:15 2004 From: joshua at marktwain.net (Joshua) Date: Thu Feb 12 16:55:20 2004 Subject: [Tutor] Client-Server Password Manager Message-ID: <1076622915.17922.17.camel@secretfire> Hi, I'm relatively new to Python, and I'm wanting to get started on a project (mainly for educational purposes). I'm thinking about writing a multi-user password management system that will have a client and server. Obviously, I need the link between to be secure (something like SSH?). I've never done any network programming, and I'm wondering if I should use Python's built-in modules (which?), or some third-party library. If anyone has any advice for me on password management (I've looked at kedpm) or network programming, it would be greatly appreciated. Joshua K. joshua (at) marktwain (dot) net From littledanehren at yahoo.com Thu Feb 12 17:13:39 2004 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Thu Feb 12 17:13:49 2004 Subject: [Tutor] Lots of Actors In-Reply-To: <BAY8-F106xi6Q4GYOcr0002d4ab@hotmail.com> Message-ID: <20040212221339.91557.qmail@web41811.mail.yahoo.com> Yi-Yu Chou wrote: > Dear all, > > I would like to us line segments to display a 3D > vector filed. > However the program becomes very slow when > displaying this vector field if > the number of line > segments is huge. Is there any better method to do > it ? > Thanks in advance !!! > > Below is my code : > > line = [] > line_mapper = [] > self.line_actor = [] > for i in range(0, vf_points.num): > line.append(vtkLineSource()) > > line[i].SetPoint1(vf_points.x[i],vf_points.y[i],vf_points.z[i]) > line[i].SetPoint2(vf_points.x[i] + > vf.vx[i],vf_points.y[i] + > vf.vy[i],vf_points.z[i] + vf.vz[i]) > line_mapper.append(vtkPolyDataMapper()) > line_mapper[i].SetInput(line[i].GetOutput()) > self.line_actor.append(vtkActor()) > self.line_actor[i].SetMapper(line_mapper[i]) > self.line_actor[i].GetProperty().SetLineWidth(1) > self.line_actor[i].GetProperty().SetColor(0,1,1) > self.line_actor[i].PickableOff() > self.tar_renderer.AddActor(self.line_actor[i]) You may want to create temporary variables. They stay "linked" to what you assigned them to, so you don't need to worry that they'll just be coppied. Try making a variable for self.line_actor[i] since you keep refering to it. Daniel Ehrenberg __________________________________ Do you Yahoo!? Yahoo! Finance: Get your refund fast by filing online. http://taxes.yahoo.com/filing.html From amonroe at columbus.rr.com Thu Feb 12 17:49:26 2004 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Thu Feb 12 17:44:08 2004 Subject: [Tutor] Need Help In-Reply-To: <000c01c3f1ac$54e57a60$052e0144@pn.at.cox.net> References: <000c01c3f1ac$54e57a60$052e0144@pn.at.cox.net> Message-ID: <107678658008.20040212174926@columbus.rr.com> > For this assignment I have been asked by my supervisor to program a > small application to monitor the current status of the cash account > in the firm's petty cash fund (the amount of cash kept on hand in > the office for incidental purchases). Well, you did good job of explaining the project, but you didn't do so well at explaining what in particular you're having trouble with. Try again. Most people on this list will give you hints, but not the answers outright. Alan From cspears2002 at yahoo.com Thu Feb 12 17:53:21 2004 From: cspears2002 at yahoo.com (Christopher Spears) Date: Thu Feb 12 17:53:27 2004 Subject: [Tutor] invalid syntax Message-ID: <20040212225321.10720.qmail@web12402.mail.yahoo.com> Here is a script that I am working on to create two lists: def get_size(n,dir): import os files_size = [] biggest_files = [] files = os.listdir(dir) files = filter(lambda x:not os.path.isdir(x) and not os.path.islink(x),files) for f in range(len(files)): files_size = files_size + [(files[f],os.path.getsize(files[f]))] for b in range(len(files_size)): if file_size[b][1] > files_size[b+1][1]: biggest_files = biggest_files + file_size[b] elif: file_size[b][1] == files_size[b+1][1]: biggest_files = biggest_files + file_size[b][1] + file_size[b][1] else: biggest_files = biggest_files + files_size[b+1] print files_size print biggest_files According to Python, the : after the elif is causing an invalid syntax error. What gives?! I thought I was supposed to include that colon. -Chris From glingl at aon.at Thu Feb 12 18:57:00 2004 From: glingl at aon.at (Gregor Lingl) Date: Thu Feb 12 18:56:05 2004 Subject: [Tutor] invalid syntax In-Reply-To: <20040212225321.10720.qmail@web12402.mail.yahoo.com> References: <20040212225321.10720.qmail@web12402.mail.yahoo.com> Message-ID: <402C12CC.3000609@aon.at> Christopher Spears schrieb: > elif: > file_size[b][1] == files_size[b+1][1]: > biggest_files = biggest_files + file_size[b][1] + file_size[b][1] > else: > biggest_files = biggest_files + >files_size[b+1] > > > > You have to put another boolean expression between "elif" and ":" elif means: else if ... . So if *what*? Ah' a closer look to your code reveals: this file_size[b][1] == .... comparison should immediately follow the elif. (Right?) . So simply delete the : and put the comparison on line up. Only if you don't have to check any more conditions, else: suffices. HTH, Gregor > print files_size > print biggest_files > >According to Python, the : after the elif is causing >an invalid syntax error. What gives?! I thought I >was supposed to include that colon. > >-Chris > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > From cspears2002 at yahoo.com Thu Feb 12 19:08:22 2004 From: cspears2002 at yahoo.com (Christopher Spears) Date: Thu Feb 12 19:08:30 2004 Subject: [Tutor] grrrr! Message-ID: <20040213000822.78497.qmail@web12405.mail.yahoo.com> I'm writing some code that examines a directory and creates two lists. One is a list of all the files in the directory excluding other directories and links along with the size of the files. The result should look something like this: [[['openunit4.pyw', 48L], ['printlongestline.pyw', 214L]...]] I have suceeded in making this work. The next list should just contain the largest file in the directory and look like this: [[huge_file, 247L]] Here is the code: def get_size(n,dir): import os files_size = [] biggest = [] files = os.listdir(dir) files = filter(lambda x:not os.path.isdir(x) and not os.path.islink(x),files) for f in range(len(files)): files_size = files_size + [[files[f],os.path.getsize(files[f])]] for x in range(len(files_size)): s = files_size[x][1] for b in range(len(files_size)): if s > files_size[b][1]: biggest = biggest + [files_size[x]] print files_size print biggest I think I need some sort of second condition in the if statement, but I have problems comparing s to biggest[0][1]. I always get an index out of range error. Suggestions, anyone? -Chris From helena_b2001 at yahoo.com Thu Feb 12 20:05:50 2004 From: helena_b2001 at yahoo.com (helena bhaska) Date: Thu Feb 12 20:05:55 2004 Subject: [Tutor] Tkinter and apache Message-ID: <20040213010550.51078.qmail@web20414.mail.yahoo.com> Hi everybody, I am trying to do something which might be really stupid and impossible, but maybe I just don't know enough. I am trying to get a file dialog window to open from a cgi script. Here a piece of code that attempts to do that: def openFile(): title='' argInitialFile='' root = Tk() root.withdraw() f = tkFileDialog.askopenfilename( parent=root,title=title, initialfile=argInitialFile) if f == "": return None return f it works fine if I open it from command line, but if I call it from the cgi script here's what I get: Mod_python error: "PythonHandler mod_python.publisher" Traceback (most recent call last): File "/usr/local/lib/python2.3/site-packages/mod_python/apache.py", line 332, in HandlerDispatch result = object(req) File "/usr/local/lib/python2.3/site-packages/mod_python/publisher.py", line 198, in handler result = apply(object, (), args) File "/usr/local/apache2/cgi-bin/display.py", line 76, in openFile f = helpers.openFile() File "/usr/local/apache2/cgi-bin/my_utils.py", line 19, in openFile root = Tk() File "/usr/local/lib/python2.3/lib-tk/Tkinter.py", line 1560, in __init__ baseName = os.path.basename(sys.argv[0]) AttributeError: 'module' object has no attribute 'argv' Any help would be greatly appreciated! Thanks! __________________________________ Do you Yahoo!? Yahoo! Finance: Get your refund fast by filing online. http://taxes.yahoo.com/filing.html From rmkrauter at yahoo.com Thu Feb 12 20:53:34 2004 From: rmkrauter at yahoo.com (Rich Krauter) Date: Thu Feb 12 20:58:48 2004 Subject: [Tutor] grrrr! In-Reply-To: <20040213000822.78497.qmail@web12405.mail.yahoo.com> References: <20040213000822.78497.qmail@web12405.mail.yahoo.com> Message-ID: <1076637214.10589.100.camel@vaio> On Thu, 2004-02-12 at 19:08, Christopher Spears wrote: > I'm writing some code that examines a directory and > creates two lists. One is a list of all the files in > the directory excluding other directories and links > along with the size of the files. The result should > look something like this: > [[['openunit4.pyw', 48L], ['printlongestline.pyw', > 214L]...]] > > I have suceeded in making this work. The next list > should just contain the largest file in the directory > and look like this: > > [[huge_file, 247L]] > > Here is the code: > > def get_size(n,dir): > import os > files_size = [] > biggest = [] > files = os.listdir(dir) > files = filter(lambda x:not os.path.isdir(x) and > not os.path.islink(x),files) > > for f in range(len(files)): > files_size = files_size + > [[files[f],os.path.getsize(files[f])]] > > for x in range(len(files_size)): > s = files_size[x][1] > for b in range(len(files_size)): > if s > files_size[b][1]: > biggest = biggest + [files_size[x]] > > > print files_size > print biggest > > I think I need some sort of second condition in the if > statement, but I have problems comparing s to > biggest[0][1]. I always get an index out of range > error. > > Suggestions, anyone? > > Hi Chris, Here's what I tried. I used a dict because I find that easier than using two parallel lists when I want to keep two sequences in sync. By using the file sizes as the keys of the dict I can get at the largest file(s) or smallest files without doing any special tests. Looks kinda long but its mostly comments. import os def get_size(dir): files_of_size = {};sizes = []; biggest_files = [];file_sizes = []; files = filter(lambda x:not os.path.isdir(x) and not os.path.islink(x),os.listdir(dir)) for f in files: # make dict with file sizes as keys and # arrays of filenames as values # I use arrays of files in case two or more # files have the same size files_of_size.setdefault(os.path.getsize(f),[]).append(f) sizes = files_of_size.keys() sizes.sort();sizes.reverse(); for s in sizes: print files_of_size[s],s # make an array of files and sizes, in descending order # of file size biggest_files.append([files_of_size[s],s]) return biggest_files if __name__ == '__main__': bf = get_size('/tmp'); print bf biggest = bf[0] print biggest Hope it helps. Rich From arkamir at softhome.net Thu Feb 12 20:50:58 2004 From: arkamir at softhome.net (Conrad Koziol) Date: Thu Feb 12 21:08:32 2004 Subject: [Tutor] regular expression Message-ID: <1076637057.19271.5.camel@conradpc> What is the fastest way to search for a string and then surround it <code> and </code> with something. Like so: x = '<div> are not allowed, these arent either <br>' <some code here> x = '<code><div></code> are not allowed, these arent either <code><br></code>' The two ways this can be done is by subsituting the string like <div> with <code><div></code> or inserting <code> and </code> before and after it. Which one would be faster and how would I do it? I got as far as creating the regular expression r'<[^<>]*>' Thanks!! From andrewm at object-craft.com.au Thu Feb 12 22:30:17 2004 From: andrewm at object-craft.com.au (Andrew McNamara) Date: Thu Feb 12 22:30:25 2004 Subject: [Tutor] regular expression In-Reply-To: Message from Conrad Koziol <arkamir@softhome.net> of "Thu, 12 Feb 2004 17:50:58 -0800." <1076637057.19271.5.camel@conradpc> References: <1076637057.19271.5.camel@conradpc> Message-ID: <20040213033017.7038C3C1E2@coffee.object-craft.com.au> >What is the fastest way to search for a string and then surround it ><code> and </code> with something. Like so: > >x = '<div> are not allowed, these arent either <br>' ><some code here> >x = '<code><div></code> are not allowed, these arent either ><code><br></code>' > >The two ways this can be done is by subsituting the string like <div> >with <code><div></code> or inserting <code> and </code> before and after >it. Which one would be faster and how would I do it? I got as far as >creating the regular expression r'<[^<>]*>' "Obviously correct" is usually more important than "fastest", so don't get too worried by which way is faster until you need a faster way. Here's one way to do what you want. Note that I'm also replacing the < and > in the quoted block, and note the use of a raw string for the replacement string - you could also double the backslash and use a regular string: re.sub('<([^>]*)>', r'<code><\1></code>', x) If you *really* want the exact results you mention, then: re.sub('(<[^>]*>)', r'<code>\1</code>', x) -- Andrew McNamara, Senior Developer, Object Craft http://www.object-craft.com.au/ From rmkrauter at yahoo.com Thu Feb 12 22:27:15 2004 From: rmkrauter at yahoo.com (Rich Krauter) Date: Thu Feb 12 22:32:26 2004 Subject: [Tutor] regular expression In-Reply-To: <1076637057.19271.5.camel@conradpc> References: <1076637057.19271.5.camel@conradpc> Message-ID: <1076642835.10589.134.camel@vaio> On Thu, 2004-02-12 at 20:50, Conrad Koziol wrote: > What is the fastest way to search for a string and then surround it > <code> and </code> with something. Like so: > > x = '<div> are not allowed, these arent either <br>' > <some code here> > x = '<code><div></code> are not allowed, these arent either > <code><br></code>' > > The two ways this can be done is by subsituting the string like <div> > with <code><div></code> or inserting <code> and </code> before and after > it. Which one would be faster and how would I do it? I got as far as > creating the regular expression r'<[^<>]*>' > > Thanks!! > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor Hi Conrad, This seems to work. Don't know about speed, and its *not* thoroughly tested: import re x = '<div> are not allowed, these arent either <br>' pat = r'(?<!<code>)((?!<.*code>)<[^<>]*>)(?!</code>)' rep = r'<code>\1</code>' (a,na) = re.subn(pat,rep,x) print a # Next line is ok since I used # negative lookaheads and negative lookbehinds. # Without them, you'd get stuff like # <code><code></code><br></code><code></code> # if you run subn multiple times (b,nb) = re.subn(pat,rep,a) print b Hope that helps. FYI, I referred to 'Text Processing In Python' by David Mertz to try to figure this out. Rich From marilyn at deliberate.com Fri Feb 13 02:03:40 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Fri Feb 13 02:03:50 2004 Subject: [Tutor] copies deep and shallow Message-ID: <Pine.LNX.4.44.0402122301010.11161-100000@Kuna> Hello Pythoners, OK. I'm stumped again. >>> print dict.copy.__doc__ D.copy() -> a shallow copy of D And from the copy module: >>> print copy.__doc__ - A shallow copy constructs a new compound object and then (to the extent possible) inserts *the same objects* into in that the original contains. - A deep copy constructs a new compound object and then, recursively, inserts *copies* into it of the objects found in the original. So, here's my code: #!/usr/bin/env python2.2 '''Trying to demonstrate deep/shallow copies of dictionaries''' import copy combos = {'steak':'lobster', 'liver':'onions'} combos2 = combos.copy() combos2['steak'] = 'eggs' print 'Original combos:', combos print ' combos2:', combos2 no_liver = copy.deepcopy(combos) del no_liver['liver'] print 'Original combos:', combos print ' no_liver:', no_liver ##### end of code And the output: bash-2.05a$ ./copies.py Original combos: {'steak': 'lobster', 'liver': 'onions'} combos2: {'steak': 'eggs', 'liver': 'onions'} Original combos: {'steak': 'lobster', 'liver': 'onions'} no_liver: {'steak': 'lobster'} bash-2.05a$ --- I thought that when I changed combos2's 'lobster' to 'eggs', that the original combos would be affected. I thought that that is what a shallow copy meant. So I'm out to lunch some how. Can anyone help? Marilyn -- From Janssen at rz.uni-frankfurt.de Fri Feb 13 04:15:35 2004 From: Janssen at rz.uni-frankfurt.de (Michael Janssen) Date: Fri Feb 13 04:15:42 2004 Subject: [Tutor] copies deep and shallow In-Reply-To: <Pine.LNX.4.44.0402122301010.11161-100000@Kuna> References: <Pine.LNX.4.44.0402122301010.11161-100000@Kuna> Message-ID: <Pine.A41.4.56.0402130939120.34152@hermes-22.rz.uni-frankfurt.de> On Thu, 12 Feb 2004, Marilyn Davis wrote: > #!/usr/bin/env python2.2 > '''Trying to demonstrate deep/shallow copies of dictionaries''' > > import copy > combos = {'steak':'lobster', 'liver':'onions'} > combos2 = combos.copy() > combos2['steak'] = 'eggs' value 'lobster' might have been the same internal object as in combos['steak']. But here 'steak' gets reassigned. You could try to *change* the string in place, but you will fail, because you can't change strings in place: >>> import copy >>> immutable = {"aString": "here"} >>> immutable2 = copy.copy(immutable) >>> immutable["aString"] += " and there" >>> immutable {'aString': 'here and there'} >>> immutable2 {'aString': 'here'} > I thought that when I changed combos2's 'lobster' to 'eggs', that the > original combos would be affected. I thought that that is what a > shallow copy meant. You actually need a nested data structur to show the effects of non-recursive copy ;-) Put another (mutable) container type within your dict and then change the content of this object: >>> lvl1 = {"lvl2": [1,2,3]} >>> lvl1_copy = copy.copy(lvl1) >>> lvl1["lvl2"][0] = 4 # reassigning within lvl2 >>> lvl1 {'lvl2': [4, 2, 3]} >>> lvl1_copy {'lvl2': [4, 2, 3]} ---> 'lvl2' list was 'shared' between the two copies of the dictionary. With copy.deepcopy the 'lvl2' list would have been created as a copy too. Michael From thomi at imail.net.nz Fri Feb 13 05:03:41 2004 From: thomi at imail.net.nz (Thomas Clive Richards) Date: Fri Feb 13 05:03:37 2004 Subject: [Tutor] custom types question In-Reply-To: <402B2ECE.9000606@aon.at> References: <E1Ar9PX-0001q0-W7@fuse1.fusemail.net> <402B2ECE.9000606@aon.at> Message-ID: <200402132303.41202.thomi@imail.net.nz> On Thursday 12 February 2004 20:44, Gregor Lingl wrote: > > I recently asked for help concerning a similar problem and finally came > up with a Vector class as a subclass of class tuple, which looks like this: > > class Vec(tuple): > > def __new__(cls, *args): > return tuple.__new__(cls, args) > > def __add__(self, other): > return Vec(*[x+y for (x,y) in zip(self,other)]) > > def __mul__(self, other): > if isinstance(other, Vec): > return sum([x*y for x,y in zip(self,other)]) > else: > return Vec(*[x*other for x in self]) > > # ... and many more methods > Here, for instance, __repr__ doesn't need to be defined > as it is inherited from tuple ... > Moreover you have the advantage, that many convenient > features of the tuple class, as slicing, tuple-unpacking etc. > also work for Vec ... > > Hope this helps, just as a suggestion ... hmm.. I'm not sure I understand this... I'm only beginning ;) For one, I'm still having trouble getting my mind around the list logic (or whatever it's called.. the "[x*y for x,y in zip(self,other)]" bits.. I'll rewrite it using errr.. normal logic, and see if I can make sense from it.. It might be worth someone writing a 3rd party module with additional types? It seems like these things muct be used quite frequently... -- Thomi Richards, thomi@once.net.nz From thomi at imail.net.nz Fri Feb 13 05:05:27 2004 From: thomi at imail.net.nz (Thomas Clive Richards) Date: Fri Feb 13 05:05:16 2004 Subject: [Tutor] custom types question In-Reply-To: <Pine.LNX.4.44.0402120031520.15850-100000@hkn.eecs.berkeley.edu> References: <Pine.LNX.4.44.0402120031520.15850-100000@hkn.eecs.berkeley.edu> Message-ID: <200402132305.27513.thomi@imail.net.nz> On Thursday 12 February 2004 21:44, Danny Yoo wrote: > > I agree: I don't think it's possible in standard Python. One can hack the > grammar to make it work, but it might take some work. There are languages > out there that do allow for extensible syntax, but Python's not one of > them. I'm still undecided if that's a bad thing or not. *grin* > Personally, i don;t think it matters that much.. it's not a huge functionality flaw... presumably if a certain type is used enough, the python developers will include it as a standard type? > > An alternative approach is to "preprocess" a piece of "extended Python" so > that it automagically translates an back to regular Python. Some projects > do take this preprocessing approach. For example: > > http://www.freenet.org.nz/python/pyp/ > > Doing a google search on "python preprocessor" picks up quite a few hits, > so if you're really determined to do this, then the preprocessor approach > would be a practical way to do it. > hmmm.. that's very interesting.. THanks for the tip ;) ... > Another one you can take a look at is the StringIO class in the StringIO > module. StringIO can disguise a string as a 'file-like' object, and is > surprisingly useful. It's written in pure Python, and there's also a C > version of it in the 'cStringIO' module. > > Ahh, ok, thanks for that! -- Thomi Richards, thomi@once.net.nz From rmkrauter at yahoo.com Fri Feb 13 09:05:22 2004 From: rmkrauter at yahoo.com (Rich Krauter) Date: Fri Feb 13 09:10:37 2004 Subject: [Tutor] regular expression In-Reply-To: <1076642835.10589.134.camel@vaio> References: <1076637057.19271.5.camel@conradpc> <1076642835.10589.134.camel@vaio> Message-ID: <1076681122.12351.74.camel@vaio> > On Thu, 2004-02-12 at 20:50, Conrad Koziol wrote: > > What is the fastest way to search for a string and then surround Hi Conrad, I tried timing the two methods proposed so far. I figured the longer pattern would take much longer. This is what I got on my pc: 1st method(longer regex) - 1000000 times, 74.0188100338 seconds 2nd method(short regex)- 1000000 times, 67.2792310715 seconds This is how I got those numbers. import re # requires 2.3 from timeit import Timer x = '<div> are not allowed, these arent either <br>' patx = r'(?<!<code>)((?!<.*code>)<[^<>]*>)(?!</code>)' paty = r'(<[^<>]*>)' rep = r'<code>\1</code>' print Timer(stmt='(a,na)=re.subn(patx,rep,x)', setup='import re;from __main__ import patx,paty,rep,x').timeit() print Timer(stmt='(aa,naa)=re.subn(paty,rep,x)', setup='import re;from __main__ import patx,paty,rep,x').timeit() Maybe this gives you an idea of how to test the relative speed of whatever solution you come up with. Rich From kiran at mhowlinux.org Fri Feb 13 12:16:32 2004 From: kiran at mhowlinux.org (kiran@mhowlinux.org) Date: Fri Feb 13 12:17:33 2004 Subject: [Tutor] Re: Tutor Digest, Vol 7, Issue 34 References: <E1ArXMl-0007QR-Ck@mail.python.org> Message-ID: <003301c3f255$3275d1b0$a12fe2dc@VULCAN> couple of problems here 1. elif is not followed by a ":" but another condition 2. u have used file_size and files_size ( one with an s and another without an s..check that) 3. figure out logical errors...i will give you an edited piece of your code...which runs...but there would still be some errors..the way u are getting the file sizes def get_size(n,dir): import os files_size = [] biggest_files = [] files = os.listdir(dir) files = filter(lambda x:not os.path.isdir(x) and not os.path.islink(x),files) for f in range(len(files)): files_size = files_size + [(files[f],os.path.getsize(files[f]))] for b in range(len(files_size)): if files_size[b][1] > files_size[b+1][1]: biggest_files = biggest_files + files_size[b] elif (files_size[b][1] == files_size[b+1][1]): biggest_files = biggest_files + files_size[b][1] + files_size[b][1] else: biggest_files = biggest_files + files_size[b+1] Beware the lollipop of mediocrity: lick it once and you suck forever <a href="http://www.mhowlinux.org/home">www.mhowlinux.org</a> Helping Linux users in Mhow couple of problems here 1. elif is not followed by a ":" but another condition 2. u have used file_size and files_size ( one with an s and another without an s..check that) 3. figure out logical errors...i will give you an edited piece of your code...which runs...but there would still be some errors..the way u are getting the file sizes def get_size(n,dir): import os files_size = [] biggest_files = [] files = os.listdir(dir) files = filter(lambda x:not os.path.isdir(x) and not os.path.islink(x),files) for f in range(len(files)): files_size = files_size + [(files[f],os.path.getsize(files[f]))] for b in range(len(files_size)): if files_size[b][1] > files_size[b+1][1]: biggest_files = biggest_files + files_size[b] elif (files_size[b][1] == files_size[b+1][1]): biggest_files = biggest_files + files_size[b][1] + files_size[b][1] else: biggest_files = biggest_files + files_size[b+1] Beware the lollipop of mediocrity: lick it once and you suck forever <a href="http://www.mhowlinux.org/home">www.mhowlinux.org</a> Helping Linux users in Mhow From marilyn at deliberate.com Fri Feb 13 12:21:31 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Fri Feb 13 12:21:36 2004 Subject: [Tutor] copies deep and shallow In-Reply-To: <Pine.A41.4.56.0402130939120.34152@hermes-22.rz.uni-frankfurt.de> Message-ID: <Pine.LNX.4.44.0402130917030.11161-100000@Kuna> On Fri, 13 Feb 2004, Michael Janssen wrote: > On Thu, 12 Feb 2004, Marilyn Davis wrote: > > > #!/usr/bin/env python2.2 > > '''Trying to demonstrate deep/shallow copies of dictionaries''' > > > > import copy > > combos = {'steak':'lobster', 'liver':'onions'} > > combos2 = combos.copy() > > combos2['steak'] = 'eggs' > > value 'lobster' might have been the same internal object as in > combos['steak']. But here 'steak' gets reassigned. You could try to > *change* the string in place, but you will fail, because you can't > change strings in place: > > >>> import copy > >>> immutable = {"aString": "here"} > >>> immutable2 = copy.copy(immutable) > >>> immutable["aString"] += " and there" > >>> immutable > {'aString': 'here and there'} > >>> immutable2 > {'aString': 'here'} Thank you. I think I see. So shallow copies are independent at the first level but dependent at deeper levels. Why would someone want a shallow copy? It seems like trouble lurking. I would think you'd either want a completely deep copy, or a reference to the same everything. I must still be missing something. Marilyn > > > > I thought that when I changed combos2's 'lobster' to 'eggs', that the > > original combos would be affected. I thought that that is what a > > shallow copy meant. > > You actually need a nested data structur to show the effects of > non-recursive copy ;-) Put another (mutable) container type within your > dict and then change the content of this object: > > >>> lvl1 = {"lvl2": [1,2,3]} > >>> lvl1_copy = copy.copy(lvl1) > >>> lvl1["lvl2"][0] = 4 # reassigning within lvl2 > >>> lvl1 > {'lvl2': [4, 2, 3]} > >>> lvl1_copy > {'lvl2': [4, 2, 3]} > > ---> 'lvl2' list was 'shared' between the two copies of the dictionary. > With copy.deepcopy the 'lvl2' list would have been created as a copy too. > > Michael > -- From taranis at spittingllamas.com Fri Feb 13 12:21:43 2004 From: taranis at spittingllamas.com (Alex Ezell) Date: Fri Feb 13 12:21:59 2004 Subject: [Tutor] BMP Manipulation Message-ID: <965346379.20040213122143@spittingllamas.com> I have been studying the Python Imaging Library (PIL) to figure out if there is a way to modify the color palette of an indexed BMP image. All the information on the ImagePalette module shows me that I can extract the color palette, but I can't seem to find any details on perhaps modifying and applying a new color palette. Does anyone have any insights into modifying color palettes? Are there limitations on using indexed BMP images? -- Alex http://www.spittingllamas.com "Formal Restrictions, contrary to what you might think, free you up by allowing you to concentrate on purer ideas." - Winter Sorbeck in Chip Kidd's The Cheese Monkeys From nicholas_wieland at yahoo.it Fri Feb 13 14:39:09 2004 From: nicholas_wieland at yahoo.it (Nicholas Wieland) Date: Fri Feb 13 14:34:17 2004 Subject: [Tutor] Client-Server Password Manager In-Reply-To: <1076622915.17922.17.camel@secretfire> References: <1076622915.17922.17.camel@secretfire> Message-ID: <1076701149.81924.3.camel@debaser.pixie.home> Il Gio, 2004-02-12 alle 22:55, Joshua ha scritto: > Hi, > > I'm relatively new to Python, and I'm wanting to get started on a > project (mainly for educational purposes). I'm thinking about writing a > multi-user password management system that will have a client and > server. Obviously, I need the link between to be secure (something like > SSH?). I've never done any network programming, and I'm wondering if I > should use Python's built-in modules (which?), or some third-party > library. If anyone has any advice for me on password management (I've > looked at kedpm) or network programming, it would be greatly > appreciated. I think your best bet is TwistedMatrix (http://www.twistedmatrix.com). At first glance it seems a little complicated (or, at least, *big*): just choose the part you need and use it. HTH, ngw From project5 at redrival.net Fri Feb 13 16:10:22 2004 From: project5 at redrival.net (Andrei) Date: Fri Feb 13 16:13:35 2004 Subject: [Tutor] Re: copies deep and shallow References: <Pine.A41.4.56.0402130939120.34152@hermes-22.rz.uni-frankfurt.de> <Pine.LNX.4.44.0402130917030.11161-100000@Kuna> Message-ID: <1mlixueuzmmso$.1nnvan3yigy5d$.dlg@40tude.net> Marilyn Davis wrote on Fri, 13 Feb 2004 09:21:31 -0800 (PST): <snip> > So shallow copies are independent at the first level but dependent at > deeper levels. I'm not sure what you mean by "deeper levels". If your whatever you copy only contains immutable components (string, numbers, tuples), there isn't really any danger in this because you can't change them in-place anyway (ragardless of how many levels deep the tuple is for example). > Why would someone want a shallow copy? It seems like trouble lurking. Try this in the interactive interpreter: a = range(2000000) # make that 4mln if you have 512 MB or 1mln for 128MB b = copy.deepcopy(a) c = copy.copy(a) Noticed any difference? Also it's not dangerous if you're using immutable items. > I would think you'd either want a completely deep copy, or a reference to > the same everything. Generally I use deepcopy just to be on the safe side, but that's not such a big problem since I don't tend to use very large amounts of data when copying. -- Yours, Andrei ===== Mail address in header catches spam. 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 Feb 13 16:15:16 2004 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Fri Feb 13 16:16:50 2004 Subject: [Tutor] grrrr! In-Reply-To: <20040213000822.78497.qmail@web12405.mail.yahoo.com> (Christopher Spears's message of "Thu, 12 Feb 2004 16:08:22 -0800 (PST)") References: <20040213000822.78497.qmail@web12405.mail.yahoo.com> Message-ID: <m3ad3mvg88.fsf@hamster.pflaesterer.de> On 13 Feb 2004, Christopher Spears <- cspears2002@yahoo.com wrote: > I'm writing some code that examines a directory and > creates two lists. One is a list of all the files in > the directory excluding other directories and links > along with the size of the files. The result should > look something like this: > [[['openunit4.pyw', 48L], ['printlongestline.pyw', > 214L]...]] > I have suceeded in making this work. The next list > should just contain the largest file in the directory > and look like this: > [[huge_file, 247L]] [Code] > I think I need some sort of second condition in the if > statement, but I have problems comparing s to > biggest[0][1]. I always get an index out of range > error. I looked at your code and saw you like functional programming style (very good). Here is a bit shorter version of your code. def get_size(dir): import os files_size = [(f, os.path.getsize(f)) for f in os.listdir(dir) if not os.path.isdir(f) or os.path.islink(f)] biggest = reduce(lambda pair1, pair2: pair1[1] > pair2[1] and pair1 or pair2, files_size) return (files_size, biggest) The list with files and the corresponding size gets build with one list comprehension. I use here tuples for these pairs (IMO they are better than lists here). Then reduce() is used to find the biggest element (size) in the list; the lambda expression compares the sizes of two pairs and returns the pair with the bigger size (if they are equal in size the second pair is returned). The result is the pair with the biggest file size. Finally the function returns a tuple: the list of files and the pair with the biggest file size. Karl -- Please do *not* send copies of replies to me. I read the list From cspears2002 at yahoo.com Fri Feb 13 17:14:37 2004 From: cspears2002 at yahoo.com (Christopher Spears) Date: Fri Feb 13 17:14:44 2004 Subject: [Tutor] setdefault() Message-ID: <20040213221437.61490.qmail@web12403.mail.yahoo.com> Can someone clarify what setdefault() does? I looked it up in the docs, and I am still confused. Thanks, Chris From glingl at aon.at Fri Feb 13 17:25:48 2004 From: glingl at aon.at (Gregor Lingl) Date: Fri Feb 13 17:24:55 2004 Subject: [Tutor] setdefault() In-Reply-To: <20040213221437.61490.qmail@web12403.mail.yahoo.com> References: <20040213221437.61490.qmail@web12403.mail.yahoo.com> Message-ID: <402D4EEC.2070605@aon.at> Christopher Spears schrieb: >Can someone clarify what setdefault() does? I looked >it up in the docs, and I am still confused. > > > If you ask a dictionary for a value for a nonexisting key using setdefault, the defaultvalue passed to setdefault as the second argument is - assigned to this key as its value - AND returned if you use setdefault with an existing key, nothing is changed and the value corresponding to this key is returned, i.e. it works lice dic[key] example: >>> dic = {"a":9, "b":-3,"c":0} >>> dic["d"] Traceback (most recent call last): File "<pyshell#1>", line 1, in -toplevel- dic["d"] KeyError: 'd' >>> dic.setdefault("d",1001) 1001 >>> dic {'a': 9, 'c': 0, 'b': -3, 'd': 1001} >>> dic.setdefault("a",1001) 9 >>> dic {'a': 9, 'c': 0, 'b': -3, 'd': 1001} >>> HTH, Gregor From cspears2002 at yahoo.com Fri Feb 13 19:05:31 2004 From: cspears2002 at yahoo.com (Christopher Spears) Date: Fri Feb 13 19:05:36 2004 Subject: [Tutor] making a function work with os.path.walk() Message-ID: <20040214000531.44750.qmail@web12404.mail.yahoo.com> I wrote a function called get_size(n,dir,files). This is the code: import os def get_size(n,dir,files): files_of_size = {}; sizes = []; biggest_files = []; files_sizes = []; files = map(os.path.join,[dir] * len(files),files) files = filter(lambda x: not os.path.isdir(x) and not os.path.islink(x), os.listdir(dir)) for f in files: files_of_size.setdefault(os.path.getsize(f),[]).append(f) sizes = files_of_size.keys() sizes.sort(); sizes.reverse(); for s in sizes: biggest_files.append([files_of_size[s],s]) while n > 0: print biggest_files[n-1] n = n - 1 The function takes a number n and a directory name and prints out the n largest files. However when I try to use it with os.path.walk() I get the following result. >>> os.path.walk('.',get_size,3) [['Unit5.doc'], 22016L] [['Unit8.doc'], 22528L] [['Unit6.doc'], 23552L] Traceback (most recent call last): File "<pyshell#4>", line 1, in -toplevel- os.path.walk('.',get_size,3) File "C:\Python23\lib\ntpath.py", line 333, in walk walk(name, func, arg) File "C:\Python23\lib\ntpath.py", line 327, in walk func(arg, top, names) File "C:\Documents and Settings\Christstopher Spears\My Documents\python\unit9.question1c.py", line 11, in get_size files_of_size.setdefault(os.path.getsize(f),[]).append(f) File "C:\Python23\lib\ntpath.py", line 228, in getsize return os.stat(filename).st_size OSError: [Errno 2] No such file or directory: 'DSCN4432.JPG' I cannot decipher the error message. From what I can gather, the function works fine in its current directory, but seems to be having problems with the other directory in the current directory. What I find odd is that it claims that the .JPG doesn't exist, but it is in the other directory. Suggestions, hints, etc? -Chris From rmkrauter at yahoo.com Fri Feb 13 21:09:02 2004 From: rmkrauter at yahoo.com (Rich Krauter) Date: Fri Feb 13 21:14:14 2004 Subject: [Tutor] making a function work with os.path.walk() In-Reply-To: <20040214000531.44750.qmail@web12404.mail.yahoo.com> References: <20040214000531.44750.qmail@web12404.mail.yahoo.com> Message-ID: <1076724542.12618.28.camel@vaio> On Fri, 2004-02-13 at 19:05, Christopher Spears wrote: > I wrote a function called get_size(n,dir,files). This > is the code: > > import os > > def get_size(n,dir,files): Don't use dir. You're masking a built-in. > files_of_size = {}; sizes = []; > biggest_files = []; files_sizes = []; You can get rid of files_sizes. It's not used. > files = map(os.path.join,[dir] * len(files),files) When debugging, it helps to put a few print statements here and there to see what's going on. Put one here to print 'files' list. > files = filter(lambda x: not os.path.isdir(x) > and not os.path.islink(x), > os.listdir(dir)) And put one here to print 'files' list. Putting in those print statements might help you see that you need to replace 'os.listdir(dir)' in above line with 'files'. That way you don't lose your path information. > > for f in files: > > files_of_size.setdefault(os.path.getsize(f),[]).append(f) > > sizes = files_of_size.keys() > sizes.sort(); sizes.reverse(); > for s in sizes: > biggest_files.append([files_of_size[s],s]) > > while n > 0: > print biggest_files[n-1] > n = n - 1 > import os def get_size(n,dir,files): print dir files_of_size = {}; sizes = []; biggest_files = []; files = map(os.path.join,[dir] * len(files),files) #print files files = filter(lambda x: not os.path.isdir(x) and not os.path.islink(x),files) #print files for f in files: files_of_size.setdefault(os.path.getsize(f),[]).append(f) sizes = files_of_size.keys() sizes.sort(); sizes.reverse(); for s in sizes: biggest_files.append([files_of_size[s],s]) for f in biggest_files[:3]: print f if __name__ == '__main__': os.path.walk('/tmp',get_size,3) I ran this on my /tmp directory. One of the directories in there had about 1000 0-byte files, and nothing larger than that. So I got back a huge list of 0 byte files for that dir. That behavior may or may not be what you want. Hope that helps. Rich From rmkrauter at yahoo.com Fri Feb 13 21:15:36 2004 From: rmkrauter at yahoo.com (Rich Krauter) Date: Fri Feb 13 21:20:54 2004 Subject: [Tutor] making a function work with os.path.walk() In-Reply-To: <1076724542.12618.28.camel@vaio> References: <20040214000531.44750.qmail@web12404.mail.yahoo.com> <1076724542.12618.28.camel@vaio> Message-ID: <1076724936.12618.34.camel@vaio> On Fri, 2004-02-13 at 21:09, Rich Krauter wrote: > for f in biggest_files[:3]: > print f oops - the 3 should be n. Rich From shitizb at yahoo.com Sat Feb 14 06:59:00 2004 From: shitizb at yahoo.com (Shitiz Bansal) Date: Sat Feb 14 06:59:08 2004 Subject: [Tutor] Saving Excel file as HTML Message-ID: <20040214115900.33837.qmail@web41502.mail.yahoo.com> hi, I have been using python to Automate Excel using the Dispatch method in win32com module. I have written a script to create and write an excel doc. I want to save this document in HTML format. I used the visual basic editor in excel macros to find out the desired syntax. but unfortunately i am getting an error. Can anybody help. Also i would like to know if i can somehow set the width of individual columns in excel .Microsoft help didnt help much. here is a part of my script: x=listdir('C:\\teams/'+j+'/teams') xlApp.Workbooks.Add() xlBook = xlApp.Workbooks(1) xlSheet = xlApp.Sheets(1) xlSheet.Cells(1,1).Value = 'TeamName' xlSheet.Cells(1,2).Value = 'Institute' xlSheet.Cells(1,3).Value = 'Team Members' ...... xlBook.SaveAs(Filename='C:\\temp1\\'+j ,FileFormat='xlHtml') xlBook.Close() Traceback (most recent call last): File "C:\Documents and Settings\Shitiz\Desktop\tryst_scripts\done1.py", line 38, in ? xlBook.SaveAs(Filename='C:\\temp1\\'+j ,FileFormat='xlHtml') File "<COMObject <unknown>>", line 2, in SaveAs com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Excel', 'SaveAs method of Workbook class failed', 'C:\\Program Files\\Microsoft Office\\Office10\\1033\\xlmain10.chm', 0, -2146827284), None) --------------------------------- Do you Yahoo!? Yahoo! Finance: Get your refund fast by filing online -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040214/3d6d84af/attachment.html From rmkrauter at yahoo.com Sat Feb 14 10:09:04 2004 From: rmkrauter at yahoo.com (Rich Krauter) Date: Sat Feb 14 10:14:17 2004 Subject: [Tutor] Saving Excel file as HTML In-Reply-To: <20040214115900.33837.qmail@web41502.mail.yahoo.com> References: <20040214115900.33837.qmail@web41502.mail.yahoo.com> Message-ID: <1076771343.13106.6.camel@vaio> On Sat, 2004-02-14 at 06:59, Shitiz Bansal wrote: > hi, > I have been using python to Automate Excel using the Dispatch method > in win32com module. > I have written a script to create and write an excel doc. > I want to save this document in HTML format. > > I used the visual basic editor in excel macros to find out the desired > syntax. > but unfortunately i am getting an error. > Can anybody help. > Also i would like to know if i can somehow set the width of individual > columns in excel .Microsoft help didnt help much. > > here is a part of my script: > > x=listdir('C:\\teams/'+j+'/teams') > xlApp.Workbooks.Add() > xlBook = xlApp.Workbooks(1) > xlSheet = xlApp.Sheets(1) > xlSheet.Cells(1,1).Value = 'TeamName' > xlSheet.Cells(1,2).Value = 'Institute' > xlSheet.Cells(1,3).Value = 'Team Members' > ...... > This is what I tried: I manually created a worksheet in excel, and recorded the macro as I proceeded to save the document as html. Then I looked at the macro to see what excel was actually doing. I translated the VB to python to do the 'saveas' operation: xlBook.PublishObjects.Add(1,'C:/test.html',"Sheet1").Publish(True) To adjust column width, I did the same thing - record the macro, look at the resulting VB, and translate it to python: xlSheet.Columns('C:C').ColumnWidth = 50 Hope that helps. Rich From Janssen at rz.uni-frankfurt.de Sat Feb 14 10:14:15 2004 From: Janssen at rz.uni-frankfurt.de (Michael Janssen) Date: Sat Feb 14 10:14:26 2004 Subject: [Tutor] setdefault() In-Reply-To: <20040213221437.61490.qmail@web12403.mail.yahoo.com> References: <20040213221437.61490.qmail@web12403.mail.yahoo.com> Message-ID: <Pine.A41.4.56.0402141502040.144792@hermes-22.rz.uni-frankfurt.de> On Fri, 13 Feb 2004, Christopher Spears wrote: > Can someone clarify what setdefault() does? I looked > it up in the docs, and I am still confused. Whiles the doc's explanation "a[k] if k in a, else x (also setting it)" is quite clear, showing some use cases might help to understand *why* there is such a method. When not concerned about the "also setting it" part, you can as easily use the get method: >>> default = 1 >>> val = aDict.get("key", default) which is nicer to type or read than catching the exception on a hard key lookup: >>> try: val = aDict["key"] >>> except KeyError: val = default But why should one be concerned about "also setting it"? For the ease of the next lookup? No, you just can go on with the get-method and it's fine. So why is there the setdefault method? Just to spare a step when you really want to both getting and setting a value? This would be two till four lines of code. That few lines wouldn't be worth adding a method into core python. I belive existence of the setdefault method is due to a more or less common task, that would be otherwise ugly to write. Imaging a dictionary with lists as values: >>> aDict = {"a": []} Now you want to append items to the lists. It's obviously easy with an existing list: >>> aDict["a"].append(0) You can even use get (this uses python's nature of references pointing to shared objects. You need problably some time to understand this, but it's an important feature and also the basic for my setdefault usecase I'm going to show): >>> aDict.get("a").append(1) ---> get retrieves the value (a list) for key "a" and 1 gets appended on this returned lists. Since python just do references to internal objects the returned list and the list within aDict are the same object and "append(1)" reflect on aDict["a"] : >>> aDict {'a': [1, 2]} You can't either do aDict["b"].append(1) (This would be a KeyError) nor: >>> aDict.get("b", []).append(0) >>> aDict {'a': [1, 2]} ---> get("b", []) has returned a new empty list as default value. append has appended an 0 on this list, which unfurtunately has gone away because get hasn't "also setting it". This is where setdefault comes back: >>> aDict.setdefault("b", []).append(0) >>> aDict {'a': [1, 2], 'b': [0]} setdefault returns the empty list and also glueing this same list into aDict. append works on the returned list which is a reference to the same list within aDict. So, when you have a dictionary of lists and want append to them, you can do it very easy with setdefault. Say you want to analyze a webserver log and you want to know from which ip's what pages are called. In pseudo code it's somethind like this: ip2pages = {} for line in file_object: ip, page = function_to_analyze_line(line) ip2pages.setdefault(ip, []).append(page) After that ip2pages is a dictionary mapping each ip to a list of pages. Here's the handwoven version: ip2pages = {} for line in file_object: ip, page = function_to_analyze_line(line) if ip2pages.has_key(ip): ip2pages[ip].append(page) else: ip2pages[ip] = [page] The latter verson isn't much worse but setdefaulting an empty list is a common task (at least for me since I've started to analyze our webservers log ;-) and very useful, so it's worth to have such a method. You can also setdefaulting dictionaries but I havn't seen this (which doesn't say much ;-) and it looks redicolous: >>> aDict.setdefault("c", {})["new"] = 5 >>> aDict {'a': [1, 2], 'c': {'new': 5}, 'b': [0]} Setdefaulting ints, tuples or strings is much more useless, because you can't change them in place. When you work on the return value of setdefault by changing the value, a new object is created and this won't reflect within aDict's value: >>> aDict.setdefault("d", 0) + 1 1 <--- look here, a new object ;-) >>> aDict {'a': [1, 2], 'c': {'new': 5}, 'b': [0], 'd': 0} Here you're better of with get: aDict_ofInts[key] = aDict_ofInts.get(key, 0) + 1 Michael From cspears2002 at yahoo.com Sat Feb 14 18:10:25 2004 From: cspears2002 at yahoo.com (Christopher Spears) Date: Sat Feb 14 18:10:30 2004 Subject: [Tutor] losing info Message-ID: <20040214231025.38657.qmail@web12408.mail.yahoo.com> I have run up against a brick wall! I wrote a function called get_size(n,directory,files): import os def get_size(n,directory,files): files_of_size = {}; sizes = []; biggest_files = []; files = filter(lambda x: not os.path.isdir(x) and not os.path.islink(x), files) for f in files: files_of_size.setdefault(os.path.getsize(f),[]).append(f) sizes = files_of_size.keys() sizes.sort(); sizes.reverse(); for s in sizes: biggest_files.append([files_of_size[s],s]) while n > 0: print biggest_files[n-1] n = n - 1 The hard part is getting it to work with os.path.walk. This happens: os.path.walk('.',get_size,3) [['Unit5.doc'], 22016L] [['Unit8.doc'], 22528L] [['Unit6.doc'], 23552L] Traceback (most recent call last): File "", line 1, in -toplevel- os.path.walk('.',get_size,3) File "C:\Python23\lib\ntpath.py", line 333, in walk walk(name, func, arg) File "C:\Python23\lib\ntpath.py", line 327, in walk func(arg, top, names) File "C:\Documents and Settings\Christstopher Spears\My Documents\python\unit9.question1c.py", line 11, in get_size files_of_size.setdefault(os.path.getsize(f),[]).append(f) File "C:\Python23\lib\ntpath.py", line 228, in getsize return os.stat(filename).st_size OSError: [Errno 2] No such file or directory: 'DSCN4432.JPG' I've been debugging the function, and this is what I have found. The portion of the script that puts together a list of file names works for both the current directory and the directory underneath it. However, the part of the function that is supposed to assemble a dictionary of sizes and filenames is not working for the directory underneath the current directory. Somehow the list of filenames is getting lost! Hence the file DSCN4432.JPG cannot be found! What could be causing this? -Chris From sigurd at 12move.de Sat Feb 14 19:32:54 2004 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Sat Feb 14 19:33:39 2004 Subject: [Tutor] losing info In-Reply-To: <20040214231025.38657.qmail@web12408.mail.yahoo.com> (Christopher Spears's message of "Sat, 14 Feb 2004 15:10:25 -0800 (PST)") References: <20040214231025.38657.qmail@web12408.mail.yahoo.com> Message-ID: <m3oes1fclu.fsf@hamster.pflaesterer.de> On 15 Feb 2004, Christopher Spears <- cspears2002@yahoo.com wrote: > I have run up against a brick wall! I wrote a function > called get_size(n,directory,files): [Code] [...] > OSError: [Errno 2] No such file or directory: > 'DSCN4432.JPG' [...] > However, the part of the function that is supposed to > assemble a dictionary of sizes and filenames is not > working for the directory underneath the current > directory. Somehow the list of filenames is getting > lost! Hence the file DSCN4432.JPG cannot be found! > What could be causing this? Without having totally debugged your code; you semm to work with with only the filenames but not with the path to the files. So your function looks in the directory were it was called for the .jpg file and can't find it. Again a different approach for your problem (it seems my first version didn't please you). It uses a simpler version and the newer os.walk() instead of os.path.walk(). os.walk seems absolutely right for your problem (it even returns only a list of filenames so you don't have to filter the directories only the links). def get_size(d, n): files_size = {} for path, dirs, files in os.walk(d): flist = [(f, os.path.getsize(os.path.join(path, f))) for f in files if not os.path.islink(f)] fcopy = flist[:] fcopy.sort(lambda e1, e2: cmp(e1[1], e2[1])) files_size[path] = (flist, fcopy[-n:]) for f in fcopy[-n:]: print f return files_size The function returns a hash table with the directory names as keys and a tuple with the list of corresponding files and the list of the `n' biggest files as entries. Perhaps instead of putting only the file name in the list put os.path.join(path, f) in the list. The sorting is done with a custom sorting function which looks at the second element of a tuple. Instead you could put the file size as first entry in the tuple and the file name as second entry. Then the sorting according to size can be done with a simple sort(). A similar approach is also possible with os.path.walk but os.walk seems here IMO better suited and easier to use. Karl -- Please do *not* send copies of replies to me. I read the list From alan.gauld at blueyonder.co.uk Sat Feb 14 20:16:48 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Feb 14 20:16:46 2004 Subject: [Tutor] making a function work with os.path.walk() References: <20040214000531.44750.qmail@web12404.mail.yahoo.com> Message-ID: <001501c3f361$625c2890$6401a8c0@xp> CHristopher, This is a guess based on a quick scan of the code and error. > def get_size(n,dir,files): > files_of_size = {}; sizes = []; > biggest_files = []; files_sizes = []; > files = map(os.path.join,[dir] * len(files),files) > files = filter(lambda x: not os.path.isdir(x) > and not os.path.islink(x), > os.listdir(dir)) I think this will prepend the top level(starting) directory to the filenames - even for the subdirectories. Thus it contains foo/f1 foo/f2 foo/g1 # should be foo/subdir/g1 then when you try to act on g1 it can't find it because the path is wrong. I think you might need to keep track of the current path... But I may be barking up the wrong tree, its very late... Alan G. From cspears2002 at yahoo.com Sat Feb 14 20:25:18 2004 From: cspears2002 at yahoo.com (Christopher Spears) Date: Sat Feb 14 20:25:22 2004 Subject: [Tutor] thanks! Message-ID: <20040215012518.80748.qmail@web12402.mail.yahoo.com> I solved the problem! As several have pointed out, I was providing file names not pathways. Here is the resulting code: import os def get_size(n,directory,files): files_of_size = {}; sizes = []; biggest_files = []; files = map(os.path.join,[directory] * len(files),files) files = filter(lambda x: not os.path.isdir(x) and not os.path.islink(x), files) #Creates a list of file pathnames. for f in files: files_of_size.setdefault(os.path.getsize(f),[]).append(f) #Creates a dictionary where the keys are the sizes. sizes = files_of_size.keys() sizes.sort(); sizes.reverse(); for s in sizes: biggest_files.append([files_of_size[s],s]) #Sorts keys from largest to smallest and places the names in a #new list in that order. print "in directory %s:" % directory try: while n > 0: print biggest_files[n-1] n = n - 1 except IndexError,msg: print "%d is too high. Try a smaller number" %n #Prints out the n largest files. Notice I do not use a lot of functional programming. I have nothing against functional programming. I just do not undertand much of it, which is why I took this particular approach. Karl has pointed out several times that if I used functional programming then my code would be much more succinct. Thanks! From sigurd at 12move.de Sat Feb 14 22:21:56 2004 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Sat Feb 14 22:59:22 2004 Subject: [Tutor] thanks! In-Reply-To: <20040215012518.80748.qmail@web12402.mail.yahoo.com> (Christopher Spears's message of "Sat, 14 Feb 2004 17:25:18 -0800 (PST)") References: <20040215012518.80748.qmail@web12402.mail.yahoo.com> Message-ID: <m3k72pf3zo.fsf@hamster.pflaesterer.de> On 15 Feb 2004, Christopher Spears <- cspears2002@yahoo.com wrote: > I solved the problem! As several have pointed out, I Congrats. > was providing file names not pathways. Here is the > resulting code: [Code] > Notice I do not use a lot of functional programming. You use map() and filter(). It's a good start :-) > I have nothing against functional programming. I just > do not undertand much of it, which is why I took this I had the (maybe wrong) impression that you wanted to use functional style. Some annotations to your solution if you like: > files = map(os.path.join,[directory] * > len(files),files) If you just want to join the file with its path there's no need to create a list of directories. map(lambda f: os.path.join(d, f), files) (with d == directory) will suffice. Or write it with a list comprehension. To create a list to throw it in the next moment away is too expensive; even more the function len() should only get used when you absolutely need it; it has to traverse the whole list to find its length. > sizes.sort(); sizes.reverse(); > for s in sizes: > biggest_files.append([files_of_size[s],s]) > #Sorts keys from largest to smallest and places the > names in a > #new list in that order. You use here a list to hold exactly two values which won't get changed: [files_of_size[s],s]; a tuple is here the better choice. Lists should get used if you don't know in advance how much values will be in the sequence and if you want to change the values afterwards; if not use a tuple which gives you faster code. General: most people write the comments *above* the according code; furthermore there are good articles about how to write comments and what to write in a comment and what not. E.g. there's no need to write the code a second time the way you did it; that doesn't help the reader (we assume he knows Python); better explain why something is written the way it's written; e.g. most people would use a tuple as container but if you chose a list it might be worth to explain why. Karl -- Please do *not* send copies of replies to me. I read the list From syrinx at simplecom.net Sat Feb 14 23:21:16 2004 From: syrinx at simplecom.net (Scott) Date: Sat Feb 14 23:23:20 2004 Subject: [Tutor] select.select Message-ID: <20040214222116.2e5f3b0e.syrinx@simplecom.net> What do you do with the list of "sockets in error" that is returned by select, if it's not empty? How do you find out what the error was? r, w, e = select.select(socketList, socketList, socketList) What do you do with 'e?' Thanks. From marilyn at deliberate.com Sun Feb 15 02:25:40 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Sun Feb 15 02:25:46 2004 Subject: [Tutor] Re: copies deep and shallow In-Reply-To: <1mlixueuzmmso$.1nnvan3yigy5d$.dlg@40tude.net> Message-ID: <Pine.LNX.4.44.0402142238080.11161-100000@Kuna> On Fri, 13 Feb 2004, Andrei wrote: > Marilyn Davis wrote on Fri, 13 Feb 2004 09:21:31 -0800 (PST): > > <snip> > > So shallow copies are independent at the first level but dependent at > > deeper levels. > > I'm not sure what you mean by "deeper levels". If your whatever you copy > only contains immutable components (string, numbers, tuples), there isn't > really any danger in this because you can't change them in-place anyway > (ragardless of how many levels deep the tuple is for example). > > > Why would someone want a shallow copy? It seems like trouble lurking. > > Try this in the interactive interpreter: > > a = range(2000000) # make that 4mln if you have 512 MB or 1mln for 128MB > b = copy.deepcopy(a) > c = copy.copy(a) > > Noticed any difference? Also it's not dangerous if you're using immutable > items. Thank you. But how is c = copy.copy(a) better than c = a in this example? Is it true that a = b.copy() does the same thing as a = copy.copy(b) for dictionaries? And is it true that for lists, a = b[:] does the same thing as a = copy.copy(b)? > > > I would think you'd either want a completely deep copy, or a reference to > > the same everything. > > Generally I use deepcopy just to be on the safe side, but that's not such a > big problem since I don't tend to use very large amounts of data when > copying. I would think it would be unusual to make a copy of dictionary, deep or shallow. I would think that you usually need a reference because you keep data in dictionaries and you don't want a branch in your data -- unless you do want a branch in your data. Or maybe you want a deep copy when you pass your dictionary to an unknown function and you want to be sure it doesn't mess with your original? When would you prefer a shallow copy of a dictionary over a reference to a dictionary? I can't think of an example of that. I can't get beyond thinking that you either want a deep copy or a reference. I must be missing something because there appears to be two ways to make shallow copies for dictionaries and for lists. There must be a good reason. Any insights would be appreciated. Thank you again. Marilyn > > -- From project5 at redrival.net Sun Feb 15 06:09:20 2004 From: project5 at redrival.net (Andrei) Date: Sun Feb 15 06:12:55 2004 Subject: [Tutor] Re: Re: copies deep and shallow References: <1mlixueuzmmso$.1nnvan3yigy5d$.dlg@40tude.net> <Pine.LNX.4.44.0402142238080.11161-100000@Kuna> Message-ID: <1c6luj9gsn5fn.198l7wfik7ifj$.dlg@40tude.net> Marilyn Davis wrote on Sat, 14 Feb 2004 23:25:40 -0800 (PST): > On Fri, 13 Feb 2004, Andrei wrote: > <snip> >> Try this in the interactive interpreter: >> >> a = range(2000000) # make that 4mln if you have 512 MB or 1mln for 128MB >> b = copy.deepcopy(a) >> c = copy.copy(a) >> >> Noticed any difference? Also it's not dangerous if you're using immutable >> items. > > Thank you. > > But how is c = copy.copy(a) better than c = a in this example? Well, copy makes a copy and c=a does not, it just says that c is the same list as a. Just try this (on top of the earlier example): d = a d[0] = 500 print a[0], b[0], c[0], d[0] You will notice that b and c have not changed, but d *and a* have. > Is it true that a = b.copy() does the same thing as a = copy.copy(b) for > dictionaries? The docs say that a.copy() makes a shallow copy of a, so I suppose it is. > And is it true that for lists, a = b[:] does the same thing as a = > copy.copy(b)? Let's try it out: >>> e = [[0, 1], [2, 3], [4, 5]] >>> f = e[1:] >>> f[1].append(6) # modify item in-place >>> e, f ([[0, 1], [2, 3], [4, 5, 6]], [[2, 3], [4, 5, 6]]) So it did indeed execute a shallow copy - if we modify one of the lists inside f, the corresponding list in e changes too. > I would think it would be unusual to make a copy of dictionary, deep > or shallow. I would think that you usually need a reference because > you keep data in dictionaries and you don't want a branch in your data > -- unless you do want a branch in your data. Well, sometimes you do want a branch :). Dictionaries are not immutable, so they're not meant to just keep constants in them. > Or maybe you want a deep copy when you pass your dictionary to an > unknown function and you want to be sure it doesn't mess with your > original? I use deepcopies for this purpose, even when I pass certain dicts to some functions I write myself - just because I think that maybe at some point I might decide to change the dict in that function and then I'd end up debugging errors due to those changes. > When would you prefer a shallow copy of a dictionary over a reference > to a dictionary? I can't think of an example of that. When the dictionary doesn't contain mutable items perhaps and you want to be certain the original dictionary isn't changed. For example look at this: >>> g = {0:1, 2:3, 4:5} >>> h = g.copy() >>> h[0] = 2 >>> g, h ({0: 1, 2: 3, 4: 5}, {0: 2, 2: 3, 4: 5}) Why would you use a (very slow) deepcopy when it doesn't offer any extra functionality? I can't modify integers/strings/tuples in-place, so I can't accidentally change g by changing something in h. If I'd just used a reference, the result would have been this (g is modified as well): >>> h = g >>> h[0] = 2 >>> g, h ({0: 2, 2: 3, 4: 5}, {0: 2, 2: 3, 4: 5}) I use references e.g. when I read items from some nested dictionary. E.g. if I have a nested dictionary and I'm interested in keys inside data["feeds"][0]["items"][0].keys(), I'll probably just do this: item = data["feeds"][0]["items"][0] item["somekey"] = newvalue item["otherkey"] = othervalue I *want* the original dictionary in data["feeds"][0]["items"][0] to be changed, so obviously I won't do a copy - the item=... assignment is only meant to add some clarity to the code and save me some typing. If I meant to change that particular item but did not want the changes to go back in the nested dictionary I'd have used copy (if the dictionary only contains immutable values) or deepcopy (if it contains mutable values). But generally speaking you can ignore copy if you wish and write perfectly reasonable applications without even knowing it exists :). But then again, you can also ignore deepcopy if you wish, or dictionaries all together (there are plenty of languages without a dictionary type) or... Oh, and I should point out that the docs mention two possible gotchas of deepcopy (in paragraph 3.18): - Recursive objects (compound objects that, directly or indirectly, contain a reference to themselves) may cause a recursive loop. - Because deep copy copies everything it may copy too much, e.g., administrative data structures that should be shared even between copies. -- Yours, Andrei ===== Mail address in header catches spam. 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 savithari at yahoo.com Sun Feb 15 12:01:21 2004 From: savithari at yahoo.com (Savitha 'n' Narahari) Date: Sun Feb 15 12:01:30 2004 Subject: [Tutor] environment variable setting Message-ID: <20040215170121.6544.qmail@web40307.mail.yahoo.com> Hello All: I know this question has been asked before, but I could not find the answer. So here it goes. I currently use JScript and VBScript on WindozeXP to set environment variables and make them permanent in the system space(not for user). This is very handy for me in the scripts I write. I am now trying to replace JScript and VBScript with python since I think it is very portable. However, I could not find a way to persist the environment variables once I leave the python script, aka I cannot persist it. I dont want to use the registry approach since it constrains me to Windoze platform. So the summary question is How do you make either putenv or os.environ["DATETIME"]="01022004" permanent, meaning even after rebooting the box ? Thanks -Narahari __________________________________ Do you Yahoo!? Yahoo! Finance: Get your refund fast by filing online. http://taxes.yahoo.com/filing.html From shitizb at yahoo.com Sun Feb 15 22:58:49 2004 From: shitizb at yahoo.com (Shitiz Bansal) Date: Sun Feb 15 22:58:58 2004 Subject: [Tutor] PYCPrintInfo object Message-ID: <20040216035849.38141.qmail@web41508.mail.yahoo.com> hi, How do i create a PYCPrintInfo object in python win32. can anybody give em an example?? shitiz --------------------------------- Do you Yahoo!? Yahoo! Finance: Get your refund fast by filing online -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040215/8cabe2da/attachment.html From isrgish at fusemail.com Mon Feb 16 10:13:10 2004 From: isrgish at fusemail.com (Isr Gish) Date: Mon Feb 16 10:13:18 2004 Subject: [Tutor] Re: get_size(n,directory,files) Message-ID: <E1AskQl-0005yu-MJ@fuse1.fusemail.net> Christropher, I was wondering, that when you add each file to your dictonary files_of_size{}. If there would be 2 files with same size you would only get the second one in the dict. This may be a rare thing, but in that why start with a dict then maKe a list of it. I think you should use a list to begin with. biggest_files = [(f, os.path.getsize(f)) for f in files] Then the whole function can be written like this. def get_size(n,directory,files): #Creates a list of tuples (filepathname, size). (or you could change this '(' to '[' and ')' to ']' for a list). files = [os.path.join(directory, f) for f in files] biggest_files = [(f, os.path.getsize(f)) for f in files if not os.path.isdir(f) and not os.path.islink(f)] biggest_files.sort(lambda f1, f2: cmp(f2[1], f1[1])) print "in directory %s:" % directory try: while n > 0: print biggest_files[n-1] n -= 1 except IndexError, msg: print "%d is too high. Try a smaller number" %n #Prints out the n largest files. All the best, Isr From glingl at aon.at Mon Feb 16 12:52:29 2004 From: glingl at aon.at (Gregor Lingl) Date: Mon Feb 16 12:51:44 2004 Subject: [Tutor] request to run program on a Linux machine Message-ID: <4031035D.2060808@aon.at> Hi! At the moment I unfortunately don't have a computer running Linux at hand, so ... ... is there anybody out there using a machine running Python 2.3 with Tkinter under Linux, who is willing to run the attached program and give me feedback concerning two questions: (1) Does the program run smoothly (2) Does it terminate without error-messages (TclError) when the window is closed while the animation is running (i. e. while a disc is moving). This can be seen e.g. when you run it from within IDLE or from the commandline of some console window ... Many thanks in advance Gregor P.S. A second posting concerning this Hanoi program, concerning some remarks on the problem mentioned above will follow. -------------- next part -------------- ## Animated Tower-Of-Hanoi game with Tkinter GUI ## author: Gregor Lingl, Vienna, Austria ## email: glingl@aon.at ## date: 16. 2. 2004 from Tkinter import * class Disc: """Movable Rectangle on a Tkinter Canvas""" def __init__(self,cv,pos,length,height,colour): """creates disc on given Canvas cv at given pos-ition""" x0, y0 = pos x1, x2 = x0-length/2.0, x0+length/2.0 y1, y2 = y0-height, y0 self.cv = cv self.item = cv.create_rectangle(x1,y1,x2,y2, fill = "#%02x%02x%02x" % colour) def move_to(self, x, y, speed): """moves bottom center of disc to position (x,y). speed is intended to assume values from 1 to 10""" x1,y1,x2,y2 = self.cv.coords(self.item) x0, y0 = (x1 + x2)/2, y2 dx, dy = x-x0, y-y0 d = (dx**2+dy**2)**0.5 steps = int(d/(10*speed-5)) + 1 dx, dy = dx/steps, dy/steps for i in range(steps): self.cv.move(self.item,dx,dy) self.cv.update() self.cv.after(20) class Tower(list): """Hanoi tower designed as a subclass of built-in type list""" def __init__(self, x, y, h): """ creates an empty tower. (x,y) is floor-level position of tower, h is height of the discs. """ self.x = x self.y = y self.h = h def top(self): return self.x, self.y - len(self)*self.h class HanoiEngine: """Plays the Hanoi-game on a given canvas.""" def __init__(self, canvas, nrOfDiscs, speed, moveCntDisplay=None): """Sets Canvas to play on as well as default values for number of discs and animation-speed. moveCntDisplay is a function with 1 parameter, which communicates the count of the actual move to the GUI containing the Hanoi-engine-canvas.""" self.cv = canvas self.nrOfDiscs = nrOfDiscs self.speed = speed self.moveDisplay = moveCntDisplay self.running = False self.moveCnt = 0 self.discs = [] self.towerA = Tower( 80, 190, 15) self.towerB = Tower(220, 190, 15) self.towerC = Tower(360, 190, 15) self.reset() def hanoi(self, n, src, dest, temp): """The classical recursive Towers-Of-Hanoi algorithm.""" if n > 0: for x in self.hanoi(n-1, src, temp, dest): yield None yield self.move(src, dest) for x in self.hanoi(n-1, temp, dest, src): yield None def move(self, src_tower, dest_tower): """moves uppermost disc of source tower to top of destination tower.""" self.moveCnt += 1 self.moveDisplay(self.moveCnt) disc = src_tower.pop() x1, y1 = src_tower.top() x2, y2 = dest_tower.top() disc.move_to(x1,20, self.speed) disc.move_to(x2,20, self.speed) disc.move_to(x2,y2, self.speed) dest_tower.append(disc) def reset(self): """Setup of (a new) game.""" self.moveCnt = 0 self.moveDisplay(self.moveCnt) while self.towerA: self.towerA.pop() while self.towerB: self.towerB.pop() while self.towerC: self.towerC.pop() for s in self.discs: self.cv.delete(s.item) ## Fancy colouring of discs: red ===> blue if self.nrOfDiscs > 1: colour_diff = 255 // (self.nrOfDiscs-1) else: colour_diff = 0 for i in range(self.nrOfDiscs): # setup towerA length_diff = 100 // self.nrOfDiscs length = 120 - i * length_diff s = Disc( self.cv, self.towerA.top(), length, 13, (255-i*colour_diff, 0, i*colour_diff)) self.discs.append(s) self.towerA.append(s) self.HG = self.hanoi(self.nrOfDiscs, self.towerA, self.towerC, self.towerB) def run(self): """runs game ;-) returns True if game is over, else False""" self.running = True try: while self.running: result = self.step() return result # True iff done except StopIteration: # game over return True except TclError: # for silently terminating in case of window closing return False def step(self): """performs one single step of the game, returns True if finished, else False""" self.HG.next() return 2**self.nrOfDiscs-1 == self.moveCnt def stop(self): """ ;-) """ self.running = False class Hanoi: """GUI for animated towers-of-Hanoi-game with upto 10 discs:""" def displayMove(self, move): """method to be passed to the Hanoi-engine as a callback to report move-count""" self.moveCntLbl.configure(text = "move:\n%d" % move) def adjust_nr_of_discs(self, e): """callback function for nr-of-discs-scale-widget""" self.hEngine.nrOfDiscs = self.discs.get() self.reset() def adjust_speed(self, e): """callback function for speeds-scale-widget""" self.hEngine.speed = self.tempo.get() def setState(self, STATE): """most simple representation of a finite state machine""" self.state = STATE try: if STATE == "START": self.discs.configure(state=NORMAL) self.discs.configure(fg="black") self.discsLbl.configure(fg="black") self.resetBtn.configure(state=DISABLED) self.startBtn.configure(text="start", state=NORMAL) self.stepBtn.configure(state=NORMAL) elif STATE == "RUNNING": self.discs.configure(state=DISABLED) self.discs.configure(fg="gray70") self.discsLbl.configure(fg="gray70") self.resetBtn.configure(state=DISABLED) self.startBtn.configure(text="pause", state=NORMAL) self.stepBtn.configure(state=DISABLED) elif STATE == "PAUSE": self.discs.configure(state=NORMAL) self.discs.configure(fg="black") self.discsLbl.configure(fg="black") self.resetBtn.configure(state=NORMAL) self.startBtn.configure(text="resume", state=NORMAL) self.stepBtn.configure(state=NORMAL) elif STATE == "DONE": self.discs.configure(state=NORMAL) self.discs.configure(fg="black") self.discsLbl.configure(fg="black") self.resetBtn.configure(state=NORMAL) self.startBtn.configure(text="start", state=DISABLED) self.stepBtn.configure(state=DISABLED) elif STATE == "TIMEOUT": self.discs.configure(state=DISABLED) self.discs.configure(fg="gray70") self.discsLbl.configure(fg="gray70") self.resetBtn.configure(state=DISABLED) self.startBtn.configure(state=DISABLED) self.stepBtn.configure(state=DISABLED) except TclError: pass def reset(self): """restores START state for a new game""" self.hEngine.reset() self.setState("START") def start(self): """callback function for start button, which also serves as pause button. Makes hEngine running until done or interrupted""" if self.state in ["START", "PAUSE"]: self.setState("RUNNING") if self.hEngine.run(): self.setState("DONE") else: self.setState("PAUSE") elif self.state == "RUNNING": self.setState("TIMEOUT") self.hEngine.stop() def step(self): """callback function for step button. makes hEngine perform a single step""" self.setState("TIMEOUT") if self.hEngine.step(): self.setState("DONE") else: self.setState("PAUSE") def __init__(self, nrOfDiscs, speed): """builds GUI, constructs Hanoi-engine and puts it into START state then launches mainloop()""" root = Tk() root.title("TOWERS OF HANOI") #root.protocol("WM_DELETE_WINDOW",root.quit) #counter productive here!? cv = Canvas(root,width=440,height=210, bg="gray90") cv.pack() fnt = ("Arial", 12, "bold") attrFrame = Frame(root) #contains scales to adjust game's attributes self.discsLbl = Label(attrFrame, width=7, height=2, font=fnt, text="discs:\n") self.discs = Scale(attrFrame, from_=1, to_=10, orient=HORIZONTAL, font=fnt, length=75, showvalue=1, repeatinterval=10, command=self.adjust_nr_of_discs) self.discs.set(nrOfDiscs) self.tempoLbl = Label(attrFrame, width=8, height=2, font=fnt, text = " speed:\n") self.tempo = Scale(attrFrame, from_=1, to_=10, orient=HORIZONTAL, font=fnt, length=100, showvalue=1,repeatinterval=10, command = self.adjust_speed) self.tempo.set(speed) self.moveCntLbl= Label(attrFrame, width=5, height=2, font=fnt, padx=20, text=" move:\n0", anchor=CENTER) for widget in ( self.discsLbl, self.discs, self.tempoLbl, self.tempo, self.moveCntLbl ): widget.pack(side=LEFT) attrFrame.pack(side=TOP) ctrlFrame = Frame(root) # contains Buttons to control the game self.resetBtn = Button(ctrlFrame, width=11, text="reset", font=fnt, state = DISABLED, padx=15, command = self.reset) self.stepBtn = Button(ctrlFrame, width=11, text="step", font=fnt, state = NORMAL, padx=15, command = self.step) self.startBtn = Button(ctrlFrame, width=11, text="start", font=fnt, state = NORMAL, padx=15, command = self.start) for widget in self.resetBtn, self.stepBtn, self.startBtn: widget.pack(side=LEFT) ctrlFrame.pack(side=TOP) # setup of the scene peg1 = cv.create_rectangle( 75, 40, 85, 190, fill='darkgreen') peg2 = cv.create_rectangle( 215, 40, 225, 190, fill='darkgreen') peg3 = cv.create_rectangle( 355, 40, 365, 190, fill='darkgreen') floor = cv.create_rectangle( 10, 191, 430, 200, fill='black') self.hEngine = HanoiEngine(cv, nrOfDiscs, speed, self.displayMove) self.state = "START" root.mainloop() if __name__ == "__main__": Hanoi(4,5) From glingl at aon.at Mon Feb 16 13:43:53 2004 From: glingl at aon.at (Gregor Lingl) Date: Mon Feb 16 13:43:05 2004 Subject: [Tutor] OIAW: feedback on program requested Message-ID: <40310F69.5070608@aon.at> Hi pythonistas! Once in a while I like to get some feedback on a program I wrote. This time it's an animated tower of hanoi game with a Tkinter - GUI. It uses some of the newer features of Python and will run only under Python 2.3 except you import generators from __future__. Although the program has about 270 lines, I hope the code is well structured so you can get a good overview quickly. Generally *feedback of any sort* is welcome, from comments on program design to corrections of malformed docstrings and comments (my English is a bit error prone). And also it you like it or not ;-) Specifically there are a few points I'd like to read your opinion about ( - is this well done, useful, overkill, dengerous etc.): (1) Making Tower a subclass of the builtin type list (2) Using a generator for the wellknown tower-of-hanoi-algorithm in order to achieve execution of single steps, as well as interrupting and resuming the game, easily. (So I use a generator only for its side-effect.) (3) I've tried to separate the Hanoi-Engine, which operates on a Tkinter-Canvas, completely from the (rest of the) user interface to make it reusable (if there is anybody who wants to reuse a Hanoi-game-canvas ;-) ) (4) A problem, for which I really don't know what's the canonical way to handle it, is peaceful termination the program while the animation is going on. That means how to terminate the program by CLOSING the WINDOW without issueing error-messages? I did it by catching TclErrors at two specific points: (a) in the run() method of HanoiEngine, which finally moves the discs (b) in the setState() method of Hanoi (the GUI-building class), which configers the widgets of the GUI. Without these two try: - except TclError: statements, closing the window while the game is running results in a TclError. I did not succeed in using the protocol-method as it inhibits terminating the priogram while the animatino is going on. Many thanks for your feedback in advance Gregor -------------- next part -------------- ## Animated Tower-Of-Hanoi game with Tkinter GUI ## author: Gregor Lingl, Vienna, Austria ## email: glingl@aon.at ## date: 16. 2. 2004 from Tkinter import * class Disc: """Movable Rectangle on a Tkinter Canvas""" def __init__(self,cv,pos,length,height,colour): """creates disc on given Canvas cv at given pos-ition""" x0, y0 = pos x1, x2 = x0-length/2.0, x0+length/2.0 y1, y2 = y0-height, y0 self.cv = cv self.item = cv.create_rectangle(x1,y1,x2,y2, fill = "#%02x%02x%02x" % colour) def move_to(self, x, y, speed): """moves bottom center of disc to position (x,y). speed is intended to assume values from 1 to 10""" x1,y1,x2,y2 = self.cv.coords(self.item) x0, y0 = (x1 + x2)/2, y2 dx, dy = x-x0, y-y0 d = (dx**2+dy**2)**0.5 steps = int(d/(10*speed-5)) + 1 dx, dy = dx/steps, dy/steps for i in range(steps): self.cv.move(self.item,dx,dy) self.cv.update() self.cv.after(20) class Tower(list): """Hanoi tower designed as a subclass of built-in type list""" def __init__(self, x, y, h): """ creates an empty tower. (x,y) is floor-level position of tower, h is height of the discs. """ self.x = x self.y = y self.h = h def top(self): return self.x, self.y - len(self)*self.h class HanoiEngine: """Plays the Hanoi-game on a given canvas.""" def __init__(self, canvas, nrOfDiscs, speed, moveCntDisplay=None): """Sets Canvas to play on as well as default values for number of discs and animation-speed. moveCntDisplay is a function with 1 parameter, which communicates the count of the actual move to the GUI containing the Hanoi-engine-canvas.""" self.cv = canvas self.nrOfDiscs = nrOfDiscs self.speed = speed self.moveDisplay = moveCntDisplay self.running = False self.moveCnt = 0 self.discs = [] self.towerA = Tower( 80, 190, 15) self.towerB = Tower(220, 190, 15) self.towerC = Tower(360, 190, 15) self.reset() def hanoi(self, n, src, dest, temp): """The classical recursive Towers-Of-Hanoi algorithm.""" if n > 0: for x in self.hanoi(n-1, src, temp, dest): yield None yield self.move(src, dest) for x in self.hanoi(n-1, temp, dest, src): yield None def move(self, src_tower, dest_tower): """moves uppermost disc of source tower to top of destination tower.""" self.moveCnt += 1 self.moveDisplay(self.moveCnt) disc = src_tower.pop() x1, y1 = src_tower.top() x2, y2 = dest_tower.top() disc.move_to(x1,20, self.speed) disc.move_to(x2,20, self.speed) disc.move_to(x2,y2, self.speed) dest_tower.append(disc) def reset(self): """Setup of (a new) game.""" self.moveCnt = 0 self.moveDisplay(self.moveCnt) while self.towerA: self.towerA.pop() while self.towerB: self.towerB.pop() while self.towerC: self.towerC.pop() for s in self.discs: self.cv.delete(s.item) ## Fancy colouring of discs: red ===> blue if self.nrOfDiscs > 1: colour_diff = 255 // (self.nrOfDiscs-1) else: colour_diff = 0 for i in range(self.nrOfDiscs): # setup towerA length_diff = 100 // self.nrOfDiscs length = 120 - i * length_diff s = Disc( self.cv, self.towerA.top(), length, 13, (255-i*colour_diff, 0, i*colour_diff)) self.discs.append(s) self.towerA.append(s) self.HG = self.hanoi(self.nrOfDiscs, self.towerA, self.towerC, self.towerB) def run(self): """runs game ;-) returns True if game is over, else False""" self.running = True try: while self.running: result = self.step() return result # True iff done except StopIteration: # game over return True except TclError: # for silently terminating in case of window closing return False def step(self): """performs one single step of the game, returns True if finished, else False""" self.HG.next() return 2**self.nrOfDiscs-1 == self.moveCnt def stop(self): """ ;-) """ self.running = False class Hanoi: """GUI for animated towers-of-Hanoi-game with upto 10 discs:""" def displayMove(self, move): """method to be passed to the Hanoi-engine as a callback to report move-count""" self.moveCntLbl.configure(text = "move:\n%d" % move) def adjust_nr_of_discs(self, e): """callback function for nr-of-discs-scale-widget""" self.hEngine.nrOfDiscs = self.discs.get() self.reset() def adjust_speed(self, e): """callback function for speeds-scale-widget""" self.hEngine.speed = self.tempo.get() def setState(self, STATE): """most simple representation of a finite state machine""" self.state = STATE try: if STATE == "START": self.discs.configure(state=NORMAL) self.discs.configure(fg="black") self.discsLbl.configure(fg="black") self.resetBtn.configure(state=DISABLED) self.startBtn.configure(text="start", state=NORMAL) self.stepBtn.configure(state=NORMAL) elif STATE == "RUNNING": self.discs.configure(state=DISABLED) self.discs.configure(fg="gray70") self.discsLbl.configure(fg="gray70") self.resetBtn.configure(state=DISABLED) self.startBtn.configure(text="pause", state=NORMAL) self.stepBtn.configure(state=DISABLED) elif STATE == "PAUSE": self.discs.configure(state=NORMAL) self.discs.configure(fg="black") self.discsLbl.configure(fg="black") self.resetBtn.configure(state=NORMAL) self.startBtn.configure(text="resume", state=NORMAL) self.stepBtn.configure(state=NORMAL) elif STATE == "DONE": self.discs.configure(state=NORMAL) self.discs.configure(fg="black") self.discsLbl.configure(fg="black") self.resetBtn.configure(state=NORMAL) self.startBtn.configure(text="start", state=DISABLED) self.stepBtn.configure(state=DISABLED) elif STATE == "TIMEOUT": self.discs.configure(state=DISABLED) self.discs.configure(fg="gray70") self.discsLbl.configure(fg="gray70") self.resetBtn.configure(state=DISABLED) self.startBtn.configure(state=DISABLED) self.stepBtn.configure(state=DISABLED) except TclError: pass def reset(self): """restores START state for a new game""" self.hEngine.reset() self.setState("START") def start(self): """callback function for start button, which also serves as pause button. Makes hEngine running until done or interrupted""" if self.state in ["START", "PAUSE"]: self.setState("RUNNING") if self.hEngine.run(): self.setState("DONE") else: self.setState("PAUSE") elif self.state == "RUNNING": self.setState("TIMEOUT") self.hEngine.stop() def step(self): """callback function for step button. makes hEngine perform a single step""" self.setState("TIMEOUT") if self.hEngine.step(): self.setState("DONE") else: self.setState("PAUSE") def __init__(self, nrOfDiscs, speed): """builds GUI, constructs Hanoi-engine and puts it into START state then launches mainloop()""" root = Tk() root.title("TOWERS OF HANOI") #root.protocol("WM_DELETE_WINDOW",root.quit) #counter productive here!? cv = Canvas(root,width=440,height=210, bg="gray90") cv.pack() fnt = ("Arial", 12, "bold") attrFrame = Frame(root) #contains scales to adjust game's attributes self.discsLbl = Label(attrFrame, width=7, height=2, font=fnt, text="discs:\n") self.discs = Scale(attrFrame, from_=1, to_=10, orient=HORIZONTAL, font=fnt, length=75, showvalue=1, repeatinterval=10, command=self.adjust_nr_of_discs) self.discs.set(nrOfDiscs) self.tempoLbl = Label(attrFrame, width=8, height=2, font=fnt, text = " speed:\n") self.tempo = Scale(attrFrame, from_=1, to_=10, orient=HORIZONTAL, font=fnt, length=100, showvalue=1,repeatinterval=10, command = self.adjust_speed) self.tempo.set(speed) self.moveCntLbl= Label(attrFrame, width=5, height=2, font=fnt, padx=20, text=" move:\n0", anchor=CENTER) for widget in ( self.discsLbl, self.discs, self.tempoLbl, self.tempo, self.moveCntLbl ): widget.pack(side=LEFT) attrFrame.pack(side=TOP) ctrlFrame = Frame(root) # contains Buttons to control the game self.resetBtn = Button(ctrlFrame, width=11, text="reset", font=fnt, state = DISABLED, padx=15, command = self.reset) self.stepBtn = Button(ctrlFrame, width=11, text="step", font=fnt, state = NORMAL, padx=15, command = self.step) self.startBtn = Button(ctrlFrame, width=11, text="start", font=fnt, state = NORMAL, padx=15, command = self.start) for widget in self.resetBtn, self.stepBtn, self.startBtn: widget.pack(side=LEFT) ctrlFrame.pack(side=TOP) # setup of the scene peg1 = cv.create_rectangle( 75, 40, 85, 190, fill='darkgreen') peg2 = cv.create_rectangle( 215, 40, 225, 190, fill='darkgreen') peg3 = cv.create_rectangle( 355, 40, 365, 190, fill='darkgreen') floor = cv.create_rectangle( 10, 191, 430, 200, fill='black') self.hEngine = HanoiEngine(cv, nrOfDiscs, speed, self.displayMove) self.state = "START" root.mainloop() if __name__ == "__main__": Hanoi(4,5) From nick at javacat.f2s.com Mon Feb 16 14:00:11 2004 From: nick at javacat.f2s.com (Nick Lunt) Date: Mon Feb 16 14:06:40 2004 Subject: [Tutor] request to run program on a Linux machine In-Reply-To: <4031035D.2060808@aon.at> References: <4031035D.2060808@aon.at> Message-ID: <20040216190011.2b0557b7@phatbox.local> Hi Gregor, very cool. Im a complete python beginner so I'll use your code as a tutorial ;). Anyway, I just ran it on Linux with python on a 700Mhz pc with 256Mb RAM and there's no performance issues at all. Im running python 2.3-3mdk with Tkinter 2.3-3mdk . I put the speed down to 1 and quit the program while a disc was moving and got the following error in the console: $ ./hanoi.py Exception in Tkinter callback Traceback (most recent call last): File "/usr/lib/python2.3/lib-tk/Tkinter.py", line 1345, in __call__ return self.func(*args) File "./hanoi.py", line 216, in step if self.hEngine.step(): File "./hanoi.py", line 127, in step self.HG.next() File "./hanoi.py", line 70, in hanoi for x in self.hanoi(n-1, src, temp, dest): yield None File "./hanoi.py", line 70, in hanoi for x in self.hanoi(n-1, src, temp, dest): yield None File "./hanoi.py", line 70, in hanoi for x in self.hanoi(n-1, src, temp, dest): yield None File "./hanoi.py", line 71, in hanoi yield self.move(src, dest) File "./hanoi.py", line 84, in move disc.move_to(x2,y2, self.speed) File "./hanoi.py", line 30, in move_to self.cv.move(self.item,dx,dy) File "/usr/lib/python2.3/lib-tk/Tkinter.py", line 2162, in move self.tk.call((self._w, 'move') + args) TclError: invalid command name ".1078258988" $ Cheers Nick. On Mon, 16 Feb 2004 18:52:29 +0100 Gregor Lingl <glingl@aon.at> wrote: > Hi! > > At the moment I unfortunately don't have a computer running > Linux at hand, so ... > > ... is there anybody out there using a machine running > Python 2.3 with Tkinter under Linux, who is willing > to run the attached program and give me feedback concerning > two questions: > > (1) Does the program run smoothly > > (2) Does it terminate without error-messages (TclError) > when the window is closed while the animation is running > (i. e. while a disc is moving). > This can be seen e.g. when you run it from within IDLE or > from the commandline of some console window ... > > Many thanks in advance > Gregor > > P.S. A second posting concerning this Hanoi program, > concerning some remarks on the problem mentioned above > will follow. > > From marilyn at deliberate.com Mon Feb 16 14:07:33 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Mon Feb 16 14:07:39 2004 Subject: [Tutor] Re: Re: copies deep and shallow Message-ID: <Pine.LNX.4.44.0402161052470.11161-100000@Kuna> Thank you Andrei, [snip] > Why would you use a (very slow) deepcopy when it doesn't offer any extra > functionality? I can't modify integers/strings/tuples in-place, so I can't I see. So deepcopy is slow, even for shallow objects? > accidentally change g by changing something in h. If I'd just used a > reference, the result would have been this (g is modified as well): > > >>> h = g > >>> h[0] = 2 > >>> g, h > ({0: 2, 2: 3, 4: 5}, {0: 2, 2: 3, 4: 5}) > > I use references e.g. when I read items from some nested dictionary. E.g. > if I have a nested dictionary and I'm interested in keys inside > data["feeds"][0]["items"][0].keys(), I'll probably just do this: > > item = data["feeds"][0]["items"][0] > item["somekey"] = newvalue > item["otherkey"] = othervalue I see. Good idea. > > I *want* the original dictionary in data["feeds"][0]["items"][0] to be > changed, so obviously I won't do a copy - the item=... assignment is only > meant to add some clarity to the code and save me some typing. > If I meant to change that particular item but did not want the changes to > go back in the nested dictionary I'd have used copy (if the dictionary only > contains immutable values) or deepcopy (if it contains mutable values). Got it. > > But generally speaking you can ignore copy if you wish and write perfectly > reasonable applications without even knowing it exists :). But then again, Yes. This is what I was thinking. > you can also ignore deepcopy if you wish, or dictionaries all together > (there are plenty of languages without a dictionary type) or... But, I'm teaching a python class! I have to deep-understand everything. And I love the dictionary type. So much is done for free. > > Oh, and I should point out that the docs mention two possible gotchas of > deepcopy (in paragraph 3.18): > - Recursive objects (compound objects that, directly or indirectly, contain > a reference to themselves) may cause a recursive loop. > - Because deep copy copies everything it may copy too much, e.g., > administrative data structures that should be shared even between copies. Yes, but it also says it cleverly solves these problems. OK. Thank you very much. I think I get it. I hope I get all there is to get. I'm very grateful that you have taken the time to explain all this. Marilyn From fredb7 at HotPOP.com Mon Feb 16 14:18:03 2004 From: fredb7 at HotPOP.com (fredb7) Date: Mon Feb 16 14:18:22 2004 Subject: [Tutor] request to run program on a Linux machine In-Reply-To: <4031035D.2060808@aon.at> References: <4031035D.2060808@aon.at> Message-ID: <D7AF723F-60B4-11D8-B71E-000393DB5FF6@HotPOP.com> Run smoothly and no error message on OS X. Good job. Hope this helps. Fred On 16-f?vr.-04, at 18:52, Gregor Lingl wrote: > Hi! > > At the moment I unfortunately don't have a computer running > Linux at hand, so ... > > ... is there anybody out there using a machine running > Python 2.3 with Tkinter under Linux, who is willing > to run the attached program and give me feedback concerning > two questions: > > (1) Does the program run smoothly > > (2) Does it terminate without error-messages (TclError) > when the window is closed while the animation is running > (i. e. while a disc is moving). > This can be seen e.g. when you run it from within IDLE or > from the commandline of some console window ... > > Many thanks in advance > Gregor > > P.S. A second posting concerning this Hanoi program, > concerning some remarks on the problem mentioned above > will follow. > > ## Animated Tower-Of-Hanoi game with Tkinter GUI > ## author: Gregor Lingl, Vienna, Austria > ## email: glingl@aon.at > ## date: 16. 2. 2004 > > from Tkinter import * > > class Disc: > """Movable Rectangle on a Tkinter Canvas""" > def __init__(self,cv,pos,length,height,colour): > """creates disc on given Canvas cv at given pos-ition""" > x0, y0 = pos > x1, x2 = x0-length/2.0, x0+length/2.0 > y1, y2 = y0-height, y0 > self.cv = cv > self.item = cv.create_rectangle(x1,y1,x2,y2, > fill = "#%02x%02x%02x" % > colour) > def move_to(self, x, y, speed): > """moves bottom center of disc to position (x,y). > speed is intended to assume values from 1 to 10""" > x1,y1,x2,y2 = self.cv.coords(self.item) > x0, y0 = (x1 + x2)/2, y2 > dx, dy = x-x0, y-y0 > d = (dx**2+dy**2)**0.5 > steps = int(d/(10*speed-5)) + 1 > dx, dy = dx/steps, dy/steps > for i in range(steps): > self.cv.move(self.item,dx,dy) > self.cv.update() > self.cv.after(20) > > class Tower(list): > """Hanoi tower designed as a subclass of built-in type list""" > def __init__(self, x, y, h): > """ creates an empty tower. > (x,y) is floor-level position of tower, > h is height of the discs. """ > self.x = x > self.y = y > self.h = h > def top(self): > return self.x, self.y - len(self)*self.h > > > class HanoiEngine: > """Plays the Hanoi-game on a given canvas.""" > def __init__(self, canvas, nrOfDiscs, speed, moveCntDisplay=None): > """Sets Canvas to play on as well as default values for > number of discs and animation-speed. > moveCntDisplay is a function with 1 parameter, which > communicates > the count of the actual move to the GUI containing the > Hanoi-engine-canvas.""" > self.cv = canvas > self.nrOfDiscs = nrOfDiscs > self.speed = speed > self.moveDisplay = moveCntDisplay > self.running = False > self.moveCnt = 0 > self.discs = [] > self.towerA = Tower( 80, 190, 15) > self.towerB = Tower(220, 190, 15) > self.towerC = Tower(360, 190, 15) > self.reset() > > def hanoi(self, n, src, dest, temp): > """The classical recursive Towers-Of-Hanoi algorithm.""" > if n > 0: > for x in self.hanoi(n-1, src, temp, dest): yield None > yield self.move(src, dest) > for x in self.hanoi(n-1, temp, dest, src): yield None > > def move(self, src_tower, dest_tower): > """moves uppermost disc of source tower to top of destination > tower.""" > self.moveCnt += 1 > self.moveDisplay(self.moveCnt) > disc = src_tower.pop() > x1, y1 = src_tower.top() > x2, y2 = dest_tower.top() > disc.move_to(x1,20, self.speed) > disc.move_to(x2,20, self.speed) > disc.move_to(x2,y2, self.speed) > dest_tower.append(disc) > > def reset(self): > """Setup of (a new) game.""" > self.moveCnt = 0 > self.moveDisplay(self.moveCnt) > while self.towerA: self.towerA.pop() > while self.towerB: self.towerB.pop() > while self.towerC: self.towerC.pop() > for s in self.discs: > self.cv.delete(s.item) > ## Fancy colouring of discs: red ===> blue > if self.nrOfDiscs > 1: > colour_diff = 255 // (self.nrOfDiscs-1) > else: > colour_diff = 0 > for i in range(self.nrOfDiscs): # setup towerA > length_diff = 100 // self.nrOfDiscs > length = 120 - i * length_diff > s = Disc( self.cv, self.towerA.top(), length, 13, > (255-i*colour_diff, 0, i*colour_diff)) > self.discs.append(s) > self.towerA.append(s) > self.HG = self.hanoi(self.nrOfDiscs, > self.towerA, self.towerC, self.towerB) > > def run(self): > """runs game ;-) > returns True if game is over, else False""" > self.running = True > try: > while self.running: > result = self.step() > return result # True iff done > except StopIteration: # game over > return True > except TclError: # for silently terminating in case of > window closing > return False > > def step(self): > """performs one single step of the game, > returns True if finished, else False""" > self.HG.next() > return 2**self.nrOfDiscs-1 == self.moveCnt > > def stop(self): > """ ;-) """ > self.running = False > > > class Hanoi: > """GUI for animated towers-of-Hanoi-game with upto 10 discs:""" > > def displayMove(self, move): > """method to be passed to the Hanoi-engine as a callback > to report move-count""" > self.moveCntLbl.configure(text = "move:\n%d" % move) > > def adjust_nr_of_discs(self, e): > """callback function for nr-of-discs-scale-widget""" > self.hEngine.nrOfDiscs = self.discs.get() > self.reset() > > def adjust_speed(self, e): > """callback function for speeds-scale-widget""" > self.hEngine.speed = self.tempo.get() > > def setState(self, STATE): > """most simple representation of a finite state machine""" > self.state = STATE > try: > if STATE == "START": > self.discs.configure(state=NORMAL) > self.discs.configure(fg="black") > self.discsLbl.configure(fg="black") > self.resetBtn.configure(state=DISABLED) > self.startBtn.configure(text="start", state=NORMAL) > self.stepBtn.configure(state=NORMAL) > elif STATE == "RUNNING": > self.discs.configure(state=DISABLED) > self.discs.configure(fg="gray70") > self.discsLbl.configure(fg="gray70") > self.resetBtn.configure(state=DISABLED) > self.startBtn.configure(text="pause", state=NORMAL) > self.stepBtn.configure(state=DISABLED) > elif STATE == "PAUSE": > self.discs.configure(state=NORMAL) > self.discs.configure(fg="black") > self.discsLbl.configure(fg="black") > self.resetBtn.configure(state=NORMAL) > self.startBtn.configure(text="resume", state=NORMAL) > self.stepBtn.configure(state=NORMAL) > elif STATE == "DONE": > self.discs.configure(state=NORMAL) > self.discs.configure(fg="black") > self.discsLbl.configure(fg="black") > self.resetBtn.configure(state=NORMAL) > self.startBtn.configure(text="start", state=DISABLED) > self.stepBtn.configure(state=DISABLED) > elif STATE == "TIMEOUT": > self.discs.configure(state=DISABLED) > self.discs.configure(fg="gray70") > self.discsLbl.configure(fg="gray70") > self.resetBtn.configure(state=DISABLED) > self.startBtn.configure(state=DISABLED) > self.stepBtn.configure(state=DISABLED) > except TclError: > pass > > def reset(self): > """restores START state for a new game""" > self.hEngine.reset() > self.setState("START") > > def start(self): > """callback function for start button, which also serves as > pause button. Makes hEngine running until done or > interrupted""" > if self.state in ["START", "PAUSE"]: > self.setState("RUNNING") > if self.hEngine.run(): > self.setState("DONE") > else: > self.setState("PAUSE") > elif self.state == "RUNNING": > self.setState("TIMEOUT") > self.hEngine.stop() > > def step(self): > """callback function for step button. > makes hEngine perform a single step""" > self.setState("TIMEOUT") > if self.hEngine.step(): > self.setState("DONE") > else: > self.setState("PAUSE") > > def __init__(self, nrOfDiscs, speed): > """builds GUI, constructs Hanoi-engine and puts it into START > state > then launches mainloop()""" > root = Tk() > root.title("TOWERS OF HANOI") > #root.protocol("WM_DELETE_WINDOW",root.quit) #counter > productive here!? > cv = Canvas(root,width=440,height=210, bg="gray90") > cv.pack() > > fnt = ("Arial", 12, "bold") > > attrFrame = Frame(root) #contains scales to adjust game's > attributes > self.discsLbl = Label(attrFrame, width=7, height=2, font=fnt, > text="discs:\n") > self.discs = Scale(attrFrame, from_=1, to_=10, > orient=HORIZONTAL, > font=fnt, length=75, showvalue=1, > repeatinterval=10, > command=self.adjust_nr_of_discs) > self.discs.set(nrOfDiscs) > self.tempoLbl = Label(attrFrame, width=8, height=2, font=fnt, > text = " speed:\n") > self.tempo = Scale(attrFrame, from_=1, to_=10, > orient=HORIZONTAL, > font=fnt, length=100, > showvalue=1,repeatinterval=10, > command = self.adjust_speed) > self.tempo.set(speed) > self.moveCntLbl= Label(attrFrame, width=5, height=2, font=fnt, > padx=20, text=" move:\n0", > anchor=CENTER) > for widget in ( self.discsLbl, self.discs, self.tempoLbl, > self.tempo, > > self.moveCntLbl ): > widget.pack(side=LEFT) > attrFrame.pack(side=TOP) > > > ctrlFrame = Frame(root) # contains Buttons to control the game > self.resetBtn = Button(ctrlFrame, width=11, text="reset", > font=fnt, > state = DISABLED, padx=15, command = > self.reset) > self.stepBtn = Button(ctrlFrame, width=11, text="step", > font=fnt, > state = NORMAL, padx=15, command = > self.step) > self.startBtn = Button(ctrlFrame, width=11, text="start", > font=fnt, > state = NORMAL, padx=15, command = > self.start) > for widget in self.resetBtn, self.stepBtn, self.startBtn: > widget.pack(side=LEFT) > ctrlFrame.pack(side=TOP) > > # setup of the scene > peg1 = cv.create_rectangle( 75, 40, 85, 190, > fill='darkgreen') > peg2 = cv.create_rectangle( 215, 40, 225, 190, > fill='darkgreen') > peg3 = cv.create_rectangle( 355, 40, 365, 190, > fill='darkgreen') > floor = cv.create_rectangle( 10, 191, 430, 200, fill='black') > > self.hEngine = HanoiEngine(cv, nrOfDiscs, speed, > self.displayMove) > self.state = "START" > > root.mainloop() > > if __name__ == "__main__": > Hanoi(4,5) > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From missive at hotmail.com Mon Feb 16 14:27:16 2004 From: missive at hotmail.com (Lee Harr) Date: Mon Feb 16 14:27:21 2004 Subject: [Tutor] Re: request to run program on a Linux machine Message-ID: <BAY2-F34WzT4TFiiQyP0002cdeb@hotmail.com> >At the moment I unfortunately don't have a computer running >Linux at hand, so ... > I am running on my FreeBSD 4.9 drive right now. Not sure if this helps you, but ... >... is there anybody out there using a machine running >Python 2.3 with Tkinter under Linux, who is willing >to run the attached program and give me feedback concerning >two questions: > >(1) Does the program run smoothly > Very smooth. >(2) Does it terminate without error-messages (TclError) >when the window is closed while the animation is running >(i. e. while a disc is moving). No errors. _________________________________________________________________ The new MSN 8: advanced junk mail protection and 2 months FREE* http://join.msn.com/?page=features/junkmail From glingl at aon.at Mon Feb 16 17:18:24 2004 From: glingl at aon.at (Gregor Lingl) Date: Mon Feb 16 17:17:45 2004 Subject: [Tutor] hanoi.py - bug found and corrected. (was: request to run...) In-Reply-To: <20040216190011.2b0557b7@phatbox.local> References: <4031035D.2060808@aon.at> <20040216190011.2b0557b7@phatbox.local> Message-ID: <403141B0.5060904@aon.at> Nick Lunt schrieb: >Hi Gregor, > >... > >I put the speed down to 1 and quit the program while a disc was moving >and got the following error in the console: > >$ ./hanoi.py >Exception in Tkinter callback >Traceback (most recent call last): > File "/usr/lib/python2.3/lib-tk/Tkinter.py", line 1345, in __call__ > return self.func(*args) >... > > self.cv.move(self.item,dx,dy) > File "/usr/lib/python2.3/lib-tk/Tkinter.py", line 2162, in move > self.tk.call((self._w, 'move') + args) >TclError: invalid command name ".1078258988" >$ > >Cheers >Nick. > > > Hi Nick! Thanks for your and credos very useful hints. They revealed a bug of the program which also occured under Windows as I recognized only now. So once more I didn't test a program thoroughly enough. *grrrrr* But I was able to correct it easily. (It was a somewhat silly error) The corrected version of hanoi.py is attached to this posting. ***Please abandon the first version and take this one*** From the other feedbacks from Mac and Linux useres I expect, that this now runs without errors on all operating systems (Thanks also to you!). Having the choice of being ashamed for having made this error or being lucky to have got your help I choose the latter ;-) Thanks again, Gregor > >On Mon, 16 Feb 2004 18:52:29 +0100 Gregor Lingl <glingl@aon.at> wrote: > > > >>Hi! >> >>At the moment I unfortunately don't have a computer running >>Linux at hand, so ... >> >>... is there anybody out there using a machine running >>Python 2.3 with Tkinter under Linux, who is willing >>to run the attached program and give me feedback concerning >>two questions: >> >>(1) Does the program run smoothly >> >>(2) Does it terminate without error-messages (TclError) >>when the window is closed while the animation is running >>(i. e. while a disc is moving). >>This can be seen e.g. when you run it from within IDLE or >>from the commandline of some console window ... >> >>Many thanks in advance >>Gregor >> >>P.S. A second posting concerning this Hanoi program, >>concerning some remarks on the problem mentioned above >>will follow. >> >> >> >> > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > -------------- next part -------------- ## Animated Tower-Of-Hanoi game with Tkinter GUI ## author: Gregor Lingl, Vienna, Austria ## email: glingl@aon.at ## date: 16. 2. 2004 ######################################################### ## bug (found by Nick Hunt and credo - Tutor list) in ## HanoiEngine.run() and HanoiEngine.step() corrected: ## lines 124 - 132 ######## 16. 2. 2004 - 23:07 ########################### from Tkinter import * class Disc: """Movable Rectangle on a Tkinter Canvas""" def __init__(self,cv,pos,length,height,colour): """creates disc on given Canvas cv at given pos-ition""" x0, y0 = pos x1, x2 = x0-length/2.0, x0+length/2.0 y1, y2 = y0-height, y0 self.cv = cv self.item = cv.create_rectangle(x1,y1,x2,y2, fill = "#%02x%02x%02x" % colour) def move_to(self, x, y, speed): """moves bottom center of disc to position (x,y). speed is intended to assume values from 1 to 10""" x1,y1,x2,y2 = self.cv.coords(self.item) x0, y0 = (x1 + x2)/2, y2 dx, dy = x-x0, y-y0 d = (dx**2+dy**2)**0.5 steps = int(d/(10*speed-5)) + 1 dx, dy = dx/steps, dy/steps for i in range(steps): self.cv.move(self.item,dx,dy) self.cv.update() self.cv.after(20) class Tower(list): """Hanoi tower designed as a subclass of built-in type list""" def __init__(self, x, y, h): """ creates an empty tower. (x,y) is floor-level position of tower, h is height of the discs. """ self.x = x self.y = y self.h = h def top(self): return self.x, self.y - len(self)*self.h class HanoiEngine: """Plays the Hanoi-game on a given canvas.""" def __init__(self, canvas, nrOfDiscs, speed, moveCntDisplay=None): """Sets Canvas to play on as well as default values for number of discs and animation-speed. moveCntDisplay is a function with 1 parameter, which communicates the count of the actual move to the GUI containing the Hanoi-engine-canvas.""" self.cv = canvas self.nrOfDiscs = nrOfDiscs self.speed = speed self.moveDisplay = moveCntDisplay self.running = False self.moveCnt = 0 self.discs = [] self.towerA = Tower( 80, 190, 15) self.towerB = Tower(220, 190, 15) self.towerC = Tower(360, 190, 15) self.reset() def hanoi(self, n, src, dest, temp): """The classical recursive Towers-Of-Hanoi algorithm.""" if n > 0: for x in self.hanoi(n-1, src, temp, dest): yield None yield self.move(src, dest) for x in self.hanoi(n-1, temp, dest, src): yield None def move(self, src_tower, dest_tower): """moves uppermost disc of source tower to top of destination tower.""" self.moveCnt += 1 self.moveDisplay(self.moveCnt) disc = src_tower.pop() x1, y1 = src_tower.top() x2, y2 = dest_tower.top() disc.move_to(x1,20, self.speed) disc.move_to(x2,20, self.speed) disc.move_to(x2,y2, self.speed) dest_tower.append(disc) def reset(self): """Setup of (a new) game.""" self.moveCnt = 0 self.moveDisplay(self.moveCnt) while self.towerA: self.towerA.pop() while self.towerB: self.towerB.pop() while self.towerC: self.towerC.pop() for s in self.discs: self.cv.delete(s.item) ## Fancy colouring of discs: red ===> blue if self.nrOfDiscs > 1: colour_diff = 255 // (self.nrOfDiscs-1) else: colour_diff = 0 for i in range(self.nrOfDiscs): # setup towerA length_diff = 100 // self.nrOfDiscs length = 120 - i * length_diff s = Disc( self.cv, self.towerA.top(), length, 13, (255-i*colour_diff, 0, i*colour_diff)) self.discs.append(s) self.towerA.append(s) self.HG = self.hanoi(self.nrOfDiscs, self.towerA, self.towerC, self.towerB) def run(self): """runs game ;-) returns True if game is over, else False""" self.running = True try: while self.running: result = self.step() return result # True iff done except StopIteration: # game over return True def step(self): """performs one single step of the game, returns True if finished, else False""" try: self.HG.next() return 2**self.nrOfDiscs-1 == self.moveCnt except TclError: return False def stop(self): """ ;-) """ self.running = False class Hanoi: """GUI for animated towers-of-Hanoi-game with upto 10 discs:""" def displayMove(self, move): """method to be passed to the Hanoi-engine as a callback to report move-count""" self.moveCntLbl.configure(text = "move:\n%d" % move) def adjust_nr_of_discs(self, e): """callback function for nr-of-discs-scale-widget""" self.hEngine.nrOfDiscs = self.discs.get() self.reset() def adjust_speed(self, e): """callback function for speeds-scale-widget""" self.hEngine.speed = self.tempo.get() def setState(self, STATE): """most simple representation of a finite state machine""" self.state = STATE try: if STATE == "START": self.discs.configure(state=NORMAL) self.discs.configure(fg="black") self.discsLbl.configure(fg="black") self.resetBtn.configure(state=DISABLED) self.startBtn.configure(text="start", state=NORMAL) self.stepBtn.configure(state=NORMAL) elif STATE == "RUNNING": self.discs.configure(state=DISABLED) self.discs.configure(fg="gray70") self.discsLbl.configure(fg="gray70") self.resetBtn.configure(state=DISABLED) self.startBtn.configure(text="pause", state=NORMAL) self.stepBtn.configure(state=DISABLED) elif STATE == "PAUSE": self.discs.configure(state=NORMAL) self.discs.configure(fg="black") self.discsLbl.configure(fg="black") self.resetBtn.configure(state=NORMAL) self.startBtn.configure(text="resume", state=NORMAL) self.stepBtn.configure(state=NORMAL) elif STATE == "DONE": self.discs.configure(state=NORMAL) self.discs.configure(fg="black") self.discsLbl.configure(fg="black") self.resetBtn.configure(state=NORMAL) self.startBtn.configure(text="start", state=DISABLED) self.stepBtn.configure(state=DISABLED) elif STATE == "TIMEOUT": self.discs.configure(state=DISABLED) self.discs.configure(fg="gray70") self.discsLbl.configure(fg="gray70") self.resetBtn.configure(state=DISABLED) self.startBtn.configure(state=DISABLED) self.stepBtn.configure(state=DISABLED) except TclError: pass def reset(self): """restores START state for a new game""" self.hEngine.reset() self.setState("START") def start(self): """callback function for start button, which also serves as pause button. Makes hEngine running until done or interrupted""" if self.state in ["START", "PAUSE"]: self.setState("RUNNING") if self.hEngine.run(): self.setState("DONE") else: self.setState("PAUSE") elif self.state == "RUNNING": self.setState("TIMEOUT") self.hEngine.stop() def step(self): """callback function for step button. makes hEngine perform a single step""" self.setState("TIMEOUT") if self.hEngine.step(): self.setState("DONE") else: self.setState("PAUSE") def __init__(self, nrOfDiscs, speed): """builds GUI, constructs Hanoi-engine and puts it into START state then launches mainloop()""" root = Tk() root.title("TOWERS OF HANOI") #root.protocol("WM_DELETE_WINDOW",root.quit) #counter productive here!? cv = Canvas(root,width=440,height=210, bg="gray90") cv.pack() fnt = ("Arial", 12, "bold") attrFrame = Frame(root) #contains scales to adjust game's attributes self.discsLbl = Label(attrFrame, width=7, height=2, font=fnt, text="discs:\n") self.discs = Scale(attrFrame, from_=1, to_=10, orient=HORIZONTAL, font=fnt, length=75, showvalue=1, repeatinterval=10, command=self.adjust_nr_of_discs) self.discs.set(nrOfDiscs) self.tempoLbl = Label(attrFrame, width=8, height=2, font=fnt, text = " speed:\n") self.tempo = Scale(attrFrame, from_=1, to_=10, orient=HORIZONTAL, font=fnt, length=100, showvalue=1,repeatinterval=10, command = self.adjust_speed) self.tempo.set(speed) self.moveCntLbl= Label(attrFrame, width=5, height=2, font=fnt, padx=20, text=" move:\n0", anchor=CENTER) for widget in ( self.discsLbl, self.discs, self.tempoLbl, self.tempo, self.moveCntLbl ): widget.pack(side=LEFT) attrFrame.pack(side=TOP) ctrlFrame = Frame(root) # contains Buttons to control the game self.resetBtn = Button(ctrlFrame, width=11, text="reset", font=fnt, state = DISABLED, padx=15, command = self.reset) self.stepBtn = Button(ctrlFrame, width=11, text="step", font=fnt, state = NORMAL, padx=15, command = self.step) self.startBtn = Button(ctrlFrame, width=11, text="start", font=fnt, state = NORMAL, padx=15, command = self.start) for widget in self.resetBtn, self.stepBtn, self.startBtn: widget.pack(side=LEFT) ctrlFrame.pack(side=TOP) # setup of the scene peg1 = cv.create_rectangle( 75, 40, 85, 190, fill='darkgreen') peg2 = cv.create_rectangle( 215, 40, 225, 190, fill='darkgreen') peg3 = cv.create_rectangle( 355, 40, 365, 190, fill='darkgreen') floor = cv.create_rectangle( 10, 191, 430, 200, fill='black') self.hEngine = HanoiEngine(cv, nrOfDiscs, speed, self.displayMove) self.state = "START" root.mainloop() if __name__ == "__main__": Hanoi(4,5) From alan.gauld at blueyonder.co.uk Mon Feb 16 18:41:45 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Mon Feb 16 18:41:26 2004 Subject: [Tutor] environment variable setting References: <20040215170121.6544.qmail@web40307.mail.yahoo.com> Message-ID: <003b01c3f4e6$704e4920$6401a8c0@xp> > I currently use JScript and VBScript on WindozeXP to set environment variables and > make them permanent in the system space(not for user). This is very handy for me in > the scripts I write. How do you do that? Is the approach portable to Python? As a general rule its very bad practice to set environment variables on a multi user operating system and hope they persist outside your executuion environment since if you can do itr another user (or program/service) could be doing it too, quickly leading to chaos! Its usually much better to use config files for that kind of setting (with access permissions preventing the dual update problem) > I leave the python script, aka I cannot persist it. I dont want to use the registry > approach since it constrains me to Windoze platform. Some operating systems simply won't let you change EVs outside your immediate environment. Others will let you alter existing values provided you don't overwrite the space beyond the existing string (ie new values must be shorter than the original!) Others will let you change them quite happily, its an inherently non portable operation. > How do you make either putenv or os.environ["DATETIME"]="01022004" permanent, > meaning even after rebooting the box ? And to make them persist after a reboot usually means editing a text file or startup script somehow! The whole point of environment variables is that they describe the current execution environment and thus, by definition, changes do not persist across reboots, that's what configuration files are for! Alan G. From arkamir at softhome.net Mon Feb 16 23:21:13 2004 From: arkamir at softhome.net (arkamir@softhome.net) Date: Mon Feb 16 23:22:03 2004 Subject: [Tutor] ascii? Message-ID: <courier.403196B9.000041F5@softhome.net> Thanks for for the all the replies to my previous question, it really helped a lot. Now I'm wondering is there a module which automatically converts strings into the html ascii counterparts. Such as (< to <) or (> to >)? I got these values from http://www.asciitable.com/. Thanks a lot! conrad From jakieabraham at yahoo.com Tue Feb 17 05:11:30 2004 From: jakieabraham at yahoo.com (Jacob Abraham) Date: Tue Feb 17 05:11:35 2004 Subject: [Tutor] Question on PyQt Signals and Slots Message-ID: <20040217101130.37736.qmail@web11207.mail.yahoo.com> Dear tutors, I am building an application using python and Qt and would like to know how one should pass arguments when using Signals and Slots. Especially when one of the arguments is a class instance. QObject.connect(self.table,SIGNAL("clicked(int,int,int,QPoint)"),self.tableclick) These were my attempts that returned errors. def tableclick(self,a,b,c,d): def tableclick(self,*args): def tableclick(self,*args,**argv): def tableclick(self,a,b,c,d,*arg): RuntimeError: Signal has wrong argument types for slot Thanks Jacob Abraham __________________________________ Do you Yahoo!? Yahoo! Finance: Get your refund fast by filing online. http://taxes.yahoo.com/filing.html From gerrit at nl.linux.org Tue Feb 17 06:30:13 2004 From: gerrit at nl.linux.org (Gerrit) Date: Tue Feb 17 06:30:39 2004 Subject: [Tutor] ascii? In-Reply-To: <courier.403196B9.000041F5@softhome.net> References: <courier.403196B9.000041F5@softhome.net> Message-ID: <20040217113013.GA4272@nl.linux.org> arkamir@softhome.net wrote: > Thanks for for the all the replies to my previous question, it really=20 > helped a lot. Now I'm wondering is there a module which automatically=20 > converts strings into the html ascii counterparts. Such as (< to <)= or=20 > (> to >)? I got these values from http://www.asciitable.com/.=20 Two possiblities: >>> cgi.escape('>') '>' >>> '&#%d;' % ord('>') '>' Gerrit. --=20 Weather in Twenthe, Netherlands 17/02 09:25 UTC: 2.0=C2=B0C mist overcast wind 2.7 m/s SW (57 m above NAP) --=20 Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From cybersamurai at terra.com.br Tue Feb 17 08:15:58 2004 From: cybersamurai at terra.com.br (Luiz Siqueira Neto) Date: Tue Feb 17 08:16:02 2004 Subject: [Tutor] Virtual file system - repository Message-ID: <4032140E.8010701@terra.com.br> Some one know some API or module for use a zip file or tar or another file format for make this work like a virtual file system? I need make a small data repository for some files and I can't find nothing like this. From project5 at redrival.net Tue Feb 17 14:05:38 2004 From: project5 at redrival.net (Andrei) Date: Tue Feb 17 14:09:13 2004 Subject: [Tutor] Re: Re: copies deep and shallow References: <Pine.LNX.4.44.0402161052470.11161-100000@Kuna> Message-ID: <1lg8kpqzccfvy.7av4fy0pf5ks.dlg@40tude.net> Marilyn Davis wrote on Mon, 16 Feb 2004 11:07:33 -0800 (PST): >> Why would you use a (very slow) deepcopy when it doesn't offer any extra >> functionality? I can't modify integers/strings/tuples in-place, so I can't > > I see. So deepcopy is slow, even for shallow objects? Well, if you try deepcopying that list of integers as I wrote in one of the earlier messages, you'll notice it's very slow compared to a shallow copy. And things don't get much shallower than integers :). It's easy to notice that a deepcopy will allocate a truckload of extra memory, while a shallow copy will allocate a lot less - just keep an eye on your task manager when doing an extremely large deepcopy. The shallow copy just kind of says for every part of some large object "this part is the same part as that one over there", which takes very little time and space to say. Deepcopy sort of says for every little piece: "Make a new thing here. Now make it look exactly the same as that piece over there. But it won't be the same piece." which takes a lot of time and memory. Reference is even faster because it only does "See this thing here? It's the same as that very large thing over there." - it doesn't even bother saying this thing for all the parts of the very large thing. You can see this very easily like this: >>> a = [[i] for i in range(50000)] # list of 50000 single item lists >>> b = copy.deepcopy(a) >>> c = copy.copy(a) >>> d = a >>> id(a), id(b), id(c), id(d) # a and d have the same id (memory address) (23646544, 23646384, 27999440, 23646544) >>> id(a[10]), id(b[10]), id(c[10]), id(d[10]) (23646928, 28001328, 23646928, 23646928) # all the items have the same memory address, except for the one in b # which was deepcopied. >> But generally speaking you can ignore copy if you wish and write perfectly >> reasonable applications without even knowing it exists :). But then again, > > Yes. This is what I was thinking. > >> you can also ignore deepcopy if you wish, or dictionaries all together >> (there are plenty of languages without a dictionary type) or... > > But, I'm teaching a python class! I have to deep-understand everything. > > And I love the dictionary type. So much is done for free. I agree, but even simpler types like lists are also much better than the old-school arrays found in other languages. Even integers are a lot better because there's only one kind of them (or two, depending whether you count the long variety as a separate one) instead of... about five :). > I'm very grateful that you have taken the time to explain all this. You're welcome. -- Yours, Andrei ===== Mail address in header catches spam. 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 cybersamurai at terra.com.br Tue Feb 17 16:16:17 2004 From: cybersamurai at terra.com.br (Luiz Siqueira Neto) Date: Tue Feb 17 16:16:19 2004 Subject: [Tutor] Simple thread Message-ID: <403284A1.5020701@terra.com.br> I can't remember but I believe that have a simple thread object for make some like this: t = thread(myObject) From libsvm at tom.com Wed Feb 18 10:03:00 2004 From: libsvm at tom.com (denny) Date: Wed Feb 18 09:57:29 2004 Subject: [Tutor] How to print to a file? Message-ID: <40337EA4.4010609@tom.com> I want to write something to a file like this: print >>filehandle, "....%d...%s..."%(num,string) but it raise error Can someone tell me how can I print it above to a file just like we print to the stdout(print "....%d...%s..."(num,string)). Or is there some funtion as we use in C/C++( fprint etc) thanks From syn_ack at comcast.net Wed Feb 18 11:00:44 2004 From: syn_ack at comcast.net (Joshua Banks) Date: Wed Feb 18 11:06:02 2004 Subject: [Tutor] Getting "file sizes" Message-ID: <200402180800.53114.syn_ack@comcast.net> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hello, I'm trying to get python to tell me the size of each individual file that if finds in a given directory. I'm a little lost on how to get that info. I've done the following: >>> import os, os.path #Assign a user friendly name and "path" for variable value. #Get a list of files in a given directory >>> portage_dir = "/var/log/portage" >>> os.listdir(portage_dir) ['1782-openmotif-2.1.30-r3.log', '1781-iptables-1.2.8-r1.log', '1756-slocate-2.7-r5.log', '1763-xloadimage-4.1-r1.log', '1773-iproute-20010824-r4.log', '1757-gentoo-sources-2.4.22-r5.log', '1788-tcl-8.3.4.log', '1797-libperl-5.8.0.log', '1769-python-2.3.3.log', '1776-xfree-drm-4.3.0-r6.log', '1806-ymessenger-1.0.4.1.log', '1766-wine-20031118-r1.log', '1800-mirrorselect-0.82-r3.log', '1746-kdeaddons-3.1.5.log', '1783-gaim-0.72-r1.log', '1752-kdeutils-3.1.5.log', '1766-xv-3.10a-r3.log', '1775-xfree-drm-4.3.0-r7.log', '1798-perl-5.8.0-r12.log', '1753-kdeartwork-3.1.5.log', '1757-slocate-2.7-r2.log', '1766-fileutils-4.1.11-r1.log', '1766-yacc-1.9.1-r1.log', '1792-libxml2-2.6.3.log', '1766-commonbox-styles-0.6.log', '1767-cryptplug-0.3.15.log', '1753-kdeutils-3.1.4.log', '1748-kdepim-3.1.4.log', '1791-python-fchksum-1.6.1-r1.log', '1803-gaim-0.75-r8.log', '1777-man-pages-1.65.log', '1783-gaim-encryption-2.21.log', '1774-iptables-1.2.8-r1.log', '1762-nmap-3.48.log', '1808-curl-7.10.8-r1.log', '1804-gaim-encryption-2.21.log', '1766-gpgme-0.3.14.log', '1810-bison-1.35.log', '1771-libvorbis-1.0.1.log', '1779-xpdf-2.03.log', '1766-ymessenger-1.0.4.1.log', '1766-xinetd-2.3.12.log', '1759-genkernel-3.0.1_beta6.log', '1766-modutils-2.4.25.log', '1778-man-pages-1.64.log', '1765-kgpg-1.0.0.log', '1784-kbd-1.08-r5.log', '1751-kdeadmin-3.1.5.log', '1801-gaim-0.75-r8.log', '1782-gaim-0.75-r8.log', '1787-genkernel-3.0.1_beta8.log', '1763-nmap-3.45.log', '1801-mirrorselect-0.82-r2.log', '1754-kdeartwork-3.1.4.log', '1766-addpatches-0.2.log', '1809-bison-1.875.log', '1795-libvorbis-1.0.1-r1.log', '1766-rpm2targz-9.0-r1.log', '1776-java-config-1.2.5.log', '1766-commonbox-utils-0.4.log', '1747-kdeaddons-3.1.4.log', '1780-xpdf-2.02.1.log', '1796-libperl-5.8.2.log', '1761-file-4.06.log', '1764-gnupg-1.2.3-r5.log', '1805-rpm2targz-9.0-r2.log', '1795-linux-headers-2.4.21.log', '1752-kdeadmin-3.1.4.log', '1786-genkernel-3.0.1_beta6.log', '1786-genkernel-3.0.1_beta9.log', '1758-xfree-drm-4.3.0-r6.log', '1794-libvorbis-1.0.1-r2.log', '1777-java-config-1.2.4.log', '1771-genkernel-3.0.1_beta6.log', '1756-fluxbox-0.9.7.log', '1770-libvorbis-1.0.1-r1.log', '1766-libsndfile-1.0.5.log', '1750-kdegraphics-3.1.5.log', '1780-iptables-1.2.9.log', '1762-file-4.02.log', '1799-nmap-3.50.log', '1772-gentoo-sources-2.4.22-r5.log', '1785-genkernel-3.0.1_beta8.log', '1750-kdetoys-3.1.4.log', '1748-kdegames-3.1.5.log', '1768-xfree-drm-4.3.0-r7.log', '1760-xpdf-2.02.1.log', '1785-kbd-1.08-r4.log', '1751-kdegraphics-3.1.4.log', '1778-lcms-1.12.log', '1798-psmisc-21.2-r4.log', '1790-python-2.3.3.log', '1809-curl-7.10.7.log', '1800-nmap-3.48.log', '1754-kde-3.1.5.log', '1749-kdetoys-3.1.5.log', '1793-libxslt-1.1.1.log', '1766-textutils-2.1.log', '1781-openmotif-2.1.30-r4.log', '1766-tcsh-6.12-r2.log', '1747-kdepim-3.1.5.log', '1749-kdegames-3.1.4.log', '1766-sh-utils-2.0.15.log', '1802-gaim-0.75-r8.log', '1797-perl-5.8.2-r1.log', '1799-psmisc-21.2-r3.log', '1789-tk-8.3.4-r1.log', '1779-lcms-1.11.log', '1807-ymessenger-1.0.4.1.log', '1787-fluxbox-0.9.7-r1.log', '1755-fluxbox-0.9.7-r1.log'] #Get the total size of the given directory >>> os.path.getsize(portage_dir) 4872L The next step is where I'm getting lost. I've tried many things but I'm lost. At this point I would like to have Python simply tell me the size of each individual file instead of the the size of the whole parent directory. Can someone, without given me the direct answer lead me in the right direction. Thanks Joshua Banks -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (GNU/Linux) iD8DBQFAM4wyp9X7q/XgeyYRArC9AJ4gLfR+OLReehlw3GCiJZr9htWpLQCdFr9g CVIYRQ9+kMFwoVks0zyp/zE= =c5cC -----END PGP SIGNATURE----- From marilyn at deliberate.com Wed Feb 18 12:41:06 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Wed Feb 18 12:41:18 2004 Subject: [Tutor] Re: Re: copies deep and shallow In-Reply-To: <1lg8kpqzccfvy.7av4fy0pf5ks.dlg@40tude.net> Message-ID: <Pine.LNX.4.44.0402180936560.11161-100000@Kuna> On Tue, 17 Feb 2004, Andrei wrote: [much snipped] > > > > And I love the dictionary type. So much is done for free. > > I agree, but even simpler types like lists are also much better than the > old-school arrays found in other languages. Even integers are a lot better > because there's only one kind of them (or two, depending whether you count > the long variety as a separate one) instead of... about five :). Five? In C there are so many more! unsigned long long, time_t, size_t, int_64, char, ... I'm so glad to be teaching Python. > > > I'm very grateful that you have taken the time to explain all this. > > You're welcome. > > Thank you again. Class tonight! Marilyn -- From dyoo at hkn.eecs.berkeley.edu Wed Feb 18 14:16:09 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Feb 18 14:16:18 2004 Subject: [Tutor] Re: Re: copies deep and shallow In-Reply-To: <1lg8kpqzccfvy.7av4fy0pf5ks.dlg@40tude.net> Message-ID: <Pine.LNX.4.44.0402181107220.13874-100000@hkn.eecs.berkeley.edu> On Tue, 17 Feb 2004, Andrei wrote: > Marilyn Davis wrote on Mon, 16 Feb 2004 11:07:33 -0800 (PST): > > >> Why would you use a (very slow) deepcopy when it doesn't offer any > >> extra functionality? I can't modify integers/strings/tuples in-place, > >> so I can't > > > > I see. So deepcopy is slow, even for shallow objects? > > Well, if you try deepcopying that list of integers as I wrote in one of > the earlier messages, you'll notice it's very slow compared to a shallow > copy. And things don't get much shallower than integers :). Hi Marilyn, I think it might be more useful to concentrate on the effect of copy vs deepcopy, rather than on its performance. If copy.deepcopy() is slower, that's only because it's doing something subtly different than copy.copy(). We can see the difference with a matrix of numbers: ### >>> matrix = [ ... [0, 1, 0], ... [1, 0, 1], ... [1, 1, 1]] >>> import copy >>> m1 = copy.copy(matrix) >>> m2 = copy.deepcopy(matrix) ### We now have two "copies" of a matrix of numbers. Let's make a change to one of the elements: ### >>> m1[0][0] = 42 >>> m1 [[42, 1, 0], [1, 0, 1], [1, 1, 1]] ### Looks ok so far. What happens to the others? ### >>> m2 [[0, 1, 0], [1, 0, 1], [1, 1, 1]] >>> matrix [[42, 1, 0], [1, 0, 1], [1, 1, 1]] ### Does this result surprise you? Hope this helps! From syn_ack at comcast.net Wed Feb 18 14:46:24 2004 From: syn_ack at comcast.net (Joshua Banks) Date: Wed Feb 18 14:51:25 2004 Subject: [Tutor] Getting "file sizes"? Message-ID: <000701c3f657$e46ca960$4202a8c0@toejam> Hello, For some reason my first email didn't make it to this list. So here it is again. I'm trying to get python to tell me the size of each individual file that if finds in a given directory. I'm a little lost on how to get that info. I've done the following: >>> import os, os.path #Assign a user friendly name and "path" for variable value. #Get a list of files in a given directory >>> portage_dir = "/var/log/portage" >>> >>> os.listdir(portage_dir) ['1782-openmotif-2.1.30-r3.log', '1781-iptables-1.2.8-r1.log', '1756-slocate-2.7-r5.log', '1763-xloadimage-4.1-r1.log', '1773-iproute-20010824-r4.log', '1757-gentoo-sources-2.4.22-r5.log', '1788-tcl-8.3.4.log', '1797-libperl-5.8.0.log', '1769-python-2.3.3.log', '1776-xfree-drm-4.3.0-r6.log', '1806-ymessenger-1.0.4.1.log', '1766-wine-20031118-r1.log', '1800-mirrorselect-0.82-r3.log', '1746-kdeaddons-3.1.5.log', '1783-gaim-0.72-r1.log', '1752-kdeutils-3.1.5.log', '1766-xv-3.10a-r3.log', '1775-xfree-drm-4.3.0-r7.log', '1798-perl-5.8.0-r12.log', '1753-kdeartwork-3.1.5.log', '1757-slocate-2.7-r2.log', '1766-fileutils-4.1.11-r1.log', '1766-yacc-1.9.1-r1.log', '1792-libxml2-2.6.3.log', '1766-commonbox-styles-0.6.log', '1767-cryptplug-0.3.15.log', '1753-kdeutils-3.1.4.log', '1748-kdepim-3.1.4.log', '1791-python-fchksum-1.6.1-r1.log', '1803-gaim-0.75-r8.log', '1777-man-pages-1.65.log', '1783-gaim-encryption-2.21.log', '1774-iptables-1.2.8-r1.log', '1762-nmap-3.48.log', '1808-curl-7.10.8-r1.log', '1804-gaim-encryption-2.21.log', '1766-gpgme-0.3.14.log', '1810-bison-1.35.log', '1771-libvorbis-1.0.1.log', '1779-xpdf-2.03.log', '1766-ymessenger-1.0.4.1.log', '1766-xinetd-2.3.12.log', '1759-genkernel-3.0.1_beta6.log', '1766-modutils-2.4.25.log', '1778-man-pages-1.64.log', '1765-kgpg-1.0.0.log', '1784-kbd-1.08-r5.log', '1751-kdeadmin-3.1.5.log', '1801-gaim-0.75-r8.log', '1782-gaim-0.75-r8.log', '1787-genkernel-3.0.1_beta8.log', '1763-nmap-3.45.log', '1801-mirrorselect-0.82-r2.log', '1754-kdeartwork-3.1.4.log', '1766-addpatches-0.2.log', '1809-bison-1.875.log', '1795-libvorbis-1.0.1-r1.log', '1766-rpm2targz-9.0-r1.log', '1776-java-config-1.2.5.log', '1766-commonbox-utils-0.4.log', '1747-kdeaddons-3.1.4.log', '1780-xpdf-2.02.1.log', '1796-libperl-5.8.2.log', '1761-file-4.06.log', '1764-gnupg-1.2.3-r5.log', '1805-rpm2targz-9.0-r2.log', '1795-linux-headers-2.4.21.log', '1752-kdeadmin-3.1.4.log', '1786-genkernel-3.0.1_beta6.log', '1786-genkernel-3.0.1_beta9.log', '1758-xfree-drm-4.3.0-r6.log', '1794-libvorbis-1.0.1-r2.log', '1777-java-config-1.2.4.log', '1771-genkernel-3.0.1_beta6.log', '1756-fluxbox-0.9.7.log', '1770-libvorbis-1.0.1-r1.log', '1766-libsndfile-1.0.5.log', '1750-kdegraphics-3.1.5.log', '1780-iptables-1.2.9.log', '1762-file-4.02.log', '1799-nmap-3.50.log', '1772-gentoo-sources-2.4.22-r5.log', '1785-genkernel-3.0.1_beta8.log', '1750-kdetoys-3.1.4.log', '1748-kdegames-3.1.5.log', '1768-xfree-drm-4.3.0-r7.log', '1760-xpdf-2.02.1.log', '1785-kbd-1.08-r4.log', '1751-kdegraphics-3.1.4.log', '1778-lcms-1.12.log', '1798-psmisc-21.2-r4.log', '1790-python-2.3.3.log', '1809-curl-7.10.7.log', '1800-nmap-3.48.log', '1754-kde-3.1.5.log', '1749-kdetoys-3.1.5.log', '1793-libxslt-1.1.1.log', '1766-textutils-2.1.log', '1781-openmotif-2.1.30-r4.log', '1766-tcsh-6.12-r2.log', '1747-kdepim-3.1.5.log', '1749-kdegames-3.1.4.log', '1766-sh-utils-2.0.15.log', '1802-gaim-0.75-r8.log', '1797-perl-5.8.2-r1.log', '1799-psmisc-21.2-r3.log', '1789-tk-8.3.4-r1.log', '1779-lcms-1.11.log', '1807-ymessenger-1.0.4.1.log', '1787-fluxbox-0.9.7-r1.log', '1755-fluxbox-0.9.7-r1.log'] #Get the total size of the given directory >>> os.path.getsize(portage_dir) 4872L The next step is where I'm getting lost. I've tried many things but I'm lost. At this point I would like to have Python simply tell me the size of each individual file instead of the the size of the whole parent directory. Can someone, without given me the direct answer lead me in the right direction. Thanks, Joshua Banks From nick at javacat.f2s.com Wed Feb 18 15:12:13 2004 From: nick at javacat.f2s.com (Nick Lunt) Date: Wed Feb 18 15:18:39 2004 Subject: [Tutor] Putting a system call into an re.sub() In-Reply-To: <403284A1.5020701@terra.com.br> References: <403284A1.5020701@terra.com.br> Message-ID: <20040218201213.3943e57d@phatbox.local> Hi list, I'm trying to work out how to perform an re on some text, then when it finds the search pattern to print out the whole line but make the pattern highlighted using the tput command (linux system). Here's a quick example of what I'm trying to achieve, where fl is any file. - code - 1. bold = os.system('tput smso') 2. norm = os.system('tput rmso') 3. 4. for line in fl.readlines(): 5. match = pat.search(line) 6. if match: 7. print pat.sub(pattern, bold + replace + norm,line) -- end code -- Here's the output I'm getting: - output - print pat.sub(pattern, bold + replace + norm, line) TypeError: unsupported operand type(s) for +: 'int' and 'str' - end output - Which is understandable seen as I'm trying to add different types. So I replaced the + signs with commas and got this: - output - - end output - Traceback (most recent call last): File "./sed.py", line 29, in ? print pat.sub(replace, (bold, replace, norm), line) TypeError: an integer is required Obviously Im having problems here so any pointers would be appreciated. I've studied the re docs on python.org and tried to find out more from the book 'Text Processing in Python'. It's simple to do in the shell and in perl, so I'm sure there's a simple way in python ;) Many thanks Nick. From marilyn at deliberate.com Wed Feb 18 15:22:27 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Wed Feb 18 15:22:33 2004 Subject: [Tutor] Re: Re: copies deep and shallow In-Reply-To: <Pine.LNX.4.44.0402181107220.13874-100000@hkn.eecs.berkeley.edu> Message-ID: <Pine.LNX.4.44.0402181219310.11161-100000@Kuna> On Wed, 18 Feb 2004, Danny Yoo wrote: > > > On Tue, 17 Feb 2004, Andrei wrote: > > > Marilyn Davis wrote on Mon, 16 Feb 2004 11:07:33 -0800 (PST): > > > > >> Why would you use a (very slow) deepcopy when it doesn't offer any > > >> extra functionality? I can't modify integers/strings/tuples in-place, > > >> so I can't > > > > > > I see. So deepcopy is slow, even for shallow objects? > > > > Well, if you try deepcopying that list of integers as I wrote in one of > > the earlier messages, you'll notice it's very slow compared to a shallow > > copy. And things don't get much shallower than integers :). > > > Hi Marilyn, > > > I think it might be more useful to concentrate on the effect of copy vs > deepcopy, rather than on its performance. If copy.deepcopy() is slower, > that's only because it's doing something subtly different than > copy.copy(). > > > We can see the difference with a matrix of numbers: > > ### > >>> matrix = [ > ... [0, 1, 0], > ... [1, 0, 1], > ... [1, 1, 1]] > >>> import copy > >>> m1 = copy.copy(matrix) > >>> m2 = copy.deepcopy(matrix) > ### > > > We now have two "copies" of a matrix of numbers. Let's make a change to > one of the elements: > > ### > >>> m1[0][0] = 42 > >>> m1 > [[42, 1, 0], [1, 0, 1], [1, 1, 1]] > ### > > > Looks ok so far. What happens to the others? > > ### > >>> m2 > [[0, 1, 0], [1, 0, 1], [1, 1, 1]] > >>> matrix > [[42, 1, 0], [1, 0, 1], [1, 1, 1]] > ### > > > Does this result surprise you? No. I'm getting it. The nested list, since it's mutable, is a reference in the copy() but a new object in the deepcopy. > > > > Hope this helps! > > Thank you. It does. I'm getting more confident. You folks are great! Marilyn -- From marilyn at deliberate.com Wed Feb 18 15:28:27 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Wed Feb 18 15:29:09 2004 Subject: [Tutor] Idle and program command line Message-ID: <Pine.LNX.4.44.0402181225580.11161-100000@Kuna> I like the "run module" facility in the Edit window. But I can't find a way to have it see command line arguments. Am I missing something? Marilyn From dyoo at hkn.eecs.berkeley.edu Wed Feb 18 16:16:37 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Feb 18 16:17:35 2004 Subject: [Tutor] How to print to a file? In-Reply-To: <40337EA4.4010609@tom.com> Message-ID: <Pine.LNX.4.44.0402181309190.23057-100000@hkn.eecs.berkeley.edu> On Wed, 18 Feb 2004, denny wrote: > I want to write something to a file like this: > print >>filehandle, "....%d...%s..."%(num,string) > but it raise error Hi Denny, What kind of error? Can you show us exactly what the error message looks like? As far as I can tell, the code that you've showed us, print >>filehandle, "....%d...%s..." % (num,string) looks syntactically correct to me. We really need to see why Python doesn't seem to like it; show us the error message, verbatim, and we can go from there. > Can someone tell me how can I print it above to a file just like we > print to the stdout(print "....%d...%s..."(num,string)). Or is there > some funtion as we use in C/C++( fprint etc) The method you tried above should work. Alternatively, you can use the 'write' method of a file object. For example, since 'sys.stdout' is a file object, we can say something like: ### sys.stdout.write('hello world\n') ### Talk to you later! From dyoo at hkn.eecs.berkeley.edu Wed Feb 18 16:29:59 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Feb 18 16:33:44 2004 Subject: [Tutor] Simple thread In-Reply-To: <403284A1.5020701@terra.com.br> Message-ID: <Pine.LNX.4.44.0402181324280.23057-100000@hkn.eecs.berkeley.edu> On Tue, 17 Feb 2004, Luiz Siqueira Neto wrote: > I can't remember but I believe that have a simple thread object for make > some like this: > > t = thread(myObject) Hi Luiz, Are you trying to make threads in Python? There's documentation here: http://www.python.org/doc/lib/module-threading.html Here's a short example that shows how to make a thread that runs off a function: ### >>> def myfunction(): ... while 1: ... print "foo" ... time.sleep(5) ... >>> t = threading.Thread(target=myfunction) >>> t.start() >>> foo >>> foo ### And now there's a thread that's printing 'foo' throughout the rest of the interpreter session. Not really useful, but at least it's illustrative. *grin* Is this what you're asking? Good luck! From sigurd at 12move.de Wed Feb 18 16:35:09 2004 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Wed Feb 18 16:36:16 2004 Subject: [Tutor] How to print to a file? In-Reply-To: <40337EA4.4010609@tom.com> (denny's message of "Wed, 18 Feb 2004 23:03:00 +0800") References: <40337EA4.4010609@tom.com> Message-ID: <m3wu6kvzqe.fsf@hamster.pflaesterer.de> On 18 Feb 2004, denny <- libsvm@tom.com wrote: > I want to write something to a file like this: > print >>filehandle, "....%d...%s..."%(num,string) > but it raise error Without seeing the error noone can tell you what might be the reason. > Can someone tell me how can I print it above to a file just like > we print to the stdout(print "....%d...%s..."(num,string)). > Or is there some funtion as we use in C/C++( fprint etc) >>> f = open("foo","w") >>> print >> f, "Test" >>> f.close() >>> Karl -- Please do *not* send copies of replies to me. I read the list From sigurd at 12move.de Wed Feb 18 16:38:11 2004 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Wed Feb 18 16:41:38 2004 Subject: [Tutor] Getting "file sizes" In-Reply-To: <200402180800.53114.syn_ack@comcast.net> (Joshua Banks's message of "Wed, 18 Feb 2004 08:00:44 -0800") References: <200402180800.53114.syn_ack@comcast.net> Message-ID: <m3smh8vzm8.fsf@hamster.pflaesterer.de> On 18 Feb 2004, Joshua Banks <- syn_ack@comcast.net wrote: > I'm trying to get python to tell me the size of each individual file > that if finds in a given directory. I'm a little lost on how to get > that info. Read the posting Message-ID: <20040215012518.80748.qmail@web12402.mail.yahoo.com>. It explains exactly your problem. Also check out the preceding posting. Karl -- Please do *not* send copies of replies to me. I read the list From dyoo at hkn.eecs.berkeley.edu Wed Feb 18 16:22:13 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Feb 18 17:12:03 2004 Subject: [Tutor] Getting "file sizes" In-Reply-To: <200402180800.53114.syn_ack@comcast.net> Message-ID: <Pine.LNX.4.44.0402181316490.23057-100000@hkn.eecs.berkeley.edu> On Wed, 18 Feb 2004, Joshua Banks wrote: > I'm trying to get python to tell me the size of each individual file > that if finds in a given directory. I'm a little lost on how to get that > info. Hi Joshua, Ah, a Gentoo fan. *grin* You may find the functions in the 'os.path' module useful: http://www.python.org/doc/lib/module-os.path.html There's a function in there that can get the size of a particular file. > #Get the total size of the given directory > > >>> os.path.getsize(portage_dir) > 4872L Ah, you know about os.path.getsize() already then. getsize() is actually more versatile than you might think: have you tried applying it on an individual file path? Good luck to you! From hcohen2 at comcast.net Wed Feb 18 17:09:54 2004 From: hcohen2 at comcast.net (hcohen2) Date: Wed Feb 18 17:13:26 2004 Subject: [Tutor] Re: Re: copies deep and shallow In-Reply-To: <Pine.LNX.4.44.0402181107220.13874-100000@hkn.eecs.berkeley.edu> References: <Pine.LNX.4.44.0402181107220.13874-100000@hkn.eecs.berkeley.edu> Message-ID: <4033E2B2.6040901@comcast.net> Danny Yoo wrote: >On Tue, 17 Feb 2004, Andrei wrote: > > > >>Marilyn Davis wrote on Mon, 16 Feb 2004 11:07:33 -0800 (PST): >> >> >> >>>>Why would you use a (very slow) deepcopy when it doesn't offer any >>>>extra functionality? I can't modify integers/strings/tuples in-place, >>>>so I can't >>>> >>>> >>>I see. So deepcopy is slow, even for shallow objects? >>> >>> >>Well, if you try deepcopying that list of integers as I wrote in one of >>the earlier messages, you'll notice it's very slow compared to a shallow >>copy. And things don't get much shallower than integers :). >> >> > > >Hi Marilyn, > > >I think it might be more useful to concentrate on the effect of copy vs >deepcopy, rather than on its performance. If copy.deepcopy() is slower, >that's only because it's doing something subtly different than >copy.copy(). > > >We can see the difference with a matrix of numbers: > >### > > >>>>matrix = [ >>>> >>>> >... [0, 1, 0], >... [1, 0, 1], >... [1, 1, 1]] > > >>>>import copy >>>>m1 = copy.copy(matrix) >>>>m2 = copy.deepcopy(matrix) >>>> >>>> >### > > >We now have two "copies" of a matrix of numbers. Let's make a change to >one of the elements: > >### > > >>>>m1[0][0] = 42 >>>>m1 >>>> >>>> >[[42, 1, 0], [1, 0, 1], [1, 1, 1]] >### > > >Looks ok so far. What happens to the others? > >### > > >>>>m2 >>>> >>>> >[[0, 1, 0], [1, 0, 1], [1, 1, 1]] > > >>>>matrix >>>> >>>> >[[42, 1, 0], [1, 0, 1], [1, 1, 1]] >### > > >Does this result surprise you? > > > >Hope this helps! > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > It bothered me, but less so having done this: >>> matrix = [[0, 1, 0], [1, 0, 1], [1, 1, 1]] >>> import copy >>> m1 = copy.copy(matrix) >>> m2 = copy.deepcopy(matrix) >>> m1 [[0, 1, 0], [1, 0, 1], [1, 1, 1]] >>> m2 [[0, 1, 0], [1, 0, 1], [1, 1, 1]] >>> matrix[0][0] = 42 >>> matrix [[42, 1, 0], [1, 0, 1], [1, 1, 1]] >>> m1 [[42, 1, 0], [1, 0, 1], [1, 1, 1]] >>> m2 [[0, 1, 0], [1, 0, 1], [1, 1, 1]] which seems to be just saying the copy() is active (linked to current value of 'matrix) while deepcopy() is a fixed snap shot. So the question arises, why should deepcopy() be slow being fixed? From syn_ack at comcast.net Wed Feb 18 19:44:49 2004 From: syn_ack at comcast.net (Joshua Banks) Date: Wed Feb 18 19:49:53 2004 Subject: [Tutor] Getting "file sizes" In-Reply-To: <Pine.LNX.4.44.0402181316490.23057-100000@hkn.eecs.berkeley.edu> References: <Pine.LNX.4.44.0402181316490.23057-100000@hkn.eecs.berkeley.edu> Message-ID: <200402181644.49426.syn_ack@comcast.net> On Wednesday 18 February 2004 01:22 pm, you wrote: > Ah, a Gentoo fan. *grin* Yes, I luv Gentoo... :P > Ah, you know about os.path.getsize() already then. getsize() is > actually more versatile than you might think: have you tried applying > it on an individual file path? Yes, I can get the file size of an individual file by specifying the complete path. But if I have a directory with 60 files then I would have to manually put the path in for each file in that directory that I wish to know the size of. Example: The following gives me a list of the files in the directory specified below. There's a total of 12 files listed for examples sake. >>> os.listdir('/var/log/portage') ['1782-openmotif-2.1.30-r3.log', '1781-iptables-1.2.8-r1.log', '1756-slocate-2.7-r5.log', '1763-xloadimage-4.1- r1.log', '1773-iproute-20010824-r4.log', '1757-gentoo-sources-2.4.22-r5.log', '1788-tcl-8.3.4.log', '1797-libpe rl-5.8.0.log', '1769-python-2.3.3.log', '1776-xfree-drm-4.3.0-r6.log', '1806-ymessenger-1.0.4.1.log', '1766-win e-20031118-r1.log'] I also understand that I can do the following 12 times, specifying a different file each time and get the "file size answers that I'm looking for. So I understand how to do this the HardWay. >>> os.path.getsize('/var/log/portage/1782-openmotif-2.1.30-r3.log') 39L What I don't understand is how to get Python to use the "getsize()" function for each file that the "os.listdir('/var/log/portage')" function lists. I've read and read and read. I don't understand, what seems, would be a simple task. Having to manually input each file, one at a time seems backwards to the progamming moto. Do more with less so to say. I'm I not making any sense? Any idea's on how I can get this to work? Thanks, Joshua Banks From amonroe at columbus.rr.com Wed Feb 18 20:29:46 2004 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Wed Feb 18 20:24:38 2004 Subject: [Tutor] Getting "file sizes" In-Reply-To: <200402181644.49426.syn_ack@comcast.net> References: <Pine.LNX.4.44.0402181316490.23057-100000@hkn.eecs.berkeley.edu> <200402181644.49426.syn_ack@comcast.net> Message-ID: <801206739259.20040218202946@columbus.rr.com> > Yes, I can get the file size of an individual file by specifying the > complete path. But if I have a directory with 60 files then I would > have to manually put the path in for each file in that directory that I > wish to know the size of. > [snip] > What I don't understand is how to get Python to use the "getsize()" > function for each file that the "os.listdir('/var/log/portage')" > function lists. This isn't recursive, but for a single directory it would work: [(x,os.path.getsize(x)) for x in os.listdir('c:/')] Alan From helena_b2001 at yahoo.com Wed Feb 18 21:21:07 2004 From: helena_b2001 at yahoo.com (helena bhaska) Date: Wed Feb 18 21:21:12 2004 Subject: [Tutor] Reading garbage from serial port In-Reply-To: <20040213010550.51078.qmail@web20414.mail.yahoo.com> Message-ID: <20040219022107.68318.qmail@web20411.mail.yahoo.com> Hi, I have a strange problem with reading data from a serial port - I use pyserial package, here's the code: ser = serial.Serial('/dev/ttyS0', 57600, timeout=None) while 1: x=ser.inWaiting() if x!=0: print x buffer = ser.read(x) ser.close() If the device connected to my computer through the serial port sends a bunch of data for some time, my program thinks there is always data on the serial port, even long after the device stops sending data - it prints the same number for x (amount of data on the port) continuously. I thought that reading data from the serial port should clear it from the serial port, but it seems like there is some garbage sitting there all the time - how do I get rid of it? I've tried flushing, but that does not fix the problem. Thanks! __________________________________ Do you Yahoo!? Yahoo! Mail SpamGuard - Read only the mail you want. http://antispam.yahoo.com/tools From helena_b2001 at yahoo.com Wed Feb 18 21:23:05 2004 From: helena_b2001 at yahoo.com (helena bhaska) Date: Wed Feb 18 21:23:10 2004 Subject: [Tutor] Reading garbage from serial port In-Reply-To: <20040219022107.68318.qmail@web20411.mail.yahoo.com> Message-ID: <20040219022305.24888.qmail@web20415.mail.yahoo.com> oops, sorry for spamming - seems that my device was going crazy, sending garbage data non-stop. --- helena bhaska <helena_b2001@yahoo.com> wrote: > Hi, > I have a strange problem with reading data from a > serial port - I use pyserial package, here's the > code: > > ser = serial.Serial('/dev/ttyS0', 57600, > timeout=None) > while 1: > x=ser.inWaiting() > if x!=0: > print x > buffer = ser.read(x) > > ser.close() > If the device connected to my computer through the > serial port sends a bunch of data for some time, my > program thinks there is always data on the serial > port, even long after the device stops sending data > - > it prints the same number for x (amount of data on > the > port) continuously. I thought that reading data > from > the serial port should clear it from the serial > port, > but it seems like there is some garbage sitting > there > all the time - how do I get rid of it? I've tried > flushing, but that does not fix the problem. > Thanks! > > __________________________________ > Do you Yahoo!? > Yahoo! Mail SpamGuard - Read only the mail you want. > http://antispam.yahoo.com/tools > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor __________________________________ Do you Yahoo!? Yahoo! Mail SpamGuard - Read only the mail you want. http://antispam.yahoo.com/tools From dyoo at hkn.eecs.berkeley.edu Wed Feb 18 22:07:54 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Feb 18 22:07:59 2004 Subject: [Tutor] Getting "file sizes" In-Reply-To: <200402181644.49426.syn_ack@comcast.net> Message-ID: <Pine.LNX.4.44.0402181902520.26440-100000@hkn.eecs.berkeley.edu> On Wed, 18 Feb 2004, Joshua Banks wrote: > What I don't understand is how to get Python to use the "getsize()" > function for each file that the "os.listdir('/var/log/portage')" > function lists. Hi Joshua, Ok, we have a concrete problem. I usually ask for concrete examples, but sometimes I'll go the other way around. Let's make the problem slightly abstract and fuzzy. *grin* Would it be accurate if I reword that as: What I don't understand is how to get Python to do some thing for each element in my list. It tries to capture the crux of the issue, without having to point to any particular process. And if that's accurate to what you're trying to do, then take a look at loops: http://www.python.org/doc/tut/node6.html#SECTION006200000000000000000 Hope this helps! From syn_ack at comcast.net Wed Feb 18 22:10:49 2004 From: syn_ack at comcast.net (Joshua Banks) Date: Wed Feb 18 22:15:52 2004 Subject: [Tutor] Getting "file sizes" In-Reply-To: <801206739259.20040218202946@columbus.rr.com> References: <Pine.LNX.4.44.0402181316490.23057-100000@hkn.eecs.berkeley.edu> <200402181644.49426.syn_ack@comcast.net> <801206739259.20040218202946@columbus.rr.com> Message-ID: <200402181910.49804.syn_ack@comcast.net> On Wednesday 18 February 2004 05:29 pm, R. Alan Monroe wrote: > > Yes, I can get the file size of an individual file by specifying > > the complete path. But if I have a directory with 60 files then I > > would have to manually put the path in for each file in that > > directory that I wish to know the size of. > > [snip] > > What I don't understand is how to get Python to use the "getsize()" > > function for each file that the "os.listdir('/var/log/portage')" > > function lists. > > This isn't recursive, but for a single directory it would work: > > [(x,os.path.getsize(x)) for x in os.listdir('c:/')] :D Ahhhh. A one-liner. I like this. Am I doing something wrong here? I'm doing this in linux. >>> import os, os.path >>> [(x,os.path.getsize(x)) for x in os.listdir('/var/log/portage')] Traceback (most recent call last): File "<stdin>", line 1, in ? File "/usr/lib/python2.3/posixpath.py", line 142, in getsize return os.stat(filename).st_size OSError: [Errno 2] No such file or directory: '1782-openmotif-2.1.30-r3.log' This is the results of using that same line on Windows 2K. >>> import os, os.path >>> [(x,os.path.getsize(x)) for x in os.listdir("c:/")] Traceback (most recent call last): ? File "<stdin>", line 1, in ? ? File "C:\Python23\lib\ntpath.py", line 228, in getsize ? ? return os.stat(filename).st_size OSError: [Errno 2] No such file or directory: 'arcldr.exe' Thanks for the response anyways. I have my homework cut out for me and your response and the others have helped point me in the right direction. Thanks, Joshua Banks From syn_ack at comcast.net Wed Feb 18 23:11:55 2004 From: syn_ack at comcast.net (Joshua Banks) Date: Wed Feb 18 23:16:59 2004 Subject: [Tutor] Getting "file sizes" !!Solved!! In-Reply-To: <801206739259.20040218202946@columbus.rr.com> References: <Pine.LNX.4.44.0402181316490.23057-100000@hkn.eecs.berkeley.edu> <200402181644.49426.syn_ack@comcast.net> <801206739259.20040218202946@columbus.rr.com> Message-ID: <200402182011.55552.syn_ack@comcast.net> Grrrrr.... Kind of funny how my monitor is like a mirror. The problem was staring me right in the face. Ok, this was my issue. 1) As I reread through my initial emails regarding this particular thread, I noticed that I didn't append my initial tests. Which, if I would've included the following, someone might of been able to point out, right away, what the problem was. I included everything except my loop testing and the fact that I'm running python as a normal non-root user. >>> import os, os.path >>> a = os.listdir('/var/log/portage') >>> for x in a: ... print x, os.path.getsize(x) ... 1782-openmotif-2.1.30-r3.log Traceback (most recent call last): File "<stdin>", line 2, in ? File "/usr/lib/python2.3/posixpath.py", line 142, in getsize return os.stat(filename).st_size OSError: [Errno 2] No such file or directory: '1782-openmotif-2.1.30-r3.log' Well I know that '1782-openmotif-2.1.30-r3.log' is the first file listed in this directory and does infact exist. BUTTTTTTT, these are the permissions and owner/groups of the directory "portage". drwxrwsr-x 2 root portage 4872 Feb 5 08:16 portage It looks as though I was missing "write" permissions to simply get and print file sizes.. Seems strange.. So I decided to run the same python commands and instead, substituted a directory that is owned by the "non-root-user(me)". And now joy has comeback into my life.. :D >>> a = os.listdir('/home/jbanks/Pythontesting') >>> for x in a: ... print x, os.path.getsize(x), "bytes" ... menu.bak 43 bytes menu.txt 43 bytes Oldpy_stuff 256 bytes persnl_gtr.py 270 bytes list_emerged.py 1475 bytes passwd.py 467 bytes quotmanip.py 465 bytes file2.py 108 bytes test.py 223 bytes file.py 107 bytes functiontst.py 140 bytes Lobster.py 647 bytes functiontst2.py 25 bytes functiontst.pyc 420 bytes Lobster.pyc 706 bytes pytips 0 bytes bd1.txt 3266 bytes bd2.txt 130 bytes game_over.py 231 bytes bell.py 377 bytes useless_trivia.py 1110 bytes ifelifelse.py 453 bytes whiletst.py 459 bytes game_over2.py 151 bytes filecopy.py 331 bytes tempature.py 735 bytes functiontst2.pyc 278 bytes This was a frustrating but good learning experience for me. So it appeared that I could list the contents of the "/var/log/portage" directory but couldn't ..." write(r-x)" write them I guess because of the directory owner/permissions. I'm still a little baffled...but I'll figure it out. I'm sure simply changing the the last set or permissions to "rwx" is the ticket. Anyways thanks to all that responded. Joshua Banks From hameedkhaan at yahoo.com Thu Feb 19 02:06:11 2004 From: hameedkhaan at yahoo.com (Hameed Khan) Date: Thu Feb 19 02:06:33 2004 Subject: [Tutor] confusion and problems with first socket script Message-ID: <20040219070611.53036.qmail@web61104.mail.yahoo.com> hi all, i am getting some problems with my first socket script. can any one of you point me why this is happening. the server script suppose to accept one connection at a time and send countdown to client connected to it from a function through a separate thread. and echo all the connections opened and closed. the client script is working fine. it echoes the countdown it recieve from server. ### CODE for socketserver.py import socket, thread import time, sys def handConnect(conn): for count in xrange(1,11): try: conn.send(str(conn.getpeername()) + ": Counting..."+str(count)+"\n") except: print "Disconnected: ", conn.getpeername(), sys.exc_info()[1] break time.sleep(2) print "Closing Connection:", conn.getpeername() conn.close() def main(): host, port = socket.gethostname(), 4786 serversock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) serversock.bind((host,port)) serversock.listen(1) # According to documentation the argument to listen() is the number of connections we can accept at one time. while True: conn, addr = serversock.accept() print "Client Connected:", addr thread.start_new_thread(handConnect, (conn,)) if __name__ == "__main__": main() ### Code for socketclient.py import socket host, port = socket.gethostname(), 4786 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((host, port)) while True: data = sock.recv(60) if not data: break print "Recieved["+str(sock.getpeername())+"]:", data print "Socket disconnected" ### End Problem: when i run two instances of the socketclien.py i get the following output on the console window of socketserver.py ### OUTPUT from socketserver.py D:\Python\workspace\practice\socket>socketserver.py Client Connected: ('10.10.1.8', 1336) Client Connected: ('10.10.1.8', 1337) Disconnected: ('10.10.1.8', 1337) (10054, 'Connection reset by peer') Closing Connection: ('10.10.1.8', 1337) Disconnected: ('10.10.1.8', 1336) (10054, 'Connection reset by peer') Closing Connection: ('10.10.1.8', 1336) ^C D:\Python\workspace\practice\socket> ### End of Out put as you can see two connections have been made at one after another. and i have specify 1 in listen() argument then why two clients can connect to it. i am not good in english and thats why i am sorry if this mail is long and if there are mistakes of grammar and spellings. i have few more questions about socket module and socket scripting, i will ask those questions in my next mail because this mail is already long enough. Anyways, Thanks in advance. Hameed khan. __________________________________ Do you Yahoo!? Yahoo! Mail SpamGuard - Read only the mail you want. http://antispam.yahoo.com/tools From Ralf.Steckel at AtosOrigin.com Thu Feb 19 03:27:42 2004 From: Ralf.Steckel at AtosOrigin.com (Steckel, Ralf) Date: Thu Feb 19 03:27:45 2004 Subject: [Tutor] Idle and program command line Message-ID: <42BF8717D22EB1409F03483C993F46A70DE829@DEACX002.ikossvan.de> Hi Marilyn, in the tutor for Idle it is written that you can't pass command line arguments to your python script via Idle. They suggest to set the arguments directly in the script. If the script is tested and to be run alone you can comment these settings out. Greetings, Ralf -----Original Message----- From: tutor-bounces+ralf.steckel=atosorigin.com@python.org [mailto:tutor-bounces+ralf.steckel=atosorigin.com@python.org]On Behalf Of Marilyn Davis Sent: Wednesday, February 18, 2004 9:28 PM To: tutor@python.org Subject: [Tutor] Idle and program command line I like the "run module" facility in the Edit window. But I can't find a way to have it see command line arguments. Am I missing something? Marilyn _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From magnus at thinkware.se Thu Feb 19 03:42:30 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Thu Feb 19 03:42:48 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gSG93IHRvIHByaW50IHRvIGEgZmlsZT8=?= Message-ID: <think001_4034757924983@webmail.thinkware.se> denny wrote: > I want to write something to a file like this: > print >>filehandle, "....%d...%s..."%(num,string) > but it raise error If you have opened "filehandle" for writing, and have correct content in the variables "num" and "string", the code above works. As Karl suggested, it's a good idea to include exact error messages in your questions. >>> filehandle = file('c:/tmp.txt', 'w') >>> num,string = 3, 'Hello' >>> print >>filehandle, "....%d...%s..."%(num,string) >>> filehandle.close() >>> print file('c:/tmp.txt').read() ...3...Hello... >>> -- 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 Feb 19 04:02:38 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Thu Feb 19 04:03:00 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gR2V0dGluZyAiZmlsZSBzaXplcyI=?= Message-ID: <think001_403478ca83ce3@webmail.thinkware.se> R. Alan Monroe wrote: > This isn't recursive, but for a single directory it would work: > > [(x,os.path.getsize(x)) for x in os.listdir('c:/')] Only if 'c:/' happens to be your current working directory... The problem is that os.listdir just returns file names, not full paths. os.path.getsize(x) won't find x if it's just the name of a file located in another directory than the current. If you would for instance replace os.listdir('c:/') with glob.glob('c:/*') you would get full paths that make os.path.getsize happy. You could also do dir = 'c:/' print [(x,os.path.getsize(dir+x)) for x in os.listdir(dir)] For a recursive version, try os.walk. for root, dirs, files in os.walk('d:/nyponverktyg'): for file in files: path = os.path.join(root, file) print path, os.path.getsize(path) -- 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 marilyn at deliberate.com Thu Feb 19 04:23:36 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Thu Feb 19 04:23:46 2004 Subject: [Tutor] Idle and program command line In-Reply-To: <42BF8717D22EB1409F03483C993F46A70DE829@DEACX002.ikossvan.de> Message-ID: <Pine.LNX.4.44.0402190122550.11161-100000@Kuna> On Thu, 19 Feb 2004, Steckel, Ralf wrote: > Hi Marilyn, > > in the tutor for Idle it is written that you can't pass command line > arguments to your python script via Idle. They suggest to set the arguments > directly in the script. If the script is tested and to be run alone you can > comment these settings out. Thank you. I figured something like that but wanted to be sure I wasn't missing some hidden button. Thanks again. Marilyn > > Greetings, > > Ralf > > -----Original Message----- > From: tutor-bounces+ralf.steckel=atosorigin.com@python.org > [mailto:tutor-bounces+ralf.steckel=atosorigin.com@python.org]On Behalf > Of Marilyn Davis > Sent: Wednesday, February 18, 2004 9:28 PM > To: tutor@python.org > Subject: [Tutor] Idle and program command line > > > > I like the "run module" facility in the Edit window. > > But I can't find a way to have it see command line arguments. > > Am I missing something? > > Marilyn > > > > _______________________________________________ > 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 magnus at thinkware.se Thu Feb 19 04:29:09 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Thu Feb 19 04:29:34 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gUHV0dGluZyBhIHN5c3RlbSBjYWxsIGludG8gYW4gcmUuc3ViKCk=?= Message-ID: <think001_40347cf3303c0@webmail.thinkware.se> You seem to be confusing os.system('tput smso') with os.popen('tput smso').read(). os.system only returns an exit status. That's the reason that you get that integer + string error. os.popen returns a file handle containing the output of your command. On the other hand, you don't really need tput. You just insert ANSI color codes, right? See e.g. these references: http://mail.python.org/pipermail/tutor/2003-January/019588.html http://pueblo.sourceforge.net/doc/manual/ansi_color_codes.html -----Ursprungligt meddelande----- Fr?n: Nick Lunt <nick@javacat.f2s.com> Skickat: 2004-02-18 21:12:13 Till: tutor@python.org ?mne: [Tutor] Putting a system call into an re.sub() > Hi list, > > I'm trying to work out how to perform an re on some text, then when it > finds the search pattern to print out the whole line but make the > pattern highlighted using the tput command (linux system). > > Here's a quick example of what I'm trying to achieve, where fl is any > file. > > - code - > > 1. bold = os.system('tput smso') > 2. norm = os.system('tput rmso') > 3. > 4. for line in fl.readlines(): > 5. match = pat.search(line) > 6. if match: > 7. print pat.sub(pattern, bold + replace + norm,line) > > -- end code -- > > Here's the output I'm getting: > > - output - > print pat.sub(pattern, bold + replace + norm, line) > TypeError: unsupported operand type(s) for +: 'int' and 'str' > - end output - > > Which is understandable seen as I'm trying to add different types. > > So I replaced the + signs with commas and got this: > - output - > > - end output - > Traceback (most recent call last): > File "./sed.py", line 29, in ? > print pat.sub(replace, (bold, replace, norm), line) > TypeError: an integer is required > > Obviously Im having problems here so any pointers would be appreciated. > I've studied the re docs on python.org and tried to find out more from > the book 'Text Processing in Python'. > > It's simple to do in the shell and in perl, so I'm sure there's a simple > way in python ;) > > Many thanks > Nick. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 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 xcombelle at kedros.com Thu Feb 19 08:10:08 2004 From: xcombelle at kedros.com (Xavier Combelle) Date: Thu Feb 19 08:14:34 2004 Subject: [Tutor] confusion and problems with first socket script In-Reply-To: <20040219070611.53036.qmail@web61104.mail.yahoo.com> References: <20040219070611.53036.qmail@web61104.mail.yahoo.com> Message-ID: <4034B5B0.5070407@kedros.com> Maybe other people are better than me in networking, but I found a kind of answer, I give you as it is Hameed Khan a ?crit : ># According to documentation the argument to listen() >is the number of connections we can accept at one >time. > > Apparently, the backlog argument is the number of queued connection and not the total number of connection accepted. *listen*( backlog) Listen for connections made to the socket. The backlog argument specifies the maximum number of queued connections and should be at least 1; the maximum value is system-dependent (usually 5). One solution to accept just one connection at time and not create a new thread to handle it > while True: > conn, addr = serversock.accept() > print "Client Connected:", addr > thread.start_new_thread(handConnect, (conn,)) > > > while True: conn, addr = serversock.accept() print "Client Connected:", addr handConnect (conn) >if __name__ == "__main__": > main() > > > > And if you don't want the client you can add a time out just before the connection sock.settimeout(3.0) >sock.connect((host, port)) > > From nick at javacat.f2s.com Thu Feb 19 11:52:14 2004 From: nick at javacat.f2s.com (Nick Lunt) Date: Thu Feb 19 11:58:42 2004 Subject: [Tutor] Putting a system call into an re.sub() In-Reply-To: <think001_40347cf3303c0@webmail.thinkware.se> References: <think001_40347cf3303c0@webmail.thinkware.se> Message-ID: <20040219165214.2b1c269b@phatbox.local> Thanks Magnus and Herschel for your help. I'm still having problems but with the info supplied by yourselves I should get it sorted soon. Many thanks again, Nick. On Thu, 19 Feb 2004 10:29:09 +0100 Magnus Lycka <magnus@thinkware.se> wrote: > You seem to be confusing os.system('tput smso') with > os.popen('tput smso').read(). os.system only returns > an exit status. That's the reason that you get that > integer + string error. os.popen returns a file > handle containing the output of your command. > > On the other hand, you don't really need tput. You just > insert ANSI color codes, right? See e.g. these references: > http://mail.python.org/pipermail/tutor/2003-January/019588.html > http://pueblo.sourceforge.net/doc/manual/ansi_color_codes.html > > > -----Ursprungligt meddelande----- > Fr?n: Nick Lunt <nick@javacat.f2s.com> > Skickat: 2004-02-18 21:12:13 > Till: tutor@python.org > ?mne: [Tutor] Putting a system call into an re.sub() > > > > Hi list, > > > > I'm trying to work out how to perform an re on some text, then when > > it finds the search pattern to print out the whole line but make the > > pattern highlighted using the tput command (linux system). > > > > Here's a quick example of what I'm trying to achieve, where fl is > > any file. > > > > - code - > > > > 1. bold = os.system('tput smso') > > 2. norm = os.system('tput rmso') > > 3. > > 4. for line in fl.readlines(): > > 5. match = pat.search(line) > > 6. if match: > > 7. print pat.sub(pattern, bold + replace + norm,line) > > > > -- end code -- > > > > Here's the output I'm getting: > > > > - output - > > print pat.sub(pattern, bold + replace + norm, line) > > TypeError: unsupported operand type(s) for +: 'int' and 'str' > > - end output - > > > > Which is understandable seen as I'm trying to add different types. > > > > So I replaced the + signs with commas and got this: > > - output - > > > > - end output - > > Traceback (most recent call last): > > File "./sed.py", line 29, in ? > > print pat.sub(replace, (bold, replace, norm), line) > > TypeError: an integer is required > > > > Obviously Im having problems here so any pointers would be > > appreciated. I've studied the re docs on python.org and tried to > > find out more from the book 'Text Processing in Python'. > > > > It's simple to do in the shell and in perl, so I'm sure there's a > > simple way in python ;) > > > > Many thanks > > Nick. > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > -- > 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 comber.cix.co.uk Thu Feb 19 12:28:05 2004 From: python at comber.cix.co.uk (Eddie Comber) Date: Thu Feb 19 12:33:45 2004 Subject: [Tutor] Trouble with PIL fonts under Windows Message-ID: <BEEOLJNPLOPIONOMGLAAAELLCMAA.python@comber.cix.co.uk> I am having problems with some PIL fonts under Windows, this link will demonstrate the problem: http://www.comber.org/charR24.gif Other fonts are reasonable but most are a problem. Does anyone recognise what might be going on here?? From dyoo at hkn.eecs.berkeley.edu Thu Feb 19 14:35:28 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Feb 19 14:35:34 2004 Subject: [Tutor] How to print to a file? (fwd) Message-ID: <Pine.LNX.4.44.0402191135180.12955-100000@hkn.eecs.berkeley.edu> ---------- Forwarded message ---------- Date: 19 Feb 2004 23:06:02 +0800 From: denny <libsvm@tom.com> To: Danny Yoo <dyoo@hkn.eecs.berkeley.edu> Subject: Re: [Tutor] How to print to a file? Thanks a lot for you reply. It works now.^_^ By the way, how can I install a higher version of python(at least than python2.2) on RedHat 7.3? Shall I find one that have complied for the very RedHat 7.3 system? thanks =D4=DA 2004-02-19 =CB=C4 =B5=C4 05:16=A3=AC Danny Yoo =D0=B4=B5=C0=A3=BA > On Wed, 18 Feb 2004, denny wrote: > > > I want to write something to a file like this: > > print >>filehandle, "....%d...%s..."%(num,string) > > but it raise error > > Hi Denny, > > > What kind of error? Can you show us exactly what the error message looks > like? As far as I can tell, the code that you've showed us, > > print >>filehandle, "....%d...%s..." % (num,string) > > looks syntactically correct to me. We really need to see why Python > doesn't seem to like it; show us the error message, verbatim, and we can > go from there. > > > > > Can someone tell me how can I print it above to a file just like we > > print to the stdout(print "....%d...%s..."(num,string)). Or is there > > some funtion as we use in C/C++( fprint etc) > > The method you tried above should work. > > > Alternatively, you can use the 'write' method of a file object. For > example, since 'sys.stdout' is a file object, we can say something like: > > ### > sys.stdout.write('hello world\n') > ### > > > > Talk to you later! > > From dyoo at hkn.eecs.berkeley.edu Thu Feb 19 14:41:36 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Feb 19 14:41:46 2004 Subject: [Tutor] Idle and program command line In-Reply-To: <Pine.LNX.4.44.0402190122550.11161-100000@Kuna> Message-ID: <Pine.LNX.4.44.0402191138020.12955-100000@hkn.eecs.berkeley.edu> On Thu, 19 Feb 2004, Marilyn Davis wrote: > > in the tutor for Idle it is written that you can't pass command line > > arguments to your python script via Idle. They suggest to set the > > arguments directly in the script. If the script is tested and to be > > run alone you can comment these settings out. > > Thank you. I figured something like that but wanted to be sure I wasn't > missing some hidden button. It might make a good feature request to allow for the definition of command line arguments in IDLE. You can ask on IDLE-dev and see what their response is: http://mail.python.org/mailman/listinfo/idle-dev Talk to you later! From michel.belanger at seidel.ca Thu Feb 19 15:53:15 2004 From: michel.belanger at seidel.ca (=?ISO-8859-1?Q?Michel_B=E9langer?=) Date: Thu Feb 19 15:58:08 2004 Subject: [Tutor] Program work fine in IDLE but not once compile from Py2exe Message-ID: <4035223B.2060805@seidel.ca> Hi all, It may not be the right place to post this message, but I do not know where else to go. I have the following function that works fine within IDLE but not the exe version compile under Py2exe. I have python 2.2.3 and Py2exe 0.5. The error message is: D:\1_Prog\Python23\dist\library.zip\PythonCardPrototype\debug.py:30: UserWarning : PyCrust has been renamed to Py. Use 'from wx import py' Traceback (most recent call last): File "PythonCardPrototype\components\button.pyc", line 144, in _dispatch File "PythonCardPrototype\event.pyc", line 334, in notifyEventListeners File "PythonCardPrototype\dispatch.pyc", line 81, in eventOccurred File "XferUpdFileOnWeb.py", line 48, in on_btnStart_mouseClick File "XferUpdFileOnWeb.py", line 176, in getPerceptionLicense LookupError: no codec search functions registered: can't find encoding The corresponding code is: def getPerceptionLicense(): #get Perception path from registry keyName = "Software\\VB and VBA Program Settings\\Perception\\Installation" key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER , keyName, 0, win32con.KEY_ALL_ACCESS) infoPath = win32api.RegQueryValueEx(key, "Path") #get license information from MSACCESS file using ADO conn=win32com.client.Dispatch(r'ADODB.Connection') filename = infoPath[0] + '\\config.per' # file is protected from direct reading by password dsn = 'Provider=Microsoft.Jet.OLEDB.4.0;Data Source=' + filename + ';Jet OLEDB:Database Password=sorbier' conn.Open(dsn) rs = win32com.client.Dispatch(r'ADODB.Recordset') rs_name = 'select * from Enregistrement' rs.Open('['+ rs_name + ']', conn, 1, 3) Code = rs.Fields("Code").Value #***following line is causing the error message. With IDLE it print a string similar to '612789' print Code return Code rs.MoveNext() rs.Close() conn.Close() Regards Michel Belanger From matt at ozor.net Thu Feb 19 16:49:35 2004 From: matt at ozor.net (Matthew Ozor) Date: Thu Feb 19 16:53:13 2004 Subject: [Tutor] Python to C++ Message-ID: <000301c3f732$445432a0$622aa8c0@cad> Hello, I wrote a program that parse an HTML page on the internet. #partial example import urllib urlopener = urllib.URLopener() con = urlopener.open("http://test/test.html") output = con.read() #end example Now 'output' holds the web page and that what I want. Is there any way to do this that easy in C/C++. I've tried google searching for examples with no luck. I am using dev-c++ which uses mingw as it compiler. Thanks Matt Ozor www.ozor.net From bigsteve127 at hotmail.com Thu Feb 19 17:05:58 2004 From: bigsteve127 at hotmail.com (big steve) Date: Thu Feb 19 17:05:02 2004 Subject: [Tutor] If Elif Message-ID: <BAY8-DAV10j5p1Fjxe0000005cd@hotmail.com> I am having a problem getting the IF/ELIF to cooperate with me. I am using a sample from: Learn to program By Alan Gauld. I keep getting this msg: IndentationError: unindent does not match any outer indentation level (<pyshell#3>, line 3) But When I don't indent I get: SyntaxError: invalid syntax _________________________________________________________________________________ This is the sample I was trying: value = 100 if value > 10: print 'This is OK' elif value > 50: #This is where I get that msg (IndentationError) print "Whoops, this is never seen' else print ' nor is this' ______________________________________________________________________________ I CAN simply us the If format and all works it is just a little confusing! Could it be that I have mesed with my default sttings on Indentation? Or am I just to thick to see the obvious? any help ? Thanks Steve Hulett -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040219/3be8eca3/attachment.html From michel.belanger at seidel.ca Thu Feb 19 17:09:10 2004 From: michel.belanger at seidel.ca (=?ISO-8859-1?Q?Michel_B=E9langer?=) Date: Thu Feb 19 17:09:21 2004 Subject: [Tutor] Program work fine in IDLE but not once compile from Py2exe Message-ID: <40353406.3040800@seidel.ca> Hi, Soory, but on my previous message the python version _is_ 2.3.3 not 2.2.3 Michel Belanger From anna at aleax.it Thu Feb 19 17:39:41 2004 From: anna at aleax.it (Anna Ravenscroft) Date: Thu Feb 19 17:39:55 2004 Subject: [Tutor] If Elif In-Reply-To: <BAY8-DAV10j5p1Fjxe0000005cd@hotmail.com> References: <BAY8-DAV10j5p1Fjxe0000005cd@hotmail.com> Message-ID: <200402191739.41877.anna@aleax.it> On Thursday 19 February 2004 05:05 pm, big steve wrote: > I am having a problem getting the IF/ELIF to cooperate with me. I am using > a sample from: Learn to program By Alan Gauld. I keep getting this > msg: > > IndentationError: unindent does not match any outer indentation level > (<pyshell#3>, line 3) > > > But When I don't indent I get: > SyntaxError: invalid syntax > ___________________________________________________________________________ >______ > > This is the sample I was trying: > > value = 100 > if value > 10: > print 'This is OK' > elif value > 50: #This is where I get that msg (IndentationError) > print "Whoops, this is never seen' > else > print ' nor is this' You're missing a full colon after else: I suspect that when you're typing this into your email that you're not typing it *exactly* as you are in your script. You need to use exact precision when typing. Are you using the IDLE window to edit your script or another text editor? If you're using another text editor, I'd try redoing it in the IDLE window and see how it works for you. Be very careful to type all the colons - they make a difference. Don't hit errant spaces or backspaces... If that doesn't work, try doing it by just entering the spaces yourself without relying on the "automagic" indentation. Once you've got it running, take a look at the logic to see how you could improve it. Hint - look at the order the conditions are evaluated... Right now, it would *always* print "this is OK" because the first clause is evaluated, comes up true, and it skips the rest of the clauses... Hope this helps give you a starting point. Anna From dyoo at hkn.eecs.berkeley.edu Thu Feb 19 21:03:45 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Feb 19 21:03:50 2004 Subject: [Tutor] Python to C++ In-Reply-To: <000301c3f732$445432a0$622aa8c0@cad> Message-ID: <Pine.LNX.4.44.0402191755030.17240-100000@hkn.eecs.berkeley.edu> On Thu, 19 Feb 2004, Matthew Ozor wrote: > > Hello, > > I wrote a program that parse an HTML page on the internet. > > #partial example > import urllib > > urlopener = urllib.URLopener() > con = urlopener.open("http://test/test.html") > output = con.read() > > #end example > > > Now 'output' holds the web page and that what I want. Is there any way > to do this that easy in C/C++. I've tried google searching for examples > with no luck. I am using dev-c++ which uses mingw as it compiler. Hi Matthew, You might want to ask that question on a forum that focuses on C programming. The folks at comp.lang.c++, for example, will probably have more familiarity with that language's libraries than the folks here on Python-tutor. Yes, there are good libraries for doing web-oriented stuff in C. See the W3C Consortium's 'libwww' library: http://www.w3.org/Library/ http://www.w3.org/Library/Examples/ Hope this helps! From xcombelle at kedros.com Fri Feb 20 03:57:12 2004 From: xcombelle at kedros.com (Xavier Combelle) Date: Fri Feb 20 04:01:36 2004 Subject: [Tutor] If Elif In-Reply-To: <BAY8-DAV10j5p1Fjxe0000005cd@hotmail.com> References: <BAY8-DAV10j5p1Fjxe0000005cd@hotmail.com> Message-ID: <4035CBE8.4070200@kedros.com> big steve a ?crit : > ** > *I am having a problem getting the IF/ELIF to cooperate with me. I am > using a sample from: Learn to program By Alan Gauld. I keep > getting this msg: * > > *IndentationError: unindent does not match any outer indentation level > (<pyshell#3>, line 3)* > > ** > * > But When I don't indent I get: > SyntaxError: invalid syntax > _________________________________________________________________________________* > * * > *This is the sample I was trying:* > * * > *value = 100 > if value > 10: > print 'This is OK' > elif value > 50: #This is where I get that msg (IndentationError) > print "Whoops, this is never seen' > else > print ' nor is this'* > * * > *______________________________________________________________________________* > * * > * * > * * > * I CAN simply us the If format and all works it is just a little > confusing! > Could it be that I have mesed with my default sttings on > Indentation? Or am I just to thick to see the obvious? any help ? > Thanks Steve Hulett* > >------------------------------------------------------------------------ > > > When I tried to execute the script I found two mistakes "Whoops, this is never seen' which begin with a double quote and end with simple quote *else which don't end with a colon (should be else:) * but I did not found indentation error I suspect that the else is not above the if (It seems can be happen if you merge tabs and spaces for example) From magnus at thinkware.se Fri Feb 20 05:30:37 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Fri Feb 20 05:30:48 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gUHl0aG9uIHRvIEMrKw==?= Message-ID: <think001_4035de225476d@webmail.thinkware.se> Matthew Ozor wrote: > I wrote a program that parse an HTML page on the internet. . > import urllib > > urlopener = urllib.URLopener() > con = urlopener.open("http://test/test.html") > output = con.read() .. > Now 'output' holds the web page and that what I want. Is there any way > to do this that easy in C/C++. No. Of course, I don't have any formal proof of that, and I'm sure the libs Danny referred to are very helpful for C++ web coders, but I don't think it ever brings you close to the developer productivity of Python. The code at http://www.w3.org/Library/Examples/chunk.c does a bit more than your program, but not much more. C++ has it's advantages, your programs might be faster, and it's easier to make standalone executables etc, but when it comes to developer ease and productivity, there is certainly a big difference for this type of applications. It's another thing if you develop drivers for hardware, or operating systems... -- 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 Fri Feb 20 06:06:19 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Fri Feb 20 06:06:29 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gUHJvZ3JhbSB3b3JrIGZpbmUgaW4gSURMRSBidXQgbm90IG9uY2UgY29tcGlsZSBmcm9tIFB5MmV4ZQ==?= Message-ID: <think001_4035e98edefc0@webmail.thinkware.se> > I have the following function that works fine within IDLE but not the > exe version compile under Py2exe. > LookupError: no codec search functions registered: can't find encoding You need to tell py2exe to include the appropriate codec to convert between Unicode and 8-bit ASCII. For us that would be cp437, and for Sweden cp850, but I'm not sure about Canada, and I don't know the py2exe way of doing it from the top of my head. -- 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 Fri Feb 20 07:26:47 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Fri Feb 20 07:27:03 2004 Subject: =?ISO-8859-1?B?UHl0aG9uIDIuMyBvbiBSSCA3IFJlOiBbVHV0b3JdIEhvdyB0byBwcmludCB0byBhIGZpbGU/IChmd2Qp?= Message-ID: <think001_4035f6e587d38@webmail.thinkware.se> denny wrote: > By the way, how can I install a higher version of python(at least than > python2.2) on RedHat 7.3? > Shall I find one that have complied for the very RedHat 7.3 system? Maybe it's time to upgrade your OS? RH 7.3 is a bit dated... It's typically easy to build Python from source on Linux systems, but you should notice that RedHat uses Python for system administration tasks, so replacing /usr/bin/python with something newer might break OS tools. (But RH 7.3 uses Python 1.5.2. as /usr/bin/python anyway, so either you've messed up already, or you have the Python 2.2 binary installed as something else anyway.) It's typically safe to install whatever you want under /usr/local though. But this is really much more of a Linux question than a Python question. The source is at http://www.python.org/ftp/python/2.3.3/Python-2.3.3.tgz and brief instructionas at http://www.python.org/download/download_source.html I think it gets installed at /usr/local by default, but I wouldn't swear on 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 matt at ozor.net Fri Feb 20 08:15:48 2004 From: matt at ozor.net (Matthew Ozor) Date: Fri Feb 20 08:15:34 2004 Subject: [Tutor] Python to C++ In-Reply-To: <think001_4035de225476d@webmail.thinkware.se> Message-ID: <001601c3f7b3$a84c86a0$622aa8c0@cad> Thanks for the pointing me to the WWW library. The Python program worked great so there really is no need to convert it to C++. If any one is interested in it goto http://www.ozor.net/hostget Just a little program that updates HOST files on Windows machines. If you check it out let me know if you see any programming mistakes as it was my first Python program. Thank for the help Matt Ozor www.ozo.net -----Original Message----- From: Magnus Lycka [mailto:magnus@thinkware.se] Sent: Friday, February 20, 2004 5:31 AM To: Matthew Ozor; tutor@python.org Subject: Re: [Tutor] Python to C++ Matthew Ozor wrote: > I wrote a program that parse an HTML page on the internet. . > import urllib > > urlopener = urllib.URLopener() > con = urlopener.open("http://test/test.html") > output = con.read() .. > Now 'output' holds the web page and that what I want. Is there any way > to do this that easy in C/C++. No. Of course, I don't have any formal proof of that, and I'm sure the libs Danny referred to are very helpful for C++ web coders, but I don't think it ever brings you close to the developer productivity of Python. The code at http://www.w3.org/Library/Examples/chunk.c does a bit more than your program, but not much more. C++ has it's advantages, your programs might be faster, and it's easier to make standalone executables etc, but when it comes to developer ease and productivity, there is certainly a big difference for this type of applications. It's another thing if you develop drivers for hardware, or operating systems... -- 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 michel.belanger at seidel.ca Fri Feb 20 08:58:39 2004 From: michel.belanger at seidel.ca (=?ISO-8859-1?Q?Michel_B=E9langer?=) Date: Fri Feb 20 08:58:48 2004 Subject: [Tutor] Program work fine in IDLE but not once compile from Py2exe Message-ID: <4036128F.7060205@seidel.ca> >> I have the following function that works fine within IDLE but not the >> exe version compile under Py2exe. > >> LookupError: no codec search functions registered: can't find encoding > >You need to tell py2exe to include the appropriate >codec to convert between Unicode and 8-bit ASCII. >For us that would be cp437, and for Sweden cp850, >but I'm not sure about Canada, and I don't know the >py2exe way of doing it from the top of my head. This info lead me to the following in Py2exe site: http://starship.python.net/crew/theller/moin.cgi/EncodingsAgain /* "In py2exe 0.5, if the encodings are not found in the built exe, add these two to the /includes/: 'encodings', 'encodings.*' You can do this by adding a line options = {"py2exe": {"packages": ["encodings"]}}, to your setup.py file." */ Here is my setup.py /* # setup.py from distutils.core import setup import py2exe setup(console=["XferUpdFileOnWeb.py"]) options = {"py2exe": {"packages": ["encodings"]}}, options = {"py2exe": {"packages": ["encodings.*"]}}, */ Running Py2exe with options added to setup produced the error again about a missing codec. Here is the last line copy from the dos prompt: "LookupError: no codec search functions registered: can't find encoding" Regards Michel Belanger -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040220/06e7a4d8/attachment.html From missive at hotmail.com Fri Feb 20 10:56:56 2004 From: missive at hotmail.com (Lee Harr) Date: Fri Feb 20 10:57:02 2004 Subject: [Tutor] Re: Virtual file system - repository Message-ID: <BAY2-F131Ksl6cq5s6i0007cd76@hotmail.com> >Some one know some API or module for use a zip file or tar or another >file format for make this work like a virtual file system? >I need make a small data repository for some files and I can't find >nothing like this. Not sure this will help, but ... http://www.pycage.de/coding_pyvfsmodule.html http://www.terra.es/personal7/inigoserna/lfm/ _________________________________________________________________ Add photos to your messages with MSN 8. Get 2 months FREE*. http://join.msn.com/?page=features/featuredemail From missive at hotmail.com Fri Feb 20 11:35:55 2004 From: missive at hotmail.com (Lee Harr) Date: Fri Feb 20 11:36:06 2004 Subject: [Tutor] Re: Question on PyQt Signals and Slots Message-ID: <BAY2-F85hgnFZS4HIv600004a0f@hotmail.com> > I am building an application using python and Qt >and would like to know how one should pass arguments >when using Signals and Slots. Especially when one of >the arguments is a class instance. > >QObject.connect(self.table,SIGNAL("clicked(int,int,int,QPoint)"),self.tableclick) > >These were my attempts that returned errors. > >def tableclick(self,a,b,c,d): >def tableclick(self,*args): >def tableclick(self,*args,**argv): >def tableclick(self,a,b,c,d,*arg): > >RuntimeError: Signal has wrong argument types for slot Sorry for the delay... it really helps if you post a complete example that exhibits the behaviour you are experiencing. Here's one: import sys from qt import * from qttable import * numRows = 5 numCols = 5 class ATable(QTable): def tableclick(self, *args, **kw): print 'click', args, kw if __name__ == '__main__': app = QApplication(sys.argv) table = ATable(numRows, numCols) QObject.connect(table, SIGNAL("clicked(int,int,int,QPoint)"), table.tableclick) #QObject.connect(table, SIGNAL("valueChanged(int,int)"), table.tableclick) table.show() app.setMainWidget(table) app.exec_loop() The second connector there -- the one commented out -- actually works. Not sure yet why the clicked signal is not working. Maybe this will help someone else help us along. _________________________________________________________________ The new MSN 8: advanced junk mail protection and 2 months FREE* http://join.msn.com/?page=features/junkmail From missive at hotmail.com Fri Feb 20 11:44:16 2004 From: missive at hotmail.com (Lee Harr) Date: Fri Feb 20 11:46:28 2004 Subject: [Tutor] Re: Question on PyQt Signals and Slots Message-ID: <BAY2-F113qoMIOGCvqQ00011677@hotmail.com> Ok. This way works ... import sys from qt import * from qttable import * numRows = 5 numCols = 5 class ATable(QTable): def tableclick(self, *args, **kw): print 'click', args, kw def tc2(*args, **kw): print 'click2', args, kw if __name__ == '__main__': app = QApplication(sys.argv) table = ATable(numRows, numCols) QObject.connect(table, SIGNAL("clicked(int, int, int, const QPoint &)"), tc2) QObject.connect(table, SIGNAL("clicked(int, int, int, const QPoint &)"), table.tableclick) #QObject.connect(table, SIGNAL("valueChanged(int,int)"), table.tableclick) table.show() app.setMainWidget(table) app.exec_loop() _________________________________________________________________ MSN 8 helps eliminate e-mail viruses. Get 2 months FREE*. http://join.msn.com/?page=features/virus From afant at geekmail.cc Wed Feb 18 20:04:15 2004 From: afant at geekmail.cc (Andrew Fant) Date: Fri Feb 20 12:38:04 2004 Subject: [Tutor] Getting "file sizes" In-Reply-To: <200402181644.49426.syn_ack@comcast.net> References: <Pine.LNX.4.44.0402181316490.23057-100000@hkn.eecs.berkeley.edu> <200402181644.49426.syn_ack@comcast.net> Message-ID: <58780000.1077152655@flux.usg.tufts.edu> Is there a reason you couldn't use glob() to generate a list of all the files in the directory that match a wildcard pattern and then make a for loop over the list to call getsize() and grab the results? I could be completely out of my depth here, but I did something like this once to grab ID3 tags from a bunch of scattered mp3 files. Andy --On Wednesday, February 18, 2004 16:44:49 -0800 Joshua Banks <syn_ack@comcast.net> wrote: > On Wednesday 18 February 2004 01:22 pm, you wrote: >> Ah, a Gentoo fan. *grin* > > Yes, I luv Gentoo... :P > >> Ah, you know about os.path.getsize() already then. getsize() is >> actually more versatile than you might think: have you tried applying >> it on an individual file path? > > Yes, I can get the file size of an individual file by specifying the > complete path. But if I have a directory with 60 files then I would > have to manually put the path in for each file in that directory that I > wish to know the size of. > > Example: The following gives me a list of the files in the directory > specified below. There's a total of 12 files listed for examples sake. > >>>> os.listdir('/var/log/portage') > ['1782-openmotif-2.1.30-r3.log', '1781-iptables-1.2.8-r1.log', > '1756-slocate-2.7-r5.log', '1763-xloadimage-4.1- > r1.log', '1773-iproute-20010824-r4.log', > '1757-gentoo-sources-2.4.22-r5.log', '1788-tcl-8.3.4.log', '1797-libpe > rl-5.8.0.log', '1769-python-2.3.3.log', '1776-xfree-drm-4.3.0-r6.log', > '1806-ymessenger-1.0.4.1.log', '1766-win > e-20031118-r1.log'] > > I also understand that I can do the following 12 times, specifying a > different file each time and get the "file size answers that I'm > looking for. So I understand how to do this the HardWay. > > >>>> os.path.getsize('/var/log/portage/1782-openmotif-2.1.30-r3.log') > 39L > > What I don't understand is how to get Python to use the "getsize()" > function for each file that the "os.listdir('/var/log/portage')" > function lists. > > I've read and read and read. I don't understand, what seems, would be a > simple task. Having to manually input each file, one at a time seems > backwards to the progamming moto. Do more with less so to say. > > I'm I not making any sense? Any idea's on how I can get this to work? > > Thanks, > Joshua Banks > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From barrys at datatree.co.uk Fri Feb 20 05:50:43 2004 From: barrys at datatree.co.uk (Barry Smithers) Date: Fri Feb 20 12:38:31 2004 Subject: [Tutor] Re: If Elif (big steve) References: <E1Au7vn-0004qC-HO@mail.python.org> Message-ID: <005c01c3f79f$63b3e2e0$b364a8c0@datatree> You've got a space in front of the elif. If you delete that it should be fine. Try the below: value = 100 if value > 10: print "This is OK" elif value > 50: #This is where I won't get that msg (IndentationError) print "Whoops, this is never seen" else: print " nor is this" Cheers Barry > Message: 6 > Date: Thu, 19 Feb 2004 15:05:58 -0700 > From: "big steve" <bigsteve127@hotmail.com> > Subject: [Tutor] If Elif > To: <Tutor@python.org> > Message-ID: <BAY8-DAV10j5p1Fjxe0000005cd@hotmail.com> > Content-Type: text/plain; charset="windows-1252" > > > I am having a problem getting the IF/ELIF to cooperate with me. I am using a sample from: Learn to program By Alan Gauld. I keep getting this msg: > > IndentationError: unindent does not match any outer indentation level (<pyshell#3>, line 3) > > > But When I don't indent I get: > SyntaxError: invalid syntax > ____________________________________________________________________________ _____ > > This is the sample I was trying: > > value = 100 > if value > 10: > print 'This is OK' > elif value > 50: #This is where I get that msg (IndentationError) > print "Whoops, this is never seen' > else > print ' nor is this' > From smriti at alumnux.com Mon Feb 16 05:52:58 2004 From: smriti at alumnux.com (smriti) Date: Fri Feb 20 12:39:26 2004 Subject: [Tutor] comments in python Message-ID: <4030A10A.5070106@alumnux.com> hi, i'm new to python. i want to know what are the different types of comment style in python. smriti From vissen at gmx.net Thu Feb 12 16:16:37 2004 From: vissen at gmx.net (vissen@gmx.net) Date: Fri Feb 20 12:39:44 2004 Subject: [Tutor] compile problem in emacs Message-ID: <26161.1076620597@www23.gmx.net> hello everybody. i am learning python and use Emacs as the editor (i am new to linux also) to compile a simple program to generate fibonacci numbers from the example given in the tutorial by Guido Rossum and it gave a syntax error. This example is included as part of documentation in redhat linux version 8 . any suggestions / ideas are useful. thanks for reading. -- -Vissen GMX ProMail (250 MB Mailbox, 50 FreeSMS, Virenschutz, 2,99 EUR/Monat...) jetzt 3 Monate GRATIS + 3x DER SPIEGEL +++ http://www.gmx.net/derspiegel +++ From dyoo at hkn.eecs.berkeley.edu Fri Feb 20 12:51:29 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Feb 20 12:51:34 2004 Subject: [Tutor] comments in python In-Reply-To: <4030A10A.5070106@alumnux.com> Message-ID: <Pine.LNX.4.44.0402200944470.31344-100000@hkn.eecs.berkeley.edu> On Mon, 16 Feb 2004, smriti wrote: > i want to know what are the different types of comment style in python. Hi Smriti, A hash character '#' will comment out everything up to the end of a line. You can see an example of a comment in the official Python Tutorial: http://www.python.org/doc/tut/node5.html There's also a "documentation string" system that allows us to label our functions with help messages. An example of such a "docstring" is in the fibonacci example here: http://www.python.org/doc/tut/node6.html#SECTION006600000000000000000 Docstrings are useful because they can be queried from the interactive interpreter: ### >>> def sayHello(): ... """This is a simple function that just says hello.""" ... print "Hello!" ... >>> sayHello.__doc__ 'This is a simple function that just says hello.' ### Docstrings also show up if we call for help() on a particular function: ### >>> help(sayHello) Help on function sayHello in module __main__: sayHello() This is a simple function that just says hello. ### and most functions in Python have these docstrings attached to them for quick reference. Good luck to you! From dyoo at hkn.eecs.berkeley.edu Fri Feb 20 12:57:04 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Feb 20 12:57:16 2004 Subject: [Tutor] compile problem in emacs In-Reply-To: <26161.1076620597@www23.gmx.net> Message-ID: <Pine.LNX.4.44.0402200951390.31344-100000@hkn.eecs.berkeley.edu> On Thu, 12 Feb 2004 vissen@gmx.net wrote: > i am learning python and use Emacs as the editor (i am new to linux > also) to compile a simple program to generate fibonacci numbers from the > example given in the tutorial by Guido Rossum and it gave a syntax > error. This example is included as part of documentation in redhat > linux version 8 . any suggestions / ideas are useful. thanks for > reading. If it's a SyntaxError, we really need to look closely at what you've typed in, as well as what Python is complaining about. The problem here is that there are many different ways a SyntaxError can occur! We don't want to enumerate them all, because you'll get bored, and it won't help. *grin* So let's try not guess the problem: show us what you typed, and we can start from there. Talk to you later! From joshua at marktwain.net Fri Feb 20 13:01:58 2004 From: joshua at marktwain.net (Joshua) Date: Fri Feb 20 13:02:04 2004 Subject: [Tutor] pwman Message-ID: <1077300118.7773.6.camel@secretfire> Hi, I can't seem to find anywhere to download the pwman (password maanger) program listed on the Vaults of Parnassus (the Vaults link doesn't work). Does anyone know where I can get it? I'm thinking about writing a password manager myself. Joshua K. From marilyn at deliberate.com Fri Feb 20 13:22:13 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Fri Feb 20 13:22:17 2004 Subject: [Tutor] Idle and program command line In-Reply-To: <Pine.LNX.4.44.0402191138020.12955-100000@hkn.eecs.berkeley.edu> Message-ID: <Pine.LNX.4.44.0402201019240.11161-100000@Kuna> On Thu, 19 Feb 2004, Danny Yoo wrote: > > > On Thu, 19 Feb 2004, Marilyn Davis wrote: > > > > in the tutor for Idle it is written that you can't pass command line > > > arguments to your python script via Idle. They suggest to set the > > > arguments directly in the script. If the script is tested and to be > > > run alone you can comment these settings out. > > > > Thank you. I figured something like that but wanted to be sure I wasn't > > missing some hidden button. > > > It might make a good feature request to allow for the definition of > command line arguments in IDLE. You can ask on IDLE-dev and see what > their response is: > > http://mail.python.org/mailman/listinfo/idle-dev > > > Talk to you later! OK, good idea. Did it and it was well-received. >From marilyn@deliberate.com Fri Feb 20 10:19:08 2004 Date: Fri, 20 Feb 2004 10:15:08 -0800 (PST) From: Marilyn Davis <marilyn@deliberate.com> To: Kurt B. Kaiser <kbk@shore.net> Cc: idle-dev@python.org Subject: Re: [Idle-dev] Setting argv in idle Thanks. The __future__ looks good. Marilyn On Fri, 20 Feb 2004, Kurt B. Kaiser wrote: > Marilyn Davis <marilyn@deliberate.com> writes: > > > My friends and I can't find a way to set up command line arguments > > to feed into our python programs while using idle. > > > > This would be a useful feature. > > > > It's easy to work-around this but, still, it would be nice. > > GvR would like this, also: > > https://sourceforge.net/tracker/index.php?func=detail&aid=441575&group_id=9579&atid=359579 > > From bgailer at alum.rpi.edu Fri Feb 20 16:33:18 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri Feb 20 16:32:49 2004 Subject: [Tutor] comments in python In-Reply-To: <4030A10A.5070106@alumnux.com> References: <4030A10A.5070106@alumnux.com> Message-ID: <6.0.0.22.0.20040220143113.02376770@mail.mric.net> At 03:52 AM 2/16/2004, smriti wrote: >hi, >i'm new to python. >i want to know what are the different types of comment style in python. Note that there are no inline /* like this */ comments Triple quotes can be used to "comment out" a block of code. >Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From glingl at aon.at Sat Feb 21 01:35:17 2004 From: glingl at aon.at (Gregor Lingl) Date: Sat Feb 21 01:34:23 2004 Subject: [Tutor] comments in python In-Reply-To: <6.0.0.22.0.20040220143113.02376770@mail.mric.net> References: <4030A10A.5070106@alumnux.com> <6.0.0.22.0.20040220143113.02376770@mail.mric.net> Message-ID: <4036FC25.9080209@aon.at> Bob Gailer schrieb: > > Triple quotes can be used to "comment out" a block of code. > Some Pythons syntax aware IDEs as IDLE or Pythonwin have menu items and keyboard shortcuts to "comment out" and to "uncomment" "regions" of code. Gregor From idiot1 at netzero.net Sat Feb 21 01:51:57 2004 From: idiot1 at netzero.net (Kirk Bailey) Date: Sat Feb 21 01:52:00 2004 Subject: [Tutor] globbing and sorting and dating, oh my! Message-ID: <401F402A.2050703@netzero.net> Hello gang, I have an interesting task. I want to add a WHAT'S NEW feature to my wiki. This must build a list of all files in the wiki (glob.glob to the rescue for a simple list of files in the library of pages) and sort them out according to AGE since last written to, delete those older than X days, take what is left and convert the time stamp to something a human could read without being a un*x geek. Once the data is converted to human preferences, I will take the results and spew it in a html page, one per line, with the usual suspects providing html markup, after which I will run of and hide for a few months. Anyone got some suggestions on accomplishing this task? -- end think http://www.tinylist.org/ - $FREE$ software for liberty +-------+ http://www.pinellasintergroupsociety.org/ - In Her Service | BOX | http://www.listville.net/ - $FREE$ list hosting services +-------+ http://www.howlermonkey.net/ - $FREE$ email service kniht http://www.sacredelectron.org/ - My personal SCREED pit (C)2004 Kirk D Bailey, all rights reserved- but ask! From gustabares at verizon.net Sat Feb 21 13:54:27 2004 From: gustabares at verizon.net (Gus Tabares) Date: Sat Feb 21 13:53:35 2004 Subject: [Tutor] Unix uid numbers Message-ID: <200402211354.40381.gustabares@verizon.net> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hey all, I was wondering if there was a function (or module) that would return the Unix username when handed the UID. I'm pretty sure there is one, I just can't seem to find it. Thanks, Gus Tabares -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (GNU/Linux) iD8DBQFAN6lqlBrctWk2LusRAtp6AJ0SoGzfRCesknUalDdjlFhrr0JU7QCffzLr CXIobnhsmhp82F1hLZC8HBE= =oH5a -----END PGP SIGNATURE----- From gustabares at verizon.net Sat Feb 21 14:20:10 2004 From: gustabares at verizon.net (Gus Tabares) Date: Sat Feb 21 14:18:58 2004 Subject: [Tutor] Unix uid numbers In-Reply-To: <200402211354.40381.gustabares@verizon.net> References: <200402211354.40381.gustabares@verizon.net> Message-ID: <200402211420.10383.gustabares@verizon.net> On Saturday 21 February 2004 13:54, Gus Tabares wrote: > Hey all, > > I was wondering if there was a function (or module) that would return the > Unix username when handed the UID. I'm pretty sure there is one, I just > can't seem to find it. > OK nevermind that. The module I was looking for is 'pwd' and the function is getpwuid(uid), incase anyone else was wondering:) Gus Tabares From carroll at tjc.com Sat Feb 21 15:19:21 2004 From: carroll at tjc.com (Terry Carroll) Date: Sat Feb 21 15:19:28 2004 Subject: [Tutor] MOdule accessing its own date/time stamp? Message-ID: <Pine.LNX.4.44.0402211217540.7159-100000@violet.rahul.net> Is there any way for a module to access the timestamp for itself? I'd like a module to be able to print out the time/date on which it was last saved. -- Terry Carroll Santa Clara, CA carroll@tjc.com Modell delendus est From sigurd at 12move.de Sat Feb 21 16:29:41 2004 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Sat Feb 21 16:48:57 2004 Subject: [Tutor] MOdule accessing its own date/time stamp? In-Reply-To: <Pine.LNX.4.44.0402211217540.7159-100000@violet.rahul.net> (Terry Carroll's message of "Sat, 21 Feb 2004 12:19:21 -0800 (PST)") References: <Pine.LNX.4.44.0402211217540.7159-100000@violet.rahul.net> Message-ID: <m3fzd4t9pd.fsf@hamster.pflaesterer.de> On 21 Feb 2004, Terry Carroll <- carroll@tjc.com wrote: > Is there any way for a module to access the timestamp for itself? > I'd like a module to be able to print out the time/date on which it was > last saved. ******************************************************************** # module foo from os.path import getmtime from time import ctime def last_saved (): return ctime(getmtime(__file__)) ******************************************************************** $ 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. >>> import foo >>> foo.last_saved() 'Sat Feb 21 22:27:38 2004' >>> Or did you mean something else? Karl -- Please do *not* send copies of replies to me. I read the list From pythontutor at venix.com Sat Feb 21 16:53:31 2004 From: pythontutor at venix.com (Lloyd Kvam) Date: Sat Feb 21 16:53:39 2004 Subject: [Tutor] MOdule accessing its own date/time stamp? In-Reply-To: <Pine.LNX.4.44.0402211217540.7159-100000@violet.rahul.net> References: <Pine.LNX.4.44.0402211217540.7159-100000@violet.rahul.net> Message-ID: <4037D35B.3070609@venix.com> The module has a __file__ attribute. os.stat applied to that file name should give you the time stamp. You will have format issues to battle after that. Terry Carroll wrote: > Is there any way for a module to access the timestamp for itself? > > I'd like a module to be able to print out the time/date on which it was > last saved. > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From carroll at tjc.com Sat Feb 21 17:10:47 2004 From: carroll at tjc.com (Terry Carroll) Date: Sat Feb 21 17:10:54 2004 Subject: [Tutor] MOdule accessing its own date/time stamp? In-Reply-To: <4037D35B.3070609@venix.com> Message-ID: <Pine.LNX.4.44.0402211407200.7159-100000@violet.rahul.net> On Sat, 21 Feb 2004, Lloyd Kvam wrote: > The module has a __file__ attribute. os.stat applied to that file name should > give you the time stamp. You will have format issues to battle after that. Thanks, Lloyd. I've got this working now: import os, time print "File %s, last saved on %s" % (__file__, time.asctime(time.localtime(os.stat(__file__)[8]))) On Sat, 21 Feb 2004, Karl Pfl?sterer wrote: > # module foo > > from os.path import getmtime > from time import ctime > > def last_saved (): > return ctime(getmtime(__file__)) Thank you to you, too, Karl. I got Lloyd's email first and started going down that rodad before I got yours, but I still appreciate the ctime/getmtime approach, too. -- Terry Carroll Santa Clara, CA carroll@tjc.com Modell delendus est From marilyn at deliberate.com Sat Feb 21 20:38:08 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Sat Feb 21 20:38:15 2004 Subject: [Tutor] Unix uid numbers In-Reply-To: <200402211420.10383.gustabares@verizon.net> Message-ID: <Pine.LNX.4.44.0402211737160.11161-100000@Kuna> On Sat, 21 Feb 2004, Gus Tabares wrote: > On Saturday 21 February 2004 13:54, Gus Tabares wrote: > > Hey all, > > > > I was wondering if there was a function (or module) that would return the > > Unix username when handed the UID. I'm pretty sure there is one, I just > > can't seem to find it. > > > > OK nevermind that. The module I was looking for is 'pwd' and the function is > getpwuid(uid), incase anyone else was wondering:) > Thank you, I was. Marilyn > > Gus Tabares > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- From dyoo at hkn.eecs.berkeley.edu Sun Feb 22 01:43:56 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Feb 22 01:44:03 2004 Subject: [Tutor] globbing and sorting and dating, oh my! In-Reply-To: <401F402A.2050703@netzero.net> Message-ID: <Pine.LNX.4.44.0402212218290.3128-100000@hkn.eecs.berkeley.edu> On Tue, 3 Feb 2004, Kirk Bailey wrote: > Hello gang, I have an interesting task. I want to add a WHAT'S NEW > feature to my wiki. [specification cut] > Anyone got some suggestions on accomplishing this task? Hi Kirk, Ok, it sounds like you've thought this problem through. let's look at how you're breaking the problem down. I'll try to put some stifling formality on your sentences. *grin* > This must build a list of all files in the wiki (glob.glob to the rescue > for a simple list of files in the library of pages) Perfectly reasonable subtask. It sounds like you already have a good plan to grab those files. Let's call this subproblem "get_all_wiki_files()" for the moment. > and sort them out according to AGE since last written to Sounds good. So, given some list of files, you want to sort that file list based on the date of each file. It's funny how certain questions will cluster in time --- Terry Carroll just asked a question on getting the timestamp of a module file: http://mail.python.org/pipermail/tutor/2004-February/028352.html You can use the same function that Karl suggested (os.path.getmtime()) to get the modification date of a file. And by using that, we can probably cook up a sorting routine. Let's call this subproblem "sort_by_date()". > delete those older than X days, So you're setting up a cutoff filter --- given a list of files, return a new list that contains only "fresh" files. Let's call this subproblem "filter_by_freshness()". > take what is left and convert the time stamp to something a human could > read without being a un*x geek. Karl's response also refers to a function called time.ctime() that takes the Unix timestamp, and translates it into nicely formatting text. So it might be nice to write a function that takes a file name, and returns its human-readable modification date. Let's call this "get_modification_date()". Notice that if we treat these three subproblems separately, then it shouldn't be too difficult to work each one out. Once we have them working, then we can put them together to do the job you want. In fact, we can even write some pseudocode: ### files = get_all_wiki_files() sorted_files = sort_by_date(files) fresh_files = filter_by_freshness(sorted_files, some_cutoff_date) for filename in fresh_files: print filename, get_modification_date(filename) ### This is one high-level view of what you just said, but stated with the "pretend" functions that we talked about. But if those pretend functions turn into reality, then this pseudocode should work. Let's look again at what you asked: """This must build a list of all files in the wiki (glob.glob to the rescue for a simple list of files in the library of pages) and sort them out according to AGE since last written to, delete those older than X days, take what is left and convert the time stamp to something a human could read without being a un*x geek. Once the data is converted to human preferences, I will take the results and spew it in a html page, one per line...""" Does the pseudocode above capture what you want? Please feel free to ask more questions on this. Good luck to you! From vissen at gmx.net Fri Feb 20 13:32:42 2004 From: vissen at gmx.net (vissen@gmx.net) Date: Sun Feb 22 02:05:20 2004 Subject: [Tutor] compile problem in emacs References: <Pine.LNX.4.44.0402200951390.31344-100000@hkn.eecs.berkeley.edu> Message-ID: <15303.1077301962@www28.gmx.net> > > i am learning python and use Emacs as the editor (i am new to linux > > also) to compile a simple program to generate fibonacci numbers from the > > example given in the tutorial by Guido Rossum and it gave a syntax > > error. This example is included as part of documentation in redhat > > linux version 8 . any suggestions / ideas are useful. thanks for > > reading. > > > If it's a SyntaxError, we really need to look closely at what you've typed > in, as well as what Python is complaining about. The problem here is that > there are many different ways a SyntaxError can occur! We don't want to > enumerate them all, because you'll get bored, and it won't help. *grin* > > So let's try not guess the problem: show us what you typed, and we can > start from there. this is the code i saved in the emacs ed file ... def fib(n): # write Fibonacci series up to n """Print a Fibonacci series up to n.""" a, b = 0, 1 while b < n: print b, a, b = b, a+b and then in terminal mode i typed : $ python prgm22.py which generates the syntax error in the line1 ( def fib(n): ). have i made any mistake ? thanks for the reply. -- -Vissen GMX ProMail (250 MB Mailbox, 50 FreeSMS, Virenschutz, 2,99 EUR/Monat...) jetzt 3 Monate GRATIS + 3x DER SPIEGEL +++ http://www.gmx.net/derspiegel +++ From justinstraube at charter.net Sun Feb 22 03:42:44 2004 From: justinstraube at charter.net (justinstraube@charter.net) Date: Sun Feb 22 03:43:05 2004 Subject: [Tutor] path names Message-ID: <200402220842.i1M8giko088289@mxsf05.cluster1.charter.net> >>> glob.glob('e:/*.avi') ['e:/jupiter2.avi', 'e:/jupiter3.avi', 'e:/jupiter4.avi'] >>> glob.glob('e:\*.avi') ['e:\\jupiter2.avi', 'e:\\jupiter3.avi', 'e:\\jupiter4.avi'] >>> Can anyone offer a simple explanation as to the differences between using '/' and '\' in a path name? And any reason to use one over the other? Also, what is happening in the second example that the path names have two slashes rather than one as in the first example? Thank you justin --- From shaleh at speakeasy.net Sun Feb 22 10:46:36 2004 From: shaleh at speakeasy.net (Sean 'Shaleh' Perry) Date: Sun Feb 22 10:46:54 2004 Subject: [Tutor] path names In-Reply-To: <200402220842.i1M8giko088289@mxsf05.cluster1.charter.net> References: <200402220842.i1M8giko088289@mxsf05.cluster1.charter.net> Message-ID: <200402220746.36809.shaleh@speakeasy.net> On Sunday 22 February 2004 00:42, justinstraube@charter.net wrote: > >>> glob.glob('e:/*.avi') > > ['e:/jupiter2.avi', 'e:/jupiter3.avi', 'e:/jupiter4.avi'] > > >>> glob.glob('e:\*.avi') > > ['e:\\jupiter2.avi', 'e:\\jupiter3.avi', 'e:\\jupiter4.avi'] > > > Can anyone offer a simple explanation as to the differences between > using '/' and '\' in a path name? And any reason to use one over the > other? > unix uses / and Windows uses \. Since Python is meant to be multi-platform it just does the right thing for you. Use whatever makes you feel comfortable. Also look at os.path.join() which adds the right slash for your platform: print os.path.join(['foo', 'bar', 'baz']) foo/bar/baz on my Linux box. > Also, what is happening in the second example that the path names have > two slashes rather than one as in the first example? > In Python code a \ (backslash) escapes the letter in front of it. For instance in regular expressions the '.' (period or dot) means 'any one character' but sometimes you want it to mean a dot, like in IP addresses so you need to use a backslash to escape its usual meaning. \d{,3}.\d{,3}.\d{,3}.\d{,3} # match an IP address will do odd things because the periods are not escaped. This would match '123a456b789d123'. Also, see how the 'd' is escaped? This makes it mean "any number" and not 'the letter d'. You will also see backslashes in formatting codes like \t (tab). From alan.gauld at blueyonder.co.uk Sun Feb 22 13:50:35 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Feb 22 13:50:21 2004 Subject: [Tutor] compile problem in emacs References: <Pine.LNX.4.44.0402200951390.31344-100000@hkn.eecs.berkeley.edu> <15303.1077301962@www28.gmx.net> Message-ID: <00f901c3f974$c1eb9430$6401a8c0@xp> > this is the code i saved in the emacs ed file ... > > def fib(n): # write Fibonacci series up to n > """Print a Fibonacci series up to n.""" > a, b = 0, 1 > while b < n: > print b, > a, b = b, a+b First question, did you really type it like this or did you have it indented? I know some mailers strip indentation...? In Python indentation matters so it should look like: def fib(n): # write Fibonacci series up to n """Print a Fibonacci series up to n.""" a, b = 0, 1 while b < n: print b, a, b = b, a+b If you don't have the indentatuion(spacing) as shown Python will get confused - and so will your readers! - and throw an error. 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 Sun Feb 22 13:56:55 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Feb 22 13:56:40 2004 Subject: [Tutor] path names References: <200402220842.i1M8giko088289@mxsf05.cluster1.charter.net> <200402220746.36809.shaleh@speakeasy.net> Message-ID: <011101c3f975$a4273a70$6401a8c0@xp> > In Python code a \ (backslash) escapes the letter in front of it. For > instance in regular expressions .... > > \d{,3}.\d{,3}.\d{,3}.\d{,3} # match an IP address > > will do odd things because the periods are not escaped. And just to emphasise the point its not just egular expressions but any string. Thus we can create a string with a newline in the middle like this: >>> print "This line splits\nover two lines" This line splits over two lines >>> Notice the \n? Which is OK except if you want to put a backslash itself in the string - as we do with a Windows path. The solution is to use a double backslash wjere the first is the usual escape character and the second to tell Python that the special char is a backslash... >>> Print "This line has a tab\t and backslash(\\)" This line has a tab and backslash(\) >>> HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From idiot1 at netzero.net Sun Feb 22 23:50:23 2004 From: idiot1 at netzero.net (Kirk Bailey) Date: Sun Feb 22 23:50:54 2004 Subject: [Tutor] globbing and sorting and dating, oh my! In-Reply-To: <Pine.LNX.4.44.0402212218290.3128-100000@hkn.eecs.berkeley.edu> References: <Pine.LNX.4.44.0402212218290.3128-100000@hkn.eecs.berkeley.edu> Message-ID: <4039868F.9030709@netzero.net> Also, the wonderful liberty in choosing variable names python offers made writing the program easier, as variables with meaningful names make it MUCH easier to track what one is doing NOW, not to mention when one must maintain the beast a year from now. THANK YOU, whoever insisted on this property. end think http://www.tinylist.org/ - $FREE$ software for liberty +-------+ http://www.pinellasintergroupsociety.org/ - In Her Service | BOX | http://www.listville.net/ - $FREE$ list hosting services +-------+ http://www.howlermonkey.net/ - $FREE$ email service kniht http://www.sacredelectron.org/ - My personal SCREED pit (C)2004 Kirk D Bailey, all rights reserved- but ask! From idiot1 at netzero.net Sun Feb 22 23:59:58 2004 From: idiot1 at netzero.net (Kirk Bailey) Date: Mon Feb 23 00:00:56 2004 Subject: [Tutor] MOdule accessing its own date/time stamp? In-Reply-To: <Pine.LNX.4.44.0402211217540.7159-100000@violet.rahul.net> References: <Pine.LNX.4.44.0402211217540.7159-100000@violet.rahul.net> Message-ID: <403988CE.8080703@netzero.net> Sure thing. It is just a file, after all. age=os.path.getmtime(path+filename) point 'path' at the location of the file, OR make it the current directory, and 'filename' the name of the module. 'age' will contain the timestamp for when it was last written to. if it is in the current directory, then " './'+filename " is the thing to do. But even if it is, declaring the absolute path to the file and it's name will ALWAYS work. This any help? Terry Carroll wrote: > Is there any way for a module to access the timestamp for itself? > > I'd like a module to be able to print out the time/date on which it was > last saved. > -- end think http://www.tinylist.org/ - $FREE$ software for liberty +-------+ http://www.pinellasintergroupsociety.org/ - In Her Service | BOX | http://www.listville.net/ - $FREE$ list hosting services +-------+ http://www.howlermonkey.net/ - $FREE$ email service kniht http://www.sacredelectron.org/ - My personal SCREED pit (C)2004 Kirk D Bailey, all rights reserved- but ask! From kp8 at mac.com Mon Feb 23 02:04:40 2004 From: kp8 at mac.com (kevin parks) Date: Mon Feb 23 02:05:53 2004 Subject: [Tutor] formatting and pretty printing nested structures Message-ID: <8CBC0485-65CE-11D8-9523-003065555ABC@mac.com> Hi. I have a list of lists. Inside the list are lists that are made up of strings and floats. When i print the list it prints the floats in the usual insane long wierdo format and i want to print them with string formatting so that they are more readable, so i somehow have to pick apart the nested items so that i can print: 0 ['C', 8.0, 8.0] 1 ['C#', 8.0099999999999998, 8.0833349227905273] more like this: 0 ['C', 8.00, 8.000000] 1 ['C#', 8.01, 8.083333] or even betterererer: 0 C 8.00 8.000000 1 C# 8.01 8.083333 What is the best way to format and print nested srtucres like i have here? cheers, kevin -- ----- from rtcmix import * c = ['C', 8.00, octpch(8.00)] cs =['C#', 8.01, octpch(8.01)] d = ['D', 8.02, octpch(8.02)] ds = ['D#', 8.03, octpch(8.03)] e = ['E', 8.04, octpch(8.04)] f = ['F', 8.05, octpch(8.05)] fs = ['F#', 8.06, octpch(8.06)] g = ['G', 8.07, octpch(8.07)] gs = ['G3', 8.08, octpch(8.08)] a = ['A', 8.09, octpch(8.09)] ash = ['A#', 8.10, octpch(8.10)] b = ['B', 8.11, octpch(8.11)] seq = [c, cs, d, ds, e, f, fs, g, gs, a, ash, b] count = 0 print '\n','~~~' * 26 print seq for i in seq: print count, i # print '%d \t %f' % (count, i) count = count + 1 print '~~~' * 26, '\n' From glingl at aon.at Mon Feb 23 04:01:20 2004 From: glingl at aon.at (Gregor Lingl) Date: Mon Feb 23 04:00:25 2004 Subject: [Tutor] formatting and pretty printing nested structures In-Reply-To: <8CBC0485-65CE-11D8-9523-003065555ABC@mac.com> References: <8CBC0485-65CE-11D8-9523-003065555ABC@mac.com> Message-ID: <4039C160.3000906@aon.at> kevin parks schrieb: > Hi. I have a list of lists. Inside the list are lists that are made up > of strings and floats. When i print the list it prints the floats in > the usual insane long wierdo format and i want to print them with > string formatting so that they are more readable, so i somehow have to > pick apart the nested items so that i can print: > > 0 ['C', 8.0, 8.0] > 1 ['C#', 8.0099999999999998, 8.0833349227905273] > > more like this: > > 0 ['C', 8.00, 8.000000] > 1 ['C#', 8.01, 8.083333] > > or even betterererer: > > 0 C 8.00 8.000000 > 1 C# 8.01 8.083333 > > What is the best way to format and print nested srtucres like i have > here? > Hi Kevin! Not having a module named rtcmix at hand nor knowing the function octpch and even not knowing if the following is the *best way*, I recommend >>> mylist = [['C', 8.0, 8.0], ['C#', 8.0099999999999998, 8.0833349227905273]] >>> for i, item in enumerate(mylist): print "%2d %-2s %4.2f%10.6f" % tuple([i]+item) 0 C 8.00 8.000000 1 C# 8.01 8.083335 or, if enumerate doesn't exist in your Python version: >>> for i in range(len(mylist)): print "%2d %-2s %4.2f%10.6f" % tuple([i]+mylist[i]) 0 C 8.00 8.000000 1 C# 8.01 8.083335 Regards, Gregor > cheers, > > kevin > > -- ----- > > from rtcmix import * > > c = ['C', 8.00, octpch(8.00)] > From RobinHood42 at clickta.com Mon Feb 23 04:48:42 2004 From: RobinHood42 at clickta.com (alice) Date: Mon Feb 23 04:47:19 2004 Subject: [Tutor] global variables & recursion Message-ID: <200402231648.42994.RobinHood42@clickta.com> I would like some advice. Is there a better way of doing this? Particularly I'm not sure if using global variables is a good idea. # Euclid's algorithm (greatest common divisor): def gcd(a,b): if (b > a): a, b = b, a r = a % b if (r == 0): return b else: return gcd(b,r) # Find integers s and t such that as + bt = gcd(a,b): # global variables (is this bad programming style?) _eulen = 0 # recursion depth _rem = [] # list of remainders def st(a,b): global _eulen global _rem # a should be bigger than b: if (b > a): a, b = b, a # find remainder: r = a % b if (r == 0): # finished # find s and t: s = 1 t = 1 - (a / b) for i in range(_eulen): b = _rem.pop() a = _rem.pop() s,t = t, s - (a/b)*t # show results: print "gcd(%d,%d) = (%d)(%d) + (%d)(%d) = %d" % (a,b,a,s,b,t,a*s+b*t) # reset _eulen and _rem: _eulen = 0 _rem = [] else: # not finished. # we will need this information later: _eulen += 1 _rem.append(a) _rem.append(b) # function calls itself: st(b,r) From glingl at aon.at Mon Feb 23 06:01:20 2004 From: glingl at aon.at (Gregor Lingl) Date: Mon Feb 23 06:00:34 2004 Subject: [Tutor] global variables & recursion In-Reply-To: <200402231648.42994.RobinHood42@clickta.com> References: <200402231648.42994.RobinHood42@clickta.com> Message-ID: <4039DD80.8030108@aon.at> Hi Alice! (Hi Robin Hood?) alice schrieb: >I would like some advice. > > I'll try. As your second problem, determioning s and t is a generaliziation of the simplecomputation of gcd, I'll concentrate on this. (Although there are 'famous' versions of euclids algorithm which are well worth discussing. So if you are interested in it, feel fre to ask more ...) >Is there a better way of doing this? >Particularly I'm not sure if using global variables is a good idea. > > Generally you should avoid using global variables, if it can easily be done. ># Find integers s and t such that as + bt = gcd(a,b): > ># global variables (is this bad programming style?) > > A standard way to do so is passing them as parameters with default arguments. >## _eulen = 0 # recursion depth >## _rem = [] # list of remainders > >def st(a,b,_eulen=0, _rem=[]): > >## global _eulen >## global _rem > > # a should be bigger than b: > if (b > a): > a, b = b, a > > # find remainder: > r = a % b > > if (r == 0): # finished > > # find s and t: > s = 1 > t = 1 - (a / b) > for i in range(_eulen): > b = _rem.pop() > a = _rem.pop() > s,t = t, s - (a/b)*t > > # show results: > print "gcd(%d,%d) = (%d)(%d) + (%d)(%d) = %d" % (a,b,a,s,b,t,a*s+b*t) > > # reset _eulen and _rem: >## _eulen = 0 > > ## Interestingly it is not necessary to reset :eulen, as it is set to 0 ## when st() is defined, and cannot be changed, because integers are ## immutable python objects ## the contrary is true for _rem, which as a list is a mutable python object *and* ## will be changed during the run of this version of your function. ## (This issue is a bit tricky) > _rem = [] > > else: # not finished. > > # we will need this information later: >## _eulen += 1 ## will be passed as argument (see below) > _rem.append(a) > _rem.append(b) > > # function calls itself: > st(b,r,_eulen+1) > > ## Here _rem need not be inserted as argument as it si the default value of this ## fourth parameter. I'll show you some more 'amendments in a follow up posting Regards, Gregor From volz at aifb.uni-karlsruhe.de Mon Feb 23 06:02:48 2004 From: volz at aifb.uni-karlsruhe.de (Raphael Volz) Date: Mon Feb 23 06:03:05 2004 Subject: [Tutor] unsubscribe In-Reply-To: <4039DD80.8030108@aon.at> Message-ID: <000901c3f9fc$93964700$718316ac@aifbeiche> unsubscribe > -----Urspr?ngliche Nachricht----- > Von: tutor-bounces@python.org > [mailto:tutor-bounces@python.org] Im Auftrag von Gregor Lingl > Gesendet: Montag, 23. Februar 2004 12:01 > An: alice > Cc: tutor@python.org > Betreff: Re: [Tutor] global variables & recursion > > > Hi Alice! (Hi Robin Hood?) > > alice schrieb: > > >I would like some advice. > > > > > I'll try. As your second problem, determioning s and t is a > generaliziation of the simplecomputation of gcd, I'll > concentrate on this. (Although > there > are 'famous' versions of euclids algorithm which are well > worth discussing. So if you are interested in it, feel fre > to ask more ...) > > >Is there a better way of doing this? > >Particularly I'm not sure if using global variables is a good idea. > > > > > Generally you should avoid using global variables, if it can > easily be done. > > ># Find integers s and t such that as + bt = gcd(a,b): > > > ># global variables (is this bad programming style?) > > > > > A standard way to do so is passing them as parameters with > default arguments. > > >## _eulen = 0 # recursion depth > >## _rem = [] # list of remainders > > > >def st(a,b,_eulen=0, _rem=[]): > > > >## global _eulen > >## global _rem > > > > # a should be bigger than b: > > if (b > a): > > a, b = b, a > > > > # find remainder: > > r = a % b > > > > if (r == 0): # finished > > > > # find s and t: > > s = 1 > > t = 1 - (a / b) > > for i in range(_eulen): > > b = _rem.pop() > > a = _rem.pop() > > s,t = t, s - (a/b)*t > > > > # show results: > > print "gcd(%d,%d) = (%d)(%d) + (%d)(%d) = %d" % > > (a,b,a,s,b,t,a*s+b*t) > > > > # reset _eulen and _rem: > >## _eulen = 0 > > > > > ## Interestingly it is not necessary to reset :eulen, as it > is set to 0 ## when st() is defined, and cannot be changed, > because integers are ## immutable python objects ## the > contrary is true for _rem, which as a list is a mutable python > object *and* > ## will be changed during the run of this version of your > function. ## (This issue is a bit tricky) > > > _rem = [] > > > > else: # not finished. > > > > # we will need this information later: > >## _eulen += 1 ## will be passed as argument (see below) > > _rem.append(a) > > _rem.append(b) > > > > # function calls itself: > > st(b,r,_eulen+1) > > > > > ## Here _rem need not be inserted as argument as it si the > default value > of this > ## fourth parameter. > > I'll show you some more 'amendments in a follow up posting > > Regards, Gregor > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From glingl at aon.at Mon Feb 23 06:45:40 2004 From: glingl at aon.at (Gregor Lingl) Date: Mon Feb 23 06:44:44 2004 Subject: [Tutor] global variables & recursion In-Reply-To: <200402231648.42994.RobinHood42@clickta.com> References: <200402231648.42994.RobinHood42@clickta.com> Message-ID: <4039E7E4.7000809@aon.at> Hi alice! After having had a quick lunch I don't have much time to complete my answer. There are a few points, which IMO make your code a bit more "pythonic". I'll explain them shortly and append the result (i. e. the code I arrived at, starting from yours): (1) replacing the for-loop by a while loop which runs until _rem is empty makes the _eulen variable obsolete (2) interstingly it is not necessary to change a and b if b < a. That's a point you should thoroughly think about (3) using list-concatenation instead of appending elements to a list produces (enlarged) copies instead of changing the list. so _rem remains [] and copies are passed to the recursive calls of st. (On the other hand: with your approach _rem seems to be restored by popping alone). So restoring with _rem=[] is not necessary. So I arrived at: # Find integers s and t such that as + bt = gcd(a,b): def st(a,b,_rem=[]): # find remainder: r = a % b if (r == 0): # finished # find s and t: s = 1 t = 1 - (a // b) while _rem: # means: while _eulen != []: b = _rem.pop() a = _rem.pop() s,t = t, s - (a//b)*t # show results: print "gcd(%d,%d) = (%d)(%d) + (%d)(%d) = %d" % (a,b,a,s,b,t,a*s+b*t) else: # not finished. # function calls itself: st(b,r,_rem+[a,b]) Regards, Gregor From shitizb at yahoo.com Mon Feb 23 09:01:24 2004 From: shitizb at yahoo.com (Shitiz Bansal) Date: Mon Feb 23 09:01:32 2004 Subject: [Tutor] Printing a PDF file Message-ID: <20040223140124.77255.qmail@web41504.mail.yahoo.com> Hi, Here is a simple code to print a word document programatically using python: from win32.client import Dispatch myWord = Dispatch('Word.Application myDoc=myWord.Documents.Add('filename') myDoc.PrintOut() myDoc.close() How do i make a similar program for printing a pdf doc (platform windows) please help shitiz --------------------------------- Do you Yahoo!? Yahoo! Mail SpamGuard - Read only the mail you want. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040223/81acc70b/attachment.html From jimbinford at hot.rr.com Mon Feb 23 09:34:00 2004 From: jimbinford at hot.rr.com (Ian Binford) Date: Mon Feb 23 09:34:05 2004 Subject: [Tutor] MySQL and Python? Message-ID: <001001c3fa1a$142f6550$3b2ec944@Binfords> Where can I look for MySQL support with Python? I'm coming off of PHP, and MySQL is my current language of choice :) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040223/907456c5/attachment.html From hcohen2 at comcast.net Mon Feb 23 09:21:33 2004 From: hcohen2 at comcast.net (hcohen2) Date: Mon Feb 23 10:25:30 2004 Subject: [Tutor] MySQL and Python? In-Reply-To: <001001c3fa1a$142f6550$3b2ec944@Binfords> References: <001001c3fa1a$142f6550$3b2ec944@Binfords> Message-ID: <403A0C6D.3020300@comcast.net> Ian Binford wrote: > Where can I look for MySQL support with Python? I'm coming off of > PHP, and MySQL is my current language of choice :) Ian, Start here: http://sourceforge.net/projects/mysql-python I really have no experience with MySQL, hence, I cannot be of further assistance. One question, however, what do you mean by " ... MySQL is my current language ... "? I thought it was a database and while there are different procedural coding of SQL to query, extract and store data I usually do not think of that as a language. Now Python, that's a programming language. Hope that is of some assistance. Also go to the python.org site and searrch further for more information. Herschel From helena_b2001 at yahoo.com Mon Feb 23 12:29:40 2004 From: helena_b2001 at yahoo.com (helena bhaska) Date: Mon Feb 23 12:29:45 2004 Subject: [Tutor] logging In-Reply-To: <20040213010550.51078.qmail@web20414.mail.yahoo.com> Message-ID: <20040223172940.21506.qmail@web20411.mail.yahoo.com> Hi, I was wondering if there is a way to limit the file size when I use python logging facility to write messages to a file? I would like to configure it so that the file does not exceen n number of lines. Thanks! __________________________________ Do you Yahoo!? Yahoo! Mail SpamGuard - Read only the mail you want. http://antispam.yahoo.com/tools From deadviannou at caramail.com Mon Feb 23 14:09:13 2004 From: deadviannou at caramail.com (Vianus le Fus ) Date: Mon Feb 23 13:09:21 2004 Subject: [Tutor] Socket connection refused Message-ID: <1077559753000847@lycos-europe.com> Hello, I'm a newbie to python so please don't be too hard with me :) I'm encountering problems using socket connections in my programs. My goal is to create a small chat program so I begin with the beginning : two really small apps, one for the server and one for the client. The server is here to listen to one port and to resend its own data to the client that's connected to the port. I have found two ways to test this : I compile the server with py2exe and launch it, then I can run the client either running the module under IDLE or compiling it with py2exe. And there's my problem : it works under IDLE (connection is set and the client receives its own data) but connection fails when using the exe client.... it says "error 10061 : Connection refused". I don't have any firewall nor other running programs that could block the socket, I really don't understand what's the difference using py2exe or not !! Please does someone know why the first method works and not the other ? ----------------------------------------------------- Serveur.py ----------------------------------------------------- import socket HOST = '127.0.0.1' PORT = 50007 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, PORT)) s.listen(1) conn, addr = s.accept() print 'Connected by', addr while 1: data = conn.recv(1024) if not data: break conn.send(data) conn.close() ----------------------------------------------------- Client.py ----------------------------------------------------- import errno import socket from Tkinter import * import tkMessageBox class Application(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.connected = 0 self.data = '' self.pack() self.createWidgets() def createWidgets(self): self.btn_quit = Button(self) self.btn_quit["text"] = "QUIT" self.btn_quit["fg"] = "red" self.btn_quit["command"] = self.end self.btn_quit.pack({"side": "left"}) self.btn_connect = Button(self) self.btn_connect["text"] = "Connect", self.btn_connect["command"] = self.connect self.btn_connect.pack({"side": "right"}) def connect(self) : try: self.s.connect(('127.0.0.1', 50007)) self.connected = 1 except socket.error, msg: tkMessageBox.showinfo(title='Connexion error', message='Can\'t connect \ to the server 127.0.0.1' + '\n' + str(errno.errorcode[msg[0]])) if self.connected == 1 : self.s.send('Hello, world') self.data = self.s.recv(1024) print 'Received', str(self.data) tkMessageBox.showinfo(title='Data received !!', message=str(self.data)) def end(self) : self.s.close() self.quit() # MAIN app = Application() app.mainloop() ----------------------------------------------------- Plus simple, plus fiable, plus rapide : d?couvrez le nouveau Caramail - http://www.caramail.lycos.fr From dyoo at hkn.eecs.berkeley.edu Mon Feb 23 13:44:51 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Feb 23 13:44:58 2004 Subject: [Tutor] unsubscribe In-Reply-To: <000901c3f9fc$93964700$718316ac@aifbeiche> Message-ID: <Pine.LNX.4.44.0402231042560.32753-100000@hkn.eecs.berkeley.edu> On Mon, 23 Feb 2004, Raphael Volz wrote: > unsubscribe Hi Raphael, You can unsubscribe from tutor by visiting that page that you used to subscribe to Tutor: http://mail.python.org/mailman/listinfo/tutor Go down to the bottom of that page: you should see an "Edit Options" form. We're using this system so that it's easier for you to unsubscribe yourself. But if you have problems unsubscribing still, please feel free to email 'tutor-admin@python.org', and the administrators can help take you off the list manually. Good luck to you. From dyoo at hkn.eecs.berkeley.edu Mon Feb 23 13:56:42 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Feb 23 13:56:50 2004 Subject: [Tutor] logging In-Reply-To: <20040223172940.21506.qmail@web20411.mail.yahoo.com> Message-ID: <Pine.LNX.4.44.0402231046370.32753-100000@hkn.eecs.berkeley.edu> On Mon, 23 Feb 2004, helena bhaska wrote: > I was wondering if there is a way to limit the file size when I use > python logging facility to write messages to a file? I would like to > configure it so that the file does not exceed n number of lines. Thanks! Hi Helena, Interesting question! Yes, it's possible to do this. The handler "RotatingFileHandler", for example, implements similar behavior: http://www.python.org/doc/lib/node285.html It might be possible to update RotatingFileHandler to count the number of lines rather than the number of bytes, but I'm not sure if it's worth the effort to do it exactly. *grin* The quick way to do this is to just set the handler of your logger to a RotatingFileHandler instance, and set the byte limit to 'n' times some constant, like 80 bytes. (Since the number of lines should be roughly proportional to the number of bytes, we'll only be off by about a constant factor.) Talk to you later! From dyoo at hkn.eecs.berkeley.edu Mon Feb 23 14:00:35 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Feb 23 14:00:41 2004 Subject: [Tutor] globbing and sorting and dating, oh my! (fwd) Message-ID: <Pine.LNX.4.44.0402231059400.32753-100000@hkn.eecs.berkeley.edu> Hi everyone, Followup on Kirk's question: looks like he solved it. *grin* ---------- Forwarded message ---------- Date: Sun, 22 Feb 2004 23:47:41 -0500 From: Kirk Bailey <idiot1@netzero.net> To: Danny Yoo <dyoo@hkn.eecs.berkeley.edu> Subject: Re: [Tutor] globbing and sorting and dating, oh my! I already solved it, and tripped across a function in time and another in os which did the work nicely. The technique of ADD A WEEK TO IT AND TOSS ANYTHING LARGER THAN 'NOW' IN THE BIT BUCKET did the trick. For an examination of the resulting script, try this link out: http://www.tinylist.org/whatsnew.txt Once I figured out time.time, it was easy. woaking through a list of all files in that dir (only pages for the wiki were there, simplifying my task immensely, a bit of luck I had the forsight to invent for myself at the beginning), I had the script: 1. read the age for each 2. toss out those too old 3. appending the acceptable ones to a new list 4. printing them in links to the reader program Then it closes the page printing out the page footer. 2 do loops. 2 lists. From nick at javacat.f2s.com Mon Feb 23 14:00:49 2004 From: nick at javacat.f2s.com (Nick Lunt) Date: Mon Feb 23 14:01:06 2004 Subject: [Tutor] Socket connection refused In-Reply-To: <1077559753000847@lycos-europe.com> References: <1077559753000847@lycos-europe.com> Message-ID: <20040223190049.76793c36@phatbox.local> Hi there, I'm also new at python but I copied/pasted your source code and it ran fine after I'd sorted out the formatting, but I suspect that was because of my email client. Anyway it runs on linux ok, the only issue I found was that when connecting, then clicking on the OK button on the 'Hello World' message I get the following TkDialog up "Can't connect to the server 127.0.0.1 EISCONN" Sorry I can't be of anymore help. Cheers Nick. On Mon, 23 Feb 2004 19:09:13 GMT "Vianus le Fus " <deadviannou@caramail.com> wrote: > Hello, > I'm a newbie to python so please don't be too hard with me :) > I'm encountering problems using socket connections in my programs. My > goal is to create a small chat program so I begin with the beginning : > two really small apps, one for the server and one for the client. The > server is here to listen to one port and to resend its own data to the > client that's connected to the port. > > I have found two ways to test this : I compile the server with py2exe > and launch it, then I can run the client either running the module > under IDLE or compiling it with py2exe. And there's my problem : it > works under IDLE (connection is set and the client receives its own > data) but connection fails when using the exe client.... it says > "error 10061 : Connection refused". I don't have any firewall nor > other running programs that could block the socket, I really don't > understand what's the difference using py2exe or not !! > > Please does someone know why the first method works and not the other > ? > > ----------------------------------------------------- > Serveur.py > ----------------------------------------------------- > import socket > > HOST = '127.0.0.1' > PORT = 50007 > > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > s.bind((HOST, PORT)) > s.listen(1) > conn, addr = s.accept() > print 'Connected by', addr > while 1: > data = conn.recv(1024) > if not data: break > conn.send(data) > conn.close() > > > > ----------------------------------------------------- > Client.py > ----------------------------------------------------- > import errno > import socket > from Tkinter import * > import tkMessageBox > > class Application(Frame): > def __init__(self, master=None): > Frame.__init__(self, master) > > self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > self.connected = 0 > self.data = '' > > self.pack() > self.createWidgets() > > > def createWidgets(self): > self.btn_quit = Button(self) > self.btn_quit["text"] = "QUIT" > self.btn_quit["fg"] = "red" > self.btn_quit["command"] = self.end > > self.btn_quit.pack({"side": "left"}) > > self.btn_connect = Button(self) > self.btn_connect["text"] = "Connect", > self.btn_connect["command"] = self.connect > > self.btn_connect.pack({"side": "right"}) > > > def connect(self) : > try: > self.s.connect(('127.0.0.1', 50007)) > self.connected = 1 > > except socket.error, msg: > tkMessageBox.showinfo(title='Connexion error', > message='Can\'t connect \ > to the server 127.0.0.1' + '\n' + str(errno.errorcode[msg[0]])) > > if self.connected == 1 : > self.s.send('Hello, world') > self.data = self.s.recv(1024) > print 'Received', str(self.data) > tkMessageBox.showinfo(title='Data received !!', > message=str(self.data)) > > > def end(self) : > self.s.close() > self.quit() > > > # MAIN > app = Application() > app.mainloop() > ----------------------------------------------------- > > Plus simple, plus fiable, plus rapide : d?couvrez le nouveau Caramail > - http://www.caramail.lycos.fr > > From deadviannou at caramail.com Mon Feb 23 15:11:55 2004 From: deadviannou at caramail.com (Djoumy . ) Date: Mon Feb 23 14:12:17 2004 Subject: [Tutor] Socket connection refused Message-ID: <1077563515006011@lycos-europe.com> ?Since it's only a small test program there are bugs for sure in my app. Anyway thanks for your help. If it works under your Linux, can the problem be coming from my Windows XP ? Djoum's ------- Message original -------? De: Nick Lunt <nick@javacat.f2s.com>? Date: Mon, 23 Feb 2004 19:00:49 +0000? Sujet: Re: [Tutor] Socket connection refused? Hi there, I'm also new at python but I copied/pasted your source code and it ran fine after I'd sorted out the formatting, but I suspect that was because of my email client. Anyway it runs on linux ok, the only issue I found was that when connecting, then clicking on the OK button on the 'Hello World' message I get the following TkDialog up "Can't connect to the server 127.0.0.1 EISCONN" Sorry I can't be of anymore help. Cheers Nick. On Mon, 23 Feb 2004 19:09:13 GMT "Vianus le Fus " wrote: > Hello, > I'm a newbie to python so please don't be too hard with me :) > I'm encountering problems using socket connections in my programs. My > goal is to create a small chat program so I begin with the beginning : > two really small apps, one for the server and one for the client. The > server is here to listen to one port and to resend its own data to the > client that's connected to the port. > > I have found two ways to test this : I compile the server with py2exe > and launch it, then I can run the client either running the module > under IDLE or compiling it with py2exe. And there's my problem : it > works under IDLE (connection is set and the client receives its own > data) but connection fails when using the exe client.... it says > "error 10061 : Connection refused". I don't have any firewall nor > other running programs that could block the socket, I really don't > understand what's the difference using py2exe or not !! > > Please does someone know why the first method works and not the other > ? > > ----------------------------------------------------- > Serveur.py > ----------------------------------------------------- > import socket > > HOST = '127.0.0.1' > PORT = 50007 > > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > s.bind((HOST, PORT)) > s.listen(1) > conn, addr = s.accept() > print 'Connected by', addr > while 1: > data = conn.recv(1024) > if not data: break > conn.send(data) > conn.close() > > > > ----------------------------------------------------- > Client.py > ----------------------------------------------------- > import errno > import socket > from Tkinter import * > import tkMessageBox > > class Application(Frame): > def __init__(self, master=None): > Frame.__init__(self, master) > > self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > self.connected = 0 > self.data = '' > > self.pack() > self.createWidgets() > > > def createWidgets(self): > self.btn_quit = Button(self) > self.btn_quit["text"] = "QUIT" > self.btn_quit["fg"] = "red" > self.btn_quit["command"] = self.end > > self.btn_quit.pack({"side": "left"}) > > self.btn_connect = Button(self) > self.btn_connect["text"] = "Connect", > self.btn_connect["command"] = self.connect > > self.btn_connect.pack({"side": "right"}) > > > def connect(self) : > try: > self.s.connect(('127.0.0.1', 50007)) > self.connected = 1 > > except socket.error, msg: > tkMessageBox.showinfo(title='Connexion error', > message='Can\'t connect \ > to the server 127.0.0.1' + '\n' + str(errno.errorcode[msg[0]])) > > if self.connected == 1 : > self.s.send('Hello, world') > self.data = self.s.recv(1024) > print 'Received', str(self.data) > tkMessageBox.showinfo(title='Data received !!', > message=str(self.data)) > > > def end(self) : > self.s.close() > self.quit() > > > # MAIN > app = Application() > app.mainloop() > ----------------------------------------------------- > > Plus simple, plus fiable, plus rapide : d?couvrez le nouveau Caramail > - http://www.caramail.lycos.fr > > _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor Plus simple, plus fiable, plus rapide : d?couvrez le nouveau Caramail - http://www.caramail.lycos.fr From nick at javacat.f2s.com Mon Feb 23 14:14:13 2004 From: nick at javacat.f2s.com (Nick Lunt) Date: Mon Feb 23 14:14:35 2004 Subject: [Tutor] Socket connection refused In-Reply-To: <20040223190049.76793c36@phatbox.local> References: <1077559753000847@lycos-europe.com> <20040223190049.76793c36@phatbox.local> Message-ID: <20040223191413.1a1d7813@phatbox.local> Oops, made an error there, I get the TkDialog error message when I've clicked on 'connect' 2 or more times. A quick google on EISCONN showed me that it is because the socket has to be closed again before another connection can be made to it. See here http://www.wlug.org.nz/EISCONN . I think you can change that behaviour with 'socketObject.listen(10)' for example, but don't take my word for that cos I tried it and while I could connect to it multiple times using telnet, only the first telnet session echoed back what I typed in. Hope that helps a bit Nick. On Mon, 23 Feb 2004 19:00:49 +0000 Nick Lunt <nick@javacat.f2s.com> wrote: > Hi there, > > I'm also new at python but I copied/pasted your source code and it ran > fine after I'd sorted out the formatting, but I suspect that was > because of my email client. > > Anyway it runs on linux ok, the only issue I found was that when > connecting, then clicking on the OK button on the 'Hello World' > message I get the following TkDialog up "Can't connect to the server > 127.0.0.1 EISCONN" > > Sorry I can't be of anymore help. > > Cheers > Nick. > > > On Mon, 23 Feb 2004 19:09:13 GMT "Vianus le Fus " > <deadviannou@caramail.com> wrote: > > > Hello, > > I'm a newbie to python so please don't be too hard with me :) > > I'm encountering problems using socket connections in my programs. > > My goal is to create a small chat program so I begin with the > > beginning : two really small apps, one for the server and one for > > the client. The server is here to listen to one port and to resend > > its own data to the client that's connected to the port. > > > > I have found two ways to test this : I compile the server with > > py2exe and launch it, then I can run the client either running the > > module under IDLE or compiling it with py2exe. And there's my > > problem : it works under IDLE (connection is set and the client > > receives its own data) but connection fails when using the exe > > client.... it says"error 10061 : Connection refused". I don't have > > any firewall nor other running programs that could block the socket, > > I really don't understand what's the difference using py2exe or not > > !! > > > > Please does someone know why the first method works and not the > > other? > > > > ----------------------------------------------------- > > Serveur.py > > ----------------------------------------------------- > > import socket > > > > HOST = '127.0.0.1' > > PORT = 50007 > > > > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > s.bind((HOST, PORT)) > > s.listen(1) > > conn, addr = s.accept() > > print 'Connected by', addr > > while 1: > > data = conn.recv(1024) > > if not data: break > > conn.send(data) > > conn.close() > > > > > > > > ----------------------------------------------------- > > Client.py > > ----------------------------------------------------- > > import errno > > import socket > > from Tkinter import * > > import tkMessageBox > > > > class Application(Frame): > > def __init__(self, master=None): > > Frame.__init__(self, master) > > > > self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > self.connected = 0 > > self.data = '' > > > > self.pack() > > self.createWidgets() > > > > > > def createWidgets(self): > > self.btn_quit = Button(self) > > self.btn_quit["text"] = "QUIT" > > self.btn_quit["fg"] = "red" > > self.btn_quit["command"] = self.end > > > > self.btn_quit.pack({"side": "left"}) > > > > self.btn_connect = Button(self) > > self.btn_connect["text"] = "Connect", > > self.btn_connect["command"] = self.connect > > > > self.btn_connect.pack({"side": "right"}) > > > > > > def connect(self) : > > try: > > self.s.connect(('127.0.0.1', 50007)) > > self.connected = 1 > > > > except socket.error, msg: > > tkMessageBox.showinfo(title='Connexion error', > > message='Can\'t connect \ > > to the server 127.0.0.1' + '\n' + str(errno.errorcode[msg[0]])) > > > > if self.connected == 1 : > > self.s.send('Hello, world') > > self.data = self.s.recv(1024) > > print 'Received', str(self.data) > > tkMessageBox.showinfo(title='Data received !!', > > message=str(self.data)) > > > > > > def end(self) : > > self.s.close() > > self.quit() > > > > > > # MAIN > > app = Application() > > app.mainloop() > > ----------------------------------------------------- > > > > Plus simple, plus fiable, plus rapide : d?couvrez le nouveau > > Caramail- http://www.caramail.lycos.fr > > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From nick at javacat.f2s.com Mon Feb 23 14:23:09 2004 From: nick at javacat.f2s.com (Nick Lunt) Date: Mon Feb 23 14:23:28 2004 Subject: [Tutor] Socket connection refused In-Reply-To: <1077563515006011@lycos-europe.com> References: <1077563515006011@lycos-europe.com> Message-ID: <20040223192309.73a0ce6a@phatbox.local> Error nr 10061 seems to indicate that there is too much load on the server, and the recommended fix is to increase the timeout, but that is when applied to SMTP/HTTP but I would expect it to be the same for all IP based servers. I have done the same server/client program as you a couple of weeks ago, I created it on linux, then emailed it to my work and ran it fine on my win2k box there, so I doubt it's a windows issue. I have had problems with py2exe on windows and linux tho even tho the programs were fine. I still haven't got my head around py2exe yet, I suspect it's more complicated than I think and Im too busy learning python to bother with it at the moment ;) Have you tried running the server and client from the windows command prompt ? It would be interesting to know how that goes. Cheers Nick. On Mon, 23 Feb 2004 20:11:55 GMT "Djoumy . " <deadviannou@caramail.com> wrote: > ?Since it's only a small test program there are bugs for sure in my > app. Anyway thanks for your help. If it works under your Linux, can > the problem be coming from my Windows XP ? > > Djoum's > > > ------- Message original -------? > De: Nick Lunt <nick@javacat.f2s.com>? > Date: Mon, 23 Feb 2004 19:00:49 +0000? > Sujet: Re: [Tutor] Socket connection refused? > > > Hi there, > > I'm also new at python but I copied/pasted your source code and it ran > fine after I'd sorted out the formatting, but I suspect that was > because of my email client. > > Anyway it runs on linux ok, the only issue I found was that when > connecting, then clicking on the OK button on the 'Hello World' > message I get the following TkDialog up "Can't connect to the server > 127.0.0.1 EISCONN" > > Sorry I can't be of anymore help. > > Cheers > Nick. > > > On Mon, 23 Feb 2004 19:09:13 GMT "Vianus le Fus " > wrote: > > > Hello, > > I'm a newbie to python so please don't be too hard with me :) > > I'm encountering problems using socket connections in my programs. > > My goal is to create a small chat program so I begin with the > > beginning : two really small apps, one for the server and one for > > the client. The server is here to listen to one port and to resend > > its own data to the client that's connected to the port. > > > > I have found two ways to test this : I compile the server with > > py2exe and launch it, then I can run the client either running the > > module under IDLE or compiling it with py2exe. And there's my > > problem : it works under IDLE (connection is set and the client > > receives its own data) but connection fails when using the exe > > client.... it says"error 10061 : Connection refused". I don't have > > any firewall nor other running programs that could block the socket, > > I really don't understand what's the difference using py2exe or not > > !! > > > > Please does someone know why the first method works and not the > > other? > > > > ----------------------------------------------------- > > Serveur.py > > ----------------------------------------------------- > > import socket > > > > HOST = '127.0.0.1' > > PORT = 50007 > > > > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > s.bind((HOST, PORT)) > > s.listen(1) > > conn, addr = s.accept() > > print 'Connected by', addr > > while 1: > > data = conn.recv(1024) > > if not data: break > > conn.send(data) > > conn.close() > > > > > > > > ----------------------------------------------------- > > Client.py > > ----------------------------------------------------- > > import errno > > import socket > > from Tkinter import * > > import tkMessageBox > > > > class Application(Frame): > > def __init__(self, master=None): > > Frame.__init__(self, master) > > > > self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > self.connected = 0 > > self.data = '' > > > > self.pack() > > self.createWidgets() > > > > > > def createWidgets(self): > > self.btn_quit = Button(self) > > self.btn_quit["text"] = "QUIT" > > self.btn_quit["fg"] = "red" > > self.btn_quit["command"] = self.end > > > > self.btn_quit.pack({"side": "left"}) > > > > self.btn_connect = Button(self) > > self.btn_connect["text"] = "Connect", > > self.btn_connect["command"] = self.connect > > > > self.btn_connect.pack({"side": "right"}) > > > > > > def connect(self) : > > try: > > self.s.connect(('127.0.0.1', 50007)) > > self.connected = 1 > > > > except socket.error, msg: > > tkMessageBox.showinfo(title='Connexion error', > > message='Can\'t connect \ > > to the server 127.0.0.1' + '\n' + str(errno.errorcode[msg[0]])) > > > > if self.connected == 1 : > > self.s.send('Hello, world') > > self.data = self.s.recv(1024) > > print 'Received', str(self.data) > > tkMessageBox.showinfo(title='Data received !!', > > message=str(self.data)) > > > > > > def end(self) : > > self.s.close() > > self.quit() > > > > > > # MAIN > > app = Application() > > app.mainloop() > > ----------------------------------------------------- > > > > Plus simple, plus fiable, plus rapide : d?couvrez le nouveau > > Caramail- http://www.caramail.lycos.fr > > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > Plus simple, plus fiable, plus rapide : d?couvrez le nouveau Caramail > - http://www.caramail.lycos.fr > > From carroll at tjc.com Mon Feb 23 14:38:36 2004 From: carroll at tjc.com (Terry Carroll) Date: Mon Feb 23 14:38:51 2004 Subject: [Tutor] formatting and pretty printing nested structures In-Reply-To: <8CBC0485-65CE-11D8-9523-003065555ABC@mac.com> Message-ID: <Pine.LNX.4.44.0402231135000.9608-100000@violet.rahul.net> On Mon, 23 Feb 2004, kevin parks wrote: > Hi. I have a list of lists. Inside the list are lists that are made up > of strings and floats. When i print the list it prints the floats in > the usual insane long wierdo format and i want to print them with > string formatting so that they are more readable, so i somehow have to > pick apart the nested items so that i can print: > > 0 ['C', 8.0, 8.0] > 1 ['C#', 8.0099999999999998, 8.0833349227905273] > > more like this: > > 0 ['C', 8.00, 8.000000] > 1 ['C#', 8.01, 8.083333] > > or even betterererer: > > 0 C 8.00 8.000000 > 1 C# 8.01 8.083333 Here's one approache; lining up the numbers is lefta s an exercise to the reader. :-) def printthelist(thelist, intformat="%d", floatformat="%.2f"): for entry in thelist: if isinstance(entry,list): printthelist(entry, intformat=intformat, floatformat=floatformat) else: try: entry+1 if repr(entry).isdigit(): print intformat % entry, else: print floatformat % entry, except TypeError: print entry, list0 = [0, ['C', 8.0, 8.0]] list1 = [1, ['C#', 8.0099999999999998, 8.0833349227905273]] printthelist(list0) print printthelist(list1) print gives: 0 C 8.00 8.00 1 C# 8.01 8.08 From deadviannou at caramail.com Mon Feb 23 15:50:15 2004 From: deadviannou at caramail.com (Djoumy . ) Date: Mon Feb 23 14:50:55 2004 Subject: [Tutor] Socket connection refused Message-ID: <1077565815002340@lycos-europe.com> ?I tried to launch the two apps from the windows command prompt but there's no changes at all. I also tried to increase the server's timeout with "s.settimeout(None)" but still there's no changes. This problem seems really odd to me, since I'd say it's coming from the py2exe compilation... maybe I got a wrong compilation option, I'm looking for informations about it but for now I'm lost :) Djoum's ------- Message original -------? De: Nick Lunt <nick@javacat.f2s.com>? Date: Mon, 23 Feb 2004 19:23:09 +0000? Sujet: Re: [Tutor] Socket connection refused? Error nr 10061 seems to indicate that there is too much load on the server, and the recommended fix is to increase the timeout, but that is when applied to SMTP/HTTP but I would expect it to be the same for all IP based servers. I have done the same server/client program as you a couple of weeks ago, I created it on linux, then emailed it to my work and ran it fine on my win2k box there, so I doubt it's a windows issue. I have had problems with py2exe on windows and linux tho even tho the programs were fine. I still haven't got my head around py2exe yet, I suspect it's more complicated than I think and Im too busy learning python to bother with it at the moment ;) Have you tried running the server and client from the windows command prompt ? It would be interesting to know how that goes. Cheers Nick. On Mon, 23 Feb 2004 20:11:55 GMT "Djoumy . " wrote: > ?Since it's only a small test program there are bugs for sure in my > app. Anyway thanks for your help. If it works under your Linux, can > the problem be coming from my Windows XP ? > > Djoum's > > > ------- Message original -------? > De: Nick Lunt ? > Date: Mon, 23 Feb 2004 19:00:49 +0000? > Sujet: Re: [Tutor] Socket connection refused? > > > Hi there, > > I'm also new at python but I copied/pasted your source code and it ran > fine after I'd sorted out the formatting, but I suspect that was > because of my email client. > > Anyway it runs on linux ok, the only issue I found was that when > connecting, then clicking on the OK button on the 'Hello World' > message I get the following TkDialog up "Can't connect to the server > 127.0.0.1 EISCONN" > > Sorry I can't be of anymore help. > > Cheers > Nick. > > > On Mon, 23 Feb 2004 19:09:13 GMT "Vianus le Fus " > wrote: > > > Hello, > > I'm a newbie to python so please don't be too hard with me :) > > I'm encountering problems using socket connections in my programs. > > My goal is to create a small chat program so I begin with the > > beginning : two really small apps, one for the server and one for > > the client. The server is here to listen to one port and to resend > > its own data to the client that's connected to the port. > > > > I have found two ways to test this : I compile the server with > > py2exe and launch it, then I can run the client either running the > > module under IDLE or compiling it with py2exe. And there's my > > problem : it works under IDLE (connection is set and the client > > receives its own data) but connection fails when using the exe > > client.... it says"error 10061 : Connection refused". I don't have > > any firewall nor other running programs that could block the socket, > > I really don't understand what's the difference using py2exe or not > > !! > > > > Please does someone know why the first method works and not the > > other? > > > > ----------------------------------------------------- > > Serveur.py > > ----------------------------------------------------- > > import socket > > > > HOST = '127.0.0.1' > > PORT = 50007 > > > > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > s.bind((HOST, PORT)) > > s.listen(1) > > conn, addr = s.accept() > > print 'Connected by', addr > > while 1: > > data = conn.recv(1024) > > if not data: break > > conn.send(data) > > conn.close() > > > > > > > > ----------------------------------------------------- > > Client.py > > ----------------------------------------------------- > > import errno > > import socket > > from Tkinter import * > > import tkMessageBox > > > > class Application(Frame): > > def __init__(self, master=None): > > Frame.__init__(self, master) > > > > self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > self.connected = 0 > > self.data = '' > > > > self.pack() > > self.createWidgets() > > > > > > def createWidgets(self): > > self.btn_quit = Button(self) > > self.btn_quit["text"] = "QUIT" > > self.btn_quit["fg"] = "red" > > self.btn_quit["command"] = self.end > > > > self.btn_quit.pack({"side": "left"}) > > > > self.btn_connect = Button(self) > > self.btn_connect["text"] = "Connect", > > self.btn_connect["command"] = self.connect > > > > self.btn_connect.pack({"side": "right"}) > > > > > > def connect(self) : > > try: > > self.s.connect(('127.0.0.1', 50007)) > > self.connected = 1 > > > > except socket.error, msg: > > tkMessageBox.showinfo(title='Connexion error', > > message='Can\'t connect \ > > to the server 127.0.0.1' + '\n' + str(errno.errorcode[msg[0]])) > > > > if self.connected == 1 : > > self.s.send('Hello, world') > > self.data = self.s.recv(1024) > > print 'Received', str(self.data) > > tkMessageBox.showinfo(title='Data received !!', > > message=str(self.data)) > > > > > > def end(self) : > > self.s.close() > > self.quit() > > > > > > # MAIN > > app = Application() > > app.mainloop() > > ----------------------------------------------------- > > > > Plus simple, plus fiable, plus rapide : d?couvrez le nouveau > > Caramail- http://www.caramail.lycos.fr > > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > Plus simple, plus fiable, plus rapide : d?couvrez le nouveau Caramail > - http://www.caramail.lycos.fr > > _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor Plus simple, plus fiable, plus rapide : d?couvrez le nouveau Caramail - http://www.caramail.lycos.fr From nick at javacat.f2s.com Mon Feb 23 15:20:31 2004 From: nick at javacat.f2s.com (Nick Lunt) Date: Mon Feb 23 15:20:54 2004 Subject: [Tutor] Socket connection refused In-Reply-To: <1077565815002340@lycos-europe.com> References: <1077565815002340@lycos-europe.com> Message-ID: <20040223202031.621eae52@phatbox.local> Hi again, I just downloaded python on the gf's winxp pc and ran your progams on there. Ran exactly the same as on the linux box :) Im gonna attach your files in this email for you to run so we can rule out formatting issues ;) Just run fserver.py from one dos box and fclient.py from another dos box and let us know what happens. Cheers Nick. On Mon, 23 Feb 2004 20:50:15 GMT "Djoumy . " <deadviannou@caramail.com> wrote: > ?I tried to launch the two apps from the windows command prompt but > there's no changes at all. I also tried to increase the server's > timeout with "s.settimeout(None)" but still there's no changes. This > problem seems really odd to me, since I'd say it's coming from the > py2exe compilation... maybe I got a wrong compilation option, I'm > looking for informations about it but for now I'm lost :) > > > Djoum's > > > ------- Message original -------? > De: Nick Lunt <nick@javacat.f2s.com>? > Date: Mon, 23 Feb 2004 19:23:09 +0000? > Sujet: Re: [Tutor] Socket connection refused? > > > Error nr 10061 seems to indicate that there is too much load on the > server, and the recommended fix is to increase the timeout, but that > is when applied to SMTP/HTTP but I would expect it to be the same for > all IP based servers. > > I have done the same server/client program as you a couple of weeks > ago, I created it on linux, then emailed it to my work and ran it fine > on my win2k box there, so I doubt it's a windows issue. > > I have had problems with py2exe on windows and linux tho even tho the > programs were fine. I still haven't got my head around py2exe yet, I > suspect it's more complicated than I think and Im too busy learning > python to bother with it at the moment ;) > > Have you tried running the server and client from the windows command > prompt ? It would be interesting to know how that goes. > > Cheers > Nick. > > > On Mon, 23 Feb 2004 20:11:55 GMT "Djoumy . " > wrote: > > > ?Since it's only a small test program there are bugs for sure in my > > app. Anyway thanks for your help. If it works under your Linux, can > > the problem be coming from my Windows XP ? > > > > Djoum's > > > > > > ------- Message original -------? > > De: Nick Lunt ? > > Date: Mon, 23 Feb 2004 19:00:49 +0000? > > Sujet: Re: [Tutor] Socket connection refused? > > > > > > Hi there, > > > > I'm also new at python but I copied/pasted your source code and it > > ran fine after I'd sorted out the formatting, but I suspect that was > > because of my email client. > > > > Anyway it runs on linux ok, the only issue I found was that when > > connecting, then clicking on the OK button on the 'Hello World' > > message I get the following TkDialog up "Can't connect to the server > > 127.0.0.1 EISCONN" > > > > Sorry I can't be of anymore help. > > > > Cheers > > Nick. > > > > > > On Mon, 23 Feb 2004 19:09:13 GMT "Vianus le Fus " > > wrote: > > > > > Hello, > > > I'm a newbie to python so please don't be too hard with me :) > > > I'm encountering problems using socket connections in my programs. > > > My goal is to create a small chat program so I begin with the > > > beginning : two really small apps, one for the server and one for > > > the client. The server is here to listen to one port and to resend > > > its own data to the client that's connected to the port. > > > > > > I have found two ways to test this : I compile the server with > > > py2exe and launch it, then I can run the client either running the > > > module under IDLE or compiling it with py2exe. And there's my > > > problem : it works under IDLE (connection is set and the client > > > receives its own data) but connection fails when using the exe > > > client.... it says"error 10061 : Connection refused". I don't have > > > any firewall nor other running programs that could block the > > > socket, I really don't understand what's the difference using > > > py2exe or not!! > > > > > > Please does someone know why the first method works and not the > > > other? > > > > > > ----------------------------------------------------- > > > Serveur.py > > > ----------------------------------------------------- > > > import socket > > > > > > HOST = '127.0.0.1' > > > PORT = 50007 > > > > > > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > > s.bind((HOST, PORT)) > > > s.listen(1) > > > conn, addr = s.accept() > > > print 'Connected by', addr > > > while 1: > > > data = conn.recv(1024) > > > if not data: break > > > conn.send(data) > > > conn.close() > > > > > > > > > > > > ----------------------------------------------------- > > > Client.py > > > ----------------------------------------------------- > > > import errno > > > import socket > > > from Tkinter import * > > > import tkMessageBox > > > > > > class Application(Frame): > > > def __init__(self, master=None): > > > Frame.__init__(self, master) > > > > > > self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > > self.connected = 0 > > > self.data = '' > > > > > > self.pack() > > > self.createWidgets() > > > > > > > > > def createWidgets(self): > > > self.btn_quit = Button(self) > > > self.btn_quit["text"] = "QUIT" > > > self.btn_quit["fg"] = "red" > > > self.btn_quit["command"] = self.end > > > > > > self.btn_quit.pack({"side": "left"}) > > > > > > self.btn_connect = Button(self) > > > self.btn_connect["text"] = "Connect", > > > self.btn_connect["command"] = self.connect > > > > > > self.btn_connect.pack({"side": "right"}) > > > > > > > > > def connect(self) : > > > try: > > > self.s.connect(('127.0.0.1', 50007)) > > > self.connected = 1 > > > > > > except socket.error, msg: > > > tkMessageBox.showinfo(title='Connexion error', > > > message='Can\'t connect \ > > > to the server 127.0.0.1' + '\n' + str(errno.errorcode[msg[0]])) > > > > > > if self.connected == 1 : > > > self.s.send('Hello, world') > > > self.data = self.s.recv(1024) > > > print 'Received', str(self.data) > > > tkMessageBox.showinfo(title='Data received !!', > > > message=str(self.data)) > > > > > > > > > def end(self) : > > > self.s.close() > > > self.quit() > > > > > > > > > # MAIN > > > app = Application() > > > app.mainloop() > > > ----------------------------------------------------- > > > > > > Plus simple, plus fiable, plus rapide : d?couvrez le nouveau > > > Caramail- http://www.caramail.lycos.fr > > > > > > > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > Plus simple, plus fiable, plus rapide : d?couvrez le nouveau > > Caramail- http://www.caramail.lycos.fr > > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > Plus simple, plus fiable, plus rapide : d?couvrez le nouveau Caramail > - http://www.caramail.lycos.fr > > -------------- next part -------------- A non-text attachment was scrubbed... Name: fclient.py Type: application/octet-stream Size: 1324 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20040223/563c0a19/fclient.obj -------------- next part -------------- A non-text attachment was scrubbed... Name: fserver.py Type: application/octet-stream Size: 299 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20040223/563c0a19/fserver.obj From marilyn at deliberate.com Mon Feb 23 16:46:39 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Mon Feb 23 16:46:47 2004 Subject: [Tutor] pseudo-private but protected? Message-ID: <Pine.LNX.4.44.0402231346000.11161-100000@Kuna> Hello Tutors, I think I get the pseudo-private name-mangling device. Are there any conventions or devices for 'pseudo-protected' attributes and methods in Python? These are accessible by members of the hierarchy, but not outside. Thank you. Marilyn From alan.gauld at blueyonder.co.uk Mon Feb 23 17:06:05 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Mon Feb 23 17:05:31 2004 Subject: [Tutor] global variables & recursion References: <200402231648.42994.RobinHood42@clickta.com> Message-ID: <005101c3fa59$3b7d3300$6401a8c0@xp> > Particularly I'm not sure if using global variables is a good idea. Its hardly ever a good idea. Much better to pass them in as arguments to the function > def gcd(a,b): > ... No probs there > # global variables (is this bad programming style?) Usually > _eulen = 0 # recursion depth > _rem = [] # list of remainders > > def st(a,b): Change to: def st(a,b,c,d): eulen = c rem = d # a should be bigger than b: if (b > a): a, b = b, a # find remainder: r = a % b if (r == 0): # finished # find s and t: s = 1 t = 1 - (a / b) for i in range(eulen): b = rem.pop() a = rem.pop() s,t = t, s - (a/b)*t # show results: print "gcd(%d,%d) = (%d)(%d) + (%d)(%d) = %d" % (a,b,a,s,b,t,a*s+b*t) # reset eulen and rem: eulen = 0 rem = [] else: # not finished. # we will need this information later: eulen += 1 rem.append(a) rem.append(b) # function calls itself: st(b,r,eulen,rem) That uses the same algorithm but avoids the global variables by simply passing them in as arguments. Now as to whether the basic algorithm can be improved, and I think it can, I'll leave to someone else, like Danny - who seems to particularly enjoy these little mathematical games... :-) Alan G. From alan.gauld at blueyonder.co.uk Mon Feb 23 17:11:13 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Mon Feb 23 17:10:45 2004 Subject: [Tutor] global variables & recursion References: <200402231648.42994.RobinHood42@clickta.com> <4039DD80.8030108@aon.at> Message-ID: <005601c3fa59$f3469b70$6401a8c0@xp> > > # function calls itself: > > st(b,r,_eulen+1) > > > > > ## Here _rem need not be inserted as argument as it si the default value > of this fourth parameter. While that's true I personally wouldn't advise leaving out _rem since it makes the code more obscure and relies on a fairly arcane bit of Python black magic. Recursive functions are notoriously hard to maintain anyway, and by relying on the persistent definition of a mutable default argument you make the problem even harder. All for the sake of saving a comma and 4 characters.... Alan G. From sandip at linux-delhi.org Mon Feb 23 16:54:55 2004 From: sandip at linux-delhi.org (Sandip Bhattacharya) Date: Mon Feb 23 17:11:06 2004 Subject: [Tutor] Re: Printing a PDF file In-Reply-To: <20040223140124.77255.qmail@web41504.mail.yahoo.com> References: <20040223140124.77255.qmail@web41504.mail.yahoo.com> Message-ID: <ge9qg1-edl.ln1@pluto.home> Shitiz Bansal wrote: > Hi, > Here is a simple code to print a word document programatically using python: > > from win32.client import Dispatch > myWord = Dispatch('Word.Application > myDoc=myWord.Documents.Add('filename') > myDoc.PrintOut() > myDoc.close() > > How do i make a similar program for printing a pdf doc (platform windows) > please help http://aspn.activestate.com/ASPN/docs/ActivePython/2.3/PyWin32/html/com/win32com/HTML/QuickStartClientCom.html Use an object browser to find out the name of the COM object corresponding to the Acrobat Reader app. Use that name instead of "Word.Application" in the code above. - Sandip -- Sandip Bhattacharya sandip (at) puroga.com Puroga Technologies Pvt. Ltd. Work: http://www.puroga.com Home: http://www.sandipb.net GPG: 51A4 6C57 4BC6 8C82 6A65 AE78 B1A1 2280 A129 0FF3 From alan.gauld at blueyonder.co.uk Mon Feb 23 17:18:20 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Mon Feb 23 17:17:48 2004 Subject: [Tutor] Socket connection refused References: <1077559753000847@lycos-europe.com> Message-ID: <006f01c3fa5a$f180da20$6401a8c0@xp> > I have found two ways to test this : I compile the server with > py2exe and launch it, then I can run the client > either running the module under IDLE or compiling it with py2exe. I strongly recommend that you do NOT use py2exe until you get your program working. One thing at a time. Its also much faster to develop the program if you don;t have to go through the py2exe stage every time yopu make a change! Just run your client and server from a pair of command prompt windows. Use Start-Run and enter "COMMAND" to start a command prompt (aka DOS box). Do it twice to get two. In one box start your client by typing: C:\>python client.py And in the other start your server C:\>python server.py (Actually its usually better to start the server first!) Now you should see the prompts and output of each program in its own box. And having just seen the code I notice its a Tkinter client so you only need one DOS box for the server, you can start the client just by double clicking in explorer... HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From glingl at aon.at Mon Feb 23 17:28:22 2004 From: glingl at aon.at (Gregor Lingl) Date: Mon Feb 23 17:27:27 2004 Subject: [Tutor] global variables & recursion In-Reply-To: <005601c3fa59$f3469b70$6401a8c0@xp> References: <200402231648.42994.RobinHood42@clickta.com> <4039DD80.8030108@aon.at> <005601c3fa59$f3469b70$6401a8c0@xp> Message-ID: <403A7E86.8020102@aon.at> Alan Gauld schrieb: >>> # function calls itself: >>> st(b,r,_eulen+1) >>> >>> >>> >>> >>## Here _rem need not be inserted as argument as it si the default >> >> >value > > >>of this fourth parameter. >> >> > >While that's true I personally wouldn't advise leaving out _rem since >it makes the code more obscure and relies on a fairly arcane bit of >Python black magic. Recursive functions are notoriously hard to >maintain >anyway, and by relying on the persistent definition of a mutable >default >argument you make the problem even harder. All for the sake of saving >a >comma and 4 characters.... > > d'accord! But I'd destictively prefer my second solution, which uses solely the list _rem, because it does exactly what one does, when one solves this diophantine equation by hand, namely reversing the euclidean algorithm. Gregor >Alan G. > > > > > From alan.gauld at blueyonder.co.uk Mon Feb 23 17:28:38 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Mon Feb 23 17:28:02 2004 Subject: [Tutor] pseudo-private but protected? References: <Pine.LNX.4.44.0402231346000.11161-100000@Kuna> Message-ID: <009701c3fa5c$6212f290$6401a8c0@xp> > I think I get the pseudo-private name-mangling device. > > Are there any conventions or devices for 'pseudo-protected' attributes > and methods in Python? As a matter of interest, why do you think such a thing would be useful? > These are accessible by members of the hierarchy, but not outside. That's one definition of protected, as used in Java and C++. It's not a universal definition - Delphi for example takes another approach. The "protected method" style of OO programming is best used as a form of protection for the programmer when dealing with statically typed languages with function overloading based on typed parameters. It basically provides a means of simplifying the public interface while allowing access to multiple typed versions of that interface. Since Python does not use that mechanism, protected methods are somewhat irrelevant. Which is why I ask why you thought you might want them? Alan G. From marilyn at deliberate.com Mon Feb 23 18:21:39 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Mon Feb 23 18:21:46 2004 Subject: [Tutor] pseudo-private but protected? In-Reply-To: <009701c3fa5c$6212f290$6401a8c0@xp> Message-ID: <Pine.LNX.4.44.0402231511460.11161-100000@Kuna> On Mon, 23 Feb 2004, Alan Gauld wrote: Thank you! > > I think I get the pseudo-private name-mangling device. > > > > Are there any conventions or devices for 'pseudo-protected' > attributes > > and methods in Python? > > As a matter of interest, why do you think such a thing would be > useful? Oh. I don't! I just anticipate C++ people to ask the question and want to be sure the answer is that it is not supported. Or, I guess it could be useful if a (possibly virtual) base class had base.set_name(), and its sub_classes are expected to call base.set_name() in their sub_class.set_name() methods but we don't want the base.set_name() method to be available outside the class. > > > These are accessible by members of the hierarchy, but not outside. > > That's one definition of protected, as used in Java and C++. > It's not a universal definition - Delphi for example takes another > approach. The "protected method" style of OO programming is best > used as a form of protection for the programmer when dealing with > statically typed languages with function overloading based on > typed parameters. It basically provides a means of simplifying I guess this isn't my example. > the public interface while allowing access to multiple typed > versions of that interface. Since Python does not use that mechanism, > protected methods are somewhat irrelevant. Oh. > > Which is why I ask why you thought you might want them? Does my example make my question make sense? Marilyn > > Alan G. > > -- From marilyn at deliberate.com Mon Feb 23 18:26:53 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Mon Feb 23 18:26:58 2004 Subject: [Tutor] pseudo-private but protected? In-Reply-To: <Pine.LNX.4.44.0402231511460.11161-100000@Kuna> Message-ID: <Pine.LNX.4.44.0402231526110.11161-100000@Kuna> Sorry, I skipped an important word: On Mon, 23 Feb 2004, Marilyn Davis wrote: > > On Mon, 23 Feb 2004, Alan Gauld wrote: > > Thank you! > > > > I think I get the pseudo-private name-mangling device. > > > > > > Are there any conventions or devices for 'pseudo-protected' > > attributes > > > and methods in Python? > > > > As a matter of interest, why do you think such a thing would be > > useful? > > Oh. I don't! I just anticipate C++ people to ask the question and > want to be sure the answer is that it is not supported. > > Or, I guess it could be useful if a (possibly virtual) base class had > base.set_name(), and its sub_classes are expected to call > base.set_name() in their sub_class.set_name() methods but we don't > want the base.set_name() method to be available outside the class. ... outside the class *hierarchy*. > > > > > > These are accessible by members of the hierarchy, but not outside. > > > > That's one definition of protected, as used in Java and C++. > > It's not a universal definition - Delphi for example takes another > > approach. The "protected method" style of OO programming is best > > used as a form of protection for the programmer when dealing with > > statically typed languages with function overloading based on > > typed parameters. It basically provides a means of simplifying > > I guess this isn't my example. > > > the public interface while allowing access to multiple typed > > versions of that interface. Since Python does not use that mechanism, > > protected methods are somewhat irrelevant. > > Oh. > > > > > Which is why I ask why you thought you might want them? > > Does my example make my question make sense? > > Marilyn > > > > > Alan G. > > > > > > -- From sigurd at 12move.de Mon Feb 23 18:41:33 2004 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Mon Feb 23 18:46:51 2004 Subject: [Tutor] global variables & recursion In-Reply-To: <403A7E86.8020102@aon.at> (Gregor Lingl's message of "Mon, 23 Feb 2004 23:28:22 +0100") References: <200402231648.42994.RobinHood42@clickta.com> <4039DD80.8030108@aon.at> <005601c3fa59$f3469b70$6401a8c0@xp> <403A7E86.8020102@aon.at> Message-ID: <m3y8qte5k0.fsf@hamster.pflaesterer.de> On 23 Feb 2004, Gregor Lingl <- glingl@aon.at wrote: > d'accord! > But I'd destictively prefer my second solution, which uses solely the > list _rem, because it > does exactly what one does, when one solves this diophantine equation > by hand, > namely reversing the euclidean algorithm. > Gregor ACK. After having looked at your second solution I tried a solution which makes it IMO clearer how s and t are found (in the original code it was a bit hidden IMO). def gcd (a, b): a, b = abs(a), abs(b) rem = [] while b > 0: rem.append((a,b)) a, b = b, a%b return a, rem def st (a, b): gc, rem = gcd(a, b) rem.reverse() s = t = 1 for a, b in rem: s, t = t, s - (a//b)*t return gc, (a, s), (b, t) The gcd function is nearly the standard solution (only the rem[] list is additional). The st() function then uses that function to compute s and t. Recursion is a very useful technique but in Python sadly not very performant (what about Stackless in that regard?). That should be told anyone who uses recursive algorithms so they are rewritten iteratively (if possible). Karl -- Please do *not* send copies of replies to me. I read the list From marilyn at deliberate.com Mon Feb 23 22:12:37 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Mon Feb 23 22:12:42 2004 Subject: [Tutor] generators and classes Message-ID: <Pine.LNX.4.44.0402231911220.11161-100000@Kuna> Hello again, I wrote this little program to demonstrate a generator: #! /usr/bin/python2.2 '''Function to generate random numbers without repetition. Demonstrates generators and the 'yield' keyword.''' from __future__ import generators import random def unique(bot, over_top): '''Generator to deliver randomly chosen values from bot to over_top - 1, delivering each value once only.''' taken = [0] * (over_top - bot) while (1): give = random.randrange(bot, over_top) if not taken[give - bot]: taken[give - bot] = 1 yield give def list_unique(bot, over_top): '''Returns a list of the generated numbers''' gen = unique(bot, over_top) return [gen.next() for i in range(bot, over_top)] if __name__ == '__main__': print '(0,5) = ', list_unique(0,5) print '(10,21) = ', list_unique(10,21) ############################# # OUTPUT: # bash-2.05a$ ./unique.py # (0,5) = [2, 3, 1, 0, 4] # (10,21) = [17, 10, 18, 20, 19, 15, 11, 13, 12, 16, 14] # bash-2.05a$ ----- But now that I'm preparing to teach OO, I want to do the class equivalent, which turns out like this: #! /usr/bin/env python2.2 import random class NumberHat: '''Generator to deliver randomly chosen values from bot to over_top - 1, delivering each value once only.''' def __init__(self, bot, over_top): self.bot = bot self.over_top = over_top self.taken = [0] * (over_top - bot) def take(self): while 1: give = random.randrange(self.bot, self.over_top) if not self.taken[give - self.bot]: self.taken[give - self.bot] = 1 return give if __name__ == '__main__': hat = NumberHat(0,10) for i in range(10): print hat.take() ############################################################ # OUTPUT: # bash-2.05a$ ./numberhat.py # 1 # 5 # 6 # 9 # 3 # 7 # 0 # 8 # 2 # 4 # bash-2.05a$ --- But there's no generator in it. Is this natural? Or is there some other thought I should be thinking? Thank you again and again. Marilyn From pythontutor at venix.com Tue Feb 24 00:43:30 2004 From: pythontutor at venix.com (Lloyd Kvam) Date: Tue Feb 24 00:44:08 2004 Subject: [Tutor] generators and classes In-Reply-To: <Pine.LNX.4.44.0402231911220.11161-100000@Kuna> References: <Pine.LNX.4.44.0402231911220.11161-100000@Kuna> Message-ID: <403AE482.50300@venix.com> In the first example, you call list_unique which handles the looping, calls the generator, and returns a list. The class example puts the looping in the caller and never builds a list. Put unique and list_unique methods into the class and I think it will work more like the first example. Marilyn Davis wrote: > Hello again, > > I wrote this little program to demonstrate a generator: > > #! /usr/bin/python2.2 > '''Function to generate random numbers without repetition. > Demonstrates generators and the 'yield' keyword.''' > > from __future__ import generators > import random > > def unique(bot, over_top): > '''Generator to deliver randomly chosen values from bot > to over_top - 1, delivering each value once only.''' > taken = [0] * (over_top - bot) > while (1): > give = random.randrange(bot, over_top) > if not taken[give - bot]: > taken[give - bot] = 1 > yield give > > def list_unique(bot, over_top): > '''Returns a list of the generated numbers''' > gen = unique(bot, over_top) > return [gen.next() for i in range(bot, over_top)] > > if __name__ == '__main__': > print '(0,5) = ', list_unique(0,5) > print '(10,21) = ', list_unique(10,21) > > ############################# > # OUTPUT: > # bash-2.05a$ ./unique.py > # (0,5) = [2, 3, 1, 0, 4] > # (10,21) = [17, 10, 18, 20, 19, 15, 11, 13, 12, 16, 14] > # bash-2.05a$ > > ----- > > But now that I'm preparing to teach OO, I want to do the class > equivalent, which turns out like this: > > #! /usr/bin/env python2.2 > > import random > > class NumberHat: > '''Generator to deliver randomly chosen values from bot > to over_top - 1, delivering each value once only.''' > def __init__(self, bot, over_top): > self.bot = bot > self.over_top = over_top > self.taken = [0] * (over_top - bot) > > def take(self): > while 1: > give = random.randrange(self.bot, self.over_top) > if not self.taken[give - self.bot]: > self.taken[give - self.bot] = 1 > return give > > if __name__ == '__main__': > hat = NumberHat(0,10) > for i in range(10): > print hat.take() > > ############################################################ > # OUTPUT: > # bash-2.05a$ ./numberhat.py > # 1 > # 5 > # 6 > # 9 > # 3 > # 7 > # 0 > # 8 > # 2 > # 4 > # bash-2.05a$ > > --- > > But there's no generator in it. Is this natural? Or is there > some other thought I should be thinking? > > Thank you again and again. > > Marilyn > > > _______________________________________________ > 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 marilyn at deliberate.com Tue Feb 24 02:54:33 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Tue Feb 24 02:54:38 2004 Subject: [Tutor] generators and classes In-Reply-To: <403AE482.50300@venix.com> Message-ID: <Pine.LNX.4.44.0402232319520.11161-100000@Kuna> Thank you for this. On Tue, 24 Feb 2004, Lloyd Kvam wrote: > In the first example, you call list_unique which handles the > looping, calls the generator, and returns a list. The class example > puts the looping in the caller and never builds a list. Put unique > and list_unique methods into the class and I think it will work more > like the first example. I'm just thinking that maybe the generator facility doesn't make sense in a class structure --> because the initializing part of the generator function belongs in __init__ and then you want the yield to be in another function because __init__ isn't allowed to return anything. So, you already have two functions with shared scope so you might as well return, skip the next(), and keep things simple. I tried to do what you suggest and it gets clumsy (but it works!). Maybe you intended something different? #! /usr/bin/python2.2 ''' Demonstrates generators and the 'yield' keyword in the context of a class structure.''' from __future__ import generators import random class Scrambler: '''Generator to deliver randomly chosen values from bot to over_top - 1, delivering each value once only. To collect the numbers, you make an object and call: object.take.next()''' def __init__(self, bot, over_top): self.bot = bot self.over_top = over_top self.taken = [0] * (over_top - bot) self.take = self.dummy() def dummy(self): while 1: give = random.randrange(self.bot, self.over_top) if not self.taken[give - self.bot]: self.taken[give - self.bot] = 1 yield give if __name__ == '__main__': scram = Scrambler(0,10) for i in range(10): print scram.take.next() ############################# # OUTPUT: # bash-2.05a$ ./scrambler.py # 3 # 4 # 8 # 2 # 7 # 1 # 6 # 0 # 9 # 5 # bash-2.05a$ ---- > > Marilyn Davis wrote: > > > Hello again, > > > > I wrote this little program to demonstrate a generator: > > > > #! /usr/bin/python2.2 > > '''Function to generate random numbers without repetition. > > Demonstrates generators and the 'yield' keyword.''' > > > > from __future__ import generators > > import random > > > > def unique(bot, over_top): > > '''Generator to deliver randomly chosen values from bot > > to over_top - 1, delivering each value once only.''' > > taken = [0] * (over_top - bot) > > while (1): > > give = random.randrange(bot, over_top) > > if not taken[give - bot]: > > taken[give - bot] = 1 > > yield give > > > > def list_unique(bot, over_top): > > '''Returns a list of the generated numbers''' > > gen = unique(bot, over_top) > > return [gen.next() for i in range(bot, over_top)] > > > > if __name__ == '__main__': > > print '(0,5) = ', list_unique(0,5) > > print '(10,21) = ', list_unique(10,21) > > > > ############################# > > # OUTPUT: > > # bash-2.05a$ ./unique.py > > # (0,5) = [2, 3, 1, 0, 4] > > # (10,21) = [17, 10, 18, 20, 19, 15, 11, 13, 12, 16, 14] > > # bash-2.05a$ > > > > ----- > > > > But now that I'm preparing to teach OO, I want to do the class > > equivalent, which turns out like this: > > > > #! /usr/bin/env python2.2 > > > > import random > > > > class NumberHat: > > '''Generator to deliver randomly chosen values from bot > > to over_top - 1, delivering each value once only.''' > > def __init__(self, bot, over_top): > > self.bot = bot > > self.over_top = over_top > > self.taken = [0] * (over_top - bot) > > > > def take(self): > > while 1: > > give = random.randrange(self.bot, self.over_top) > > if not self.taken[give - self.bot]: > > self.taken[give - self.bot] = 1 > > return give > > > > if __name__ == '__main__': > > hat = NumberHat(0,10) > > for i in range(10): > > print hat.take() > > > > ############################################################ > > # OUTPUT: > > # bash-2.05a$ ./numberhat.py > > # 1 > > # 5 > > # 6 > > # 9 > > # 3 > > # 7 > > # 0 > > # 8 > > # 2 > > # 4 > > # bash-2.05a$ > > > > --- > > > > But there's no generator in it. Is this natural? Or is there > > some other thought I should be thinking? > > > > Thank you again and again. > > > > Marilyn > > > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > -- From kp8 at mac.com Tue Feb 24 03:47:26 2004 From: kp8 at mac.com (kevin parks) Date: Tue Feb 24 03:48:39 2004 Subject: [Tutor] Musical Pitch Message-ID: <123C654F-66A6-11D8-A143-003065555ABC@mac.com> Hi all.... I am here once again seeking some advice... You see i do lots of stuff with music (and python) and i am starting to think that there may be a better way of dealing with musical pitch. One problem is that there are a lot of different ways to represent a note and sometimes you want one and other times you need another representation, and more often than not, you need ways of moving fluidly between the two. So far i have just been sort of making things up as i go along, making huge silly lists or dictionaries. In order to spare the list some bandwidth i'll just post a URL showing the type of monstrous kludgy constructs i have been using: http://www.people.virginia.edu/~kpp9c/pitchname.py.html But i am wondering if maybe it is time for me to take another (possibly OO ? gasp!) oriented approach or just build a pitch module that i can import and reuse. Here are some possible representations just to give you a taste of what i am up against (here i am talking 12 tone equal temperament, i have other tools i use for dealing with tuning ratios) 1. Old fashioned letter names : A4 (C#3, and the like) 2. Frequencies in Hz : 440.00 3. MIDI note numbers: 69 4. Octave point pitch-class: 8.09 (middle c = 8.00, there are 12 pitch classes in an octave, 8.12 would = 9.00) 5. Octave point decimal : 8.75 (middle c = 8.00, but now the pitch-class continuum is 100/12 (8.333..) * number of half steps. An octave run of which would look something like this: C 8.000000 C# 8.083335 D 8.166671 D# 8.249998 E 8.333333 F 8.416668 F# 8.500004 G 8.583331 G3 8.666666 A 8.750001 A# 8.833337 B 8.916664 So in all, 5 different representations of pitch.... Then there would be a slew of modulo 12 operations that maybe could be functions or methods if i decide to get fancy such as transposition, inversion, reducing to 1 oct range, compliment, pitch mapping.... etc. All of which i hope to build up over time.... so... I am wondering: 1. anyone already have something like this hacked together? 2. anyone bored and want to take a whack helping me get started? Or even just suggest some possible paths? cheers, kp From deadviannou at caramail.com Tue Feb 24 09:37:27 2004 From: deadviannou at caramail.com (Djoumy . ) Date: Tue Feb 24 08:37:53 2004 Subject: [Tutor] Socket connection refused Message-ID: <1077629847027268@lycos-europe.com> ?ok Alan and Nick you got the same idea but I still have my problem : 1 - I open client.py (or fclient.py that's the same one) with IDLE, launch server.py (or fserver.py) typing "python server.py" in a command prompt. The server is well launched, and running the client module under IDLE gives a good result : it sends and receives "Hello world" as expected. yeah great :) 2 - Now the same thing but launching the client (after the server) in another command prompt "python client.py". And there I got the problem : Connection refused... Now I'm sure it's not coming from py2exe but I still don't understand what's the difference between launching the client under IDLE or in a command prompt.... Djoum's ------- Message original -------? De: Alan Gauld <alan.gauld@blueyonder.co.uk>? Date: Mon, 23 Feb 2004 22:18:20 -0000? Sujet: Re: [Tutor] Socket connection refused? > I have found two ways to test this : I compile the server with > py2exe and launch it, then I can run the client > either running the module under IDLE or compiling it with py2exe. I strongly recommend that you do NOT use py2exe until you get your program working. One thing at a time. Its also much faster to develop the program if you don;t have to go through the py2exe stage every time yopu make a change! Just run your client and server from a pair of command prompt windows. Use Start-Run and enter "COMMAND" to start a command prompt (aka DOS box). Do it twice to get two. In one box start your client by typing: C:\>python client.py And in the other start your server C:\>python server.py (Actually its usually better to start the server first!) Now you should see the prompts and output of each program in its own box. And having just seen the code I notice its a Tkinter client so you only need one DOS box for the server, you can start the client just by double clicking in explorer... HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld Pour gagner une Playstation 2, envoyez un SMS avec le code PS au 61321 (0,35 euro hors co?t du SMS). From pythontutor at venix.com Tue Feb 24 09:25:52 2004 From: pythontutor at venix.com (Lloyd Kvam) Date: Tue Feb 24 09:26:34 2004 Subject: [Tutor] generators and classes In-Reply-To: <Pine.LNX.4.44.0402232319520.11161-100000@Kuna> References: <Pine.LNX.4.44.0402232319520.11161-100000@Kuna> Message-ID: <403B5EF0.5090708@venix.com> Look at SimPy for some generator code with classes that would be hard to do otherwise. http://simpy.sourceforge.net/ Home Marilyn Davis wrote: > Thank you for this. > > On Tue, 24 Feb 2004, Lloyd Kvam wrote: > > >>In the first example, you call list_unique which handles the >>looping, calls the generator, and returns a list. The class example >>puts the looping in the caller and never builds a list. Put unique >>and list_unique methods into the class and I think it will work more >>like the first example. > > > I'm just thinking that maybe the generator facility doesn't make sense > in a class structure --> because the initializing part of the > generator function belongs in __init__ and then you want the yield to > be in another function because __init__ isn't allowed to return > anything. So, you already have two functions with shared scope so you > might as well return, skip the next(), and keep things simple. > > I tried to do what you suggest and it gets clumsy (but it works!). > > Maybe you intended something different? > > #! /usr/bin/python2.2 > ''' > Demonstrates generators and the 'yield' keyword in the > context of a class structure.''' > > from __future__ import generators > import random > > class Scrambler: > '''Generator to deliver randomly chosen values from bot > to over_top - 1, delivering each value once only. To > collect the numbers, you make an object and call: > object.take.next()''' > def __init__(self, bot, over_top): > self.bot = bot > self.over_top = over_top > self.taken = [0] * (over_top - bot) > self.take = self.dummy() > > def dummy(self): > while 1: > give = random.randrange(self.bot, self.over_top) > if not self.taken[give - self.bot]: > self.taken[give - self.bot] = 1 > yield give > > if __name__ == '__main__': > scram = Scrambler(0,10) > for i in range(10): > print scram.take.next() > > ############################# > # OUTPUT: > # bash-2.05a$ ./scrambler.py > # 3 > # 4 > # 8 > # 2 > # 7 > # 1 > # 6 > # 0 > # 9 > # 5 > # bash-2.05a$ > > ---- > >>Marilyn Davis wrote: >> >> >>>Hello again, >>> >>>I wrote this little program to demonstrate a generator: >>> >>>#! /usr/bin/python2.2 >>>'''Function to generate random numbers without repetition. >>>Demonstrates generators and the 'yield' keyword.''' >>> >>>from __future__ import generators >>>import random >>> >>>def unique(bot, over_top): >>> '''Generator to deliver randomly chosen values from bot >>> to over_top - 1, delivering each value once only.''' >>> taken = [0] * (over_top - bot) >>> while (1): >>> give = random.randrange(bot, over_top) >>> if not taken[give - bot]: >>> taken[give - bot] = 1 >>> yield give >>> >>>def list_unique(bot, over_top): >>> '''Returns a list of the generated numbers''' >>> gen = unique(bot, over_top) >>> return [gen.next() for i in range(bot, over_top)] >>> >>>if __name__ == '__main__': >>> print '(0,5) = ', list_unique(0,5) >>> print '(10,21) = ', list_unique(10,21) >>> >>>############################# >>># OUTPUT: >>># bash-2.05a$ ./unique.py >>># (0,5) = [2, 3, 1, 0, 4] >>># (10,21) = [17, 10, 18, 20, 19, 15, 11, 13, 12, 16, 14] >>># bash-2.05a$ >>> >>>----- >>> >>>But now that I'm preparing to teach OO, I want to do the class >>>equivalent, which turns out like this: >>> >>>#! /usr/bin/env python2.2 >>> >>>import random >>> >>>class NumberHat: >>> '''Generator to deliver randomly chosen values from bot >>>to over_top - 1, delivering each value once only.''' >>> def __init__(self, bot, over_top): >>> self.bot = bot >>> self.over_top = over_top >>> self.taken = [0] * (over_top - bot) >>> >>> def take(self): >>> while 1: >>> give = random.randrange(self.bot, self.over_top) >>> if not self.taken[give - self.bot]: >>> self.taken[give - self.bot] = 1 >>> return give >>> >>>if __name__ == '__main__': >>> hat = NumberHat(0,10) >>> for i in range(10): >>> print hat.take() >>> >>>############################################################ >>># OUTPUT: >>># bash-2.05a$ ./numberhat.py >>># 1 >>># 5 >>># 6 >>># 9 >>># 3 >>># 7 >>># 0 >>># 8 >>># 2 >>># 4 >>># bash-2.05a$ >>> >>>--- >>> >>>But there's no generator in it. Is this natural? Or is there >>>some other thought I should be thinking? >>> >>>Thank you again and again. >>> >>>Marilyn >>> >>> >>>_______________________________________________ >>>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 guillermo.fernandez at epfl.ch Tue Feb 24 09:51:42 2004 From: guillermo.fernandez at epfl.ch (Guillermo Fernandez Castellanos) Date: Tue Feb 24 09:51:48 2004 Subject: [Tutor] Adding to python path Message-ID: <403B64FE.8040508@epfl.ch> Hi, I've a program that it's structured like that: I've a main file, called bego.py that uses other modules that are all stored (for clarity reasons) in a lib/ folder. Those modules can also be used separatelly to write scripts, and I've already made a few. I would like to keep (always for clarity reasons) all the scripts in a scripts/ folder. How could the scripts in the scripts/ folder use the modules of the lib/ folder if they must be called as normal programs? Structure of my program: bego.py lib/ begohandler.py mac.py ... syslogdb.py scripts/ matlab.py ... arrow.py Any links, or help would be wellcomed. Thanks! Guille From vmonkey at earthlink.net Tue Feb 24 10:54:25 2004 From: vmonkey at earthlink.net (vmonkey) Date: Tue Feb 24 10:52:02 2004 Subject: [Tutor] Arrgh! Paths on windows! Message-ID: <403B73B1.9010007@earthlink.net> What is wrong with the following lines of code? import os tmp = os.path.normpath("c:/Documents and Settings/Joe Blow/Local Settings/Temporary Internet Files") It SHOULD create a path properly formatted for windows in the variable tmp. But I get this error whenever I run it: SyntaxError: EOL while scanning single-quoted string Can anyone help me with this? From magnus at thinkware.se Tue Feb 24 11:11:20 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Tue Feb 24 11:11:29 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gQXJyZ2ghIFBhdGhzIG9uIHdpbmRvd3Mh?= Message-ID: <think001_403b76056c873@webmail.thinkware.se> The way it looks in your mail: with a line break after "Local", there is certainly EndOfLine in a single-quoted string. I get that error just as I expect. If I put the whole path on one line, I get just the normalized path I expect. Python is (quite deliberately) picky on whitespace handling, but all languages I know of are picky about linebreaks in strings. If you want to split the long string to fit in fewer columns, you need to quote each segment separately. >>> tmp = os.path.normpath("c:/Documents and Settings/" "Joe Blow/Local " "Settings/Temporary Internet Files") Be careful to preserve the whitespaces as well. "Local " != "Local" -----Ursprungligt meddelande----- Fr?n: vmonkey <vmonkey@earthlink.net> Skickat: 2004-02-24 16:54:25 Till: tutor@python.org ?mne: [Tutor] Arrgh! Paths on windows! > What is wrong with the following lines of code? > > import os > > tmp = os.path.normpath("c:/Documents and Settings/Joe Blow/Local > Settings/Temporary Internet Files") > > It SHOULD create a path properly formatted for windows in the variable > tmp. But I get this error whenever I run it: > > SyntaxError: EOL while scanning single-quoted string > > Can anyone help me with this? > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 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 guillermo.fernandez at epfl.ch Tue Feb 24 11:12:29 2004 From: guillermo.fernandez at epfl.ch (Guillermo Fernandez Castellanos) Date: Tue Feb 24 11:18:17 2004 Subject: [Tutor] Arrgh! Paths on windows! In-Reply-To: <403B73B1.9010007@earthlink.net> References: <403B73B1.9010007@earthlink.net> Message-ID: <403B77ED.8050300@epfl.ch> Try either: tmp = os.path.normpath("c:/Documents and Settings/Joe Blow/Local \ Settings/Temporary Internet Files") or put everything in one single line. The problem is that you split your string in 2 parts, and the interpreter tells you that he find the start of the string but not the end. your command is equivalend to type: >>> tmp = os.path.normpath("c:/Documents and Settings/Joe Blow/Local SyntaxError: EOL while scanning single-quoted string >>> in IDLE :-) Guille vmonkey wrote: > What is wrong with the following lines of code? > > import os > > tmp = os.path.normpath("c:/Documents and Settings/Joe Blow/Local > Settings/Temporary Internet Files") > > It SHOULD create a path properly formatted for windows in the variable > tmp. But I get this error whenever I run it: > > SyntaxError: EOL while scanning single-quoted string > > Can anyone help me with this? > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From magnus at thinkware.se Tue Feb 24 11:19:32 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Tue Feb 24 11:19:43 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gQWRkaW5nIHRvIHB5dGhvbiBwYXRo?= Message-ID: <think001_403b77f084d8f@webmail.thinkware.se> > How could the scripts in the scripts/ folder use the modules of the lib/ folder > if they must be called as normal programs? import sys sys.path.append('../lib') ..methinks. Another option is to place the lib code in the standard site-packages directory. > Structure of my program: > bego.py > lib/ > begohandler.py > mac.py > ... > syslogdb.py > scripts/ > matlab.py > ... > arrow.py -- 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 vmonkey at earthlink.net Tue Feb 24 11:24:14 2004 From: vmonkey at earthlink.net (vmonkey) Date: Tue Feb 24 11:21:47 2004 Subject: [Tutor] Arrgh! Paths on windows! In-Reply-To: <think001_403b76056c873@webmail.thinkware.se> References: <think001_403b76056c873@webmail.thinkware.se> Message-ID: <403B7AAE.3010501@earthlink.net> Thanks, your solution worked. Is there a better way for me to do this in the future? Magnus Lycka wrote: >The way it looks in your mail: with a line break after "Local", >there is certainly EndOfLine in a single-quoted string. I get >that error just as I expect. If I put the whole path on one line, >I get just the normalized path I expect. > >Python is (quite deliberately) picky on whitespace handling, >but all languages I know of are picky about linebreaks in strings. > >If you want to split the long string to fit in fewer columns, >you need to quote each segment separately. > > > >>>>tmp = os.path.normpath("c:/Documents and Settings/" >>>> >>>> > "Joe Blow/Local " > "Settings/Temporary Internet Files") > >Be careful to preserve the whitespaces as well. "Local " != "Local" > >-----Ursprungligt meddelande----- >Fr?n: vmonkey <vmonkey@earthlink.net> >Skickat: 2004-02-24 16:54:25 >Till: tutor@python.org >?mne: [Tutor] Arrgh! Paths on windows! > > > > >>What is wrong with the following lines of code? >> >>import os >> >>tmp = os.path.normpath("c:/Documents and Settings/Joe Blow/Local >>Settings/Temporary Internet Files") >> >>It SHOULD create a path properly formatted for windows in the variable >>tmp. But I get this error whenever I run it: >> >>SyntaxError: EOL while scanning single-quoted string >> >>Can anyone help me with this? >> >> >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor >> >> >> > > > > From nick at javacat.f2s.com Tue Feb 24 11:57:41 2004 From: nick at javacat.f2s.com (Nick Lunt) Date: Tue Feb 24 12:11:08 2004 Subject: [Tutor] Socket connection refused In-Reply-To: <1077629847027268@lycos-europe.com> References: <1077629847027268@lycos-europe.com> Message-ID: <20040224165741.74b3c256@phatbox.local> I'm not 100% clear mate, have you launched both the server and the client from different command prompts (forget IDLE and py2exe for now) ? If you have and your still getting "connection refused" then Im stumped. Can you try it on another computer somewhere ? It works on windowsXP and linux here at home both with python2.3 . I do however get an error when I run the client from within IDLE. IDLE has problems with the Tkinter module sometimes so that doesn't surprise me. Can you clarify that you have run the client and server without using either py2exe or IDLE for any of them please. Cheers Nick. On Tue, 24 Feb 2004 14:37:27 GMT "Djoumy . " <deadviannou@caramail.com> wrote: > ?ok Alan and Nick you got the same idea but I still have my problem : > > 1 - I open client.py (or fclient.py that's the same one) with IDLE, > launch server.py (or fserver.py) > typing "python server.py" in a command prompt. The server is > well launched, and running the client module > under IDLE gives a good result : it sends and receives "Hello world" > as expected. yeah great :) > > 2 - Now the same thing but launching the client (after the server) in > another command prompt "python > client.py". And there I got the problem : Connection refused... > > Now I'm sure it's not coming from py2exe but I still don't understand > what's the difference between launching > the client under IDLE or in a command prompt.... > > Djoum's > > > ------- Message original -------? > De: Alan Gauld <alan.gauld@blueyonder.co.uk>? > Date: Mon, 23 Feb 2004 22:18:20 -0000? > Sujet: Re: [Tutor] Socket connection refused? > > > > I have found two ways to test this : I compile the server with > > py2exe and launch it, then I can run the client > > either running the module under IDLE or compiling it with py2exe. > > I strongly recommend that you do NOT use py2exe until you get your > program working. One thing at a time. Its also much faster to develop > the program if you don;t have to go through the py2exe stage every > time yopu make a change! > > Just run your client and server from a pair of command prompt windows. > > Use Start-Run and enter "COMMAND" to start a command prompt > (aka DOS box). Do it twice to get two. > > In one box start your client by typing: > > C:\>python client.py > > And in the other start your server > > C:\>python server.py > > (Actually its usually better to start the server first!) > > Now you should see the prompts and output of each program in its > own box. > > And having just seen the code I notice its a Tkinter client so > you only need one DOS box for the server, you can start the client > just by double clicking in explorer... > > HTH, > > Alan G > Author of the Learn to Program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld > > Pour gagner une Playstation 2, envoyez un SMS avec le code PS au 61321 > (0,35 euro hors co?t du SMS). > > From glingl at aon.at Tue Feb 24 12:44:17 2004 From: glingl at aon.at (Gregor Lingl) Date: Tue Feb 24 12:43:25 2004 Subject: [Tutor] global variables & recursion (& stackless) In-Reply-To: <m3y8qte5k0.fsf@hamster.pflaesterer.de> References: <200402231648.42994.RobinHood42@clickta.com> <4039DD80.8030108@aon.at> <005601c3fa59$f3469b70$6401a8c0@xp> <403A7E86.8020102@aon.at> <m3y8qte5k0.fsf@hamster.pflaesterer.de> Message-ID: <403B8D71.6080500@aon.at> Karl Pfl?sterer schrieb: >ACK. After having looked at your second solution I tried a solution >which makes it IMO clearer how s and t are found (in the original code >it was a bit hidden IMO). > >def gcd (a, b): > a, b = abs(a), abs(b) > rem = [] > while b > 0: > rem.append((a,b)) > a, b = b, a%b > return a, rem > >def st (a, b): > gc, rem = gcd(a, b) > rem.reverse() > s = t = 1 > for a, b in rem: > s, t = t, s - (a//b)*t > return gc, (a, s), (b, t) > > > > That's a fine solution.... mine was directly derived from alice's, using her recursive approach and (intentionally) making only slight modifications. Certainly alice will be pleased to see her solution now turned into a iterative one. >The gcd function is nearly the standard solution (only the rem[] list is >additional). > >The st() function then uses that function to compute s and t. > > >Recursion is a very useful technique but in Python sadly not very >performant (what about Stackless in that regard?). > I'v timed the performance of gcd roughly with: >>> if 1: t1 = clock() for a in range(1,1001): for b in range(1,a): x = gcd(a,b) print clock()-t1 This computes approx 500000 gcds Results: function Python2.2 Python2.3.3 Python2.3.3-Stackless3.0 ggt-iterative 2.20 s 2.10 s 1.62 s (!) ggt-recursive 2.40 s 2.45 s 2.30 s So in this case the performance issue concerning iterative versus recursive seems to be of minor importance Regards, Gregor P.S. time used by the naked loops + assignment: if 1: t1 = clock() for a in range(1,1001): for b in range(1,a): x = b print clock()-t1 needs approx. 0.2s >That should be told >anyone who uses recursive algorithms so they are rewritten iteratively >(if possible). > > From marilyn at deliberate.com Tue Feb 24 13:08:12 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Tue Feb 24 13:08:18 2004 Subject: [Tutor] generators and classes In-Reply-To: <403B5EF0.5090708@venix.com> Message-ID: <Pine.LNX.4.44.0402240941400.11161-100000@Kuna> Thank you Lloyd. On Tue, 24 Feb 2004, Lloyd Kvam wrote: > Look at SimPy for some generator code with classes that would be hard to > do otherwise. > > http://simpy.sourceforge.net/ > Home I can't take on such a big study right now. I did do 2 other implementations, one with __get_item__ and one with __iter__ --> just in case anyone is interested, here they are. I like __get_item__ best, which is this one: #! /usr/bin/env python2.2 import random class NumberHat: '''Generator to deliver randomly chosen values from bot to over_top - 1, delivering each value once only. This one implements __getitem__ so you can access the numbers with [].''' def __init__(self, bot, over_top): self.bot = bot self.over_top = over_top self.numbers = [] for i in range(bot, over_top): while 1: new_number = random.randrange(self.bot, self.over_top) if new_number in self.numbers: continue self.numbers.append(new_number) break def __getitem__(self,i): return self.numbers[i] def __repr__(self): return str([num for num in self.numbers]) if __name__ == '__main__': hat = NumberHat(0,10) print hat print [hat[i] for i in range(10)] print [num for num in hat] ############################################################ # OUTPUT: # bash-2.05a$ ./numberhat2.py # [3, 7, 2, 5, 0, 6, 8, 1, 4, 9] # [3, 7, 2, 5, 0, 6, 8, 1, 4, 9] # [3, 7, 2, 5, 0, 6, 8, 1, 4, 9] # bash-2.05a$ ----- #! /usr/bin/env python2.2 import random class NumberHat: '''Generator to deliver randomly chosen values from bot to over_top - 1, delivering each value once. This one implements an __iter__ method so that you can use a next() call.''' def __init__(self, bot, over_top): self.bot = bot self.over_top = over_top self.numbers = [] for i in range(bot, over_top): while 1: new_number = random.randrange(self.bot, self.over_top) if new_number in self.numbers: continue self.numbers.append(new_number) break self.at = -1 def __iter__(self): return self def next(self): self.at += 1 return self.numbers[self.at] def __repr__(self): return str([num for num in self.numbers]) if __name__ == '__main__': hat = NumberHat(0,10) print hat print [hat.next() for x in range(10)] ############################################################ # OUTPUT: # bash-2.05a$ ./numberhat3.py # [7, 2, 6, 1, 4, 3, 8, 9, 5, 0] # [7, 2, 6, 1, 4, 3, 8, 9, 5, 0] # bash-2.05a$ From sa at sfsu.edu Tue Feb 24 18:41:02 2004 From: sa at sfsu.edu (Sean Abrahams) Date: Tue Feb 24 18:39:03 2004 Subject: [Tutor] Code/Style Review of Data Validation Code Message-ID: <E803F383-6722-11D8-8AEB-000A95C48278@sfsu.edu> The following is some code I wrote to validate certain types of data that is passed into a python script via a web form. However, the way it is implemented now you can pass in any set of rules and any set of data and get back some results on wether the data passed the tests. The style of the resulting dict helps with redisplaying the results back onto the web page. I'm interested in improving the code overall and perhaps working exceptions in, instead of using a specific dict format. Anyone have any arguments for creating a class for this type of stuff? etc? Thanks, ---Sean ------ def validateData(rules, data): """ Validates {data} according to {rules}. Datatypes --------- alpha - can only contain alpha letters alphanum - can only contain alpha letters and/or numbers num - can only contain numbers email - must conform to email regexp recipe phone - must conform to phone regexp recipe Usage ----- data = { 'firstname' : 'John', 'lastname' : 'St. Claire', 'email' : 'jsn.com', 'phone' : '415-333-3333' } rules = { 'firstname' : { 'dataType' : 'alpha', 'minlen' : '2', 'maxlen' : '64', 'isRequired' : '1' }, 'lastname' : { 'dataType' : 'alpha', 'minlen' : '2', 'maxlen' : '64', 'isRequired' : '1' }, 'email' : { 'dataType' : 'email', 'minlen' : '5', 'maxlen' : '30', 'isRequired' : '0' }, 'phone' : { 'dataType' : 'phone', 'minlen' : '7' , 'maxlen' : '32', 'isRequired' : '0' }, } @returns dict of the format: results = { 'name' : 'John' 'name_error' : '', # Empty because no error 'lastname' : 'St. Claire', 'lastname_error' : '', 'email' : 'jsn.com', 'email_error' : '* Invalid email address. Please enter a valid email address. (Ex: yourname@sfsu.edu)', 'phone' : '415-333-3333', 'phone_error' : '' } @param data: dict of data @type data: dict @param rules: the rules that will be applied towards the data @type rules: dict of dicts @returns: original data with _error keys added @rtype: dict """ results = {} for key in rules.keys(): try: if rules[key]['isRequired'] == '0' and data[key] == "": pass else: errorCheck = validate(data[key], rules[key]['dataType'], rules[key]['minlen'], rules[key]['maxlen']) results[key] = errorCheck[0] try: results[key+"_error"] = errorCheck[1] except IndexError: results[key+"_error"] = "" except KeyError: results[key] = "" results[key+"_error"] = "* Error" return results def validate(input, dataType, minlen, maxlen): """ Validate input, applying dataType, minlen, and maxlen constraints, and return results. @param input: the input of the form field @type input: string @param dataType: the dataType the input must match to @type dataType: string @param minlen: the minimum length input must be @type minlen: string @param maxlen: the maximum length input can be @type maxlen: string @returns: results in the format of: results = ['Jon'] if the data is valid results = ['invalidemail.com', "* Error Message"] if data is invalid @rtype: list """ results = [] if dataType == "alpha": if re.compile("^\D+$").search(input): results = [input] else: results = [input, "* Only letters are allowed."] if dataType == "alphanum": if re.compile("^([1-zA-Z0-1@#.,'/\-\s]{1,255})$").search(input): results = [input] else: results = [input, "* Only alphanumerics are allowed."] if dataType == "num": if re.compile("^\d+$").search(input): results = [input] else: results = [input, "* Only numbers are allowed."] if dataType == "email": if re.compile("^.+@.+\..{2,3}$").search(input): results = [input] else: results = [input, """* Invalid email address. Please enter a valid email address. (Ex: yourname@domain.com)"""] if dataType == "phone": if re.compile("^1?\s*-?\s*(\d{3}|\(\s*\d{3}\s*\))\s*-?\s*\d{3}\s*-? \s*\d{4}$").search(input): results = [input] else: results = [input, """* Invalid phone number. Please enter the complete number. (Ex: 415-333-3333)"""] if len(str(input)) < int(minlen): results = [input, """* Must contain at least """ + \ str(minlen) + """ characters."""] if len(str(input)) > int(maxlen): results = [input, """* Must contain less than """ + \ str(maxlen) + """ characters."""] return results From glingl at aon.at Tue Feb 24 18:46:46 2004 From: glingl at aon.at (Gregor Lingl) Date: Tue Feb 24 18:45:52 2004 Subject: [Tutor] generators and classes In-Reply-To: <Pine.LNX.4.44.0402240941400.11161-100000@Kuna> References: <Pine.LNX.4.44.0402240941400.11161-100000@Kuna> Message-ID: <403BE266.6060506@aon.at> Marilyn Davis schrieb: >Thank you Lloyd. > >On Tue, 24 Feb 2004, Lloyd Kvam wrote: > > > >>Look at SimPy for some generator code with classes that would be hard to >>do otherwise. >> >>http://simpy.sourceforge.net/ >>Home >> >> > >I can't take on such a big study right now. > >I did do 2 other implementations, ... > Another one, just as a contribution to the disussion: class NumberHat: def __init__(self, domain): self.domain = domain def gen(self, values): while values: index = random.randrange(len(values)) yield values.pop(index) def __iter__(self): return self.gen(self.domain) >>> hat = NumberHat(range(10)) >>> [x for x in hat] [4, 2, 0, 9, 7, 5, 6, 1, 3, 8] >>> [x for x in hat] [] >>> [x for x in NumberHat(range(-3,4))] [2, -1, 1, 3, -2, -3, 0] BTW, I observed, that if you replace the next() method in >#! /usr/bin/env python2.2 > >import random > >class NumberHat: > '''Generator to deliver randomly chosen values from bot >to over_top - 1, delivering each value once. This one >implements an __iter__ method so that you can use a next() >call.''' > > def __init__(self, bot, over_top): > ... > > > def __iter__(self): > return self > > def next(self): > self.at += 1 > return self.numbers[self.at] > > by: def next(self): self.at += 1 try: return self.numbers[self.at] except: raise StopIteration you get a full fledged generator and the [x for x in hat] idiom works also with this class. Finally: in the Python docs you find: You could achieve the effect of generators manually by writing your own class and storing all the local variables of the generator as instance variables. For example, returning a list of integers could be done by setting |self.count| to 0, and having the next() method increment |self.count| and return it. However, for a moderately complicated generator, writing a corresponding class would be much messier. Lib/test/test_generators.py contains a number of more interesting examples. So I'd prefer to stick with an ordinary generator function like your unique(), but avoiding to get stuck in an infinite loop, because no more unused randomnumber can be found, e.g.: def unique(bot, over_top): domain = range(bot,over_top) while domain: index = random.randrange(len(domain)) yield domain.pop(index) Regards, Gregor From jmatthew at columbus.rr.com Tue Feb 24 21:03:13 2004 From: jmatthew at columbus.rr.com (John Matthews) Date: Tue Feb 24 21:03:08 2004 Subject: [Tutor] colored text output to Windows console Message-ID: <403C0261.2090903@columbus.rr.com> I have written a text mode game that keeps track of 3 lists. I would like for the output of the game to use colors to make it easier for the user to read the text. Kind of like what is seen on an ANSI BBS. From my initial research, it seems this impossible to do in a Windows 'DOS box'. Any suggestions? Thanks! + John Matthews http://8ftarch.org Eight Foot Architect + | "blind man in a roomful REGIME "we're very unlikely to find large | | of deaf people." CHANGE stockpiles of weapons, I don't | +- Paul O'Neill----------------- 2004 -------think they exist." David Kay------+ From shaleh at speakeasy.net Tue Feb 24 22:33:40 2004 From: shaleh at speakeasy.net (Sean 'Shaleh' Perry) Date: Tue Feb 24 22:33:57 2004 Subject: [Tutor] Code/Style Review of Data Validation Code In-Reply-To: <E803F383-6722-11D8-8AEB-000A95C48278@sfsu.edu> References: <E803F383-6722-11D8-8AEB-000A95C48278@sfsu.edu> Message-ID: <200402241933.40226.shaleh@speakeasy.net> On Tuesday 24 February 2004 15:41, Sean Abrahams wrote: > The following is some code I wrote to validate certain types of data > that is passed into a python script via a web form. However, the way it > is implemented now you can pass in any set of rules and any set of data > and get back some results on wether the data passed the tests. > > The style of the resulting dict helps with redisplaying the results > back onto the web page. > > I'm interested in improving the code overall and perhaps working > exceptions in, instead of using a specific dict format. Anyone have any > arguments for creating a class for this type of stuff? etc? > Sorry, don't have time to comment on all of it. However, I do have a question. Why loop over the rules? I would have done: for key in data: if there is a rule and it is required: apply rule This way, if I only get two pieces of data I can get right in and out. From deadviannou at caramail.com Wed Feb 25 06:43:45 2004 From: deadviannou at caramail.com (Djoumy . ) Date: Wed Feb 25 05:43:54 2004 Subject: [Tutor] Socket connection refused Message-ID: <1077705825007084@lycos-europe.com> sorry i'm not really good in english so maybe what I said wasn't very clear. So : launching the server and the client in a (separate) command prompt?doesn't work I still have a "connection refused" error, I suppose you're stumped :) I'll try to launch it on another computer, but if it works correctly that will mean the problem is coming from my computer... I really don't understand why, since I got a Windows XP professional (SP1) without any specific running process. Djoum's P.S : By the way, each time I answer a mail of Tutor, it creates a new thread. How can I do to avoid this ? (I tried "answer" and "answer to all" but doesn't work) ------- Message original -------? De: Nick Lunt <nick@javacat.f2s.com>? Date: Tue, 24 Feb 2004 16:57:41 +0000? Sujet: Re: [Tutor] Socket connection refused? I'm not 100% clear mate, have you launched both the server and the client from different command prompts (forget IDLE and py2exe for now) ? If you have and your still getting "connection refused" then Im stumped. Can you try it on another computer somewhere ? It works on windowsXP and linux here at home both with python2.3 . I do however get an error when I run the client from within IDLE. IDLE has problems with the Tkinter module sometimes so that doesn't surprise me. Can you clarify that you have run the client and server without using either py2exe or IDLE for any of them please. Cheers Nick. On Tue, 24 Feb 2004 14:37:27 GMT "Djoumy . " wrote: > ?ok Alan and Nick you got the same idea but I still have my problem : > > 1 - I open client.py (or fclient.py that's the same one) with IDLE, > launch server.py (or fserver.py) > typing "python server.py" in a command prompt. The server is > well launched, and running the client module > under IDLE gives a good result : it sends and receives "Hello world" > as expected. yeah great :) > > 2 - Now the same thing but launching the client (after the server) in > another command prompt "python > client.py". And there I got the problem : Connection refused... > > Now I'm sure it's not coming from py2exe but I still don't understand > what's the difference between launching > the client under IDLE or in a command prompt.... > > Djoum's > > > ------- Message original -------? > De: Alan Gauld ? > Date: Mon, 23 Feb 2004 22:18:20 -0000? > Sujet: Re: [Tutor] Socket connection refused? > > > > I have found two ways to test this : I compile the server with > > py2exe and launch it, then I can run the client > > either running the module under IDLE or compiling it with py2exe. > > I strongly recommend that you do NOT use py2exe until you get your > program working. One thing at a time. Its also much faster to develop > the program if you don;t have to go through the py2exe stage every > time yopu make a change! > > Just run your client and server from a pair of command prompt windows. > > Use Start-Run and enter "COMMAND" to start a command prompt > (aka DOS box). Do it twice to get two. > > In one box start your client by typing: > > C:\>python client.py > > And in the other start your server > > C:\>python server.py > > (Actually its usually better to start the server first!) > > Now you should see the prompts and output of each program in its > own box. > > And having just seen the code I notice its a Tkinter client so > you only need one DOS box for the server, you can start the client > just by double clicking in explorer... > > HTH, > > Alan G > Author of the Learn to Program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld > > Pour gagner une Playstation 2, envoyez un SMS avec le code PS au 61321 > (0,35 euro hors co?t du SMS). > > _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor Pour gagner une Playstation 2, envoyez un SMS avec le code PS au 61321 (0,35 euro hors co?t du SMS). From glingl at aon.at Wed Feb 25 06:42:32 2004 From: glingl at aon.at (Gregor Lingl) Date: Wed Feb 25 06:41:39 2004 Subject: [Fwd: [Tutor] global variables & recursion] Message-ID: <403C8A28.6030500@aon.at> alice intended this to go to the list -------- Original-Nachricht -------- Oh yes, very nice. That's much nicer than my original attempt. Is it always possible to turn a recursive algorithm into an iterative one? (sorry if that's a stupid question) On Wednesday 25 February 2004 00:44, Gregor Lingl wrote: > Karl Pfl?sterer schrieb: > >ACK. After having looked at your second solution I tried a solution > >which makes it IMO clearer how s and t are found (in the original code > >it was a bit hidden IMO). > > > >def gcd (a, b): > > a, b = abs(a), abs(b) > > rem = [] > > while b > 0: > > rem.append((a,b)) > > a, b = b, a%b > > return a, rem > > > >def st (a, b): > > gc, rem = gcd(a, b) > > rem.reverse() > > s = t = 1 > > for a, b in rem: > > s, t = t, s - (a//b)*t > > return gc, (a, s), (b, t) > > That's a fine solution.... > mine was directly derived from alice's, using her recursive approach > and (intentionally) making only slight modifications. Certainly alice > will be pleased > to see her solution now turned into a iterative one. From syn_ack at comcast.net Wed Feb 25 09:00:19 2004 From: syn_ack at comcast.net (Joshua Banks) Date: Wed Feb 25 09:05:56 2004 Subject: [Tutor] Socket connection refused In-Reply-To: <1077705825007084@lycos-europe.com> References: <1077705825007084@lycos-europe.com> Message-ID: <200402250600.19876.syn_ack@comcast.net> On Wednesday 25 February 2004 03:43 am, Djoumy . wrote: > sorry i'm not really good in english so maybe what I said wasn't very > clear. So : launching the server and the client in a (separate) > command prompt?doesn't work I still have a "connection refused" > error, I suppose you're stumped :) > I'll try to launch it on another computer, but if it works correctly > that will mean the problem is coming from my computer... I really > don't understand why, since I got a Windows XP professional (SP1) > without any specific running process. > > Djoum's > > P.S : By the way, each time I answer a mail of Tutor, it creates a > new thread. How can I do to avoid this ? (I tried "answer" and > "answer to all" but doesn't work) Djoumy, do you have the WinXP firewall turned on? If so, maybe this is whats causing your "Connection Refused". But you said this works when done with IDLE on the same XP machine. Just a shot in the dark. I'm not sure what you mean in your "P.S." statement. I'm not sure how "tutor@python.org" has thier mail server setup either. You didn't say what kind of email client that your using either? HTH's, Joshua Banks From nick at javacat.f2s.com Wed Feb 25 09:33:02 2004 From: nick at javacat.f2s.com (Nick Lunt) Date: Wed Feb 25 09:33:15 2004 Subject: [Tutor] Socket connection refused In-Reply-To: <200402250600.19876.syn_ack@comcast.net> References: <1077705825007084@lycos-europe.com> <200402250600.19876.syn_ack@comcast.net> Message-ID: <20040225143302.5d66fbc1@phatbox.local> As your python progams are fine it may be worth looking at your windows event viewer to see if that sheds any light on the problem, particularly the security section (if I'm remembering windows correctly). Also start the server from the command line and type 'telnet localhost 50007' and see what happens. Good luck, but if you still have no luck then I'm afraid there's not much more I can do, I'm duff at windows stuff ;) But post your results back here anyway cos I'm sure there's plenty on this list who know enough about windows to get you sorted. Cheers Nick. On Wed, 25 Feb 2004 06:00:19 -0800 Joshua Banks <syn_ack@comcast.net> wrote: > On Wednesday 25 February 2004 03:43 am, Djoumy . wrote: > > sorry i'm not really good in english so maybe what I said wasn't > > very clear. So : launching the server and the client in a (separate) > > command prompt?doesn't work I still have a "connection refused" > > error, I suppose you're stumped :) > > I'll try to launch it on another computer, but if it works correctly > > that will mean the problem is coming from my computer... I really > > don't understand why, since I got a Windows XP professional (SP1) > > without any specific running process. > > > > Djoum's > > > > P.S : By the way, each time I answer a mail of Tutor, it creates a > > new thread. How can I do to avoid this ? (I tried "answer" and > > "answer to all" but doesn't work) > > Djoumy, do you have the WinXP firewall turned on? If so, maybe this is > whats causing your "Connection Refused". But you said this works when > done with IDLE on the same XP machine. Just a shot in the dark. > > I'm not sure what you mean in your "P.S." statement. I'm not sure how > "tutor@python.org" has thier mail server setup either. You didn't say > what kind of email client that your using either? > > HTH's, > Joshua Banks > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From SWidney at LasVegasNevada.GOV Wed Feb 25 11:18:11 2004 From: SWidney at LasVegasNevada.GOV (Scott Widney) Date: Wed Feb 25 11:18:31 2004 Subject: [Tutor] RE: Tutor Digest, Vol 7, Issue 55 Message-ID: <0E5508EBA1620743B409A2B8365DE16F0FCB87E9@sovereign.ci.las-vegas.nv.us> Fredrik Lundh wrote a module for exactly this. Here's a link: http://www.effbot.org/zone/console-index.htm Enjoy! > Date: Tue, 24 Feb 2004 21:03:13 -0500 > From: John Matthews <jmatthew@columbus.rr.com> > Subject: [Tutor] colored text output to Windows console > To: tutor@python.org > Message-ID: <403C0261.2090903@columbus.rr.com> > Content-Type: text/plain; charset=us-ascii; format=flowed > > I have written a text mode game that keeps track of 3 lists. I would like for > the output of the game to use colors to make it easier for the user to read > the text. Kind of like what is seen on an ANSI BBS. > > From my initial research, it seems this impossible to do in a Windows 'DOS box'. > > Any suggestions? Thanks! From deadviannou at caramail.com Wed Feb 25 16:10:29 2004 From: deadviannou at caramail.com (Djoumy . ) Date: Wed Feb 25 15:10:36 2004 Subject: [Tutor] Socket connection refused Message-ID: <1077739829021589@lycos-europe.com> ?I don't have the WinXP firewall turned on, I switched it off before testing my app, thinking it could block socket connexions. I'm using caramail as email client, maybe not the best choice... but each time I answer a mail from someone, Tutor get it as a new thread in its archives, instead of creating a sub-thread as it should do. Djoum's ------- Message original -------? De: Joshua Banks <syn_ack@comcast.net>? Date: Wed, 25 Feb 2004 06:00:19 -0800? Sujet: Re: [Tutor] Socket connection refused? On Wednesday 25 February 2004 03:43 am, Djoumy . wrote: > sorry i'm not really good in english so maybe what I said wasn't very > clear. So : launching the server and the client in a (separate) > command prompt?doesn't work I still have a "connection refused" > error, I suppose you're stumped :) > I'll try to launch it on another computer, but if it works correctly > that will mean the problem is coming from my computer... I really > don't understand why, since I got a Windows XP professional (SP1) > without any specific running process. > > Djoum's > > P.S : By the way, each time I answer a mail of Tutor, it creates a > new thread. How can I do to avoid this ? (I tried "answer" and > "answer to all" but doesn't work) Djoumy, do you have the WinXP firewall turned on? If so, maybe this is whats causing your "Connection Refused". But you said this works when done with IDLE on the same XP machine. Just a shot in the dark. I'm not sure what you mean in your "P.S." statement. I'm not sure how "tutor@python.org" has thier mail server setup either. You didn't say what kind of email client that your using either? HTH's, Joshua Banks _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor Pour gagner une Playstation 2, envoyez un SMS avec le code PS au 61321 (0,35 euro hors co?t du SMS). From marilyn at deliberate.com Wed Feb 25 16:08:44 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Wed Feb 25 16:08:52 2004 Subject: [Tutor] generators and classes In-Reply-To: <403BE266.6060506@aon.at> Message-ID: <Pine.LNX.4.44.0402251304370.11161-100000@Kuna> Thank you again. On Wed, 25 Feb 2004, Gregor Lingl wrote: > > > Marilyn Davis schrieb: > > >Thank you Lloyd. > > > >On Tue, 24 Feb 2004, Lloyd Kvam wrote: > > > > > > > >>Look at SimPy for some generator code with classes that would be hard to > >>do otherwise. > >> > >>http://simpy.sourceforge.net/ > >>Home > >> > >> > > > >I can't take on such a big study right now. > > > >I did do 2 other implementations, ... > > > Another one, just as a contribution to the disussion: > > class NumberHat: > def __init__(self, domain): > self.domain = domain > def gen(self, values): > while values: > index = random.randrange(len(values)) > yield values.pop(index) > def __iter__(self): > return self.gen(self.domain) Interesting. Thank you. > > >>> hat = NumberHat(range(10)) > >>> [x for x in hat] > [4, 2, 0, 9, 7, 5, 6, 1, 3, 8] > >>> [x for x in hat] > [] > >>> [x for x in NumberHat(range(-3,4))] > [2, -1, 1, 3, -2, -3, 0] > > BTW, I observed, that if you replace the > next() method in > > >#! /usr/bin/env python2.2 > > > >import random > > > >class NumberHat: > > '''Generator to deliver randomly chosen values from bot > >to over_top - 1, delivering each value once. This one > >implements an __iter__ method so that you can use a next() > >call.''' > > > > def __init__(self, bot, over_top): > > ... > > > > > > def __iter__(self): > > return self > > > > def next(self): > > self.at += 1 > > return self.numbers[self.at] > > > > > by: > > def next(self): > self.at += 1 > try: > return self.numbers[self.at] > except: > raise StopIteration > > you get a full fledged generator and the > [x for x in hat] idiom works also with this class. Cool. > > Finally: in the Python docs you find: > > You could achieve the effect of generators manually by writing your own > class and storing all the local variables of the generator as instance > variables. For example, returning a list of integers could be done by > setting |self.count| to 0, and having the next() method increment > |self.count| and return it. However, for a moderately complicated > generator, writing a corresponding class would be much messier. > Lib/test/test_generators.py contains a number of more interesting examples. > > So I'd prefer to stick with an ordinary generator function like > your unique(), but avoiding to get stuck in an infinite loop, > because no more unused randomnumber can be found, e.g.: > > def unique(bot, over_top): > domain = range(bot,over_top) > while domain: > index = random.randrange(len(domain)) > yield domain.pop(index) Good idea. Thank you. Marilyn > > Regards, Gregor > > -- From chekuri at uchicago.edu Wed Feb 25 16:13:23 2004 From: chekuri at uchicago.edu (chekuri@uchicago.edu) Date: Wed Feb 25 16:17:45 2004 Subject: [Tutor] How to create a splash screen using wxpython Message-ID: <1077743603.403d0ff37d269@webmail-b.uchicago.edu> I know what wrappers are and have programmed them during a c course, but I am new to python and cannot make heads or tails of the wxpython classes. wxSplashScreen seems to be the that should be used to create a splash screen, but what is the function that wraps around the constructor function of spashscreen from wxwindows? In brief my question is how to create a splash screen using wxpython From glingl at aon.at Wed Feb 25 16:47:27 2004 From: glingl at aon.at (Gregor Lingl) Date: Wed Feb 25 16:46:40 2004 Subject: [Tutor] Musical Pitch In-Reply-To: <123C654F-66A6-11D8-A143-003065555ABC@mac.com> References: <123C654F-66A6-11D8-A143-003065555ABC@mac.com> Message-ID: <403D17EF.1090207@aon.at> Hi Kevin! kevin parks schrieb: > ... So far i have just been sort of making things up as i go along, > making huge silly lists or dictionaries. In order to spare the list > some bandwidth i'll just post a URL showing the type of monstrous > kludgy constructs i have been using: > > http://www.people.virginia.edu/~kpp9c/pitchname.py.html > > But i am wondering if maybe it is time for me to take another > (possibly OO ? gasp!) oriented approach or just build a pitch module > that i can import and reuse. > > Here are some possible representations just to give you a taste of > what i am up against (here i am talking 12 tone equal temperament, i > have other tools i use for dealing with tuning ratios) > > 1. Old fashioned letter names : A4 (C#3, and the like) > 2. Frequencies in Hz : 440.00 > 3. MIDI note numbers: 69 > 4. Octave point pitch-class: 8.09 (middle c = 8.00, there are 12 pitch > classes in an octave, 8.12 would = 9.00) > 5. Octave point decimal : 8.75 (middle c = 8.00, but now the > pitch-class continuum is 100/12 (8.333..) * number of half steps. An > octave run of which would look something like this: ... > > > So in all, 5 different representations of pitch.... > > Then there would be a slew of modulo 12 operations that maybe could be > functions or methods if i decide to get fancy such as transposition, > inversion, reducing to 1 oct range, compliment, pitch mapping.... etc. > > All of which i hope to build up over time.... > > so... I am wondering: > > 1. anyone already have something like this hacked together? No > 2. anyone bored and want to take a whack helping me get started? Bored? Not at all. Nevertheless, here is a couple of functions, which might get you started: def pitchname(midi, name={0:"C",1:"C#",2:"D",3:"D#", 4:"E",5:"F",6:"F#",7:"G", 8:"G#",9:"A",10:"A#",11:"H"} ): return "%s%d" % (name[midi%12],midi//12-1) def frequency(midi, f = 2**(1.0/12)): return round(440 * f**(midi-69),3) def octpoint_pc(midi): return "%d.%02d" % (3+midi//12,midi%12) def octpoint_dc(midi): return round( 3+midi/12.0 ,6) for i in range(128): print pitchname(i), frequency(i), octpoint_pc(i), octpoint_dc(i), i #you can get your table: pitch = [ (pitchname(i), frequency(i), octpoint_pc(i), octpoint_dc(i), i) for i in range(128)] for p in pitch: print p Perhaps you have to convert some of the numbers into strings, if needed ... BTW, do you know midi-software with Python-interfaces (for Windows) Any hint/link would be appreciated... (A friend of mine asked me for this some weeks ago.) Regards, Gregor From peter.giza at comcast.net Wed Feb 25 16:51:18 2004 From: peter.giza at comcast.net (Peter E. Giza) Date: Wed Feb 25 16:59:40 2004 Subject: [Tutor] Newbie HTTP Basic Auth question In-Reply-To: <403D17EF.1090207@aon.at> Message-ID: <DHEELFBNHIGFKIDIIGLJIEGGEPAA.peter.giza@comcast.net> Hello All, Can someone point me to some sample code to handle username and password setting for server side HTTP basic authentication during a form submit? I have tried the cookbook, etc. with no luck. Any help would be greatly appreciated. Regards, Peter From syn_ack at comcast.net Wed Feb 25 17:58:28 2004 From: syn_ack at comcast.net (Joshua Banks) Date: Wed Feb 25 18:05:32 2004 Subject: [Tutor] Socket connection refused References: <1077739829021589@lycos-europe.com> Message-ID: <004101c3fbf2$e22fb2a0$4202a8c0@toejam> Hi Djoumy, I'm not new to networking but new to Python. Could you please send me your code. I've since deleted your orginal email with the attatched code. I have Linux, Win2k and WinXP here at home that I can test with. All running Python 2.3.3. I'm pretty new to python but am willing to test your code to see if I run into any of the same problems that your having. Just zip up the code and send it to my email address and let me know what directions are needed to execute the test. I believe there's a server.py and client.py app that your testing with. I can even packet sniff and capture the client server interaction to help further diagnose what the possible connection problem could be if there is one for me. If I don't run into any problems I will have a packet sniff/capture of what a good client-sever connection should look like that you can look at. Have you ever used Ethereal before? If not, I can show you how if you would like. Having a packet sniffing tool can be very helpful in isolating where a network problem lives.. Once you can isolate where the problem is then you can spend more energy in the correct area.Thats if your test comprises of two physical machines trying to communicate with eachother. If the client and server app are both installed on the same machine then I wont be to big of a help. All I could do is just test too see if I get the same results. Do you have an Instant Messenger client installed that you can use to chat with? This will help speed the trouble shooting process up. I have Yahoo Instant Messenger installed on my end. Let me know how you would like to proceed Djoumy? Sorry.. Not familar with your mail client. So I can't help shed any light in that area. Joshua Banks From cspears2002 at yahoo.com Wed Feb 25 20:04:03 2004 From: cspears2002 at yahoo.com (Christopher Spears) Date: Wed Feb 25 20:04:11 2004 Subject: [Tutor] writing methods Message-ID: <20040226010403.73210.qmail@web12407.mail.yahoo.com> I am trying to solve the following homework assignment: Using the UserDict module, create a class called Odict, which will be just like a dictionary but will "remember" the order in which key/value pairs are added to the dictionary. (Hint: Override the built-in __setitem__ method.) Create a new method for the Odict object called okeys, which will return the ordered keys. I don't expect to get the answer, but I would like to be pointed in the right direction. I think my major problem is that concepts that surround writing methods are still not transparent to me. I find myself spending a lot of time staring at the UserDict module code, scratching my head, and trying out stuff in IDLE to figure out how the code works. Is there a good tutorial or something on the web that will clear these concepts ups for me? ===== "I'm the last person to pretend that I'm a radio. I'd rather go out and be a color television set." -David Bowie "Who dares wins" -British military motto "The freak is the norm." - "The Infernal Desire Machines of Dr. Hoffman" by Angela Carter From darnold02 at sprynet.com Wed Feb 25 20:53:40 2004 From: darnold02 at sprynet.com (Don Arnold) Date: Wed Feb 25 20:52:16 2004 Subject: [Tutor] How to create a splash screen using wxpython In-Reply-To: <1077743603.403d0ff37d269@webmail-b.uchicago.edu> References: <1077743603.403d0ff37d269@webmail-b.uchicago.edu> Message-ID: <998089AA-67FE-11D8-B1DC-000A95C4F940@sprynet.com> On Feb 25, 2004, at 3:13 PM, chekuri@uchicago.edu wrote: > I know what wrappers are and have programmed them during a c course, > but I am > new to python and cannot make heads or tails of the wxpython classes. > wxSplashScreen seems to be the that should be used to create a splash > screen, > but what is the function that wraps around the constructor function of > spashscreen from wxwindows? > > In brief my question is how to create a splash screen using wxpython Check out the demo that comes with wxPython. I don't have it installed on this machine, but I believe it's all.py in the demo folder (not sure of the exact path). HTH, Don From darnold02 at sprynet.com Wed Feb 25 22:07:20 2004 From: darnold02 at sprynet.com (Don Arnold) Date: Wed Feb 25 22:05:59 2004 Subject: [Tutor] How to create a splash screen using wxpython In-Reply-To: <998089AA-67FE-11D8-B1DC-000A95C4F940@sprynet.com> References: <1077743603.403d0ff37d269@webmail-b.uchicago.edu> <998089AA-67FE-11D8-B1DC-000A95C4F940@sprynet.com> Message-ID: <E472F794-6808-11D8-B1DC-000A95C4F940@sprynet.com> On Feb 25, 2004, at 7:53 PM, Don Arnold wrote: > > On Feb 25, 2004, at 3:13 PM, chekuri@uchicago.edu wrote: > >> I know what wrappers are and have programmed them during a c course, >> but I am >> new to python and cannot make heads or tails of the wxpython classes. >> wxSplashScreen seems to be the that should be used to create a splash >> screen, >> but what is the function that wraps around the constructor function of >> spashscreen from wxwindows? >> >> In brief my question is how to create a splash screen using wxpython > > Check out the demo that comes with wxPython. I don't have it installed > on this machine, but I believe it's all.py in the demo folder (not > sure of the exact path). > > HTH, > Don > Scratch that. I just realized that I'm thinking of the Pmw demo for Tkinter. Sorry for the confusion, Don From bioinfo_python at yahoo.com Wed Feb 25 23:23:29 2004 From: bioinfo_python at yahoo.com (Martin Gandhi) Date: Wed Feb 25 23:23:36 2004 Subject: [Tutor] REgular expression Message-ID: <20040226042329.81253.qmail@web61001.mail.yahoo.com> Hi group, I am a newbie to Python. I am trying to parse the content between " ". My file containts a list of 5000 vertices, please see below. I've been trying to parse the content inbetween quotes ("xxxx"). My Regular Expression: >myre = re.compile("\s\"/[a-zA-Z0-9]\"/") >m = myre.match(str) >print m.group() >None I tried several other option, but every time I get None as the answer. Could any one please help me in getting the content between quotes. A part of the file that I have to parser is pasted below: Thanks MG *Network aho2 *Vertices 5000 1 "EGFR" box 2 "Src" ellipse 3 "RIP" 4 "SHP2" 5 "SOS1" 6 "SOS2" 7 "Epiregulin" 8 "Grb2" 9 "EGF" 10 "Cbl" 12 "Caspase1" 13 "Tenascin C" 14 "G(alphai)" --------------------------------- Do you Yahoo!? Get better spam protection with Yahoo! Mail -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040225/a11cb92f/attachment.html From jimbinford at hot.rr.com Wed Feb 25 23:24:11 2004 From: jimbinford at hot.rr.com (Ian Binford) Date: Wed Feb 25 23:24:15 2004 Subject: [Tutor] File upload with Python? Message-ID: <000f01c3fc20$6291a110$3b2ec944@Binfords> Where can I find functions for web-based file upload using Python? Also, is there a way to count the number of connections to a server/directory/file by unique IP and display this number? Yours, Jim -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040225/264ef865/attachment-0001.html From syn_ack at comcast.net Thu Feb 26 00:45:24 2004 From: syn_ack at comcast.net (Joshua Banks) Date: Thu Feb 26 00:50:04 2004 Subject: [Tutor] Re: Getting "file sizes" !Sovled!! For real.. Heh..Heh.. Message-ID: <000501c3fc2b$bb9e8fb0$4202a8c0@toejam> Ok, now I've actually figured out what was really happening. I was temporarily tricked into thinking I had solved the problem. The os.path.getsize() function has no idea about the path that is the value of "a". But it is smart enough to look in the current working directory. So If I ran the script below in same directory that I was actually searching for in the script it would run fine. So the I needed a way to give os.path.getsize() the correct path to look in so that I could run from a directory other than the one parsed in the script. Here its failing: >>> import os, os.path >>> a = os.listdir('/var/log/portage') >>> for x in a: ... print x, os.path.getsize(x) ... 1782-openmotif-2.1.30-r3.log Traceback (most recent call last): File "<stdin>", line 2, in ? File "/usr/lib/python2.3/posixpath.py", line 142, in getsize return os.stat(filename).st_size OSError: [Errno 2] No such file or directory: '1782-openmotif-2.1.30-r3.log' Here its finally working correctly. import os, os.path dirname = "/var/log/portage/" a = os.listdir(dirname) for x in a: print x, os.path.getsize(dirname + x) Just had to clarify. Thanks to my brother for helping with this hair bail. Programming is no joke. It's about the most formal and anal language that I think I'll ever come acrossed. Joshua Banks From Janssen at rz.uni-frankfurt.de Thu Feb 26 05:26:38 2004 From: Janssen at rz.uni-frankfurt.de (Michael Janssen) Date: Thu Feb 26 05:26:49 2004 Subject: [Tutor] REgular expression In-Reply-To: <20040226042329.81253.qmail@web61001.mail.yahoo.com> References: <20040226042329.81253.qmail@web61001.mail.yahoo.com> Message-ID: <Pine.A41.4.56.0402261037490.56312@hermes-22.rz.uni-frankfurt.de> On Wed, 25 Feb 2004, Martin Gandhi wrote: > Hi group, > I am a newbie to Python. I am trying to parse the content between " > ". My file containts a list of 5000 vertices, please see below. I've > been trying to parse the content inbetween quotes ("xxxx"). > > My Regular Expression: > >myre = re.compile("\s\"/[a-zA-Z0-9]\"/") Hello Martin, you can simplify your regular expression by using single quotes to write the string. This way, you can use dubble quotes inside without escaping them. So you can write: '\s"/[a-zA-Z0-9]"/' The both slashes seems like perl or sed syntax for me. They have no special meaning in python. This is one reason, why you don't get a result. Perhaps you have added them, to get only the content between them as the result. In python this is done with ()-brackets. Check the Library Reference docs for all those ()-brackets stuff: http://www.python.org/doc/current/lib/re-syntax.html '[a-zA-Z0-9]' is okey but only stands for one character out of this set. You'll need to repeat this expression with (for example) '*' or '+' . > >m = myre.match(str) "match" try to find a match for the expression on the first character of the given string. What you want to have is "search": reg = re.compile('b') mt = reg.search("abc") # "b" gets found despite not in front. print mt.group() So, you'll need to replace slashes with brackets, add a repetition marker and use "search". I'm sure you will work it out from here yourself. When problems occour, feel free to ask - or report us your success :-) Michael From kiran at mhowlinux.org Thu Feb 26 07:45:39 2004 From: kiran at mhowlinux.org (kiran@mhowlinux.org) Date: Thu Feb 26 07:46:22 2004 Subject: [Tutor] Re:Comments in Python Message-ID: <002301c3fc66$75faa490$432fe2dc@VULCAN> hi,, There are two styles of comments in python # single line comment " " " this is a multiline comment which spawns many lines " " " multiline comments are also used to embed what are called doc strings in a function let me explain if u have a class say of type school class school: """ this class is useful for defining a type of school with its strength,affiliation,address etc this class has following methods and properties affilitaion() address() """ def affiliation(board): .... ... ... def address(add): ... ... ... in above piece of code the triple qouted string not only is a comment but when i declare an object say t=school and then t . __doc__ returns those comments also help(school) returns same comments gud luck -kiran Beware the lollipop of mediocrity: lick it once and you suck forever www.mhowlinux.org- Helping Linux users in Mhow hi,, There are two styles of comments in python # single line comment " " " this is a multiline comment which spawns many lines " " " multiline comments are also used to embed what are called doc strings in a function let me explain if u have a class say of type school class school: """ this class is useful for defining a type of school with its strength,affiliation,address etc this class has following methods and properties affilitaion() address() """ def affiliation(board): .... ... ... def address(add): ... ... ... in above piece of code the triple qouted string not only is a comment but when i declare an object say t=school and then t . __doc__ returns those comments also help(school) returns same comments gud luck -kiran Beware the lollipop of mediocrity: lick it once and you suck forever www.mhowlinux.org- Helping Linux users in Mhow -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040226/aa82bc57/attachment.html From kiran at mhowlinux.org Thu Feb 26 07:58:37 2004 From: kiran at mhowlinux.org (kiran@mhowlinux.org) Date: Thu Feb 26 07:59:17 2004 Subject: [Tutor] re:colors in python Message-ID: <005501c3fc68$4508aa60$432fe2dc@VULCAN> u would need either ncurses library or Wconio if u are using windows py 2.2 find attached Wconio library for py 2.2 which does it very simply like in borland turbo pascal/c simply import WConio WConio.textcolor(5) print "test" ps: works only in console mode....(black) screen not under IDLE Beware the lollipop of mediocrity: lick it once and you suck forever www.mhowlinux.org- Helping Linux users in Mhow --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.580 / Virus Database: 367 - Release Date: 2/6/2004 u would need either ncurses library or Wconio if u are using windows py 2.2 find attached Wconio library for py 2.2 which does it very simply like in borland turbo pascal/c simply import WConio WConio.textcolor(5) print "test" ps: works only in console mode....(black) screen not under IDLE Beware the lollipop of mediocrity: lick it once and you suck forever www.mhowlinux.org- Helping Linux users in Mhow --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.580 / Virus Database: 367 - Release Date: 2/6/2004 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040226/3b673b91/attachment.html From carroll at tjc.com Thu Feb 26 10:06:00 2004 From: carroll at tjc.com (Terry Carroll) Date: Thu Feb 26 10:06:05 2004 Subject: [Tutor] writing methods In-Reply-To: <20040226010403.73210.qmail@web12407.mail.yahoo.com> Message-ID: <Pine.LNX.4.44.0402260646000.18475-100000@violet.rahul.net> On Wed, 25 Feb 2004, Christopher Spears wrote: > I am trying to solve the following homework > assignment: > > Using the UserDict module, create a class called > Odict, which will be just like a dictionary but will > "remember" the order in which key/value pairs are > added to the dictionary. (Hint: Override the built-in > __setitem__ method.) Create a new method for the Odict > object called okeys, which will return the ordered > keys. > > I don't expect to get the answer, but I would like to > be pointed in the right direction. I think my major > problem is that concepts that surround writing methods > are still not transparent to me. I find myself > spending a lot of time staring at the UserDict module > code, Looking at the UserDict code probably won't help. I think you're looking at the intro to the problem ("Using the UserDict module...") and interpreting this as meaning that you should start with the UserDict module's code, and write a new class using it. I don't think so. I think it means that you should define a new class, subclassing from UserDict, i.e., the class definition line should look like this (I don't think I'm giving anything away here): import UserDict def Odict(UserDict.UserDict): [more stuff here] The problem continues, "(Hint: Override the built-in __setitem__ method.)" Okay, UserDict operates by maintaining a dictionary named "data" that includes the dictionary-type stuff. __setitem__ adds an entry. You'd have to add that entry (most easily by calling UserDict.__setitem__) *and* also maintain some additional structure that tracks the order. This assignment is not a no-brainer, but I suspect it's one of those things that you either get or don', and once the light bulb flashes, you'll get it completely. You're not asking for code (as you shouldn't), but here is a general approach I would use to take this on: 1) Override __init__, and set up another structure to track in addition to self.data, used to track the order in which things are added (probably a list, could be done other ways; make sure you invoke the __init__ you're overriding so it does its work, too). 2) Override __setitem__, so that it updates your structure, in addition to invoking UserDict's __setitem__ to do the add. 3) "Create a new method for the Odict object called okeys, which will return the ordered keys" using that structure. > Is there a good tutorial or something on the web that will clear these > concepts ups for me? Plenty; great starting points are <http://www.python.org/topics/learn/> and <http://www.python.org/doc/Intros.html>. Good luck! From syn_ack at comcast.net Thu Feb 26 10:53:45 2004 From: syn_ack at comcast.net (Joshua Banks) Date: Thu Feb 26 10:58:30 2004 Subject: [Tutor] Re: Getting "file sizes" !Sovled!! For real.. Heh..Heh.. References: <000201c3fc74$b649c680$6401a8c0@phantomfiber.com> Message-ID: <002601c3fc80$b7609740$4202a8c0@toejam> ----- Original Message ----- From: "Blake Winton" <bwinton@latte.ca> > > import os, os.path > > dirname = "/var/log/portage/" > > a = os.listdir(dirname) > > for x in a: > > print x, os.path.getsize(dirname + x) > > Just had to clarify. > Just as a side note, you might want to check out > os.path.join. You could rewrite your first example as: > import os, os.path > dirname = "/var/log/portage" # Notice the lack of a trailing / ! > a = os.listdir(dirname) > for x in a: > print x, os.path.getsize( os.path.join( dirname, x ) ) > And it might work on my system. > >>> os.path.join( "var", "log", "portage" ) > 'var\\log\\portage' > > (I'm on NT, so my path separators are different from yours. > With os.path.join, you don't have to worry about it. ;) Thanks for the response Blake. >>> dirname = os.path.join("c:", "Documents and Settings", "jj", "Desktop") >>> print dirname c:Documents and Settings\jj\Desktop Hmmmm.. This doesn't work like I thought it would... Sorry Blake... But I don't understand from reading the definition of "os.path" and your example of how this is helping in regards to my example? I'll try again below. I can use either windows or linux for testing. To recap. In my original example above I'm forcing python, (atleast I think I am), to know the ABsolute path name by adding the trailing back-slash(windows) or forward-slash(linux). This way there is no mistaking this for a file. Me being anal I guess. Any my reasoning follows: "/var/log/portage" >>>> "portage" could be a file in parent "log" directory at first glance. "/var/log/portage/" >>>> Without a doubt "portage" is a child/subdirectory of "log". Here's what I did with windows. Please tell me how "os.path.join" is suppose to help in regards to the example Im giving? Are you just saying that I don't have to use the trailing backslashes is all? Just trying to figure out the added benifits or using "os.path.join". Here's my test results. import os, os.path dirname = "c:\\Documents and Settings\\jj\\Desktop" a = os.listdir(dirname) for x in a: print x, os.path.getsize(dirname + x) Gives me: C:\Python23>python dirlist.py 99sl-english Traceback (most recent call last): File "dirlist.py", line 5, in ? print x, os.path.getsize(dirname + x) File "C:\Python23\lib\ntpath.py", line 228, in getsize return os.stat(filename).st_size OSError: [Errno 2] No such file or directory: 'c:\\Documents and Settings\\jj\\Desktop99sl-english' If I try: (using trailing backslashes) dirname = "c:\\Documents and Settings\\jj\\Desktop\\" a = os.listdir(dirname) for x in a: print x, os.path.getsize(dirname + x) This works. If I try: (without the back slashes[less typing], but [more typing] adding "os.path.join" below and removing the "+" operator. dirname = "c:\\Documents and Settings\\jj\\Desktop" a = os.listdir(dirname) for x in a: print x, os.path.getsize(os.path.join(dirname, x) This worked as well. I would like to understand this better because I'm trying to figure out how to incorparate the use of "os.path.walk" to recursively look through the specified directory structure to that it lists all subdirectories and associated files and sizes? Thanks for you help. Joshua Banks From Christian.Wyglendowski at greenville.edu Thu Feb 26 11:21:21 2004 From: Christian.Wyglendowski at greenville.edu (Christian Wyglendowski) Date: Thu Feb 26 11:21:46 2004 Subject: [Tutor] How to create a splash screen using wxpython Message-ID: <CE1475C007B563499EDBF8CDA30AB45B0A38D3@empex.greenville.edu> > On Feb 25, 2004, at 7:53 PM, Don Arnold wrote: > > > > > On Feb 25, 2004, at 3:13 PM, chekuri@uchicago.edu wrote: > > > >> I know what wrappers are and have programmed them during a > c course, > >> but I am > >> new to python and cannot make heads or tails of the > wxpython classes. > >> wxSplashScreen seems to be the that should be used to > create a splash > >> screen, > >> but what is the function that wraps around the constructor > function of > >> spashscreen from wxwindows? > >> > >> In brief my question is how to create a splash screen > using wxpython > > > > Check out the demo that comes with wxPython. I don't have > it installed > > on this machine, but I believe it's all.py in the demo folder (not > > sure of the exact path). > > > > HTH, > > Don > > > Scratch that. I just realized that I'm thinking of the Pmw demo for > Tkinter. > > Sorry for the confusion, > Don > I think this is what Don was talking about. Search for the class MySplashScreen in the file (Win32) C:\Python23\Lib\site-packages\wxPython\demo\Main.py or (Unix) /usr/lib/python2.3/site-packages/wxPython/demo/Main.py. It's right around line 95 in my copy of the file. That should show you how to do it. Christian http://www.dowski.com From syn_ack at comcast.net Thu Feb 26 11:28:36 2004 From: syn_ack at comcast.net (Joshua Banks) Date: Thu Feb 26 11:33:19 2004 Subject: [Tutor] Is there a "tutor achive with a search function"? Message-ID: <006801c3fc85$961ba570$4202a8c0@toejam> Is this the place to look? http://www.python.org/search/ I've found the "tutor list archive" but it doesn't have a search function. I have to manually look through each months archive. I've looked here: http://mail.python.org/pipermail/tutor/ no search feature. and, http://mail.python.org/pipermail/python-list/ no search feature. and, http://groups.yahoo.com/group/python-list/ this has a search feature but doesn't look upto date but I can use. I was hoping that the "tutor list" is archived somewhere that is searchable. Does anyone have links to a "searchable tutor list" ? Thanks, Joshua Banks From syn_ack at comcast.net Thu Feb 26 11:40:51 2004 From: syn_ack at comcast.net (Joshua Banks) Date: Thu Feb 26 11:50:44 2004 Subject: [Tutor] Re: Getting "file sizes" !Sovled!! For real.. Heh..Heh.. References: <003a01c3fc83$15297660$6401a8c0@phantomfiber.com> Message-ID: <007601c3fc87$4c058300$4202a8c0@toejam> ----- Original Message ----- From: "Blake Winton" <bwinton@latte.ca> > That's exactly when you would want to use os.path.join. Because > if you have: > basedir = getHomeDirectory( "jj" ) > # returns either "C:\\Documents and Settings\\jj\\" or "/home/jj/" > subdir = "Desktop" > subfile = "file.txt" > So now you want to create the path of basedir + subdir + subfile, > but that's not going to work, because you don't know what separator > to add between subdir and subfile, because you don't know which OS > you're running on. And that's where os.path.join comes in. You > can just pass it all the bits, and it will figure it out for you. > Make sense? Kindof. Heh..Heh... I guess it will make total sense once I'm able to figure out how to incorparate "os.path.walk". I'm researching that right now. Thanks for recapping on your comments though. That helps. Reading the Python Lib pdf is like reading Unix man pages. Unix/linux was cryptic at first but I got used to it. Written by engineers for engineers it seems. And it seems rightly so with all the Python doc's I have. So it will just take some time for me to get used to Python is all. Thanks for your help or any further suggestions. Joshua Banks From bvande at po-box.mcgill.ca Thu Feb 26 11:58:37 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Thu Feb 26 12:02:56 2004 Subject: [Tutor] newbie looking to avoid bad habits Message-ID: <403E25BD.7020602@po-box.mcgill.ca> Hi all, I am a Python newbie and haven't done any programing at all in over 10 years. My limited previous experience is with BASIC. Once I took a course, I found that after having programmed in BASIC on my own for a few years that I'd managed to pick up many bad habits in code structure, etc. Unfortunately, this was all long enough ago that the details are lost. I do know that I tended to produce ugly, kludgey code that worked. Working is good; pretty and working is better. I've not been using Python long enough to acquire any habits, good or bad. I've looked through the links on python.org and some other sources, too. There is plenty available. What I need is a recommendation to narrow all of that down. Could be something fairly short, though longer is OK too. Web better than paper, but paper OK too. I'm looking for something that addresses style, preferably from a relative newcomers perspective. I've been using the second ed. of Learning Python. Very good book, but so far (100 pp in) it doesn't quite meet these desiderata. And, while I've order Python in a Nutshell sight unseen, I'd be surprised if it did either. The best resource on these issues that I have found so far is "How to Think Like a Computer Scientist". But, while that seems a very good book for its audience, the pace is slow enough for me to make reading for the occasion style nugget a bit painful. I am a technical guy (I'm a philosopher working in philosophy of math and logic) with little computer application experience, so I can take a book for grown-ups, though not one for the cognoscenti. Recommendations for reading are my primary aim, but if anyone has anything to say to a newbie about 'hygiene' I'd read that gratefully too ;-) Thanks and best Brian van den Broek From syn_ack at comcast.net Thu Feb 26 12:10:09 2004 From: syn_ack at comcast.net (Joshua Banks) Date: Thu Feb 26 12:14:57 2004 Subject: [Tutor] Re: Getting "file sizes" !Sovled!! For real.. Heh..Heh.. References: <003a01c3fc83$15297660$6401a8c0@phantomfiber.com> Message-ID: <00bb01c3fc8b$63fec300$4202a8c0@toejam> ----- Original Message ----- From: "Blake Winton" <bwinton@latte.ca> > It doesn't really help in your example, because you're only going > one directory deep, but pretend you wanted to grab all the files in > all the sub-directories of jj... > > > I would like to understand this better because I'm trying to > > figure out how to incorparate the use of "os.path.walk" to > > recursively look through the specified directory structure > > to that it lists all subdirectories and associated files and > > sizes? > > That's exactly when you would want to use os.path.join. Because > if you have: > basedir = getHomeDirectory( "jj" ) > # returns either "C:\\Documents and Settings\\jj\\" or "/home/jj/" > subdir = "Desktop" > subfile = "file.txt" > So now you want to create the path of basedir + subdir + subfile, > but that's not going to work, because you don't know what separator > to add between subdir and subfile, because you don't know which OS > you're running on. And that's where os.path.join comes in. You > can just pass it all the bits, and it will figure it out for you. > Make sense? Blake can you provide me with a quick example of using os.walk.path and os.path.join using my example? I'm totally lost at this point. I thought that I understood but I'm back to droolling with a blank stare. I think I need to sign up for a Python course. import os, os.path dirname = "c:\\Documents and Settings\\jj\\Desktop\\" a = os.listdir(dirname) for x in a: print x, os.path.getsize(dirname + x) Thanks, Joshua Banks From chris at heisel.org Thu Feb 26 12:18:04 2004 From: chris at heisel.org (Chris Heisel) Date: Thu Feb 26 12:18:16 2004 Subject: [Tutor] Intercepting Form data and passing it back Message-ID: <403E2A4C.2030606@heisel.org> Hi, I've got a data form on a Web site that currently points to a CGI script of my client's CMS. I'd like to write a script that could accept the input from the data form, do some massaging and filtering of it, and then send it on to the original CGI script as a POST request. I figure I can use the cgi module to handle the incoming data from the form (who's target I'd change to point at my new script), no problem. But how would I go about sending the data back to the CGI script via POST (how it is currently sent from the form). Can I use httplib? Is there a good tutorial or information on the list or online that might help? Thanks, Chris From syn_ack at comcast.net Thu Feb 26 12:02:24 2004 From: syn_ack at comcast.net (Joshua Banks) Date: Thu Feb 26 12:57:11 2004 Subject: [Tutor] Re: Getting "file sizes" !Sovled!! For real.. Heh..Heh.. References: <007a01c3fc89$481d3a60$622aa8c0@cad> Message-ID: <00a801c3fc8a$4e616d00$4202a8c0@toejam> ----- Original Message ----- From: "Matthew Ozor" <matt@ozor.net> > Can you send me a link the Python Lib PDF? http://www.python.org/doc/2.3.3/ HTH's, Joshua Banks From deadviannou at caramail.com Thu Feb 26 14:00:00 2004 From: deadviannou at caramail.com (Djoumy . ) Date: Thu Feb 26 13:00:09 2004 Subject: [Tutor] Socket connection refused Message-ID: <1077818400016158@lycos-europe.com> ?Hi, I've managed to solve my socket problem !! That wasn't directly connected to Python programming. 2 weeks ago I've got my network card roasted, so I bought a new one and installed it with the same connexion params. Everything worked without any problem (internet, ftp, icq...) until I discovered I wasn't reachable by ping commands or anything using socket connexions. In fact, WinXP (without telling it to me...) thought the old card was still here, so it had kept its MAC address. Then no socket connexion could be opened because there was a MAC id mismatch... It took me near 1 week to find the problem but now everything's OK. Thank you all for having proposed your help, maybe I should install Linux on my computer to avoid stupid bugs like this... Djoum's ------- Message original -------? De: Joshua Banks <syn_ack@comcast.net>? Date: Wed, 25 Feb 2004 14:58:28 -0800? Sujet: Re: Re: [Tutor] Socket connection refused? Hi Djoumy, I'm not new to networking but new to Python. Could you please send me your code. I've since deleted your orginal email with the attatched code. I have Linux, Win2k and WinXP here at home that I can test with. All running Python 2.3.3. I'm pretty new to python but am willing to test your code to see if I run into any of the same problems that your having. Just zip up the code and send it to my email address and let me know what directions are needed to execute the test. I believe there's a server.py and client.py app that your testing with. I can even packet sniff and capture the client server interaction to help further diagnose what the possible connection problem could be if there is one for me. If I don't run into any problems I will have a packet sniff/capture of what a good client-sever connection should look like that you can look at. Have you ever used Ethereal before? If not, I can show you how if you would like. Having a packet sniffing tool can be very helpful in isolating where a network problem lives.. Once you can isolate where the problem is then you can spend more energy in the correct area.Thats if your test comprises of two physical machines trying to communicate with eachother. If the client and server app are both installed on the same machine then I wont be to big of a help. All I could do is just test too see if I get the same results. Do you have an Instant Messenger client installed that you can use to chat with? This will help speed the trouble shooting process up. I have Yahoo Instant Messenger installed on my end. Let me know how you would like to proceed Djoumy? Sorry.. Not familar with your mail client. So I can't help shed any light in that area. Joshua Banks Votre e-mail et vos SMS vous suivent sur Minitel : 3615 CARAMAIL From bwinton at latte.ca Thu Feb 26 13:07:40 2004 From: bwinton at latte.ca (Blake Winton) Date: Thu Feb 26 13:07:47 2004 Subject: [Tutor] Re: Getting "file sizes" !Sovled!! For real.. Heh..Heh.. In-Reply-To: <00bb01c3fc8b$63fec300$4202a8c0@toejam> Message-ID: <003b01c3fc93$6cf7d840$6401a8c0@phantomfiber.com> > Blake can you provide me with a quick example of using > os.walk.path and os.path.join using my example? Sadly, no, because I'm insanely busy at work, and because I don't use os.path.walk all that often, so I don't remember how to use it. Hopefully one of the other tutors will jump in to the discussion now, and show you something simple to understand, which still being very powerful. ;) I can give you this modification to your example, though: > import os, os.path > dirname = "c:\\Documents and Settings\\jj\\Desktop\\" > a = os.listdir(dirname) > for x in a: > print x, os.path.getsize(dirname + x) import os, os.path dirname = "c:\\Documents and Settings\\jj\\Desktop\\" a = os.listdir(dirname) for x in a: fullPath = os.path.join( dirname, x ); if os.path.isdir( fullPath ): b = os.listdir( fullPath ) for y in b: fullSubPath = os.path.join( dirname, x, y ) print x, "->" , y, os.path.getsize( fullSubPath ) print x, os.path.getsize( os.path.join( dirname, x ) ) does that help at all? Later, Blake. From syn_ack at comcast.net Thu Feb 26 13:24:42 2004 From: syn_ack at comcast.net (Joshua Banks) Date: Thu Feb 26 13:29:22 2004 Subject: [Tutor] Socket connection refused References: <1077818400016158@lycos-europe.com> Message-ID: <010301c3fc95$cdfe0810$4202a8c0@toejam> Glad to here you have this figured out. I know how frustrating things like this can be. In regards to Linux, Linux is a whole nother world of learning, reading and mailing lists. Its a great learning experience though. Everything relating to computers has thier fare share of bugs though, to include Linux. Joshua Banks From nick at javacat.f2s.com Thu Feb 26 13:35:17 2004 From: nick at javacat.f2s.com (Nick Lunt) Date: Thu Feb 26 13:35:56 2004 Subject: [Tutor] Socket connection refused In-Reply-To: <010301c3fc95$cdfe0810$4202a8c0@toejam> References: <1077818400016158@lycos-europe.com> <010301c3fc95$cdfe0810$4202a8c0@toejam> Message-ID: <20040226183517.15f7e547@phatbox.local> I have to second what Joshua says on the linux front, it can be quite a learning curve. The main advantage of linux over windows in the current 'internet age' is I don't have to keep patching my os to keep virus' out, whereas the gf is so busy updating software and running anti virus apps on her XP box I'm surprised she has time to actually do any work on it :) Glad you've solved the problem ;) Nick. On Thu, 26 Feb 2004 10:24:42 -0800 "Joshua Banks" <syn_ack@comcast.net> wrote: > Glad to here you have this figured out. I know how frustrating things > like this can be. In regards to Linux, Linux is a whole nother world > of learning, reading and mailing lists. Its a great learning > experience though. Everything relating to computers has thier fare > share of bugs though, to include Linux. > > Joshua Banks > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From syn_ack at comcast.net Thu Feb 26 13:39:32 2004 From: syn_ack at comcast.net (Joshua Banks) Date: Thu Feb 26 13:44:26 2004 Subject: [Tutor] Re: Getting "file sizes" !Sovled!! For real.. Heh..Heh.. References: <003b01c3fc93$6cf7d840$6401a8c0@phantomfiber.com> Message-ID: <010901c3fc97$e05935f0$4202a8c0@toejam> I'll actually start a new thread for my os.walk confusion. Thanks Blake. I'm pretty busy too. Sorry for being on the lazy side. All my free time is spent reading Python documentation. So any little pointers help of which you've helped allot. The code example worked for the most part. Although it only went one layer deeper into the given directory structure. Thats cool though. This is helping me get my brain to start thinking differently about programming. Thanks again, Joshua Banks ----- Original Message ----- From: "Blake Winton" <bwinton@latte.ca> > I can give you this modification to your example, though: > > import os, os.path > > dirname = "c:\\Documents and Settings\\jj\\Desktop\\" > > a = os.listdir(dirname) > > for x in a: > > print x, os.path.getsize(dirname + x) > > import os, os.path > dirname = "c:\\Documents and Settings\\jj\\Desktop\\" > a = os.listdir(dirname) > for x in a: > fullPath = os.path.join( dirname, x ); > if os.path.isdir( fullPath ): > b = os.listdir( fullPath ) > for y in b: > fullSubPath = os.path.join( dirname, x, y ) > print x, "->" , y, os.path.getsize( fullSubPath ) > print x, os.path.getsize( os.path.join( dirname, x ) ) > > does that help at all? > > Later, > Blake. > From syn_ack at comcast.net Thu Feb 26 13:56:08 2004 From: syn_ack at comcast.net (Joshua Banks) Date: Thu Feb 26 14:01:01 2004 Subject: [Tutor] Socket connection refused References: <1077818400016158@lycos-europe.com><010301c3fc95$cdfe0810$4202a8c0@toejam> <20040226183517.15f7e547@phatbox.local> Message-ID: <011001c3fc9a$322c40f0$4202a8c0@toejam> ----- Original Message ----- From: "Nick Lunt" > The main advantage of linux over windows in the current 'internet age' > is I don't have to keep patching my os to keep virus' out, whereas the > gf is so busy updating software and running anti virus apps on her XP > box I'm surprised she has time to actually do any work on it :) LOL... to funny Nick. Yes, I forgot to mention that I've never had virus problems with linux. That was actually one of the main reasons I started to learn with linux. Not to mention, everything is free to include support if you the patients. I run a startfull firewall, interanl dns-caching server, web and ftp. All free and secure for the most part except for the Windows viruses that come through email sometimes. Joshua Banks From jeffpeery at yahoo.com Thu Feb 26 14:36:51 2004 From: jeffpeery at yahoo.com (Jeff Peery) Date: Thu Feb 26 14:36:56 2004 Subject: [Tutor] (no subject) Message-ID: <20040226193651.31038.qmail@web60102.mail.yahoo.com> hi, I have a little problem. I'm just learning python and I downloaded the latest windows installer 2.3.3 I ran the executable and installed everything correctly. I'm running widows xp. the programs are all in the start menu, I can see the command line executable and the IDLE executable and the help files. all of these things work except for the IDLE executable. If I choose it, my computer thinks for a bit (the hour glass shows up) then nothing happens???? any ideas of how I can make it work? thanks!! Jeff -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040226/ee4006eb/attachment.html From dyoo at hkn.eecs.berkeley.edu Thu Feb 26 15:07:59 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Feb 26 15:08:08 2004 Subject: [Tutor] Is there a "tutor achive with a search function"? In-Reply-To: <006801c3fc85$961ba570$4202a8c0@toejam> Message-ID: <Pine.LNX.4.44.0402261205110.5193-100000@hkn.eecs.berkeley.edu> On Thu, 26 Feb 2004, Joshua Banks wrote: > I've found the "tutor list archive" but it doesn't have a search > function. I have to manually look through each months archive. [some text cut] > I was hoping that the "tutor list" is archived somewhere that is > searchable. Does anyone have links to a "searchable tutor list" ? Hi Joshua, Try the searchable archive from Activestate: http://aspn.activestate.com/ASPN/Mail/Browse/Threaded/python-Tutor Hope this helps! From SWidney at LasVegasNevada.GOV Thu Feb 26 15:18:55 2004 From: SWidney at LasVegasNevada.GOV (Scott Widney) Date: Thu Feb 26 15:19:18 2004 Subject: [Tutor] newbie looking to avoid bad habits Message-ID: <0E5508EBA1620743B409A2B8365DE16F0FCB88E1@sovereign.ci.las-vegas.nv.us> > Date: Thu, 26 Feb 2004 11:58:37 -0500 > From: Brian van den Broek <bvande@po-box.mcgill.ca> > Subject: [Tutor] newbie looking to avoid bad habits > To: Tutor@python.org > Message-ID: <403E25BD.7020602@po-box.mcgill.ca> > Content-Type: text/plain; charset=us-ascii; format=flowed > > Hi all, > > > I'm looking for something that addresses style, preferably from > a relative newcomers perspective. This may no be what you are looking for, but there is a document titled the Python Style Guide: http://www.python.org/doc/essays/styleguide.html -- see what you think. Scott From alex at alexnewby.com Thu Feb 26 16:35:22 2004 From: alex at alexnewby.com (Alex Newby) Date: Thu Feb 26 16:36:45 2004 Subject: [Tutor] Re: newbie looking to avoid bad habits Message-ID: <1077831322.23650.181722611@webmail.messagingengine.com> Hi Brian, You may find the PEPS on python-style useful http://www.python.org/peps/pep-0000.html Python tends to take care of a lot of good style for you, indentation, etc. Hygiene isn't my forte (kidding ;-) Sincerely, Alex Newby http://alexnewby.com Message: 1 Date: Thu, 26 Feb 2004 11:58:37 -0500 From: Brian van den Broek <bvande@po-box.mcgill.ca> Subject: [Tutor] newbie looking to avoid bad habits To: Tutor@python.org Message-ID: <403E25BD.7020602@po-box.mcgill.ca> Content-Type: text/plain; charset=us-ascii; format=flowed Hi all, I am a Python newbie and haven't done any programing at all in over 10 years. My limited previous experience is with BASIC. Once I took a course, I found that after having programmed in BASIC on my own for a few years that I'd managed to pick up many bad habits in code structure, etc. Unfortunately, this was all long enough ago that the details are lost. I do know that I tended to produce ugly, kludgey code that worked. Working is good; pretty and working is better. I've not been using Python long enough to acquire any habits, good or bad. I've looked through the links on python.org and some other sources, too. There is plenty available. What I need is a recommendation to narrow all of that down. Could be something fairly short, though longer is OK too. Web better than paper, but paper OK too. I'm looking for something that addresses style, preferably from a relative newcomers perspective. I've been using the second ed. of Learning Python. Very good book, but so far (100 pp in) it doesn't quite meet these desiderata. And, while I've order Python in a Nutshell sight unseen, I'd be surprised if it did either. The best resource on these issues that I have found so far is "How to Think Like a Computer Scientist". But, while that seems a very good book for its audience, the pace is slow enough for me to make reading for the occasion style nugget a bit painful. I am a technical guy (I'm a philosopher working in philosophy of math and logic) with little computer application experience, so I can take a book for grown-ups, though not one for the cognoscenti. Recommendations for reading are my primary aim, but if anyone has anything to say to a newbie about 'hygiene' I'd read that gratefully too ;-) Thanks and best Brian van den Broek ------------------------------ From cspears2002 at yahoo.com Thu Feb 26 17:56:19 2004 From: cspears2002 at yahoo.com (Christopher Spears) Date: Thu Feb 26 17:56:27 2004 Subject: [Tutor] __setitem__ Message-ID: <20040226225619.75669.qmail@web12407.mail.yahoo.com> What does __setitem__ do? From reading the docs, I think it has something to do with setting values in a class. -Chris ===== "I'm the last person to pretend that I'm a radio. I'd rather go out and be a color television set." -David Bowie "Who dares wins" -British military motto "The freak is the norm." - "The Infernal Desire Machines of Dr. Hoffman" by Angela Carter From glingl at aon.at Thu Feb 26 18:09:58 2004 From: glingl at aon.at (Gregor Lingl) Date: Thu Feb 26 18:09:08 2004 Subject: [Tutor] (no subject) In-Reply-To: <20040226193651.31038.qmail@web60102.mail.yahoo.com> References: <20040226193651.31038.qmail@web60102.mail.yahoo.com> Message-ID: <403E7CC6.7000205@aon.at> Jeff Peery schrieb: > hi, I have a little problem. I'm just learning python and I downloaded > the latest windows installer 2.3.3 I ran the executable and installed > everything correctly. I'm running widows xp. the programs are all in > the start menu, I can see the command line executable and the IDLE > executable and the help files. all of these things work except for > the IDLE executable. If I choose it, my computer thinks for a bit > (the hour glass shows up) then nothing happens???? any ideas of how I > can make it work? thanks!! > Hi Jeff! This is not a little problem since IDLE is a very useful tool when learning Python. Try the following: localize the directory where idle.py is stored. If you did a standard install it should be C:\Python23\Lib\idlelib else there are probably another drive and/or some dirs preceding the Python23. Open a cmd - window, go to the idlelib - dir: c:>cd \Python23\Lib\idlelib Then let Python execute idle: c:\Python23\Lib\idlelib> c:\Python23\python idle.py What happens? Do you get an error message? Which one? Let us know. Gregor > Jeff > >------------------------------------------------------------------------ > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > From glingl at aon.at Thu Feb 26 18:23:31 2004 From: glingl at aon.at (Gregor Lingl) Date: Thu Feb 26 18:22:36 2004 Subject: [Tutor] __setitem__ In-Reply-To: <20040226225619.75669.qmail@web12407.mail.yahoo.com> References: <20040226225619.75669.qmail@web12407.mail.yahoo.com> Message-ID: <403E7FF3.2000708@aon.at> Hi Christopher! >What does __setitem__ do? From reading the docs, I >think it has something to do with setting values in a >class. > > ... hmmm... better: in an object ... Let's see ... >-Chris > > > First an example: >>> class A: def __init__(self, n): self.data = [0]*n # a list of n zeros def __setitem__(self, i, val): self.data[i] = val def __getitem__(self, i): return self.data[i] >>> a=A(10) >>> a[3]="huuu!" >>> for i in range(5): print a[i] 0 0 0 huuu! 0 >>> Conclusion: if a class A defines the special method __setitem__ it makes the expression a[i] meaningful for any instance a of A. So you can set values via an index. Of cours you must provide correctness: >>> a[12]="outch!" Traceback (most recent call last): File "<pyshell#13>", line 1, in -toplevel- a[12]="outch!" File "<pyshell#7>", line 5, in __setitem__ self.data[i] = val IndexError: list assignment index out of range >>> This doesn't work, since the data attribute has length 10 only. In the same way the __getitem__ special method lets you access the components of a.data via the [...] - operator. Do you have some previous experience with procramming with classes in Python? If not, tinkering with special methods isnot a very good starting point, I think ... Regards, Gregor >===== >"I'm the last person to pretend that I'm a radio. I'd rather go out and be a color television set." >-David Bowie > >"Who dares wins" >-British military motto > >"The freak is the norm." - "The Infernal Desire Machines of Dr. Hoffman" by Angela Carter > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > From syn_ack at comcast.net Thu Feb 26 18:40:23 2004 From: syn_ack at comcast.net (Joshua Banks) Date: Thu Feb 26 18:45:03 2004 Subject: [Tutor] Is there a "tutor achive with a search function"? References: <Pine.LNX.4.44.0402261205110.5193-100000@hkn.eecs.berkeley.edu> Message-ID: <013e01c3fcc1$e7bac2d0$4202a8c0@toejam> ----- Original Message ----- From: "Danny Yoo > Try the searchable archive from Activestate: > http://aspn.activestate.com/ASPN/Mail/Browse/Threaded/python-Tutor Thanks Danny. Joshua Banks From missive at hotmail.com Thu Feb 26 18:48:13 2004 From: missive at hotmail.com (Lee Harr) Date: Thu Feb 26 18:48:18 2004 Subject: [Tutor] Re: File upload with Python? Message-ID: <BAY2-F10477bieLYCT40000d084@hotmail.com> >Where can I find functions for web-based file upload using Python? > >Also, is there a way to count the number of connections to a = >server/directory/file by unique IP and display this number? > Please send only plain text to the list (not html) Depends. Do you want to upload files? http://python.org/doc/current/modindex.html http://python.org/doc/current/lib/module-ftplib.html http://python.org/doc/current/lib/module-urllib2.html Or do you want to start a server? http://python.org/doc/current/lib/module-BaseHTTPServer.html http://www.twistedmatrix.com/ Logging connections can be done. The details will depend on which server you are using. _________________________________________________________________ Add photos to your e-mail with MSN 8. Get 2 months FREE*. http://join.msn.com/?page=features/featuredemail From jpmiller at tds.net Thu Feb 26 20:03:16 2004 From: jpmiller at tds.net (Joshua P. Miller) Date: Thu Feb 26 20:03:48 2004 Subject: [Tutor] Re: Intercepting Form data and passing it back Message-ID: <403E9754.8080402@tds.net> You can post data to the CGI script by using the urllib module. As long as you have maintained the field names associated with the form data, you could use those to create a dictionary (using the field names and the values associated with them as key/value pairs) and then use the urllib module to do something like this: import urllib params = { name1 : value1, name2 : value2, name3 : value3 ... } params = urllib.urlencode(params) urllib.urlopen("http://www.client.com/cgi-bin/script.cgi", params) That's just a basic example. You can do a lot more with the urllib module, including reading the output from the CGI script that you are posting data to. If you really want to fine tune what is sent to the server/script, you could learn the HTTP protocol and manually send the headers and form data using the socket module. http://www.python.org/doc/2.3.3/lib/module-urllib.html Joshua P. Miller jpmiller@tds.net From rob at jam.rr.com Thu Feb 26 20:05:50 2004 From: rob at jam.rr.com (Rob Andrews) Date: Thu Feb 26 20:05:03 2004 Subject: [Tutor] IDLE/XP In-Reply-To: <20040226193651.31038.qmail@web60102.mail.yahoo.com> References: <20040226193651.31038.qmail@web60102.mail.yahoo.com> Message-ID: <403E97EE.4050500@jam.rr.com> In the arena of Windows, one option is always to uninstall and then reinstall, paying careful attention to any details that might make an impact in functionality. And with XP, security settings can also be an issue. For instance, was Python installed and configured while logged into the machine with Administrator powers? When I read your problem, I downloaded Python 2.3.3 as a limited-privileges user, then logged in as a user with Administrator privileges to handle the installation (using default install options). Logging back in as a limited-privilege user, I was able to run IDLE without incident. Can you think of any details that might stand out on your end? -Rob Jeff Peery wrote: > hi, I have a little problem. I'm just learning python and I downloaded > the latest windows installer 2.3.3 I ran the executable and installed > everything correctly. I'm running widows xp. the programs are all in > the start menu, I can see the command line executable and the IDLE > executable and the help files. all of these things work except for the > IDLE executable. If I choose it, my computer thinks for a bit (the hour > glass shows up) then nothing happens???? any ideas of how I can make it > work? thanks!! From david at graniteweb.com Thu Feb 26 23:45:36 2004 From: david at graniteweb.com (David Rock) Date: Thu Feb 26 23:45:43 2004 Subject: [Tutor] newbie looking to avoid bad habits In-Reply-To: <403E25BD.7020602@po-box.mcgill.ca> References: <403E25BD.7020602@po-box.mcgill.ca> Message-ID: <20040227044536.GA29738@wdfs.graniteweb.com> * Brian van den Broek <bvande@po-box.mcgill.ca> [2004-02-26 11:58]: > Hi all, > > I'm looking for something that addresses style, preferably from a > relative newcomers perspective. I've been using the second ed. of > Learning Python. Very good book, but so far (100 pp in) it doesn't > quite meet these desiderata. And, while I've order Python in a > Nutshell sight unseen, I'd be surprised if it did either. A good place to start is straight from the horse's mouth, so to speak: http://www.python.org/doc/essays/styleguide.html You will get a good list of style suggestions from Google with a search on: python style code > Recommendations for reading are my primary aim, but if anyone has > anything to say to a newbie about 'hygiene' I'd read that > gratefully too ;-) On the whole, python is somewhat self-regulating as far as keeping your code from being too messy. In a lot of ways, you have to try to make ugly code ;-) -- David Rock david@graniteweb.com From Janssen at rz.uni-frankfurt.de Fri Feb 27 08:31:20 2004 From: Janssen at rz.uni-frankfurt.de (Michael Janssen) Date: Fri Feb 27 08:31:37 2004 Subject: [Tutor] __setitem__ In-Reply-To: <20040226225619.75669.qmail@web12407.mail.yahoo.com> References: <20040226225619.75669.qmail@web12407.mail.yahoo.com> Message-ID: <Pine.A41.4.56.0402271238370.18004@hermes-22.rz.uni-frankfurt.de> On Thu, 26 Feb 2004, Christopher Spears wrote: > What does __setitem__ do? From reading the docs, I > think it has something to do with setting values in a > class. Hi Christopher, as Gregor stated: it's more for setting values on an object. A class is what a programmer uses to create objects. The point of my post is to name the tool that helps to regocnize what "__setitem__ or all those __methods__ of an object" might be: >>> my_object = {} # creating a new dictionary >>> dir(my_object) # looking "into" this object [snip: complete list of methods that a python dicts have. Try it out] Here you will see, that a dictionary has several special methods like __setitem__ and several not-that-special methods like keys or get . The special methods are what do the dictionaries functionality, when you work "via syntax" on the dictionary: >>> my_object["no such key"] # uses __getitem__ internally >>> my_object["a new key"] = 0 # uses __setitem__ >>> if "a new key" in my_object: # __contains__ (? not sure) The other normal methods are just used as is: my_object.keys() You can also do: >>> my_object.__getitem__("no such keys") >>> my_object.__setitem__("a new key") and so on. This way you name the special methods directly. Effect is the same than using syntax stuff. What UserDict basically does is to create an internal real dictionary ("real" in contrast to "User"-Dict) within __init__: def __init__(self, dict=None): self.data = {} if dict is not None: self.update(dict) then UserDict maps all special methods and normal methods to the ones of the internally used dict. E.G. __setitem__ : def __setitem__(self, key, item): self.data[key] = item here UserDict.__setitems__ gets translated/mapped via syntax into __setintem__ of the internally used dictionary self.data . And the same for all other methods. What's the good of UserDict? It's the simplest way to override some methods without the need of reimplementing all other method, because UserDict has allready done it for you. "overriding" can be done by Subclassing: class My_UserDict(UserDict.UserDict): def __setitem__(self, key, item): print "you've asked me to insert %s in key: %s" \ % (item, key) print "since I don't do it, this is just for" print "educational purpose" my_dict = My_UserDict() my_dict["set a key, try to..."] = 0 # won't work but print a message my_dict.keys() # this and all other methods works as normal # try also "dir(my_dict)": no visible difference to dir({}) So, I hope it's getting clearer to everyone what "__special_methods__" means and how to override them. Now you should have a better chance to find the solution for ordered keys :-) Michael From cspears2002 at yahoo.com Fri Feb 27 11:30:37 2004 From: cspears2002 at yahoo.com (Christopher Spears) Date: Fri Feb 27 11:36:38 2004 Subject: [Tutor] __setitem__ In-Reply-To: <Pine.A41.4.56.0402271238370.18004@hermes-22.rz.uni-frankfurt.de> Message-ID: <20040227163037.22752.qmail@web12407.mail.yahoo.com> Thanks! I do have a question though regarding this statement: > A class is > what a programmer uses to create objects. This is confusing to me because I always thought of classes as another type of data object like strings or dictionaries except a class is an object that can hold variables, functions, etc. like a file (which is also seen as an data object by Python, right?). -Chris From chekuri at uchicago.edu Fri Feb 27 13:28:33 2004 From: chekuri at uchicago.edu (chekuri@uchicago.edu) Date: Fri Feb 27 13:28:40 2004 Subject: [Tutor] using wxSPlashScreen? Message-ID: <1077906513.403f8c51d7dfe@webmail-b.uchicago.edu> I had been referred to lib/splashscreen class in response to a previous question on creation of splash screen.The documentation states that the class has been deprecated.I am trying to use wxSPlashScreen class to create a splash Screen. Here is what I have come up with so far. Help me out with understanding the inheritance in python by this practical example. #import all modules from wxPython from wxPython.wx import * #define a class SplashScreen that inherits wxSplashScreen class SplashScreen(wxSplashScreen): # Default = defined default value for the given variable def __init__(self,bitmapfile,splashStyle,milliseconds,parent,id, pos = Default,size = Default,style = Default): #I am calling the __init__ method of wxSplashScreen as the- #constructor is not inherited automatically # Although wxWindows defines the constructor as receiving #a wxBitMap object as first argument Can we use a # bit map file string? wxSplashScreen.__init_(self,bitMapPath, wxSPLASH_CENTER_ON_SCREEN,6000,None,-1) class splashApp(wxApp): def OnInit(self): wxInitAllImageHandlers() #make an instance of SplashScreen) splash = SplashScreen("file.bmp",wxSPLASH_CENTER_ON_SCREEN_,6000,None,-1) splash.Show(true) splash.SetTopWindow(splash) return true def main(): appinstance = splashApp(0) appinstance.MainLoop() if__name__ == '__main__' main() My questions? while running in debug mode, it says wxSPLASH_CENTER_ON_SCREEN is not defined? but it is a valid argument in wxWindows How do I set up a bit map into the splash screen Does any one have an example of using the wxSplashScreen class; not the one in lib/splashscreen which apparently is deprecated. Some of these might be basic but I am new to python and have programming experience in c (only a quarter worth) Thanks satyam From shitizb at yahoo.com Fri Feb 27 13:29:08 2004 From: shitizb at yahoo.com (Shitiz Bansal) Date: Fri Feb 27 13:29:17 2004 Subject: [Tutor] Print query in python Message-ID: <20040227182908.36369.qmail@web41508.mail.yahoo.com> Hi, How do i query my printer about particular print jobs and their details using python or command line options? Can anybody tell me which package to use? Thanx in advance Shitiz --------------------------------- Do you Yahoo!? Get better spam protection with Yahoo! Mail -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040227/082dbb0a/attachment.html From cspears2002 at yahoo.com Fri Feb 27 13:43:35 2004 From: cspears2002 at yahoo.com (Christopher Spears) Date: Fri Feb 27 13:43:45 2004 Subject: [Tutor] TypeError Message-ID: <20040227184335.8422.qmail@web12404.mail.yahoo.com> I entered the following code and got an error: >>> import UserDict >>> a = UserDict() Traceback (most recent call last): File "<pyshell#3>", line 1, in -toplevel- a = UserDict() TypeError: 'module' object is not callable What does this mean? I am trying to use the UserDict class, which is is located in the UserDict module. When I normally assign a class to a variable, the above syntax works. This is especially frustrating to me because I know I was able to do this yesterday. From dyoo at hkn.eecs.berkeley.edu Fri Feb 27 14:00:12 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Feb 27 14:00:31 2004 Subject: [Tutor] TypeError In-Reply-To: <20040227184335.8422.qmail@web12404.mail.yahoo.com> Message-ID: <Pine.LNX.4.44.0402271057590.21381-100000@hkn.eecs.berkeley.edu> On Fri, 27 Feb 2004, Christopher Spears wrote: > I entered the following code and got an error: > > >>> import UserDict > >>> a = UserDict() > > Traceback (most recent call last): > File "<pyshell#3>", line 1, in -toplevel- > a = UserDict() > TypeError: 'module' object is not callable > > What does this mean? I am trying to use the UserDict class, which is is > located in the UserDict module. Hi Chris, Try saying: a = UserDict.UserDict() The reason for this is because a module like "UserDict" can hold more than a single class. What you may have done earlier might have been something like: ### from UserDict import UserDict a = UserDict() ### where the 'from' statement allows us to pull a single thing out of a module. Hope this helps! From hcohen2 at comcast.net Fri Feb 27 13:00:05 2004 From: hcohen2 at comcast.net (hcohen2) Date: Fri Feb 27 14:03:54 2004 Subject: [Tutor] TypeError In-Reply-To: <20040227184335.8422.qmail@web12404.mail.yahoo.com> References: <20040227184335.8422.qmail@web12404.mail.yahoo.com> Message-ID: <403F85A5.6040103@comcast.net> Christopher Spears wrote: >I entered the following code and got an error: > > > >>>>import UserDict >>>>a = UserDict() >>>> >>>> You are using a function or class in UserDict without identifying the owning module. a = UserDict.UserDict() #assuming the latter is a defined method/function it should now work. However had you from UserDict import UserDict it should then work. Besides not being the preferred import syntax, if later you wanted another function/class from this module it would be unknown. >Traceback (most recent call last): > File "<pyshell#3>", line 1, in -toplevel- > a = UserDict() >TypeError: 'module' object is not callable > >What does this mean? I am trying to use the UserDict >class, which is is located in the UserDict module. >When I normally assign a class to a variable, the >above syntax works. This is especially frustrating to >me because I know I was able to do this yesterday. > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > From dyoo at hkn.eecs.berkeley.edu Fri Feb 27 16:28:31 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Feb 27 16:28:40 2004 Subject: [Tutor] __setitem__ [classes and functions] In-Reply-To: <20040227163037.22752.qmail@web12407.mail.yahoo.com> Message-ID: <Pine.LNX.4.44.0402271301550.1653-100000@hkn.eecs.berkeley.edu> On Fri, 27 Feb 2004, Christopher Spears wrote: > Thanks! I do have a question though regarding this statement: > > > A class is what a programmer uses to create objects. > > This is confusing to me because I always thought of classes as another > type of data object like strings or dictionaries except a class is an > object that can hold variables, functions, etc. like a file (which is > also seen as an data object by Python, right?). Hi Chris, Here's one perspective that might help: A class is, in some aspects, very similar to a function. Functions are things that we can manipulate: ### >>> def makeEmptyDictionary(): ... return {} ... >>> makeEmptyDictionary <function makeEmptyDictionary at 0x8158a5c> ### One neat thing about objects in Python is that they can be squirreled away in lists or dictionaries: ### >>> [makeEmptyDictionary, makeEmptyDictionary] [<function makeEmptyDictionary at 0x8158a5c>, <function makeEmptyDictionary at 0x8158a5c>] ### This isn't as useless as it might first appear: a variation of this is a core idea behind the "switch" statement in other programming languages. For example, the following snippet: ### >>> def add(x, y): return x + y ... >>> def sub(x, y): return x - y ... >>> def math_eval(operation, x, y): ... dispatch_table = { '+': add, ... '-': sub } ... if operation in dispatch_table: ... operator = dispatch_table[operation] ... return operator(x, y) ... else: ... print "I don't know about", operation ... return None ... >>> math_eval('+', 3, 17) 20 >>> math_eval('-', 49, 17) 32 >>> math_eval('-', 49, 7) 42 ### uses a dictionary whose keys are functions. (Sorry for the detour! *grin*) Anyway, so functions are objects. But not only can these functions can also be stored or passed around, but they can also be called ("applied"): ### >>> makeEmptyDictionary() {} ### And this function "calling" is traditionally what we usually do with functions, and we usually expect a function call to return back to us some object. It turns out that since functions are objects, it's perfectly possible to have a function whose return value is itself a function: ### >>> def getOperator(operation): ... dispatch_table = { '+': add, ... '-': sub } ... if operation in dispatch_table: ... return dispatch_table[operation] ... else: ... print "I don't know about", operation ... return None ... >>> getOperator("+") <function add at 0x8159704> >>> getOperator("-") <function sub at 0x81584c4> ### but let's not get into that too deeply yet. *grin* Anywa, so just as we defined a function, we can create a class: ### >>> class MyClass: ... def __init__(self): ... pass ... >>> MyClass <class __main__.MyClass at 0x8158b4c> ### This class, too, is itself an object, and can be passed around as parameters, stored in lists, and returned by functions: ### >>> def getSomeClass(password): ... if password == 'foo': ... return MyClass ... else: ... print "No, you need to say the magic word." ... return None ... >>> c = getSomeClass('foo') >>> c <class __main__.MyClass at 0x8158b4c> ### And just as we did that math_eval() example by pulling out the right function from a dictionary, we can do something similar with classes! We can keep a list of classes in some dictionary, and return any particular class. These classes, too, can be applied, and their return values: ### >>> MyClass() <__main__.MyClass instance at 0x8154254> >>> >>> >>> c() <__main__.MyClass instance at 0x8154264> ### ... are "instances". The return value that comes off a class is itself another object, but we try to be more formal about it can call it an "instance" to further describe the thing we're getting back. An "instance" is a label we attach to object that's was born by a class. Anyway, hope this helps! From cspears2002 at yahoo.com Fri Feb 27 18:13:30 2004 From: cspears2002 at yahoo.com (Christopher Spears) Date: Fri Feb 27 18:13:39 2004 Subject: [Tutor] what is an object? Message-ID: <20040227231330.92377.qmail@web12407.mail.yahoo.com> Thanks for everybody who has been replying to my posts. These posts have been really helpful to me (and hopefully to others too). I have a very fundamental question to ask. What exactly is an object? A part of my understands what an object is, but I cannot articulate this to another person. -Chris From glingl at aon.at Fri Feb 27 18:20:46 2004 From: glingl at aon.at (Gregor Lingl) Date: Fri Feb 27 18:19:52 2004 Subject: [Tutor] __setitem__ [classes and functions] In-Reply-To: <Pine.LNX.4.44.0402271301550.1653-100000@hkn.eecs.berkeley.edu> References: <Pine.LNX.4.44.0402271301550.1653-100000@hkn.eecs.berkeley.edu> Message-ID: <403FD0CE.1010608@aon.at> Danny Yoo schrieb:... >>>>def math_eval(operation, x, y): >>>> >>>> >... dispatch_table = { '+': add, >... '-': sub } >... if operation in dispatch_table: >... operator = dispatch_table[operation] >... return operator(x, y) >... else: >... print "I don't know about", operation >... return None >... > > >>>>math_eval('+', 3, 17) >>>> >>>> >20 > > >>>>math_eval('-', 49, 17) >>>> >>>> >32 > > >>>>math_eval('-', 49, 7) >>>> >>>> >42 >### > >uses a dictionary whose keys are functions. (Sorry for the detour! >*grin*) > > I only see functions as *values* of the dictionary... or what do you mean? (BTW, do functions count as "immutable objects", so they in principle can be used as dictionary keys?) Gregor From glingl at aon.at Fri Feb 27 19:23:52 2004 From: glingl at aon.at (Gregor Lingl) Date: Fri Feb 27 19:22:58 2004 Subject: [Tutor] what is an object? In-Reply-To: <20040227231330.92377.qmail@web12407.mail.yahoo.com> References: <20040227231330.92377.qmail@web12407.mail.yahoo.com> Message-ID: <403FDF98.5060102@aon.at> Christopher Spears schrieb: > I have a very >fundamental question to ask. What exactly is an >object? A part of my understands what an object is, >but I cannot articulate this to another person. > > > Hmm, the most fundamental questions tend to be the most difficult ones to answer. So I'm certainly not the right person for this and were it only because of my limited ability to express my thoughts in proper English. Nevertheless I'll try to give you a few (unordered) remarks. There are certainly others on the list, who will give you more complete and more "exact" answers. (0) I assume you want to know what an object in Python is - not in real life (ore in some other computer language - the concepts differ ...) (1) In Python (nearly) everything is an object. or (1') An object is the representation of some*thing* you can think of, or you can find in the real world, in your computer. (2) examples: 3 "huu" True [1,2,3] {} len What means nearly? The following is *not* an object *but* a statement: class A: def __init__(self, name): self.name=name def whoareyou(self): print self.name But if this statement is executed by the Python interpreter you have - the possibility to produce new objects: obj1 = A("Frank") obj2 = A("Jude") now obj1 and obj2 are objects. - and you've got another new object: A sorry, this is a class-object. (I'm anxious that we now are at a point, where further explanation will make things make more unclear than clear - and that beeing content with a more superficial explanation ist the right thing here ...) If you think of something to be an object, you always can use the built-in function type to determine which type (sort) of object it is: >>> type(True) <type 'bool'> >>> type(3) <type 'int'> >>> type("huu") <type 'str'> >>> type(True) <type 'bool'> >>> type([1,2,3]) <type 'list'> >>> type({}) <type 'dict'> >>> type(len) <type 'builtin_function_or_method'> >>> class A: def __init__(self,name): self.name=name def whoareyou(self): print self.name >>> obj1 = A("Frank") >>> obj2 = A("Jude") >>> type(obj1) <type 'instance'> >>> type(A) <type 'classobj'> >>> One disitinction you should observe is the difference between built-in objects - "types" - an user defined objects produced by a user defined class. Since nearly everything is an object, it'?s hard to chracterize objects because there are so much differen flavours. Perhaps what is important to note is: many of them can take part on operations like +, *, etc.... or as you saw operations with [] like a[0] .... Many of them have attributes. (a) instance attributes (which are not "callable") >>> obj1.name 'Frank' (b) and methods, which represent the ability of objects to perform some tasks and are essentially functions bound to their objects ... >>> obj2.whoareyou() Jude >>> "hoo gaz gar".split() ['hoo', 'gaz', 'gar'] Think about this now, read more answers certainly to come from others and think about them for a few days. Then determine what you want to clarify next and come back with your next "objects-centered" question. Regards, Gregor >-Chris > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > From cspears2002 at yahoo.com Fri Feb 27 19:26:11 2004 From: cspears2002 at yahoo.com (Christopher Spears) Date: Fri Feb 27 19:26:17 2004 Subject: [Tutor] indexing with a class Message-ID: <20040228002611.86383.qmail@web12406.mail.yahoo.com> I am trying to create a class in the UserDict module that will remember the order in which I enter keys. Here is an example of an attempt to solve this problem: class ODict(UserDict): def __setitem__(self, key, item): counter = 0 self.data[key] = item counter = counter + 1 self.order = [(key,counter)] The idea was to have the class generate a list of tuples that have the key and the order that key was entered, i.e. [('key1',1),('key2',2),...etc]. But when I went for a test run, I got this result (UserDict2 is a copy of the UserDict module. I wanted to work with a copy instead of the original for safety.): >>> import UserDict2 >>> dict = {} >>> a = UserDict2.ODict(dict) >>> a['test'] = 1 >>> a.order [('test', 1)] >>> a['another test'] = 2 >>> a {'test': 1, 'another test': 2} >>> a.order [('another test', 1)] This has been my first major stumbling block. When I use the class, it keeps overwriting any counters, etc. that I use. Maybe a better way is to pass some sort of result to a function under the ODict class? Right now, I just have: class ODict(UserDict): def __setitem__(self, key, item): counter = 0 self.data[key] = item counter = counter + 1 self.order = [(key,counter)] def okeys(self): print order This won't work, so my second stumbling block is how to do I get this class to pass some sort of useful result when I use the __setitem__ special method. Any hints? From sigurd at 12move.de Fri Feb 27 21:21:37 2004 From: sigurd at 12move.de (=?iso-8859-1?q?Karl_Pfl=E4sterer?=) Date: Fri Feb 27 21:26:03 2004 Subject: [Tutor] indexing with a class In-Reply-To: <20040228002611.86383.qmail@web12406.mail.yahoo.com> (Christopher Spears's message of "Fri, 27 Feb 2004 16:26:11 -0800 (PST)") References: <20040228002611.86383.qmail@web12406.mail.yahoo.com> Message-ID: <m3brnkkm0v.fsf@hamster.pflaesterer.de> On 28 Feb 2004, Christopher Spears <- cspears2002@yahoo.com wrote: > I am trying to create a class in the UserDict module > that will remember the order in which I enter keys. If you use a newer Python (newer 2.2 IIRC you can subclass dict()). > Here is an example of an attempt to solve this > problem: > class ODict(UserDict): > def __setitem__(self, key, item): > counter = 0 > self.data[key] = item > counter = counter + 1 > self.order = [(key,counter)] I see here several problems: (a) you don't show us the __init__ method (b) above you create always a new list but I think you wanted to append the new values to an existing list (c) the data you give is redundant; counter is implicit in the index of the value in the list; so there no need to store it. (d) With overwriting __setitem__ you solve only a part of the problem (hint: try to create a dict with a sequence of tuples (as key, value pairs) as input. You won't find these values in your list. > The idea was to have the class generate a list of > tuples that have the key and the order that key was > entered, i.e. [('key1',1),('key2',2),...etc]. See above what I wrote. > But when I went for a test run, I got this result > (UserDict2 is a copy of the UserDict module. I wanted > to work with a copy instead of the original for > safety.): There's no need for that; you never change an existing module by only importing it. [...] > This has been my first major stumbling block. When I > use the class, it keeps overwriting any counters, etc. > that I use. Above I wrote why that happens. Initialice your list as an empty list (perhaps taking care of the cases when you gave an argument to the dictionary when you created it) and append() new values. > Maybe a better way is to pass some sort of result to a > function under the ODict class? Right now, I just > have: > class ODict(UserDict): > def __setitem__(self, key, item): > counter = 0 > self.data[key] = item > counter = counter + 1 > self.order = [(key,counter)] > def okeys(self): > print order > This won't work, so my second stumbling block is how > to do I get this class to pass some sort of useful > result when I use the __setitem__ special method. Any hints? It depends what you regard as useful results? Do you want to see the list whenever you entered a new value to the dict? You could write: def __setitem__ (self, key, value): . . . self.order.append(key) return self.order But the more difficult part is IMO to take care of all the ways you can create a dict with some values given. >>> dict(a=1, b=2, c=3) {'a': 1, 'c': 3, 'b': 2} >>> dict([('a', 1),('b', 2), ('c', 3)]) {'a': 1, 'c': 3, 'b': 2} >>> dict({'a':1, 'b':2}) {'a': 1, 'b': 2} __setitem__ won't get called in any of these cases (at least with userDict) Karl -- Please do *not* send copies of replies to me. I read the list From alan.gauld at blueyonder.co.uk Sat Feb 28 03:55:15 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Feb 28 03:54:25 2004 Subject: [Tutor] colored text output to Windows console References: <403C0261.2090903@columbus.rr.com> Message-ID: <007401c3fdd8$953ad550$6401a8c0@xp> > I have written a text mode game that keeps track of 3 lists. I would like for > the output of the game to use colors to make it easier for the user to read the > text. Kind of like what is seen on an ANSI BBS. > > From my initial research, it seems this impossible to do in a Windows 'DOS box'. It is possible but the user must load the ANSI.SYS device driver, usually in the CONFIG.SYS file. This allows you to embed standard ANSI codes into your print strings and thus change the colours(16 possible) and attributes(bold, underline etc). In the days of Windows, editing CONFIG.SYS is probably too much to ask users so either you need to create an "installer" that does it for them or write a simple GUI wrapper round your console mode code. Alan G From dyoo at hkn.eecs.berkeley.edu Sat Feb 28 04:50:42 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Feb 28 04:50:52 2004 Subject: [Tutor] __setitem__ [classes and functions] In-Reply-To: <403FD0CE.1010608@aon.at> Message-ID: <Pine.LNX.4.44.0402280137330.7738-100000@hkn.eecs.berkeley.edu> > >uses a dictionary whose keys are functions. (Sorry for the detour! > >*grin*) > > > > > I only see functions as *values* of the dictionary... or what do you > mean? Doh. I knew I should have gotten more coffee in the morning. I meant to say "value", but blurted out "key" for some reason. > (BTW, do functions count as "immutable objects", so they in principle > can be used as dictionary keys?) Hmmm...interesting question! Let me check something: ### >>> def addOne(x): return x + 1 ... >>> def addTwo(x): return x + 2 ... >>> d = {addOne: 1, ... addTwo: 2} >>> >>> d {<function addOne at 0x60470>: 1, <function addTwo at 0x60a70>: 2} ### Wow, the answer to that appears to be yes! But this is probably not as applicable as the original example, because different functions will have different hash values, even if they have the same body: ### >>> hash(lambda x: x) 394352 >>> hash(lambda x: x) 395888 ### The "hash" value of a function is probably calculated based on the function's location in memory, and that will limit the usefulness of a function as a dictionary key. Hope this helps! From Janssen at rz.uni-frankfurt.de Sat Feb 28 10:19:54 2004 From: Janssen at rz.uni-frankfurt.de (Michael Janssen) Date: Sat Feb 28 10:20:07 2004 Subject: [Tutor] __setitem__ In-Reply-To: <20040227163037.22752.qmail@web12407.mail.yahoo.com> References: <20040227163037.22752.qmail@web12407.mail.yahoo.com> Message-ID: <Pine.A41.4.58.0402281547340.18854@stupool24.rz.uni-frankfurt.de> On Fri, 27 Feb 2004, Christopher Spears wrote: > [Michael] > > A class is > > what a programmer uses to create objects. > > This is confusing to me because I always thought of > classes as another type of data object like strings or > dictionaries except a class is an object that can hold > variables, functions, etc. Yes, you're right, classes are objects, too. What I have thinking about must have been something like: when you want to create your own object (e.g. a dictionary with ordered keys) you have to use classes which in turn means that you have to start with writing >>> class SomeWhat: ... """Example do nothing class""" ... pass after that "SomeWhat" is a class object. But you won't do something to it via __setitem__ but rather write down a __setitem__ method while typing in your class. Once the class is turned from textual represention into an object by the mighty interpreter __setitem__ don't do something for the class but will do something for the objects instantiated from this class. To bring it into one sentence: >>> SomeWhat.__setitem__("key", "value") is completly nonsense (... running a fast test ... yes its nonsense ;-) while >>> instance_of_somewhat.__setitem__("key", "value") is sensible (after adding a __setitem__ method of course) So this is why I belive that classes are indeed objects but you can't do much with them than subclassing and instantiating. So I should have written that classes are used to create objects with behaviour defined by the programmer. Hey, I'm still curious if you find the ordered key solution. *Please* mail use after you've get it :-) Michael From bvande at po-box.mcgill.ca Sat Feb 28 10:42:45 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sat Feb 28 10:41:35 2004 Subject: [Tutor] Re: newbie looking to avoid bad habits Message-ID: <4040B6F5.5070609@po-box.mcgill.ca> Hi all, thanks to Scott Widney, Alex Newby, and David Rock for the refs., etc. (Sorry if I missed anyone and for thread-breaking -- I'm on digest.) The python.org style guides are some help, thanks. For what it's worth, http://www.python.org/peps/pep-0008.html is the better looking of the two versions of "Guido on Style". I've yet to do the suggested google search. If I find anything that seems really good, I will post about it. In retrospect, I guess my question stands a good chance of being unanswerable. When I teach formal logic, some students always ask how to go about writing good proofs. The only thing that can really be said to them is "read proofs, write proofs, and you will begin to be able to tell good proofs from bad. (Wax on. Wax off.)" In the end, I guess my question likely has the same answer. Thanks again. Best to all, Brian van den Broek From guillermo.fernandez at epfl.ch Sat Feb 28 11:34:29 2004 From: guillermo.fernandez at epfl.ch (Guillermo Fernandez) Date: Sat Feb 28 11:34:54 2004 Subject: [Tutor] Adding to python path In-Reply-To: <think001_403b77f084d8f@webmail.thinkware.se> References: <think001_403b77f084d8f@webmail.thinkware.se> Message-ID: <4040C315.9070406@epfl.ch> Thanks for the answer, works great! :-) Isn't there any way off adding that code (sys.path.append('../lib')) only one, outside the scripts, for example in an __init__.py file in the scripts directory? Thanks, Guille Magnus Lycka wrote: >>How could the scripts in the scripts/ folder use the modules of the lib/ folder >>if they must be called as normal programs? > > > import sys > sys.path.append('../lib') > > ..methinks. Another option is to place the lib code in the > standard site-packages directory. > > >>Structure of my program: >>bego.py >>lib/ >> begohandler.py >> mac.py >> ... >> syslogdb.py >>scripts/ >> matlab.py >> ... >> arrow.py > > > From carroll at tjc.com Sat Feb 28 14:24:24 2004 From: carroll at tjc.com (Terry Carroll) Date: Sat Feb 28 14:24:30 2004 Subject: [Tutor] indexing with a class In-Reply-To: <m3brnkkm0v.fsf@hamster.pflaesterer.de> Message-ID: <Pine.LNX.4.44.0402281123190.20053-100000@violet.rahul.net> On Sat, 28 Feb 2004, Karl Pfl?sterer wrote: > On 28 Feb 2004, Christopher Spears <- cspears2002@yahoo.com wrote: > > > I am trying to create a class in the UserDict module > > that will remember the order in which I enter keys. > > If you use a newer Python (newer 2.2 IIRC you can subclass dict()). I was going to mention that before, but, as Christopher related it, the constraint on this homework problem was to use UserDict. -- Terry Carroll Santa Clara, CA carroll@tjc.com From carroll at tjc.com Sat Feb 28 15:23:26 2004 From: carroll at tjc.com (Terry Carroll) Date: Sat Feb 28 15:23:31 2004 Subject: [Tutor] indexing with a class In-Reply-To: <20040228002611.86383.qmail@web12406.mail.yahoo.com> Message-ID: <Pine.LNX.4.44.0402281136240.20053-100000@violet.rahul.net> On Fri, 27 Feb 2004, Christopher Spears wrote: > I am trying to create a class in the UserDict module > that will remember the order in which I enter keys. > Here is an example of an attempt to solve this > problem: > > class ODict(UserDict): > def __setitem__(self, key, item): > counter = 0 > self.data[key] = item > counter = counter + 1 > self.order = [(key,counter)] > > The idea was to have the class generate a list of > tuples that have the key and the order that key was > entered, i.e. [('key1',1),('key2',2),...etc]. > > But when I went for a test run, I got this result > (UserDict2 is a copy of the UserDict module. I wanted > to work with a copy instead of the original for > safety.): > >>> import UserDict2 > >>> dict = {} > >>> a = UserDict2.ODict(dict) > >>> a['test'] = 1 > >>> a.order > [('test', 1)] > >>> a['another test'] = 2 > >>> a > {'test': 1, 'another test': 2} > >>> a.order > [('another test', 1)] This looks like what you'd expect. Let's run through this. First time through _setitem_: > def __setitem__(self, key, item): key is "test", "item" is 1. Other variables (counter, self.order) are not yet in use. > counter = 0 counter is 0 > self.data[key] = item self.data["test"] is 1; that is: self.data is {"test":1} > counter = counter + 1 counter is 1 > self.order = [(key,counter)] self.order is [("test",1)] Now you reach the end. Second time: > def __setitem__(self, key, item): key is "another test"; item is 2. The variable counter is not yet in use, and self.order still has [("test",1)] from last time. > counter = 0 counter is 0 > self.data[key] = item self.data["another test"] is 2; that is: self.data is {"test":1, "another test":2} > counter = counter + 1 counter is 1 > self.order = [(key,counter)] self.order is [("another test", 1)] It looks to me like you have a few thing here; first, you expect, counter to retain its value between calls. It won't. But note that the self.variables do. If you really want to retain variable values across invocations, they need to be variables within the object itself. The best way to do this is in an __init__ method, which you do not show. Second, you overwrite your list of tuples in each run, instead of modifying it. You should probably use list.append() to append a new entry. Of course, you can't append to a list that doesn't exist, so your first run-through, when the list needs to be created, is problematic. The way I would go at this is to initialize it to an empty list in __init__, and append to it in the __setitem__. As an aside, I don't see why you'd want to maintain a counter and put that into the list anyway. The way you're looking at it, the first entry would have "1" for the stored count, the second "2", the third "3", etc. Why store the count? If you'll need to give back the items by the order in which they were added, it is better (and easier, too) to just use the order of the list. So, your "order" list should just end up like this: ["test", "another test", "yet another test"], etc. Finally, this line of yours scares me: > (UserDict2 is a copy of the UserDict module. I wanted > to work with a copy instead of the original for > safety.): I am pretty sure that the nature of your assignment is *not* to take the UserDict.py file and modify it. I'm willing to be that, when the assignment says to "use the UserDict module" (or whatever the exact words were, that your instructor meant to use it to subclass from. This seems pretty clear from the hint that __setitem__ should be overridden (as opposed to being modified. I strongly suggest you seek clarification on this from your instructor. I'm pretty sure he or she is not expecting you to take the Python UserDict module and edit it. In general, if you're subclassing form an existing module, (say you're writing a class bar based on the existing class foo) is something like this: def bar(foo): def __init__(self, other params): foo.__init__(self, other params) # invoke the superclass's init [all my additional __init__ type stuff goes here] def __another_method__(self, other params) foo.__another_method__(self, other params) # invoke superclass's method For your case, I suggest your definitions look something like this: def ODict(UserDict.UserDict): def __init__(self, dict=None, **kwargs) UserDict.UserDict.__init__(self, dict=None, **kwargs) YOUR ADDITIONAL __init__ CODE GOES HERE def __setitem__(self, key, item): UserDict.UserDict.__setitem__(self, key, item) YOUR ADDITIONAL __setitem__ CODE GOES HERE I hope this helps. -- Terry Carroll Santa Clara, CA carroll@tjc.com Modell delendus est From sandip at linux-delhi.org Sat Feb 28 18:11:56 2004 From: sandip at linux-delhi.org (Sandip Bhattacharya) Date: Sat Feb 28 18:16:22 2004 Subject: [Tutor] Reading text lines from a socket Message-ID: <sqj7h1-efj.ln1@pluto.home> The socket objects only allow data to be read in by chunks (recv()). How do I manage to read in data one line at a time where a line is defined as a lf/cr-lf terminated test string? In other words how can one write their own clients for reading/writing data for text based protocols like smtp? Thanks, Sandip -- Sandip Bhattacharya sandip (at) puroga.com Puroga Technologies Pvt. Ltd. Work: http://www.puroga.com Home: http://www.sandipb.net GPG: 51A4 6C57 4BC6 8C82 6A65 AE78 B1A1 2280 A129 0FF3 From red_necks25 at yahoo.com Sat Feb 28 18:16:29 2004 From: red_necks25 at yahoo.com (moore william) Date: Sat Feb 28 18:16:33 2004 Subject: [Tutor] Email in GUI Message-ID: <20040228231629.41683.qmail@web13602.mail.yahoo.com> I am trying to add email to a GUI program. Does anyone have an toutorial on how this is done? __________________________________ Do you Yahoo!? Get better spam protection with Yahoo! Mail. http://antispam.yahoo.com/tools From sandip at linux-delhi.org Sat Feb 28 18:26:33 2004 From: sandip at linux-delhi.org (Sandip Bhattacharya) Date: Sat Feb 28 18:30:38 2004 Subject: [Tutor] Re: what is an object? In-Reply-To: <20040227231330.92377.qmail@web12407.mail.yahoo.com> References: <20040227231330.92377.qmail@web12407.mail.yahoo.com> Message-ID: <amk7h1-cgj.ln1@pluto.home> Christopher Spears wrote: > fundamental question to ask. What exactly is an > object? A part of my understands what an object is, > but I cannot articulate this to another person. > There is a general Object-Oriented answer, and then there is a python answer. ;) Fundamentally, an object is a distinct entity or an instance of a class of types. So if humans are a class of living beings, Christopher Spears is an instance of the human class and can therefore be considered an "object". ;) Similarly, if you have a class named AClass then the following creates two instances/objects of the same class. a = AClass() b = AClass() This is how most OO based programming languages like C++/Java define objects. However, python extends the term "object" further - in Python even the types are considered objects! So in the above example, even AClass is condered an object! Even string literals ("String"), lists ([]), etc are called as objects! - Sandip -- Sandip Bhattacharya sandip (at) puroga.com Puroga Technologies Pvt. Ltd. Work: http://www.puroga.com Home: http://www.sandipb.net GPG: 51A4 6C57 4BC6 8C82 6A65 AE78 B1A1 2280 A129 0FF3 From pythontutor at venix.com Sat Feb 28 18:34:33 2004 From: pythontutor at venix.com (Lloyd Kvam) Date: Sat Feb 28 18:34:54 2004 Subject: [Tutor] Reading text lines from a socket In-Reply-To: <sqj7h1-efj.ln1@pluto.home> References: <sqj7h1-efj.ln1@pluto.home> Message-ID: <40412589.40704@venix.com> Sockets deal with packetized data. The network protocols do not guarantee keeping the data in line oriented chunks - even if the data starts out that way. You need to deal with extracting lines from chunks. So long as the connection is working properly, this is easy. The challenge occurs when the remainder of a line never gets delivered. The best strategy depends upon the details of what you are doing. Sandip Bhattacharya wrote: > The socket objects only allow data to be read in by chunks (recv()). How > do I manage to read in data one line at a time where a line is defined > as a lf/cr-lf terminated test string? > > In other words how can one write their own clients for reading/writing > data for text based protocols like smtp? > > Thanks, > > Sandip > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From sandip at linux-delhi.org Sat Feb 28 19:19:36 2004 From: sandip at linux-delhi.org (Sandip Bhattacharya) Date: Sat Feb 28 19:23:57 2004 Subject: [Tutor] Re: Reading text lines from a socket In-Reply-To: <40412589.40704@venix.com> References: <sqj7h1-efj.ln1@pluto.home> <40412589.40704@venix.com> Message-ID: <opn7h1-mij.ln1@pluto.home> [Reposting to the general list too] Lloyd Kvam wrote: > Sockets deal with packetized data. The network protocols do not guarantee > keeping the data in line oriented chunks - even if the data starts out > that way. > > You need to deal with extracting lines from chunks. So long as the > connection is > working properly, this is easy. The challenge occurs when the remainder > of a line > never gets delivered. The best strategy depends upon the details of > what you are > doing. I understand that. In Python using sockets is like using sockets in C. However, I was looking for a python equivalent of the perl idiom of opening a socket and getting a file handle ... and then reading this file handle as any other line oriented file using $socket->readline I am trying to write a simple Netcraft style script which tries the HEAD method on a webserver and reads the Server: header from the response. I would not like to use urllib, because even a call to something like urllib.info() reads in the complete webpage on an open(). Even if this particular problem could be done elegantly, I would be interested to know the answer to my original question because the feature of reading a line at a time from a socket will help me in a lot of other places in the future. - Sandip -- Sandip Bhattacharya sandip (at) puroga.com Puroga Technologies Pvt. Ltd. Work: http://www.puroga.com Home: http://www.sandipb.net GPG: 51A4 6C57 4BC6 8C82 6A65 AE78 B1A1 2280 A129 0FF3 From pythontutor at venix.com Sat Feb 28 20:28:59 2004 From: pythontutor at venix.com (Lloyd Kvam) Date: Sat Feb 28 20:29:37 2004 Subject: [Tutor] Re: Reading text lines from a socket In-Reply-To: <opn7h1-mij.ln1@pluto.home> References: <sqj7h1-efj.ln1@pluto.home> <40412589.40704@venix.com> <opn7h1-mij.ln1@pluto.home> Message-ID: <4041405B.3070503@venix.com> Well, I've never used it, but sockets do have the makefile method. That would seem to fit what you're trying to do. Sandip Bhattacharya wrote: > [Reposting to the general list too] > > Lloyd Kvam wrote: > >> Sockets deal with packetized data. The network protocols do not >> guarantee >> keeping the data in line oriented chunks - even if the data starts out >> that way. >> >> You need to deal with extracting lines from chunks. So long as the >> connection is >> working properly, this is easy. The challenge occurs when the >> remainder of a line >> never gets delivered. The best strategy depends upon the details of >> what you are >> doing. > > > I understand that. In Python using sockets is like using sockets in C. > > However, I was looking for a python equivalent of the perl idiom of > opening a socket and getting a file handle ... and then reading this > file handle as any other line oriented file using $socket->readline > > I am trying to write a simple Netcraft style script which tries the HEAD > method on a webserver and reads the Server: header from the response. I > would not like to use urllib, because even a call to something like > urllib.info() reads in the complete webpage on an open(). > > Even if this particular problem could be done elegantly, I would be > interested to know the answer to my original question because the > feature of reading a line at a time from a socket will help me in a lot > of other places in the future. > > - Sandip > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From pythontut at pusspaws.net Sun Feb 29 07:44:12 2004 From: pythontut at pusspaws.net (Dave S) Date: Sun Feb 29 08:11:26 2004 Subject: [Tutor] getting idle to run Message-ID: <4041DE9C.9070201@pusspaws.net> Im runing gentoo1.4, python-2.3.3 +berkdb -bootstrap -build -doc +gdbm -ipv6 +ncurses +readline +ssl +tcltk -ucs2 I have some experience of basic, forth, 6502, 8051 assembler & bash .. but am just starting out on python. OK here goes ... how do I get IDLE to start ?! I am following "learning python" O'reilly. Typing "idle" from python generated a "not defined error". "import idle" generates "no module named idle" I have searched my hard drive & have found its source ... /usr/lib/python2.3/idlelib/idle.pyc /usr/lib/python2.3/idlelib/idle.pyo /usr/lib/python2.3/idlelib/idle.pyw /usr/lib/python2.3/idlelib/idle.py However I am stumped ! Its probarbly realy simple to solve - but the book glosses over this bit & a google has not faired much better. Any help much appreciated Dave From syn_ack at comcast.net Sun Feb 29 11:22:35 2004 From: syn_ack at comcast.net (Joshua Banks) Date: Sun Feb 29 11:27:16 2004 Subject: [Tutor] getting idle to run References: <4041DE9C.9070201@pusspaws.net> Message-ID: <000801c3fee0$3dfdabb0$4202a8c0@toejam> ----- Original Message ----- From: "Dave S" > OK here goes ... how do I get IDLE to start ?! Hey Dave, I run Gentoo as well. You start IDLE simply by opening a terminal and typing: idle Or you can start a Python command line by typing: python If IDLE doesn't work then that means that you need to have TKinter installed before it will run. Atleast thats what Gentoo told me when I tried to run idle. Let us know if that helps? Joshua Banks From stewart at midtoad.homelinux.org Sun Feb 29 11:45:56 2004 From: stewart at midtoad.homelinux.org (Stewart Midwinter) Date: Sun Feb 29 11:50:23 2004 Subject: [Tutor] getting idle to run In-Reply-To: <4041DE9C.9070201@pusspaws.net> References: <4041DE9C.9070201@pusspaws.net> Message-ID: <20040229094556.6a1d1c97@pc-00065.midtoad.homelinux.org> Dave, looks like you're running linux, like me. In my distro, Mandrake 9.2, I have the following menu entry: Applications | Development | Devlopment Environment | Idle So, check for that. If you don't, you could make up a desktop shortcut based on the following: open a terminal, cd to your idlelib directory, and type python idle.py Works for me, anyway! S On Sun, 29 Feb 2004 12:44:12 +0000 Dave S <pythontut@pusspaws.net> spake thusly: > OK here goes ... how do I get IDLE to start ?! -- Stewart Midwinter running on Mandrake Linux 9.2 PGP public key at: http://www.keyserver.net e-mail: Stewart 'at' Midwinter.ca, stewart 'at' midtoad.homelinux.org web: http://www.midwinter.ca, http://midtoad.homelinux.org voice: +1.403.714.4329 Umwelt schuetzen, Rad benuetzen! From orbitz at ezabel.com Sun Feb 29 12:33:25 2004 From: orbitz at ezabel.com (orbitz@ezabel.com) Date: Sun Feb 29 12:34:58 2004 Subject: [Tutor] Email in GUI In-Reply-To: <20040228231629.41683.qmail@web13602.mail.yahoo.com> References: <20040228231629.41683.qmail@web13602.mail.yahoo.com> Message-ID: <20040229123325.68f5eaf4.orbitz@ezabel.com> I doubt anyone would write a specific tutorial just for how to add e-mail to a GUI program. Why not look at the module list at python website, specifically teh SMTP one. I'm sure if you look at other module lists you'll find IMAP and POP3 modules aswell. Those should get you on the right path. On Sat, 28 Feb 2004 15:16:29 -0800 (PST) moore william <red_necks25@yahoo.com> wrote: > I am trying to add email to a GUI program. Does anyone > have an toutorial on how this is done? > > __________________________________ > Do you Yahoo!? > Get better spam protection with Yahoo! Mail. > http://antispam.yahoo.com/tools > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From cspears2002 at yahoo.com Sun Feb 29 12:59:49 2004 From: cspears2002 at yahoo.com (Christopher Spears) Date: Sun Feb 29 12:59:55 2004 Subject: [Tutor] Eureka! Message-ID: <20040229175949.72573.qmail@web12407.mail.yahoo.com> For those not familiar with my homework problem, here it is: Using the UserDict module, create a class called Odict, which will be just like a dictionary but will "remember" the order in which key/value pairs are added to the dictionary. (Hint: Override the built-in __setitem__ method.) Create a new method for the Odict object called okeys, which will return the ordered keys. I copied the UserDict module and created a module called UserDict2. Inside this module, I created the following class and definition: class ODict(UserDict): order = [] def __setitem__(self, key, item): self.data[key] = item self.order.append(key) def okeys(self): print self.order Here are the results: >>> import UserDict2 >>> dict = {} >>> a = UserDict2.ODict(dict) >>> a['a'] = 1 >>> a {'a': 1} >>> a.order ['a'] >>> a['b'] = 2 >>> a {'a': 1, 'b': 2} >>> a.order ['a', 'b'] >>> a[(1,2)] = 3 >>> a {'a': 1, (1, 2): 3, 'b': 2} >>> a.order ['a', 'b', (1, 2)] In order to access the function, do the following: >>> UserDict2.ODict.okeys(a) ['a', 'b', (1, 2)] What I created was basically a type of keys function. The order that the keys were listed in is implicit in their position in the list. I do have a question though. In the past, when I entered something like: class ODict(UserDict): order = [] def __setitem__(self, key, item): I would get some sort of error about the order variable. Can anyone explain this? I wish I remember what I wrote, but it's all a big blur to me. Should I have used __init__ to declare the order variable? What is the purpose of __init__ anyway? -Chris From pythontut at pusspaws.net Sun Feb 29 12:59:35 2004 From: pythontut at pusspaws.net (Dave S) Date: Sun Feb 29 13:26:51 2004 Subject: [Tutor] getting idle to run In-Reply-To: <4041DE9C.9070201@pusspaws.net> References: <4041DE9C.9070201@pusspaws.net> Message-ID: <40422887.7070105@pusspaws.net> Dave S wrote: > Im runing gentoo1.4, python-2.3.3 +berkdb -bootstrap -build -doc > +gdbm -ipv6 +ncurses +readline +ssl +tcltk -ucs2 > I have some experience of basic, forth, 6502, 8051 assembler & bash .. > but am just starting out on python. > > OK here goes ... how do I get IDLE to start ?! > > I am following "learning python" O'reilly. > Typing "idle" from python generated a "not defined error". > "import idle" generates "no module named idle" > > I have searched my hard drive & have found its source ... > > /usr/lib/python2.3/idlelib/idle.pyc > /usr/lib/python2.3/idlelib/idle.pyo > /usr/lib/python2.3/idlelib/idle.pyw > /usr/lib/python2.3/idlelib/idle.py > > However I am stumped ! > > Its probarbly realy simple to solve - but the book glosses over this > bit & a google has not faired much better. > > Any help much appreciated > > Dave > Thanks for all your input .. OK here goes ... I never thought of calling idle directly from bash (doh :-) ), it works great ! I was trying "import idle" from within python. Just as a side .. I decided to try python because everyone keeps recommending it. So far its pretty cool ;-) ... page 75 of 589 .. I like its style Dave From nick at javacat.f2s.com Sun Feb 29 15:05:52 2004 From: nick at javacat.f2s.com (Nick Lunt) Date: Sun Feb 29 15:05:53 2004 Subject: [Tutor] Eureka! In-Reply-To: <20040229175949.72573.qmail@web12407.mail.yahoo.com> References: <20040229175949.72573.qmail@web12407.mail.yahoo.com> Message-ID: <20040229200552.08877afa@phatbox.local> Hi Chris, Im not gonna try to answer your question because I'm not a tutor, and there are many others on here who will answer better than I could. However I'd just like to point out that in your python session code below you've used the name 'dict' as a variable, are you aware that 'dict' is a built in type ? eg >>> a = ('a','b') >>> b = ('alpha','bravo') >>> c = dict(zip(a,b)) >>> c {'a': 'alpha', 'b': 'bravo'} Try typing 'dir(dict)' at the python prompt for further info. Sorry if your already aware of that, but I thought I'd just point it out ;) Cheers Nick. On Sun, 29 Feb 2004 09:59:49 -0800 (PST) Christopher Spears <cspears2002@yahoo.com> wrote: > For those not familiar with my homework problem, here > it is: > > Using the UserDict module, create a class called > Odict, which will be just like a dictionary but will > "remember" the order in which key/value pairs are > added to the dictionary. (Hint: Override the built-in > __setitem__ method.) Create a new method for the Odict > object called okeys, which will return the ordered > keys. > > I copied the UserDict module and created a module > called UserDict2. Inside this module, I created the > following class and definition: > > class ODict(UserDict): > order = [] > def __setitem__(self, key, item): > self.data[key] = item > self.order.append(key) > def okeys(self): > print self.order > > Here are the results: > >>> import UserDict2 > >>> dict = {} > >>> a = UserDict2.ODict(dict) > >>> a['a'] = 1 > >>> a > {'a': 1} > >>> a.order > ['a'] > >>> a['b'] = 2 > >>> a > {'a': 1, 'b': 2} > >>> a.order > ['a', 'b'] > >>> a[(1,2)] = 3 > >>> a > {'a': 1, (1, 2): 3, 'b': 2} > >>> a.order > ['a', 'b', (1, 2)] > > In order to access the function, do the following: > >>> UserDict2.ODict.okeys(a) > ['a', 'b', (1, 2)] > > What I created was basically a type of keys function. > The order that the keys were listed in is implicit in > their position in the list. I do have a question > though. In the past, when I entered something like: > > class ODict(UserDict): > order = [] > def __setitem__(self, key, item): > > I would get some sort of error about the order > variable. Can anyone explain this? I wish I remember > what I wrote, but it's all a big blur to me. Should I > have used __init__ to declare the order variable? > What is the purpose of __init__ anyway? > > -Chris > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From cspears2002 at yahoo.com Sun Feb 29 16:12:25 2004 From: cspears2002 at yahoo.com (Christopher Spears) Date: Sun Feb 29 16:12:32 2004 Subject: [Tutor] importing another classes's __init__ Message-ID: <20040229211225.72049.qmail@web12404.mail.yahoo.com> I am trying to make a class called UList based on the class UserList. This is an example of how UserList works: >>> import UserList >>> list = [1,2,3] >>> a = UserList.UserList(list) >>> a [1, 2, 3] This is the code I wrote for UList: import UserList class UList(UserList.UserList): def __init__(self, initlist=None): UserList.UserList.__init__(self, initlist=None) When I tried the class out, I got: >>> import UList >>> list = [1,2,3] >>> a = UList.UList(list) >>> a [] What gives? I thought the line UserList.UserList.__init__(self, initlist=None) would import UserList's __init__ method. -Chris From magnus at thinkware.se Sun Feb 29 16:14:00 2004 From: magnus at thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sun Feb 29 16:14:12 2004 Subject: [Tutor] Eureka! In-Reply-To: <20040229175949.72573.qmail@web12407.mail.yahoo.com> Message-ID: <5.2.1.1.0.20040229220806.02400be8@www.thinkware.se> At 09:59 2004-02-29 -0800, Christopher Spears wrote: >I copied the UserDict module and created a module >called UserDict2. Inside this module, I created the >following class and definition: Why did you do that? There is no reason to copy any standard library files just because you want to subclass a class in one of them. Except the waste of disk space, it means that you'll miss bugfixes or performance improvements that others do in UserDict, and you might also waste more RAM (and CPU-time) when you run your program. Perhaps you can look in the standard libraries to see how this is normally done. For instance, you can look at the class definitions in SimpleHTTPServer.py. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From cspears2002 at yahoo.com Sun Feb 29 16:28:45 2004 From: cspears2002 at yahoo.com (Christopher Spears) Date: Sun Feb 29 16:29:01 2004 Subject: [Tutor] problem creating a subclass Message-ID: <20040229212845.60368.qmail@web12403.mail.yahoo.com> I am creating a new class based on UserList called UList. Here is the code: import UserList class UList(UserList.UserList): def __init__(self, initlist=None): UserList.UserList.__init__(self, initlist=None) When I tested the class, the following happened: >>> import UList >>> list = [1,2,3] >>> a = UList.UList(list) >>> a [] What gives? -Chris ===== "I'm the last person to pretend that I'm a radio. I'd rather go out and be a color television set." -David Bowie "Who dares wins" -British military motto "The freak is the norm." - "The Infernal Desire Machines of Dr. Hoffman" by Angela Carter From pythontutor at venix.com Sun Feb 29 17:37:34 2004 From: pythontutor at venix.com (Lloyd Kvam) Date: Sun Feb 29 17:37:32 2004 Subject: [Tutor] problem creating a subclass In-Reply-To: <20040229212845.60368.qmail@web12403.mail.yahoo.com> References: <20040229212845.60368.qmail@web12403.mail.yahoo.com> Message-ID: <404269AE.3040605@venix.com> You didn't pass the list that came in, you passed None. Christopher Spears wrote: > I am creating a new class based on UserList called > UList. Here is the code: > > import UserList > > class UList(UserList.UserList): > def __init__(self, initlist=None): ^^^^^ defines a default value > UserList.UserList.__init__(self, > initlist=None) ^^^^^ passes None You want (the slightly odd looking) initlist=initlist which will pass your variable named initlist to the argument that has the same name, initlist. > > When I tested the class, the following happened: > > >>>>import UList >>>>list = [1,2,3] >>>>a = UList.UList(list) >>>>a > > [] > > What gives? > -Chris > > ===== > "I'm the last person to pretend that I'm a radio. I'd rather go out and be a color television set." > -David Bowie > > "Who dares wins" > -British military motto > > "The freak is the norm." - "The Infernal Desire Machines of Dr. Hoffman" by Angela Carter > > _______________________________________________ > 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 cspears2002 at yahoo.com Sun Feb 29 17:39:12 2004 From: cspears2002 at yahoo.com (Christopher Spears) Date: Sun Feb 29 17:39:19 2004 Subject: [Tutor] answer to indexing problem Message-ID: <20040229223912.66143.qmail@web12405.mail.yahoo.com> Several people have asked my why did I make a copy of the UserDict module called UserDict2, which I then modified to solve my homework problem. The answer is simple:IGNORANCE. I didn't know any better. After I did this, several people have told me that modifying the module directly is a bad idea. I now know better, and for my second homework problem concerning classes, I simply created my own to file to contain the classes instead of modifying a module. -Chris ===== "I'm the last person to pretend that I'm a radio. I'd rather go out and be a color television set." -David Bowie "Who dares wins" -British military motto "The freak is the norm." - "The Infernal Desire Machines of Dr. Hoffman" by Angela Carter From nick at javacat.f2s.com Sun Feb 29 17:52:18 2004 From: nick at javacat.f2s.com (Nick Lunt) Date: Sun Feb 29 17:52:16 2004 Subject: [Tutor] problem creating a subclass In-Reply-To: <404269AE.3040605@venix.com> References: <20040229212845.60368.qmail@web12403.mail.yahoo.com> <404269AE.3040605@venix.com> Message-ID: <20040229225218.7025d0bd@phatbox.local> Maybe I'm missing something obvious here but I don't see how Chris' UList class is going to work at all. The class has no UList method, so how is 'a = UList.UList(alist)' going to work ? Nick. On Sun, 29 Feb 2004 17:37:34 -0500 Lloyd Kvam <pythontutor@venix.com> wrote: > You didn't pass the list that came in, you passed None. > > Christopher Spears wrote: > > > I am creating a new class based on UserList called > > UList. Here is the code: > > > > import UserList > > > > class UList(UserList.UserList): > > def __init__(self, initlist=None): > ^^^^^ defines a default value > > UserList.UserList.__init__(self, > > initlist=None) > ^^^^^ passes None > > You want (the slightly odd looking) initlist=initlist > which will pass your variable named initlist to the argument that > has the same name, initlist. > > > > > When I tested the class, the following happened: > > > > > >>>>import UList > >>>>list = [1,2,3] > >>>>a = UList.UList(list) > >>>>a > > > > [] > > > > What gives? > > -Chris > > > > ===== > > "I'm the last person to pretend that I'm a radio. I'd rather go out > > and be a color television set."-David Bowie > > > > "Who dares wins" > > -British military motto > > > > "The freak is the norm." - "The Infernal Desire Machines of Dr. > > Hoffman" by Angela Carter > > > > _______________________________________________ > > 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 sigurd at 12move.de Sun Feb 29 18:07:19 2004 From: sigurd at 12move.de (=?iso-8859-1?q?Karl_Pfl=E4sterer?=) Date: Sun Feb 29 18:09:54 2004 Subject: [Tutor] importing another classes's __init__ In-Reply-To: <20040229211225.72049.qmail@web12404.mail.yahoo.com> (Christopher Spears's message of "Sun, 29 Feb 2004 13:12:25 -0800 (PST)") References: <20040229211225.72049.qmail@web12404.mail.yahoo.com> Message-ID: <m3hdx9ebg3.fsf@hamster.pflaesterer.de> On 29 Feb 2004, Christopher Spears <- cspears2002@yahoo.com wrote: > I am trying to make a class called UList based on the > class UserList. This is an example of how UserList > works: Since some of your questions refer to homework I'm curious why your teacher does not use the features of modern Python but teaches you to use UserDict or UserList. [...] > import UserList > class UList(UserList.UserList): > def __init__(self, initlist=None): > UserList.UserList.__init__(self, > initlist=None) > When I tried the class out, I got: >>>> import UList >>>> list = [1,2,3] >>>> a = UList.UList(list) >>>> a > [] > What gives? I thought the line > UserList.UserList.__init__(self, initlist=None) would > import UserList's __init__ method. You made one error: class UList(UserList.UserList): > def __init__(self, initlist=None): > UserList.UserList.__init__(self, initlist=None) ^^^^^^^^^^^^ Here you set initlist explicitly to None when calling the __init__ method. Change that to simple `initlist' so __init__ gets called with whatever was given as argument to UList(). Karl -- Please do *not* send copies of replies to me. I read the list From shitizb at yahoo.com Sun Feb 29 18:20:10 2004 From: shitizb at yahoo.com (Shitiz Bansal) Date: Sun Feb 29 18:20:16 2004 Subject: [Tutor] Windows Processes Message-ID: <20040229232010.77299.qmail@web41508.mail.yahoo.com> Hi, I need to check whether a particular process is running on my windows machine or not. The code i am using is: import win32pdh processinfo,processes=win32pdh.EnumObjectItems(None,None,"Process",-1) number=processes.count('process name') if number==1: print 'ok' else: print 'notok' All i need to do is to find the number of times a particular process is running. The code works fine but the trouble is that it takes around 15 seconds to complete. Since i do not require everything the program is doing(I already have the process name so no need to enumerate all processes and the processinfo is not required) , is there a faster and more efficient way of doing this? Shitiz --------------------------------- Do you Yahoo!? Get better spam protection with Yahoo! Mail -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040229/b078c39c/attachment-0001.html From glingl at aon.at Sun Feb 29 19:11:11 2004 From: glingl at aon.at (Gregor Lingl) Date: Sun Feb 29 19:10:17 2004 Subject: [Fwd: Re: [Tutor] what is an object?] Message-ID: <40427F9F.3040709@aon.at> Betreff: Re: [Tutor] what is an object? Datum: Sun, 29 Feb 2004 07:36:08 -0800 (PST) Von: Martin Gandhi <bioinfo_python@yahoo.com> An: Gregor Lingl <glingl@aon.at> Hi Gregor, Thanks for your explnation. It was clear. However, I have one simple question that I often stumbled upon. I have read Guido's tutorial and also learning pyton and I see that every where. What exactly both semantic and logical meaning of "callable". In your explantion you mentioned that instance attributed are not "callable" Sorry for asking a lame question. It will really make a difference to understand better, though.. Thanks MG *//* From glingl at aon.at Sun Feb 29 19:32:47 2004 From: glingl at aon.at (Gregor Lingl) Date: Sun Feb 29 19:31:54 2004 Subject: [Fwd: Re: [Tutor] what is an object?] In-Reply-To: <40427F9F.3040709@aon.at> References: <40427F9F.3040709@aon.at> Message-ID: <404284AF.3020100@aon.at> Martin Ghandi schrieb: > ... I have one simple question that I often stumbled upon. I have read > Guido's tutorial and also learning pyton and I see that every where. > > What exactly both semantic and logical meaning of "callable". > > Formally an object f is called callable ;-) if you can call it using the syntax f() or f(arg1, args, ...) Semantically than means that f contains some code which is executed when f is called. There is a built in function callable, which you can use to determine if some object is callable or not: >>> callable(3) False >>> callable( [1,2,3] ) False >>> callable(len) # built-in function True >>> def fun(): print "hi" >>> callable(fun) True >>> fun() hi # Trying to call a not callable object results # in a Type error: >>> callable("hi!") False >>> "hi!"() Traceback (most recent call last): File "<pyshell#29>", line 1, in -toplevel- "hi!"() TypeError: 'str' object is not callable >>> # So if you think of callable objects, first functions come to your # mind. But classes are also callable: >>> class A: pass >>> callable(A) True >>> a = A() >>> callable(a) False # while instances of classes normally are not callable, # however you can make them callable by defining the # special method __call__: >>> class B: def __call__(self): print "hi!" >>> b = B() >>> callable(b) True >>> b() hi! # calling b, which goes like this: b(), calls b.__call__() behind the scene ;-) HTH Gregor From alan.gauld at blueyonder.co.uk Sun Feb 29 19:59:56 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Feb 29 19:59:38 2004 Subject: [Tutor] Eureka! References: <20040229175949.72573.qmail@web12407.mail.yahoo.com> Message-ID: <002001c3ff28$83b5f2a0$6401a8c0@xp> > I copied the UserDict module and created a module > called UserDict2. Inside this module, I created the > following class and definition: > > class ODict(UserDict): Why did you copy the UserDict module? You don't need to copy the module to access the class, just import it. > their position in the list. I do have a question > though. In the past, when I entered something like: > > class ODict(UserDict): > order = [] > def __setitem__(self, key, item): > > I would get some sort of error about the order > variable. Can anyone explain this? I wish I remember > what I wrote, but it's all a big blur to me. Should I > have used __init__ to declare the order variable? > What is the purpose of __init__ anyway? If you want each instance of your class to have its own order - and presumably you do! - then you need to set order, or more precisely self.order within the __init__ method. Otherwise all instances of your class will share the same order list. The purpose of init is to initialise the variables of a new object instance. Any variables you set up inside init will be unique to that instance. HTH, Alan G From alan.gauld at blueyonder.co.uk Sun Feb 29 20:02:12 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Feb 29 20:01:53 2004 Subject: [Tutor] Eureka! References: <20040229175949.72573.qmail@web12407.mail.yahoo.com> <20040229200552.08877afa@phatbox.local> Message-ID: <002701c3ff28$d45a5390$6401a8c0@xp> > Im not gonna try to answer your question because I'm not a tutor, and > there are many others on here who will answer better than I could. I'd just like to point out that anyone on the list can be "a tutor". There is no formal distinction between the taught and the teachers. If you know the answer to a question feel free to fire away! Alan G. Who is definitely not a tutor except when he is... ;-) From alan.gauld at blueyonder.co.uk Sun Feb 29 20:05:40 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Feb 29 20:05:24 2004 Subject: [Tutor] importing another classes's __init__ References: <20040229211225.72049.qmail@web12404.mail.yahoo.com> Message-ID: <002c01c3ff29$50c89310$6401a8c0@xp> > import UserList > > class UList(UserList.UserList): > def __init__(self, initlist=None): > UserList.UserList.__init__(self, > initlist=None) > > >>> a = UList.UList(list) > >>> a > [] > > What gives? I thought the line > UserList.UserList.__init__(self, initlist=None) would > import UserList's __init__ method. It doesn't import it, it calls it. And you passed a list value of None so that's what it gave you... I suspect you meant to do this: class UList(UserList.UserList): def __init__(self, initlist=None): UserList.UserList.__init__(self, initlist) Note no "=None" in the call to UserList.__init__() 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 Sun Feb 29 20:07:45 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Feb 29 20:07:27 2004 Subject: [Tutor] problem creating a subclass References: <20040229212845.60368.qmail@web12403.mail.yahoo.com> <404269AE.3040605@venix.com> Message-ID: <003501c3ff29$9b54bdf0$6401a8c0@xp> > > class UList(UserList.UserList): > > def __init__(self, initlist=None): > ^^^^^ defines a default value > > UserList.UserList.__init__(self, > > initlist=None) > ^^^^^ passes None > > You want (the slightly odd looking) initlist=initlist Actually just passing initlist will do the job fine. There is no need to explicitly assign any value. The value is coming in as an argument to UList.__init__() Alan G. From alan.gauld at blueyonder.co.uk Sun Feb 29 20:11:08 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Feb 29 20:10:50 2004 Subject: [Tutor] problem creating a subclass References: <20040229212845.60368.qmail@web12403.mail.yahoo.com><404269AE.3040605@venix.com> <20040229225218.7025d0bd@phatbox.local> Message-ID: <003c01c3ff2a$13c4a6b0$6401a8c0@xp> > Maybe I'm missing something obvious here but I don't see how Chris' > UList class is going to work at all. The class has no UList method, so > how is 'a = UList.UList(alist)' going to work ? Because this is in another file from ULIst(actually the >>> prompt). So he imported the ULIst module and is accessing the ULIst class within the UList module: import UList L = UList.Ulist() # Ulist class within Ulist module Compare with: import sys sys.exit() HTH Alan G. From carroll at tjc.com Sun Feb 29 21:21:25 2004 From: carroll at tjc.com (Terry Carroll) Date: Sun Feb 29 21:21:30 2004 Subject: [Tutor] importing another classes's __init__ In-Reply-To: <m3hdx9ebg3.fsf@hamster.pflaesterer.de> Message-ID: <Pine.LNX.4.44.0402291820240.20053-100000@violet.rahul.net> On Mon, 1 Mar 2004, Karl Pfl?sterer wrote: > On 29 Feb 2004, Christopher Spears <- cspears2002@yahoo.com wrote: > > > I am trying to make a class called UList based on the > > class UserList. This is an example of how UserList > > works: > > Since some of your questions refer to homework I'm curious why your > teacher does not use the features of modern Python but teaches you to > use UserDict or UserList. Well, if I was the instructor, I could defend that; it's instructive to be able to look at the UserDict.py and UserList.py code. From carroll at tjc.com Sun Feb 29 21:23:39 2004 From: carroll at tjc.com (Terry Carroll) Date: Sun Feb 29 21:23:43 2004 Subject: [Tutor] answer to indexing problem In-Reply-To: <20040229223912.66143.qmail@web12405.mail.yahoo.com> Message-ID: <Pine.LNX.4.44.0402291822330.20053-100000@violet.rahul.net> On Sun, 29 Feb 2004, Christopher Spears wrote: > Several people have asked my why did I make a copy of > the UserDict module called UserDict2, which I then > modified to solve my homework problem. The answer is > simple:IGNORANCE. I didn't know any better. After I > did this, several people have told me that modifying > the module directly is a bad idea. I now know better, > and for my second homework problem concerning classes, > I simply created my own to file to contain the classes > instead of modifying a module. That's great. The most wonderful thing about ignorance is that it's a curable condition. You don't want to see what some of *my* early programs looked like, when I was a student! Some of those were *really* ugly. -- Terry Carroll Santa Clara, CA carroll@tjc.com Modell delendus est