From bvande at po-box.mcgill.ca Sun Aug 1 00:15:07 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sun Aug 1 00:18:46 2004 Subject: [Tutor] redirecting help -- is this a bad idea? In-Reply-To: <6.1.0.6.0.20040731090137.028dca40@mail4.skillsoft.com> References: <410AE64C.3050107@po-box.mcgill.ca> <6.1.0.6.0.20040731090137.028dca40@mail4.skillsoft.com> Message-ID: <410C19EB.6010400@po-box.mcgill.ca> Kent Johnson said unto the world upon 31/07/2004 09:13: > Brian, > > A couple of thoughts: > > - You might consider just making your classes work well with pydoc. The > built-in help is introspecting the docstrings for the module you ask for > help on. If you write docstrings for your module, built-in help will > document it. Take a look at some library modules and the corresponding > help to see how this works. If you go this way, your help will be > integrated with the help for built-in objects, so your user won't have > to figure out which help to use. Hi Kent, thanks for the reply. I started out wanting to be good about docstrings. Then I got sloppy. The first time I read my own code a month later, I put being sloppy behind me :-) In the particular case at hand, I don't want to go the pydoc way--I want a very minimal help for a friend who would be completely off-put by the sort of things that go in docstrings. I wanted really basic "type this to do that" type stuff. Typical docstring messages wouldn't be helpful in this case. And I wanted to preserve the builtin help function under another name so that I could keep making use of it when I ran the program, too. > - If you continue down the path you show below, there is no need to > define _PyHelper. You can just assign > pyhelp = help > > Then define your own helper and assign it to help. OK, let me run that back to see if I follow the intent: Before I make my own help, the standard one is present as always. Then pyhelp = help assigns pyhelp to that standard help function, and that assignment persists even after I have done my thing to make help call my custom function? If I've got that right, then won't there be the small problem that typing pyhelp at the prompt will give the old instructions of help? (As in, it will still say "help(object) for help about object", etc.) But that won't work as expected, once I've redirected help. I'd thought I needed to use the class PyHelper just so that pyhelp would print out the new, customized way to get to the pydoc functionality. Have I misunderstood your point? Anyway, thanks for the reply. Best, Brian vdB > > BTW you are not redefining __builtin__.help when you do this, you are > shadowing it with a definition of help in the current global namespace. > > Kent > > At 08:22 PM 7/30/2004 -0400, Brian van den Broek wrote: > >> Hi all, >> >> I'm making my first use of classes and also over-riding python builtins. >> I'd like to run what I am doing by the list as a sanity check and see >> if I >> get a giant *don't do that!* back :-) >> >> What I am trying to do is create a set of programs for use by a friend >> who >> is even less computer literate than I. =-O Part of my aim is to make it >> self-documenting in an easy to use way. So, I want to redirect the help >> command to my own help function for my set of programs, while still >> preserving the normal help behaviour under another name. >> >> Having dipped into site.py to see how help was able to work both by >> typing >> "help" and by typing "help()", I saw it was implemented with a class: >> >> class _Helper: >> def __repr__(self): >> return "Type help() for interactive help, " \ >> "or help(object) for help about object." >> def __call__(self, *args, **kwds): >> import pydoc >> return pydoc.help(*args, **kwds) >> >> __builtin__.help = _Helper() >> >> >> I used this as the basis of my redirection of "help". The function that >> does the work of my help system is tell(). So I've done the following: >> >> class _Helper: >> def __repr__(self): >> return "Type help() for interactive help, " \ >> "or help(object) for help about object.\n" \ >> "(For Python's own help function, type pyhelp.)" >> def __call__(self, *args, **kwds): >> return tell(*args, **kwds) >> >> help = _Helper() >> >> class _PyHelper: >> def __repr__(self): >> return "Type pyhelp() for interactive help, " \ >> "or pyhelp(object) for help about object." >> def __call__(self, *args, **kwds): >> import pydoc >> return pydoc.help(*args, **kwds) >> >> pyhelp = _PyHelper() >> >> >> Profoundly wrong or just fine? >> >> Best, >> >> Brian vdB From kent_johnson at skillsoft.com Sun Aug 1 01:03:57 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sun Aug 1 01:04:05 2004 Subject: [Tutor] redirecting help -- is this a bad idea? In-Reply-To: <410C19EB.6010400@po-box.mcgill.ca> References: <410AE64C.3050107@po-box.mcgill.ca> <6.1.0.6.0.20040731090137.028dca40@mail4.skillsoft.com> <410C19EB.6010400@po-box.mcgill.ca> Message-ID: <6.1.0.6.0.20040731184733.028ca610@mail4.skillsoft.com> Brian, You are right on both counts. Assigning pyhelp = help makes both variables point to the same object (the original instance of _Helper). If you then rebind help to a different object, the binding to pyhelp persists. The way to think about assignment in Python is that the variable is just a reference to the actual value. Python variables are just names for values. Values have their own existence. An assignment statement binds a variable to a value. "pyhelp = help" means, "Whatever value help is bound to, bind pyhelp to the same thing." (I hope I haven't confused you too much, I don't think I'm explaining this very well.) I missed the point that your _PyHelper class has a different __repr__() than the standard one. You do need a new class if you want to change the behavior of the built-in help. At 06:15 PM 7/31/2004 -0400, Brian van den Broek wrote: >>- If you continue down the path you show below, there is no need to >>define _PyHelper. You can just assign >>pyhelp = help >>Then define your own helper and assign it to help. > >OK, let me run that back to see if I follow the intent: Before I make my >own help, the standard one is present as always. Then > >pyhelp = help > >assigns pyhelp to that standard help function, and that assignment >persists even after I have done my thing to make help call my custom function? > >If I've got that right, then won't there be the small problem that typing >pyhelp at the prompt will give the old instructions of help? (As in, it >will still say "help(object) for help about object", etc.) But that won't >work as expected, once I've redirected help. I'd thought I needed to use >the class PyHelper just so that pyhelp would print out the new, customized >way to get to the pydoc functionality. From bvande at po-box.mcgill.ca Sun Aug 1 01:36:27 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sun Aug 1 01:38:28 2004 Subject: [Tutor] redirecting help -- is this a bad idea? In-Reply-To: <6.1.0.6.0.20040731184733.028ca610@mail4.skillsoft.com> References: <410AE64C.3050107@po-box.mcgill.ca> <6.1.0.6.0.20040731090137.028dca40@mail4.skillsoft.com> <410C19EB.6010400@po-box.mcgill.ca> <6.1.0.6.0.20040731184733.028ca610@mail4.skillsoft.com> Message-ID: <410C2CFB.7010902@po-box.mcgill.ca> Kent Johnson said unto the world upon 31/07/2004 19:03: > Brian, > > You are right on both counts. > > Assigning pyhelp = help makes both variables point to the same object > (the original instance of _Helper). If you then rebind help to a > different object, the binding to pyhelp persists. > > The way to think about assignment in Python is that the variable is just > a reference to the actual value. Python variables are just names for > values. Values have their own existence. An assignment statement binds a > variable to a value. "pyhelp = help" means, "Whatever value help is > bound to, bind pyhelp to the same thing." > > (I hope I haven't confused you too much, I don't think I'm explaining > this very well.) > > I missed the point that your _PyHelper class has a different __repr__() > than the standard one. You do need a new class if you want to change the > behavior of the built-in help. Hi Kent, thanks for clarifying. Easy enough to have missed the __repr__ change. Past that, there was nothing unclear in what you said. The thing that threw me is that I'm just starting on trying to apply the OOP features of Python. While I believe I understand the ideas in the abstract just fine, the application part is a horse of an entirely different colour ;-) (It's even got me feeling less certain about aspects of Python I thought I had under control.) Anyway, thanks again and best, Brian vdB > At 06:15 PM 7/31/2004 -0400, Brian van den Broek wrote: > >>> - If you continue down the path you show below, there is no need to >>> define _PyHelper. You can just assign >>> pyhelp = help >>> Then define your own helper and assign it to help. >> >> >> OK, let me run that back to see if I follow the intent: Before I make >> my own help, the standard one is present as always. Then >> >> pyhelp = help >> >> assigns pyhelp to that standard help function, and that assignment >> persists even after I have done my thing to make help call my custom >> function? >> >> If I've got that right, then won't there be the small problem that >> typing pyhelp at the prompt will give the old instructions of help? >> (As in, it will still say "help(object) for help about object", etc.) >> But that won't work as expected, once I've redirected help. I'd >> thought I needed to use the class PyHelper just so that pyhelp would >> print out the new, customized way to get to the pydoc functionality. From alan.gauld at blueyonder.co.uk Sun Aug 1 10:39:42 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Aug 1 10:39:31 2004 Subject: [Tutor] Understanding DBAPI cursor.execute References: <200407311007.19763.jfabiani@yolo.com><1091297663.5417.22.camel@laptop.venix.com> <200407311333.37915.jfabiani@yolo.com> Message-ID: <01d501c477a3$178ce220$6401a8c0@xp> > thanks I think I understand the quoting issue. But you suggested that I > should follow "MySQLdb requirements in formating the parameters.". Where do > I find such information In the MySql documentation. > and this implies that not all DBAPI modules are NOT > the same. NO it implies that the SQL formatting requirements used by each DB is slightly different. That's why you should use the DBAPI to do the formatting. > I thought the purpose of the DBAPI was to create a standard > interface??? I'm guessing it failed or the params issue was not addressed. It does. But when you use Python string formatting you are bypassing the module and taking responsibility for formatting upon yourself. cursor.execute("SELECT FOO FROM %s" % 'BAR') Is exactly the same to the DBAPI as cursor.execute("SELECT FOO FROM BAR") ie a hard coded string. If you want the DBAPI module to do its stuff you must pass the data in as parameters: cursor.execute("SELECT FOO FROM %s", 'BAR') By using Python formatting for the SQL string you are effectively bypassing all the DBAPI formatting code. Alan G. From alan.gauld at blueyonder.co.uk Sun Aug 1 10:48:27 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Aug 1 10:48:15 2004 Subject: [Tutor] redirecting help -- is this a bad idea? References: <410AE64C.3050107@po-box.mcgill.ca><6.1.0.6.0.20040731090137.028dca40@mail4.skillsoft.com> <410C19EB.6010400@po-box.mcgill.ca> Message-ID: <01de01c477a4$500c45e0$6401a8c0@xp> > pyhelp = help > > assigns pyhelp to that standard help function, and that assignment > persists even after I have done my thing to make help call my custom function? Yes because the old help is a name bound to a help function *object* The assignment simply binds another new name to that same function object. > pyhelp at the prompt will give the old instructions of help? No problem because pyhelp is still pointing at the original help object, not your new one. > work as expected, once I've redirected help. You redirect the name help but that doesn't change the underlying original help object. Try some ASCII art: Before: pyHelp -------> [ original help function ] ^ | help --------------- After: pyHelp -------> [ original help function ] help ---------> [ New help class ] Does that help? > Have I misunderstood your point? You just got confused about how Python handles names and function objects. Alan g. From rdm at rcblue.com Sun Aug 1 14:20:48 2004 From: rdm at rcblue.com (Dick Moores) Date: Sun Aug 1 14:22:00 2004 Subject: [Tutor] Why does counting to 20 million stress my computer? In-Reply-To: <017101c46ea2$56996fb0$6401a8c0@xp> References: <017101c46ea2$56996fb0$6401a8c0@xp> Message-ID: <6.1.2.0.2.20040801041441.02c0bec0@rcblue.com> At 14:41 7/20/2004, Alan Gauld wrote: > > So xrange is definitely quicker. Is it better to use xrange all the >time in > > place of range then ? > >I haven't checked but my guess is that for small values range will be >faster >because it holds all the values in RAM and indexing will be faster >than >calculation. > >But if in doubt try it out... >And tell us the result! Thanks to Kent Johnson's post of 7/29 I discovered the timeit module, and was able to compare counting with range() vs. counting with xrange() for much smaller numbers than a million. Alan Gauld's guess is correct: range() is faster counting to numbers less than 30,000 or so; however, from just below 1000 down to 1, xrange() is faster. Here the script I used: ===================================== #SpinSpeeds.py def countUsingRange(n): for i in range(n): pass def countUsingXrange(n): for i in xrange(n): pass if __name__=='__main__': from timeit import Timer repetitions = 1000 n = 25000 t = Timer("countUsingRange(25000)", "from __main__ import countUsingRange") rangeTime = t.timeit(repetitions) t = Timer("countUsingXrange(25000)", "from __main__ import countUsingXrange") xrangeTime = t.timeit(repetitions) print " range(%d) time = %f for %d repetitions" % (n, rangeTime, repetitions) print "xrange(%d) time = %f for %d repetitions" % (n, xrangeTime, repetitions) ========================================== This gets: range(30000) time = 2.902619 for 1000 repetitions xrange(30000) time = 3.064199 for 1000 repetitions some other results: range(10000000) time = 12.296007 for 10 repetitions xrange(10000000) time = 9.133722 for 10 repetitions range(1000000) time = 11.747225 for 100 repetitions xrange(1000000) time = 10.285452 for 100 repetitions range(100000) time = 11.334980 for 1000 repetitions xrange(100000) time = 10.022997 for 1000 repetitions range(50000) time = 10.775690 for 2000 repetitions xrange(50000) time = 9.947329 for 2000 repetitions range(40000) time = 8.305034 for 2000 repetitions xrange(40000) time = 8.039629 for 2000 repetitions range(20000) time = 7.343917 for 4000 repetitions xrange(20000) time = 7.936993 for 4000 repetitions range(10000) time = 8.892325 for 10000 repetitions xrange(10000) time = 9.650432 for 10000 repetitions range(1000) time = 8.960758 for 100000 repetitions xrange(1000) time = 10.031941 for 100000 repetitions range(750) time = 10.103314 for 150000 repetitions xrange(750) time = 10.909828 for 150000 repetitions range(500) time = 9.309678 for 200000 repetitions xrange(500) time = 8.274005 for 200000 repetitions range(100) time = 10.556858 for 1000000 repetitions xrange(100) time = 8.477174 for 1000000 repetitions range(10) time = 29.615361 for 10000000 repetitions xrange(10) time = 21.842709 for 10000000 repetitions range(5) time = 12.460505 for 5000000 repetitions xrange(5) time = 9.244912 for 5000000 repetitions range(1) time = 10.714814 for 5000000 repetitions xrange(1) time = 7.521607 for 5000000 repetitions Dick Moores From klas.martelleur at telia.com Sun Aug 1 17:10:24 2004 From: klas.martelleur at telia.com (Klas Marteleur) Date: Sun Aug 1 17:02:34 2004 Subject: [Tutor] Question on a example in the book "Learn to program using python" by Alan Gauld Message-ID: <200408011710.24330.klas.martelleur@telia.com> Hi First of all thanks for a interesting mailing list, i think i learn a lot by reading all good questions and answers. I bought a copy of the great book "Learn o program using python" 2001, i have read it back and forth a couple of times and now i am going thru testing and trying to understand all examples (...i think i am slowly starting to learn :) ) I got stuck on the case studie for the very useful :) program "Grammar counter" though. No matter what i try i get the error "Error analyzing file....." I type "python document.py example_file.txt" in a console. Can somebody of you professionals point me to what i am doing wrong? Many thanks Klas Marteleur code: #!/usr/bin/python import sys,string, re class Document: def __init__(self, filename): self.filename = filename self.para_count = 1 self.line_count, self.sentence_count = 0,0 self.clause_count, self.word_count = 0,0 self.alphas = string.letters + string.digits self.stop_tokens = ['.','?','!'] self.punctuation_chars = ['&','(',')','-', ';',':',','] + \ self.stop_tokens self.punctuation_counts = {} self.groups = [] for c in self.punctuation_chars: self.punctuation_counts[c] = 0 self.format = """%s contains: %d paragraphs, %d lines and %d sentences. These in turn contain %d clauses and a total of %d words.""" def getCharGroups(self): try: f = open(self.filename,"r") for line in f.readlines(): self.line_count = self.line_count + 1 if len(line) == 1: self.para_count = self.para_count + 1 else: self.groups = self.groups + string.split(line) except: print "Failed to read file", self.filename sys.exit() def getWords(self): for i in range(len(self.groups)): self.groups[i] = self.ltrim(self.groups) self.groups[i] = self.rtrim(self.groups[i]) self.removeExceptions() def removeExceptions(self): pass def ltrim(self,word): return word def rtrim(self,word): return word def generateStats(self): self.word_count = len(self.groups) for c in self.stop_tokens: sentence_count = sentence_count + \ self.punctuation_counts[c] for c in self.punctuation_counts.keys(): clause_count = clause_count + \ self.punctuation_counts[c] def printStats(self): print self.format % (self.filename, self.para_count, self.line_count, self.sentence_count, self.clause_count, self.words_count) print "The following punctuation characters were used:" for i in self.punctuation_counts.keys(): print "\t%s\t:\t%4d" % \ (i,self.punctuation_counts[i]) def Analyze(self): self.getCharGroups() self.getWords() self.generateStats() class TextDocument(Document): def ltrim(self, word): while (len(word) > 0) and \ (word[0] not in self.alphas): ch = word[0] if ch in self.punctuation_counts.keys(): self.punctuation_counts[ch] = \ self.punctuation_counts[ch]+1 word = word[1:] return word def rtrim(self,word): while (len(word) > 0) and \ (word[-1] not in self.alphas): ch = word[-1] if ch in self.punctuation_counts.keys(): self.punctuation_counts[ch] = \ self.punctuation_counts[ch]+1 word = word[:-1] return word def removeExceptions(self): top = len(self.groups) i = 0 while i < top: if (len(self.groups[i]) == 0): del(self.groups[i]) top = top - 1 i = i + 1 class HTMLDocument(Document): def getCharGroups(self): tag = re.compile("<.+?>") para = re.compile("<[pP]>") self.para_count = 0 f = open(self.filename, "r") lines = f.readlines() n = 0 while n < len(lines): if len(lines[n]) > 1: if para.search(lines[n]): self.para_count = self.para_count + 1 lines[n] = tag.sub('',lines[n]) if len(lines[n]) <= 1: del(lines)[n] else: self.groups = self.groups + string.split(lines[n]) n = n + 1 else: n = n + 1 self.line_count = len(lines) if __name__ == "__main__": if len (sys.argv) <> 2: print "Usage: python document.py" sys.exit() else: try: D = HTMLDocument(sys.argv[1]) D.Analyze() D.printStats() except: print "Error analyzing file: %s" % sys.argv[1] -------------- next part -------------- A non-text attachment was scrubbed... Name: document.py Type: text/x-python Size: 4448 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20040801/5bbe1a1c/document.py From kent_johnson at skillsoft.com Sun Aug 1 17:27:33 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sun Aug 1 17:28:33 2004 Subject: [Tutor] Question on a example in the book "Learn to program using python" by Alan Gauld In-Reply-To: <200408011710.24330.klas.martelleur@telia.com> References: <200408011710.24330.klas.martelleur@telia.com> Message-ID: <6.1.0.6.0.20040801111700.028da380@mail4.skillsoft.com> Klas, The try / except block in your main program is hiding a lot of useful information from you - the details of what type of exception was thrown, and where the problem occurs. If a Python program exits by throwing an exception, the Python runtime prints this information. By catching the exception you are losing this information. Taking out the try / except, the main program looks like this: if __name__ == "__main__": if len (sys.argv) <> 2: print "Usage: python document.py" sys.exit() else: D = HTMLDocument(sys.argv[1]) D.Analyze() D.printStats() If I run the program now, it outputs Traceback (most recent call last): File "document.py", line 130, in ? D.Analyze() File "document.py", line 70, in Analyze self.generateStats() File "document.py", line 54, in generateStats sentence_count = sentence_count + \ UnboundLocalError: local variable 'sentence_count' referenced before assignment This is much more useful. Apparently the variable sentence_count is being used before it is initialized. The problem is at line 54, which reads sentence_count = sentence_count + \ self.punctuation_counts[c] sentence_count is an instance variable and you have forgotten the self qualifier. These lines should read self.sentence_count = self.sentence_count + \ self.punctuation_counts[c] Fixing this gets past the original error. There are several similar errors that I will let you find :-) Kent At 05:10 PM 8/1/2004 +0200, Klas Marteleur wrote: >Hi > >First of all thanks for a interesting mailing list, i think i learn a lot by >reading all good questions and answers. > >I bought a copy of the great book "Learn o program using python" 2001, i have >read it back and forth a couple of times and now i am going thru testing and >trying to understand all examples (...i think i am slowly starting to learn >:) ) > >I got stuck on the case studie for the very useful :) program "Grammar >counter" though. >No matter what i try i get the error "Error analyzing file....." > >I type "python document.py example_file.txt" in a console. > >Can somebody of you professionals point me to what i am doing wrong? > >Many thanks >Klas Marteleur From rdm at rcblue.com Sun Aug 1 18:36:43 2004 From: rdm at rcblue.com (Dick Moores) Date: Sun Aug 1 18:36:46 2004 Subject: [Tutor] What's the problem with my SpinSpeeds.py? Message-ID: <6.1.2.0.2.20040801092944.025bfb48@rcblue.com> Why am I unable to use countUsingRange(n) instead of countUsingRange(25000)? When I do so, I get Traceback (most recent call last): File "C:/Python23/1.py", line 17, in -toplevel- rangeTime = t.timeit(repetitions) File "C:\Python23\lib\timeit.py", line 158, in timeit return self.inner(it, self.timer) File "", line 6, in inner NameError: global name 'n' is not defined Is this fixable? Dick ===================================== #SpinSpeeds.py def countUsingRange(n): for i in range(n): pass def countUsingXrange(n): for i in xrange(n): pass if __name__=='__main__': from timeit import Timer repetitions = 1000 n = 25000 t = Timer("countUsingRange(25000)", "from __main__ import countUsingRange") rangeTime = t.timeit(repetitions) t = Timer("countUsingXrange(25000)", "from __main__ import countUsingXrange") xrangeTime = t.timeit(repetitions) print " range(%d) time = %f for %d repetitions" % (n, rangeTime, repetitions) print "xrange(%d) time = %f for %d repetitions" % (n, xrangeTime, repetitions) ========================================== From kent_johnson at skillsoft.com Sun Aug 1 19:05:59 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sun Aug 1 19:06:10 2004 Subject: [Tutor] What's the problem with my SpinSpeeds.py? In-Reply-To: <6.1.2.0.2.20040801092944.025bfb48@rcblue.com> References: <6.1.2.0.2.20040801092944.025bfb48@rcblue.com> Message-ID: <6.1.0.6.0.20040801125238.028d9c90@mail4.skillsoft.com> Dick, The key to understanding this is to realize that the execution of countUsingRange(n) happens in a separate module with its own namespace. Here is a simpler example to show what is going on: Suppose a.py contains this code: def printSomething(a): print 'Something is', a n = 3 import b b.test() and b.py contains this: def test(): from __main__ import printSomething printSomething(100) Running a.py results in the printout Something is 100 The important thing to notice is the 'from __main__ import printSomething' in b.py. Without this line, test() would not know what printSomething means and it would throw aNameError when it is invoked. (Note: a.py is being run as main, so its module name is __main__. If a were run by importing it from another module, the import in b would be 'from a import ...') Now suppose you change b.py to def test(): from __main__ import printSomething printSomething(n) When you run this, you will get a NameError because module b has nothing named n. The solution is to change b.py to also import n: def test(): from __main__ import printSomething, n printSomething(n) Now it works. What does this have to do with your question? Well, a.py is analogous to your main program. b.py corresponds to the timeit module. timeit is using the exec statement to run the code you pass it, but the same scoping rules apply. So the solution is to add n to the import statements you pass to Timer(), for example t = Timer("countUsingRange(25000)", "from __main__ import countUsingRange, n") Kent At 09:36 AM 8/1/2004 -0700, Dick Moores wrote: >Why am I unable to use countUsingRange(n) instead of countUsingRange(25000)? > >When I do so, I get > >Traceback (most recent call last): > File "C:/Python23/1.py", line 17, in -toplevel- > rangeTime = t.timeit(repetitions) > File "C:\Python23\lib\timeit.py", line 158, in timeit > return self.inner(it, self.timer) > File "", line 6, in inner >NameError: global name 'n' is not defined > >Is this fixable? > >Dick > >===================================== >#SpinSpeeds.py > >def countUsingRange(n): > for i in range(n): > pass > >def countUsingXrange(n): > for i in xrange(n): > pass > >if __name__=='__main__': > from timeit import Timer > repetitions = 1000 > n = 25000 > > t = Timer("countUsingRange(25000)", "from __main__ import > countUsingRange") > rangeTime = t.timeit(repetitions) > > t = Timer("countUsingXrange(25000)", "from __main__ import > countUsingXrange") > xrangeTime = t.timeit(repetitions) > > print " range(%d) time = %f for %d repetitions" % (n, rangeTime, > repetitions) > print "xrange(%d) time = %f for %d repetitions" % (n, xrangeTime, > repetitions) >========================================== >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From Dragonfirebane at aol.com Sun Aug 1 19:09:05 2004 From: Dragonfirebane at aol.com (Dragonfirebane@aol.com) Date: Sun Aug 1 19:09:20 2004 Subject: [Tutor] What's the problem with my SpinSpeeds.py? Message-ID: <87.1210b9e4.2e3e7db1@aol.com> In addition to using string formatting so that it counts to 'n' and , you could also do: repetitions = int(raw_input("How many times should I count? ")) n = int(raw_input("How high should I count? ")) so that the user can see for themselves the time difference. Email: dragonfirebane@aol.com AIM: singingxduck Programming Python for the fun of it. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040801/e98137f5/attachment-0001.html From alan.gauld at blueyonder.co.uk Sun Aug 1 20:06:31 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Aug 1 20:06:12 2004 Subject: [Tutor] Question on a example in the book "Learn to program usingpython" by Alan Gauld References: <200408011710.24330.klas.martelleur@telia.com> Message-ID: <020e01c477f2$4664d220$6401a8c0@xp> Hi Klas, > I got stuck on the case studie for the very useful :) program "Grammar > counter" though. I am currently reworking the Grammer checker as part of my rewrite of the web tutorial. I've never been too happy with that case study because I tried to show a real world example of a program evolving warts and all. The end result (as is often the case!) was a bit of a messy, sub optimal program. What I should have done and didn't was added a section showing how to take the working version and tidy it up! > No matter what i try i get the error "Error analyzing file....." But despite what I just said, it should work! :-) But as you find it in the book it doesn't, due to a silly mistake - Sorry ! I missed out self from a couple of attribute accesses: > def generateStats(self): > self.word_count = len(self.groups) > for c in self.stop_tokens: > sentence_count = sentence_count + \ > self.punctuation_counts[c] > for c in self.punctuation_counts.keys(): > clause_count = clause_count + \ > self.punctuation_counts[c] both sentence_count and clause_count are attributes of the class so should be accessed via self.sentence_count etc... This error was picked up by a reader and the fix is listed on the book errata page, which you should check - there are quite a lot of typos, not all of them my fault!. http://www.freenetpages.co.uk/hp/alan.gauld/book/errata.htm HTH. FWIW The Games Framework/Hangman case study is much better quality code because it illustrates designing a program from scratch rather than evolving an existing one. Alan G. From alan.gauld at blueyonder.co.uk Sun Aug 1 20:10:41 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Aug 1 20:10:21 2004 Subject: [Tutor] What's the problem with my SpinSpeeds.py? References: <6.1.2.0.2.20040801092944.025bfb48@rcblue.com> Message-ID: <021301c477f2$db16c4f0$6401a8c0@xp> > Why am I unable to use countUsingRange(n) instead of countUsingRange(25000)? Because you are passing a string into the timer. The timer tries to parse the string but doesn't have access to n internally. You could use n if you created the string using a format operator: > if __name__=='__main__': > from timeit import Timer > repetitions = 1000 > n = 25000 > cmd = "countUsingRange(%d)" % n > t = Timer(cmd, "from __main__ import countUsingRange") > rangeTime = t.timeit(repetitions) HTH, Alan G. From rdm at rcblue.com Sun Aug 1 22:35:28 2004 From: rdm at rcblue.com (Dick Moores) Date: Sun Aug 1 22:35:31 2004 Subject: [Tutor] What's the problem with my SpinSpeeds.py? Message-ID: <6.1.2.0.2.20040801131105.0438cec0@rcblue.com> My thanks to dragonfirebane, Alan Gauld, and Kent Johnson for their help and guidance. I don't really grasp yet what's going on, but here's what I have now. It incorporates all of their suggestions. --Dick ==================== #SpinSpeeds.py def countUsingRange(n): for i in range(n): pass def countUsingXrange(n): for i in xrange(n): pass def countUsingCounter(n): c = 0 while c < n: c += 1 def getCountAndRepetitionsFromUser(): print "Enter count and repetitions as, e.g., 900 10000" n, repetitions = raw_input("Enter count and repetitions: ").split() return int(n), int(repetitions) if __name__=='__main__': from timeit import Timer n, repetitions = getCountAndRepetitionsFromUser() t = Timer("countUsingRange(n)", "from __main__ import countUsingRange, n") rangeTime = t.timeit(repetitions) cmd = "countUsingXrange(%d)" % n t = Timer(cmd, "from __main__ import countUsingXrange") xrangeTime = t.timeit(repetitions) t = Timer("countUsingCounter(%d)" % n, "from __main__ import countUsingCounter") counterTime = t.timeit(repetitions) print print " range(%d) time = %f for %d repetitions" % (n, rangeTime, repetitions) print "xrange(%d) time = %f for %d repetitions" % (n, xrangeTime, repetitions) print "counter %d time = %f for %d repetitions" % (n, counterTime, repetitions) ========================================== From Ralf.Steckel at AtosOrigin.com Mon Aug 2 01:38:52 2004 From: Ralf.Steckel at AtosOrigin.com (Steckel, Ralf) Date: Mon Aug 2 01:38:55 2004 Subject: [Tutor] Version conflict? Message-ID: <42BF8717D22EB1409F03483C993F46A70DE900@DEACX002.ikossvan.de> Hi tolis, from your e-mail i guess you are using python on a windows box. I think before you installed python 2.3 you didn't uninstall python 2.2 and/or you didn't change the PATH environment setting from the directory where python 2.2 is located to the directory where python 2.3 is located (if you used the default installation directories, this is C:\Python22 for 2.2 and C:\Python23 for 2.3). I suggest that you uninstall Python 2.3. Then uninstall Python 2.2 and then install Python 2.3 again. If you want to run two different versions of python parallel on Windows, i don't know if this is possible. Perhaps it's sufficient just to modify the PATH environment variable, but i think there are also some python specific settings in the registry. attention: for modifiying the PATH environment variable: don't alter the complete value, just the part for Python. Best wishes, Ralf > -----Original Message----- > From: tutor-bounces@python.org > [mailto:tutor-bounces@python.org]On Behalf Of tolis@softhome.net > Sent: Friday, July 30, 2004 5:33 PM > To: tutor@python.org > Subject: [Tutor] Version conflict? > > > I use python 2.3 but when I double clicking a .py file I get 3 times a > window message > saying that python22.dll was not found. After pressing OK for 3 times > the .py files starts. > How can I fix the problem? > The problem started many month after installing Python 2.3 > I copy python23.dll to python22.dll (now having 2 .dll) and > the message > stopped. > But, now I have an "ImportError: DLL load failed: bla bla..." when > importing packages like Numeric. > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From rdm at rcblue.com Mon Aug 2 03:04:02 2004 From: rdm at rcblue.com (Dick Moores) Date: Mon Aug 2 03:05:25 2004 Subject: [Tutor] Please take another look at my frac.py Message-ID: <6.1.2.0.2.20040801174613.04e787b8@rcblue.com> Danny Yoo will be disappointed, I'm sure. His kind post of Fri, 23 Jul 2004 15:26:36 -0700 (PDT) tried to show me how to shorten the program by consolidating the functions that get user input, but I was unable to implement his suggestions. But I have made the program a lot more modular. If there's some more work needed, please tell me. Thanks, tutors. Dick Moores ===================================== #frac.py print """ Enter a decimal number and Frac will calculate a fraction for use as an approximation to the number. You can choose to set a maximum denominator for the fraction, or to set a minimum error for the fraction to satisfy. Enter e or E for the mathematical constant 2.7182818284590451, and pi or PI for the mathematical constant 3.1415926535897931. You can exit the program at any prompt by entering 0 (zero). """ import random, time def exit(): print "Thank you for using Frac. Frac will now close." time.sleep(1.1) def getDecimalFromUser(): while True: print "If nothing entered, a random decimal " \ "between 0.1 and 1.0 will be chosen." string = raw_input("Decimal: ") if string in ["pi", "PI"]: decimal = 3.1415926535897931 elif string in ["E", "e"]: decimal = 2.7182818284590451 elif string == "": decimal = getRandomDecimal() print decimal, "was picked at random for you.\n" else: try: decimal = float(string) except: print "That's not a decimal number! Try again." continue break return decimal def getRandomDecimal(): decimal = random.uniform(0.1, 1.0) return decimal def getChoiceFromUser(): while True: choice = raw_input("Minimum error (e) or maximum denominator (d)? ") if not (choice in ['d', 'D', 'e', 'E', '0']): print "Enter d or e" continue break return choice def getMaxDenomFromUser(): while True: print "If no maximum denominator entered, the default is 100" maxDenom = raw_input("Maximum denominator: ") if maxDenom == "": maxDenom = 100 print "Maximum denominator is %g by default" % maxDenom else: try: maxDenom = int(maxDenom) except: print "That's not an integer! Try again." continue break return maxDenom def getMinimumErrorFromUser(): while True: print "If no minimum error entered, the default is %g percent" % .01 minimumError = raw_input("Minimum error in percent: ") if minimumError == "": minimumError = .01 print "Minimum error is %g by default" % .01 else: try: minimumError = float(minimumError) except: print "That's not a decimal number!" continue break return minimumError def bestFracForMaxDenom(decimal, maxDenom): leastError = 1 for denom in xrange(1, maxDenom + 1): num = round(decimal * denom) error = abs((num / denom - decimal) / decimal) if error < leastError: leastError = error bestDenom = denom bestNum = num # leastError is a float; should I have this if statement? if leastError == 0: break return int(bestNum), bestDenom, leastError def bestFracForMinimumError(decimal, minimumError): denom = 0 while True: denom += 1 num = round(decimal * denom) error = abs((num / denom - decimal) / decimal) * 100 if error <= minimumError: break return int(num), denom, error while True: decimal = getDecimalFromUser() if decimal == 0: break choice = getChoiceFromUser() if choice == "0": break if choice == "d": maxDenom = getMaxDenomFromUser() if maxDenom == 0: break bestNum, bestDenom, leastError = bestFracForMaxDenom(decimal, maxDenom) print "\n For a decimal of %s, %d/%d," % (str(decimal), bestNum, bestDenom) print "which is equal to %s, is the closest fraction" % (str(float(bestNum)/bestDenom)) print "up to a maximum denominator of %d" % maxDenom print "Error is %.13e percent" % (leastError * 100) print "=====================================" print else: minimumError = getMinimumErrorFromUser() if minimumError == 0: break num, denom, error = bestFracForMinimumError(decimal, minimumError) print "\n For a decimal of %s, %d/%d," % (str(decimal), num, denom) print "which is equal to %s, is the closest fraction" % (str(float(num)/denom)) print "with smallest denominator and error <= %.13g percent" % minimumError print "Actual error is %.13e percent" % error print "============================================" print exit() ===========end fraq.py========================= From jfabiani at yolo.com Mon Aug 2 06:40:07 2004 From: jfabiani at yolo.com (John Fabiani) Date: Mon Aug 2 06:40:12 2004 Subject: [Tutor] How does WxPython use fonts Message-ID: <200408012140.07757.jfabiani@yolo.com> Hi, I just got WxPthon 2.5.1.5 working on my SUSE 9.1 64bit system - but it looks terrible. One thing for sure the fonts do not (in fact the entire look) does not match my standard 2.4 look when running the demo. So this is just a guess - 2.5 does not use the same fonts as the 2.4 install. How do I set 2.5 to match the 2.4 look? I think some of the issue could be that 2.5 is using 75dpi fonts and should be using 100dpi fonts. I say that because I recall that KDE looks similar before I installed the 100 DPI fonts. John From klas.martelleur at telia.com Mon Aug 2 16:34:18 2004 From: klas.martelleur at telia.com (Klas Marteleur) Date: Mon Aug 2 16:26:18 2004 Subject: [Tutor] Question on a example in the book "Learn to program using python" by Alan Gauld In-Reply-To: <6.1.0.6.0.20040801111700.028da380@mail4.skillsoft.com> References: <200408011710.24330.klas.martelleur@telia.com> <6.1.0.6.0.20040801111700.028da380@mail4.skillsoft.com> Message-ID: <200408021634.18024.klas.martelleur@telia.com> Thanks Kent and Alan for your hints I have the problem that i get totaly blind when i look at code try to spot errors, but i guess i will be better at it with more experience. Taking out try / except was a good hint! After i spoted some more errors i got the program to run, but i dont get the punctuation count to work. I get "zero" on every row. Shouldnt there be a "...D = TextDocument(sys.argv[1])... " somewere? OT...and Alan you should not be sorry for the small errors in your book, its the best "computer book" i have ever read i can see there is a lot of work put into it! I especially like that its possible to read the book and not sitting by the computer at the same time, and its real packed with facts. Thanks! OT Here is the "new" program: ---------------------------------------------------------------- #!/usr/bin/python import sys,string, re class Document: def __init__(self, filename): self.filename = filename self.para_count = 1 self.line_count, self.sentence_count = 0,0 self.clause_count, self.word_count = 0,0 self.alphas = string.letters + string.digits self.stop_tokens = ['.','?','!'] self.punctuation_chars = ['&','(',')','-',';',':',','] + self.stop_tokens self.punctuation_counts = {} self.groups = [] for c in self.punctuation_chars: self.punctuation_counts[c] = 0 self.format = """%s contains: %d paragraphs, %d lines and %d sentences.These in turn contain %d clauses and a total of %d words.""" def getCharGroups(self): try: f = open(self.filename,"r") for line in f.readlines(): self.line_count = self.line_count + 1 if len(line) == 1: self.para_count = self.para_count + 1 else: self.groups = self.groups + string.split(line) except: print "Failed to read file", self.filename sys.exit() def getWords(self): for i in range(len(self.groups)): self.groups[i] = self.ltrim(self.groups[i]) self.groups[i] = self.rtrim(self.groups[i]) self.removeExceptions() def removeExceptions(self): pass def ltrim(self,word): return word def rtrim(self,word): return word def generateStats(self): self.word_count = len(self.groups) for c in self.stop_tokens: self.sentence_count = self.sentence_count + self.punctuation_counts[c] for c in self.punctuation_counts.keys(): self.clause_count = self.clause_count + self.punctuation_counts[c] def printStats(self): print self.format % (self.filename, self.para_count, self.line_count, self.sentence_count, self.clause_count, self.word_count) print "The following punctuation characters were used:" for i in self.punctuation_counts.keys(): print "\t%s\t:\t%4d" % \ (i,self.punctuation_counts[i]) def Analyze(self): self.getCharGroups() self.getWords() self.generateStats() class TextDocument(Document): def ltrim(self, word): while (len(word) > 0) and (word[0] not in self.alphas): ch = word[0] if ch in self.punctuation_counts.keys(): self.punctuation_counts[ch] = self.punctuation_counts[ch]+1 word = word[1:] return word def rtrim(self,word): while (len(word) > 0) and (word[-1] not in self.alphas): ch = word[-1] if ch in self.punctuation_counts.keys(): self.punctuation_counts[ch] = self.punctuation_counts[ch]+1 word = word[:-1] return word def removeExceptions(self): top = len(self.groups) i = 0 while i < top: if (len(self.groups[i]) == 0): del(self.groups[i]) top = top - 1 i = i + 1 class HTMLDocument(Document): def getCharGroups(self): tag = re.compile("<.+?>") para = re.compile("<[pP]>") self.para_count = 0 f = open(self.filename, "r") lines = f.readlines() n = 0 while n < len(lines): if len(lines[n]) > 1: if para.search(lines[n]): self.para_count = self.para_count + 1 lines[n] = tag.sub('',lines[n]) if len(lines[n]) <= 1: del(lines)[n] else: self.groups = self.groups + string.split(lines[n]) n = n + 1 else: n = n + 1 self.line_count = len(lines) if __name__ == "__main__": if len (sys.argv) <> 2: print "Usage: python document.py" sys.exit() else: try: D = TextDocument(sys.argv[1]) #This way it counts the punctuation as well # D = HTMLDocument(sys.argv[1]) D.Analyze() D.printStats() except: print "Error analyzing file: %s" % sys.argv[1] ------------------------------------------------------- Kind regards Klas s?ndagen den 1 augusti 2004 17.27 skrev Kent Johnson: > Klas, > > The try / except block in your main program is hiding a lot of useful > information from you - the details of what type of exception was thrown, > and where the problem occurs. If a Python program exits by throwing an > exception, the Python runtime prints this information. By catching the > exception you are losing this information. > > Taking out the try / except, the main program looks like this: > if __name__ == "__main__": > if len (sys.argv) <> 2: > print "Usage: python document.py" > sys.exit() > else: > D = HTMLDocument(sys.argv[1]) > D.Analyze() > D.printStats() > > If I run the program now, it outputs > Traceback (most recent call last): > File "document.py", line 130, in ? > D.Analyze() > File "document.py", line 70, in Analyze > self.generateStats() > File "document.py", line 54, in generateStats > sentence_count = sentence_count + \ > UnboundLocalError: local variable 'sentence_count' referenced before > assignment > > This is much more useful. Apparently the variable sentence_count is being > used before it is initialized. The problem is at line 54, which reads > sentence_count = sentence_count + \ > self.punctuation_counts[c] > > sentence_count is an instance variable and you have forgotten the self > qualifier. These lines should read > self.sentence_count = self.sentence_count + \ > self.punctuation_counts[c] > > Fixing this gets past the original error. There are several similar errors > that I will let you find :-) > > Kent > > At 05:10 PM 8/1/2004 +0200, Klas Marteleur wrote: > >Hi > > > >First of all thanks for a interesting mailing list, i think i learn a lot > > by reading all good questions and answers. > > > >I bought a copy of the great book "Learn o program using python" 2001, i > > have read it back and forth a couple of times and now i am going thru > > testing and trying to understand all examples (...i think i am slowly > > starting to learn > > > >:) ) > > > >I got stuck on the case studie for the very useful :) program "Grammar > >counter" though. > >No matter what i try i get the error "Error analyzing file....." > > > >I type "python document.py example_file.txt" in a console. > > > >Can somebody of you professionals point me to what i am doing wrong? > > > >Many thanks > >Klas Marteleur > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From davholla2002 at yahoo.co.uk Mon Aug 2 17:08:04 2004 From: davholla2002 at yahoo.co.uk (=?iso-8859-1?q?David=20Holland?=) Date: Mon Aug 2 17:11:18 2004 Subject: [Tutor] Shut down PC In-Reply-To: <20040802100051.892281E4038@bag.python.org> Message-ID: <20040802150804.1565.qmail@web25402.mail.ukl.yahoo.com> Hi, I want to write a program to force my niece improve her maths skills. I can quite easily write a program that asks her random questions. How can you make a python program that under certaim cirumstances shuts down the PC (eg crashing the program). I know this may sound silly but she is 15 and innumerate ! Thanks David ___________________________________________________________ALL-NEW Yahoo! Messenger - all new features - even more fun! http://uk.messenger.yahoo.com From vicki at thepenguin.org Mon Aug 2 17:18:20 2004 From: vicki at thepenguin.org (vicki@thepenguin.org) Date: Mon Aug 2 17:20:23 2004 Subject: [Tutor] Shut down PC In-Reply-To: <20040802150804.1565.qmail@web25402.mail.ukl.yahoo.com> References: <20040802100051.892281E4038@bag.python.org> <20040802150804.1565.qmail@web25402.mail.ukl.yahoo.com> Message-ID: <46874.206.53.226.235.1091459900.squirrel@206.53.226.235> > Hi, > I want to write a program to force my niece improve > her maths skills. I can quite easily write a program > that asks her random questions. > How can you make a python program that under certaim > cirumstances shuts down the PC (eg crashing the > program). > I know this may sound silly but she is 15 and > innumerate ! > Thanks > > David Do you mean that you want the program to terminate or the operating system to terminate? If the latter, you need to tell us what OS you are using. If you mean the former, you might describe a sequence of events that you want to simulate to give us a better idea how to help. --vicki From barnabydscott at yahoo.com Mon Aug 2 17:41:17 2004 From: barnabydscott at yahoo.com (Barnaby Scott) Date: Mon Aug 2 17:41:20 2004 Subject: [Tutor] cgi script writing a file: permission denied, but only sometimes! Message-ID: <20040802154117.70596.qmail@web61202.mail.yahoo.com> I have a problem with a cgi script, which seems to work for nearly everyone (including me), but for one person at least does not. The fragment of code invloved is below: Obviously there is a lot more, but it is the line with file(...).write(...) in it which is not being exectued and is giving Errno 13: Permission Denied. def save(self): assert os.getenv('REQUEST_METHOD') == 'POST', 'only POST allowed' assert self.existcode != 2, 'Cannot save a rival version of an automatic page' newtext = getattr(self, 'newtext', '') if not newtext: return self.delete() elif newtext != self.gettext(): self.backup() file(self.textfile,'w').write(newtext) return self.resend(message='Thank you for your update') else: return self.resend() The file in question has permissions rw-r--r--, and because the script is running as the owner, this normally works. The script is called by a SSI tag. This problem may be beyond the scope of this list, but does anyone have any suggestions even where to START looking for a cause? Why would this work in 99% of cases but for one particular web user not work? Any clues gratefully received. __________________________________ Do you Yahoo!? Yahoo! Mail Address AutoComplete - You start. We finish. http://promotions.yahoo.com/new_mail From davholla2002 at yahoo.co.uk Mon Aug 2 18:05:38 2004 From: davholla2002 at yahoo.co.uk (=?iso-8859-1?q?David=20Holland?=) Date: Mon Aug 2 18:05:39 2004 Subject: [Tutor] Shut down PC In-Reply-To: <46874.206.53.226.235.1091459900.squirrel@206.53.226.235> Message-ID: <20040802160538.92043.qmail@web25403.mail.ukl.yahoo.com> Hi I have both Windows and Linux on my PC. Basically I want the operating system to terminate if people using the PC do not know a password and do not answers questions within a time limit or if they try to avoid doing these questions by crashing the program. --- vicki@thepenguin.org wrote: > > Hi, > > I want to write a program to force my niece > improve > > her maths skills. I can quite easily write a > program > > that asks her random questions. > > How can you make a python program that under > certaim > > cirumstances shuts down the PC (eg crashing the > > program). > > I know this may sound silly but she is 15 and > > innumerate ! > > Thanks > > > > David > > Do you mean that you want the program to terminate > or the operating system > to terminate? If the latter, you need to tell us > what OS you are using. If > you mean the former, you might describe a sequence > of events that you want > to simulate to give us a better idea how to help. > > --vicki > > ___________________________________________________________ALL-NEW Yahoo! Messenger - all new features - even more fun! http://uk.messenger.yahoo.com From crashnmash2003 at yahoo.com Mon Aug 2 18:27:41 2004 From: crashnmash2003 at yahoo.com (David Dodds) Date: Mon Aug 2 18:27:46 2004 Subject: [Tutor] i dont understand Message-ID: <20040802162742.50957.qmail@web53306.mail.yahoo.com> hey all im a new computer user and i would love to get into programing but i dont understand it for example why u have to use "?.() and stuff for. i would really appreciate some one to lern me and give me basic step by step instructions thanx... ===== __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From amonroe at columbus.rr.com Mon Aug 2 18:56:31 2004 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Mon Aug 2 18:56:41 2004 Subject: [Tutor] i dont understand In-Reply-To: <20040802162742.50957.qmail@web53306.mail.yahoo.com> References: <20040802162742.50957.qmail@web53306.mail.yahoo.com> Message-ID: <50839302272.20040802125631@columbus.rr.com> > hey all im a new computer user and i would love to get > into programing but i dont understand it for example > why u have to use "?.() and stuff for. Have you taken algebra in school yet? Programming makes more sense after algebra. Alan From Janssen at rz.uni-frankfurt.de Mon Aug 2 19:40:17 2004 From: Janssen at rz.uni-frankfurt.de (Michael Janssen) Date: Mon Aug 2 19:40:24 2004 Subject: [Tutor] Shut down PC In-Reply-To: <20040802160538.92043.qmail@web25403.mail.ukl.yahoo.com> References: <20040802160538.92043.qmail@web25403.mail.ukl.yahoo.com> Message-ID: On Mon, 2 Aug 2004, David Holland wrote: > Hi I have both Windows and Linux on my PC. > Basically I want the operating system to terminate if > people using the PC do not know a password and do not > answers questions within a time limit on Linux you can stop the computer with "/sbin/init 0" (besides various other commands). This will switch into runlevel 0, ie halt. Permissions might be set accordingly. os.system is the Python function to call external commands. Windows can be stopped with a much more complicated command using rundll32. rundll32 is used to run methods from dll-files (libraries) on their own. Perhaps google knows more about the proper library to use and the name of the shutdow method. Perhaps win32all has something to offer: http://starship.python.net/crew/mhammond/win32/ > or if they try to avoid doing these questions by crashing the program. try: main() except: os.system("/sbin/init 0") should catch some tricks but suspending the programm isn't catched and probably more things. Besides it's a funny way to make writing and debugging a Python script more risky ;-) Michael From dyoo at hkn.eecs.berkeley.edu Mon Aug 2 19:53:44 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Aug 2 19:53:48 2004 Subject: [Tutor] i dont understand [parentheses for functions] In-Reply-To: <20040802162742.50957.qmail@web53306.mail.yahoo.com> Message-ID: On Mon, 2 Aug 2004, David Dodds wrote: > hey all im a new computer user and i would love to get into programing > but i dont understand it Hi David, No problem; feel free to ask questions here about the stuff you don't understand, and we'll do our best to point you in the right direction. > for example why u have to use "?.() and stuff for. Hmmm... can you show us an example of what you mean? The problem is that parentheses are used in a lot of different contexts; it would be great if we could focus on a real, concrete example. One example where parentheses are used is to "fire" off or "apply" a function. We can tell Python: "To sing a song: Sing a verse, Sing a refrain. Sing another verse. Sing the refrain again. " For example: ### >>> def singSong(): ... singVerseOne() ... singRefrain() ... singVerseTwo() ... singRefrain() ... >>> >>> def singVerseOne(): ... print """ ... Theory girl, ... Workign in an academic world ... I bet she never had a systems guy ... Bet her advisor never told her why ... I'm gonna try for a...""" ... >>> >>> def singRefrain(): ... print """ ... ... theory girl, ... She doesn't want to code in C or Perl ... She never touches keyboard, mouse, or screen ... Because she uses an abstract machine ... It's nice and clean""" ... >>> >>> def singVerseTwo(): ... print """ ... And when she quotes ... algorithms from memory ... You'll find she knows ... all of Knuth Volumes One, Two, Three ... ... Why is the math so tough? ... How can I ... prove my love for a...""" ... ### When we ask Python what "singSong" is, it tells us: ### >>> singSong ### that it's a "function". But how do we turn it on? Functions are things that can be activated by using parentheses: ### >>> singSong() Theory girl, Workign in an academic world I bet she never had a systems guy Bet her advisor never told her why I'm gonna try for a... ... theory girl, She doesn't want to code in C or Perl She never touches keyboard, mouse, or screen Because she uses an abstract machine It's nice and clean And when she quotes algorithms from memory You'll find she knows all of Knuth Volumes One, Two, Three Why is the math so tough? How can I prove my love for a... ... theory girl, She doesn't want to code in C or Perl She never touches keyboard, mouse, or screen Because she uses an abstract machine It's nice and clean ### There it goes. If we leave off the parentheses, a function won't fire off. Also, if we write "singSong()" like this: ### >>> def singSong(): ... singVerseOne ... singRefrain ... singVerseTwo ... ### then when we fire off singSong, nothing will appear to happen, ### >>> singSong() >>> ### because although the 'singSong' function itself fires off, it doesn't tell Python to fire off the other three functions. So parentheses are used to fire off, or "apply" functions. It seems a little redundant to use parentheses to fire off functions, but it makes more sense when functions "take in" things. For example: ### >>> def sayMadLib(verb1, noun1): ... print "Once upon a", noun1, ... print "there was a cow who would", verb1, "all day" ... >>> sayMadLib("blue moon", "croak") Once upon a croak there was a cow who would blue moon all day ### Whoops! Got things backwards. Let me try that again: ### >>> sayMadLib("croak", "blue moon") Once upon a blue moon there was a cow who would croak all day ### That's better. What we have here is a function that takes in two things. Those two "parameters" go in the parentheses, so that Python knows to give them to the function. The parentheses are there to make it easier to see that a function is "taking in" things when it is being called. Does this make sense so far? From scottcann at linuxmail.org Mon Aug 2 19:46:20 2004 From: scottcann at linuxmail.org (Scott Cann) Date: Mon Aug 2 20:07:36 2004 Subject: [Tutor] Play notes like qbasic Message-ID: <20040802174620.D999E4160A1@ws5-2.us4.outblaze.com> I found a list of songs in QBasic play format and would like to parse them with python, as a learning project. Does anyone know if there is a beep, sound function that would toot the internal speaker. Or is there something out there that does it already. No use inventing sliced bread. Thanks Scott Cann -- ______________________________________________ Check out the latest SMS services @ http://www.linuxmail.org This allows you to send and receive SMS through your mailbox. Powered by Outblaze From alan.gauld at blueyonder.co.uk Mon Aug 2 20:21:04 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Mon Aug 2 20:20:39 2004 Subject: [Tutor] What's the problem with my SpinSpeeds.py? References: <6.1.2.0.2.20040801131105.0438cec0@rcblue.com> Message-ID: <005401c478bd$795b11a0$6401a8c0@xp> > My thanks to dragonfirebane, Alan Gauld, and Kent Johnson for their help > and guidance. I don't really grasp yet what's going on, but here's what > I have now. It incorporates all of their suggestions. --Dick You only needed a subset of them they solve the same problem in different ways.:-) > t = Timer("countUsingRange(n)", "from __main__ import > countUsingRange, n") > rangeTime = t.timeit(repetitions) This executes and times the string "countUsingRange(n)" after first executing "from __main__ import countUsingRange, n". The import step brings 'n' into scope for the timer so that the first string can be evaluated correctly. > cmd = "countUsingXrange(%d)" % n > t = Timer(cmd, "from __main__ import countUsingXrange") > xrangeTime = t.timeit(repetitions) This creates a string "countUsingXrange(XXX)" where XXX is the value of n. Then it creates a timer to execute and time that string after first executing "from __main__ import countUsingXrange" which simply makes your function visible. > t = Timer("countUsingCounter(%d)" % n, "from __main__ import > countUsingCounter") > counterTime = t.timeit(repetitions) And this does exactly the same except that it creates the command string inline. Any one of the three techniques should work OK. There is a subtle difference between them inasmuch as the first puts slightly more work into the timing module since it has to perform the variable substitution whereas forming the string before entering the timer could be slightly faster during timing, but the difference is negligible in this case. Preforming the string allows multiple timers to be easily created for the same command should you need to do so... Alan G. From vicki at thepenguin.org Mon Aug 2 20:34:09 2004 From: vicki at thepenguin.org (vicki@thepenguin.org) Date: Mon Aug 2 20:36:14 2004 Subject: [Tutor] Play notes like qbasic In-Reply-To: <20040802174620.D999E4160A1@ws5-2.us4.outblaze.com> References: <20040802174620.D999E4160A1@ws5-2.us4.outblaze.com> Message-ID: <17798.206.53.226.235.1091471649.squirrel@206.53.226.235> > I found a list of songs in QBasic play format > and would like to parse them with python, as a > learning project. > > Does anyone know if there is a beep, sound function > that would toot the internal speaker. > Or is there something out there that does it already. > No use inventing sliced bread. > > Thanks > > Scott Cann Take a look at the winsound functions at http://www.python.org/doc/current/lib/module-winsound.html For Linux, there are several options. Are you on Windows? --vicki From klas.martelleur at telia.com Mon Aug 2 20:48:54 2004 From: klas.martelleur at telia.com (Klas Marteleur) Date: Mon Aug 2 20:40:56 2004 Subject: [Tutor] Question on a example in the book "Learn to program using python" by Alan Gauld In-Reply-To: <200408021634.18024.klas.martelleur@telia.com> References: <200408011710.24330.klas.martelleur@telia.com> <6.1.0.6.0.20040801111700.028da380@mail4.skillsoft.com> <200408021634.18024.klas.martelleur@telia.com> Message-ID: <200408022048.54430.klas.martelleur@telia.com> Ohh man... it was the HTMLDocument() that was the problem.... as it clearly says on the errata page that Alan tip me about yesterday... argghh :) Sorry! Now i just have to understand what was wrong with the old one :) Klas m?ndagen den 2 augusti 2004 16.34 skrev Klas Marteleur: > Thanks Kent and Alan for your hints > > I have the problem that i get totaly blind when i look at code try to spot > errors, but i guess i will be better at it with more experience. > Taking out try / except was a good hint! > After i spoted some more errors i got the program to run, but i dont get > the punctuation count to work. I get "zero" on every row. > > Shouldnt there be a "...D = TextDocument(sys.argv[1])... " somewere? > > OT...and Alan you should not be sorry for the small errors in your book, > its the best "computer book" i have ever read i can see there is a lot of > work put into it! > I especially like that its possible to read the book and not sitting by the > computer at the same time, and its real packed with facts. Thanks! OT > > Here is the "new" program: > ---------------------------------------------------------------- > #!/usr/bin/python > import sys,string, re > > class Document: > def __init__(self, filename): > self.filename = filename > self.para_count = 1 > self.line_count, self.sentence_count = 0,0 > self.clause_count, self.word_count = 0,0 > self.alphas = string.letters + string.digits > self.stop_tokens = ['.','?','!'] > self.punctuation_chars = ['&','(',')','-',';',':',','] + > self.stop_tokens > self.punctuation_counts = {} > self.groups = [] > for c in self.punctuation_chars: > self.punctuation_counts[c] = 0 > self.format = """%s contains: %d paragraphs, %d lines and %d > sentences.These in turn contain %d clauses and a total of %d words.""" > > def getCharGroups(self): > try: > f = open(self.filename,"r") > for line in f.readlines(): > self.line_count = self.line_count + 1 > if len(line) == 1: > self.para_count = self.para_count + 1 > else: > self.groups = self.groups + string.split(line) > except: > print "Failed to read file", self.filename > sys.exit() > > def getWords(self): > for i in range(len(self.groups)): > self.groups[i] = self.ltrim(self.groups[i]) > self.groups[i] = self.rtrim(self.groups[i]) > self.removeExceptions() > > def removeExceptions(self): > pass > > def ltrim(self,word): > return word > > def rtrim(self,word): > return word > > def generateStats(self): > self.word_count = len(self.groups) > for c in self.stop_tokens: > self.sentence_count = self.sentence_count + > self.punctuation_counts[c] > for c in self.punctuation_counts.keys(): > self.clause_count = self.clause_count + > self.punctuation_counts[c] > > def printStats(self): > print self.format % (self.filename, self.para_count, > self.line_count, self.sentence_count, self.clause_count, self.word_count) > print "The following punctuation characters were used:" > for i in self.punctuation_counts.keys(): > print "\t%s\t:\t%4d" % \ > (i,self.punctuation_counts[i]) > > def Analyze(self): > self.getCharGroups() > self.getWords() > self.generateStats() > > class TextDocument(Document): > def ltrim(self, word): > while (len(word) > 0) and (word[0] not in self.alphas): > ch = word[0] > if ch in self.punctuation_counts.keys(): > self.punctuation_counts[ch] = self.punctuation_counts[ch]+1 > word = word[1:] > return word > > def rtrim(self,word): > while (len(word) > 0) and (word[-1] not in self.alphas): > ch = word[-1] > if ch in self.punctuation_counts.keys(): > self.punctuation_counts[ch] = self.punctuation_counts[ch]+1 > word = word[:-1] > return word > > def removeExceptions(self): > top = len(self.groups) > i = 0 > while i < top: > if (len(self.groups[i]) == 0): > del(self.groups[i]) > top = top - 1 > i = i + 1 > > class HTMLDocument(Document): > def getCharGroups(self): > tag = re.compile("<.+?>") > para = re.compile("<[pP]>") > self.para_count = 0 > f = open(self.filename, "r") > lines = f.readlines() > n = 0 > while n < len(lines): > if len(lines[n]) > 1: > if para.search(lines[n]): > self.para_count = self.para_count + 1 > lines[n] = tag.sub('',lines[n]) > if len(lines[n]) <= 1: > del(lines)[n] > else: > self.groups = self.groups + string.split(lines[n]) > n = n + 1 > else: > n = n + 1 > self.line_count = len(lines) > > if __name__ == "__main__": > if len (sys.argv) <> 2: > print "Usage: python document.py" > sys.exit() > else: > try: > D = TextDocument(sys.argv[1]) #This way it counts the > punctuation as well > # D = HTMLDocument(sys.argv[1]) > D.Analyze() > D.printStats() > except: > print "Error analyzing file: %s" % sys.argv[1] > ------------------------------------------------------- > > Kind regards > Klas > > s?ndagen den 1 augusti 2004 17.27 skrev Kent Johnson: > > Klas, > > > > The try / except block in your main program is hiding a lot of useful > > information from you - the details of what type of exception was thrown, > > and where the problem occurs. If a Python program exits by throwing an > > exception, the Python runtime prints this information. By catching the > > exception you are losing this information. > > > > Taking out the try / except, the main program looks like this: > > if __name__ == "__main__": > > if len (sys.argv) <> 2: > > print "Usage: python document.py" > > sys.exit() > > else: > > D = HTMLDocument(sys.argv[1]) > > D.Analyze() > > D.printStats() > > > > If I run the program now, it outputs > > Traceback (most recent call last): > > File "document.py", line 130, in ? > > D.Analyze() > > File "document.py", line 70, in Analyze > > self.generateStats() > > File "document.py", line 54, in generateStats > > sentence_count = sentence_count + \ > > UnboundLocalError: local variable 'sentence_count' referenced before > > assignment > > > > This is much more useful. Apparently the variable sentence_count is being > > used before it is initialized. The problem is at line 54, which reads > > sentence_count = sentence_count + \ > > self.punctuation_counts[c] > > > > sentence_count is an instance variable and you have forgotten the self > > qualifier. These lines should read > > self.sentence_count = self.sentence_count + \ > > self.punctuation_counts[c] > > > > Fixing this gets past the original error. There are several similar > > errors that I will let you find :-) > > > > Kent > > > > At 05:10 PM 8/1/2004 +0200, Klas Marteleur wrote: > > >Hi > > > > > >First of all thanks for a interesting mailing list, i think i learn a > > > lot by reading all good questions and answers. > > > > > >I bought a copy of the great book "Learn o program using python" 2001, i > > > have read it back and forth a couple of times and now i am going thru > > > testing and trying to understand all examples (...i think i am slowly > > > starting to learn > > > > > >:) ) > > > > > >I got stuck on the case studie for the very useful :) program "Grammar > > >counter" though. > > >No matter what i try i get the error "Error analyzing file....." > > > > > >I type "python document.py example_file.txt" in a console. > > > > > >Can somebody of you professionals point me to what i am doing wrong? > > > > > >Many thanks > > >Klas Marteleur > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From kent_johnson at skillsoft.com Mon Aug 2 21:06:58 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Mon Aug 2 21:07:03 2004 Subject: [Tutor] i dont understand In-Reply-To: <20040802162742.50957.qmail@web53306.mail.yahoo.com> References: <20040802162742.50957.qmail@web53306.mail.yahoo.com> Message-ID: <6.1.0.6.0.20040802145656.02a00dc8@mail4.skillsoft.com> Have you tried any of the tutorials listed on the "Python for Non-Programmers" page? If so, where do you get stuck? http://www.python.org/topics/learn/non-prog.html You might like the book "Python Programming for the absolute beginner", it doesn't assume you know about "?.() and stuff like that. http://premierpressbooks.com/ptr_detail.cfm?group=Programming&isbn=1%2D59200%2D073%2D8 Otherwise you can ask here about specific things you don't understand. Kent At 09:27 AM 8/2/2004 -0700, David Dodds wrote: >hey all im a new computer user and i would love to get >into programing but i dont understand it for example >why u have to use "?.() and stuff for. i would really >appreciate some one to lern me and give me basic step >by step instructions > thanx... > >===== > > >__________________________________________________ >Do You Yahoo!? >Tired of spam? Yahoo! Mail has the best spam protection around >http://mail.yahoo.com >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From alan.gauld at blueyonder.co.uk Mon Aug 2 22:05:52 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Mon Aug 2 22:05:25 2004 Subject: [Tutor] Question on a example in the book "Learn to program usingpython" by Alan Gauld References: <200408011710.24330.klas.martelleur@telia.com><6.1.0.6.0.20040801111700.028da380@mail4.skillsoft.com> <200408021634.18024.klas.martelleur@telia.com> Message-ID: <006601c478cc$1d3fd2c0$6401a8c0@xp> > Shouldnt there be a "...D = TextDocument(sys.argv[1])... " somewere? Only if you pass it .txt files. An interesting excercise would be to strip off the last bit of the filename and see if it matches '.txt' or '.htm' or '.html' and create the appropriate type of document object. Hint: There is a module for manipulating filenames :-) > OT...and Alan you should not be sorry for the small errors in your book, > its the best "computer book" i have ever read Aw shucks! :-) As to your problem, I can't see anything significantly different to my original code (as per the CD ROM with the book and written prior to the reviewers and copy-editors and typesetters "improvements"!) which definitely works... I'll try to get back to it later tonight. Meantime, what kind of file are you passing as a parameter? And are you actually using TextDocument or HTMLDocument? Regards, Alan G. From alan.gauld at blueyonder.co.uk Mon Aug 2 22:14:03 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Mon Aug 2 22:13:36 2004 Subject: [Tutor] i dont understand References: <20040802162742.50957.qmail@web53306.mail.yahoo.com> Message-ID: <007501c478cd$41cc66c0$6401a8c0@xp> > hey all im a new computer user and i would love to get > into programing but i dont understand it for example > why u have to use "?.() and stuff for. Exactly the same reason we use them in normal language, so that the reader (in this case the PC!) can understand what we are trying to say. Thats also why we use capital letters at the start of sentences in most languages like English, it helps the reader understand whats written more easily. > i would really appreciate some one to lern me and give > me basic step by step instructions Similarly computers like us to spell things carefully and use the right grammar, just like a normal language (this is a problem for me because I type too fast for my own good and make lots of mistakes!). So treat the computer like a very literally minded English teacher who won't tolerate any spelling or grammar mistakes and you'll get along just fine! Then to understand what you need to input to create a program you need to think a bit like a math student doing algebra. Lots of variables and math operations and grouping of values in parentheses etc. Itsnot rocket science just the basics of English and Math that you get taught in junior school. But basically computers aren't very bright so programmers have to do their thinking for them! HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From klas.martelleur at telia.com Mon Aug 2 23:51:00 2004 From: klas.martelleur at telia.com (Klas Marteleur) Date: Mon Aug 2 23:42:57 2004 Subject: [Tutor] Question on a example in the book "Learn to program usingpython" by Alan Gauld In-Reply-To: <006601c478cc$1d3fd2c0$6401a8c0@xp> References: <200408011710.24330.klas.martelleur@telia.com> <200408021634.18024.klas.martelleur@telia.com> <006601c478cc$1d3fd2c0$6401a8c0@xp> Message-ID: <200408022351.00728.klas.martelleur@telia.com> Sorry to bother you guys again with a few more "stupid" questions more, just so i understand everything correct. Is it correct... 1. that there is nothing in this program that "senses" which type of file i pass as a parameter? 2. that if you want to analyse a .txt file instead of a .html file, you change the last bit from "D = HTMLDocument(sys.argv[1])" to "D = TextDocument(sys.argv[1])"? Kind regards Klas m?ndagen den 2 augusti 2004 22.05 skrev Alan Gauld: > > Shouldnt there be a "...D = TextDocument(sys.argv[1])... " somewere? > > Only if you pass it .txt files. > An interesting excercise would be to strip off the last bit of > the filename and see if it matches '.txt' or '.htm' or '.html' > and create the appropriate type of document object. > > Hint: There is a module for manipulating filenames :-) > > > OT...and Alan you should not be sorry for the small errors in your > > book, > > > its the best "computer book" i have ever read > > Aw shucks! :-) > > As to your problem, I can't see anything significantly different to > my original code (as per the CD ROM with the book and written prior > to the reviewers and copy-editors and typesetters "improvements"!) > which definitely works... > > I'll try to get back to it later tonight. > Meantime, what kind of file are you passing as a parameter? > And are you actually using TextDocument or HTMLDocument? > > Regards, > > Alan G. From alan.gauld at blueyonder.co.uk Tue Aug 3 00:41:15 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Aug 3 00:40:45 2004 Subject: [Tutor] Question on a example in the book "Learn to program usingpython" by Alan Gauld References: <200408011710.24330.klas.martelleur@telia.com> <200408021634.18024.klas.martelleur@telia.com> <006601c478cc$1d3fd2c0$6401a8c0@xp> <200408022351.00728.klas.martelleur@telia.com> Message-ID: <007e01c478e1$d1dd9130$6401a8c0@xp> > Sorry to bother you guys again with a few more "stupid" questions > more, just so i understand everything correct. > > 1. that there is nothing in this program that "senses" which type > of file i pass as a parameter? Nope, the computer is too stupid to know the difference, it just sees a file full of characters, it has no idea what those characters mean, the programmer must provide that intelligence. To the computer a python program file and an html file are both just plain text files. Windows explorer as an application has a notion of the diffrence, but really thats just detecting the file ending and comparing with a database of such endings in the Windows registry - exactly the kind of thing you would need to write but on a bigger scale. > 2. that if you want to analyse a .txt file instead of a .html file, > you change the last bit from "D = HTMLDocument(sys.argv[1])" to > "D = TextDocument(sys.argv[1])"? Correct, either that or you write the extra code to detect which kind of file it is and select the document type accordingly. Thats one advantage of the GUI solution - it has a toggle box to allow the user to select at run time. Alan G. From alan.gauld at blueyonder.co.uk Tue Aug 3 00:47:10 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Aug 3 00:46:40 2004 Subject: [Tutor] Question on a example in the book "Learn to program usingpython" by Alan Gauld References: <200408011710.24330.klas.martelleur@telia.com><6.1.0.6.0.20040801111700.028da380@mail4.skillsoft.com><200408021634.18024.klas.martelleur@telia.com> <200408022048.54430.klas.martelleur@telia.com> Message-ID: <009501c478e2$a5aee0e0$6401a8c0@xp> > Ohh man... it was the HTMLDocument() that was the problem.... > as it clearly says on the errata page that Alan tip me about Ah well at least you found it. It also means you have the early first printing which has all of the typos, most got fixed in the second printing... Unfortunately I can't do much about that but at least you know now that all of those errata fixes need to be applied not just the second set... > Now i just have to understand what was wrong with the old one :) And that's the most important thing. :-) Alan G. From rdm at rcblue.com Tue Aug 3 10:31:08 2004 From: rdm at rcblue.com (Dick Moores) Date: Tue Aug 3 10:31:16 2004 Subject: [Tutor] What's the problem with my SpinSpeeds.py? In-Reply-To: <005401c478bd$795b11a0$6401a8c0@xp> References: <6.1.2.0.2.20040801131105.0438cec0@rcblue.com> <005401c478bd$795b11a0$6401a8c0@xp> Message-ID: <6.1.2.0.2.20040803012541.029fc3c0@rcblue.com> Alan Gauld wrote at 11:21 8/2/2004: > > t = Timer("countUsingRange(n)", "from __main__ import > > countUsingRange, n") > > rangeTime = t.timeit(repetitions) > >This executes and times the string > >"countUsingRange(n)" > >after first executing > >"from __main__ import countUsingRange, n". Thank you for clearing up some of the mystery. The basic one for me is what it means to execute a string, as in, 'This executes and times the string "countUsingRange(n)"'. And why does Timer take arguments that are in quotes, (which makes them strings, I suppose). It seems that my discovery of the timeit module has gotten me in over my head, IOW ahead of myself in my learning of Python. Dick Moores From davholla2002 at yahoo.co.uk Tue Aug 3 14:15:41 2004 From: davholla2002 at yahoo.co.uk (=?iso-8859-1?q?David=20Holland?=) Date: Tue Aug 3 14:15:42 2004 Subject: [Tutor] Shut down PC In-Reply-To: <20040802175351.69A4B1E400F@bag.python.org> Message-ID: <20040803121541.28616.qmail@web25408.mail.ukl.yahoo.com> Thanks for all the advice I will try it this weekend. (If anyone else has any ideas please get in touch. --------------------------------- ALL-NEW Yahoo! Messenger - all new features - even more fun! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040803/1a742362/attachment.htm From kent_johnson at skillsoft.com Tue Aug 3 14:58:04 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Tue Aug 3 14:58:07 2004 Subject: [Tutor] What's the problem with my SpinSpeeds.py? In-Reply-To: <6.1.2.0.2.20040803012541.029fc3c0@rcblue.com> References: <6.1.2.0.2.20040801131105.0438cec0@rcblue.com> <005401c478bd$795b11a0$6401a8c0@xp> <6.1.2.0.2.20040803012541.029fc3c0@rcblue.com> Message-ID: <6.1.0.6.0.20040803084439.029b0d38@mail4.skillsoft.com> The timeit module is using the exec statement to run the code you give it. Exec takes a string value and runs it as Python code. For example >>> exec "print 'Hello, world!'" Hello, world! >>> exec "a=3; print a" 3 This is useful if you want to run user-supplied code, which is what timeit does. There is a brief description of exec here: http://docs.python.org/ref/exec.html If you are feeling brave you can look at timeit.py yourself and see what it does :-) (Look in the Lib directory of your Python installation.) It's use of exec is quite a bit more sophisticated than my examples. In your case, timeit actually creates a string containing this program: def inner(_it, _timer): from __main__ import countUsingRange, n _t0 = _timer() for _i in _it: countUsingRange(n) _t1 = _timer() return _t1 - _t0 It uses exec to execute the string, which _defines_ the function inner() without running it. Then it extracts the function object itself from the exec'ed code and runs it. HTH Kent At 01:31 AM 8/3/2004 -0700, Dick Moores wrote: >Alan Gauld wrote at 11:21 8/2/2004: >> > t = Timer("countUsingRange(n)", "from __main__ import >> > countUsingRange, n") >> > rangeTime = t.timeit(repetitions) >> >>This executes and times the string >> >>"countUsingRange(n)" >> >>after first executing >> >>"from __main__ import countUsingRange, n". > >Thank you for clearing up some of the mystery. The basic one for me is >what it means to execute a string, as in, 'This executes and times the string >"countUsingRange(n)"'. And why does Timer take arguments that are in >quotes, (which makes them strings, I suppose). It seems that my discovery >of the timeit module has gotten me in over my head, IOW ahead of myself in >my learning of Python. > >Dick Moores > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From aztech1200 at yahoo.com Tue Aug 3 17:38:16 2004 From: aztech1200 at yahoo.com (Aztech Guy) Date: Tue Aug 3 17:38:19 2004 Subject: [Tutor] Re: Ideas for beginning programs? games, math, UNIX-style filters In-Reply-To: Message-ID: <20040803153816.52250.qmail@web53308.mail.yahoo.com> Hi Bryan, As some others have suggested, games (in your case, I's suggest starting off with small ones, since you say you're a beginner) are generally considered a great way to learn programming - not to mention having fun ..... :-) So you could try some simple, known games, or even make up some simple games of your own, and then write programs that implement them. e.g. the guess a number game (already mentioned by some), tic-tac-toe (noughts and crosses), Nim, etc. Programs to do mathematical calculations are another good area, and you don't need a Ph.D. in math. for many of the areas, either. There's a whole category of simple math./arithmetic problems that can be solved by writing programs. Examples: - finding prime numbers - finding the only/some/all numbers in a given range, that satisfy some property, like: - starts with a given digit(s) / has a given digit(s) / ends with ditto - sum of the digits is even / odd / a prime / other ... - finding perfect numbers (Google to know what it is) - finding factorials, Fibonacci numbers - alphanumeric puzzles, example: SEND + MORE ------ MONEY In the above problem, you have to find the digits that the letters represent, such that substiting the digits makes the above a valid sum, i.e. SEND + MORE = MONEY. Google for 'math puzzles' or 'arithmetic puzzles' or similar phrases to get more ideas ....... Programs like UNIX filters can be fun, too - these are programs that read some input, either from standard input or from a file, do some processing of some kind on the data read, and write the results to standard output. e.g. printing/deleting lines that contain a certain letter/word/phrase, summing up numbers in a given column of the input, counting the number of characters, lines and words, converting upper case to lower or vice versa, removing punctuation, changing multiple spaces/tabs to a single space/tab, etc.... To get some info about filters (also known as command-line utilities, try reading this article of mine on the subject: http://www-106.ibm.com/developerworks/opensource/library/l-clutil Its written in C, not Python, and you might find it slightly on the advanced side; on the other hand, it was written as a tutorial-cum-example on writing filters, and I think the topic is explained with a good amount of detail, step by step, so you may be able to get enough info about how to write a filter, and then write some in Python - yes, filters can be written quite easily in Python too - it supports standard input/output/error. Also the filters you write, unless they use any UNIX-specific features, should work on Windows as well, possibly with some changes. HTH Az. > Bryan Fields unitedgaribay.com> writes: > > > My question to the list is: Can anyone present me > with some good ideas for > > programs to write using the concepts I have > studied so far? > __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From klas.martelleur at telia.com Tue Aug 3 18:01:03 2004 From: klas.martelleur at telia.com (Klas Marteleur) Date: Tue Aug 3 17:52:52 2004 Subject: [Tutor] Is it possible to add PYTHONPATHS recursively? Message-ID: <200408031801.03985.klas.martelleur@telia.com> Hi again Is it possible to add PYTHONPATHS recursively, so that every subfolder will be included? Now i am creating .pth files under site-packages. Klas From alan.gauld at blueyonder.co.uk Tue Aug 3 19:29:36 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Aug 3 19:28:54 2004 Subject: [Tutor] What's the problem with my SpinSpeeds.py? References: <6.1.2.0.2.20040801131105.0438cec0@rcblue.com><005401c478bd$795b11a0$6401a8c0@xp> <6.1.2.0.2.20040803012541.029fc3c0@rcblue.com> Message-ID: <00e401c4797f$72bd69c0$6401a8c0@xp> > >This executes and times the string > > > >"countUsingRange(n)" > > > >after first executing > > > >"from __main__ import countUsingRange, n". > > Thank you for clearing up some of the mystery. The basic one for me is > what it means to execute a string, I haven't checked the code but I imagine that the timer uses eval() or exec() to execute the string passed in (as you say it's a string because it's in quotes, but also because that's what the function is looking for!) You can think of it a bit like the timer wrapping up a Python >>> prompt inside a function. Just as the >>> prompt takes a string (the characters we type) and executes it, so the timer takes a string and executes it. > discovery of the timeit module has gotten me in over my head, IOW ahead > of myself in my learning of Python. Thats OK, sometimes the big discoveries ome that way. But if it gets too dizzy just back off and come back to it later. Alan G. From alipolatel at yahoo.com Tue Aug 3 19:43:58 2004 From: alipolatel at yahoo.com (Ali Polatel) Date: Tue Aug 3 19:44:01 2004 Subject: [Tutor] Some Questions about Python Message-ID: <20040803174358.13723.qmail@web61004.mail.yahoo.com> Dear Friends, I have some questions about Python : 1.Can we delete or create a file with Python? 2.Can we rename a file with Python? 3.How can we restart a computer or shutdown a computer with python? thanks __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040803/1a643d54/attachment.htm From kent_johnson at skillsoft.com Tue Aug 3 20:32:39 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Tue Aug 3 20:32:58 2004 Subject: [Tutor] Is it possible to add PYTHONPATHS recursively? In-Reply-To: <200408031801.03985.klas.martelleur@telia.com> References: <200408031801.03985.klas.martelleur@telia.com> Message-ID: <6.1.0.6.0.20040803142343.0296da48@mail4.skillsoft.com> You could do this programmatically in sitecustomize.py: - Put a module named sitecustomize.py in your Python/Lib directory - Make whatever changes you want to sys.path in this module, e.g. import sys sys.path.append() (Use os.walk() to traverse a directory tree) - sitecustomize.py will be executed every time the interpreter starts I'm not sure it's a good idea to append every subfolder of site-packages, since some packages will have subpackages (in folders) that shouldn't become top-level packages. You might want to have a single subfolder of site-packages that you put your folders in. Then in sitecustomize.py you would recursively traverse that folder. Kent At 06:01 PM 8/3/2004 +0200, Klas Marteleur wrote: >Hi again > >Is it possible to add PYTHONPATHS recursively, so that every subfolder >will be >included? > >Now i am creating .pth files under site-packages. > >Klas >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From dyoo at hkn.eecs.berkeley.edu Tue Aug 3 22:35:49 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Aug 3 22:35:53 2004 Subject: [Tutor] Some Questions about Python In-Reply-To: <20040803174358.13723.qmail@web61004.mail.yahoo.com> Message-ID: On Tue, 3 Aug 2004, Ali Polatel wrote: > 1.Can we delete or create a file with Python? > 2.Can we rename a file with Python? Hi Ali, You may want to look at: http://www.python.org/doc/lib/os-file-dir.html The functions os.unlink() and os.rename() should apply to your question. You may also want to look at some tutorials at: http://www.python.org/topics/learn/non-prog.html as these should cover how to do standard input-output in Python. > 3.How can we restart a computer or shutdown a computer with python? We actually had some discussion about this yesterday. Here's a link to the relevant thread: http://mail.python.org/pipermail/tutor/2004-August/030849.html Good luck! From bill at celestial.net Tue Aug 3 23:29:26 2004 From: bill at celestial.net (Bill Campbell) Date: Tue Aug 3 23:29:29 2004 Subject: [Tutor] python equivalent to perl hash slices? Message-ID: <20040803212926.GA72649@alexis.mi.celestial.com> Is there a python equivalent to perl's hash slices which I use extensively to simplify jobs such as parsing tabular data. As an example, in perl I might handle a file where the first line of the file is a tab delimited set of column names, with something like this: #!/usr/local/bin/perl my $line1 = <>; # get first line of input chomp($line1); my @fields = split("\n", $line); my @outlist = qw(field1 field2); my %record; while(<>) { chomp; @record{@fields} = split("\n"); # %record is now a hash (dictionary) with keys in the order # specified in the first line. print join("\t", @record(@outlist)) . "\n"; # This prints only the members of the %record dictionary # with the keys specified in @outlist } __END__ I now use this extensively with mysql and postgresql database functions to write generic classes based on table metadata, and to do conversions of data from other sources (e.g. ancient Unify RDBMS SQL output). Bill -- INTERNET: bill@Celestial.COM Bill Campbell; Celestial Software LLC UUCP: camco!bill PO Box 820; 6641 E. Mercer Way FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 http://www.celestial.com/ "I do not feel obliged to believe that the same God who has endowed us with sense, reason, and intellect has intended us to forego their use." -- Galileo Galilei From dyoo at hkn.eecs.berkeley.edu Tue Aug 3 23:49:52 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Aug 3 23:50:09 2004 Subject: [Tutor] python equivalent to perl hash slices? In-Reply-To: <20040803212926.GA72649@alexis.mi.celestial.com> Message-ID: On Tue, 3 Aug 2004, Bill Campbell wrote: > Is there a python equivalent to perl's hash slices which I use > extensively to simplify jobs such as parsing tabular data. Hi Bill, Not directly; the reason that something like: ### >>> mapping = {0: 'zero', 1: 'one', 2:'two', 3:'three', 4:'four', ... 5: 'five', 6: 'six', 7:'seven', 8:'eight', 9:'nine'} >>> >>> mapping[3,1,4,1,5,9,2,6] Traceback (most recent call last): File "", line 1, in ? KeyError: (3, 1, 4, 1, 5, 9, 2, 6) ### doesnt work is because sequences are perfectly possible as "composite keys" in Python. This is useful when we want to do something representing a table or graph: ### >>> sparse_graph = {} >>> sparse_graph[0, 0] = 'origin' >>> sparse_graph[1, 42] = 'point1' >>> sparse_graph[-3, 17] = 'point2' ### There's no built-in, as far as I remember, for doing dictionary slices in Python. That being said, your particular code example can be written with zip(), since you have a list of keys and values, and you want to just put them together. Here's an example of zip(): ### >>> zip(["zero", "one", "two", "three", "four", "five"], ... [0, 1, 2, 3, 4, 5]) [('zero', 0), ('one', 1), ('two', 2), ('three', 3), ('four', 4), ('five', 5)] ### This should allow you to transcribe: @record{@fields} = split("\t"); ## Perl as something like: record = zip(fields, line.split('\t')) ## Python The other part of code gets a list of values, given a list of keys. That can be handled by something like this: ### >>> def dict_slice(d, keys): ... return map(d.get, keys) ... ### For example: ### >>> dict_slice({0: 'zero', 1: 'one', 2:'two', 3:'three', 4:'four', ... 5: 'five', 6: 'six', 7:'seven', 8:'eight', 9:'nine'}, ... [3,1,4,1,5,9,2,6]) ['three', 'one', 'four', 'one', 'five', 'nine', 'two', 'six'] ### Hope this helps! From dyoo at hkn.eecs.berkeley.edu Wed Aug 4 00:14:56 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Aug 4 00:14:59 2004 Subject: [Tutor] python equivalent to perl hash slices? In-Reply-To: Message-ID: > That being said, your particular code example can be written with zip(), > since you have a list of keys and values, and you want to just put them > together. Here's an example of zip(): > > ### > >>> zip(["zero", "one", "two", "three", "four", "five"], > ... [0, 1, 2, 3, 4, 5]) > [('zero', 0), ('one', 1), ('two', 2), ('three', 3), ('four', 4), ('five', > 5)] > ### Hi Bill, Gah! That's wrong! *grin* I'm sorry; I must have been daydreaming. The above produces a list of key-value pairs, but that's not a dict. So needs one more thing: dict(): ### >>> cols = ['zero', 'one', 'two', 'three', 'four', 'five'] >>> vals = [0, 1, 2, 3, 4, 5] >>> d = dict(zip(cols, vals)) >>> d {'three': 3, 'two': 2, 'four': 4, 'zero': 0, 'five': 5, 'one': 1} ### And now we have a dictionary. My apologies again for the mistake! From ppareek at ualberta.ca Wed Aug 4 00:48:52 2004 From: ppareek at ualberta.ca (Priyanka) Date: Wed Aug 4 00:48:54 2004 Subject: [Tutor] creating directories Message-ID: <4AD6B67A-E59F-11D8-B1FC-000A95D1A54E@ualberta.ca> given a filename with the path, is there a possible way to create a new file with that name, simultaneously creating the directories in the file path. Suppose that I have to write to a file named: "dir1/dir2/dir3/name.html", where only dir1 exists, is it possible to create dir2 and dir3 and open a new file name.html to write on to. Thanks, ppareek From bigapple631 at optonline.net Wed Aug 4 01:01:06 2004 From: bigapple631 at optonline.net (jason hochstein) Date: Wed Aug 4 01:00:37 2004 Subject: [Tutor] read and write data?? Message-ID: <003601c479ad$c21dc310$bc4ebb18@hochstein> I cant figure out how to write data into or read data out of a file. I keep getting errors saying the file I create doesn't exist, even though I see it in my saved docs. What am I doing wrong? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040803/6ff9ebed/attachment.htm From pythonTutor at venix.com Wed Aug 4 01:32:48 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Wed Aug 4 01:32:52 2004 Subject: [Tutor] creating directories In-Reply-To: <4AD6B67A-E59F-11D8-B1FC-000A95D1A54E@ualberta.ca> References: <4AD6B67A-E59F-11D8-B1FC-000A95D1A54E@ualberta.ca> Message-ID: <1091575967.2098.181.camel@laptop.venix.com> The os module has a function called makedirs which will make the directories in a path. You can then use open to create the file. os.makedirs('dir1/dir2/dir3', mode= ) # umask will also be applied myfile = open('dir1/dir2/dir3/name.html', 'wt') On Tue, 2004-08-03 at 18:48, Priyanka wrote: > given a filename with the path, is there a possible way to create a new > file with that name, simultaneously creating the directories in the > file path. > Suppose that I have to write to a file named: > "dir1/dir2/dir3/name.html", where only dir1 exists, is it possible to > create dir2 and dir3 and open a new file name.html to write on to. > > Thanks, > ppareek > > _______________________________________________ > 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 bill at celestial.net Wed Aug 4 01:34:22 2004 From: bill at celestial.net (Bill Campbell) Date: Wed Aug 4 01:34:25 2004 Subject: [Tutor] python equivalent to perl hash slices? In-Reply-To: References: Message-ID: <20040803233422.GA79290@alexis.mi.celestial.com> On Tue, Aug 03, 2004, Danny Yoo wrote: > >> That being said, your particular code example can be written with zip(), >> since you have a list of keys and values, and you want to just put them >> together. Here's an example of zip(): >> >> ### >> >>> zip(["zero", "one", "two", "three", "four", "five"], >> ... [0, 1, 2, 3, 4, 5]) >> [('zero', 0), ('one', 1), ('two', 2), ('three', 3), ('four', 4), ('five', >> 5)] >> ### > >Hi Bill, > >Gah! That's wrong! *grin* A mistake! I've never made one of those (a few million maybe :-). >I'm sorry; I must have been daydreaming. The above produces a list of >key-value pairs, but that's not a dict. So needs one more thing: >dict(): > >### >>>> cols = ['zero', 'one', 'two', 'three', 'four', 'five'] >>>> vals = [0, 1, 2, 3, 4, 5] >>>> d = dict(zip(cols, vals)) >>>> d >{'three': 3, 'two': 2, 'four': 4, 'zero': 0, 'five': 5, 'one': 1} >### > >And now we have a dictionary. I remember now reading about zip in the O'Reilly ``Learning Python'' book, and thinking it might be useful. One could then get the array slice for values with something like this, or is there an easier way? >>> map((lambda k: d.get(k, None)), cols) Bill -- INTERNET: bill@Celestial.COM Bill Campbell; Celestial Software LLC UUCP: camco!bill PO Box 820; 6641 E. Mercer Way FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 URL: http://www.celestial.com/ ``The children who know how to think for themselves spoil the harmony of the collective society that is coming, where everyone would be interdependent.'' 1899 John Dewey, educational philosopher, proponent of modern public schools. From dyoo at hkn.eecs.berkeley.edu Wed Aug 4 01:50:17 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Aug 4 01:50:21 2004 Subject: [Tutor] read and write data?? In-Reply-To: <003601c479ad$c21dc310$bc4ebb18@hochstein> Message-ID: On Tue, 3 Aug 2004, jason hochstein wrote: > I cant figure out how to write data into or read data out of a file. I > keep getting errors saying the file I create doesn't exist, even though > I see it in my saved docs. What am I doing wrong? Hi Jason, We need a little more information. Can you show us what the literal error message is? Also, show us the snippet of code that you're using to open() your file. It's usually best to try to send us enough information so that we can try to duplicate the problem that you're getting. And when you get exceptions, copy-and-paste the error message; error messages often have very subtle clues as to what's going on. The problem might be as simple as a backslash-escaping issue (if you're on Windows), or opening a file in read-mode instead of write mode. We can't what's going on without more information, though. Here's a small example of opening and closing files: ### >>> >>> f = open('message', 'w') >>> f.write("This is a message") >>> f.write("do you see this?") >>> f.close() >>> >>> >>> f = open('message') >>> for line in f: ... print line.upper() ... THIS IS A MESSAGEDO YOU SEE THIS? ### Hope this helps! From rdm at rcblue.com Wed Aug 4 07:46:30 2004 From: rdm at rcblue.com (Dick Moores) Date: Wed Aug 4 07:46:32 2004 Subject: [Tutor] What's the problem with my SpinSpeeds.py? Message-ID: <6.1.2.0.2.20040803224603.020e9540@rcblue.com> Thanks very much for adding to my understanding. Dick Moores Kent Johnson wrote at 05:58 8/3/2004: >The timeit module is using the exec statement to run the code you give it. > >Exec takes a string value and runs it as Python code. For example > >>> exec "print 'Hello, world!'" >Hello, world! > >>> exec "a=3; print a" >3 > >This is useful if you want to run user-supplied code, which is what >timeit does. >There is a brief description of exec here: >http://docs.python.org/ref/exec.html > >If you are feeling brave you can look at timeit.py yourself and see what >it does :-) (Look in the Lib directory of your Python installation.) >It's use of exec is quite a bit more sophisticated than my examples. In >your case, timeit actually creates a string containing this program: >def inner(_it, _timer): > from __main__ import countUsingRange, n > _t0 = _timer() > for _i in _it: > countUsingRange(n) > _t1 = _timer() > return _t1 - _t0 > >It uses exec to execute the string, which _defines_ the function inner() >without running it. Then it extracts the function object itself from the >exec'ed code and runs it. > >HTH >Kent From kent_johnson at skillsoft.com Wed Aug 4 15:01:59 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Wed Aug 4 15:02:02 2004 Subject: [Tutor] Perl phrasebook Message-ID: <6.1.0.6.0.20040804090004.028eb150@mail4.skillsoft.com> Here is a new resource for people migrating from Perl to Python: http://www.python.org/moin/PerlPhrasebook Kent From alan.gauld at blueyonder.co.uk Wed Aug 4 17:34:32 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Aug 4 17:34:21 2004 Subject: [Tutor] read and write data?? References: <003601c479ad$c21dc310$bc4ebb18@hochstein> Message-ID: <014401c47a38$8a1f97a0$6401a8c0@xp> > I cant figure out how to write data into or read data out of a file. Try the file handling topic in my tutor... > I keep getting errors saying the file I create doesn't exist, > even though I see it in my saved docs. What am I doing wrong? I have no idea, without seeing your code its impossible to tell. If you post the code (or sample if its very long) plus any errors we might be able to see whats happening. It might be worth telling us what OS you are using too. Alan G. From tim at johnsons-web.com Wed Aug 4 23:08:25 2004 From: tim at johnsons-web.com (Tim Johnson) Date: Wed Aug 4 23:03:55 2004 Subject: [Tutor] Perl template toolkit accessibility Message-ID: <20040804210825.GI1854@johnsons-web.com> I know this is a *python* ML. Anyway, I program in python, my partner programs in perl. The perl template toolkit is pretty awesome, and he says he thinks that there are hooks into it for python. Does anyone know anything about this? Pointers to docs and links would be just fine at this stage. thanks tim -- Tim Johnson http://www.alaska-internet-solutions.com From bill at celestial.net Thu Aug 5 00:48:42 2004 From: bill at celestial.net (Bill Campbell) Date: Thu Aug 5 00:48:46 2004 Subject: [Tutor] Perl template toolkit accessibility In-Reply-To: <20040804210825.GI1854@johnsons-web.com> References: <20040804210825.GI1854@johnsons-web.com> Message-ID: <20040804224842.GA62674@alexis.mi.celestial.com> On Wed, Aug 04, 2004, Tim Johnson wrote: > I know this is a *python* ML. Anyway, I > program in python, my partner programs in > perl. The perl template toolkit is pretty > awesome, and he says he thinks that there are > hooks into it for python. Does anyone > know anything about this? > >Pointers to docs and links would be just fine >at this stage. You might look at Zope and Plone. I've done a fair amount of programming using the perl CGI::Application and HTML::Template modules, and am pretty new to python, Zope and Plone (PZP). The perl modules mentioned above allow one to build complete applications using standard perl methodology, using templates to largely separate the display and programming efforts. Zope templates mix pretty freely with scripts (python), ZSQL methods, data connectors, and other objects which allows what may be a more flexible building block approach rather than a more monolithic application, and thus easier for relatively inexperienced people to use for ad-hoc pages, queries, and applications. Bill -- INTERNET: bill@Celestial.COM Bill Campbell; Celestial Software LLC UUCP: camco!bill PO Box 820; 6641 E. Mercer Way FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 URL: http://www.celestial.com/ The ultimate result of shielding men from the effects of folly is to fill the world with fools. -- Herbert Spencer (1891) From tim at johnsons-web.com Thu Aug 5 01:11:53 2004 From: tim at johnsons-web.com (Tim Johnson) Date: Thu Aug 5 01:07:19 2004 Subject: [Tutor] Perl template toolkit accessibility In-Reply-To: <20040804224842.GA62674@alexis.mi.celestial.com> References: <20040804210825.GI1854@johnsons-web.com> <20040804224842.GA62674@alexis.mi.celestial.com> Message-ID: <20040804231153.GJ1854@johnsons-web.com> * Bill Campbell [040804 14:59]: > On Wed, Aug 04, 2004, Tim Johnson wrote: > > I know this is a *python* ML. Anyway, I > > program in python, my partner programs in > > perl. The perl template toolkit is pretty > > awesome, and he says he thinks that there are > > hooks into it for python. Does anyone > > know anything about this? > > > >Pointers to docs and links would be just fine > >at this stage. > > You might look at Zope and Plone. Thanks Bill. I will check that out. One of the things that I will look for is a way to create the code via python and then submit it as content, via stdout just as one can create html, javascript, css etc. and submit to stdout. That could be one way. Perl and python have such awesome resources that to be able to exploit the resources of one by the other might be a leg up on both. cheers tim > I've done a fair amount of programming using the perl CGI::Application and > HTML::Template modules, and am pretty new to python, Zope and Plone (PZP). > The perl modules mentioned above allow one to build complete applications > using standard perl methodology, using templates to largely separate the > display and programming efforts. Zope templates mix pretty freely with > scripts (python), ZSQL methods, data connectors, and other objects which > allows what may be a more flexible building block approach rather than a > more monolithic application, and thus easier for relatively inexperienced > people to use for ad-hoc pages, queries, and applications. > > Bill > -- > INTERNET: bill@Celestial.COM Bill Campbell; Celestial Software LLC > UUCP: camco!bill PO Box 820; 6641 E. Mercer Way > FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 > URL: http://www.celestial.com/ > > The ultimate result of shielding men from the effects of folly is to fill > the world with fools. -- Herbert Spencer (1891) -- Tim Johnson http://www.alaska-internet-solutions.com From ppareek at ualberta.ca Thu Aug 5 01:14:12 2004 From: ppareek at ualberta.ca (Priyanka) Date: Thu Aug 5 01:14:14 2004 Subject: [Tutor] reading forms Message-ID: Hi, I have created a html form that posts the comments posed by a visitor to my website. It has a text area for letting the visitor write the comment in. However when I use cgi.FieldStorage() to get the string in the text area, it is not printing out the '\n' character of the string. Thus, even when I use the string.replace() function to replace the '\n' characters with , it is not doing so. Also, is there any method by which the browser would not interpret the HTML tags in the comment area and print them out as is? thanks, ppareek From m at mongers.org Thu Aug 5 01:54:17 2004 From: m at mongers.org (Morten Liebach) Date: Thu Aug 5 02:02:52 2004 Subject: [Tutor] Perl template toolkit accessibility In-Reply-To: <20040804210825.GI1854@johnsons-web.com> References: <20040804210825.GI1854@johnsons-web.com> Message-ID: <20040804235439.GA610@mongers.org> On 2004-08-04 13:08:25 -0800, Tim Johnson wrote: > I know this is a *python* ML. Anyway, I > program in python, my partner programs in > perl. The perl template toolkit is pretty > awesome, and he says he thinks that there are > hooks into it for python. Does anyone > know anything about this? > > Pointers to docs and links would be just fine > at this stage. Cheetah templates (http://www.cheetahtemplate.org/) might suit you. Have a nice day Morten -- http://m.mongers.org/ -- http://gallery.zentience.org/ __END__ From kent_johnson at skillsoft.com Thu Aug 5 02:10:32 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Thu Aug 5 02:11:23 2004 Subject: [Tutor] reading forms In-Reply-To: References: Message-ID: <6.1.0.6.0.20040804200539.028f7ff0@mail4.skillsoft.com> At 05:14 PM 8/4/2004 -0600, Priyanka wrote: >Hi, >I have created a html form that posts the comments posed by a visitor to >my website. It has a text area for letting the visitor write the comment >in. However when I use cgi.FieldStorage() to get the string in the text >area, it is not printing out the '\n' character of the string. Thus, >even when I use the string.replace() function to replace the '\n' >characters with , it is not doing so. You should use
or
not >Also, is there any method by which the browser would not interpret the >HTML tags in the comment area and print them out as is? Do you mean you want to show the comment in an HTML page? Try cgi.escape(comment), this will turn '&<>' into '&<>' Kent From janos.juhasz at VELUX.com Thu Aug 5 10:42:01 2004 From: janos.juhasz at VELUX.com (janos.juhasz@VELUX.com) Date: Thu Aug 5 10:42:05 2004 Subject: [Tutor] reading sequencies from text file Message-ID: Hi All, I always had the same problem with python. I want to assign value in condition, but it isn't valid in Python. I want to write always like while (seq=fread(f, 4340)) { fwrite(....); } But I could do just like this f = open('K:/IT/gsm/mobilok.SPB') e = open('K:/IT/gsm/mobilok.txt', 'wt') while 1: actline = f.read(4340) if len(actline) == 4340: e.write(actline[:70]) e.write('\n') else: break f.close() e.close() Is it the pythonic way? Yours sincerely, ______________________________ J?nos Juh?sz -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040805/a35e5c14/attachment.html From adam at monkeez.org Thu Aug 5 11:32:37 2004 From: adam at monkeez.org (Adam) Date: Thu Aug 5 11:33:17 2004 Subject: [Tutor] wav sound Message-ID: <20040805103237.17e6b3a9@debian> I'm writing a wxPython app and want to play small wav files. Anyone suggest how to do this? I'd like it to be cross-platform friendly. So far I have... sounds = {30:'a.wav', 31:'b.wav'.... and so on} sound_file = 'sound_media/' + sounds[text] playsound = open(sound_file,'rb') totalframes = playsound.getnframes() playsound.readframes(totalframes) but it's not working - am I wrong to assume that it is this simple? Thanks Adam -- ============================= site: http://www.monkeez.org wiki: http://wiki.monkeez.org ============================= From andy at andybak.net Thu Aug 5 11:38:04 2004 From: andy at andybak.net (Andy Baker) Date: Thu Aug 5 11:38:07 2004 Subject: [Tutor] Dumb Subclassing question Message-ID: <20040805093805.558011E4009@bag.python.org> Hi all, Please bear with me as I might have this hopelessly muddled. My attempts to learn OO through simple cases never turn out that simple... I, like everyone else in the universe, am writing a prog to manipulate and organize mp3's... The idea was to base it on Jason Orendorff 'path' module (http://www.jorendorff.com/articles/python/path/) and add some methods to the path object that are mp3 specific. So I subclass the 'path' object as 'mp3path' and add some of my own methods. Several of the methods in the original 'path' return more path objects so the methods I inherit from path also return path objects. I want my new methods to act on the returned objects. An example: myPath.files() returns a list of path objects I have added a new method ID3tag to my MP3path class I want myMP3path.files to return a list of objects that can still access my ID3tag method. Options that have occurred to me: 1. Override every method in 'path' that returns paths with a wrapper method that converts them into mp3paths. This seems ugly, boring and pointless. 2. Forget subclassing and add methods directly into the path module source. This will be bad when a new version of 'path' comes along and also seems like cheating. 3. Add methods dynamically into the path object. (Is this 'decorator'?) I looked at the instancemethod function in the standard library 'new' module and this adds methiods to instances but not to classes so I would have to do this for every instance. 4. Forget the whole OO thang and just use functions. (Looking more attractive by the minute ;-) Am I being thick here? What's the proper way to do this? I can see a similar situation happeneing if I ever subclass 'string' or suchlike. From alan.gauld at blueyonder.co.uk Thu Aug 5 14:43:01 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Aug 5 14:42:36 2004 Subject: [Tutor] reading sequencies from text file References: Message-ID: <002c01c47ae9$beae9e60$6401a8c0@xp> > I want to write always like > > while (seq=fread(f, 4340)) > { fwrite(....); > } > while 1: > actline = f.read(4340) > if len(actline) == 4340: > e.write(actline[:70]) > e.write('\n') > else: break > Is it the pythonic way? Pretty much although usually the break is put inside the if, like this: while 1: actline = f.read(4340) if len(actline) < 4340: break e.write(actline[:70]) e.write('\n') Which avoids an extra level of structural complexity for the mainline code. Another way closer to your prefered route is to create a File class that reads the data into a buffer. Somewhat like: class File: def __init__(self,name,mode='r'): self.f = open(name,mode) def read(self,size=0): self.buffer = self.f.read(size) return len(self.buffer) etc.... f = File('foo.txt') while f.read(4340) == 4340: # do stuff with f.buffer If you do that kind of file processing often you might find the effort of creating it in a module worthwhile. HTH, Alan G. From alan.gauld at blueyonder.co.uk Thu Aug 5 15:01:06 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Aug 5 15:00:41 2004 Subject: [Tutor] Dumb Subclassing question References: <20040805093805.558011E4009@bag.python.org> Message-ID: <003301c47aec$45616da0$6401a8c0@xp> > I, like everyone else in the universe, am writing a prog to manipulate and > organize mp3's... Nope, I just use iTunes :-) > So I subclass the 'path' object as 'mp3path' and add some of my own methods. Sounds OK. > I have added a new method ID3tag to my MP3path class > I want myMP3path.files to return a list of objects that can still access my > ID3tag method. In that case they need to have access to objects of your class. Or do you mean you want other objects to access the ID3tag method of the returned objects? ie the returned objects should have ID3tag methods? > Options that have occurred to me: > > 1. Override every method in 'path' that returns paths with a wrapper method > that converts them into mp3paths. This seems ugly, boring and pointless. Its the only sensible way if you want all path objects to be your specialised variants. How else can the path objects be treated as your objects unless they get converted at some stage? But see below... > 2. Forget subclassing and add methods directly into the path module source. > This will be bad when a new version of 'path' comes along and also seems > like cheating. It will break all sorts of things, especially if you try using path for something where you really want path objects! Or more likely you try to use a 3rd party bit of code that expects real path objects... > 3. Add methods dynamically into the path object. (Is this 'decorator'?) No its not decorator and is even more messy! > looked at the instancemethod function in the standard library 'new' module > and this adds methiods to instances but not to classes so I would have to do > this for every instance. Exactly so. Yuk! > 4. Forget the whole OO thang and just use functions. (Looking more > attractive by the minute ;-) How would that help? You still have the same issues? One thing you might like to consider is the composite pattern. Here we distinguish between link nodes and leafnodes of a tree. You only want path nodes to gave ID3tags methods if they are leaf nodes(ie files) I assume? So you can write a function that determines the nature of path node you get and only convert the leaf nodes to your class type. That is instead of overriding path to retirn your objects why not get the list of paths back and then convert those as needed to your class? Does that make sense - I don't think I'm explaining it very well... And don't have time for an example! Basically write a type conversion function (like int(), str(),list() etc) and apply it as needed. Pseudo code: def mp3path(aVanillaPath): mp3p = MP3Path() # create new instance for attribute in aVanillaPath: # use getattr()??? mp3p.attribute = attribute # copy inherited stuff return mp3p for path in myPath.files(): if path is leaf node # using isinstance or somesuch? path = mp3path(path) path.ID3tag() # do things with new path object HTH Alan G. From rmkrauter at yahoo.com Thu Aug 5 15:05:17 2004 From: rmkrauter at yahoo.com (Rich Krauter) Date: Thu Aug 5 15:30:41 2004 Subject: [Tutor] Dumb Subclassing question In-Reply-To: <20040805093805.558011E4009@bag.python.org> References: <20040805093805.558011E4009@bag.python.org> Message-ID: <4112308D.2070504@yahoo.com> Andy Baker wrote: > Hi all, > > Please bear with me as I might have this hopelessly muddled. My attempts to > learn OO through simple cases never turn out that simple... > > I, like everyone else in the universe, am writing a prog to manipulate and > organize mp3's... > > The idea was to base it on Jason Orendorff 'path' module > (http://www.jorendorff.com/articles/python/path/) and add some methods to > the path object that are mp3 specific. > > So I subclass the 'path' object as 'mp3path' and add some of my own methods. > > Several of the methods in the original 'path' return more path objects so > the methods I inherit from path also return path objects. I want my new > methods to act on the returned objects. > > An example: > > myPath.files() returns a list of path objects > > I have added a new method ID3tag to my MP3path class > I want myMP3path.files to return a list of objects that can still access my > ID3tag method. > > Options that have occurred to me: > > 1. Override every method in 'path' that returns paths with a wrapper method > that converts them into mp3paths. This seems ugly, boring and pointless. > 2. Forget subclassing and add methods directly into the path module source. > This will be bad when a new version of 'path' comes along and also seems > like cheating. > 3. Add methods dynamically into the path object. (Is this 'decorator'?) I > looked at the instancemethod function in the standard library 'new' module > and this adds methiods to instances but not to classes so I would have to do > this for every instance. > 4. Forget the whole OO thang and just use functions. (Looking more > attractive by the minute ;-) > > Hi Andy, I'd stick with classes. You might want to try composition (has-a) instead of inheritance (is-a). One of the attributes of your MP3 object can be a path object; in addition you can add all the other attributes you need. Basic idea (untested): import your_module # substitute name of the module you're using class MP3(object): def(__init__(self,filename): self.filename = filename # don't know name of class in module you reference # so I'm making it up. (Next line is composition.) self.pathobj = your_module.path_wrapper(filename) # do some work to get info out of mp3 headers self.ID3Tag = self.get_ID3Tag(filename) ... if __name__ == '__main__: import os mp3root = '/path/to/mp3' # list to hold collection of MP3 objects mp3s = [] for root,dirs,files in os.walk(mp3root): for f in files: mp3s.append(MP3('%s/%s'%(root,f)) # now you have a collection of MP3 objects # and you can do stuff with it. ... ... Good luck. Rich From andy at andybak.net Thu Aug 5 16:09:58 2004 From: andy at andybak.net (Andy Baker) Date: Thu Aug 5 16:10:10 2004 Subject: [Tutor] Dumb Subclassing question In-Reply-To: <003301c47aec$45616da0$6401a8c0@xp> Message-ID: <20040805141008.06A601E400F@bag.python.org> > > I, like everyone else in the universe, am writing a prog to > manipulate and > > organize mp3's... > > Nope, I just use iTunes :-) Oooh I wasn't going to bite but I will anyway! I have been using a mix of 'MP3 Tag Studio' and Musicbrainz which between them are a fair bit more powerful than Itunes but I need more power! > > So I subclass the 'path' object as 'mp3path' and add some of my own > methods. > > Sounds OK. > > > I have added a new method ID3tag to my MP3path class I want > > myMP3path.files to return a list of objects that can still > access my > > ID3tag method. > > In that case they need to have access to objects of your class. > Or do you mean you want other objects to access the ID3tag > method of the returned objects? ie the returned objects > should have ID3tag methods? I mean that any path object returned should have mp3 related methods. > > Options that have occurred to me: > > > > 1. Override every method in 'path' that returns paths with a wrapper > method > > that converts them into mp3paths. This seems ugly, boring and > pointless. > > Its the only sensible way if you want all path objects to be > your specialised variants. How else can the path objects be > treated as your objects unless they get converted at some > stage? But see below... ...... > > 3. Add methods dynamically into the path object. (Is this > 'decorator'?) > > No its not decorator and is even more messy! (unrelated question: How does adding methods to existing instances differ from decorator then? I get the feeling that a lot of common design patterns don't apply exactly the same way to Python because it is less restrictive of what you can do in the first place) > > looked at the instancemethod function in the standard library 'new' > module > > and this adds methiods to instances but not to classes so I would > have to do > > this for every instance. > > Exactly so. Yuk! Well! You say Yuk but I did a bit more digging and (thanks to Mark Pilgrim:http://diveintomark.org/archives/2003/01/27/dynamically_extending_ap is ) found that despite what is implied in the standard library docs, 'instancemethod' will happily add methods to classes. This new methods then get nicely inherited by instances of the class. So I end up with code like this: ___________________ from path import * import new, id3 # Methods to add to 'path' class def _mp3s(self): return [mp3s for mp3s in self.files('*.mp3')] def _hasmp3s(self): return (self.isdir() and len(self.mp3s())>0) # Bind new methods to add to 'path' class path.mp3s = new.instancemethod(_mp3s, None, path) path.hasmp3s = new.instancemethod(_hasmp3s, None, path) testmp3 = path('testmp3') first_directory = testmp3.dirs()[0] print first_directory.hasmp3s() >>>>True _____________________ (Obviously the code don't do much yet!) This seems cleaner to me than the alternative of overriding all the methods just to add a type wrapper. I'd be interested to know what trouble I might be storing up in terms of bad OO practice... > > 4. Forget the whole OO thang and just use functions. (Looking more > > attractive by the minute ;-) > > How would that help? You still have the same issues? > One thing you might like to consider is the composite pattern. > Here we distinguish between link nodes and leafnodes of a tree. > You only want path nodes to gave ID3tags methods if they are > leaf nodes(ie files) I assume? > > So you can write a function that determines the nature of > path node you get and only convert the leaf nodes to your > class type. That is instead of overriding path to retirn your > objects why not get the list of paths back and then convert > those as needed to your class? > Well, the class I am basing myself on doesn't differentiate between path's and filenames and I find that approach fairly nice (only one object type to deal with. Just use .isfile() or isdir() if you need to know). > Does that make sense - I don't think I'm explaining it very > well... And don't have time for an example! > Basically write a type conversion function (like int(), > str(),list() etc) and apply it as needed. > > Pseudo code: > > def mp3path(aVanillaPath): > mp3p = MP3Path() # create new instance > for attribute in aVanillaPath: # use getattr()??? > mp3p.attribute = attribute # copy inherited stuff > return mp3p > > for path in myPath.files(): > if path is leaf node # using isinstance or somesuch? > path = mp3path(path) > path.ID3tag() # do things with new path object > HTH > > Alan G. > > From andy at andybak.net Thu Aug 5 16:48:10 2004 From: andy at andybak.net (Andy Baker) Date: Thu Aug 5 16:48:12 2004 Subject: [Tutor] Dumb subclassing question Message-ID: <20040805144811.7FF4F1E4009@bag.python.org> > Rich Krauter rmkrauter at yahoo.com wrote > Andy Baker wrote: ... > Hi Andy, > > I'd stick with classes. You might want to try composition > (has-a) instead of inheritance (is-a). > One of the attributes of your MP3 object can be a path > object; in addition you can add all the other attributes you need. Cheers. That gave me a whole 'Doh! Of course!' moment when I read it as I hadn't thought of the object relationship that way round. I will have a play with that but I am still tempted to persevere with adding methods dynamically as it seems like it will result in the least code. > Basic idea (untested): > > import your_module # substitute name of the module you're using > > class MP3(object): > def(__init__(self,filename): > self.filename = filename > # don't know name of class in module you reference > # so I'm making it up. (Next line is composition.) > self.pathobj = your_module.path_wrapper(filename) > > # do some work to get info out of mp3 headers > self.ID3Tag = self.get_ID3Tag(filename) > ... > > if __name__ == '__main__: > import os > mp3root = '/path/to/mp3' > # list to hold collection of MP3 objects > mp3s = [] > for root,dirs,files in os.walk(mp3root): > for f in files: > mp3s.append(MP3('%s/%s'%(root,f)) > > # now you have a collection of MP3 objects > # and you can do stuff with it. > ... > ... > > Good luck. > > Rich > > * Previous message: [Tutor] Dumb Subclassing question > * Messages sorted by: [ date ] [ thread ] [ subject ] [ author ] > > More information about the Tutor mailing list > From kent_johnson at skillsoft.com Thu Aug 5 16:51:27 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Thu Aug 5 16:51:37 2004 Subject: [Tutor] Dumb Subclassing question In-Reply-To: <20040805093805.558011E4009@bag.python.org> References: <20040805093805.558011E4009@bag.python.org> Message-ID: <6.1.0.6.0.20040805103047.029c3178@mail4.skillsoft.com> Andy, There is a way to do this by replacing path.__new__(). The __new__ method of a class is a factory that returns the actual instance object that will eventually be returned by the call to the class itself. By replacing __new__ you can return a class of a different type. I'm not sure this is a good design. A path to a directory should not have mp3 accessors, and an object representing an MP3 file doesn't need a files() method. I think Rich Krauter's approach of making an MP3 class that wraps a path to a file is probably a better design. But you raise an interesting challenge which I couldn't resist. Here is a short program that munges path() so it actually returns an instance of a subclass of path: from path import path # Here is the new subclass class MyPath(path): def coolStuff(self): print 'It works!' # Remember the old __new__ so we can delegate to it originalNew = path.__new__ # This is going to be the new path.__new__. It will return an instance of MyPath def newNew(cls, *args, **kwds): return originalNew(MyPath, *args, **kwds) # Replace path.__new__ with our new version path.__new__ = staticmethod(newNew) # Try it out p = path("C:") print type(p) p.coolStuff() f = p.files() print f[0] print type(f[0]) Running this program prints It works! C:.DS_Store You could change newNew so it looks at the arguments it is passed and only creates a MyPath if the path has a particular form, e.g. ends with '.mp3'. To do this you would call originalNew(path, *args, **kwds) when you want a plain path. You can read more about overriding __new__ here: http://www.python.org/2.2.1/descrintro.html#__new__ I hope I haven't gone beyond what is appropriate for this list - this is definitely advanced stuff. But it is a good chance for me to learn too! Kent At 10:38 AM 8/5/2004 +0100, Andy Baker wrote: >Hi all, > >Please bear with me as I might have this hopelessly muddled. My attempts to >learn OO through simple cases never turn out that simple... > >I, like everyone else in the universe, am writing a prog to manipulate and >organize mp3's... > >The idea was to base it on Jason Orendorff 'path' module >(http://www.jorendorff.com/articles/python/path/) and add some methods to >the path object that are mp3 specific. > >So I subclass the 'path' object as 'mp3path' and add some of my own methods. > >Several of the methods in the original 'path' return more path objects so >the methods I inherit from path also return path objects. I want my new >methods to act on the returned objects. > >An example: > >myPath.files() returns a list of path objects > >I have added a new method ID3tag to my MP3path class >I want myMP3path.files to return a list of objects that can still access my >ID3tag method. > >Options that have occurred to me: > >1. Override every method in 'path' that returns paths with a wrapper method >that converts them into mp3paths. This seems ugly, boring and pointless. >2. Forget subclassing and add methods directly into the path module source. >This will be bad when a new version of 'path' comes along and also seems >like cheating. >3. Add methods dynamically into the path object. (Is this 'decorator'?) I >looked at the instancemethod function in the standard library 'new' module >and this adds methiods to instances but not to classes so I would have to do >this for every instance. >4. Forget the whole OO thang and just use functions. (Looking more >attractive by the minute ;-) > >Am I being thick here? What's the proper way to do this? I can see a similar >situation happeneing if I ever subclass 'string' or suchlike. > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From prefetch at gmail.com Thu Aug 5 16:58:27 2004 From: prefetch at gmail.com (prefetch) Date: Thu Aug 5 16:58:30 2004 Subject: [Tutor] simple c-api question Message-ID: <17226728040805075851dd08bb@mail.gmail.com> hi all, i'm wonder what the "accepted python way" to do the following is: i've got a c module like this: char ** SortEachBlock(char ** BlockList, int BlockSize, int ListSize) { for(i = 0; i < ListSize;i++) { myqsort(BlockList[i], BlockSize) } return BlockList; } make sense? it's sorting each array in an array, then returning it. how would i "pythonize" this? would i use something like this? static PyObject * SortEachBlock(PyObject * self, PyObject *args) and then how would i return my char** ? return Py_BuildValue("s", &BlockList); and how would i pass my BlockList to this in python? does anyone know..? From andy at andybak.net Thu Aug 5 17:12:00 2004 From: andy at andybak.net (Andy Baker) Date: Thu Aug 5 17:12:03 2004 Subject: [tutor] Dumb subclassing question In-Reply-To: <20040805145833.196651E4013@bag.python.org> Message-ID: <20040805151201.F0B451E4009@bag.python.org> > From: Kent Johnson > Andy, > > There is a way to do this by replacing path.__new__(). The > __new__ method of a class is a factory that returns the > actual instance object that will eventually be returned by > the call to the class itself. By replacing __new__ you can > return a class of a different type. > > I'm not sure this is a good design. A path to a directory > should not have > mp3 accessors, and an object representing an MP3 file doesn't need a > files() method. I think Rich Krauter's approach of making an > MP3 class that wraps a path to a file is probably a better design. Like I said earlier, I can see the sense in this but like you this has become more of an abstract problem solving issue to me now! Your idea below is some spooky voodoo! It would be way beyond my ability to do so but your black magic could surely be wrapped in a general metaclass type thing and given a nice syntax? On second thoughts I am sooooo running before I can walk ;-) > But you raise an interesting challenge which I couldn't > resist. Here is a short program that munges path() so it > actually returns an instance of a subclass of path: > > from path import path > > # Here is the new subclass > class MyPath(path): > def coolStuff(self): > print 'It works!' > > # Remember the old __new__ so we can delegate to it > originalNew = path.__new__ > > # This is going to be the new path.__new__. It will return an > instance of MyPath def newNew(cls, *args, **kwds): > return originalNew(MyPath, *args, **kwds) > > # Replace path.__new__ with our new version path.__new__ = > staticmethod(newNew) > > # Try it out > p = path("C:") > print type(p) > p.coolStuff() > > f = p.files() > print f[0] > print type(f[0]) > > Running this program prints > > It works! > C:.DS_Store > > > You could change newNew so it looks at the arguments it is > passed and only creates a MyPath if the path has a particular > form, e.g. ends with '.mp3'. > To do this you would call originalNew(path, *args, **kwds) > when you want a plain path. You can read more about > overriding __new__ here: > http://www.python.org/2.2.1/descrintro.html#__new__ > > I hope I haven't gone beyond what is appropriate for this > list - this is definitely advanced stuff. But it is a good > chance for me to learn too! > > Kent > From kent_johnson at skillsoft.com Thu Aug 5 17:58:58 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Thu Aug 5 17:59:22 2004 Subject: [tutor] Dumb subclassing question In-Reply-To: <20040805151201.F0B451E4009@bag.python.org> References: <20040805145833.196651E4013@bag.python.org> <20040805151201.F0B451E4009@bag.python.org> Message-ID: <6.1.0.6.0.20040805114855.029ccc88@mail4.skillsoft.com> At 04:12 PM 8/5/2004 +0100, Andy Baker wrote: >Your idea below is some spooky voodoo! It would be way beyond my ability to >do so but your black magic could surely be wrapped in a general metaclass >type thing and given a nice syntax? On second thoughts I am sooooo running >before I can walk ;-) I'm over my head too. I'm amazed that this is possible :-) Since my solution modifies the (only) path class object, it can go in the module that defines the subclass, and then be applied behind the scenes for all users. ####################################### # MyPath.py from path import path class MyPath(path): def coolStuff(self): print 'It works!' # Remember the old __new__ so we can delegate to it originalNew = path.__new__ # This is going to be the new path.__new__. It will return an instance of MyPath def newNew(cls, *args, **kwds): return originalNew(MyPath, *args, **kwds) # Replace path.__new__ with our new version path.__new__ = staticmethod(newNew) ################################# # MyPathClient.py from MyPath import MyPath # Try it out p = MyPath("C:") print type(p) p.coolStuff() f = p.files()[0] print f print type(f) f.coolStuff() prints: It works! C:.DS_Store It works! From orbitz at ezabel.com Thu Aug 5 19:19:16 2004 From: orbitz at ezabel.com (orbitz) Date: Thu Aug 5 19:19:38 2004 Subject: [Tutor] CSV Module Message-ID: <41126C14.9010102@ezabel.com> I'm trying to use the csv module to read in a file nicley. My dialect looks like: class TabSep(csv.Dialect): delimiter = '\t' quotechar = '"' escapechar = None doublequote = True skipinitialspace = True lineterminator = '\r\n' quoting = csv.QUOTE_MINIMAL My problem is, while reading the file, one of the parts of it has a ^M on it so I get: _csv.Error: newline inside string Why is csv even complaining about this? I don't care what's in there, I tell it what to use as line terminator. Is there any way around this? From flaxeater at yahoo.com Thu Aug 5 22:21:58 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Thu Aug 5 22:22:04 2004 Subject: [Tutor] Dumb Subclassing question Message-ID: <20040805202158.76050.qmail@web52609.mail.yahoo.com> I must say this is one of the most neeto hacks I've seen in a while. And it's very understandable with your comments. *applaud* > from path import path > > # Here is the new subclass > class MyPath(path): > def coolStuff(self): > print 'It works!' > > # Remember the old __new__ so we can delegate to it > originalNew = path.__new__ > > # This is going to be the new path.__new__. It will return an instance > of MyPath > def newNew(cls, *args, **kwds): > return originalNew(MyPath, *args, **kwds) > > # Replace path.__new__ with our new version > path.__new__ = staticmethod(newNew) > > # Try it out > p = path("C:") > print type(p) > p.coolStuff() > > f = p.files() > print f[0] > print type(f[0]) > > Running this program prints > > It works! > C:.DS_Store > > __________________________________ Do you Yahoo!? Yahoo! Mail - 50x more storage than other providers! http://promotions.yahoo.com/new_mail From T.Chern at unibas.ch Thu Aug 5 22:38:54 2004 From: T.Chern at unibas.ch (Tzu-Ming Chern) Date: Thu Aug 5 22:38:56 2004 Subject: [Tutor] passing variables to the system command Message-ID: Hi Python tutors, I'm having problems finding a way to pass variables when using the systems command in python. For example, in a simple python script, I would like to run another python script using the systems command. This python script takes the variables (argument1 and 2) as commandline arguments, which are filenames infact. The python scripts and all the filenames are in the same directory. See the following for example: import os argument1 = filename1 argument2 = filename2 os.system("some_other_python_script.py argument1 argument2") or os.system("chmod u+x argument1") --------------------------------------- When I try to run this, I get the error that the variables passed (which are filenames) cannot be opened. What is the correct syntax to run another script that takes in commandline arguments in a python script using the unix systems command? cheers, Tzu-Ming From alan.gauld at blueyonder.co.uk Thu Aug 5 22:56:21 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Aug 5 22:55:50 2004 Subject: [Tutor] Dumb Subclassing question References: Message-ID: <005301c47b2e$a9b96c70$6401a8c0@xp> > 'MP3 Tag Studio' and Musicbrainz which between them are a fair bit more > powerful than Itunes but I need more power! Yes, but with iTunes fully scriptable I can pretty much make it do anything I need - which is very possibly less than you need! :-) > I mean that any path object returned should have mp3 related methods. OK That's what I had assumed,. I just wanted to be sure. > > No its not decorator and is even more messy! > > (unrelated question: How does adding methods to existing instances differ > from decorator then? The decorator is a class that sits in front of another class, thus decorating it. A big assumption in OO patterns is that the existing objects can't be changed - because in most languages they can't! You don't have access to the source in most cases and you can't dynamically add metjods as you can in Python. A decorator uses composition as suggested by someone else. You forward the messages on to the pdeudo parent. The example given in the Patterns book is that of a scrollable window in a GUI. The Window class has no scrolling capability but by wrapping it in a decorator class with scrolling the scroll message is received by the decorator which adjusts the view settings of the component window then when the refresh (ie draw) method is invoked the decorator simply delegates it to the Window. So from the outside we have a class with scroll and draw methods but in fact its two classes. Now we could do that with subclassing so why use decorator? Well what if we have other things we want to scroll too? We can use our decorator object with any window like object without having to subclass every widget that might need scrollers. > I get the feeling that a lot of common design patterns > don't apply exactly the same way to Python They apply the same but Python often has other ways of doing it, sometimes, but only occasionally, more neatly. > Well! You say Yuk but I did a bit more digging and (thanks to Mark > Pilgrim:http://diveintomark.org/archives/2003/01/27/dynamically_extend ing_ap > is ) found that despite what is implied in the standard library docs, > 'instancemethod' will happily add methods to classes. This new methods then > get nicely inherited by instances of the class. But you have still changed the behaviour of an existing class, what happens when another bit of code creates a path object and expects the old behaviour? It will get very confused and may do bad things. And it will be devilishly hard to both tet and debug. Changing behaviour at run time should be considered an extremely advanced topic with huge risks involved. BUT of course if your project is small and you know exactly what all of the imported objects do then it might be OK. There are no hard and fast rules. > This seems cleaner to me than the alternative of overriding all the methods > just to add a type wrapper. I'd be interested to know what trouble I might > be storing up in terms of bad OO practice... If you can be sure that nothing in your total code base relies on the original behaviour, or that you do not significantly (define significant?!) change that behaviour you can get away with it, but its exactly the kind of change that OOP tries to save you from! > > So you can write a function that determines the nature of > > path node you get and only convert the leaf nodes to your > > class type. That is instead of overriding path to retirn your > > objects why not get the list of paths back and then convert > > those as needed to your class? > > > Well, the class I am basing myself on doesn't differentiate between path's > and filenames and I find that approach fairly nice (only one object type to > deal with. Just use .isfile() or isdir() if you need to know). So it does distinguish between them, it calls the test functions to determine the difference! So why not use those same functions to determine when to convert the leaf nodes to your new classes? Then when you process the list and use the ID3tags method (which presumably will only be with files) it will be there. > > for aPath in myPath.files(): > > if aPath is leaf node # using isinstance or somesuch? if aPath.isfile(): # using your method above > > aPath = mp3path(path) > > aPath.ID3tag() # do things with new path object That way you write a single conversion function and convert the files you need to convert. No impact on path at all... You could override the path constructor as suggested elsewhere but that still potentially breaks existing code by returning a different kind of object from the one the code expects. On a final note, it should be realised that OOP does not automatically imply writing less code. In fact for short programs it very often means more code, but hopefully the result is both more maintainable and more robust and flexible. Alan G. From jeff at ccvcorp.com Fri Aug 6 00:16:48 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri Aug 6 00:16:25 2004 Subject: [Tutor] passing variables to the system command In-Reply-To: References: Message-ID: <4112B1D0.6080702@ccvcorp.com> Tzu-Ming Chern wrote: > Hi Python tutors, > > I'm having problems finding a way to pass variables when using the systems > command in python. For example, in a simple python script, I would like to > run another python script using the systems command. This python script > takes the variables (argument1 and 2) as commandline arguments, which are > filenames infact. The python scripts and all the filenames are in the same > directory. See the following for example: > > import os > > argument1 = filename1 > argument2 = filename2 > > os.system("some_other_python_script.py argument1 argument2") What you need to do is construct a string using the values of those variables. The best way to do this is usually string formatting with the % operator. cmdstring = "some_other_script.py %s %s" % (argument1 argument2) os.system(cmdstring) You can do this all on one line, too, but I separated it specifically to show that this is a feature of strings rather than something related to os.system() or the os module. See http://docs.python.org/lib/typesseq-strings.html for a more detailed look at how to use string formatting. Jeff Shannon Technician/Programmer Credit International From kent_johnson at skillsoft.com Fri Aug 6 03:13:37 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Aug 6 03:14:16 2004 Subject: [Tutor] CSV Module In-Reply-To: <41126C14.9010102@ezabel.com> References: <41126C14.9010102@ezabel.com> Message-ID: <6.1.0.6.0.20040805155050.02a4e698@mail4.skillsoft.com> This seems to be a limitation of the csv module. Or two limitations, maybe. First, it ignores the lineterminator parameter on reads - it is using the standard file iterator to break the input into lines. Second, I don't think it allows a newline inside a value. This bug report has a little more detail about the first limitation: https://sourceforge.net/tracker/?func=detail&atid=105470&aid=789519&group_id=5470 Kent At 01:19 PM 8/5/2004 -0400, orbitz wrote: >I'm trying to use the csv module to read in a file nicley. My dialect >looks like: > >class TabSep(csv.Dialect): > delimiter = '\t' > quotechar = '"' > escapechar = None > doublequote = True > skipinitialspace = True > lineterminator = '\r\n' > quoting = csv.QUOTE_MINIMAL > >My problem is, while reading the file, one of the parts of it has a ^M on >it so I get: > >_csv.Error: newline inside string > >Why is csv even complaining about this? I don't care what's in there, I >tell it what to use as line terminator. Is there any way around this? >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From amonroe at columbus.rr.com Fri Aug 6 03:18:12 2004 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Fri Aug 6 03:18:25 2004 Subject: [Tutor] Is there a Python interface to ZeroC's Ice yet? Message-ID: <1121128603265.20040805211812@columbus.rr.com> Google mostly came up with generic corba-oriented sites. Is anyone working on a Python specific module for it? Alan From kent_johnson at skillsoft.com Fri Aug 6 03:31:55 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Aug 6 03:32:02 2004 Subject: [Tutor] Simple code (was: Dumb Subclassing question) In-Reply-To: <005301c47b2e$a9b96c70$6401a8c0@xp> References: <005301c47b2e$a9b96c70$6401a8c0@xp> Message-ID: <6.1.0.6.0.20040805211722.028a4218@mail4.skillsoft.com> >On a final note, it should be realised that OOP does not >automatically imply writing less code. In fact for short programs >it very often means more code, but hopefully the result is both >more maintainable and more robust and flexible. I think good programming practice often does imply writing less code, for two reasons. One is the DRY principle - Don't Repeat Yourself. In other words don't copy/paste identical sections of code. Don't duplicate data. Look for the common bits and factor them out into shared functions or classes or configuration files. Second is YAGNI - You Aren't Gonna Need It -- which is closely related to "Do the simplest thing that could possibly work." These two principles of Extreme Programming are generally useful. The idea is, don't write code that you don't need today. Don't complicate today's design to accommodate tomorrow's anticipated needs, because when tomorrow comes there will often be something else that is more important. One of the great things about Python is that you can write short programs without cluttering them up with needless OO complexity. A really simple program might start out as straight-line code without even any functions. As it gets more complicated you break it up into functions to keep it readable or to reuse bits of code. When you have several functions that are sharing common state variables, or when you need to duplicate some state variables, you introduce a class or two and maybe break the program up into multiple modules. I'm all in favor of maintainable and robust code. I generally try to omit the flexibility until I actually need it. Simple is good. Kent From alan.gauld at blueyonder.co.uk Fri Aug 6 08:21:54 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Aug 6 08:21:16 2004 Subject: [Tutor] passing variables to the system command References: Message-ID: <006e01c47b7d$ab5417c0$6401a8c0@xp> > I'm having problems finding a way to pass variables when using the systems > command in python. > argument1 = filename1 > argument2 = filename2 > > os.system("some_other_python_script.py argument1 argument2") Try: os.system("some_other_python_script.py %s %s" % (argument1, argument2)) In other words insert the values using the string format operator. Also you might be safer calling python explicitly: command ="python some_python_script.py %s %s" % (argument1, argument2) os.system(command) > os.system("chmod u+x argument1") The problem with this approach is that the external environment that system() creates has no idea what argument1 means - it only exists inside your program. You have to translate argument1 back into a literal value before calling system() 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 Fri Aug 6 08:34:07 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Aug 6 08:33:29 2004 Subject: [Tutor] Simple code (was: Dumb Subclassing question) References: <005301c47b2e$a9b96c70$6401a8c0@xp> <6.1.0.6.0.20040805211722.028a4218@mail4.skillsoft.com> Message-ID: <007b01c47b7f$60634cc0$6401a8c0@xp> > >On a final note, it should be realised that OOP does not > >automatically imply writing less code. In fact for short programs > > I think good programming practice often does imply writing less code, for > two reasons. One is the DRY principle - Don't Repeat Yourself. In other > words don't copy/paste identical sections of code. Don't duplicate data. Yes but the reason OOP results in more code for short programs is that there is a minimum amount of scaffolding involved in creating classes etc in the first place! > Second is YAGNI - You Aren't Gonna Need It -- which is closely related to > "Do the simplest thing that could possibly work." But simplest is not necessarily shoirtest. Short code is often very complex. This thread is a good example. While the overridden constructor technique is neat and results in less code, it will be far more difficult to refactor if it turns out later to be unsuitable. The simple solution is just to override the methods or create a new convertion function - more work but simpler code. > These two principles of Extreme Programming are generally useful. They are sometimes useful. :-) XP has many limitations as well as advantages. > One of the great things about Python is that you can write short programs > without cluttering them up with needless OO complexity. Absolutely, use OOP where it is appropriate but if writing a hello world print "hello World" is better than an OOP solution! > I'm all in favor of maintainable and robust code. I generally try to omit > the flexibility until I actually need it. Simple is good. Sure, and one of the aims of OOP is to provide flexibility for free. You can extend a class without changing the original and therefore without incurring a roisk of breaking existing code. Of course for this to work properly the classes need to be designed well to sart with - no side effects etc. Alan G. From rdm at rcblue.com Fri Aug 6 10:43:04 2004 From: rdm at rcblue.com (Dick Moores) Date: Fri Aug 6 10:44:23 2004 Subject: [Tutor] The Boolean operator "and" Message-ID: <6.1.2.0.2.20040806011948.059d2ec0@rcblue.com> I have a question about one sentence in the fine Python book I'm presently studying, Practical Python, by Magnus Lie Hetland (Apress). The sentence is "Actually, if x is false, it returns x--otherwise it returns y." This sentence is in the paragraph on p. 109 that begins, 'The Boolean operators have one interesting property: They only evaluate what they need to. For instance, the expression x and y requires both x and y to be true; so if x is false, the expression returns false immediately, without worrying about y. Actually, if x is false, it returns x--otherwise it returns y. (Can you see how this give the expected meaning?) This behavior is called short-circuit logic: the Boolean operators are often called logical operators, and as you can see, the second value is sometimes "short-circuited." This works with or, too. In the expression x or y, if x is true, it is returned, otherwise y is returned. (Can you see how this makes sense?)' In the sentence I'm questioning, "Actually, if x is false, it returns x--otherwise it returns y", it seems to me that if x evaluates to False, False is returned, not x itself, (which might be "3 > 4"). Am I confused? Or quibbling? Thanks, Dick Moores From gew75 at hotmail.com Fri Aug 6 11:10:58 2004 From: gew75 at hotmail.com (Glen Wheeler) Date: Fri Aug 6 11:11:05 2004 Subject: [Tutor] The Boolean operator "and" References: <6.1.2.0.2.20040806011948.059d2ec0@rcblue.com> Message-ID: > I have a question about one sentence in the fine Python book I'm > presently studying, Practical Python, by Magnus Lie Hetland (Apress). The > sentence is "Actually, if x is false, it returns x--otherwise it returns > y." This sentence is in the paragraph on p. 109 that begins, > > 'The Boolean operators have one interesting property: They only evaluate > what they need to. For instance, the expression x and y requires both x > and y to be true; so if x is false, the expression returns false > immediately, without worrying about y. Actually, if x is false, it > returns x--otherwise it returns y. (Can you see how this give the > expected meaning?) This behavior is called short-circuit logic: the > Boolean operators are often called logical operators, and as you can see, > the second value is sometimes "short-circuited." This works with or, too. > In the expression x or y, if x is true, it is returned, otherwise y is > returned. (Can you see how this makes sense?)' > > In the sentence I'm questioning, "Actually, if x is false, it returns > x--otherwise it returns y", it seems to me that if x evaluates to False, > False is returned, not x itself, (which might be "3 > 4"). > > Am I confused? Or quibbling? > I'd say a little bit of both ;). Mr Hetland is (of course) correct in his statement you quote above. The key part is where he states ``if x is false''. This is not ``x evaluates to False''. A quick interpreter session to hopefully clarify what he is trying to say: >>> x = 3 < 4 >>> x True >>> x is True True # Note how x actually *is* True >>> x is False False >>> The point is that any logical expression is not stored as a string, but as either True or False. This is neat, since it implies that the expected value of any logical expression will be True or False. Thus, we have if statements. Any logical statement or expression is evaluated before assignment to the variable holding that statement actually occurs. >>> x = 1 > 0 >>> y = 1 < 0 >>> x and y False >>> x or y True >>> x is False False >>> x is True True I hope this helps clear things up. Glen From rdm at rcblue.com Fri Aug 6 11:48:40 2004 From: rdm at rcblue.com (Dick Moores) Date: Fri Aug 6 11:48:43 2004 Subject: [Tutor] The Boolean operator "and" In-Reply-To: References: <6.1.2.0.2.20040806011948.059d2ec0@rcblue.com> Message-ID: <6.1.2.0.2.20040806024612.0572a248@rcblue.com> Glen Wheeler wrote at 02:10 8/6/2004: >Any logical statement or expression is evaluated before assignment to the >variable holding that statement actually occurs. That sentence is what clears it up for me. Thanks _very_ much. Dick Moores From dshemwell at charter.net Fri Aug 6 13:42:01 2004 From: dshemwell at charter.net (Daniel) Date: Fri Aug 6 13:41:58 2004 Subject: [Tutor] question Message-ID: <391q2v$54usmb@mxip18a.cluster1.charter.net> I need help with programming I'm new at it so my questions are going to be basic well anyway how would I get a string to display on start up of a module/program? What command? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040806/9268f89f/attachment.html From andy at andybak.net Fri Aug 6 13:44:30 2004 From: andy at andybak.net (Andy Baker) Date: Fri Aug 6 13:44:32 2004 Subject: [Tutor] Simple code (was: Dumb Subclassing question) In-Reply-To: <007b01c47b7f$60634cc0$6401a8c0@xp> Message-ID: <20040806114431.0219C1E4009@bag.python.org> My original design that led me down this path was poorly thought out but here is a simpler use case: 1. I have some need for a string method that isn't currently in Python 2. I subclass string to newstring and add my method '.bowdlerize' 3. I now have the problem that all existing python functions and methods return string instances rather than newstring so I have to wrap or convert every return value before I can use my new method: Now with a simple function instead of a method there is no problem as I can pass it strings: bowlderize(anystring) But if I want my function to be a method of strings I have to subclass strings: string.bowdlerize() #ERROR newstring.bowdlerize() #OK If I use the 'new.instancemethod' (or the overriding of __NEW__) trick then I can add my .bowdlerize() method to strings and not have to do any casting. I haven't changed the behaviour of strings. Simply adding a new method to an existing class cannot break old code (they simply will never call my method). The only issue I see OO-wise is that of maintainability. The methods of strings are now split over two different files and someone familiar with the existing string methods will have to look to see what bowdlerize is supposed to do. Is that a serious enough drawback to generally rule out adding methods into existing classes? (although simply using a function: bowlderize(anystring) seems even cleaner...) From pythonTutor at venix.com Fri Aug 6 14:47:31 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Fri Aug 6 14:48:40 2004 Subject: [Tutor] The Boolean operator "and" In-Reply-To: References: <6.1.2.0.2.20040806011948.059d2ec0@rcblue.com> Message-ID: <1091796450.4556.23.camel@laptop.venix.com> x and y can simply be values. 0, 0.0, None, [], '' all evaluate to False. >>> x = None >>> y = 0.0 >>> result = x and y >>> result >>> print result None >>> print x or y 0.0 Note that the values do NOT get changed to booleans. On Fri, 2004-08-06 at 05:10, Glen Wheeler wrote: (snipped) > Mr Hetland is (of course) correct in his statement you quote above. The > key part is where he states ``if x is false''. This is not ``x evaluates to > False''. > > A quick interpreter session to hopefully clarify what he is trying to say: > > >>> x = 3 < 4 > >>> x > True > >>> x is True > True > # Note how x actually *is* True > >>> x is False > False > >>> > > The point is that any logical expression is not stored as a string, but as > either True or False. This is neat, since it implies that the expected > value of any logical expression will be True or False. Thus, we have if > statements. > Any logical statement or expression is evaluated before assignment to the > variable holding that statement actually occurs. > > >>> x = 1 > 0 > >>> y = 1 < 0 > >>> x and y > False > >>> x or y > True > >>> x is False > False > >>> x is True > True > > I hope this helps clear things up. > > Glen > _______________________________________________ > 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 klas.martelleur at telia.com Fri Aug 6 15:02:49 2004 From: klas.martelleur at telia.com (Klas Marteleur) Date: Fri Aug 6 14:54:09 2004 Subject: [Tutor] question In-Reply-To: <391q2v$54usmb@mxip18a.cluster1.charter.net> References: <391q2v$54usmb@mxip18a.cluster1.charter.net> Message-ID: <200408061502.49442.klas.martelleur@telia.com> Try Alan Gaulds excellent tutorial on http://www.freenetpages.co.uk/hp/alan.gauld/ Klas fredagen den 6 augusti 2004 13.42 skrev Daniel: > I need help with programming I'm new at it so my questions are going to be > basic well anyway how would I get a string to display on start up of a > module/program? What command? From pythonTutor at venix.com Fri Aug 6 15:03:06 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Fri Aug 6 15:03:11 2004 Subject: [Tutor] The Boolean operator "and" In-Reply-To: <1091796450.4556.23.camel@laptop.venix.com> References: <6.1.2.0.2.20040806011948.059d2ec0@rcblue.com> <1091796450.4556.23.camel@laptop.venix.com> Message-ID: <1091797384.4556.31.camel@laptop.venix.com> I think this is better phrasing below. Those values are equivalent to False when used in a context where a boolean would be appropriate. http://docs.python.org/lib/truth.html#l2h-90 Lists the values that evaluate as False. On Fri, 2004-08-06 at 08:47, Lloyd Kvam wrote: > x and y can simply be values. 0, 0.0, None, [], '' all evaluate to ^^as > False. > >>> x = None > >>> y = 0.0 > >>> result = x and y > >>> result > >>> print result > None > >>> print x or y > 0.0 > > Note that the values do NOT get changed to booleans. > > > On Fri, 2004-08-06 at 05:10, Glen Wheeler wrote: > (snipped) > > > Mr Hetland is (of course) correct in his statement you quote above. The > > key part is where he states ``if x is false''. This is not ``x evaluates to > > False''. > > > > A quick interpreter session to hopefully clarify what he is trying to say: > > > > >>> x = 3 < 4 > > >>> x > > True > > >>> x is True > > True > > # Note how x actually *is* True > > >>> x is False > > False > > >>> > > > > The point is that any logical expression is not stored as a string, but as > > either True or False. This is neat, since it implies that the expected > > value of any logical expression will be True or False. Thus, we have if > > statements. > > Any logical statement or expression is evaluated before assignment to the > > variable holding that statement actually occurs. > > > > >>> x = 1 > 0 > > >>> y = 1 < 0 > > >>> x and y > > False > > >>> x or y > > True > > >>> x is False > > False > > >>> x is True > > True > > > > I hope this helps clear things up. > > > > Glen > > _______________________________________________ > > 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 gew75 at hotmail.com Fri Aug 6 15:12:17 2004 From: gew75 at hotmail.com (Glen Wheeler) Date: Fri Aug 6 15:12:37 2004 Subject: [Tutor] The Boolean operator "and" References: <6.1.2.0.2.20040806011948.059d2ec0@rcblue.com><1091796450.4556.23.camel@laptop.venix.com> <1091797384.4556.31.camel@laptop.venix.com> Message-ID: Yes...however I was not talking about actual values. I was talking about logical expressions. The chapter in question was on boolean algebra, right? Sorry if I unintentionally confused anyone. Lloyd is also correct. Glen From: "Lloyd Kvam" > I think this is better phrasing below. Those values are equivalent to > False when used in a context where a boolean would be appropriate. > > http://docs.python.org/lib/truth.html#l2h-90 > Lists the values that evaluate as False. > > On Fri, 2004-08-06 at 08:47, Lloyd Kvam wrote: > > x and y can simply be values. 0, 0.0, None, [], '' all evaluate to > ^^as > > False. > > >>> x = None > > >>> y = 0.0 > > >>> result = x and y > > >>> result > > >>> print result > > None > > >>> print x or y > > 0.0 > > > > Note that the values do NOT get changed to booleans. > > > > > > On Fri, 2004-08-06 at 05:10, Glen Wheeler wrote: > > (snipped) > > > > > Mr Hetland is (of course) correct in his statement you quote above. The > > > key part is where he states ``if x is false''. This is not ``x evaluates to > > > False''. > > > > > > A quick interpreter session to hopefully clarify what he is trying to say: > > > > > > >>> x = 3 < 4 > > > >>> x > > > True > > > >>> x is True > > > True > > > # Note how x actually *is* True > > > >>> x is False > > > False > > > >>> > > > > > > The point is that any logical expression is not stored as a string, but as > > > either True or False. This is neat, since it implies that the expected > > > value of any logical expression will be True or False. Thus, we have if > > > statements. > > > Any logical statement or expression is evaluated before assignment to the > > > variable holding that statement actually occurs. > > > > > > >>> x = 1 > 0 > > > >>> y = 1 < 0 > > > >>> x and y > > > False > > > >>> x or y > > > True > > > >>> x is False > > > False > > > >>> x is True > > > True > > > > > > I hope this helps clear things up. > > > > > > Glen > > > _______________________________________________ > > > 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 python at kapitalisten.no Fri Aug 6 16:39:59 2004 From: python at kapitalisten.no (=?iso-8859-1?Q?=D8yvind?=) Date: Fri Aug 6 16:40:17 2004 Subject: [Tutor] Tk variable problem Message-ID: <1561.193.216.177.231.1091803199.squirrel@mail.sporck.net> I have made a box that shows what directory is currently default. If one wants to change the directory, one can press a button and change it. However, the new directory is not changing the text where the default one is told, but rather printing the new info in addition to the old. How can I update the directoryinfo instead of adding the new to the old and wrong info? Thanks in advance... def preferanser(): def die(event): root.destroy() def bildekatalog(): bildedir = tkFileDialog.askdirectory(initialdir='c:/bilder/') print bildedir blabel = Label(root) xx = StringVar(root) xx.set("Bildekatalog:\n" + bildedir) blabel["text"] = xx.get() blabel.pack() root.mainloop() root = Tk() blabel = Label(root) xx = StringVar(root) xx.set("Bildekatalog:\n" + bildedir) blabel["height"] = 10 blabel["width"] = 30 blabel["text"] = xx.get() b = Button(root, text="Endre", width=10, command=bildekatalog) blabel.pack(side=LEFT) b.pack(side=RIGHT, padx=40, pady=15) root.mainloop() -- This email has been scanned for viruses & spam by Decna as - www.decna.no Denne E-post er sjekket for virus & spam av Decna as - www.decna.no From prefetch at gmail.com Fri Aug 6 17:57:16 2004 From: prefetch at gmail.com (prefetch) Date: Fri Aug 6 17:57:21 2004 Subject: [Tutor] c-api question Message-ID: <17226728040806085765af9d45@mail.gmail.com> hi all, i'm wonder what the "accepted python way" to do the following is: i've got a c module like this: char ** SortEachBlock(char ** BlockList, int BlockSize, int ListSize) { for(i = 0; i < ListSize;i++) { myqsort(BlockList[i], BlockSize) } return BlockList; } make sense? it's sorting each array in an array, then returning it. how would i "pythonize" this? would i use something like this? static PyObject * SortEachBlock(PyObject * self, PyObject *args) and then how would i return my char** ? return Py_BuildValue("s", &BlockList); and how would i pass my BlockList to this in python? does anyone know..? From jeff at ccvcorp.com Fri Aug 6 20:39:59 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri Aug 6 20:39:34 2004 Subject: [Tutor] The Boolean operator "and" In-Reply-To: <6.1.2.0.2.20040806011948.059d2ec0@rcblue.com> References: <6.1.2.0.2.20040806011948.059d2ec0@rcblue.com> Message-ID: <4113D07F.2060805@ccvcorp.com> Dick Moores wrote: > I have a question about one sentence in the fine Python book I'm > presently studying, Practical Python, by Magnus Lie Hetland (Apress). > The sentence is "Actually, if x is false, it returns x--otherwise it > returns y." This sentence is in the paragraph on p. 109 that begins, The key here is that there's a difference between being false, and being False. [], {}, 0.0, and 0 are all 'false' as well, and if x is one of those things, you'll get that rather than the boolean object False. >>> x = [] >>> y = [1] >>> >>> x and y [] >>> x or y [1] >>> If you're using this in a boolean context (i.e. an if statement), then the effect is the same as if it were False, but in other contexts the distinction can be important. Jeff Shannon Technician/Programmer Credit International From alan.gauld at blueyonder.co.uk Fri Aug 6 20:52:01 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Aug 6 20:51:17 2004 Subject: [Tutor] Simple code (was: Dumb Subclassing question) References: Message-ID: <008001c47be6$75edf4c0$6401a8c0@xp> > 1. I have some need for a string method that isn't currently in Python > 2. I subclass string to newstring and add my method '.bowdlerize' > 3. I now have the problem that all existing python functions and methods > return string instances rather than newstring so I have to wrap or convert > every return value before I can use my new method: How many such functions are there? Apart from the string specific functions like repr() and str() I can't think of many that return strings? > Now with a simple function instead of a method there is no problem as I can > pass it strings: > bowlderize(anystring) BUt this is true, which is why functions are sometimes better than classes! A lesson that Java has failed to learn... > But if I want my function to be a method of strings I have to subclass > strings: > string.bowdlerize() #ERROR > newstring.bowdlerize() #OK OR newstring(string).bowdlerize() Using a conversion function. This is after all the same approach when a builtin function returns a tuple but we need a list. Or it returns an int and we need a float - we convert it with a type conversion function. > If I use the 'new.instancemethod' (or the overriding of __NEW__) trick then > I can add my .bowdlerize() method to strings and not have to do any > casting. > > I haven't changed the behaviour of strings. Yes you have, you changed the size of the string class. Thus anyone reading/writing binary data that relies on the size of a string class will find their code is broken! > Simply adding a new method to an existing class cannot break old code Yes it can, see above. But I agree its relatively safe if you only add a new method and provided that method never changes the internal state of the object. Such read only methods are comparatively safe but they still change the size of the class - and extra reference. > Is that a serious enough drawback to generally rule out adding methods into > existing classes? (although simply using a function: bowlderize(anystring) > seems even cleaner...) Provided your methods are read only its not too bad. If your methods ever change the internals of the object they instantly become dangerous. However to pick up another point, in Python it's relatively unusual for well written code (including the standard library) to return any specific type of object - such as a string. Generally they return some variation of whatever was passed to them. Thus the same function can handle strings, lists, tuples etc and return a variant of the same object. So they could handle your new class just as well. These sorts of issues are far more significant in strictly typed languages like Java and C++. Alan G. From alan.gauld at blueyonder.co.uk Fri Aug 6 20:56:27 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Aug 6 20:55:40 2004 Subject: [Tutor] The Boolean operator "and" References: <6.1.2.0.2.20040806011948.059d2ec0@rcblue.com> Message-ID: <009201c47be7$1446c2a0$6401a8c0@xp> > In the sentence I'm questioning, "Actually, if x is false, it returns > x--otherwise it returns y", it seems to me that if x evaluates to False, > False is returned, not x itself, (which might be "3 > 4"). The sentence should probably say: "Actually if *the value of x* is equivalent to False it returns x" In Python a non zero value is equivalent to True and a zero (or empty or None) value is False. This concept of short-circuit evaluation of boolean expressions is explained in some detail on the functional programming page of my tutor. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at blueyonder.co.uk Fri Aug 6 21:20:26 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Aug 6 21:19:39 2004 Subject: [Tutor] question References: <391q2v$54usmb@mxip18a.cluster1.charter.net> Message-ID: <00b001c47bea$6dfb0e70$6401a8c0@xp> > I need help with programming I'm new at it so my questions are going to be > basic That's OK, it's what we are here for! :-) > well anyway how would I get a string to display on start up of a > module/program? What command? print "hello world" will print hello world on your console window. Put that in a file by itself and them import the file and the message will print. Thus create a file called mymessage.py containing the single print statement above. Save it in the sitepackages folder in your python installation(so that it can be found by python) OR create a new folder and add it to your PYTHONPATH envoironment variable (How to do that depends on your OS) Now open your python prompt(or IDLE) and when you get the chevrons, >>> type >>> import mymessage Note no .py... And hopefully the message hello world will appear. You will find lots more in the nonprogrammers tutorials on the Python web site, one of which is mine: Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/ From alan.gauld at blueyonder.co.uk Fri Aug 6 21:26:21 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Aug 6 21:25:33 2004 Subject: [Tutor] Tk variable problem References: <1561.193.216.177.231.1091803199.squirrel@mail.sporck.net> Message-ID: <00bf01c47beb$4156b8f0$6401a8c0@xp> > I have made a box that shows what directory is currently default. If one > wants to change the directory, one can press a button and change it. When you say a "box" I assume you mean a Label widget? It is important you tell us exactly what you are doing since the text insertion methods are slightly different betwen Labels, Text widgets and Entry widgets... > However, the new directory is not changing the text where the default one > is told, but rather printing the new info in addition to the old. It is very hard to read your code since the indentation has gone(at least for me it has!). Can you repost with plain text so that we can see the structure more clearly? You also seem to have two calls to mainloop(), that usually confuses Tkinter... It certainly confuses me! > I update the directoryinfo instead of adding the new to the old and wrong > info? > > Thanks in advance... > > def preferanser(): > def die(event): > root.destroy() > def bildekatalog(): > bildedir = tkFileDialog.askdirectory(initialdir='c:/bilder/') > print bildedir > blabel = Label(root) > xx = StringVar(root) > xx.set("Bildekatalog:\n" + bildedir) > blabel["text"] = xx.get() > blabel.pack() > root.mainloop() > > root = Tk() > blabel = Label(root) > xx = StringVar(root) > xx.set("Bildekatalog:\n" + bildedir) > blabel["height"] = 10 > blabel["width"] = 30 > blabel["text"] = xx.get() > > b = Button(root, text="Endre", width=10, command=bildekatalog) > > blabel.pack(side=LEFT) > b.pack(side=RIGHT, padx=40, pady=15) > > root.mainloop() Alan G From python at kapitalisten.no Fri Aug 6 21:51:35 2004 From: python at kapitalisten.no (=?iso-8859-1?Q?=D8yvind?=) Date: Fri Aug 6 21:51:42 2004 Subject: [Tutor] Tk variable problem In-Reply-To: <00bf01c47beb$4156b8f0$6401a8c0@xp> References: <1561.193.216.177.231.1091803199.squirrel@mail.sporck.net> <00bf01c47beb$4156b8f0$6401a8c0@xp> Message-ID: <1622.193.216.177.231.1091821895.squirrel@mail.sporck.net> >> I have made a box that shows what directory is currently default. If > one >> wants to change the directory, one can press a button and change it. > > When you say a "box" I assume you mean a Label widget? > It is important you tell us exactly what you are doing since the > text insertion methods are slightly different betwen Labels, > Text widgets and Entry widgets... I guess one of my problems are that I am not too certain what each part is called. I call it a box, since it is a square box that comes up on the screen. However, I assume you are right. What I realy mean is a widget with a label and a button. The label tells the user which directory that is active now. if that is wrong, the user can press the button and select a new. The problem is that the label is not updated with the new selection, but rather adds a new label with the new selection. The old is still there. >> However, the new directory is not changing the text where the > default one >> is told, but rather printing the new info in addition to the old. > > It is very hard to read your code since the indentation has > gone(at least for me it has!). Can you repost with plain text > so that we can see the structure more clearly? Sorry... I thought I did....I have updated it below. > You also seem to have two calls to mainloop(), that usually confuses > Tkinter... It certainly confuses me! It is on two different tab spacings. Does that still confuse Tkinter? >> I update the directoryinfo instead of adding the new to the old and > wrong >> info? >> >> Thanks in advance... >> >> def preferanser(): >> def die(event): >> root.destroy() >> def bildekatalog(): >> bildedir = tkFileDialog.askdirectory(initialdir='c:/bilder/') >> print bildedir >> blabel = Label(root) >> xx = StringVar(root) >> xx.set("Bildekatalog:\n" + bildedir) >> blabel["text"] = xx.get() >> blabel.pack() >> root.mainloop() >> >> root = Tk() >> blabel = Label(root) >> xx = StringVar(root) >> xx.set("Bildekatalog:\n" + bildedir) >> blabel["height"] = 10 >> blabel["width"] = 30 >> blabel["text"] = xx.get() >> >> b = Button(root, text="Endre", width=10, command=bildekatalog) >> >> blabel.pack(side=LEFT) >> b.pack(side=RIGHT, padx=40, pady=15) -- This email has been scanned for viruses & spam by Decna as - www.decna.no Denne E-post er sjekket for virus & spam av Decna as - www.decna.no From learning.python at dbmail.dk Fri Aug 6 23:20:39 2004 From: learning.python at dbmail.dk (Ole Jensen) Date: Fri Aug 6 23:20:38 2004 Subject: [Tutor] Adding custom modules to the module index? Message-ID: <000501c47bfb$3928f610$87c48f52@allmycore> How do you add custom modules so that you are able to import them directly from python? E.g. I want to import MyNewModule, and want to avoid the following: >>> Import MyNewModule Traceback (most recent call last): File "", line 1, in -toplevel- import MyNewModule ImportError: No module named MyNewModule I've read that its possible to add your own modules so they can be imported from IDLE like above, I just cannot remember how!? I've tried searching through google and python.org but I've lacked a key search word so I hope someone here can help me. ------- My question is derived from wanting to try out the Zope DataBase (ZODB) as it says in the documentation (http://zope.org/Documentation/Articles/ZODB1): [quote] After installing ZODB, you can start to experiment with it right from the Python command line interpreter. For example, try the following python code in your interpreter:: >>> from ZODB import FileStorage, DB >>> storage = FileStorage.FileStorage(mydatabase.fs) >>> db = DB(storage) >>> connection = db.open() >>> root = connection.root() [/quote] I have just installed Zope and I read the above as if I straight away should be able to play around with ZODB within IDLE, please correct me if I am way of base... TIA Ole Jensen From james.mccarney at cgi.com Fri Aug 6 23:23:07 2004 From: james.mccarney at cgi.com (James Alexander McCarney) Date: Fri Aug 6 23:23:14 2004 Subject: [Tutor] RE problems In-Reply-To: <20040806185123.347C01E4016@bag.python.org> Message-ID: <000b01c47bfb$917813f0$65a3a60a@GMC50444> Hi tutors, I am having problems returning everything I want from a regular expression. I am merely getting the first string in the html text file, which stands to reason as per the code. Could someone give me the magic to put all the strings tagged < > thus. Thanks for any tips you can provide. As for the document, I am reading amk's RE how-to; and I know it's all in there; it's just that I've cudgeled my brains a lot today. ;-( Best regards, James ## ## import pythoncom from win32com.client import Dispatch import re app = Dispatch('Word.Application') app.Visible = 1 doc = app.Documents.Add() f = open("C:\myfile.html") ## ## ## ## allines = f.read() p=re.compile(r"(<.*?>)",re.DOTALL) m=p.match(allines) ## s1 = doc.Sentences(1) s1.Text = m.group() doc.SaveAs("C:\myTestPy.doc') app.Quit() app = None pythoncom.CoUninitialize() f.close() From bennetb at gmail.com Fri Aug 6 23:38:52 2004 From: bennetb at gmail.com (Brandon Bennett) Date: Fri Aug 6 23:39:06 2004 Subject: [Tutor] RE problems In-Reply-To: <000b01c47bfb$917813f0$65a3a60a@GMC50444> References: <000b01c47bfb$917813f0$65a3a60a@GMC50444> Message-ID: I think this is a classic example of the greedy .* Use "(<[^>]*>)" This is match all characters between the < > that is not > (the ending tab. ~Brandon On Fri, 6 Aug 2004 17:23:07 -0400, James Alexander McCarney wrote: > Hi tutors, > > I am having problems returning everything I want from a regular expression. > I am merely getting the first string in the html text file, which stands to > reason as per the code. > > Could someone give me the magic to put all the strings tagged < > thus. > > Thanks for any tips you can provide. As for the document, > > I am reading amk's RE how-to; and I know it's all in there; it's just that > I've cudgeled my brains a lot today. ;-( > > Best regards, > James > > ## > ## > import pythoncom > from win32com.client import Dispatch > import re > > app = Dispatch('Word.Application') > app.Visible = 1 > > doc = app.Documents.Add() > > f = open("C:\myfile.html") > > ## > ## > ## > ## > > allines = f.read() > p=re.compile(r"(<.*?>)",re.DOTALL) > m=p.match(allines) > > ## > > s1 = doc.Sentences(1) > s1.Text = m.group() > > doc.SaveAs("C:\myTestPy.doc') > > app.Quit() > app = None > > pythoncom.CoUninitialize() > f.close() > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From dshemwell at charter.net Fri Aug 6 23:08:01 2004 From: dshemwell at charter.net (Daniel) Date: Fri Aug 6 23:41:30 2004 Subject: [Tutor] Else command Message-ID: <391s2r$59srkn@mxip15a.cluster1.charter.net> What command would I use and in what order to make it respond to everything but what I defined a certain variable as? For example I tell it that hi= "Hello" and then I want it so it says "what?" for everything else -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040806/5f53fb51/attachment.html From alan.gauld at blueyonder.co.uk Sat Aug 7 00:13:18 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Aug 7 00:12:29 2004 Subject: [Tutor] Tk variable problem References: <1561.193.216.177.231.1091803199.squirrel@mail.sporck.net> <00bf01c47beb$4156b8f0$6401a8c0@xp> <1622.193.216.177.231.1091821895.squirrel@mail.sporck.net> Message-ID: <00ca01c47c02$943979b0$6401a8c0@xp> OK Thats a bit esier to read. I've commented the code below: > > You also seem to have two calls to mainloop(), that usually confuses > > Tkinter... It certainly confuses me! > > It is on two different tab spacings. Does that still confuse Tkinter? It will when the second one gets called! > >> def preferanser(): > >> def die(event): > >> root.destroy() > >> def bildekatalog(): > >> bildedir = tkFileDialog.askdirectory(initialdir='c:/bilder/') > >> print bildedir > >> blabel = Label(root) > >> xx = StringVar(root) > >> xx.set("Bildekatalog:\n" + bildedir) > >> blabel["text"] = xx.get() > >> blabel.pack() > >> root.mainloop() I'm assuming the lines below here were not really intended to be part of the fuction definition above(preferanswer())? Even if they were I'd suggest you are better making all your function definitions top level ones. Otherwise the functions you define go out of scope when the top function completes and it all gets a bit confusing IMHO. So I've repasted them as separate functions: # this event handler never actually gets used because we dont set it anywhere!? def die(event): root.destroy() # this event handler gets called when the button gets pressed. def bildekatalog(): # first we get the new value bildedir = tkFileDialog.askdirectory(initialdir='c:/bilder/') print bildedir # and print it on the console window for debugging # now we repeat all the initialisation code thus creating # a duplicate set of controls! So comment them out: # xx = StringVar(root) # xx.set("Bildekatalog:\n" + bildedir) # blabel = Label(root) # blabel["text"] = xx.get() # blabel.pack() # # and just set the text property of the Label directly. blabel["text"] = bildedir root = Tk() # start the Tk ball rolling xx = StringVar(root) # create a string and initialise it. # but we can't use bildedir cause it doesn't exist here! xx.set("Bildekatalog:\n" + bildedir) blabel = Label(root) # crate a Label widget and set parameters blabel["height"] = 10 blabel["width"] = 30 blabel["text"] = xx.get() # easier to do the above with: blabel = Label(root, height=10, width=30, text=xx.get() ) blabel.pack(side=LEFT) # make it visible # now for the button which calls the function... b = Button(root, text="Endre", width=10, command=bildekatalog) b.pack(side=RIGHT, padx=40, pady=15) root.mainloop() # call it once at the outermost level. HTH, Alan G From alan.gauld at blueyonder.co.uk Sat Aug 7 00:49:19 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Aug 7 00:48:30 2004 Subject: [Tutor] Adding custom modules to the module index? References: <000501c47bfb$3928f610$87c48f52@allmycore> Message-ID: <00e401c47c07$9c22d400$6401a8c0@xp> > How do you add custom modules so that you are able to import them > directly from python? Basically you create a file and save it someplace thats in your PYTHONPATH environment variable or within the sys.path variable. > I've read that its possible to add your own modules so they can be > imported from IDLE like above, I just cannot remember how!? Its covered in my tutorial under functions and modules. Setting the PYTHONPATH environment variable is OS dependant but should be easy to find. If not get back to us and we can probably help if you tell us which OS you use. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/tutor2 From alan.gauld at blueyonder.co.uk Sat Aug 7 00:52:27 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Aug 7 00:51:38 2004 Subject: [Tutor] Else command References: <391s2r$59srkn@mxip15a.cluster1.charter.net> Message-ID: <00f001c47c08$0c562010$6401a8c0@xp> > What command would I use and in what order to make it respond to everything > but what I defined a certain variable as? For example I tell it that hi= > "Hello" and then I want it so it says "what?" for everything else if not hi == "hello": print 'what?' Is that what you mean? An alternative way is to use the not-equal operator: if hi != "hello": print "what?" HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From f2001847 at bits-pilani.ac.in Sat Aug 7 08:09:01 2004 From: f2001847 at bits-pilani.ac.in (f2001847@bits-pilani.ac.in) Date: Sat Aug 7 07:37:24 2004 Subject: [Tutor] Adding custom modules to the module index? In-Reply-To: <00e401c47c07$9c22d400$6401a8c0@xp> Message-ID: if ur using windows then just create a file with extension .pth and in that file each line should contain the directory in which ur modules are located.This way u can import all the modules in different directories. File with .pth extension should be created in ur python directory(directory where python was installed). -naresh > > How do you add custom modules so that you are able to import them > > directly from python? > > Basically you create a file and save it someplace thats in > your PYTHONPATH environment variable or within the sys.path > variable. > > > I've read that its possible to add your own modules so they can be > > imported from IDLE like above, I just cannot remember how!? > > Its covered in my tutorial under functions and modules. > Setting the PYTHONPATH environment variable is OS dependant > but should be easy to find. If not get back to us and we can > probably help if you tell us which OS you use. > > Alan G > Author of the Learn to Program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld/tutor2 > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From s4046441 at student.uq.edu.au Sat Aug 7 09:40:00 2004 From: s4046441 at student.uq.edu.au (Ms Soo Chong) Date: Sat Aug 7 09:40:08 2004 Subject: [Tutor] Help on Python to PostgreSQL and CGI Message-ID: <4115454117be.4117be411545@uq.edu.au> Hi, I am currently a fourth year Uni student who is working on a Thesis that required me to use python language to develop a webpage that user to query on. I have to use python language to fetch data from PostgreSQL and display it on a website where user to search from. I am so new to python and struggling so hard to learn and apply it. I wonder if anybody out there can help me a helping hand. I am currently reading through a book "Learning Python" and looking through some useful tutorials. I am actually searching for modules that can link postgreSQL and python together. Please give me some advice which at least help me to start up the program, cause I'm really lost. I wonder if the CGI tutorial on the python website :http://www.python.org/doc/lib/module-cgi.html, worked for my case? Operating System: Linux Programming Lang: Python Database : PostgreSQL Thank you. Really looking forward for your reply. Cheers. From alan.gauld at blueyonder.co.uk Sat Aug 7 12:54:09 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Aug 7 12:53:11 2004 Subject: [Tutor] Adding custom modules to the module index? References: Message-ID: <010301c47c6c$de4b8560$6401a8c0@xp> > if ur using windows then just create a file with extension .pth Are .pth files a Windows only thing? I thought they worked in all environments? I just keep forgetting they are there... I'm so used to using environment variables for setting paths(*) that I forget that Python has this weoird alternative :-) (*) Java: CLASSPATH Man pages: MANPATH execution path: PATH Load libraries: LDLIBRARY Python: PYTHONPATH etc etc... I'll also need to update my tutorial to mention .pth files. Alan G. From alan.gauld at blueyonder.co.uk Sat Aug 7 13:08:47 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Aug 7 13:07:49 2004 Subject: [Tutor] Help on Python to PostgreSQL and CGI References: <4115454117be.4117be411545@uq.edu.au> Message-ID: <010801c47c6e$e9678960$6401a8c0@xp> > language to fetch data from PostgreSQL Use the DBAPI and the postGres driver module See the DBAPI topic guides/section of the Python web page. Also here is a series of artocles on using Python and PostGres under Lunux: http://www.billworkgroup.org/billworkgroup/home/Doc/BillInstallLinux/DebianPostgreSQLInstall > and display it on a website where user to search from. Use the cgi module for that and if you want to there is an HTML formatting module somewhere on the net too. Its not part of the standard library but it looked fairly useful once you get beyond simple HTML embedded in a string. HTMLGen is the module... http://starship.python.net/crew/friedrich/HTMLgen/html/main.html Here is an article about it. http://www.linuxjournal.com/article.php?sid=2986 Standard CGI processing in Python is described in another article: http://www.linuxjournal.com/article.php?sid=3616 > I'm really lost. I wonder if the CGI tutorial on the python > website :http://www.python.org/doc/lib/module-cgi.html, > worked for my case? It should do. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/ From missive at hotmail.com Sat Aug 7 14:47:14 2004 From: missive at hotmail.com (Lee Harr) Date: Sat Aug 7 14:47:23 2004 Subject: [Tutor] Re: Help on Python to PostgreSQL and CGI Message-ID: >I am actually searching for modules that can link postgreSQL and python >together. I use psycopg: http://initd.org/software/initd/psycopg but there are several others also. Keep in mind that CGI and database access are really two completely separate issues. First, see if you can access the database from python, then see if you can generate and return simple plain text CGI pages. Finally, see if you can return data from the database through the CGI. One step at a time... _________________________________________________________________ Add photos to your messages with MSN 8. Get 2 months FREE*. http://join.msn.com/?page=features/featuredemail From aztech1200 at yahoo.com Sat Aug 7 17:41:22 2004 From: aztech1200 at yahoo.com (Aztech Guy) Date: Sat Aug 7 17:41:26 2004 Subject: [Tutor] Perl template toolkit accessibility In-Reply-To: <20040804231153.GJ1854@johnsons-web.com> Message-ID: <20040807154122.93084.qmail@web53310.mail.yahoo.com> Hi, > Perl and python have such awesome resources that > to be able to > exploit the resources of one by the other might be > a leg up on > both. I've been thinking that recently, too ... Not sure if this'll do what you want, but worth investigating: the Inline::X series of Perl modules by Brian Ingerson - substitute C/Python/Ruby/others for X. It allows you to write snippets of one of those languages embedded inside a Perl script. I did try it out, a little, and it worked - for C and Python. Didn't try too many features though. Also, it will require the X language's compiler or interpreter on the system on which you run your code - which is anyway (more or less) true for Ruby and Python, of course, but not for C (since you can just deploy your C program's binary). Another possible way - in the future - and would need to be checked if it works - is using Parrot, the VM for Perl 6. Supposed to be able to run Python and Ruby as well - when it's released. HTH Az. "Winter brings penguins" --- Tim Johnson wrote: > > > I know this is a *python* ML. Anyway, I > > > program in python, my partner programs in > > > perl. The perl template toolkit is pretty > > > awesome, and he says he thinks that there > are > > > hooks into it for python. Does anyone > > > know anything about this? > Perl and python have such awesome resources that > to be able to > exploit the resources of one by the other might be > a leg up on > both. > > cheers > tim __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From jfabiani at yolo.com Sat Aug 7 19:01:48 2004 From: jfabiani at yolo.com (John Fabiani) Date: Sat Aug 7 19:01:52 2004 Subject: [Tutor] Help on Python to PostgreSQL and CGI In-Reply-To: <4115454117be.4117be411545@uq.edu.au> References: <4115454117be.4117be411545@uq.edu.au> Message-ID: <200408071001.48446.jfabiani@yolo.com> On Saturday 07 August 2004 00:40, Ms Soo Chong wrote: > Hi, > > I am currently a fourth year Uni student who is working on a Thesis that > required me to use python language to develop a webpage that user to query > on. I have to use python language to fetch data from PostgreSQL and display > it on a website where user to search from. I am so new to python and > struggling so hard to learn and apply it. I wonder if anybody out there can > help me a helping hand. > > I am currently reading through a book "Learning Python" and looking through > some useful tutorials. I am actually searching for modules that can link > postgreSQL and python together. Please give me some advice which at least > help me to start up the program, cause I'm really lost. I wonder if the CGI > tutorial on the python website > :http://www.python.org/doc/lib/module-cgi.html, worked for my case? > > Operating System: Linux > Programming Lang: Python > Database : PostgreSQL > > Thank you. > > Really looking forward for your reply. > > Cheers. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor Other may point you in a different direction - but I have found psycopg to be the best of the interfaces. At least that's the one I was able to getting working with other modules. Also take a look a the PDO module (look it up on google). I found it very easy to use. Of course I suggest that you also learn/ read DBAPI 2.0 (specially to how strings are handled). John From kent_johnson at skillsoft.com Sat Aug 7 19:25:33 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sat Aug 7 19:25:37 2004 Subject: [Tutor] RE problems In-Reply-To: <000b01c47bfb$917813f0$65a3a60a@GMC50444> References: <20040806185123.347C01E4016@bag.python.org> <000b01c47bfb$917813f0$65a3a60a@GMC50444> Message-ID: <6.1.0.6.0.20040807131813.02a1b810@mail4.skillsoft.com> James, I'm not sure what you are trying to do. If you want to match all the tags in the HTML, try re.findall() instead of re.match() - match will only find the first match. For example: >>> import re >>> text = '''

Here is some text
\nOn two lines

''' >>> p=re.compile(r"(<.*?>)",re.DOTALL) >>> print p.match(text).group()

>>> print p.findall(text) ['

', '
', '

'] If this is not what you meant, please post a short snippet of HTML and the result you are trying to get from it. Kent At 05:23 PM 8/6/2004 -0400, James Alexander McCarney wrote: >Hi tutors, > >I am having problems returning everything I want from a regular expression. >I am merely getting the first string in the html text file, which stands to >reason as per the code. > >Could someone give me the magic to put all the strings tagged < > thus. > >Thanks for any tips you can provide. As for the document, > >I am reading amk's RE how-to; and I know it's all in there; it's just that >I've cudgeled my brains a lot today. ;-( > >Best regards, >James > >## >## >import pythoncom >from win32com.client import Dispatch >import re > > >app = Dispatch('Word.Application') >app.Visible = 1 > >doc = app.Documents.Add() > >f = open("C:\myfile.html") > >## >## >## >## > >allines = f.read() >p=re.compile(r"(<.*?>)",re.DOTALL) >m=p.match(allines) > >## > > >s1 = doc.Sentences(1) >s1.Text = m.group() > >doc.SaveAs("C:\myTestPy.doc') > >app.Quit() >app = None > >pythoncom.CoUninitialize() >f.close() > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From kent_johnson at skillsoft.com Sat Aug 7 19:35:04 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sat Aug 7 19:35:08 2004 Subject: [Tutor] Adding custom modules to the module index? In-Reply-To: <000501c47bfb$3928f610$87c48f52@allmycore> References: <000501c47bfb$3928f610$87c48f52@allmycore> Message-ID: <6.1.0.6.0.20040807133345.028fd5b0@mail4.skillsoft.com> One easy way to do this is to put your module in the directory Lib/site-packages in your Python distribution. Anything in this directory will be available to import in all your programs. Kent At 11:20 PM 8/6/2004 +0200, Ole Jensen wrote: >How do you add custom modules so that you are able to import them >directly from python? > >E.g. I want to import MyNewModule, and want to avoid the following: > > >>> Import MyNewModule > >Traceback (most recent call last): > File "", line 1, in -toplevel- > import MyNewModule >ImportError: No module named MyNewModule > >I've read that its possible to add your own modules so they can be >imported from IDLE like above, I just cannot remember how!? I've tried >searching through google and python.org but I've lacked a key search >word so I hope someone here can help me. > >------- > >My question is derived from wanting to try out the Zope DataBase (ZODB) >as it says in the documentation >(http://zope.org/Documentation/Articles/ZODB1): > >[quote] >After installing ZODB, you can start to experiment with it right from >the Python command line interpreter. For example, try the following >python code in your interpreter:: > >>> from ZODB import FileStorage, DB >>> storage = >FileStorage.FileStorage(mydatabase.fs) >>> db = DB(storage) >>> >connection = db.open() >>> root = connection.root() >[/quote] > >I have just installed Zope and I read the above as if I straight away >should be able to play around with ZODB within IDLE, please correct me >if I am way of base... > >TIA >Ole Jensen > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From marvboyes at att.net Sat Aug 7 15:17:57 2004 From: marvboyes at att.net (Marv Boyes) Date: Sun Aug 8 01:32:13 2004 Subject: [Tutor] Checking to see whether or not a filesystem is mounted--? Message-ID: <4114D685.40002@att.net> Hello, all. Having a great time here-- this list is an excellent complement to my newbie reading on Python. I never imagined that a robust, full-featured programming language would be so easy and enjoyable to learn. Anyway, enough preamble. I'm wanting to write a small graphical applet for mounting and unmounting filesystems with a button-press. Can anyone suggest a method for testing whether or not a particular filesystem is mounted (so I can inform the user with a message dialog)? Specifically, I don't like relying on supermount-- which is, in my experience, unreliable-- for USB flashdrives on my own system, and have been managing them 'by hand' from a terminal. But programming is all about identifying problems and solving them [right? ;) ], and I'm delighted that I've been able to solve a lot of little problems and nagging deficiencies on my own with Python. Any guidance would be greatly appreciated; thanks very much in advance. Marv -- Help in the research to fight devastating diseases like Huntington's, Parkinson's, and Alzheimer's-- donate your computer's leisure time to Folding@Home. http://www.stanford.edu/group/pandegroup/folding/ -- From kalle at lysator.liu.se Sun Aug 8 02:46:08 2004 From: kalle at lysator.liu.se (Kalle Svensson) Date: Sun Aug 8 02:40:00 2004 Subject: [Tutor] Checking to see whether or not a filesystem is mounted--? In-Reply-To: <4114D685.40002@att.net> References: <4114D685.40002@att.net> Message-ID: <20040808004608.GI17831@i92.ryd.student.liu.se> Hi! [Marv Boyes] > Anyway, enough preamble. I'm wanting to write a small graphical applet > for mounting and unmounting filesystems with a button-press. Can anyone > suggest a method for testing whether or not a particular filesystem is > mounted (so I can inform the user with a message dialog)? I'd probably try reading the output of `mount`. This consists of one or more lines, formatted something like on type [()] If there is a line matching the device you're interested in, the device is mounted. Otherwise it isn't, obviously. Symbolic links could make this more difficult, I suppose. E.g. if /foo is a symlink to /mnt/bar, /foo won't appear in the `mount` output even if /mnt/bar is mounted. I assume there are other difficulties as well. Otherwise it wouldn't be any fun, would it? Program output can be gathered with os.popen and friends or any of several third-party modules. For this purpose, I think os.popen is sufficient. Read more about it on http://python.org/doc/lib/os-newstreams.html#os-newstreams . Good luck! Peace, Kalle -- http://juckapan.org/~kalle/ http://laxmasteriet.se/04-05/ From shabboleth at bonq.com Sun Aug 8 04:16:52 2004 From: shabboleth at bonq.com (Glen) Date: Sun Aug 8 04:17:05 2004 Subject: [Tutor] Tkinter Message-ID: <1091931361.529.4.camel@Waterhouse> Hello All, I am working through an online python tutorial. I have just reached the point covering GUI programming. The tutorial imports the Tkinter module. When I run the program I get this error: ImportError: no module named Tkinter. What do I need to install to give me the Tkinter module? Thanks, Glen From bill.mill at gmail.com Sun Aug 8 04:41:07 2004 From: bill.mill at gmail.com (Bill Mill) Date: Sun Aug 8 04:41:11 2004 Subject: [Tutor] Tkinter In-Reply-To: <1091931361.529.4.camel@Waterhouse> References: <1091931361.529.4.camel@Waterhouse> Message-ID: <797fe3d404080719413bbec8dc@mail.gmail.com> Glen, Could we have more details about your system? Obviously, you need to install the tkinter module, but just how you do that is dependant on your OS. Peace Bill Mill On Sat, 07 Aug 2004 19:16:52 -0700, Glen wrote: > Hello All, > > I am working through an online python tutorial. I have just reached the > point covering GUI programming. The tutorial imports the Tkinter module. > > When I run the program I get this error: > > ImportError: no module named Tkinter. What do I need to install to give > me the Tkinter module? > > Thanks, > > Glen > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From bill.mill at gmail.com Sun Aug 8 07:19:31 2004 From: bill.mill at gmail.com (Bill Mill) Date: Sun Aug 8 07:19:35 2004 Subject: [Tutor] Tkinter In-Reply-To: <1091935860.518.0.camel@Waterhouse> References: <1091931361.529.4.camel@Waterhouse> <797fe3d404080719413bbec8dc@mail.gmail.com> <1091935860.518.0.camel@Waterhouse> Message-ID: <797fe3d404080722194db12faf@mail.gmail.com> Glen, Libranet is a debian-based system right? Well, if their package manager doesn't list tkinter or python-tk in it (it is likely that it does), you can do it from the command line with the program "apt-get". Simply open up a command terminal, type "su" (without the quotes) and enter the root password to assume root privileges. Then, type "apt-get install python-tk". If your apt repositories are set up correctly, tkinter will download and install itself. Also, note that this is more of a debian or libranet problem than a python one, but I hope this helps you out. Once you're done installing it, make sure that you type "exit" or ctrl-d to logout the root user; you don't want to stay logged in with it. Peace Bill Mill On Sat, 07 Aug 2004 20:31:00 -0700, Glen wrote: > I'm sorry, I'm running libranet linux 2.8.1 > > Glen > > > > On Sat, 2004-08-07 at 19:41, Bill Mill wrote: > > Glen, > > > > Could we have more details about your system? Obviously, you need to > > install the tkinter module, but just how you do that is dependant on > > your OS. > > > > Peace > > Bill Mill > > > > On Sat, 07 Aug 2004 19:16:52 -0700, Glen wrote: > > > Hello All, > > > > > > I am working through an online python tutorial. I have just reached the > > > point covering GUI programming. The tutorial imports the Tkinter module. > > > > > > When I run the program I get this error: > > > > > > ImportError: no module named Tkinter. What do I need to install to give > > > me the Tkinter module? > > > > > > Thanks, > > > > > > Glen > > > > > > _______________________________________________ > > > 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 alan.gauld at blueyonder.co.uk Sun Aug 8 09:12:59 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Aug 8 09:12:50 2004 Subject: [Tutor] Tkinter References: <1091931361.529.4.camel@Waterhouse> Message-ID: <013201c47d17$23c57740$6401a8c0@xp> > I am working through an online python tutorial. I have just reached the > point covering GUI programming. The tutorial imports the Tkinter module. Tkinter must be installed on your system and that means Python must be built to accept Tkinter. If you are using Linux you can rebuild the sources or find a package (rpm etc) that has it already. On windows Tkinter should be there already. I'm not sure about MacOSX, you may have to do some messing around there? (I use MacOSX but I've never used Tkinter on the Mac for some reason...) Rebuilding Python with Tkinter on linux is simply a matter of running the config script before make. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/tutor2 From m at mongers.org Sun Aug 8 10:20:50 2004 From: m at mongers.org (Morten Liebach) Date: Sun Aug 8 10:28:41 2004 Subject: [Tutor] Checking to see whether or not a filesystem is mounted--? In-Reply-To: <20040808004608.GI17831@i92.ryd.student.liu.se> References: <4114D685.40002@att.net> <20040808004608.GI17831@i92.ryd.student.liu.se> Message-ID: <20040808082011.GA2352@mongers.org> On 2004-08-08 02:46:08 +0200, Kalle Svensson wrote: > Hi! > > [Marv Boyes] > > Anyway, enough preamble. I'm wanting to write a small graphical applet > > for mounting and unmounting filesystems with a button-press. Can anyone > > suggest a method for testing whether or not a particular filesystem is > > mounted (so I can inform the user with a message dialog)? > > I'd probably try reading the output of `mount`. This consists of one > or more lines, formatted something like > > on type [()] > > If there is a line matching the device you're interested in, the > device is mounted. Otherwise it isn't, obviously. > > Symbolic links could make this more difficult, I suppose. E.g. if > /foo is a symlink to /mnt/bar, /foo won't appear in the `mount` output > even if /mnt/bar is mounted. I assume there are other difficulties as > well. Otherwise it wouldn't be any fun, would it? Try looking for the same device in /etc/fstab, that'll remove some ambiguities. Have a nice day Morten -- http://m.mongers.org/ -- http://gallery.zentience.org/ __END__ From missive at hotmail.com Sun Aug 8 16:27:19 2004 From: missive at hotmail.com (Lee Harr) Date: Sun Aug 8 16:27:22 2004 Subject: [Tutor] Re: Checking to see whether or not a filesystem is mounted--? Message-ID: >Anyway, enough preamble. I'm wanting to write a small graphical applet >for mounting and unmounting filesystems with a button-press. Can anyone >suggest a method for testing whether or not a particular filesystem is >mounted (so I can inform the user with a message dialog)? > You could try mounting it and see if you get an error: homer# mount /mnt mount: /dev/ad0s1e: Device busy _________________________________________________________________ MSN 8 helps eliminate e-mail viruses. Get 2 months FREE*. http://join.msn.com/?page=features/virus From shabboleth at bonq.com Sun Aug 8 16:55:50 2004 From: shabboleth at bonq.com (Glen) Date: Sun Aug 8 16:56:18 2004 Subject: [Tutor] Tkinter In-Reply-To: <013201c47d17$23c57740$6401a8c0@xp> (from alan.gauld@blueyonder.co.uk on Sun, Aug 08, 2004 at 00:12:59 -0700) References: <1091931361.529.4.camel@Waterhouse> <013201c47d17$23c57740$6401a8c0@xp> Message-ID: <20040808145550.GC540@Waterhouse.attbi.com> OK, I have installed python-tk and it is working now. Bill, Thank you for your quick response. Alan, It is your online tutorial that I am working through. Thank you very much for your efforts in writing it. Glen From bill at celestial.net Sun Aug 8 19:46:19 2004 From: bill at celestial.net (Bill Campbell) Date: Sun Aug 8 19:46:23 2004 Subject: [Tutor] Checking to see whether or not a filesystem is mounted--? In-Reply-To: <20040808004608.GI17831@i92.ryd.student.liu.se> References: <4114D685.40002@att.net> <20040808004608.GI17831@i92.ryd.student.liu.se> Message-ID: <20040808174619.GA91799@alexis.mi.celestial.com> On Sun, Aug 08, 2004, Kalle Svensson wrote: >Hi! > >[Marv Boyes] >> Anyway, enough preamble. I'm wanting to write a small graphical applet >> for mounting and unmounting filesystems with a button-press. Can anyone >> suggest a method for testing whether or not a particular filesystem is >> mounted (so I can inform the user with a message dialog)? > >I'd probably try reading the output of `mount`. This consists of one >or more lines, formatted something like I normally parse the output of the gnu df (gdf) to find mounted file systems eliminating special things like procfs. There are many variations in the output of the mount command on different operating systems. I build the gnu fileutils, findutils, with program=prefix='g', and on Linux systems make symlinks from the standard commands to ones with ``g'' prefixes so my scripts don't require changes or special tests. #!/usr/local/bin/python import os, os.path # Dictionary of things that aren't real file systems pseudofilesys = \ dict(map((lambda x: (x, 1)), ('none', 'shmfs', 'procfs', 'tmpfs'))) gdf_cols = ('filesys', 'blocks', 'used', 'avail', 'use', 'dir') def mounted() : '''return array of mounted file systems''' df = os.popen('gdf 2>/dev/null', 'r') df.readline() # skip first line mounted = [] for line in df.readlines() : line = line.strip() rec = dict(zip(gdf_cols, line.split(None, 5))) filesys = rec['filesys'] dir = rec.get('dir', None) # Check for directory, NFS mounts, or pseudo file systems if dir and not (filesys.find(':') >0 or pseudofilesys.has_key(filesys)): mounted.append(dir) df.close() return mounted Bill -- INTERNET: bill@Celestial.COM Bill Campbell; Celestial Software LLC UUCP: camco!bill PO Box 820; 6641 E. Mercer Way FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 URL: http://www.celestial.com/ ``Ah, you know the type. They like to blame it all on the Jews or the Blacks, 'cause if they couldn't, they'd have to wake up to the fact that life's one big, scary, glorious, complex and ultimately unfathomable crapshoot -- and the only reason THEY can't seem to keep up is they're a bunch of misfits and losers.'' -- A analysis of Neo-Nazis, from "The Badger" comic From alan.gauld at blueyonder.co.uk Sun Aug 8 20:10:43 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Aug 8 20:10:24 2004 Subject: [Tutor] Regex puzzlement Message-ID: <014f01c47d73$05913550$6401a8c0@xp> My turn to be confused by a regex... >>> import re >>> r = re.compile('[&()-;:,.?!]') >>> r.findall('Here is one, or two. but not 6 or 7') [',', '.', '6', '7'] >>> Why is it finding the numbers? Presumably some weird regex convention amongst the chars I've put in the group, but what? And how do I get rid of it? Alan G. From bill.mill at gmail.com Sun Aug 8 20:57:57 2004 From: bill.mill at gmail.com (Bill Mill) Date: Sun Aug 8 20:58:08 2004 Subject: [Tutor] Regex puzzlement In-Reply-To: <014f01c47d73$05913550$6401a8c0@xp> References: <014f01c47d73$05913550$6401a8c0@xp> Message-ID: <797fe3d404080811574723edb3@mail.gmail.com> from the re documentation (http://www.python.org/doc/current/lib/re-syntax.html): If you want to include a "]" or a "-" inside a set, precede it with a backslash What happened is that the '-' was interpreted by the regex module as meaning that you had presented a character range from '\\' to ';'. In [31]: ord('\\') Out[31]: 92 In [32]: ord(';') Out[32]: 59 In [33]: ord('1') Out[33]: 49 In [34]: ord('a') Out[34]: 97 Thus, anything with an ord between 92 and 59 would be interpreted as matching your regex. Peace Bill Mill On Sun, 8 Aug 2004 19:10:43 +0100, Alan Gauld wrote: > My turn to be confused by a regex... > > >>> import re > >>> r = re.compile('[&()-;:,.?!]') > >>> r.findall('Here is one, or two. but not 6 or 7') > [',', '.', '6', '7'] > >>> > > Why is it finding the numbers? > Presumably some weird regex convention amongst the chars I've > put in the group, but what? And how do I get rid of it? > > Alan G. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From bill.mill at gmail.com Sun Aug 8 21:03:31 2004 From: bill.mill at gmail.com (Bill Mill) Date: Sun Aug 8 21:03:34 2004 Subject: [Tutor] Regex puzzlement In-Reply-To: <797fe3d404080811574723edb3@mail.gmail.com> References: <014f01c47d73$05913550$6401a8c0@xp> <797fe3d404080811574723edb3@mail.gmail.com> Message-ID: <797fe3d404080812036fda2d4d@mail.gmail.com> Hey, that last message didn't make sense. What I meant was that it was interpreted as a character range from ')' to ';', where: In [36]: ord(')') Out[36]: 41 In [32]: ord(';') Out[32]: 59 In [33]: ord('1') Out[33]: 49 In [34]: ord('a') Out[34]: 97 so anything with an ord between 41 and 59 matches your regex. Peace Bill Mill On Sun, 8 Aug 2004 14:57:57 -0400, Bill Mill wrote: > from the re documentation > (http://www.python.org/doc/current/lib/re-syntax.html): > If you want to include a "]" or a "-" inside a set, precede it > with a backslash > > What happened is that the '-' was interpreted by the regex module as > meaning that you had presented a character range from '\\' to ';'. > > In [31]: ord('\\') > Out[31]: 92 > > In [32]: ord(';') > Out[32]: 59 > > In [33]: ord('1') > Out[33]: 49 > > In [34]: ord('a') > Out[34]: 97 > > Thus, anything with an ord between 92 and 59 would be interpreted as > matching your regex. > > Peace > Bill Mill > > > > On Sun, 8 Aug 2004 19:10:43 +0100, Alan Gauld > wrote: > > My turn to be confused by a regex... > > > > >>> import re > > >>> r = re.compile('[&()-;:,.?!]') > > >>> r.findall('Here is one, or two. but not 6 or 7') > > [',', '.', '6', '7'] > > >>> > > > > Why is it finding the numbers? > > Presumably some weird regex convention amongst the chars I've > > put in the group, but what? And how do I get rid of it? > > > > Alan G. > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > From klappnase at freenet.de Sun Aug 8 23:07:07 2004 From: klappnase at freenet.de (Michael Lange) Date: Sun Aug 8 23:10:25 2004 Subject: [Tutor] Checking to see whether or not a filesystem is mounted--? In-Reply-To: <4114D685.40002@att.net> References: <4114D685.40002@att.net> Message-ID: <20040808230707.620c0b43.klappnase@freenet.de> On Sat, 07 Aug 2004 09:17:57 -0400 Marv Boyes wrote: > Anyway, enough preamble. I'm wanting to write a small graphical applet > for mounting and unmounting filesystems with a button-press. Can anyone > suggest a method for testing whether or not a particular filesystem is > mounted (so I can inform the user with a message dialog)? > Another suggestion, which I found very handy for personal use: device = sys.argv[1] mntlist = commands.getoutput('cat /etc/mtab').split() if device in mntlist: This worked fine for me in a little program that I use to put icons on my desktop for floppy and cdrom which allow to mount the device and open the file manager with a mouse-click as if I were using Gnome or KDE; "device" gets of course passed to the app as command line argument( like '/mnt/floppy'), and if device is already mounted you are asked to unmount it or just simply open the file manager there. Michael From alan.gauld at blueyonder.co.uk Mon Aug 9 00:27:44 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Mon Aug 9 00:27:22 2004 Subject: [Tutor] Regex puzzlement References: <014f01c47d73$05913550$6401a8c0@xp> <797fe3d404080811574723edb3@mail.gmail.com> <797fe3d404080812036fda2d4d@mail.gmail.com> Message-ID: <015801c47d96$ed4931e0$6401a8c0@xp> Doh! Its always obvious once you see it! Thanks Bill, I knew it had to be something abouyt one of the characters but short of escaping each one in turn... I knew about the range thing, just didn't see it. Thanks again. Alan G. ----- Original Message ----- From: "Bill Mill" To: "Alan Gauld" Cc: Sent: Sunday, August 08, 2004 8:03 PM Subject: Re: [Tutor] Regex puzzlement > Hey, that last message didn't make sense. What I meant was that it was > interpreted as a character range from ')' to ';', where: > > In [36]: ord(')') > Out[36]: 41 > > In [32]: ord(';') > Out[32]: 59 > > In [33]: ord('1') > Out[33]: 49 > > In [34]: ord('a') > Out[34]: 97 > > so anything with an ord between 41 and 59 matches your regex. > > Peace > Bill Mill > > On Sun, 8 Aug 2004 14:57:57 -0400, Bill Mill wrote: > > from the re documentation > > (http://www.python.org/doc/current/lib/re-syntax.html): > > If you want to include a "]" or a "-" inside a set, precede it > > with a backslash > > > > What happened is that the '-' was interpreted by the regex module as > > meaning that you had presented a character range from '\\' to ';'. > > > > In [31]: ord('\\') > > Out[31]: 92 > > > > In [32]: ord(';') > > Out[32]: 59 > > > > In [33]: ord('1') > > Out[33]: 49 > > > > In [34]: ord('a') > > Out[34]: 97 > > > > Thus, anything with an ord between 92 and 59 would be interpreted as > > matching your regex. > > > > Peace > > Bill Mill > > > > > > > > On Sun, 8 Aug 2004 19:10:43 +0100, Alan Gauld > > wrote: > > > My turn to be confused by a regex... > > > > > > >>> import re > > > >>> r = re.compile('[&()-;:,.?!]') > > > >>> r.findall('Here is one, or two. but not 6 or 7') > > > [',', '.', '6', '7'] > > > >>> > > > > > > Why is it finding the numbers? > > > Presumably some weird regex convention amongst the chars I've > > > put in the group, but what? And how do I get rid of it? > > > > > > Alan G. > > > > > > _______________________________________________ > > > Tutor maillist - Tutor@python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > From rdm at rcblue.com Mon Aug 9 00:32:28 2004 From: rdm at rcblue.com (Dick Moores) Date: Mon Aug 9 00:32:32 2004 Subject: [Tutor] Python cashes low integers? How? Where? Message-ID: <6.1.2.0.2.20040808151623.023c6828@rcblue.com> I've been reading Wesley Chun's _Core Python Programming_ today, about object identities. Using p. 85 I entered >>> a = 4 >>> b = 1 + 3 >>> a is b True The book says this will be False. The book's errata page () says that the error is because Python cashes low integers, and to try this with floats: >>> a = 4.0 >>> b = 1.0 + 3.0 >>> a is b False I tested with larger integers: >>> f = 100 >>> g = 99 + 1 >>> f is g False OK. Now, this intrigued me. Where does Python do this cashing? Not in my computer's memory, because rebooting doesn't change the above results. So where? Thanks, Dick Moores Win XP, Python 2.3.4 From kalle at lysator.liu.se Mon Aug 9 01:15:41 2004 From: kalle at lysator.liu.se (Kalle Svensson) Date: Mon Aug 9 01:09:28 2004 Subject: [Tutor] Python cashes low integers? How? Where? In-Reply-To: <6.1.2.0.2.20040808151623.023c6828@rcblue.com> References: <6.1.2.0.2.20040808151623.023c6828@rcblue.com> Message-ID: <20040808231541.GL17831@i92.ryd.student.liu.se> Hi! [Dick Moores] > >>> a = 4 > >>> b = 1 + 3 > >>> a is b > True ... > OK. Now, this intrigued me. Where does Python do this cashing? Not > in my computer's memory, because rebooting doesn't change the above > results. So where? Indeed in your computer's memory, but the cache is not persistent between reboots or even Python invocations. The line 'a = 4' creates an integer object with the value 4 (let's call it ), and since 4 is less than some limit, the object is cached. 'a' now points to and the integer cache contains one object, the same . Next, the line 'b = 1 + 3' creates two integer objects, and . They are also cached. They are then added together. Since the result is 4, no new integer object is created but a reference to the cached is returned and 'b' is made to point to it. Thus 'a is b' comes to be true. The integer cache now contains , and . The next time you start Python, the integer cache is empty again. Hope this helps! Peace, Kalle -- http://juckapan.org/~kalle/ http://laxmasteriet.se/04-05/ From goluptious at hotmail.com Mon Aug 9 03:35:47 2004 From: goluptious at hotmail.com (goluptious) Date: Mon Aug 9 03:35:53 2004 Subject: [Tutor] timer vs. timeout - struct.unpack Message-ID: A somewhat brief explanation of what I am trying to accomplish: First, I have never programmed in any language before. I chose Python because I was able to read and understand some of the scripts that I had seen. Second, I know that the project that I am trying to do is actually quite advanced, but I have to try it anyway. Third, the company that I work for manufactures network digital video surveillance equipment - network cameras and video servers. They have developed a protocol using UDP that is used to get and set the network configuration information for all devices on a LAN. Fourth, they have developed a Windows-centric application using their SearchDevice Protocol, that I can't get to run - even under Wine - on my Linux box. Fifth, after spending about a week searching the Web and going through 'Learn to Program Using Python' and 'Python Essential Reference', I've come up with a very crude starting point. The Project 1. Create a UDP client that can broadcast a request asking all devices on the LAN to report their network configuration. 2. From the data received from the clients, extract the network configuration information and display it. 3. Change the network configuration information of a single device, selected devices or all devices. I've managed to get most through most of point 1 and I'm starting on point 2. The script that I have created (see below) works well enough that I can take the data from stdout and manually extract the network configuration information of the devices. Problem 1. Because I don't know how many devices are on the LAN and I don't want the program to wait indefinitely for a reply to the request from the client, I have set a receive timeout. This timeout causes a traceback error in messin = sock.recv(236) (see error message below). Is there a better way to set a timeout? Should I use a timer instead? Problem 2. I've tried using both messin = sock.recv(236) and messin = sock.recvfrom(236). The former doesn't give me any kind of readable information in stdout unless I use struct.unpack. The latter gives me readable information in stdout and include the IP address and port, which are not necessary as they are already included in the data stream. So I decided to use messin = sock.recv(236). The information that is written to the file 'foo' is unreadable, as are the stdout from messin and messunpack[0], however, stdout from messunpack is OK (see printout of stdout below). Could someone offer some advice on how to use struct.unpack properly so that I can extract the necessary information from the data? Problem 3. The commID is supposed to be a randomly generated string. Can someone offer some advice on how to create such a string? I'm not asking for anyone to do my work for me. I would just like some advice. Thank you, Sean Bobb ###---->BEGIN SCRIPT ---- #! /usr/bin/env python from socket import * from struct import * servid = '96c363be-b894-43b5-8501-ae5c00e779b3' #must be this null terminated string (40 bytes) commId = 'ab22ff01-309c-4da3-9f8d-75bcda04811d' #random transaction ID using this format (40 bytes) packSize = '\xec\x00' #Total bytes of data frame: for the request it should be 236 bytes(0xEC) (2 bytes) macAddr = '\xff\xff\xff\xff\xff\xff' # for request should be ff:ff:ff:ff:ff:ff (4 bytes) ipaddr = '' # for request null value (4 bytes) netmask ='' # for request null value (4 bytes) gateway = '' # for request null value (4 bytes) dns1 = '' # for request null value (4 bytes) dns2 = '' # for request null value (4 bytes) dns3 = '' # for request null value (4 bytes) htport ='' # for request null value (2 bytes) recvinfo = '' # for request null value (20 bytes) resv = '\x00' messout = servid + (4 * resv) + commId + (4 * resv) + packSize + (2 * resv) + macAddr + (146 * resv) # the final reserve value of 146 is actually a combination of ipaddr through recvinfo, including a 2 byte reserve after macAddr and 98 bytes after htport rcvtime = pack('ll', 1l, 0l) f = open("/root/scripts/foo", "w+") # just used to see what kind of info I can write to a file sock = socket(AF_INET, SOCK_DGRAM) # open a socket for UDP communication sock.setsockopt(SOL_SOCKET, SO_BROADCAST, 1) # set the socket option to allow broadcast sock.setsockopt(SOL_SOCKET, SO_RCVTIMEO, rcvtime) # set the receive timeout so that the socket doesn't wait indefinitely sock.bind(('',58798)) # bind the socket to 255.255.255.255 port 58798 (required for the SearchDevice Protocol) sock.sendto(messout, ('', 58797)) # send to 255.255.255.255 port 58797 (required for the SearchDevice Protocol) while 1: #without the loop, the socket only receives information from a single device before exiting messin = sock.recv(236) #receive a data packet of 236 bytes messunpack = unpack('236s', messin) # convert the data from 32-bit packed binary to a tuple f.write(messin) # just used to test writing to a file (not necessary) f.write(messunpack[0]) # same as above (written data is identical to above) print messunpack #just used to test the script (only information that I can parse manually) print messunpack[0] #just used to test the script print messin #just used to test the script (stdout is the same as messunpack[0]) sock.close() #the script doesn't reach this far, the receive timeout causes a traceback error in messin = sock.recv(236) ###---->END SCRIPT ---- ###---->PRINTOUT of STDOUT ---- ('96c363be-b894-43b5-8501-ae5c00e779b3\x00\x00\x00\x00ab22ff01-309c-4da3-9f8 d-75bcda04811d\x00\x00\x00\x00\xec\x00\x00\x02\x00\x04)\x08\xf5p\x00\x00\xc0 \xa8\x00\xf0\xff\xff\xff\x00\xc0\xa8\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00 \x00\x00\x00\x00\x1f\x90\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00 \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00 \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00 \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00 \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00 \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00 \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00',) ###---SNIP----- ###---->ERROR MESSAGE BEGIN---- Traceback (most recent call last): File "ipinstalludpclient3.py", line 29, in ? messin = sock.recv(236) socket.error: (11, 'Resource temporarily unavailable') ###---->END ERROR MESSAGE ---- From jule_s14 at hotmail.com Mon Aug 9 06:17:39 2004 From: jule_s14 at hotmail.com (Julian Martinez del Campo) Date: Mon Aug 9 06:17:43 2004 Subject: [Tutor] Begginer in need of help Message-ID: I am brand new to python and am learning python through tutorials on the net. i am stuck on one exercise, where i have to write a program that has a user guess your name, but they only get 3 chances to do so until the program quits. I cannot get my program to quit after the 3 tries. can u help. (here is my program) s = 0 a = 1 name = "dan" while a < 4: my_name = raw_input("what is my name? ") if my_name == "julian": print "correct" a = 10 elif s < 3: s = s + a print "Nope, you have, ",3-s," tries left" _________________________________________________________________ FREE pop-up blocking with the new MSN Toolbar – get it now! http://toolbar.msn.click-url.com/go/onm00200415ave/direct/01/ From rdm at rcblue.com Mon Aug 9 08:49:50 2004 From: rdm at rcblue.com (Dick Moores) Date: Mon Aug 9 08:49:53 2004 Subject: [Tutor] Python cashes low integers? How? Where? In-Reply-To: <20040808231541.GL17831@i92.ryd.student.liu.se> References: <6.1.2.0.2.20040808151623.023c6828@rcblue.com> <20040808231541.GL17831@i92.ryd.student.liu.se> Message-ID: <6.1.2.0.2.20040808233734.02315ec0@rcblue.com> Kalle Svensson wrote at 16:15 8/8/2004: >Hi! > >[Dick Moores] > > >>> a = 4 > > >>> b = 1 + 3 > > >>> a is b > > True >... > > OK. Now, this intrigued me. Where does Python do this cashing? Not > > in my computer's memory, because rebooting doesn't change the above > > results. So where? > >Indeed in your computer's memory, but the cache is not persistent >between reboots or even Python invocations. > >The line 'a = 4' creates an integer object with the value 4 (let's >call it ), and since 4 is less than some limit, the object is >cached. 'a' now points to and the integer cache contains one >object, the same . > >Next, the line 'b = 1 + 3' creates two integer objects, and >. They are also cached. They are then added together. Since >the result is 4, no new integer object is created but a reference to >the cached is returned and 'b' is made to point to it. > >Thus 'a is b' comes to be true. The integer cache now contains >, and . The next time you start Python, the >integer cache is empty again. > >Hope this helps! Sure did. Thanks very much. BTW for me, the caching seems to be done for integers up to, but not including, 100. If I could ask what seems to be a related question: On p. 85 Chun says, "Each object has associated with it a counter that tracks the total number of references that exist to that object. This number simply indicates how many variables are 'pointing to' any particular object." However, he doesn't say how to find this number. Is there a way? Thanks, Dick Moores From gew75 at hotmail.com Mon Aug 9 08:52:54 2004 From: gew75 at hotmail.com (Glen Wheeler) Date: Mon Aug 9 08:53:03 2004 Subject: [Tutor] Begginer in need of help References: Message-ID: Hi Julian, Welcome to Python! It's a wonderful language. I have some comments on your existing program: > s = 0 > a = 1 > It's always a good idea to name your variables something meaningful. It doesn't make any difference to the python interpreter, and it makes your life easier when trying to debug code you've written. > name = "dan" What is this variable for? > while a < 4: > my_name = raw_input("what is my name? ") > if my_name == "julian": > print "correct" > a = 10 > elif s < 3: > s = s + a > print "Nope, you have, ",3-s," tries left" This loop will exit if a is not less than 4. The basic problem here is that a is only ever assigned a value if my_name == "julian". There is no otherwise, you only have an elif part (where a is not assigned any value). I would suggest that you add an else clause, or simply place a = a+1 after the elif (outside the scope of that block) like so: > while a < 4: > my_name = raw_input("what is my name? ") > if my_name == "julian": > print "correct" > a = 10 > elif s < 3: > s = s + a > print "Nope, you have, ",3-s," tries left" *> a = a + 1 The problem here is that this makes your message give erroneous output. I'll leave you that to fix yourself, but as a suggestion try removing the s variable entirely and just use a. Even better would be to rename a to perhaps number_of_tries? HTH, Glen ----- Original Message ----- From: "Julian Martinez del Campo" To: Sent: Monday, August 09, 2004 2:17 PM Subject: [Tutor] Begginer in need of help > I am brand new to python and am learning python through tutorials on the > net. i am stuck on one exercise, where i have to write a program that has a > user guess your name, but they only get 3 chances to do so until the program > quits. I cannot get my program to quit after the 3 tries. can u help. > (here is my program) > > > s = 0 > a = 1 > > name = "dan" > while a < 4: > my_name = raw_input("what is my name? ") > if my_name == "julian": > print "correct" > a = 10 > elif s < 3: > s = s + a > print "Nope, you have, ",3-s," tries left" > > _________________________________________________________________ > FREE pop-up blocking with the new MSN Toolbar ? get it now! > http://toolbar.msn.click-url.com/go/onm00200415ave/direct/01/ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From kalle at lysator.liu.se Mon Aug 9 09:59:49 2004 From: kalle at lysator.liu.se (Kalle Svensson) Date: Mon Aug 9 09:53:33 2004 Subject: [Tutor] Python cashes low integers? How? Where? In-Reply-To: <6.1.2.0.2.20040808233734.02315ec0@rcblue.com> References: <6.1.2.0.2.20040808151623.023c6828@rcblue.com> <20040808231541.GL17831@i92.ryd.student.liu.se> <6.1.2.0.2.20040808233734.02315ec0@rcblue.com> Message-ID: <20040809075949.GN17831@i92.ryd.student.liu.se> [Dick Moores] > If I could ask what seems to be a related question: On p. 85 Chun > says, "Each object has associated with it a counter that tracks the > total number of references that exist to that object. This number > simply indicates how many variables are 'pointing to' any particular > object." However, he doesn't say how to find this number. Is there > a way? Yes. The number is called a refcount, and can be read with the function sys.getrefcount. http://python.org/doc/lib/module-sys.html#l2h-344 Peace, Kalle -- http://juckapan.org/~kalle/ http://laxmasteriet.se/04-05/ From rdm at rcblue.com Mon Aug 9 10:22:01 2004 From: rdm at rcblue.com (Dick Moores) Date: Mon Aug 9 10:22:13 2004 Subject: [Tutor] Python cashes low integers? How? Where? In-Reply-To: <20040809075949.GN17831@i92.ryd.student.liu.se> References: <6.1.2.0.2.20040808151623.023c6828@rcblue.com> <20040808231541.GL17831@i92.ryd.student.liu.se> <6.1.2.0.2.20040808233734.02315ec0@rcblue.com> <20040809075949.GN17831@i92.ryd.student.liu.se> Message-ID: <6.1.2.0.2.20040809010922.05060ec0@rcblue.com> Kalle Svensson wrote at 00:59 8/9/2004: >[Dick Moores] > > If I could ask what seems to be a related question: On p. 85 Chun > > says, "Each object has associated with it a counter that tracks the > > total number of references that exist to that object. This number > > simply indicates how many variables are 'pointing to' any particular > > object." However, he doesn't say how to find this number. Is there > > a way? > >Yes. The number is called a refcount, and can be read with the >function sys.getrefcount. >http://python.org/doc/lib/module-sys.html#l2h-344 Thanks! But why do I get these results for sys.getrefcount(3456)? Shouldn't it return at least a 3, and then drop to one less after del a ? >>>import sys >>> a = b = c = 3456 >>> sys.getrefcount(3456) 2 >>> a is b True >>> b is c True >>> a is c True >>> del a >>> sys.getrefcount(3456) 2 With "Dick" I get pretty much what I expected: a = b = c = "Dick" >>> sys.getrefcount("Dick") 5 >>> del a >>> sys.getrefcount("Dick") 4 Dick From python at bernardlebel.com Mon Aug 9 12:26:58 2004 From: python at bernardlebel.com (Bernard Lebel) Date: Mon Aug 9 12:27:11 2004 Subject: [Tutor] sys.path.append() not permanent? Message-ID: <004001c47dfb$6a5316b0$0d01a8c0@studioaction.local> Hello, I'm appending a sys path for a module, but each time I launch python (using PythonWin) the path is gone and I have to reappend it. Is there a way to append the path so it actually stays appended? I'm running: sys.path.append( 'C:\\Python23\\Lib\\site-packages\\mysql-python-1.0.0.win32-py2.3' ) Thanks Bernard From goluptious at hotmail.com Mon Aug 9 12:31:40 2004 From: goluptious at hotmail.com (goluptious) Date: Mon Aug 9 12:31:45 2004 Subject: [Tutor] Re: timer vs. timeout - struct.unpack Message-ID: I figured out how to extract the data and and display it, but I still haven't managed to figure out a proper method to run my loop. Is there some way to use the Traceback to close the loop so that I can close the socket? Is a timer a better option? If so, should I use the threading timer or create my own using time? BTW, after a little more searching I found out that the commId was actually a UUID, so I modified the script to incorporate this also. If anyone has some advice as to how to do all these functions a little less crudely, or perhaps something that I will be able to port to other operating systems I would really appreciate it. (I've tried just copying over the dnet.so file from my Linux box to Windows, but it returns an error no module named dnet, I guess libdnet has to be compiled under Windows.) Thank you, Sean Bobb ###--->BEGIN SCRIPT ---### #! /usr/bin/env python from socket import * from struct import * import re import dnet import commands def uuidgen(): return commands.getoutput('uuidgen') servid = '96c363be-b894-43b5-8501-ae5c00e779b3' resv = '\x00' commId = uuidgen() packSize = '\xec\x00' macAddr = '\xff\xff\xff\xff\xff\xff' ipAddr = '' netMask ='' gateWay = '' Dns1 = '' Dns2 = '' Dns3 = '' httpPort ='' messout = servid + (4 * resv) + commId + (4 * resv) + packSize + (2 * resv) + macAddr + (146 * resv) rcvtime = pack('ll', 1l, 0l) sock = socket(AF_INET, SOCK_DGRAM) sock.setsockopt(SOL_SOCKET, SO_BROADCAST, 1) sock.setsockopt(SOL_SOCKET, SO_RCVTIMEO, rcvtime) sock.bind(('',58798)) sock.sendto(messout, ('', 58797)) while 1: messin = sock.recv(236) messunpack = unpack('236s', messin) spl = re.split('96c36.*?\\xec\\x00\\x00\\x02', messunpack[0]) spl1 = spl[1] macaddr = dnet.eth_ntoa(spl1[0:6]) ipaddr = inet_ntoa(spl1[8:12]) netmask = inet_ntoa(spl1[12:16]) gateway = inet_ntoa(spl1[16:20]) dns1 = inet_ntoa(spl1[20:24]) dns2 = inet_ntoa(spl1[24:28]) dns3 = inet_ntoa(spl1[28:32]) httpport = str(ord(spl1[32]) * 256 + ord(spl1[33])) print "MAC Address: " + macaddr + "\nIP Address: " + ipaddr + "\nNetmask: " + netmask + "\nGateway: " + gateway + "\nDNS1: " + dns1 + "\nDNS2: " + dns2 + "\nDNS3: " + dns3 + "\nHTTP Port: " + httpport + "\n\n" sock.close() From kent_johnson at skillsoft.com Mon Aug 9 14:19:16 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Mon Aug 9 14:19:19 2004 Subject: [Tutor] Python cashes low integers? How? Where? In-Reply-To: <6.1.2.0.2.20040809010922.05060ec0@rcblue.com> References: <6.1.2.0.2.20040808151623.023c6828@rcblue.com> <20040808231541.GL17831@i92.ryd.student.liu.se> <6.1.2.0.2.20040808233734.02315ec0@rcblue.com> <20040809075949.GN17831@i92.ryd.student.liu.se> <6.1.2.0.2.20040809010922.05060ec0@rcblue.com> Message-ID: <6.1.0.6.0.20040809081639.02a181e8@mail4.skillsoft.com> Since 3456 is not cached, you are calling getrefcount on a different 3456 than the one you assigned to a, b and c! >>> import sys >>> a=b=c=3456 >>> sys.getrefcount(3456) 2 >>> sys.getrefcount(a) 4 >>> del c >>> sys.getrefcount(a) 3 Kent At 01:22 AM 8/9/2004 -0700, Dick Moores wrote: But why do I get these results for sys.getrefcount(3456)? Shouldn't it return at least a 3, and then drop to one less after del a ? > >>>import sys > >>> a = b = c = 3456 > >>> sys.getrefcount(3456) >2 > >>> a is b >True > >>> b is c >True > >>> a is c >True > >>> del a > >>> sys.getrefcount(3456) >2 From kent_johnson at skillsoft.com Mon Aug 9 14:29:30 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Mon Aug 9 14:29:36 2004 Subject: [Tutor] Re: timer vs. timeout - struct.unpack In-Reply-To: References: Message-ID: <6.1.0.6.0.20040809082134.02a1ec50@mail4.skillsoft.com> Sean Bobb, It looks like maybe the socket module is throwing an exception when the socket read times out. You can use a try / except block to catch the exception and close the socket. For example, something like this: sock = ... # set up socket try: while 1: messin = sock.recv(236) # handle data from socket except socket.error, (errno, strerror): sock.close() if errno != 11: raise # unexpected error, don't hide it You may have to tweak this a bit, I am guessing at what is going on. Kent At 06:31 PM 8/9/2004 +0800, goluptious wrote: >I figured out how to extract the data and and display it, but I still >haven't managed to figure out a proper method to run my loop. >Is there some way to use the Traceback to close the loop so that I can close >the socket? >Is a timer a better option? If so, should I use the threading timer or >create my own using time? > >BTW, after a little more searching I found out that the commId was actually >a UUID, so I modified the script to incorporate this also. > >If anyone has some advice as to how to do all these functions a little less >crudely, or perhaps something that I will be able to port to other operating >systems I would really appreciate it. (I've tried just copying over the >dnet.so file from my Linux box to Windows, but it returns an error no module >named dnet, I guess libdnet has to be compiled under Windows.) > >Thank you, > >Sean Bobb > > >###--->BEGIN SCRIPT ---### >#! /usr/bin/env python > >from socket import * >from struct import * >import re >import dnet >import commands > >def uuidgen(): > return commands.getoutput('uuidgen') > >servid = '96c363be-b894-43b5-8501-ae5c00e779b3' >resv = '\x00' >commId = uuidgen() >packSize = '\xec\x00' >macAddr = '\xff\xff\xff\xff\xff\xff' >ipAddr = '' >netMask ='' >gateWay = '' >Dns1 = '' >Dns2 = '' >Dns3 = '' >httpPort ='' >messout = servid + (4 * resv) + commId + (4 * resv) + packSize + (2 * resv) >+ macAddr + (146 * resv) >rcvtime = pack('ll', 1l, 0l) > >sock = socket(AF_INET, SOCK_DGRAM) >sock.setsockopt(SOL_SOCKET, SO_BROADCAST, 1) >sock.setsockopt(SOL_SOCKET, SO_RCVTIMEO, rcvtime) >sock.bind(('',58798)) >sock.sendto(messout, ('', 58797)) >while 1: > messin = sock.recv(236) > messunpack = unpack('236s', messin) > spl = re.split('96c36.*?\\xec\\x00\\x00\\x02', messunpack[0]) > spl1 = spl[1] > macaddr = dnet.eth_ntoa(spl1[0:6]) > ipaddr = inet_ntoa(spl1[8:12]) > netmask = inet_ntoa(spl1[12:16]) > gateway = inet_ntoa(spl1[16:20]) > dns1 = inet_ntoa(spl1[20:24]) > dns2 = inet_ntoa(spl1[24:28]) > dns3 = inet_ntoa(spl1[28:32]) > httpport = str(ord(spl1[32]) * 256 + ord(spl1[33])) > print "MAC Address: " + macaddr + "\nIP Address: " + ipaddr + "\nNetmask: " >+ netmask + "\nGateway: " + gateway + "\nDNS1: " + dns1 + "\nDNS2: " + dns2 >+ "\nDNS3: " + dns3 + "\nHTTP Port: " + httpport + "\n\n" >sock.close() >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From kent_johnson at skillsoft.com Mon Aug 9 14:37:26 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Mon Aug 9 14:37:28 2004 Subject: [Tutor] sys.path.append() not permanent? In-Reply-To: <004001c47dfb$6a5316b0$0d01a8c0@studioaction.local> References: <004001c47dfb$6a5316b0$0d01a8c0@studioaction.local> Message-ID: <6.1.0.6.0.20040809083133.02a1e4a0@mail4.skillsoft.com> Bernard, Create a file called sitecustomize.py containing your sys.path.append statement.Save it in C:\Python23\Lib\site-packages\sitecustomize.py. It will be imported each time you run python. Kent At 12:26 PM 8/9/2004 +0200, Bernard Lebel wrote: >Hello, > >I'm appending a sys path for a module, but each time I launch python (using >PythonWin) the path is gone and I have to reappend it. Is there a way to >append the path so it actually stays appended? > >I'm running: >sys.path.append( >'C:\\Python23\\Lib\\site-packages\\mysql-python-1.0.0.win32-py2.3' ) > > >Thanks >Bernard > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From python at bernardlebel.com Mon Aug 9 14:47:49 2004 From: python at bernardlebel.com (Bernard Lebel) Date: Mon Aug 9 14:47:59 2004 Subject: [Tutor] sys.path.append() not permanent? References: <004001c47dfb$6a5316b0$0d01a8c0@studioaction.local> <6.1.0.6.0.20040809083133.02a1e4a0@mail4.skillsoft.com> Message-ID: <005b01c47e0f$15e6e840$0d01a8c0@studioaction.local> Thanks Kent, it worked like a charm. Bernard ----- Original Message ----- From: "Kent Johnson" To: Sent: Monday, August 09, 2004 2:37 PM Subject: Re: [Tutor] sys.path.append() not permanent? > Bernard, > > Create a file called sitecustomize.py containing your sys.path.append > statement.Save it in C:\Python23\Lib\site-packages\sitecustomize.py. It > will be imported each time you run python. > > Kent > > At 12:26 PM 8/9/2004 +0200, Bernard Lebel wrote: > >Hello, > > > >I'm appending a sys path for a module, but each time I launch python (using > >PythonWin) the path is gone and I have to reappend it. Is there a way to > >append the path so it actually stays appended? > > > >I'm running: > >sys.path.append( > >'C:\\Python23\\Lib\\site-packages\\mysql-python-1.0.0.win32-py2.3' ) > > > > > >Thanks > >Bernard > > > >_______________________________________________ > >Tutor maillist - Tutor@python.org > >http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From goluptious at hotmail.com Mon Aug 9 15:29:02 2004 From: goluptious at hotmail.com (S Bobb) Date: Mon Aug 9 15:29:06 2004 Subject: [Tutor] Re: timer vs. timeout - struct.unpack Message-ID: Thanks for the help. I've placed the try/except just as you suggested. Now it's coming back with another error: Traceback (most recent call last): File "ipinstalludpclient3.py", line 50, in ? except socket.error, (errno, strerror): AttributeError: type object '_socketobject' has no attribute 'error' The script is still running through properly, it just isn't exiting without an exception. I've figured out another roundabout way to extract the MAC address now, so that I don't have to use dnet. Does anyone have any other suggestions for creating a UUID? I just read that commands is Unix-centric. I'd like to be able to use this script cross-platform. Sean >From: Kent Johnson >To: "goluptious" ,tutor@python.org >Subject: Re: [Tutor] Re: timer vs. timeout - struct.unpack >Date: Mon, 09 Aug 2004 08:29:30 -0400 > >Sean Bobb, > >It looks like maybe the socket module is throwing an exception when the >socket read times out. You can use a try / except block to catch the >exception and close the socket. For example, something like this: > >sock = ... # set up socket >try: > while 1: > messin = sock.recv(236) > # handle data from socket >except socket.error, (errno, strerror): > sock.close() > if errno != 11: > raise # unexpected error, don't hide it > >You may have to tweak this a bit, I am guessing at what is going on. > >Kent > >At 06:31 PM 8/9/2004 +0800, goluptious wrote: >>I figured out how to extract the data and and display it, but I still >>haven't managed to figure out a proper method to run my loop. >>Is there some way to use the Traceback to close the loop so that I can >>close >>the socket? >>Is a timer a better option? If so, should I use the threading timer or >>create my own using time? >> >>BTW, after a little more searching I found out that the commId was >>actually >>a UUID, so I modified the script to incorporate this also. >> >>If anyone has some advice as to how to do all these functions a little >>less >>crudely, or perhaps something that I will be able to port to other >>operating >>systems I would really appreciate it. (I've tried just copying over the >>dnet.so file from my Linux box to Windows, but it returns an error no >>module >>named dnet, I guess libdnet has to be compiled under Windows.) >> >>Thank you, >> >>Sean Bobb >> >> >>###--->BEGIN SCRIPT ---### >>#! /usr/bin/env python >> >>from socket import * >>from struct import * >>import re >>import dnet >>import commands >> >>def uuidgen(): >> return commands.getoutput('uuidgen') >> >>servid = '96c363be-b894-43b5-8501-ae5c00e779b3' >>resv = '\x00' >>commId = uuidgen() >>packSize = '\xec\x00' >>macAddr = '\xff\xff\xff\xff\xff\xff' >>ipAddr = '' >>netMask ='' >>gateWay = '' >>Dns1 = '' >>Dns2 = '' >>Dns3 = '' >>httpPort ='' >>messout = servid + (4 * resv) + commId + (4 * resv) + packSize + (2 * >>resv) >>+ macAddr + (146 * resv) >>rcvtime = pack('ll', 1l, 0l) >> >>sock = socket(AF_INET, SOCK_DGRAM) >>sock.setsockopt(SOL_SOCKET, SO_BROADCAST, 1) >>sock.setsockopt(SOL_SOCKET, SO_RCVTIMEO, rcvtime) >>sock.bind(('',58798)) >>sock.sendto(messout, ('', 58797)) >>while 1: >> messin = sock.recv(236) >> messunpack = unpack('236s', messin) >> spl = re.split('96c36.*?\\xec\\x00\\x00\\x02', messunpack[0]) >> spl1 = spl[1] >> macaddr = dnet.eth_ntoa(spl1[0:6]) >> ipaddr = inet_ntoa(spl1[8:12]) >> netmask = inet_ntoa(spl1[12:16]) >> gateway = inet_ntoa(spl1[16:20]) >> dns1 = inet_ntoa(spl1[20:24]) >> dns2 = inet_ntoa(spl1[24:28]) >> dns3 = inet_ntoa(spl1[28:32]) >> httpport = str(ord(spl1[32]) * 256 + ord(spl1[33])) >> print "MAC Address: " + macaddr + "\nIP Address: " + ipaddr + >>"\nNetmask: " >>+ netmask + "\nGateway: " + gateway + "\nDNS1: " + dns1 + "\nDNS2: " + >>dns2 >>+ "\nDNS3: " + dns3 + "\nHTTP Port: " + httpport + "\n\n" >>sock.close() >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor > _________________________________________________________________ STOP MORE SPAM with the new MSN 8 and get 2 months FREE* http://join.msn.com/?page=features/junkmail From kent_johnson at skillsoft.com Mon Aug 9 15:50:07 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Mon Aug 9 15:50:41 2004 Subject: [Tutor] Re: timer vs. timeout - struct.unpack In-Reply-To: References: Message-ID: <6.1.0.6.0.20040809094237.027ef770@mail4.skillsoft.com> Ah, you are importing socket with from socket import * so the except line should be just except error, (errno, strerror): What version of Python are you using? Python 2.3 has a settimeout() method on a socket and timeouts raise socket.timeout instead of socket.error. I have used this successfully with TCP sockets to time out an HTTP connection. Kent At 09:29 PM 8/9/2004 +0800, S Bobb wrote: >Thanks for the help. > >I've placed the try/except just as you suggested. Now it's coming back with >another error: > >Traceback (most recent call last): > File "ipinstalludpclient3.py", line 50, in ? > except socket.error, (errno, strerror): >AttributeError: type object '_socketobject' has no attribute 'error' > >The script is still running through properly, it just isn't exiting without >an exception. > >I've figured out another roundabout way to extract the MAC address now, so >that I don't have to use dnet. >Does anyone have any other suggestions for creating a UUID? I just read that >commands is Unix-centric. I'd like to be able to use this script >cross-platform. > >Sean > > > > >>From: Kent Johnson >>To: "goluptious" ,tutor@python.org >>Subject: Re: [Tutor] Re: timer vs. timeout - struct.unpack >>Date: Mon, 09 Aug 2004 08:29:30 -0400 >> >>Sean Bobb, >> >>It looks like maybe the socket module is throwing an exception when the >>socket read times out. You can use a try / except block to catch the >>exception and close the socket. For example, something like this: >> >>sock = ... # set up socket >>try: >> while 1: >> messin = sock.recv(236) >> # handle data from socket >>except socket.error, (errno, strerror): >> sock.close() >> if errno != 11: >> raise # unexpected error, don't hide it >> >>You may have to tweak this a bit, I am guessing at what is going on. >> >>Kent >> >>At 06:31 PM 8/9/2004 +0800, goluptious wrote: >>>I figured out how to extract the data and and display it, but I still >>>haven't managed to figure out a proper method to run my loop. >>>Is there some way to use the Traceback to close the loop so that I can close >>>the socket? >>>Is a timer a better option? If so, should I use the threading timer or >>>create my own using time? >>> >>>BTW, after a little more searching I found out that the commId was actually >>>a UUID, so I modified the script to incorporate this also. >>> >>>If anyone has some advice as to how to do all these functions a little less >>>crudely, or perhaps something that I will be able to port to other operating >>>systems I would really appreciate it. (I've tried just copying over the >>>dnet.so file from my Linux box to Windows, but it returns an error no module >>>named dnet, I guess libdnet has to be compiled under Windows.) >>> >>>Thank you, >>> >>>Sean Bobb >>> >>> >>>###--->BEGIN SCRIPT ---### >>>#! /usr/bin/env python >>> >>>from socket import * >>>from struct import * >>>import re >>>import dnet >>>import commands >>> >>>def uuidgen(): >>> return commands.getoutput('uuidgen') >>> >>>servid = '96c363be-b894-43b5-8501-ae5c00e779b3' >>>resv = '\x00' >>>commId = uuidgen() >>>packSize = '\xec\x00' >>>macAddr = '\xff\xff\xff\xff\xff\xff' >>>ipAddr = '' >>>netMask ='' >>>gateWay = '' >>>Dns1 = '' >>>Dns2 = '' >>>Dns3 = '' >>>httpPort ='' >>>messout = servid + (4 * resv) + commId + (4 * resv) + packSize + (2 * resv) >>>+ macAddr + (146 * resv) >>>rcvtime = pack('ll', 1l, 0l) >>> >>>sock = socket(AF_INET, SOCK_DGRAM) >>>sock.setsockopt(SOL_SOCKET, SO_BROADCAST, 1) >>>sock.setsockopt(SOL_SOCKET, SO_RCVTIMEO, rcvtime) >>>sock.bind(('',58798)) >>>sock.sendto(messout, ('', 58797)) >>>while 1: >>> messin = sock.recv(236) >>> messunpack = unpack('236s', messin) >>> spl = re.split('96c36.*?\\xec\\x00\\x00\\x02', messunpack[0]) >>> spl1 = spl[1] >>> macaddr = dnet.eth_ntoa(spl1[0:6]) >>> ipaddr = inet_ntoa(spl1[8:12]) >>> netmask = inet_ntoa(spl1[12:16]) >>> gateway = inet_ntoa(spl1[16:20]) >>> dns1 = inet_ntoa(spl1[20:24]) >>> dns2 = inet_ntoa(spl1[24:28]) >>> dns3 = inet_ntoa(spl1[28:32]) >>> httpport = str(ord(spl1[32]) * 256 + ord(spl1[33])) >>> print "MAC Address: " + macaddr + "\nIP Address: " + ipaddr + >>> "\nNetmask: " >>>+ netmask + "\nGateway: " + gateway + "\nDNS1: " + dns1 + "\nDNS2: " + dns2 >>>+ "\nDNS3: " + dns3 + "\nHTTP Port: " + httpport + "\n\n" >>>sock.close() >>>_______________________________________________ >>>Tutor maillist - Tutor@python.org >>>http://mail.python.org/mailman/listinfo/tutor > >_________________________________________________________________ >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 lennart at rogers.com Mon Aug 9 17:12:47 2004 From: lennart at rogers.com (Lennart Andersen) Date: Mon Aug 9 17:13:11 2004 Subject: [Tutor] Source code samples Message-ID: <20040809151247.GA2226@lnux2.lndn.phub.net.cable> Hey, I am new to python and programming so I would like to apologies for any stupid question..... Where can I get a really good book on how to read source code, I am in the process of reading "How to think like a computer scientist". Again, I am new at this..... Regards, -- Lennart Andersen The Newbie. From rdm at rcblue.com Mon Aug 9 18:08:36 2004 From: rdm at rcblue.com (Dick Moores) Date: Mon Aug 9 18:08:38 2004 Subject: [Tutor] Python cashes low integers? How? Where? In-Reply-To: <6.1.0.6.0.20040809081639.02a181e8@mail4.skillsoft.com> References: <6.1.2.0.2.20040808151623.023c6828@rcblue.com> <20040808231541.GL17831@i92.ryd.student.liu.se> <6.1.2.0.2.20040808233734.02315ec0@rcblue.com> <20040809075949.GN17831@i92.ryd.student.liu.se> <6.1.2.0.2.20040809010922.05060ec0@rcblue.com> <6.1.0.6.0.20040809081639.02a181e8@mail4.skillsoft.com> Message-ID: <6.1.2.0.2.20040809085528.0289fa00@rcblue.com> Kent Johnson wrote at 05:19 8/9/2004: >Since 3456 is not cached, you are calling getrefcount on a different >3456 than the one you assigned to a, b and c! > > >>> import sys > >>> a=b=c=3456 > >>> sys.getrefcount(3456) >2 > >>> sys.getrefcount(a) >4 > >>> del c > >>> sys.getrefcount(a) >3 So "qwerty" and "Dick" are cached, but 3456 is not? (Sorry to persist with this.) >>>import sys >>> a = b = c = "qwerty" >>> sys.getrefcount(c) 4 >>> sys.getrefcount("qwerty") 5 >>> sys.getrefcount("Dick") 2 >>> d = e = f = "Dick" >>> sys.getrefcount("Dick") 5 And why the high refcount here? (I restarted Python for this.) >>> import sys >>> g = h = i = 4 >>> sys.getrefcount(4) 93 Dick From dyoo at hkn.eecs.berkeley.edu Mon Aug 9 19:03:14 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Aug 9 19:03:18 2004 Subject: [Tutor] Source code samples In-Reply-To: <20040809151247.GA2226@lnux2.lndn.phub.net.cable> Message-ID: On Mon, 9 Aug 2004, Lennart Andersen wrote: > Hey, I am new to python and programming so I would like to apologies for > any stupid question..... Hi Lennart, Welcome aboard! Please feel free to ask your questions on Tutor; we're here to help. > Where can I get a really good book on how to read source code, I am in > the process of reading "How to think like a computer scientist". > > Again, I am new at this..... Hmmm... well, I can't think of one at the moment that's specific to Python, but the book "Code Reading" seems to be pretty good: http://www.spinellis.gr/codereading/ If you're looking for samples of code to look at, you may want to browse: The Vaults of Parnassus: http://www.vex.net/parnassus/ The Python Cookbook: http://aspn.activestate.com/ASPN/Python/Cookbook/ Useless Python: http://uselesspython.com/ Good luck to you! From dyoo at hkn.eecs.berkeley.edu Mon Aug 9 19:30:24 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Aug 9 19:30:27 2004 Subject: [Tutor] Python cashes low integers? How? Where? In-Reply-To: <6.1.2.0.2.20040809085528.0289fa00@rcblue.com> Message-ID: On Mon, 9 Aug 2004, Dick Moores wrote: > Kent Johnson wrote at 05:19 8/9/2004: > >Since 3456 is not cached, you are calling getrefcount on a different > >3456 than the one you assigned to a, b and c! > > > > >>> import sys > > >>> a=b=c=3456 > > >>> sys.getrefcount(3456) > >2 > > >>> sys.getrefcount(a) > >4 > > >>> del c > > >>> sys.getrefcount(a) > >3 > > So "qwerty" and "Dick" are cached, but 3456 is not? (Sorry to persist > with this.) Hi Dick, Not a problem, but just as a warning: all of these details are really not part of Python as a language, but more with its current C implementation. The implementors of Python added some efficiency tricks to the system, and some of these tricks are not duplicated in other implmentations of Python. We had a small discussion about this a few months ago: http://mail.python.org/pipermail/tutor/2004-May/029625.html It turns out that Python does try to internalize ("intern") small name-like strings in a cache. The rationale is that these names are likely to recur in a program, and so it's probably worthwhile to save them around, to avoid having to churn so many strings out. So yes, 'querty' and 'Dick', being name-like string literals, will get cached by CPython 2.3.3. But you should not really need to worry about this. *grin* It's possible that the caching strategy that the implementors choose might change; it's not set in stone that Python should do this kind of caching. > And why the high refcount here? (I restarted Python for this.) > >>> import sys > >>> g = h = i = 4 > >>> sys.getrefcount(4) > 93 Not sure about this one. It might depend on your runtime environment (like things in 'sitecustomize.py'). I get a much-reduced refcount for '4' from a clean startup on my interpreter, from a plain Unix xterm: ### [dyoo@shoebox idlelib]$ python Python 2.3.3 (#1, Aug 9 2004, 10:11:39) [GCC 3.3.3 20040412 (Gentoo Linux 3.3.3-r6, ssp-3.3.2-2, pie-8.7.6)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> g = h = i = 4 >>> import sys >>> sys.getrefcount(4) 16 >>> j = 4 >>> sys.getrefcount(4) 17 >>> del j >>> sys.getrefcount(4) 16 ### The dynamic nature of the runtime makes this hard to predict well. In fact, when we run from IDLE, then yes, the refcount goes up: ### From IDLE's interactive interpreter Python 2.3.3 (#1, Aug 9 2004, 10:11:39) [GCC 3.3.3 20040412 (Gentoo Linux 3.3.3-r6, ssp-3.3.2-2, pie-8.7.6)] on linux2 Type "copyright", "credits" or "license()" for more information. **************************************************************** Personal firewall software may warn about the connection IDLE makes to its subprocess using this computer's internal loopback interface. This connection is not visible on any external interface and no data is sent to or received from the Internet. **************************************************************** IDLE 1.0.2 >>> import sys >>> sys.getrefcount(4) 105 >>> ### and that's probably because '4' is used quite a bit by the IDLE internals. Remember, IDLE is running on Python, so it too may hold references to numeric constants. Anyway, hope this helps! From klas.martelleur at telia.com Mon Aug 9 19:54:35 2004 From: klas.martelleur at telia.com (Klas Marteleur) Date: Mon Aug 9 19:45:24 2004 Subject: [Tutor] In need for some advice Message-ID: <200408091954.35131.klas.martelleur@telia.com> Hi again I have just gone thrue Alan G's book and i think i am ready for some project of my own. I stumbled over a little file conversion project at work wich i thought could be a good start, and i need some help in the "right" direction. This is what i want to do: From our CAD system we get output files looking somewhat like file "output.txt" attached to this mail. It is possible to adjust the column witdh if nessesary from within the CAD (these values will be "locked" in the CAD when i found out what is best suited for my program.) It must understand "swedish" characters ?, ? ?. I want to convert the file to look like "inputToPDM.txt" attached to this mail, so i can import it to our PDM system (it only supports files formated like this one). It must understand "swedish" charakters ?, ?, ?. Then ofcourse i want a little GUI which takes a input (a filename) and a output (a filename) :) This is how i plan to do it: 1. Create a file named createEbomFromFile.py wich should take care of the actual work. The file should consist of a "class" "createEbomFromFile(self, inputFile, ouputFile). A couple of functions, one that reads the file to a list and splits it to correct portions (a word per list "item"), mayby some kind of filter function as well to remove unwanted characters, and one that prints the new formated list to a file that our PDM system understand. 2. Create a file named createEbomFromFileGui.py which imports createEbomFromFile and creates my slick Tkinter interface. How does this sound? Am i being to complicated? I want to design this program myself but i need some Startup tips. Anyone has a example that reminds of this that he/she could share with me? Klas -------------- next part -------------- Parent Name Parent Revision Child Name Child RevisionQuantityFind NumberReference Designator Remark Usage WP PRP 03003365 AB 03003240 AC 1 10 - - - 03003365 AB 03003358 AA 2 9 Mtrl. spec.: 56-3239-47 YES - 03003365 AB 03003359 AB 8 8 - - YES 03003365 AB 03003360 AB 1 7 - YES YES 03003365 AB 03003361 AA 2 6 - - - 03003365 AB 03003362 AB 1 5 - YES YES 03003365 AB 03003363 AB 1 4 - YES YES 03003365 AB 03003364 AB 1 3 - YES YES 03003365 AB 59-0763-00 1 16 2 DIN 934 - - 03003365 AB 59-0781-00 1 16 1 - - - -------------- next part -------------- Parent Name;Parent Revision;Child Name;Child Revision;Quantity;Find Number;Reference Designator;Remark;Usage;WP;PRP 03002094;AA;03002062;AA;1;10;10;-;;-;- 03002094;AA;03002093;AA;2;20;9;Mtrl. spec.: 56-3239-47;;YES;- 03002094;AA;03002086;AA;8;30;8;-;;-;YES 03002094;AA;03002090;AA;1;40;7;-;;YES;YES 03002094;AA;03002091;AA;2;50;6;-;;-;- 03002094;AA;03002089;AA;1;60;5;-;;YES;YES 03002094;AA;03002087;AA;1;70;4;-;;YES;YES 03002094;AA;03002088;AA;1;80;3;-;;YES;YES 03002094;AA;03002092;AA;16;90;2;DIN 934;;-;- 03002094;AA;03002085;AA;16;100;1;-;;-;- From dyoo at hkn.eecs.berkeley.edu Mon Aug 9 19:43:09 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Aug 9 19:50:59 2004 Subject: [Tutor] Is there a Python interface to ZeroC's Ice yet? In-Reply-To: <1121128603265.20040805211812@columbus.rr.com> Message-ID: On Thu, 5 Aug 2004, R. Alan Monroe wrote: > Google mostly came up with generic corba-oriented sites. Is anyone > working on a Python specific module for it? Hi Alan, You may want to ask on the comp.lang.python newsgroup about this one; I'm not sure many of us have played with Ice yet. From looking at: http://www.zeroc.com/ice.html There appear to be hooks to C++, Java, C#, and PHP, but no mention of Python yet. Folks on comp.lang.python may have more knowledge about it, though. Good luck! From rdm at rcblue.com Mon Aug 9 19:51:39 2004 From: rdm at rcblue.com (Dick Moores) Date: Mon Aug 9 19:51:42 2004 Subject: [Tutor] Python cashes low integers? How? Where? In-Reply-To: References: <6.1.2.0.2.20040809085528.0289fa00@rcblue.com> Message-ID: <6.1.2.0.2.20040809103806.047f7b80@rcblue.com> Danny Yoo wrote at 10:30 8/9/2004: >The implementors of Python added some efficiency tricks to the system, and >some of these tricks are not duplicated in other implmentations of Python. >We had a small discussion about this a few months ago: > > http://mail.python.org/pipermail/tutor/2004-May/029625.html > >It turns out that Python does try to internalize ("intern") small >name-like strings in a cache. The rationale is that these names are >likely to recur in a program, and so it's probably worthwhile to save them >around, to avoid having to churn so many strings out. > >So yes, 'querty' and 'Dick', being name-like string literals, will get >cached by CPython 2.3.3. But you should not really need to worry about >this. *grin* It's possible that the caching strategy that the >implementors choose might change; it's not set in stone that Python should >do this kind of caching. Thanks very much, Danny. My curiosity about this has been satisfied for the time being, and I can return to more practical matters in my study of Python. Dick From dyoo at hkn.eecs.berkeley.edu Mon Aug 9 20:01:13 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Aug 9 20:01:16 2004 Subject: [Tutor] Checking to see whether or not a filesystem is mounted--? In-Reply-To: <4114D685.40002@att.net> Message-ID: On Sat, 7 Aug 2004, Marv Boyes wrote: > Hello, all. Having a great time here-- this list is an excellent > complement to my newbie reading on Python. I never imagined that a > robust, full-featured programming language would be so easy and > enjoyable to learn. > > Anyway, enough preamble. I'm wanting to write a small graphical applet > for mounting and unmounting filesystems with a button-press. Can anyone > suggest a method for testing whether or not a particular filesystem is > mounted (so I can inform the user with a message dialog)? Hi Marv, David McClosky wrote a library for detecting mount points: http://bebop.bigasterisk.com/python/docs/MtPython http://bebop.bigasterisk.com/python/MtPython-1.0.tar.gz and there appear to be a 'mounted_only' option that you can check to see if something is really mounted already. Good luck! From alan.gauld at blueyonder.co.uk Mon Aug 9 20:43:01 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Mon Aug 9 21:11:35 2004 Subject: [Tutor] Begginer in need of help References: Message-ID: <01b801c47e42$66c40440$6401a8c0@xp> s = 0 a = 1 name = "dan" while a < 4: # You need to increment a each time through the loop # so that eventually it equals 4! my_name = raw_input("what is my name? ") if my_name == "julian": print "correct" a = 10 elif s < 3: s = s + a print "Nope, you have, ",3-s," tries left" _________________________________________________________________ FREE pop-up blocking with the new MSN Toolbar ? get it now! http://toolbar.msn.click-url.com/go/onm00200415ave/direct/01/ From kent_johnson at skillsoft.com Mon Aug 9 21:32:11 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Mon Aug 9 21:32:22 2004 Subject: [Tutor] In need for some advice In-Reply-To: <200408091954.35131.klas.martelleur@telia.com> References: <200408091954.35131.klas.martelleur@telia.com> Message-ID: <6.1.0.6.0.20040809143209.0298fdb0@mail4.skillsoft.com> Klas, This looks like a good starting project and a good plan. I'm not sure you need a createEbomFromFile class, a procedural module will probably work fine for this. It might have four functions in it: def readInput(inputPath) # Reads the input file and creates a list of values (probably a list of lists, with one list for each line of the input file) def filterInput(inputList) # Any necessary processing of the list def writeList(outputPath) # Write the list to the output file def processFiles(inputPath, outputPath) # Just calls the above three functions to do the whole job Of course you should change the names of the functions and arguments to whatever makes the most sense to you. I would develop this program incrementally, taking very small steps. You could start with a simple readInput that reads a file and returns its lines. Write a main program that calls readInput and prints the result. So it might look something like this: def readInput(inputPath): # code to read the file into a list of lines return inputList if __name__ == '__main__': inputList = readInput('path/to/sample/file.txt') for line in inputList: print line Now you can refine readInput until it gives you what you really want. Next work on filterInput if you need it, or maybe this is part of readInput Finally write writeList() and processFiles. At this point you will have a complete program that reads and processes an input file and creates an output file. You may want to write a better main program that allows you to pass the input and output paths on the command line, or maybe at this point you will start on the Tk GUI. The GUI will allow you to specify the input file and output file, then it just calls processFiles() with the two paths. Kent At 07:54 PM 8/9/2004 +0200, Klas Marteleur wrote: >Hi again > >I have just gone thrue Alan G's book and i think i am ready for some project >of my own. I stumbled over a little file conversion project at work wich i >thought could be a good start, and i need some help in the "right" direction. > >This is what i want to do: > From our CAD system we get output files looking somewhat like file >"output.txt" attached to this mail. It is possible to adjust the column witdh >if nessesary from within the CAD (these values will be "locked" in the CAD >when i found out what is best suited for my program.) It must understand >"swedish" characters ?, ? ?. > >I want to convert the file to look like "inputToPDM.txt" attached to this >mail, so i can import it to our PDM system (it only supports files formated >like this one). It must understand "swedish" charakters ?, ?, ?. > >Then ofcourse i want a little GUI which takes a input (a filename) and a >output (a filename) :) > >This is how i plan to do it: >1. Create a file named createEbomFromFile.py wich should take care of the >actual work. The file should consist of a "class" "createEbomFromFile(self, >inputFile, ouputFile). A couple of functions, one that reads the file to a >list and splits it to correct portions (a word per list "item"), mayby some >kind of filter function as well to remove unwanted characters, and one that >prints the new formated list to a file that our PDM system understand. > >2. Create a file named createEbomFromFileGui.py which imports >createEbomFromFile and creates my slick Tkinter interface. > > >How does this sound? Am i being to complicated? I want to design this program >myself but i need some Startup tips. Anyone has a example that reminds of >this that he/she could share with me? > >Klas > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From alan.gauld at blueyonder.co.uk Mon Aug 9 23:28:47 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Mon Aug 9 23:28:09 2004 Subject: [Tutor] Source code samples References: <20040809151247.GA2226@lnux2.lndn.phub.net.cable> Message-ID: <01cb01c47e57$db81d4f0$6401a8c0@xp> > Where can I get a really good book on how to read source code, I am in the > process of reading "How to think like a computer scientist". I assume from what you've written that you want something extra? "How to Think..." is a pretty good introduction to reading (and writing!) source code. There are several others around (including mine) but without a clearer idea of what you feel is lacking in "How to Think..." its hard to recommend anything specific. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/ From alan.gauld at blueyonder.co.uk Mon Aug 9 23:43:46 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Mon Aug 9 23:43:08 2004 Subject: [Tutor] In need for some advice References: <200408091954.35131.klas.martelleur@telia.com> Message-ID: <01dc01c47e59$f3116890$6401a8c0@xp> > This is what i want to do: > From our CAD system we get output files looking somewhat like file > "output.txt" attached to this mail. ... > I want to convert the file to look like "inputToPDM.txt" ...so > i can import it to our PDM system Sounds like a very good first project. Not too hard but enough to test out your understanding and give opportunity for discovering a few new tricks too. > Then ofcourse i want a little GUI which takes a input (a filename) > and a output (a filename) :) OK, 3 frames maybe. The top two each with a label and Entry widget and the bottom with a couple of buttons? > This is how i plan to do it: > 1. Create a file named createEbomFromFile.py ... > consist of a "class" "createEbomFromFile(self, inputFile, ouputFile). That looks more like a function. Remember objects should be things, so named as nouns not verbs... How about a PDMfile class with a method read(someFile) where someFile is in the format you specified. Or you could go the other way and have a Class for your input file and give it a method producePDM(PDMfile) Or maybe a combination of the two? How to choose? Recall that ojects have responsibilities and are masters of their own data. So think where the data lies and put the processing methods there. > 2. Create a file named createEbomFromFileGui.py which imports > createEbomFromFile and creates my slick Tkinter interface. Separation of data and presentation, well done. Thats always a good idea. > How does this sound? Am i being too complicated? No, it's a good way forward. Don't forget to play with the >>> prompt to try out your ideas before committing them to a file. And remember there is never an absolute right or wrong design. > I want to design this program myself but i need some Startup tips. Hopefully the above ideas are enough to set you going. Something else you might like to try is to think about how you will test the program. Again the >>> prompt will be your friend. But thinking about all the different ways you could break the code is a good way to prevent it breaking! :-) Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/ From bilange at gamebox.net Tue Aug 10 01:30:34 2004 From: bilange at gamebox.net (Eric Belanger) Date: Tue Aug 10 01:30:37 2004 Subject: [Tutor] Linear programming - is it bad? Message-ID: <4118091A.9000400@gamebox.net> Hi! This is my first post here (ive been reading this list for a few weeks, interesting content!). So my question: is it bad to write a python program/script in a linear way? By linear, I mean: the code is executed line by line, without any (programmer defined) classes or functions, a bit like [Q]BASIC without GOTO's, or , while we're at it, HTML. I could also compare it to Doom 3: going from A to B, then C, without any choices or options, until Z. I assume that by writing huge projects/programs, im assured programmers *needs* to use functions and classes. But since Im beginning, I dont see the point. For example, I made a small program that modify a few registry strings to be able to login automaticly in Windows NT/2000/XP (Registry trick explained at: http://www.winguides.com/registry/display.php/13/ ), asking the user his login name and password. In this case, I didnt stored a part of my own code into functions/classes. (For the console version of it, that is. Using wxPython, guess I didnt have the choice ;) I dont know what to add, except asking whats your opinion about this topic. Last thing - I would add my source code of that program i was talking about, but I dont know if you guys do like to have attachments in messages from mailing list. If you'd like to see the source code, heres a link to it. (Hope my old pentium who hosts the file will survive the slashdot effect ;) http://home.bilange.ca/files/index.php?dir=&file=AutoLogC.py Thanks! Eric Belanger - bilange A gamebox _ net From amonroe at columbus.rr.com Tue Aug 10 01:50:17 2004 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Tue Aug 10 01:50:26 2004 Subject: [Tutor] Linear programming - is it bad? In-Reply-To: <4118091A.9000400@gamebox.net> References: <4118091A.9000400@gamebox.net> Message-ID: <192210219539.20040809195017@columbus.rr.com> > So my question: is it bad to write a python program/script in a linear > way? By linear, I mean: the code is executed line by line, without any > (programmer defined) classes or functions In my opinion, linear is perfect for a lot of things. Classes are overkill if you're not managing a number of similar objects. Functions are still pretty necessary if you have repeating tasks of any kind, though. Alan From dyoo at hkn.eecs.berkeley.edu Tue Aug 10 02:03:24 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Aug 10 02:03:30 2004 Subject: [Tutor] Linear programming - is it bad? In-Reply-To: <4118091A.9000400@gamebox.net> Message-ID: On Mon, 9 Aug 2004, Eric Belanger wrote: > So my question: is it bad to write a python program/script in a linear > way? By linear, I mean: the code is executed line by line, without any > (programmer defined) classes or functions, a bit like [Q]BASIC without > GOTO's, or , while we're at it, HTML. Hi Eric, Truthfully? It's really painful for me to debug straight-line code that goes on for several pages. It rambles on and on, and the letters just start swimming in my head because I have a puny brain. I don't usually say that out loud, but you did ask if long code was bad. *grin* As far as the computer is concerned, it's fine with code as long as it's syntactically correct. But boxing related code into functions does help other people read the code. Using functions is really more for people than for Python. There are some places where writing a function is technically necessary, but usually, it's more in consideration for human readers. > I assume that by writing huge projects/programs, im assured programmers > *needs* to use functions and classes. But since Im beginning, I dont see > the point. They can help clean up some code. I hate talking in abstractions though. *grin* Let me take a look at a portion of the 'AutoLogC.py' code you put up, and see if we can show how functions can help. Thanks for sharing your code, by the way! Ok, here's a good block we can talk about: ### #For each strings, check if it exists (if not, create without any value) #otherwise, gather its current value for displaying later. try: data = QueryValueEx(reg,"DefaultUserName") regusername = data[0] except WindowsError: print "Error: DefaultUserName string missing from registry: creating an empty string." nothing = SetValueEx(reg,"DefaultUserName",0,REG_SZ,"") regusername = "" try: data = QueryValueEx(reg,"DefaultPassword") regpassword = data[0] except WindowsError: print "Error: DefaultPassword string missing from registry: creating an empty string." nothing = SetValueEx(reg,"DefaultPassword",0,REG_SZ,"") regpassword = "" try: data = QueryValueEx(reg,"DefaultDomainName") regdomain = data[0] except WindowsError: print "Error: DefaultDomainName string missing from registry: creating an empty string." nothing = SetValueEx(reg,"DefaultDomainName",0,REG_SZ,"") regdomain = "" try: data = QueryValueEx(reg,"AutoAdminLogon") regautolog = data[0] except WindowsError: print "Error: AutoAdminLogon string missing from registry: creating an empty string." nothing = SetValueEx(reg,"AutoAdminLogon",0,REG_SZ,"0") regautolog = "0" ### There are four similar-looking blocks here that try to lookup registry keys for : DefaultUserName DefaultPassword DefaultDomainName AutoAdminLogon We can capture the thing that's pretty constant within all those blocks as a function. Something like: ### def queryForValue(reg, name): try: values = QueryValueEx(reg, name) return values[0] except WindowsError: print "Error:", name, "string missing from registry:", print "creating an empty string." nothing = SetValueEx(reg,name,0,REG_SZ,"0") return "0" ### that we can then use this user-defined queryForValue() function to do the registry lookup for us and handle the ugliness of WindowsError exceptions: ### regusername = queryForValue(reg, "DefaultUserName") regusername = queryForValue(reg, "DefaultUserName") regpassword = queryForValue(reg, "DefaultPassword") regdomain = queryForValue(reg, "DefaultDomainName") regautolog = queryForValue(reg, "AutoAdminLogon") ### We don't gain much in terms of the capability of the program: this does everything that the previous code did before. What we do win, though, is a lot of brevity, and brief is good. *grin* I hope this was a compelling example of why programmers use functions. Good luck! From goluptious at hotmail.com Tue Aug 10 02:08:29 2004 From: goluptious at hotmail.com (goluptious) Date: Tue Aug 10 02:08:34 2004 Subject: [Tutor] Re: timer vs. timeout - struct.unpack References: Message-ID: Beautiful! It's exiting without an error. Thank you. BTW, the script now runs in Windows if I drop in a UUID generated in Linux. I still haven't found a good cross-platform UUID generator. Sean ###--->BEGIN SCRIPT----#### #! /usr/bin/env python from socket import * from struct import * from binascii import * import re import commands def uuidgen(): return commands.getoutput('uuidgen') servid = '96c363be-b894-43b5-8501-ae5c00e779b3' resv = '\x00' commId = uuidgen() packSize = '\xec\x00' macAddr = '\xff\xff\xff\xff\xff\xff' ipAddr = '' netMask ='' gateWay = '' Dns1 = '' Dns2 = '' Dns3 = '' httpPort ='' messout = servid + (4 * resv) + commId + (4 * resv) + packSize + (2 * resv) + macAddr + (146 * resv) rcvtime = pack('ll', 2l, 0l) f = open("/root/scripts/foo", "w+") sock = socket(AF_INET, SOCK_DGRAM) sock.setsockopt(SOL_SOCKET, SO_BROADCAST, 1) sock.settimeout(2) sock.bind(('',58798)) sock.sendto(messout, ('', 58797)) try: while 1: messin = sock.recv(236) messunpack = unpack('236s', messin) spl = re.split('96c36.*?\\xec\\x00\\x00\\x02', messunpack[0]) spl1 = spl[1] macaddr = b2a_hex(spl1[0]) + ":" + b2a_hex(spl1[1]) + ":" + b2a_hex(spl1[2]) + ":" + b2a_hex(spl1[3]) + ":" + b2a_hex(spl1[4]) + ":" + b2a_hex(spl1[5]) ipaddr = inet_ntoa(spl1[8:12]) netmask = inet_ntoa(spl1[12:16]) gateway = inet_ntoa(spl1[16:20]) dns1 = inet_ntoa(spl1[20:24]) dns2 = inet_ntoa(spl1[24:28]) dns3 = inet_ntoa(spl1[28:32]) httpport = str(ord(spl1[32]) * 256 + ord(spl1[33])) f.write("MAC Address: " + macaddr + "\nIP Address: " + ipaddr + "\nNetmask: " + netmask + "\nGateway: " + gateway + "\nDNS1: " + dns1 + "\nDNS2: " + dns2 + "\nDNS3: " + dns3 + "\nHTTP Port: " + httpport + "\n\n") print "MAC Address: " + macaddr + "\nIP Address: " + ipaddr + "\nNetmask: " + netmask + "\nGateway: " + gateway + "\nDNS1: " + dns1 + "\nDNS2: " + dns2 + "\nDNS3: " + dns3 + "\nHTTP Port: " + httpport + "\n\n" except timeout: sock.close() ----- Original Message ----- From: Kent Johnson To: "goluptious" ,tutor@python.org Subject: Re: [Tutor] Re: timer vs. timeout - struct.unpack Date: Mon, 09 Aug 2004 08:29:30 -0400 Ah, you are importing socket with from socket import * so the except line should be just except error, (errno, strerror): What version of Python are you using? Python 2.3 has a settimeout() method on a socket and timeouts raise socket.timeout instead of socket.error. I have used this successfully with TCP sockets to time out an HTTP connection. Kent ----- Original Message ----- From: "S Bobb" To: Sent: Monday, August 09, 2004 21:29 Subject: Re: [Tutor] Re: timer vs. timeout - struct.unpack Thanks for the help. I've placed the try/except just as you suggested. Now it's coming back with another error: Traceback (most recent call last): File "ipinstalludpclient3.py", line 50, in ? except socket.error, (errno, strerror): AttributeError: type object '_socketobject' has no attribute 'error' The script is still running through properly, it just isn't exiting without an exception. I've figured out another roundabout way to extract the MAC address now, so that I don't have to use dnet. Does anyone have any other suggestions for creating a UUID? I just read that commands is Unix-centric. I'd like to be able to use this script cross-platform. Sean >From: Kent Johnson >To: "goluptious" ,tutor@python.org >Subject: Re: [Tutor] Re: timer vs. timeout - struct.unpack >Date: Mon, 09 Aug 2004 08:29:30 -0400 > >Sean Bobb, > >It looks like maybe the socket module is throwing an exception when the >socket read times out. You can use a try / except block to catch the >exception and close the socket. For example, something like this: > >sock = ... # set up socket >try: > while 1: > messin = sock.recv(236) > # handle data from socket >except socket.error, (errno, strerror): > sock.close() > if errno != 11: > raise # unexpected error, don't hide it > >You may have to tweak this a bit, I am guessing at what is going on. > >Kent > >At 06:31 PM 8/9/2004 +0800, goluptious wrote: >>I figured out how to extract the data and and display it, but I still >>haven't managed to figure out a proper method to run my loop. >>Is there some way to use the Traceback to close the loop so that I can >>close >>the socket? >>Is a timer a better option? If so, should I use the threading timer or >>create my own using time? >> >>BTW, after a little more searching I found out that the commId was >>actually >>a UUID, so I modified the script to incorporate this also. >> >>If anyone has some advice as to how to do all these functions a little >>less >>crudely, or perhaps something that I will be able to port to other >>operating >>systems I would really appreciate it. (I've tried just copying over the >>dnet.so file from my Linux box to Windows, but it returns an error no >>module >>named dnet, I guess libdnet has to be compiled under Windows.) >> >>Thank you, >> >>Sean Bobb >> >> >>###--->BEGIN SCRIPT ---### >>#! /usr/bin/env python >> >>from socket import * >>from struct import * >>import re >>import dnet >>import commands >> >>def uuidgen(): >> return commands.getoutput('uuidgen') >> >>servid = '96c363be-b894-43b5-8501-ae5c00e779b3' >>resv = '\x00' >>commId = uuidgen() >>packSize = '\xec\x00' >>macAddr = '\xff\xff\xff\xff\xff\xff' >>ipAddr = '' >>netMask ='' >>gateWay = '' >>Dns1 = '' >>Dns2 = '' >>Dns3 = '' >>httpPort ='' >>messout = servid + (4 * resv) + commId + (4 * resv) + packSize + (2 * >>resv) >>+ macAddr + (146 * resv) >>rcvtime = pack('ll', 1l, 0l) >> >>sock = socket(AF_INET, SOCK_DGRAM) >>sock.setsockopt(SOL_SOCKET, SO_BROADCAST, 1) >>sock.setsockopt(SOL_SOCKET, SO_RCVTIMEO, rcvtime) >>sock.bind(('',58798)) >>sock.sendto(messout, ('', 58797)) >>while 1: >> messin = sock.recv(236) >> messunpack = unpack('236s', messin) >> spl = re.split('96c36.*?\\xec\\x00\\x00\\x02', messunpack[0]) >> spl1 = spl[1] >> macaddr = dnet.eth_ntoa(spl1[0:6]) >> ipaddr = inet_ntoa(spl1[8:12]) >> netmask = inet_ntoa(spl1[12:16]) >> gateway = inet_ntoa(spl1[16:20]) >> dns1 = inet_ntoa(spl1[20:24]) >> dns2 = inet_ntoa(spl1[24:28]) >> dns3 = inet_ntoa(spl1[28:32]) >> httpport = str(ord(spl1[32]) * 256 + ord(spl1[33])) >> print "MAC Address: " + macaddr + "\nIP Address: " + ipaddr + >>"\nNetmask: " >>+ netmask + "\nGateway: " + gateway + "\nDNS1: " + dns1 + "\nDNS2: " + >>dns2 >>+ "\nDNS3: " + dns3 + "\nHTTP Port: " + httpport + "\n\n" >>sock.close() >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor > _________________________________________________________________ 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 r2b2 at myway.com Tue Aug 10 02:21:32 2004 From: r2b2 at myway.com (r2b2) Date: Tue Aug 10 02:21:38 2004 Subject: [Tutor] text file Message-ID: <20040810002132.082B23962@mprdmxin.myway.com> I want to open a text file and change the text size and save. is this possible? _______________________________________________ No banners. No pop-ups. No kidding. Make My Way your home on the Web - http://www.myway.com From dyoo at hkn.eecs.berkeley.edu Tue Aug 10 02:22:21 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Aug 10 02:22:26 2004 Subject: [Tutor] Linear programming - is it bad? In-Reply-To: Message-ID: > We can capture the thing that's pretty constant within all those blocks as > a function. Something like: > > ### > def queryForValue(reg, name): > try: > values = QueryValueEx(reg, name) > return values[0] > except WindowsError: > print "Error:", name, "string missing from registry:", > print "creating an empty string." > nothing = SetValueEx(reg,name,0,REG_SZ,"0") > return "0" > ### Hi Eric, Ack! I didn't see that the default values for all but the AutoAdminLogon were the empty string, and not zero. Let me fix this. ### def queryForValue(reg, name, defaultValue=""): try: values = QueryValueEx(reg, name) return values[0] except WindowsError: print "Error:", name, "string missing from registry:", print "creating default value:", defaultValue nothing = SetValueEx(reg, name, 0, REG_SZ, defaultValue) return "0" regusername = queryForValue(reg, "DefaultUserName") regusername = queryForValue(reg, "DefaultUserName") regpassword = queryForValue(reg, "DefaultPassword") regdomain = queryForValue(reg, "DefaultDomainName") regautolog = queryForValue(reg, "AutoAdminLogon", "0") ### Sorry for goofing up like that; I should have paid closer attention to your code. From dyoo at hkn.eecs.berkeley.edu Tue Aug 10 02:35:07 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Aug 10 02:35:10 2004 Subject: [Tutor] Re: timer vs. timeout - struct.unpack In-Reply-To: Message-ID: On Tue, 10 Aug 2004, goluptious wrote: > BTW, the script now runs in Windows if I drop in a UUID generated in > Linux. I still haven't found a good cross-platform UUID generator. Hi Goluptious, There's a quick and dirty UUID generator in the Python Cookbook: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/213761 That snippet does not generate ISO-11578-standard UUID's, but it should still be useful. There's also a a nice blog article that talks about UUID issues here: http://blog.voiceofhumanity.net/newslog2.php/_v252/__show_article/_a000252-000040.htm From goluptious at hotmail.com Tue Aug 10 04:15:35 2004 From: goluptious at hotmail.com (goluptious) Date: Tue Aug 10 04:15:39 2004 Subject: [Tutor] Re: timer vs. timeout - struct.unpack References: Message-ID: Thank you. I found that link before, and, actually, that is where I got the idea to use commands.getouput('uuidgen') (see the comments at that URL), since I don't know if I need to use standard UUIDs. Doing some more searching I found pythoncom.CreateGuid, which I am now using on Windows. Now I need to start working on the next part of the project: setting the network configuration for the devices. Thanks again. Sean ###--->BEGIN SCRIPT ---### #! /usr/bin/env python from socket import * from struct import * from binascii import * import re import sys import tempfile if sys.platform == 'win32': import pythoncom commId = re.split('}', re.split('{', str(pythoncom.CreateGuid()))[1])[0] f = open(tempfile.gettempdir() + "/ipinstaller-tmp", "w+") else: import commands def uuidgen(): return commands.getoutput('uuidgen') commId = uuidgen() f = open(tempfile.gettempdir() + "/.ipinstaller-tmp", "w+") servid = '96c363be-b894-43b5-8501-ae5c00e779b3' resv = '\x00' packSize = '\xec\x00' macAddr = '\xff\xff\xff\xff\xff\xff' ipAddr = '' netMask ='' gateWay = '' Dns1 = '' Dns2 = '' Dns3 = '' httpPort ='' messout = servid + (4 * resv) + commId + (4 * resv) + packSize + (2 * resv) + macAddr + (146 * resv) rcvtime = pack('ll', 2l, 0l) sock = socket(AF_INET, SOCK_DGRAM) sock.setsockopt(SOL_SOCKET, SO_BROADCAST, 1) sock.setsockopt(SOL_SOCKET, SO_RCVTIMEO, rcvtime) sock.settimeout(2) sock.bind(('',58798)) sock.sendto(messout, ('255.255.255.255', 58797)) try: while 1: messin = sock.recv(256) messunpack = unpack('256s', messin) spl = re.split('96c36.*?\\xec\\x00\\x00\\x02', messunpack[0]) spl1 = spl[1] macaddr = b2a_hex(spl1[0]) + ":" + b2a_hex(spl1[1]) + ":" + b2a_hex(spl1[2]) + ":" + b2a_hex(spl1[3]) + ":" + b2a_hex(spl1[4]) + ":" + b2a_hex(spl1[5]) ipaddr = inet_ntoa(spl1[8:12]) netmask = inet_ntoa(spl1[12:16]) gateway = inet_ntoa(spl1[16:20]) dns1 = inet_ntoa(spl1[20:24]) dns2 = inet_ntoa(spl1[24:28]) dns3 = inet_ntoa(spl1[28:32]) httpport = str(ord(spl1[32]) * 256 + ord(spl1[33])) f.write("MAC Address: " + macaddr + "\nIP Address: " + ipaddr + "\nNetmask: " + netmask + "\nGateway: " + gateway + "\nDNS1: " + dns1 + "\nDNS2: " + dns2 + "\nDNS3: " + dns3 + "\nHTTP Port: " + httpport + "\n\n") print "MAC Address: " + macaddr + "\nIP Address: " + ipaddr + "\nNetmask: " + netmask + "\nGateway: " + gateway + "\nDNS1: " + dns1 + "\nDNS2: " + dns2 + "\nDNS3: " + dns3 + "\nHTTP Port: " + httpport + "\n\n" except timeout: sock.close() ----- Original Message ----- From: "Danny Yoo" To: "goluptious" Cc: Sent: Tuesday, August 10, 2004 08:35 Subject: Re: [Tutor] Re: timer vs. timeout - struct.unpack On Tue, 10 Aug 2004, goluptious wrote: > BTW, the script now runs in Windows if I drop in a UUID generated in > Linux. I still haven't found a good cross-platform UUID generator. Hi Goluptious, There's a quick and dirty UUID generator in the Python Cookbook: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/213761 That snippet does not generate ISO-11578-standard UUID's, but it should still be useful. There's also a a nice blog article that talks about UUID issues here: http://blog.voiceofhumanity.net/newslog2.php/_v252/__show_article/_a000252-000040.htm From bvande at po-box.mcgill.ca Tue Aug 10 05:48:57 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Tue Aug 10 05:49:20 2004 Subject: [Tutor] Linear programming - is it bad? In-Reply-To: <4118091A.9000400@gamebox.net> References: <4118091A.9000400@gamebox.net> Message-ID: <411845A9.3000301@po-box.mcgill.ca> Eric Belanger said unto the world upon 2004-08-09 19:30: > Hi! > > This is my first post here (ive been reading this list for a few weeks, > interesting content!). > > So my question: is it bad to write a python program/script in a linear > way? By linear, I mean: the code is executed line by line, without any > (programmer defined) classes or functions, a bit like [Q]BASIC without > GOTO's, or , while we're at it, HTML. I could also compare it to Doom 3: > going from A to B, then C, without any choices or options, until Z. > > I assume that by writing huge projects/programs, im assured programmers > *needs* to use functions and classes. But since Im beginning, I dont see > the point. > > > Thanks! > > Eric Belanger - bilange A gamebox _ net Hi Eric, I didn't take a look at the code you linked to (in the snipp'ed part), and I'm a relative programming newbie, so read what I say with your skeptic's goggles on ;-) (Also, having come to the end of writing this email, it seems I am in verbose-mode today. Oops.) That said, so far in my own programming efforts, I've noticed two benefits of functions that I wouldn't want to live without: 1) Program logic that you use time and time again can be wrapped into a function, and them imported from a module into new code that you create. As a simple example, in several of my first programs, I found myself opening a file, calling readlines on it, and then closing the file. Typing that each time seems silly (and typo-prone). So, without claim that its the prettiest such function in the world, I put the following into a module I called fileutils.py: def reader(full_file_path): '''reader(full_file_path) -> file_contents (as a list) Given a full file path (or a file name in the current working directory), reader() uses the readlines() method of file objects to read the lines into a list, closes the file, and then returns the list.''' the_file_to_read = open(full_file_path, 'r') file_contents = the_file_to_read.readlines() the_file_to_read.close() return file_contents Now, instead of retyping of copying and pasting, I can say from fileutils import reader as reader and then invoke the function as though I'd defined it in whatever program or interactive session I am in. Hassle-free, less to type, and the debugging was done once and for all. (This function could certainly be improved (for instance, it could take an optional mode argument to allow for binary files, and I guess the call-tip part of the docstring really shouldn't imply a complete file path is needed), but since it is pretty much what I was typing each time, it saves me time and effort as is.) 2) Danny's point about functions being for helping humans read is very important. Write a 10-line function, debug it, and understand what it does. Then, when your code uses it, if you are trying to work out why exactly your program is doing some unexpected thing, instead of conceptually stepping through all 10 lines, you can read the one line with the function call as an extended Python command that does exactly what you created it to do. In effect, it packs trusted code logic into a single line. It's *much* easier to conceptualize your code that way. Of course both points (1) and (2) depend upon a thorough test and debug of your function. And, it will surely happen that at some point, while enjoying benefit (2), you will be unable to see why your program is doing some unexpected thing. Eventually (and probably at 3am while feeling on the verge of going completely bonkers), you will be driven to examine some function very carefully only to discover that you were a bit too quick to decide that the function def did indeed do exactly what you wanted. That can make debugging more difficult, but get a trust-worthy, reusable function and you never have to debug that bit again. (A few such 3am experiences will certainly teach you to push the boundaries of a function in every which way while testing it *before* you decide to start importing it into other programs.) Note too that you can get some, but not all, of the benefit of (1) by writing code in a linear manner. If you do it fresh each time, every time is a new chance to make an error. You might think to get around that by copying and pasting from the original source. Doing that, you can be reasonably sure there are no bugs in the lines you paste. What you cannot be so sure of is that there are no bugs caused by the interaction of the pasted code and the code it is pasted into. (You must be much more skeptical that the code does exactly what it is supposed to do in the new context than you need be of well-tested functions that you import.) Take, for example, my reader example from above. If I did it in a linear manner, I'd run the risk that I might put those lines right into the middle of a program where file_contents (say) already had a meaning. The names in the pasted code and the pasted-to code might clash, creating possibly nasty bugs. Functions avoid that; even if I copy and paste by reader's def block into a new program context, the name file_contents isn't top-level. Instead, it's a name in the function's namespace; if I have a file_contents variable in my top-level code the two can live in peace and harmony, never stepping upon each other's toes since each has its own namespace. (Trying to get the same thing by pasting and then manually checking for name-clashes has two problems: (a) what a hassle!, and (b) you'd still be vulnerable to introducing new clashes as you extend the code.) Anyway, that's about 3 times what I set out to type . . . . Best, Brian vdB From alan.gauld at blueyonder.co.uk Tue Aug 10 09:10:45 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Aug 10 09:10:00 2004 Subject: [Tutor] Linear programming - is it bad? References: <4118091A.9000400@gamebox.net> Message-ID: <01fd01c47ea9$28187200$6401a8c0@xp> > This is my first post here (ive been reading this list for a few weeks, > interesting content!). Welcome to the gang ;-) > So my question: is it bad to write a python program/script in a linear > way? By linear, I mean: the code is executed line by line, without any > (programmer defined) classes or functions, NO, its pefect for very short programs. Its also fine for "throw-away" code. Stuff to do a one-off job. BUT its no good for reusable code. If you want to use the code as a module in the future it will be much better if you wrap the code in a function - evenif it is just one single function! I'm currently rewriting the case study in my tutorial and the approach I'm taking this time covers this transformation. The first iteration is a linear script, then we turn it into a module using functions and global variables then we make it more flexible and finally add classes etc... > a bit like [Q]BASIC without GOTO's, Or even Functions and Subroutines. GOTOs are just a variation on linear programming - thats why they are considered bad practice, even in QBASIC! > *needs* to use functions and classes. But since Im beginning, I dont see > the point. You are right. For very small projects (less than 20 or 30 lines say) there is rarely any point except reusability. Once you get past this size functions help to organise things and make them more readable, even for the author! Clases rarely become useful till you double the size again, about 50 lines upwards. The sizes are totally arbitrary and my own invention, but hopefully that gives a concrete feel to the sort of size of program where you should think about modularizing things? > messages from mailing list. If you'd like to see the source code, heres > a link to it. (Hope my old pentium who hosts the file will survive the > slashdot effect ;) > > http://home.bilange.ca/files/index.php?dir=&file=AutoLogC.py If its short code attach it, if its long (>100 lines?) post a URL. Another arbitrary size limit :-) Alan G. From alan.gauld at blueyonder.co.uk Tue Aug 10 09:24:34 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Aug 10 09:23:48 2004 Subject: [Tutor] Linear programming - is it bad? References: <4118091A.9000400@gamebox.net> Message-ID: <020401c47eab$15d05a20$6401a8c0@xp> > messages from mailing list. If you'd like to see the source code, heres > a link to it. (Hope my old pentium who hosts the file will survive the > slashdot effect ;) > > http://home.bilange.ca/files/index.php?dir=&file=AutoLogC.py I just noticed that you ask some questions in the code so I thought I'd answer a few of them: > #Is there a pythonized version of DOS cls? > system("cls") No, clearing the screen is a very OS depemdant thing, for example on Unix its "clear" instead of CLS. There is a module that Fred Lundh(sp?) wrote that tries to provide OS independant behaviour but I don't think it ever made it into the standard library. > #looks like raw_input is the only choice for dealing with user input. > #unfortunately, the user has to press enter, since its not a > one-key press event. > blah = raw_input("> ") You can use getch() as well which just pulls the current keyboard state, that avoids the need for hitting enter. But because its instantaneous you need to put it in a loop: key = getch() while not key: key = getch() Or for your purpose, simply detecting a keystroke: while not getch(): pass Finally you have 4 try/except blocks looking for the same exception. You could do it in one by setting a status flag after each stage, it just tidies the code a little. But as Danny has shown you could use functions here much more effectively. Linear style programming is OK for *very short* programs but yours has some repeating code so functions are better for that as well as making it more readable. Hope the above pointers help, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/ From alan.gauld at blueyonder.co.uk Tue Aug 10 09:30:46 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Aug 10 09:30:01 2004 Subject: [Tutor] text file References: <20040810002132.082B23962@mprdmxin.myway.com> Message-ID: <020f01c47eab$f3c8d870$6401a8c0@xp> > I want to open a text file and change the text size and save. > is this possible? No, text files don't have a size for the text, they only hold the characters. The size will be entirely dependant on the display device. If you open a Rich Text File, a PDF file or an HTML file you can control the size (and font etc) because they do contain formatting codes that allow you to set the size that the display should use. But plain text files only hold the characters. If you want to create files where you control the text size etc I strongly recommend HTML as a starting point. Its much easier to work with than either RTF or PDF. For general guidance on file handling info check the "Handling Files" topic in my tutorial. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/ From alan.gauld at blueyonder.co.uk Tue Aug 10 12:54:38 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Aug 10 12:53:52 2004 Subject: [Tutor] Linear programming - is it bad? References: <4118091A.9000400@gamebox.net> <020401c47eab$15d05a20$6401a8c0@xp> Message-ID: <022401c47ec8$6efb79f0$6401a8c0@xp> > You can use getch() as well which just pulls the current > keyboard state, that avoids the need for hitting enter. > But because its instantaneous you need to put it in a loop: > > key = getch() > while not key: > key = getch() And I should have pointedout that getch() lives in the msvcrt module for Windows and in the curses module for Linux. Alan G From mhansen at cso.atmel.com Tue Aug 10 16:46:10 2004 From: mhansen at cso.atmel.com (Mike Hansen) Date: Tue Aug 10 16:45:56 2004 Subject: [Tutor] Linear programming - is it bad? In-Reply-To: <20040810002225.605791E4012@bag.python.org> References: <20040810002225.605791E4012@bag.python.org> Message-ID: <4118DFB2.2030001@cso.atmel.com> I've been making my way through Steve McCoonnell's Code Complete(2nd Edition). There a good section in it with reasons to write functions/procedures/routines. It's not just to eliminate repeating code, but also to reduce complexity. Our brains can only load so much into our organic buffers, so it makes programs easier to read if you break it up into functions. > Subject: > [Tutor] Linear programming - is it bad? > From: > Eric Belanger > Date: > Mon, 09 Aug 2004 19:30:34 -0400 > To: > Tutor@python.org > > To: > Tutor@python.org > > > Hi! > > This is my first post here (ive been reading this list for a few > weeks, interesting content!). > > So my question: is it bad to write a python program/script in a linear > way? By linear, I mean: the code is executed line by line, without any > (programmer defined) classes or functions, a bit like [Q]BASIC without > GOTO's, or , while we're at it, HTML. I could also compare it to Doom > 3: going from A to B, then C, without any choices or options, until Z. > > I assume that by writing huge projects/programs, im assured > programmers *needs* to use functions and classes. But since Im > beginning, I dont see the point. > > For example, I made a small program that modify a few registry strings > to be able to login automaticly in Windows NT/2000/XP (Registry trick > explained at: http://www.winguides.com/registry/display.php/13/ ), > asking the user his login name and password. In this case, I didnt > stored a part of my own code into functions/classes. (For the console > version of it, that is. Using wxPython, guess I didnt have the choice ;) > > I dont know what to add, except asking whats your opinion about this > topic. > > Last thing - I would add my source code of that program i was talking > about, but I dont know if you guys do like to have attachments in > messages from mailing list. If you'd like to see the source code, > heres a link to it. (Hope my old pentium who hosts the file will > survive the slashdot effect ;) > > http://home.bilange.ca/files/index.php?dir=&file=AutoLogC.py > > Thanks! > > Eric Belanger - bilange A gamebox _ net > > From ps_python at yahoo.com Tue Aug 10 17:40:34 2004 From: ps_python at yahoo.com (kumar s) Date: Tue Aug 10 17:40:38 2004 Subject: [Tutor] expand In-Reply-To: <1091931361.529.4.camel@Waterhouse> Message-ID: <20040810154034.12306.qmail@web53705.mail.yahoo.com> Dear group, I am looking into a code by a friend of mine. x = re.comile("XXXX") x_match = x.search(string) y = int(x_match.expand("\\3")) y1 = int(x_match.expand("\\5")) I did not understand what .expand is doing here. What is it doing. is it same as expandtabs method in string module? Can any one help me please. thank you SK __________________________________ Do you Yahoo!? Read only the mail you want - Yahoo! Mail SpamGuard. http://promotions.yahoo.com/new_mail From bilange at gamebox.net Tue Aug 10 17:57:20 2004 From: bilange at gamebox.net (Eric Belanger) Date: Tue Aug 10 17:57:29 2004 Subject: [Tutor] Linear programming - is it bad? In-Reply-To: <01fd01c47ea9$28187200$6401a8c0@xp> References: <4118091A.9000400@gamebox.net> <01fd01c47ea9$28187200$6401a8c0@xp> Message-ID: <4118F060.8020906@gamebox.net> Hi, Thanks for all the replies. Also, thank you (Danny) for pointing out redundancy in my code. I made this script a bit quickly without thinking about optimizing, to tell the truth. Also, while we're in this exact subject, we could use getch in a function: ### from msvcrt import getch def wait_keystroke(sz_display = ""): if sz_display != "": print sz_display key = getch() while not key: key = getch() return key key_pressed = wait_keystroke("Press any key to continue...") print "You pressed: " + key_pressed ### Thanks again for your input! Eric Belanger From kent_johnson at skillsoft.com Tue Aug 10 18:08:17 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Tue Aug 10 18:08:20 2004 Subject: [Tutor] expand In-Reply-To: <20040810154034.12306.qmail@web53705.mail.yahoo.com> References: <1091931361.529.4.camel@Waterhouse> <20040810154034.12306.qmail@web53705.mail.yahoo.com> Message-ID: <6.1.0.6.0.20040810115556.0298fd88@mail4.skillsoft.com> match.expand(template) returns the string obtained by doing backslash substitution on the template. The backslash values will be replaced with the substring matched by the corresponding group of the regular expression. Groups are defined by parentheses in the regex. For example \1 will be substituted with the first group matched by the regex. In your example, since the template only has the \xx value, it is the same as match.group(xx). For example: >>> import re >>> r=re.compile(r'(a+).*?(b+)') >>> m=r.search('aaaxxbbbb') >>> m.expand('\\1') 'aaa' >>> m.expand('\\2') 'bbbb' >>> m.expand('\\1yy\\2') 'aaayybbbb' >>> m.group(1) 'aaa' >>> m.group(2) 'bbbb' >>> See http://docs.python.org/lib/match-objects.html for more information about match objects Kent At 08:40 AM 8/10/2004 -0700, kumar s wrote: >Dear group, > >I am looking into a code by a friend of mine. > >x = re.comile("XXXX") >x_match = x.search(string) >y = int(x_match.expand("\\3")) >y1 = int(x_match.expand("\\5")) > >I did not understand what .expand is doing here. What >is it doing. is it same as expandtabs method in string >module? >Can any one help me please. >thank you > >SK > > > >__________________________________ >Do you Yahoo!? >Read only the mail you want - Yahoo! Mail SpamGuard. >http://promotions.yahoo.com/new_mail >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From klas.martelleur at telia.com Tue Aug 10 18:59:47 2004 From: klas.martelleur at telia.com (Klas Marteleur) Date: Tue Aug 10 18:50:27 2004 Subject: [Tutor] Insert elements in a lis Message-ID: <200408101859.47288.klas.martelleur@telia.com> Hi Is it possible to insert elements in a list in an easy way? example: Startlist [1, 2, 3, 5] Endlist [1, 2, 3, 4, 5 ] Klas From klas.martelleur at telia.com Tue Aug 10 19:37:30 2004 From: klas.martelleur at telia.com (Klas Marteleur) Date: Tue Aug 10 19:28:09 2004 Subject: Fwd: Re: [Tutor] Insert elements in a lis Message-ID: <200408101937.30368.klas.martelleur@telia.com> Chad! i forward your reply to the list, mayby someone else is interested. Thanks for your reply Chad, i will try it. -------------- next part -------------- An embedded message was scrubbed... From: Chad Crabtree Subject: Re: [Tutor] Insert elements in a lis Date: Tue, 10 Aug 2004 10:17:33 -0700 (PDT) Size: 2709 Url: http://mail.python.org/pipermail/tutor/attachments/20040810/de06ced4/attachment.mht From kent_johnson at skillsoft.com Tue Aug 10 19:40:21 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Tue Aug 10 19:40:55 2004 Subject: [Tutor] Insert elements in a lis In-Reply-To: <200408101859.47288.klas.martelleur@telia.com> References: <200408101859.47288.klas.martelleur@telia.com> Message-ID: <6.1.0.6.0.20040810133602.02864458@mail4.skillsoft.com> Sure! Use list.insert(index, value): >>> l = [1, 2, 3, 5] >>> l.insert(3, 4) # Insert the value 4 at index 3 >>> l [1, 2, 3, 4, 5] Alternately you can use slice assignment to insert a list >>> l = [1, 2, 3, 5] >>> l[3:3] = [4] >>> l [1, 2, 3, 4, 5] See http://docs.python.org/lib/typesseq-mutable.html for a list of all the ways you can change a list. Kent At 06:59 PM 8/10/2004 +0200, Klas Marteleur wrote: >Hi >Is it possible to insert elements in a list in an easy way? > >example: > >Startlist >[1, 2, 3, 5] > >Endlist >[1, 2, 3, 4, 5 ] > >Klas >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From david at graniteweb.com Tue Aug 10 21:02:54 2004 From: david at graniteweb.com (David Rock) Date: Tue Aug 10 21:02:59 2004 Subject: [Tutor] gzip file close Message-ID: <20040810190254.GA31705@wdfs.attbi.com> I am trying to use the gzip module to open files for reading data, but I think I am having a problem with using it with non-gzipped files. What I want to do is pass a wordlist of filenames, some gzipped, some not on the commandline and have the program make the distiction between the two, but I get the following results: $parse_bpimagelist.py -m esdgp1 esdgp1.0408061210.bpimagelist.gz esdgp1.0408091210.bpimagelist Traceback (most recent call last): File "/home/drock/parse_bpimagelist.py", line 235, in ? d = getdata( file ) File "/home/drock/parse_bpimagelist.py", line 36, in getdata buffer = fp_input.readline() File "/usr/lib/python2.3/gzip.py", line 379, in readline c = self.read(readsize) File "/usr/lib/python2.3/gzip.py", line 224, in read self._read(readsize) File "/usr/lib/python2.3/gzip.py", line 260, in _read self._read_gzip_header() File "/usr/lib/python2.3/gzip.py", line 161, in _read_gzip_header raise IOError, 'Not a gzipped file' IOError: Not a gzipped file The first file is gzipped, the second is not. The try block I am trying to use looks like this: try: fp_input = gzip.open( inputfile, 'rb' ) except: fp_input = open( inputfile, 'rb' ) The idea was that if the file is not gzipped, it would do the second file open instead. One thing I found in the documentation is that gzip's close() method doesn't close the gzipped file, but I don't understand what that means. I don't think that's the issue because even if the non-gzipped file is listed first, it still doesn't work. I thought maybe it was because the close() operation wasn't working properly, but I don't see evidence to support that. Is it possible that the exception is NOT getting handled properly? Thanks. -- David Rock david@graniteweb.com -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20040810/9d3b3f15/attachment.pgp From pythonTutor at venix.com Tue Aug 10 21:29:34 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Tue Aug 10 21:29:41 2004 Subject: [Tutor] gzip file close In-Reply-To: <20040810190254.GA31705@wdfs.attbi.com> References: <20040810190254.GA31705@wdfs.attbi.com> Message-ID: <1092166174.20939.41.camel@laptop.venix.com> Reading through the traceback, the open lines you show don't appear. The error gets triggered when you do a readline at line 36. Obviously, that's later in the processing than you would like. The easiest way out may be something like: if inputfile.endswith('.gz'): It looks like a try block would include a large chunk of code. If you did stick with a try block it would be imperative to have a specific exception (except IOError:) rather than a blank except clause. On Tue, 2004-08-10 at 15:02, David Rock wrote: > I am trying to use the gzip module to open files for reading data, but I > think I am having a problem with using it with non-gzipped files. What I > want to do is pass a wordlist of filenames, some gzipped, some not on > the commandline and have the program make the distiction between the > two, but I get the following results: > > $parse_bpimagelist.py -m esdgp1 esdgp1.0408061210.bpimagelist.gz esdgp1.0408091210.bpimagelist > > Traceback (most recent call last): > File "/home/drock/parse_bpimagelist.py", line 235, in ? > d = getdata( file ) > File "/home/drock/parse_bpimagelist.py", line 36, in getdata > buffer = fp_input.readline() > File "/usr/lib/python2.3/gzip.py", line 379, in readline > c = self.read(readsize) > File "/usr/lib/python2.3/gzip.py", line 224, in read > self._read(readsize) > File "/usr/lib/python2.3/gzip.py", line 260, in _read > self._read_gzip_header() > File "/usr/lib/python2.3/gzip.py", line 161, in _read_gzip_header > raise IOError, 'Not a gzipped file' > IOError: Not a gzipped file > > The first file is gzipped, the second is not. The try block I am trying to use looks like this: > try: > fp_input = gzip.open( inputfile, 'rb' ) > except: > fp_input = open( inputfile, 'rb' ) > > The idea was that if the file is not gzipped, it would do the second > file open instead. One thing I found in the documentation is that gzip's > close() method doesn't close the gzipped file, but I don't understand > what that means. I don't think that's the issue because even if the > non-gzipped file is listed first, it still doesn't work. I thought maybe > it was because the close() operation wasn't working properly, but I > don't see evidence to support that. > > Is it possible that the exception is NOT getting handled properly? > > Thanks. -- 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 Tue Aug 10 22:02:25 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Aug 10 22:02:28 2004 Subject: [Tutor] gzip file close In-Reply-To: <20040810190254.GA31705@wdfs.attbi.com> Message-ID: On Tue, 10 Aug 2004, David Rock wrote: > The first file is gzipped, the second is not. The try block I am trying > to use looks like this: > > try: > fp_input = gzip.open( inputfile, 'rb' ) > except: > fp_input = open( inputfile, 'rb' ) > > The idea was that if the file is not gzipped, it would do the second > file open instead. Hi David, The assumption that you're making here is that gzip.open() raises an exception on a non-gzipped file, but this might not be true. For example: ### >>> from StringIO import StringIO >>> bogusData = StringIO("I am not a zipped file") >>> bogusData.seek(0) >>> >>> import gzip >>> unzippedFile = gzip.GzipFile(fileobj=bogusData) >>> unzippedFile.read(1) Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.3/gzip.py", line 224, in read self._read(readsize) File "/usr/lib/python2.3/gzip.py", line 260, in _read self._read_gzip_header() File "/usr/lib/python2.3/gzip.py", line 161, in _read_gzip_header raise IOError, 'Not a gzipped file' IOError: Not a gzipped file ### So it appears that gzip.GzipFile only starts reading the source file on a request for data, and not on open(). Hope this helps! From alan.gauld at blueyonder.co.uk Tue Aug 10 23:09:07 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Aug 10 23:09:18 2004 Subject: [Tutor] Insert elements in a lis References: <200408101859.47288.klas.martelleur@telia.com> Message-ID: <024701c47f1e$46666a80$6401a8c0@xp> > Is it possible to insert elements in a list in an easy way? >>> print [1,3,5].insert(1,2) [1,2,3,5] Is that easy enough? :-) You can also insert sublists etc too. The official tutor covers all this stuff quite well. There is a trick using slices: >>> L = [1,3,5] >>> L[2:2] = [4, 4.5] # insert a sequence >>> print L [1, 3, 4, 4.5, 5] The trick is to remember that slices effectively point *between* the members so [2:2] points to the region from "just before 2" to "just before 2" - ie between 1 and 2... Think about it :-) HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/ From david at graniteweb.com Tue Aug 10 23:45:28 2004 From: david at graniteweb.com (David Rock) Date: Tue Aug 10 23:45:32 2004 Subject: [Tutor] gzip file close In-Reply-To: References: <20040810190254.GA31705@wdfs.attbi.com> Message-ID: <20040810214528.GA32376@wdfs.attbi.com> * Danny Yoo [2004-08-10 13:02]: > > Hi David, > > > The assumption that you're making here is that gzip.open() raises an > exception on a non-gzipped file, but this might not be true. > > > For example: > > ### > >>> from StringIO import StringIO > >>> bogusData = StringIO("I am not a zipped file") > >>> bogusData.seek(0) > >>> > >>> import gzip > >>> unzippedFile = gzip.GzipFile(fileobj=bogusData) > >>> unzippedFile.read(1) > Traceback (most recent call last): > File "", line 1, in ? > File "/usr/lib/python2.3/gzip.py", line 224, in read > self._read(readsize) > File "/usr/lib/python2.3/gzip.py", line 260, in _read > self._read_gzip_header() > File "/usr/lib/python2.3/gzip.py", line 161, in _read_gzip_header > raise IOError, 'Not a gzipped file' > IOError: Not a gzipped file > ### > > > So it appears that gzip.GzipFile only starts reading the source file on a > request for data, and not on open(). Looks like that's it. I have added some logic to the script to open the file and do a quick read to verify if it is a gzipped file (based on what the gzip.py module looks like), so now it looks like this: fp_input = gzip.open( inputfile, 'rb' ) try: # test if it's a gzipped file (gzip.py actually calls # _read_gzip_header with a read(2) to look for the # gzip magic info, so this forces a read which fails # on non-gzipped files fp_input.read(5) except IOError: fp_input.close() fp_input = open( inputfile, 'rb' ) else: # This may not be necessary, but I figure it's safer to be # sure you're reading from the beginning fp_input.rewind() Thanks for the insight. It's obvious once you _read_ the traceback ;-) -- David Rock david@graniteweb.com -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20040810/ebfa224b/attachment.pgp From kalle at lysator.liu.se Wed Aug 11 00:06:37 2004 From: kalle at lysator.liu.se (Kalle Svensson) Date: Wed Aug 11 00:00:10 2004 Subject: [Tutor] Insert elements in a lis In-Reply-To: <024701c47f1e$46666a80$6401a8c0@xp> References: <200408101859.47288.klas.martelleur@telia.com> <024701c47f1e$46666a80$6401a8c0@xp> Message-ID: <20040810220637.GZ17831@i92.ryd.student.liu.se> [Alan Gauld] > > Is it possible to insert elements in a list in an easy way? > > >>> print [1,3,5].insert(1,2) > [1,2,3,5] What Python version is that? I get None (since insert modifies the list in-place and doesn't return the list) in Pythons 2.1, 2.2 and 2.3. Peace, Kalle -- http://juckapan.org/~kalle/ http://laxmasteriet.se/04-05/ From bigapple631 at optonline.net Wed Aug 11 01:25:25 2004 From: bigapple631 at optonline.net (jason hochstein) Date: Wed Aug 11 01:26:13 2004 Subject: [Tutor] sum of a list Message-ID: <001601c47f31$5098c210$bc4ebb18@hochstein> I can't figure out or find anywhere how to get the sum of a list?? Here is what I have so far: l_input=[] while True: s = raw_input("Type number. Hit enter for more or type quit to finish: ") if s == "quit": break else: l_input.append(float(s)) print "Here is your list of numbers ", l_input for i in l_input: I am trying to get the sum of all numbers inputed so I can work with the the total. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040810/95df877e/attachment.htm From bill.mill at gmail.com Wed Aug 11 01:41:47 2004 From: bill.mill at gmail.com (Bill Mill) Date: Wed Aug 11 01:41:52 2004 Subject: [Tutor] sum of a list In-Reply-To: <001601c47f31$5098c210$bc4ebb18@hochstein> References: <001601c47f31$5098c210$bc4ebb18@hochstein> Message-ID: <797fe3d4040810164154f0242e@mail.gmail.com> Jason, try "sum(l_input)". Otherwise, try: def mysum(mylist): sum = 0 for elt in mylist: sum += elt return sum Peace Bill Mill ----- Original Message ----- From: jason hochstein Date: Tue, 10 Aug 2004 19:25:25 -0400 Subject: [Tutor] sum of a list To: tutor@python.org I can't figure out or find anywhere how to get the sum of a list?? Here is what I have so far: l_input=[] while True: s = raw_input("Type number. Hit enter for more or type quit to finish: ") if s == "quit": break else: l_input.append(float(s)) print "Here is your list of numbers ", l_input for i in l_input: I am trying to get the sum of all numbers inputed so I can work with the the total. From pythonTutor at venix.com Wed Aug 11 01:48:50 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Wed Aug 11 01:48:56 2004 Subject: [Tutor] sum of a list In-Reply-To: <001601c47f31$5098c210$bc4ebb18@hochstein> References: <001601c47f31$5098c210$bc4ebb18@hochstein> Message-ID: <1092181730.20939.83.camel@laptop.venix.com> On Tue, 2004-08-10 at 19:25, jason hochstein wrote: > I can't figure out or find anywhere how to get the sum of a list?? > Here is what I have so far: > > l_input=[] > > while True: > s = raw_input("Type number. Hit enter for more or type quit to > finish: ") > > > if s == "quit": > break > else: > l_input.append(float(s)) > > print "Here is your list of numbers ", l_input > > for i in l_input: at this point you probably already tried something like total = total + i and got NameError: name 'total' is not defined The problem is that total + i can only be computed if total already exists. The usual solution is to initialize total to 0.0. total = 0.0 for i in l_input: total = total + i print total The latest version of python includes a builtin function called sum that will compute your total without a loop total = sum(l_input) > > > I am trying to get the sum of all numbers inputed so I can work with > the the total. > > ______________________________________________________________________ > > _______________________________________________ > 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 python-tutor at vs.megalink.ru Wed Aug 11 02:55:52 2004 From: python-tutor at vs.megalink.ru (Vsevolod Sipakov) Date: Wed Aug 11 02:55:55 2004 Subject: [Tutor] Linear programming - is it bad? In-Reply-To: References: Message-ID: <20040811005552.GA19444@megalink.ru> Hello, On Mon, Aug 09, 2004 at 05:22:21PM -0700, Danny Yoo wrote: > Ack! I didn't see that the default values for all but the AutoAdminLogon > were the empty string, and not zero. Let me fix this. > > ### > def queryForValue(reg, name, defaultValue=""): > try: > values = QueryValueEx(reg, name) > return values[0] > except WindowsError: > print "Error:", name, "string missing from registry:", > print "creating default value:", defaultValue > nothing = SetValueEx(reg, name, 0, REG_SZ, defaultValue) > return "0" I think this function should return defaultValue too :-) > regusername = queryForValue(reg, "DefaultUserName") > regusername = queryForValue(reg, "DefaultUserName") > regpassword = queryForValue(reg, "DefaultPassword") > regdomain = queryForValue(reg, "DefaultDomainName") > regautolog = queryForValue(reg, "AutoAdminLogon", "0") > ### > -- Vsevolod Sipakov From Dragonfirebane at aol.com Wed Aug 11 04:34:54 2004 From: Dragonfirebane at aol.com (Dragonfirebane@aol.com) Date: Wed Aug 11 04:35:05 2004 Subject: [Tutor] sum of a list Message-ID: <6.302885bd.2e4adfce@aol.com> In a message dated 8/10/2004 7:27:04 PM Eastern Standard Time, bigapple631@optonline.net writes: I can't figure out or find anywhere how to get the sum of a list?? Here is what I have so far: l_input=[] while True: s = raw_input("Type number. Hit enter for more or type quit to finish: ") if s == "quit": break else: l_input.append(float(s)) print "Here is your list of numbers ", l_input for i in l_input: I am trying to get the sum of all numbers inputed so I can work with the the total. >>> a = [1, 2, 3, 4, 5] >>> sum(a) 15 sum() works with any sequence, not just lists. Email: dragonfirebane@aol.com AIM: singingxduck Programming Python for the fun of it. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040810/8b485c9c/attachment.html From bill.mill at gmail.com Wed Aug 11 05:07:26 2004 From: bill.mill at gmail.com (Bill Mill) Date: Wed Aug 11 05:07:29 2004 Subject: [Tutor] sum of a list In-Reply-To: <6.302885bd.2e4adfce@aol.com> References: <6.302885bd.2e4adfce@aol.com> Message-ID: <797fe3d4040810200731c8c69@mail.gmail.com> > sum() works with any sequence, not just lists. Not true. Witness: >>> sum('123') Traceback (most recent call last): File "", line 1, in ? TypeError: unsupported operand type(s) for +: 'int' and 'str' >>> sum('123', '') Traceback (most recent call last): File "", line 1, in ? TypeError: sum() can't sum strings [use ''.join(seq) instead] It works for any sequence composed of numeric elements, AFAICT. The documentation is unclear on this point, saying only that the sequences are *normally* numbers, although it explicitly disallows strings. I assume that it works on anything which can be added to start and which is not a string or a class derived from a string. Peace Bill Mill From alan.gauld at blueyonder.co.uk Wed Aug 11 08:45:38 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Aug 11 08:47:09 2004 Subject: [Tutor] Insert elements in a lis References: <200408101859.47288.klas.martelleur@telia.com><024701c47f1e$46666a80$6401a8c0@xp> <20040810220637.GZ17831@i92.ryd.student.liu.se> Message-ID: <028401c47f6e$d027dce0$6401a8c0@xp> > > >>> print [1,3,5].insert(1,2) > > [1,2,3,5] > > What Python version is that? I get None (since insert modifies the > list in-place and doesn't return the list) in Pythons 2.1, 2.2 and > 2.3. Rats! You caught me! I actually did: >>> L = [1,3,5].insert(11,2) >>> print L And in the email "abbreviated" it, but forgot that insert doesn't actually return the new list - oops! Alan G. From alan.gauld at blueyonder.co.uk Wed Aug 11 08:50:00 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Aug 11 08:51:33 2004 Subject: [Tutor] sum of a list References: <001601c47f31$5098c210$bc4ebb18@hochstein> Message-ID: <029901c47f6f$6c7ceb80$6401a8c0@xp> > I can't figure out or find anywhere how to get the sum of a list?? L = [1,2,3] sum = reduce(operator.add,L) Which is shorthand for sum = 0 for item in L: sum += item Check my topic on Functional Programming for more info. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/ From alan.gauld at blueyonder.co.uk Wed Aug 11 08:51:47 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Aug 11 08:53:18 2004 Subject: [Tutor] sum of a list References: <001601c47f31$5098c210$bc4ebb18@hochstein> <797fe3d4040810164154f0242e@mail.gmail.com> Message-ID: <029e01c47f6f$abbe9d70$6401a8c0@xp> > try "sum(l_input)". Wow! When did that one appear? I've never noticed a sum() function before. You just keep on learning... Alan G. From gew75 at hotmail.com Wed Aug 11 10:30:31 2004 From: gew75 at hotmail.com (Glen Wheeler) Date: Wed Aug 11 10:31:33 2004 Subject: [Tutor] Insert elements in a lis References: <200408101859.47288.klas.martelleur@telia.com><024701c47f1e$46666a80$6401a8c0@xp><20040810220637.GZ17831@i92.ryd.student.liu.se> <028401c47f6e$d027dce0$6401a8c0@xp> Message-ID: > [..] > >>> L = [1,3,5].insert(11,2) > >>> print L > > And in the email "abbreviated" it, but forgot that insert doesn't > actually return the new list - oops! > Another case of e-mail abbreviation? I assume this is meant to be: >>> l = [1,2,3] >>> l.insert(1,2) >>> print l ??? From michele.alzetta at aliceposta.it Wed Aug 11 12:47:20 2004 From: michele.alzetta at aliceposta.it (Michele Alzetta) Date: Wed Aug 11 12:47:23 2004 Subject: [Tutor] How do I make a process aware of .... Message-ID: <1092221240.26340.50.camel@localhost> I would like to have a running python process become aware of when a certain user logs in / logs out and of how long he has been connected ... any hints as to how this can be done ? Any way of knowing when a process is running (more elegant and pythonic than "ps aux || grep program"") ? Thnx ! -- Michele From jmatthews at mcb-inc.com Wed Aug 11 15:18:46 2004 From: jmatthews at mcb-inc.com (John Matthews) Date: Wed Aug 11 15:18:04 2004 Subject: [Tutor] trying to get data from digital camera.jpg file with EXIF.py Message-ID: <411A1CB6.4080503@mcb-inc.com> I read this list each day and find it quite informative and enjoyable. Thanks tutors! I am a beginning programmer and I am trying to use EXIF to get the "Image DateTime" from my .jpg files for a little program I am writing that makes web pages for my family photos. I am trying to use EXIF.py by Gene Cash. He also has written exiftool.py, and both of these files are available here: http://home.cfl.rr.com/genecash/digital_camera.html Just messing around at the interpreter I do something like this and get what appears to be an empty dictionary. import EXIF, os file = open('temp.jpg') data = EXIF.process_file(file) print data >>> {} I thought that would dump the same data I get at the command prompt when I do: exiftool.py -v temp.jpg but I must be way off. If someone can offer me a pointer I would really appreciate it! Thanks! -- John Matthews McDonald, Cassell & Bassett, Inc. 600 West Spring Street Columbus, Ohio 43215 (614) 628-0630 (614) 628-0633 Fax From alipolatel at yahoo.com Wed Aug 11 16:13:45 2004 From: alipolatel at yahoo.com (Ali Polatel) Date: Wed Aug 11 16:13:48 2004 Subject: [Tutor] Need help with telnet Message-ID: <20040811141345.53629.qmail@web61007.mail.yahoo.com> Friends I want to write a programme which connects to the chess server that I play chess using telnet... The IP of the chess server is "65.245.208.34" (ports is 5007 or 5072) (www.chessclub.com is the url) Can someone write me a simple script so that I can understand how to write telnet scripts with python? Regards, Ali Polatel --------------------------------- Do you Yahoo!? Read only the mail you want - Yahoo! Mail SpamGuard. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040811/eb179ab6/attachment.htm From alipolatel at yahoo.com Wed Aug 11 16:14:33 2004 From: alipolatel at yahoo.com (Ali Polatel) Date: Wed Aug 11 16:14:36 2004 Subject: [Tutor] searching Message-ID: <20040811141433.55762.qmail@web61009.mail.yahoo.com> --------------------------------- Do you Yahoo!? New and Improved Yahoo! Mail - Send 10MB messages! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040811/015e5de3/attachment.html From alipolatel at yahoo.com Wed Aug 11 16:15:39 2004 From: alipolatel at yahoo.com (Ali Polatel) Date: Wed Aug 11 16:15:42 2004 Subject: [Tutor] searching in files Message-ID: <20040811141539.55983.qmail@web61009.mail.yahoo.com> I am writing a programme which includes searching some words in a txt file... How can I do this?Is there a module in python which can do that? Regards __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040811/a17e77a3/attachment.htm From kent_johnson at skillsoft.com Wed Aug 11 16:33:40 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Wed Aug 11 16:33:46 2004 Subject: [Tutor] trying to get data from digital camera.jpg file with EXIF.py In-Reply-To: <411A1CB6.4080503@mcb-inc.com> References: <411A1CB6.4080503@mcb-inc.com> Message-ID: <6.1.0.6.0.20040811103009.028bd508@mail4.skillsoft.com> Try opening the file in binary mode, that is what exiftool does: file = open('temp.jpg', 'rb') Kent At 09:18 AM 8/11/2004 -0400, John Matthews wrote: >I read this list each day and find it quite informative and enjoyable. >Thanks tutors! > >I am a beginning programmer and I am trying to use EXIF to get the "Image >DateTime" from my .jpg files for a little program I am writing that makes >web pages for my family photos. > >I am trying to use EXIF.py by Gene Cash. He also has written exiftool.py, >and both of these files are available here: > >http://home.cfl.rr.com/genecash/digital_camera.html > >Just messing around at the interpreter I do something like this and get >what appears to be an empty dictionary. > >import EXIF, os >file = open('temp.jpg') >data = EXIF.process_file(file) >print data > >>> >{} > >I thought that would dump the same data I get at the command prompt when I do: > >exiftool.py -v temp.jpg > >but I must be way off. If someone can offer me a pointer I would really >appreciate it! > >Thanks! >-- >John Matthews >McDonald, Cassell & Bassett, Inc. >600 West Spring Street >Columbus, Ohio 43215 >(614) 628-0630 >(614) 628-0633 Fax >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From amonroe at columbus.rr.com Wed Aug 11 16:42:05 2004 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Wed Aug 11 16:42:13 2004 Subject: [Tutor] searching in files In-Reply-To: <20040811141539.55983.qmail@web61009.mail.yahoo.com> References: <20040811141539.55983.qmail@web61009.mail.yahoo.com> Message-ID: <18855557307.20040811104205@columbus.rr.com> > I am writing a programme which includes searching some words in a txt file... > How can I do this?Is there a module in python which can do that? Check out the .readlines method for reading files. Then have a look at the "in" keyword - it can tell you if a particular string exists inside of another string. Alan From alipolatel at yahoo.com Wed Aug 11 16:46:11 2004 From: alipolatel at yahoo.com (Ali Polatel) Date: Wed Aug 11 16:46:15 2004 Subject: [Tutor] searching in files In-Reply-To: <18855557307.20040811104205@columbus.rr.com> Message-ID: <20040811144611.31158.qmail@web61001.mail.yahoo.com> Yes I know the method readlines but the file is enorm large and it can make the computer slow if I make the programme read all of it into a sentence... Any other advices? Regards --------------------------------- Do you Yahoo!? Yahoo! Mail is new and improved - Check it out! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040811/5858da8b/attachment.html From kent_johnson at skillsoft.com Wed Aug 11 16:55:54 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Wed Aug 11 16:56:00 2004 Subject: [Tutor] searching in files In-Reply-To: <20040811144611.31158.qmail@web61001.mail.yahoo.com> References: <18855557307.20040811104205@columbus.rr.com> <20040811144611.31158.qmail@web61001.mail.yahoo.com> Message-ID: <6.1.0.6.0.20040811105311.0296ddf0@mail4.skillsoft.com> You can iterate over lines in a file without reading in the whole file at once, using for line in aFile: >>> f=open('index.html') >>> for line in f: ... if '

' in line: ... print line ...

Python Rocks!

Blogging

About me

Kent At 07:46 AM 8/11/2004 -0700, Ali Polatel wrote: >Yes I know the method readlines but the file is enorm large and it can >make the computer slow if I make the programme read all of it into a >sentence... >Any other advices? >Regards > > >Do you Yahoo!? >Yahoo! Mail is new and improved - >Check >it out! >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From dyoo at hkn.eecs.berkeley.edu Wed Aug 11 19:42:09 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Aug 11 19:42:15 2004 Subject: [Tutor] Linear programming - is it bad? In-Reply-To: <20040811005552.GA19444@megalink.ru> Message-ID: On Wed, 11 Aug 2004, Vsevolod Sipakov wrote: > > Ack! I didn't see that the default values for all but the AutoAdminLogon > > were the empty string, and not zero. Let me fix this. > > > > ### > > def queryForValue(reg, name, defaultValue=""): > > try: > > values = QueryValueEx(reg, name) > > return values[0] > > except WindowsError: > > print "Error:", name, "string missing from registry:", > > print "creating default value:", defaultValue > > nothing = SetValueEx(reg, name, 0, REG_SZ, defaultValue) > > return "0" > > I think this function should return defaultValue too :-) Hi Vsevolod, Gah! Good grief. Thanks for seeing what I missed. ### def queryForValue(reg, name, defaultValue=""): try: values = QueryValueEx(reg, name) return values[0] except WindowsError: print "Error:", name, "string missing from registry:", print "creating default value:", defaultValue nothing = SetValueEx(reg, name, 0, REG_SZ, defaultValue) return defaultValue ### Thank you again; good catch. Why is programming so hard? *grin* Talk to you later! From klas.martelleur at telia.com Wed Aug 11 19:58:01 2004 From: klas.martelleur at telia.com (Klas Marteleur) Date: Wed Aug 11 19:48:30 2004 Subject: [Tutor] Create file / Print list to file Message-ID: <200408111958.01115.klas.martelleur@telia.com> Hi and thanks for all the previous answers. I am still struggling with my conversion program. Here are todays questions :) 1. Is it possible to tell python to create a file (for example if specified file doesnt exist)? It sems possible to create a directory thrue the os module. But i cant find out how to create a file. 2. How can i print a list to a file? I have tried the following: def writeListToFile(inputList, outputFile): a = open(outputFile, "w") listLength = len(inputList) for i in range(0,listLength): a.write(inputList[i]) a.close() but i get a "Type error" inputList is list of lists (each row is list) Klas From dyoo at hkn.eecs.berkeley.edu Wed Aug 11 20:04:30 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Aug 11 20:04:34 2004 Subject: [Tutor] Need help with telnet In-Reply-To: <20040811141345.53629.qmail@web61007.mail.yahoo.com> Message-ID: On Wed, 11 Aug 2004, Ali Polatel wrote: > Can someone write me a simple script so that I can understand how to > write telnet scripts with python? Hi Ali, The Standard Library comes with a fairly nice telnetlib Have you looked at the 'telnetlib' documentation? Here's a link to it: http://python.org/doc/lib/module-telnetlib.html The documentation there comes with a simple example that should help show how to use it: http://python.org/doc/lib/telnet-example.html If you have more questions, please feel free to ask on Tutor. From alan.gauld at blueyonder.co.uk Wed Aug 11 20:04:05 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Aug 11 20:05:57 2004 Subject: [Tutor] Insert elements in a lis References: <200408101859.47288.klas.martelleur@telia.com><024701c47f1e$46666a80$6401a8c0@xp><20040810220637.GZ17831@i92.ryd.student.liu.se> <028401c47f6e$d027dce0$6401a8c0@xp> Message-ID: <000c01c47fcd$97b9b590$6401a8c0@xp> > I actually did: > > >>> L = [1,3,5].insert(11,2) > >>> print L > Actually I didn't even do that! I did: >>> L = [1,3,5]. >>> L.insert(1,2) >>> print L :-) Alan G. From aicolburn at yahoo.com Wed Aug 11 20:07:22 2004 From: aicolburn at yahoo.com (Alan Colburn) Date: Wed Aug 11 20:07:26 2004 Subject: [Tutor] [OT] Linux Message-ID: <20040811180722.50605.qmail@web51102.mail.yahoo.com> Hi all -- I know this is OT, but this list seems to have a lot of folks who love Linux. If I'm way off base here, please accept my apologies. I recently "discovered" Linux, via the Knoppix CD. I must say, I was both surprised and excited by what I saw! Now I'd like to learn more and install a distribution on one of my laptops. I could either reformat an old laptop (166 MHz, ~90 Mb RAM, 2G HD) or find space on a newer machine. Which path would you recommend? If the safer alternative of the older machine sounds good to you, which distribution(s) will run well on a machine that old? I've had a hard time finding an answer. Alternatively, if I should go with the newer machine, how large a partition do you think I would want? (I'd probably use the newest Mandrake, based on the common perception of its ease for newbies; I don't need every app in the world installed. Once Python is in place, what else does one really need? :-). My thanks (or apologies) ahead of time -- Al C. __________________________________ Do you Yahoo!? New and Improved Yahoo! Mail - 100MB free storage! http://promotions.yahoo.com/new_mail From dyoo at hkn.eecs.berkeley.edu Wed Aug 11 20:12:50 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Aug 11 20:12:55 2004 Subject: [Tutor] Create file / Print list to file In-Reply-To: <200408111958.01115.klas.martelleur@telia.com> Message-ID: > 2. How can i print a list to a file? I have tried the following: > > def writeListToFile(inputList, outputFile): > a = open(outputFile, "w") > listLength = len(inputList) > for i in range(0,listLength): > a.write(inputList[i]) > a.close() > > but i get a "Type error" Hi Klas, Ah, try not to paraphrase error messages: show the literal error message that Python emits. It helps a lot, because we can then try to duplicate the exact same error message on our end. > inputList is list of lists (each row is list) Ok. a.write() is a function that takes strings, not lists, so the line: > a.write(inputList[i]) is probably the cause of the type error. 'inputList[i]' here is a list, and not a string that the write() method expects. A quicky way to fix that is to just get a string representation of the list, and pass that off to write(): a.write(str(inputList[i])) By the way, we can run a for-loop right across a list. So instead of: ### listLength = len(inputList) for i in range(0,listLength): a.write(str(inputlist[i])) ### we can loop directly on the list, like this: ### for subList in inputList: a.write(str(subList)) ### This lets us avoid worrying about explicit list indexing. Good luck to you! From nick at javacat.f2s.com Wed Aug 11 20:22:49 2004 From: nick at javacat.f2s.com (Nick Lunt) Date: Wed Aug 11 20:20:36 2004 Subject: [Tutor] Create file / Print list to file In-Reply-To: <200408111958.01115.klas.martelleur@telia.com> Message-ID: Hi Klas, >1. Is it possible to tell python to create a file (for example if specified >file doesnt exist)? It sems possible to create a directory thrue the os >module. But i cant find out how to create a file. lets say you dont have a file called '/newfile'. >>> f = open('/anyfile','w') >>> f.close() You do now ;) There may be an easier way, but that seems easy enough to me. > 2. How can i print a list to a file? I have tried the following: Your correct in that you cant write a list to a file, but you seem to be iterating through your list in a strange way, this is simpler >>> l = ['this','is','a','list'] >>> f = open('/anyfile','w') >>> for i in l: ... f.write(i) >>> f.close() if you look at the contents of /anyfile it will contain the contents of list l. Hope that helps Nick. -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org]On Behalf Of Klas Marteleur Sent: 11 August 2004 18:58 To: tutor@python.org Subject: [Tutor] Create file / Print list to file Hi and thanks for all the previous answers. I am still struggling with my conversion program. Here are todays questions :) 1. Is it possible to tell python to create a file (for example if specified file doesnt exist)? It sems possible to create a directory thrue the os module. But i cant find out how to create a file. 2. How can i print a list to a file? I have tried the following: def writeListToFile(inputList, outputFile): a = open(outputFile, "w") listLength = len(inputList) for i in range(0,listLength): a.write(inputList[i]) a.close() but i get a "Type error" inputList is list of lists (each row is list) Klas _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From kent_johnson at skillsoft.com Wed Aug 11 20:20:28 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Wed Aug 11 20:21:28 2004 Subject: [Tutor] Create file / Print list to file In-Reply-To: <200408111958.01115.klas.martelleur@telia.com> References: <200408111958.01115.klas.martelleur@telia.com> Message-ID: <6.1.0.6.0.20040811141547.028c1b20@mail4.skillsoft.com> Klas, You can create a file by opening it for writing. Note that file.write() doesn't append a newline, so you may have to write them yourself depending on what is in your list and what you want the output to look like. Here is an example that formats the lines with spaces between the list items. Danny gave you an example that writes the literal list. Kent >>> l=[ ['line', 'one'], ['second', 'line'], ['this', 'is', 'the', 'third'] ] >>> f=open('foo.txt', 'w') >>> for line in l: ... lineData = ' '.join(line) ... f.write(lineData) ... f.write('\n') ... >>> f.close() >>> f=open('foo.txt') >>> for line in f: ... print line, ... line one second line this is the third >>> Kent At 07:58 PM 8/11/2004 +0200, you wrote: >Hi and thanks for all the previous answers. I am still struggling with my >conversion program. > >Here are todays questions :) > >1. Is it possible to tell python to create a file (for example if specified >file doesnt exist)? It sems possible to create a directory thrue the os >module. But i cant find out how to create a file. > >2. How can i print a list to a file? I have tried the following: > >def writeListToFile(inputList, outputFile): > a = open(outputFile, "w") > listLength = len(inputList) > for i in range(0,listLength): > a.write(inputList[i]) > a.close() > >but i get a "Type error" > >inputList is list of lists (each row is list) > >Klas >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From dyoo at hkn.eecs.berkeley.edu Wed Aug 11 20:23:20 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Aug 11 20:23:25 2004 Subject: [Tutor] How do I make a process aware of .... In-Reply-To: <1092221240.26340.50.camel@localhost> Message-ID: On Wed, 11 Aug 2004, Michele Alzetta wrote: > I would like to have a running python process become aware of when a > certain user logs in / logs out and of how long he has been connected > ... any hints as to how this can be done ? > > Any way of knowing when a process is running (more elegant and pythonic > than "ps aux || grep program"") ? Hi Michele, You may want to look at the 'python-utmp' third party module: http://melkor.dnp.fmph.uniba.sk/~garabik/python-utmp/ which gives us access to the utmp file --- utmp's the file that tells us who's logged in, and how long they've been on. The 'w' unix command reads from the same file, so it should be authoritative. *grin* As for detecting when someone logs in... hmm... I'm not so sure about that. Does anyone else know if there's a nice way of doing this, besides an explicit poll loop? Good luck! From bill at celestial.net Wed Aug 11 20:39:02 2004 From: bill at celestial.net (Bill Campbell) Date: Wed Aug 11 20:39:11 2004 Subject: [Tutor] [OT] Linux In-Reply-To: <20040811180722.50605.qmail@web51102.mail.yahoo.com> References: <20040811180722.50605.qmail@web51102.mail.yahoo.com> Message-ID: <20040811183902.GB17458@alexis.mi.celestial.com> On Wed, Aug 11, 2004, Alan Colburn wrote: >Hi all -- >I know this is OT, but this list seems to have a lot of folks who love >Linux. If I'm way off base here, please accept my apologies. >I recently "discovered" Linux, via the Knoppix CD. I must say, I was both >surprised and excited by what I saw! Now I'd like to learn more and install >a distribution on one of my laptops. I could either reformat an old laptop >(166 MHz, ~90 Mb RAM, 2G HD) or find space on a newer machine. Which path >would you recommend? That laptop is a bit anemic for current Linux distributions. I've been running Linux on a ThinkPad 600 for five years, starting with Caldera OpenLinux 1.3, and now have SuSE 9.0 Professional on it. The latest versions of SuSE won't install on less than 128MB of RAM (I have 256MB in the ThinkPad). You can install a very stripped down version on a 2GB hard drive, but that would leave out much of the fun stuff. You can buy some pretty nice boot-only machines between 3 and 4 hundred USD, and Fry's has machines with Linux installed for about $200.00. >If the safer alternative of the older machine sounds good to you, which >distribution(s) will run well on a machine that old? I've had a hard time >finding an answer. Alternatively, if I should go with the newer machine, >how large a partition do you think I would want? (I'd probably use the >newest Mandrake, based on the common perception of its ease for newbies; I >don't need every app in the world installed. Once Python is in place, what >else does one really need? :-). We moved all our Linux to SuSE about two years ago, and IMHO it's the best engineered distribution available today. I recommend the SuSE ``Professional'' packaging, particularly if one is going to do much development work, as the ``Personal'' version doesn't always have the development libraries without building them yourself, and some programs I use aren't in the personal version. SuSE 9.1 Professional is quite complete, and has standard packages for python, apache, zope, etc. Bill -- INTERNET: bill@Celestial.COM Bill Campbell; Celestial Software LLC UUCP: camco!bill PO Box 820; 6641 E. Mercer Way FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 URL: http://www.celestial.com/ ``The Income Tax has made more Liars out of American people than Golf has.'' Will Rogers From dyoo at hkn.eecs.berkeley.edu Wed Aug 11 20:55:17 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Aug 11 20:55:26 2004 Subject: [Tutor] sum of a list In-Reply-To: <029e01c47f6f$abbe9d70$6401a8c0@xp> Message-ID: On Wed, 11 Aug 2004, Alan Gauld wrote: > > try "sum(l_input)". > > Wow! When did that one appear? I've never noticed a sum() function > before. Hi Alan, The Python implementors snuck...er, added sum() into Python 2.3: http://www.python.org/doc/lib/built-in-funcs.html#l2h-65 Here's a link to the python-dev summary about sum(): http://www.python.org/dev/summary/2003-04-16_2003-04-30.html#summing-a-bunch-of-numbers-or-whatevers Hope this helps! From rob.benton at conwaycorp.net Wed Aug 11 21:34:56 2004 From: rob.benton at conwaycorp.net (Rob Benton) Date: Wed Aug 11 21:35:00 2004 Subject: [Tutor] [OT] Linux In-Reply-To: <20040811183902.GB17458@alexis.mi.celestial.com> References: <20040811180722.50605.qmail@web51102.mail.yahoo.com> <20040811183902.GB17458@alexis.mi.celestial.com> Message-ID: <411A74E0.6010406@conwaycorp.net> This conversation happens all the time. :) Debian is my personal favorite. The best resource I've ever found to picking distros is http://www.distrowatch.com Bill Campbell wrote: > On Wed, Aug 11, 2004, Alan Colburn wrote: > >>Hi all -- > > >>I know this is OT, but this list seems to have a lot of folks who love >>Linux. If I'm way off base here, please accept my apologies. > > >>I recently "discovered" Linux, via the Knoppix CD. I must say, I was both >>surprised and excited by what I saw! Now I'd like to learn more and install >>a distribution on one of my laptops. I could either reformat an old laptop >>(166 MHz, ~90 Mb RAM, 2G HD) or find space on a newer machine. Which path >>would you recommend? > > > That laptop is a bit anemic for current Linux distributions. I've been > running Linux on a ThinkPad 600 for five years, starting with Caldera > OpenLinux 1.3, and now have SuSE 9.0 Professional on it. The latest > versions of SuSE won't install on less than 128MB of RAM (I have 256MB in > the ThinkPad). You can install a very stripped down version on a 2GB hard > drive, but that would leave out much of the fun stuff. > > You can buy some pretty nice boot-only machines between 3 and 4 hundred > USD, and Fry's has machines with Linux installed for about $200.00. > > >>If the safer alternative of the older machine sounds good to you, which >>distribution(s) will run well on a machine that old? I've had a hard time >>finding an answer. Alternatively, if I should go with the newer machine, >>how large a partition do you think I would want? (I'd probably use the >>newest Mandrake, based on the common perception of its ease for newbies; I >>don't need every app in the world installed. Once Python is in place, what >>else does one really need? :-). > > > We moved all our Linux to SuSE about two years ago, and IMHO it's the best > engineered distribution available today. I recommend the SuSE > ``Professional'' packaging, particularly if one is going to do much > development work, as the ``Personal'' version doesn't always have the > development libraries without building them yourself, and some programs I > use aren't in the personal version. > > SuSE 9.1 Professional is quite complete, and has standard packages for > python, apache, zope, etc. > > Bill > -- > INTERNET: bill@Celestial.COM Bill Campbell; Celestial Software LLC > UUCP: camco!bill PO Box 820; 6641 E. Mercer Way > FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 > URL: http://www.celestial.com/ > > ``The Income Tax has made more Liars out of American people than Golf has.'' > Will Rogers > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From pythonTutor at venix.com Wed Aug 11 21:37:34 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Wed Aug 11 21:37:41 2004 Subject: [Tutor] Need help with telnet In-Reply-To: <20040811141345.53629.qmail@web61007.mail.yahoo.com> References: <20040811141345.53629.qmail@web61007.mail.yahoo.com> Message-ID: <1092253053.3247.11.camel@laptop.venix.com> If chessclub.com uses gnuchess, you might find the sample program for popen2 in Fredrik Lundh's book "Python Standard Library" useful. It's from chapter three on page 104. I believe much of the material in the book has been posted to the Internet. You would have to adapt the example to fit telnetlib. Danny has already pointed you towards the documentation for telnetlib. Lundh's book also has an example for telnetlib. On Wed, 2004-08-11 at 10:13, Ali Polatel wrote: > Friends I want to write a programme which connects to the chess server > that I play chess using telnet... > The IP of the chess server is "65.245.208.34" (ports is 5007 or 5072) > (www.chessclub.com is the url) > Can someone write me a simple script so that I can understand how to > write telnet scripts with python? > Regards, > Ali Polatel > > > > > ______________________________________________________________________ > Do you Yahoo!? > Read only the mail you want - Yahoo! Mail SpamGuard. > > ______________________________________________________________________ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From nick at javacat.f2s.com Wed Aug 11 22:28:27 2004 From: nick at javacat.f2s.com (Nick Lunt) Date: Wed Aug 11 22:26:16 2004 Subject: [Tutor] [OT] Linux In-Reply-To: <20040811183902.GB17458@alexis.mi.celestial.com> Message-ID: Hi Alan, On Wed, Aug 11, 2004, Alan Colburn wrote: >I could either reformat an old laptop >(166 MHz, ~90 Mb RAM, 2G HD) or find space on a newer machine. Which path >would you recommend? I would download Slackware Linux for the laptop (www.slackware.com) . It is designed to run on a 486 and onwards. Cheers Nick. From alan.gauld at blueyonder.co.uk Thu Aug 12 00:08:47 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Aug 12 00:10:34 2004 Subject: [Tutor] trying to get data from digital camera.jpg file with EXIF.py References: <411A1CB6.4080503@mcb-inc.com> Message-ID: <001a01c47fef$c67f7690$6401a8c0@xp> > I am trying to use EXIF.py by Gene Cash. He also has written > exiftool.py, and both of these files are available here: > > http://home.cfl.rr.com/genecash/digital_camera.html I don;t know the tool but... > I thought that would dump the same data I get at the command prompt when > I do: > > exiftool.py -v temp.jpg > > but I must be way off. If someone can offer me a pointer I would really > appreciate it! Since the tool is a .py file why not open it up in a text editor (like IDLE) and see what it does? Then copy it... :-) And there's nothing like reading real world code for gaining experience quickly. Alan G From alan.gauld at blueyonder.co.uk Thu Aug 12 00:11:05 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Aug 12 00:12:52 2004 Subject: [Tutor] Need help with telnet References: <20040811141345.53629.qmail@web61007.mail.yahoo.com> Message-ID: <002201c47ff0$18fbf2e0$6401a8c0@xp> > Friends I want to write a programme which connects to the chess > server that I play chess using telnet... > Can someone write me a simple script so that I can understand > how to write telnet scripts with python? If you want to script a telnet session you might find pyexpect a more useful tool. You specify patterns to look for in the telnet output and the functions to call when they are found. Its based on the well known Tcl tool expect. I can't remember if its in the standard library but if not I'm sure its on sourceforge... Alan G. From alan.gauld at blueyonder.co.uk Thu Aug 12 00:13:20 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Aug 12 00:15:09 2004 Subject: [Tutor] searching in files References: <20040811141539.55983.qmail@web61009.mail.yahoo.com> Message-ID: <002c01c47ff0$690c2a20$6401a8c0@xp> > I am writing a programme which includes searching some words in a txt file... > How can I do this?Is there a module in python which can do that? You can search for strings using the builtin string mehods, so if you read() the file into a huge string its easy. If you specifically want to search for *words* then you might want to use the re module to search for regular expressions. More powerful, slower for simple searches but faster for complex ones - like limiting to whole words... HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/ From alan.gauld at blueyonder.co.uk Thu Aug 12 00:14:28 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Aug 12 00:16:16 2004 Subject: [Tutor] searching in files References: <20040811144611.31158.qmail@web61001.mail.yahoo.com> Message-ID: <003801c47ff0$91d88020$6401a8c0@xp> > Yes I know the method readlines but the file is enorm large In that case use xreadlines(), it will only read the lines as you ask for them not all at once. HTH, Alan G. From bigapple631 at optonline.net Thu Aug 12 00:19:13 2004 From: bigapple631 at optonline.net (jason hochstein) Date: Thu Aug 12 00:20:27 2004 Subject: [Tutor] same ol s Message-ID: <001a01c47ff1$3b8256a0$bc4ebb18@hochstein> I am still having problems getting the median and mode of a list. Any ideas?? I am confused on how you tell the code to decipher from a list with an even or odd amount of numbers in it. The mode is totally eluding me. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040811/4caef552/attachment.htm From alan.gauld at blueyonder.co.uk Thu Aug 12 00:22:13 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Aug 12 00:24:00 2004 Subject: [Tutor] Create file / Print list to file References: <200408111958.01115.klas.martelleur@telia.com> Message-ID: <004101c47ff1$a6f868c0$6401a8c0@xp> > 1. Is it possible to tell python to create a file (for example if specified > file doesnt exist)? Yes just create it for writing or appending and the file will be created if it doesn't already exist. If writing to an existing file will get overwritten, if appending the data will be appended at the end - surprise! Check the file handling chapter in the book - p96 :-) > 2. How can i print a list to a file? I have tried the following: > > def writeListToFile(inputList, outputFile): > a = open(outputFile, "w") > listLength = len(inputList) > for i in range(0,listLength): > a.write(inputList[i]) for i in inputList: a.write(i) Is simpler! > a.close() > > but i get a "Type error" write expects strings so try converting i to a string: a.write(str(i)) And you might want to add a newline character too? a.write(str(a) + '\n') > inputList is list of lists (each row is list) In this case you need to look at the recursion chapter of the book where there is an example of printing lists of lists... change print to write() and you are there... HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/ From alan.gauld at blueyonder.co.uk Thu Aug 12 00:31:21 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Aug 12 00:33:07 2004 Subject: [Tutor] [OT] Linux References: <20040811180722.50605.qmail@web51102.mail.yahoo.com> Message-ID: <005801c47ff2$edab3490$6401a8c0@xp> > I recently "discovered" Linux, via the Knoppix CD. I > must say, I was both surprised and excited :-) I've been playing with Linux since 1993 and I have a love/hate thing with it. But I'm never long without a Linux box of some kind... > reformat an old laptop (166 MHz, ~90 Mb RAM, 2G HD) > or find space on a newer machine. For playing the old macjine should be OK, but laptops can be tricky unless you can find a Linux build specifically for that - IBM Thinkpads are good bets. The problem is lots of unusual devices. Modern laptops and distros will be no problem but an old laptop will need either a slimmed down distro or an old distro to fit that 2G disk with space for work. > distribution(s) will run well on a machine that old? The age isn't really a problem, even new Linux distros will run on old hardware, but they take up a lot of space. I'd go for a small distro like Vector which is based on Slackware. Thats easily upgradeable but everything fits comfortably on 1G and was happy with my 200M P3 and 64M RAM. - And as a bonus the window manager look a lot like MacOS X so you might fool your friends you bought a Mac :-) > large a partition do you think I would want? (I'd > probably use the newest Mandrake, based on the common > perception of its ease for newbies; Mandrake is good for newbies, bt a full install of any modern distro will look at 4-6G or more. A lot depends on how serious you want to get. Many folks use Linux as their main system day in day out. If thats your plan spec the PC as you would any other - the faster and bigger the better. If you are still playing for education then I'd try the smaller laptop first. Alan G. From klas.martelleur at telia.com Thu Aug 12 00:43:33 2004 From: klas.martelleur at telia.com (Klas Marteleur) Date: Thu Aug 12 00:34:01 2004 Subject: [Tutor] Create file / Print list to file In-Reply-To: <6.1.0.6.0.20040811141547.028c1b20@mail4.skillsoft.com> References: <200408111958.01115.klas.martelleur@telia.com> <6.1.0.6.0.20040811141547.028c1b20@mail4.skillsoft.com> Message-ID: <200408120043.33485.klas.martelleur@telia.com> I dont know what i am doing diffrent from you but i dont get it to work: This is my function: def writeListToFile(inputList, outputFile): print "\nThis is the inputlist\n",inputList f = open(outputFile,"w") print "\nThis is f\n", f for line in inputList: lineData = ' '.join(line) f.write(lineData) f.write('\n') f.close() and this is a snippet of the output: ...This is the inputlist [['Parent Name', ';', 'Parent Revision', ';', 'Child Name', ';', 'Child Revision', ';', 'Quantity', ';', 'Find Number', ';', 'Reference Designator', ';', 'Remark', ';', 'Usage', ';', 'WP', ';', 'PRP'], ['03003365', ';', 'AB', ';', '03003240', ';', 'AC', ';', '1', ';', 100, ';', '10', ';', '-', ';', '', ';', '-', ';', '-'], ['03003365', ';', 'AB', ';', '03003358', ';', 'AA', ';', '2', ';', 90, ';', '9', ';', 'Mtrl. spec.: 56-3239-47 ', ';', '', ';', 'YES', ';', '-'], ['03003365', ';', 'AB', ';', '03003359', ';', 'AB', ';', '8', ';', 80, ';', '8', ';', '-', ';', '', ';', '-', ';', 'YES'], ['03003365', ';', 'AB', ';', '03003360', ';', 'AB', ';', '1', ';', 70, ';', '7', ';', '-', ';', '', ';', 'YES', ';', 'YES'], ['03003365', ';', 'AB', ';', '03003361', ';', 'AA', ';', '2', ';', 60, ';', '6', ';', '-', ';', '', ';', '-', ';', '-'], ['03003365', ';', 'AB', ';', '03003362', ';', 'AB', ';', '1', ';', 50, ';', '5', ';', '-', ';', '', ';', 'YES', ';', 'YES'], ['03003365', ';', 'AB', ';', '03003363', ';', 'AB', ';', '1', ';', 40, ';', '4', ';', '-', ';', '', ';', 'YES', ';', 'YES'], ['03003365', ';', 'AB', ';', '03003364', ';', 'AB', ';', '1', ';', 30, ';', '3', ';', '-', ';', '', ';', 'YES', ';', 'YES'], ['03003365', ';', 'AB', ';', '59-0763-00', ';', '1', ';', '16', ';', 20, ';', '2', ';', 'DIN 934 ', ';', '', ';', '-', ';', '-'], ['03003365', ';', 'AB', ';', '59-0781-00', ';', '1', ';', '16', ';', 10, ';', '1', ';', '-', ';', '', ';', '-', ';', '-']] This is f Traceback (most recent call last): File "/home/klas/Python_filer/Tragic/CreateEbomFromFile4.py", line 109, in ? writeListToFile(modifiedList,'/home/klas/Python_filer/Tragic/output.txt') File "/home/klas/Python_filer/Tragic/CreateEbomFromFile4.py", line 80, in writeListToFile lineData = ' '.join(line) TypeError: sequence item 10: expected string, int found i want the file to look something like Parent name;Parent Revision;Child Name;....... 03003365;AB;03003240;..... Alan! I will try recursion tomorrow if nessesary again thanks all Klas Klas From flaxeater at yahoo.com Thu Aug 12 00:42:10 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Thu Aug 12 00:42:12 2004 Subject: [Tutor] same ol s Message-ID: <20040811224210.60443.qmail@web52602.mail.yahoo.com> jason hochstein wrote: > I am still having problems getting the median and mode of a list. Any > ideas?? I am confused on how you tell the code to decipher from a list > with an even or odd amount of numbers in it. The mode is totally > eluding me. > >------------------------------------------------------------------------ > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > Show us some code. uhmmm modulus operator is % so if len(list)%2==0: print "it's even" __________________________________ Do you Yahoo!? Yahoo! Mail - 50x more storage than other providers! http://promotions.yahoo.com/new_mail From bigapple631 at optonline.net Thu Aug 12 00:47:19 2004 From: bigapple631 at optonline.net (jason hochstein) Date: Thu Aug 12 00:48:12 2004 Subject: [Tutor] same ol s References: <20040811224210.60443.qmail@web52602.mail.yahoo.com> Message-ID: <005c01c47ff5$28a3b930$bc4ebb18@hochstein> This is what I have so far: l_input=[] while True: s = raw_input("Type number. Hit enter for more or type quit to finish: ") if s == "quit": break else: l_input.append(float(s)) for i in l_input: average = sum(l_input) / len(l_input) middle = len(l_input) / ? mcf = ??? print "The mean of this list is ",average print "The median of this list is",middle print "The mode of this list is",mcf ----- Original Message ----- From: "Chad Crabtree" To: "jason hochstein" Cc: Sent: Wednesday, August 11, 2004 6:42 PM Subject: Re: [Tutor] same ol s > jason hochstein wrote: > > > I am still having problems getting the median and mode of a list. > Any > > ideas?? I am confused on how you tell the code to decipher from a > list > > with an even or odd amount of numbers in it. The mode is totally > > eluding me. > > > >------------------------------------------------------------------------ > > > >_______________________________________________ > >Tutor maillist - Tutor@python.org > >http://mail.python.org/mailman/listinfo/tutor > > > > > Show us some code. uhmmm > > modulus operator is % so > > if len(list)%2==0: > print "it's even" > > > > > > __________________________________ > Do you Yahoo!? > Yahoo! Mail - 50x more storage than other providers! > http://promotions.yahoo.com/new_mail From bigapple631 at optonline.net Thu Aug 12 00:54:33 2004 From: bigapple631 at optonline.net (jason hochstein) Date: Thu Aug 12 00:55:23 2004 Subject: [Tutor] Me again Message-ID: <007001c47ff6$2b0b4de0$bc4ebb18@hochstein> This is what I get when using the %. l_input=[] while True: s = raw_input("Type number. Hit enter for more or type quit to finish: ") if s == "quit": break else: l_input.append(float(s)) for i in l_input: average = sum(l_input) / len(l_input) middle = len(l_input) % 2 print "The mean of this list is ",average print "The median of this list is",middle Here is what I get: >> The mean of this list is 5.5 The median of this list is 0 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040811/7a4040e9/attachment.html From bvande at po-box.mcgill.ca Thu Aug 12 01:10:42 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Thu Aug 12 01:11:01 2004 Subject: [Tutor] same ol s In-Reply-To: <001a01c47ff1$3b8256a0$bc4ebb18@hochstein> References: <001a01c47ff1$3b8256a0$bc4ebb18@hochstein> Message-ID: <411AA772.7030300@po-box.mcgill.ca> jason hochstein said unto the world upon 2004-08-11 18:19: > I am still having problems getting the median and mode of a list. Any > ideas?? I am confused on how you tell the code to decipher from a list > with an even or odd amount of numbers in it. The mode is totally > eluding me. Hi Jason, it would be easier for the people on the list to help you if you shared what you had tried--even if it doesn't do what you want, a code sample will help people figure out how to formulate a response so that it can help you solve the problem, rather than solving it for you. And don't worry about feeling that its not "good enough" -- I've tried my best is posting silly learner things and haven't yet made a single tutor member ridicule me ;-) I'll address the mode part of your question. I'm going to give it more in English than code. My suggestion would be to try to put something like what I here describe into code and to post another question if you get stuck on how to do that. I've purposely been silent on a few parts of the dictionary techniques I mention. See section 2.3.7 Mapping Types of the library reference for the exact syntax details. Let's assume you have a list of integers and you want to find the mode or modes of that list. And, just to be explicit, by "mode" I mean the most frequently occurring data point in the list. So, for example [1, 2, 2, 3, 4, 4, 4, 5] would have 4 as its mode. There may not be a unique mode: [1, 1, 2, 3, 3] has both 1 and 3 occurring most often. Now what's the mode of [1, 4, 5, 2, 3, 3, 4, 5, 6, 5, 6]? 5. How do you tell? Well, if you are like me and find this list too long to take in with a single glance, you go through the list, keeping a running count of how often each data point occurs, and on getting to the end, see that there were more 5's than anything else. That suggests a strategy for doing it in Python. Iterate through the list, keeping count of how often each data point has appeared. The way I'd do it (no bets that this is best; I'm learning too) is to use a dictionary. Integers can be used a dictionary keys (this is because they are immutable--though there might be more to it than just that). So, I'd initialize an empty dictionary before I start my loop: occurrence_count = {} Then, I'd iterate through my list, considering each data point one by one. You'd do this like so: for i in integer_list: # where integer_list is the collection of data # Fancy code logic here What you would then do in the indented fancy code logic block is check for whether occurrence_count had i as a key. (i will take each of the values in your list as the iteration repeats again and again going through the list, so this is really checking of each data point whether it is a key in your dictionary.) If it doesn't, this is because it is the first time you've seen that number. So, make a new key/value pair for your dictionary with i as key and value as 1 (its the first occurrence after all): occurrence_count[i] = 1 If it does have a key, you need to augment the key by 1. So: occurrence_count[i] = occurrence_count[i] + 1 Once the iteration over the list is done, you'll have a dictionary where every element in your data is a key, and the values will tell you how often that data element occurred. From that you can have Python tell you which element occurred most often. I'll leave that to you entirely. Have a try, and ask again with some code showing what you tried and others on the list will surely be happy to help you some more. I hope that helps get you started. Best, Brian vdB From alan.gauld at blueyonder.co.uk Thu Aug 12 01:31:42 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Aug 12 01:33:28 2004 Subject: [Tutor] same ol s References: <001a01c47ff1$3b8256a0$bc4ebb18@hochstein> Message-ID: <009501c47ffb$5bceb9d0$6401a8c0@xp> > I am still having problems getting the median and mode Groan, I hate statistics... Remind me again, what are the definitions of median and mode? Alan G. From dyoo at hkn.eecs.berkeley.edu Thu Aug 12 01:36:35 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Aug 12 01:36:39 2004 Subject: [Tutor] Create file / Print list to file In-Reply-To: <200408120043.33485.klas.martelleur@telia.com> Message-ID: On Thu, 12 Aug 2004, Klas Marteleur wrote: > File "/home/klas/Python_filer/Tragic/CreateEbomFromFile4.py", line 80, in > writeListToFile > lineData = ' '.join(line) > TypeError: sequence item 10: expected string, int found Hi Klas, The join() method requires that every element in the 'line' should be a string. It's a function that takes a sequence of strings, and returns a string. But many of your example data lines have numbers. For example: ['03003365', ';', 'AB', ';', '03003359', ';', 'AB', ';', '8', ';', 80, ';', '8', ';', '-', ';', '', ';', '-', ';', 'YES'] ^^ has the number 80 in there. You can probably do something like: lineData = ' '.join([str(x) for x in line]) to first pass each element through the str() conversion function, and then join those strings together. Hope this helps! From alan.gauld at blueyonder.co.uk Thu Aug 12 01:37:44 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Aug 12 01:39:30 2004 Subject: [Tutor] Create file / Print list to file References: <200408111958.01115.klas.martelleur@telia.com><6.1.0.6.0.20040811141547.028c1b20@mail4.skillsoft.com> <200408120043.33485.klas.martelleur@telia.com> Message-ID: <009a01c47ffc$33e30a60$6401a8c0@xp> > I dont know what i am doing diffrent from you but i dont get it to work: > ...This is the inputlist > [['Parent Name', ';', 'Parent Revision', ';', 'Child Name', ';', 'Child > Revision', ';', 'Quantity', ';', 'Find Number', ';', 'Reference Designator', > ';', 'Remark', ';', 'Usage', ';', 'WP', ';', 'PRP'], ['03003365', ';', 'AB', > i want the file to look something like > > Parent name;Parent Revision;Child Name;....... > 03003365;AB;03003240;..... The difference is you are printing Pythons string representation of a list - henvce the brackets. You want the contents of the list. > Alan! I will try recursion tomorrow if nessesary Thats what the recursive solution does - it will flatten the list and print out the elements. That might still not be exactly what you want. But between them... >>> L = [[1,2,3],[4,5,6]] >>> print L [[1, 2, 3], [4, 5, 6]] >>> for item in L: print item [1, 2, 3] [4, 5, 6] >>> printList(L) # as defined in my tutor 1,2,3,4,5,6 It all depends what you actually want. Alan G. From bigapple631 at optonline.net Thu Aug 12 01:39:22 2004 From: bigapple631 at optonline.net (jason hochstein) Date: Thu Aug 12 01:40:38 2004 Subject: [Tutor] same ol s References: <001a01c47ff1$3b8256a0$bc4ebb18@hochstein> <009501c47ffb$5bceb9d0$6401a8c0@xp> Message-ID: <009301c47ffc$6ddc0b40$bc4ebb18@hochstein> The median is the middle number in your list, if the numbers are sorted in ascending order. If it is an even numbered list, the median would be half way between the 2 middle numbers. (1,2,3,4,5,6,7,8,9) 5 is the median. The mode is the number making the most common appearance. (1,2,3,3,3,4,5) 3 is the mode. ----- Original Message ----- From: "Alan Gauld" To: "jason hochstein" ; Sent: Wednesday, August 11, 2004 7:31 PM Subject: Re: [Tutor] same ol s > > > I am still having problems getting the median and mode > > Groan, I hate statistics... > Remind me again, what are the definitions of median and mode? > > Alan G. From pythonTutor at venix.com Thu Aug 12 02:16:53 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Thu Aug 12 02:17:12 2004 Subject: [Tutor] same ol s In-Reply-To: <009301c47ffc$6ddc0b40$bc4ebb18@hochstein> References: <001a01c47ff1$3b8256a0$bc4ebb18@hochstein> <009501c47ffb$5bceb9d0$6401a8c0@xp> <009301c47ffc$6ddc0b40$bc4ebb18@hochstein> Message-ID: <1092269812.2100.28.camel@laptop.venix.com> Danny already told you that we try to limit our help to references on homework assignments. On Wed, 2004-08-11 at 19:39, jason hochstein wrote: > The median is the middle number in your list, if the numbers are sorted in > ascending order. If you look up the list methods, you will find how to sort a list. THis is the general index to Python documentation: http://docs.python.org/lib/genindex.html In the L section, look for: list type, operations on > If it is an even numbered list, An earlier response pointed out that you can use the modulus operator to test for even or odd. I'll repeat that here, number % 2 == 0 # true when number is even > the median would be half Half of a number, is the number divided by two. Look up the divmod function if you need help with division in python. divmod can also help with detecting even versus odd. > way between the 2 middle numbers. (1,2,3,4,5,6,7,8,9) 5 is the median. Do you know how to reference an element in a list? From your example above, list = [1,2,3,4,5,6,7,8,9] list[0] # will reference the first element, the 1 list[1] # will reference the second element, the 2 and so on. The Python tutorial (and Alan Gauld's) tutorial cover this. That should help in picking out the middle number. > > The mode is the number making the most common appearance. (1,2,3,3,3,4,5) 3 > is the mode. You received some detailed help for computing the mode earlier. > > ----- Original Message ----- > From: "Alan Gauld" > To: "jason hochstein" ; > Sent: Wednesday, August 11, 2004 7:31 PM > Subject: Re: [Tutor] same ol s > > > > > > > I am still having problems getting the median and mode > > > > Groan, I hate statistics... > > Remind me again, what are the definitions of median and mode? > > > > Alan G. > > _______________________________________________ > 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 Dragonfirebane at aol.com Thu Aug 12 02:18:25 2004 From: Dragonfirebane at aol.com (Dragonfirebane@aol.com) Date: Thu Aug 12 02:18:41 2004 Subject: [Tutor] same ol s Message-ID: <8e.121276f5.2e4c1151@aol.com> In a message dated 8/11/2004 6:21:25 PM Eastern Standard Time, bigapple631@optonline.net writes: I am still having problems getting the median and mode of a list. Any ideas?? I am confused on how you tell the code to decipher from a list with an even or odd amount of numbers in it. The mode is totally eluding me. Well, you can use len(list) to determine if its even or odd: ### if str(len(list)/2.0)[-1] != 0: print 'Odd number of elements.' else: print 'Even number of elements.' ### Then based on that, sort() the list and get the middle element, like so: ### print 'Median: %s' % list[int(round(len(list)/2.0))] ### if the length of the list is odd or like so: ### print 'Medians: %s, %s' % (list[(len(list)/2) - 1], list[(len(list)/2)]) ### if it is even, to get the median. As for the mode, the suggestion made by bvande@po-box.mcgill.ca seems reasonable. Email: dragonfirebane@aol.com AIM: singingxduck Programming Python for the fun of it. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040811/9d1c43c9/attachment.html From david at graniteweb.com Thu Aug 12 04:57:05 2004 From: david at graniteweb.com (David Rock) Date: Thu Aug 12 04:57:08 2004 Subject: [Tutor] [OT] Linux In-Reply-To: <20040811180722.50605.qmail@web51102.mail.yahoo.com> References: <20040811180722.50605.qmail@web51102.mail.yahoo.com> Message-ID: <20040812025705.GB4833@wdfs.attbi.com> * Alan Colburn [2004-08-11 11:07]: > Hi all -- > > I recently "discovered" Linux, via the Knoppix CD. I > must say, I was both > surprised and excited by what I saw! Now I'd like to > learn more and install > a distribution on one of my laptops. I could either > reformat an old laptop > (166 MHz, ~90 Mb RAM, 2G HD) or find space on a newer > machine. Which path > would you recommend? My personal favorite is gentoo linux, but I would not recommend it for a system as old as the laptop you are talking about. Gentoo is a "from source" distribution, meaning it's designed to compile all the software on the machine from the sourcecode. It would run great once it's compiled, but compiling on something that old will make you old, too. :-) Still, it's been the most stable distro I've used in the last 10 years. As for space on a new system, most distros will install comfortably on 5 Gig with an average installation. -- David Rock david@graniteweb.com -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20040811/d7d2e02c/attachment-0001.pgp From zmerch at 30below.com Thu Aug 12 05:17:16 2004 From: zmerch at 30below.com (Roger Merchberger) Date: Thu Aug 12 05:17:23 2004 Subject: [Tutor] [OT] Linux In-Reply-To: <20040812025705.GB4833@wdfs.attbi.com> References: <20040811180722.50605.qmail@web51102.mail.yahoo.com> <20040811180722.50605.qmail@web51102.mail.yahoo.com> Message-ID: <5.1.0.14.2.20040811231055.0478b9c8@mail.30below.com> Rumor has it that David Rock may have mentioned these words: >* Alan Colburn [2004-08-11 11:07]: > > I could either reformat an old laptop > > (166 MHz, ~90 Mb RAM, 2G HD) or find space on a newer > > machine. Which path would you recommend? > >My personal favorite is gentoo linux, but I would not recommend it for a >system as old as the laptop you are talking about. Or for running qmail. Gentoo's "version" of it is so, so b0rked, that it's... it's... Well, let's just say "Broken beyond repair." > Gentoo is a "from >source" distribution, meaning it's designed to compile all the software >on the machine from the sourcecode. It would run great once it's >compiled, but compiling on something that old will make you old, too. >:-) > >Still, it's been the most stable distro I've used in the last 10 years. >As for space on a new system, most distros will install comfortably on 5 >Gig with an average installation. If you want "From source" and you actually want to learn something about Linux at the same time: http://www.linuxfromscratch.org/ to do it by hand. If you want it automated, look for the "Automated LFS" link on that page. Get the tarball, build nALFS, and *poof* -> InstaLinux. (Well, if instant for you is 2-6 days, depending on CPU/HD speed... ;-) ) You will learn more about linux in a week than you could out of a book in months. Trust me. Oh, and with a *really lame* attempt to bring this back ontopic: Python *screams* when natively compiled -> under natively compiled libraries. Trust me. My Crusoe laptop loves me for it. ;-) HTH, Roger "Merch" Merchberger LFS Registered User #9350 -- 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 klas.martelleur at telia.com Thu Aug 12 08:51:55 2004 From: klas.martelleur at telia.com (Klas Marteleur) Date: Thu Aug 12 08:42:19 2004 Subject: [Tutor] Create file / Print list to file In-Reply-To: References: Message-ID: <200408120851.55716.klas.martelleur@telia.com> Thanks Danny, Alan, Nick and Kent. Something really cool about this list is that you often get several good answers, all with diffrent ways of looking at the problems that means you learn a lot on the way. The following lines accomplish what i want: > You can probably do something like: > > lineData = ' '.join([str(x) for x in line]) > > to first pass each element through the str() conversion function, and then > join those strings together. Klas From alan.gauld at blueyonder.co.uk Thu Aug 12 08:53:14 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Aug 12 08:54:55 2004 Subject: [Tutor] same ol s References: <8e.121276f5.2e4c1151@aol.com> Message-ID: <00cb01c48039$0a51f110$6401a8c0@xp> > Well, you can use len(list) to determine if its even or odd: > > ### > if str(len(list)/2.0)[-1] != 0: > print 'Odd number of elements.' > else: > print 'Even number of elements.' > ### Eek! Try this, its a bit simpler. if len(aList) % 2: print 'odd' else: print 'even' The % operator returns the remainder of an integer division. If the length is even the remainder is zero, or false. Alan G. From alipolatel at yahoo.com Thu Aug 12 11:09:54 2004 From: alipolatel at yahoo.com (Ali Polatel) Date: Thu Aug 12 11:09:56 2004 Subject: [Tutor] Deleting System Files? Message-ID: <20040812090954.74281.qmail@web61002.mail.yahoo.com> Dear Friends, Can Python delete system files? I tried it importing the module os and using the function "os.remove" but the computer asks "xxx.xxx is a system file.Are you sure to remove xxx.xxx ?" and the programme gives error... Is there any way to make the programme click "yes to all" ? Regards, --------------------------------- Do you Yahoo!? Take Yahoo! Mail with you! Get it on your mobile phone. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040812/a82c0532/attachment.html From alipolatel at yahoo.com Thu Aug 12 11:56:33 2004 From: alipolatel at yahoo.com (Ali Polatel) Date: Thu Aug 12 11:56:35 2004 Subject: [Tutor] Dos command Message-ID: <20040812095633.81461.qmail@web61002.mail.yahoo.com> Dear Friends, I want to put the result of a dos-command in a list..how can i do this?(I remember it was related with os module but forgot the function) for example dir command... Regards --------------------------------- Do you Yahoo!? Yahoo! Mail - 50x more storage than other providers! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040812/cda55e08/attachment.html From my.mailing.lists at noos.fr Thu Aug 12 12:29:52 2004 From: my.mailing.lists at noos.fr (nik) Date: Thu Aug 12 12:30:06 2004 Subject: [Tutor] 'import site' failed error Message-ID: <411B46A0.5080608@noos.fr> hi, I've compiled the example in the Extending and Embedding tutorial section 2.1 (creating an module with a couple of string objects), and I get the error 'import site' failed; use -v for traceback even though the correct output is then printed to the screen. What does this mean? Do I need to post my code here (I've made a few modifications)? How do I do the -v for traceback, and would it be useful to me? I tried searching the tutor archives on ASPN, but it didn't seem to be working, even when I tried searches like list, which were clearly in a lot of people's posts - any idea what's up with that? thanks, nik From kent_johnson at skillsoft.com Thu Aug 12 12:49:44 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Thu Aug 12 12:49:55 2004 Subject: [Tutor] 'import site' failed error In-Reply-To: <411B46A0.5080608@noos.fr> References: <411B46A0.5080608@noos.fr> Message-ID: <6.1.0.6.0.20040812064630.02a11dd0@mail4.skillsoft.com> nik, I guess it is referring to the -v (verbose) option that you can pass to python when you start it up: D:\Projects>python -v # installing zipimport hook import zipimport # builtin # installed zipimport hook # C:\Python23\lib\site.pyc matches C:\Python23\lib\site.py import site # precompiled from C:\Python23\lib\site.pyc # C:\Python23\lib\os.pyc matches C:\Python23\lib\os.py import os # precompiled from C:\Python23\lib\os.pyc etc... traceback is the stack trace. So this may give you more specific information about the location and type of failure. Give it a try and let us know what it says! Kent At 12:29 PM 8/12/2004 +0200, nik wrote: >hi, > >I've compiled the example in the Extending and Embedding tutorial section >2.1 (creating an module with a couple of string objects), and I get the error > >'import site' failed; use -v for traceback > >even though the correct output is then printed to the screen. > >What does this mean? >Do I need to post my code here (I've made a few modifications)? >How do I do the -v for traceback, and would it be useful to me? From bill.mill at gmail.com Thu Aug 12 13:09:31 2004 From: bill.mill at gmail.com (Bill Mill) Date: Thu Aug 12 13:09:37 2004 Subject: [Tutor] Dos command In-Reply-To: <797fe3d404081203543a2a6ff1@mail.gmail.com> References: <20040812095633.81461.qmail@web61002.mail.yahoo.com> <797fe3d404081203543a2a6ff1@mail.gmail.com> Message-ID: <797fe3d404081204095338656f@mail.gmail.com> Ali, Note that I'm on linux, so I'll use linux commands, but you can substitute them easily for dos ones. You can definitely do it with the os module, >>> import os >>> st_in, st_out = os.popen2('mount') >>> st_out.readlines() ['/dev/hda5 on / type ext3 (rw)\n', 'none on /proc type proc (rw)\n', 'none on /sys type sysfs (rw)\n', 'none on /dev/pts type devpts (rw,gid=5,mode=620)\n', 'usbdevfs on /proc/bus/usb type usbdevfs (rw)\n', 'none on /dev/shm type tmpfs (rw)\n', '/dev/hda7 on /home type ext3 (rw)\n', '/dev/hda2 on /c type vfat (rw,uid=500,gid=500)\n', '/dev/hda3 on /music type vfat (rw,uid=500,gid=500,umask=000)\n', 'sunrpc on /var/lib/nfs/rpc_pipefs type rpc_pipefs (rw)\n', 'none on /proc/sys/fs/binfmt_misc type binfmt_misc (rw)\n'] You can also do it with the commands module: >>> import commands >>> commands.getoutput('mount').split('\n') ['/dev/hda5 on / type ext3 (rw)', 'none on /proc type proc (rw)', 'none on /sys type sysfs (rw)', 'none on /dev/pts type devpts (rw,gid=5,mode=620)', 'usbdevfs on /proc/bus/usb type usbdevfs (rw)', 'none on /dev/shm type tmpfs (rw)', '/dev/hda7 on /home type ext3 (rw)', '/dev/hda2 on /c type vfat (rw,uid=500,gid=500)', '/dev/hda3 on /music type vfat (rw,uid=500,gid=500,umask=000)', 'sunrpc on /var/lib/nfs/rpc_pipefs type rpc_pipefs (rw)', 'none on /proc/sys/fs/binfmt_misc type binfmt_misc (rw)'] this might be clearer if you're only reading, not writing, data. Peace Bill Mill ----- Original Message ----- From: Ali Polatel Date: Thu, 12 Aug 2004 02:56:33 -0700 (PDT) Subject: [Tutor] Dos command To: tutor@python.org Dear Friends, I want to put the result of a dos-command in a list..how can i do this?(I remember it was related with os module but forgot the function) for example dir command... Regards ________________________________ Do you Yahoo!? Yahoo! Mail - 50x more storage than other providers! From my.mailing.lists at noos.fr Thu Aug 12 13:11:29 2004 From: my.mailing.lists at noos.fr (nik) Date: Thu Aug 12 13:11:47 2004 Subject: [Tutor] 'import site' failed error In-Reply-To: <6.1.0.6.0.20040812064630.02a11dd0@mail4.skillsoft.com> References: <411B46A0.5080608@noos.fr> <6.1.0.6.0.20040812064630.02a11dd0@mail4.skillsoft.com> Message-ID: <411B5061.5000606@noos.fr> Hi Kent, that was a quick reply! I've embedded the interpreter in a C app, and so the python file is called using PyRun_SimpleFile(fp, "demo2.py"); so, I'm not too sure how to put the -v option in there (I'm doing some websearching on it now). I tried a simple python file like print "hello", but it didn't come up with the import site error, so I guess it's more to do with the embedding or my module thingy? nik Kent Johnson wrote: > nik, > > I guess it is referring to the -v (verbose) option that you can pass > to python when you start it up: > D:\Projects>python -v > # installing zipimport hook > import zipimport # builtin > # installed zipimport hook > # C:\Python23\lib\site.pyc matches C:\Python23\lib\site.py > import site # precompiled from C:\Python23\lib\site.pyc > # C:\Python23\lib\os.pyc matches C:\Python23\lib\os.py > import os # precompiled from C:\Python23\lib\os.pyc > etc... > > traceback is the stack trace. So this may give you more specific > information about the location and type of failure. Give it a try and > let us know what it says! > > Kent > > At 12:29 PM 8/12/2004 +0200, nik wrote: > >> hi, >> >> I've compiled the example in the Extending and Embedding tutorial >> section 2.1 (creating an module with a couple of string objects), and >> I get the error >> >> 'import site' failed; use -v for traceback >> >> even though the correct output is then printed to the screen. >> >> What does this mean? >> Do I need to post my code here (I've made a few modifications)? >> How do I do the -v for traceback, and would it be useful to me? > > > From alipolatel at yahoo.com Thu Aug 12 13:43:41 2004 From: alipolatel at yahoo.com (Ali Polatel) Date: Thu Aug 12 13:43:44 2004 Subject: [Tutor]Dos Command Message-ID: <20040812114341.27758.qmail@web61001.mail.yahoo.com> This command >>> import os >>> st_in, st_out = os.popen2('mount') >>> st_out.readlines() gives this error: AttributeError: 'tuple' object has no attribute 'readlines' --------------------------------- Do you Yahoo!? Yahoo! Mail is new and improved - Check it out! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040812/572c8329/attachment.htm From alipolatel at yahoo.com Thu Aug 12 13:55:18 2004 From: alipolatel at yahoo.com (Ali Polatel) Date: Thu Aug 12 13:55:21 2004 Subject: [Tutor] Self-Deleting Message-ID: <20040812115518.43856.qmail@web61008.mail.yahoo.com> I have written a programme ... I also want to do a demo version of it which will delete itself after some days... It should find its path in the computer it is saved and delete itself or make himself useless Can a programme delete itself? regards --------------------------------- Do you Yahoo!? Yahoo! Mail Address AutoComplete - You start. We finish. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040812/1d6cd266/attachment.html From vicki at thepenguin.org Thu Aug 12 14:41:23 2004 From: vicki at thepenguin.org (vicki@thepenguin.org) Date: Thu Aug 12 14:43:36 2004 Subject: [Tutor] [OT] Linux In-Reply-To: <005801c47ff2$edab3490$6401a8c0@xp> References: <20040811180722.50605.qmail@web51102.mail.yahoo.com> <005801c47ff2$edab3490$6401a8c0@xp> Message-ID: <35503.12.223.198.92.1092314483.squirrel@12.223.198.92> > For playing the old macjine should be OK, but laptops can > be tricky unless you can find a Linux build specifically > for that - IBM Thinkpads are good bets. The problem is > lots of unusual devices. Modern laptops and distros will > be no problem but an old laptop will need either a slimmed > down distro or an old distro to fit that 2G disk with > space for work. > >> distribution(s) will run well on a machine that old? A lot also depends on how serious you intend to get. If you want to know the guts of Linux, nothing beats Slackware which has few gui tools and requires you to edit files to change settings. It has a steaper learning curve but is well worth it if you want to become an admin since you will understand what the gui-based admin tools used by the other distros are doing to accomplish the same things. I have been working with Linux since 1995, started with Slack, went to RedHat and SuSE, and then came back to Slack when I noticed my skills were tied into the gui tools rather than the filesystem itself. If you need some specific help, either join a LUG (Linux User's Group) or email me off-line. I use Windows only when I have to; I love Linux. --vicki From klas.martelleur at telia.com Thu Aug 12 17:09:19 2004 From: klas.martelleur at telia.com (Klas Marteleur) Date: Thu Aug 12 16:59:39 2004 Subject: [Tutor] Error handling in functions / main program Message-ID: <200408121709.19091.klas.martelleur@telia.com> Hi My convert program that should convert one text file to another text file is now built of three functions: def readInput(inputFile): Which opens and reads a file into a list and splits it to elements. It returns a list. def modifyList(inputList,latestRevision): Which takes the "splited" list and a 1 or a 0 as latestRevison to perform or not perform some "extra" modifications on the list. This function returns a modified list. def writeListToFile(inputList, outputFile): This function writes the modified list (inputList) to a file(outputFile). Returns nothing and a: if __name__=='__main__': which executes the functions very basic. No user input yet ...and i am also planing to write a little GUI in another file ----------------------------------------------------------- Now to my questions: How much and what type of error handling should be handled by: 1. The functions 2 The main program / GUI program. I mean i could add a lot of extra error checking in the functions (... so that correct inputs are used etc)? Or should that be the responsebility of the main program to asure that the input to the functions are correct? Then what type of error handling should be located in the functions? ----------------------------------------------------------- I hope my questions wasnt to confusing (english is not my native language). Kind regards Klas From mhansen at cso.atmel.com Thu Aug 12 17:21:59 2004 From: mhansen at cso.atmel.com (Mike Hansen) Date: Thu Aug 12 17:22:02 2004 Subject: [Tutor] Dual interface app Message-ID: <411B8B17.4010600@cso.atmel.com> I'm thinking of making an program that can be run from the command line or through a web page. The program requires a couple of arguments. At first I thought I could check the command line arguments, and if they didn't exist check the cgi form values. However, I started running into problems when I thought this out further. What if someone runs it from a command line and forgets to add the arguments? The program will check for command line arguments, then it will check the cgi form values and assume it's being called from the web interface. The responses would have to be either in text or html. One solution I thought of was to get the command line interface working in one program. Then write another program for the web interface importing the command line program and using the common functions. Does anyone have any other ideas? Is there a way to detect if a program is being called from the command line vs web without too much voodoo? Mike From pythonTutor at venix.com Thu Aug 12 17:34:29 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Thu Aug 12 17:34:35 2004 Subject: [Tutor] Error handling in functions / main program In-Reply-To: <200408121709.19091.klas.martelleur@telia.com> References: <200408121709.19091.klas.martelleur@telia.com> Message-ID: <1092324868.4072.81.camel@laptop.venix.com> This is tough to answer and depends a lot on the context. Different folks are likely to give different responses. My rules of thumb: User input NEVER causes a program failure. try/except catches ALL errors and provides a (hopefully) useful error message and a chance to provide valid input. If the program fails in an unexpected area, report the failure and exit. This is likely to be a blanket try/except in main. It does NOT try to keep the program running, but simply provides a graceful shutdown. I like to email program traces back to me so that I can quickly respond to problems. I think that each try/except should be carefully programmed to deal with EXPECTED errors. A try/except that covers too much will likely do the wrong thing when presented with the unexpected error. My programs usually have only a handful of try/except statements usually related to user-input errors, network errors, and those fairly rare cases where processing errors are expected and there is a reasonable recovery strategy. On Thu, 2004-08-12 at 11:09, Klas Marteleur wrote: > ...and i am also planing to write a little GUI in another file > ----------------------------------------------------------- > Now to my questions: > How much and what type of error handling should be handled by: > 1. The functions > 2 The main program / GUI program. > > I mean i could add a lot of extra error checking in the functions (... so that > correct inputs are used etc)? Or should that be the responsebility of the > main program to asure that the input to the functions are correct? > Then what type of error handling should be located in the functions? > ----------------------------------------------------------- > > I hope my questions wasnt to confusing (english is not my native language). > > Kind regards > Klas > _______________________________________________ > 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 kent_johnson at skillsoft.com Thu Aug 12 17:35:05 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Thu Aug 12 17:35:09 2004 Subject: [Tutor] Error handling in functions / main program In-Reply-To: <200408121709.19091.klas.martelleur@telia.com> References: <200408121709.19091.klas.martelleur@telia.com> Message-ID: <6.1.0.6.0.20040812112511.028eb5c8@mail4.skillsoft.com> Klas, In general I think it is a good idea if functions check there inputs for validity and generate a meaningful error. That way, if the function is used by multiple clients, you don't have to duplicate the checking code. A lot depends on who will be using the program and what the cost is of an error. If the program is just for you and it is easy to set up and fast to run, it might be OK to leave out any error checking and have it terminate with a stack trace when there is an error. You will understand what the stack trace is telling you, kick yourself for your silly mistake, and try again. On the other hand if the program is for use by other people, or if it requires a complex setup or takes a long time to run, you might want to be more careful with your error checking and making helpful error messages. You don't want a program to run for 5 minutes and then crash because you misspelled an argument, and you don't want users to have to come to you and ask you 'what does this mean' because they got a stack trace. For me a lot of error checking is reactive, because you don't know in advance what kinds of errors users will get. Of course you try to think it through in advance, but you will always be surprised. Many errors will be due to unexpected inputs or unexpected environment. When a user comes to you with a problem, ask yourself, "How could I have detected that? What could the program do so the user can figure out the problem himself?" Make the change so you don't get that question any more. Kent At 05:09 PM 8/12/2004 +0200, Klas Marteleur wrote: >Now to my questions: >How much and what type of error handling should be handled by: >1. The functions >2 The main program / GUI program. > >I mean i could add a lot of extra error checking in the functions (... so >that >correct inputs are used etc)? Or should that be the responsebility of the >main program to asure that the input to the functions are correct? >Then what type of error handling should be located in the functions? From kent_johnson at skillsoft.com Thu Aug 12 17:57:18 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Thu Aug 12 17:57:21 2004 Subject: [Tutor] Error handling in functions / main program In-Reply-To: <1092324868.4072.81.camel@laptop.venix.com> References: <200408121709.19091.klas.martelleur@telia.com> <1092324868.4072.81.camel@laptop.venix.com> Message-ID: <6.1.0.6.0.20040812115323.028ed340@mail4.skillsoft.com> Yes, you want to be careful not to hide too much. When a user gets an unexpected error you will want the stack trace. If all you get is a general error message you don't have much to work with. There was a good example of this on the list recently where the main program had a try/except that just printed an error and exited. Without the stack trace there was no way to know what the problem was; when he took out the try/except it was obvious. The logging module can help with this - you can put detailed error messages in a log file and simple messages in the UI. Kent At 11:34 AM 8/12/2004 -0400, Lloyd Kvam wrote: > If the program fails in an unexpected area, report the failure and >exit. This is likely to be a blanket try/except in main. It does NOT >try to keep the program running, but simply provides a graceful >shutdown. I like to email program traces back to me so that I can >quickly respond to problems. From kent_johnson at skillsoft.com Thu Aug 12 18:00:19 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Thu Aug 12 18:00:22 2004 Subject: [Tutor] Dual interface app In-Reply-To: <411B8B17.4010600@cso.atmel.com> References: <411B8B17.4010600@cso.atmel.com> Message-ID: <6.1.0.6.0.20040812115833.028ed5d0@mail4.skillsoft.com> Your solution is a good one - get the command line program working, then write a separate cgi interface to the same functions. You may want to have three modules - the functional module that does the work, the command line interface module and the cgi module. Kent At 09:21 AM 8/12/2004 -0600, Mike Hansen wrote: >I'm thinking of making an program that can be run from the command line or >through a web page. The program requires a couple of arguments. At first I >thought I could check the command line arguments, and if they didn't exist >check the cgi form values. However, I started running into problems when I >thought this out further. What if someone runs it from a command line and >forgets to add the arguments? The program will check for command line >arguments, then it will check the cgi form values and assume it's being >called from the web interface. The responses would have to be either in >text or html. >One solution I thought of was to get the command line interface working in >one program. Then write another program for the web interface importing >the command line program and using the common functions. > >Does anyone have any other ideas? Is there a way to detect if a program is >being called from the command line vs web without too much voodoo? > >Mike >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From alipolatel at yahoo.com Thu Aug 12 18:12:11 2004 From: alipolatel at yahoo.com (Ali Polatel) Date: Thu Aug 12 18:12:16 2004 Subject: [Tutor] Begin on Start-up Message-ID: <20040812161211.91691.qmail@web61008.mail.yahoo.com> Dear Friends, Can a python programme set itself so that it will be launched every start-up? If yes how? Regards --------------------------------- Do you Yahoo!? New and Improved Yahoo! Mail - Send 10MB messages! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040812/b019e6b3/attachment.html From my.mailing.lists at noos.fr Thu Aug 12 18:20:50 2004 From: my.mailing.lists at noos.fr (nik) Date: Thu Aug 12 18:20:55 2004 Subject: [Tutor] 'import site' failed error In-Reply-To: <411B5061.5000606@noos.fr> References: <411B46A0.5080608@noos.fr> <6.1.0.6.0.20040812064630.02a11dd0@mail4.skillsoft.com> <411B5061.5000606@noos.fr> Message-ID: <411B98E2.5060606@noos.fr> I've drawn a blank trying to find how to get PyRun_SimpleFile to run with the verbose option - I found someone mention it on a wishlist, so perhaps it isn't possible yet. So instead I'm just going to ignore it for the meanwhile, since the program still seems to output correctly (the good ol' head-in-the-sand technique). However, if anyone knows how I can sort it out, please let me know. thanks, nik nik wrote: > Hi Kent, that was a quick reply! > > I've embedded the interpreter in a C app, and so the python file is > called using PyRun_SimpleFile(fp, "demo2.py"); > so, I'm not too sure how to put the -v option in there (I'm doing some > websearching on it now). > > I tried a simple python file like print "hello", but it didn't come up > with the import site error, so I guess it's more to do with the > embedding or my module thingy? > > nik > > Kent Johnson wrote: > >> nik, >> >> I guess it is referring to the -v (verbose) option that you can pass >> to python when you start it up: >> D:\Projects>python -v >> # installing zipimport hook >> import zipimport # builtin >> # installed zipimport hook >> # C:\Python23\lib\site.pyc matches C:\Python23\lib\site.py >> import site # precompiled from C:\Python23\lib\site.pyc >> # C:\Python23\lib\os.pyc matches C:\Python23\lib\os.py >> import os # precompiled from C:\Python23\lib\os.pyc >> etc... >> >> traceback is the stack trace. So this may give you more specific >> information about the location and type of failure. Give it a try and >> let us know what it says! >> >> Kent >> >> At 12:29 PM 8/12/2004 +0200, nik wrote: >> >>> hi, >>> >>> I've compiled the example in the Extending and Embedding tutorial >>> section 2.1 (creating an module with a couple of string objects), >>> and I get the error >>> >>> 'import site' failed; use -v for traceback >>> >>> even though the correct output is then printed to the screen. >>> >>> What does this mean? >>> Do I need to post my code here (I've made a few modifications)? >>> How do I do the -v for traceback, and would it be useful to me? >> >> >> >> > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From my.mailing.lists at noos.fr Thu Aug 12 18:42:34 2004 From: my.mailing.lists at noos.fr (nik) Date: Thu Aug 12 18:42:39 2004 Subject: [Tutor] Creating a complex python object Message-ID: <411B9DFA.5090709@noos.fr> hi again, I'm trying to pass a complicated structure from my C++ app to a python script, so that my users have a chance to alter it if they want. I'd like to provide example scripts that can serialise the data into files, or create entries into a database etc. The structure is a mix of lists, strings, and lists of lists - I suppose in a simplified way it looks like (in C++); using namespace std; typedef list listOfStrings; typedef struct { listOfStrings subData; string subTitle; string subHeading; } subComponent; typedef list listOfSubcomponenets; typedef { listOfSubcomponents theData; string Title; string otherStuff; } myStructure; With a filled myStructure instance being the object I want to pass to the python script. I've only just started looking at python, but it's looking like it's possible. From the example of embedding python in the tutorial, it shows me how to create an object with a couple of strings as attributes. I can see that I could make these objects lists, but I'm wondering what to do about the inner list (listOfStrings in my example above). I'm wondering if I'm on the right track with these views of the problem; * I could generate the whole thing adding lists to lists, but I'm not sure if the user would find that easy to navigate through the PyObject (ie the object would have an attribute called 'theData', but then what? Do I tell them go to the first item of theData and that's a list? To them it wouldn't be called subData, it'd just be an item). * I could create a PyObject that's the subComponent, and put that in the myStructure PyObject. I tried this and got a segmentation fault so I've done something wrong (not suprisingly, since I haven't got a clue what I'm doing yet). * The boost::python library seems to be suggesting that it can create the PyObject automatically (abracadabra!), although I've not gone into this in depth. Is that true? Is this the right list for this kind of question, or should I be going to C++-sig? thanks, nik From peter1002 at pagodagamedatabase.com Thu Aug 12 18:57:03 2004 From: peter1002 at pagodagamedatabase.com (Peter Rootham-Smith) Date: Thu Aug 12 18:56:57 2004 Subject: [Tutor] Limits in Python for number of lines / functions / classes / etc In-Reply-To: <20040812153459.515F61E4015@bag.python.org> References: <20040812153459.515F61E4015@bag.python.org> Message-ID: Hi there, I'm new to Python and am considering using it to do something like Nat's World, that is a slideshow you can point and click and move around and do things. I'm hoping to use pygame and make something cross-platform (I develop on a Mac.) Don't know easy this really is. I'm going to be generating Python code from a set of definition files. What are the limits in Python for number of lines etc that I might hit? I've seen there was a limit on the number of lines in a file. Thanks for any help, Peter. From project5 at redrival.net Thu Aug 12 19:10:50 2004 From: project5 at redrival.net (Andrei) Date: Thu Aug 12 19:11:32 2004 Subject: [Tutor] Re: Begin on Start-up References: <20040812161211.91691.qmail@web61008.mail.yahoo.com> Message-ID: <1a9c1z2lu6n8o$.o65cr20co9o9.dlg@40tude.net> Ali Polatel wrote on Thu, 12 Aug 2004 09:12:11 -0700 (PDT): > Dear Friends, > Can a python programme set itself so that it will be launched every start-up? > If yes how? Running on Windows? Make a shortcut to it in Start -> Programs -> Startup. If you want to avoid doing this manually, include it in the installer (NSIS for example) or in the program itself - not sure which module you'd need for that, but presumably win32all can help. -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From project5 at redrival.net Thu Aug 12 19:20:35 2004 From: project5 at redrival.net (Andrei) Date: Thu Aug 12 19:21:16 2004 Subject: [Tutor] Re: Limits in Python for number of lines / functions / classes / etc References: <20040812153459.515F61E4015@bag.python.org> Message-ID: <82npr24rgt3s.flgl0r6doisv$.dlg@40tude.net> Peter Rootham-Smith wrote on Thu, 12 Aug 2004 17:57:03 +0100: Hi, > I'm new to Python and am considering using it to do something like > Nat's World, that is a slideshow you can point and click and move > around and do things. I'm hoping to use pygame and make something > cross-platform (I develop on a Mac.) Don't know easy this really is. It's not trivial, but it doesn't sound extremely hard neither. > I'm going to be generating Python code from a set of definition files. > What are the limits in Python for number of lines etc that I might hit? > I've seen there was a limit on the number of lines in a file. I don't know of any file size limit. The largest piece of Python code I've ever handled is about 7 megabytes of code in a single .py file. Worked OK. The code was (obviously) not hand-written, but it was data stored as Python code (with str and eval). But why would you need to generate such huge amounts of code? Wouldn't it be better to save and load data in a bsddb? -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From vicki at thepenguin.org Thu Aug 12 19:21:17 2004 From: vicki at thepenguin.org (vicki@thepenguin.org) Date: Thu Aug 12 19:23:31 2004 Subject: [Tutor] Looping problem Message-ID: <18667.206.53.226.235.1092331277.squirrel@206.53.226.235> Okay, I am trying to parse some data which looks something like this: ab11 04142069 08000000006E 0414106A 10169100000000000061 10169000000000000060 1016934129CD4CCB201E 10169200000000000062 10169500000000000065 10169400000000000064 20170000000281082A07D4021A0000000815 What I need to do is move to the point just after the ab command, and then send an '\x02' for each , send an '\x03' for each , read in each after sending the , and recognize when I reach the end of data and send an '\x04' for the and receive the two s. I wrote the following: LTRD_START = False LTRD_END = False for readString in infile.readlines(): word = "" #Find our place in the input file if re.search("Load Time Resolve Data",readString): LTRD_START = True else: if re.search("ab11",readString): print "Do Nothing" elif LTRD_START: #Strip off beginning whitespace readString.lstrip() #Strip off and send [02] on port s = string.lstrip(readString) readString = string.lstrip(s,'') port.write('\x02') print readString #Reset loop variable INSIDE = False #While not at the end of the data while not LTRD_END: for byte in readString: #Check to see if it is a comm word like if byte == '<': INSIDE = True word = byte elif INSIDE and byte != '>': word += byte elif INSIDE and byte == '>': word += byte #Check to see if this is the end of the data if word == '': port.write('\x03') result = port.read() elif word == '': LTRD_END = True result = port.read() print result result = port.read() print result break #Since this is the end of a comm word, #reset the loop variable INSIDE = False elif INSIDE == False: port.write(byte) But I've got something wrong, because it loops infinitely and doesn't kick out when it hits the . Can anyone else see it? Vicki "A pessimist sees the difficulty in every opportunity; an optimist sees the opportunity in every difficulty." -- Winston Churchill From chris.irish at libertydistribution.com Thu Aug 12 19:31:50 2004 From: chris.irish at libertydistribution.com (Chris Irish) Date: Thu Aug 12 19:31:59 2004 Subject: [Tutor] Me again In-Reply-To: <007001c47ff6$2b0b4de0$bc4ebb18@hochstein> References: <007001c47ff6$2b0b4de0$bc4ebb18@hochstein> Message-ID: <411BA986.7060702@libertydistribution.com> jason hochstein wrote: > This is what I get when using the %. > > l_input=[] > > while True: > s = raw_input("Type number. Hit enter for more or type quit to > finish: ") > > > if s == "quit": > break > else: > l_input.append(float(s)) > > > for i in l_input: > average = sum(l_input) / len(l_input) > middle = len(l_input) % 2 > > > print "The mean of this list is ",average > print "The median of this list is",middle > > Here is what I get: > >> The mean of this list is 5.5 > The median of this list is 0 Is the median not what you were expecting? You also didn't show what numbers you entered at the prompt. However, when I run this i get the correct avg, but the % operator you used won't return the median. Instead you getting the value of the remainder of your division i.e. 6%2=0 , and 7%2=1. If you want the middle value just find the length of the list and divide by two. But if the length isn't a even number you'll have to find the avg of the two middle values. Hope that helps.......Chris >------------------------------------------------------------------------ > >_______________________________________________ > > From project5 at redrival.net Thu Aug 12 19:34:48 2004 From: project5 at redrival.net (Andrei) Date: Thu Aug 12 19:35:31 2004 Subject: [Tutor] Re: Self-Deleting References: <20040812115518.43856.qmail@web61008.mail.yahoo.com> Message-ID: Ali Polatel wrote on Thu, 12 Aug 2004 04:55:18 -0700 (PDT): > I have written a programme ... > I also want to do a demo version of it which will delete itself after some days... > It should find its path in the computer it is saved and delete itself or make himself useless > Can a programme delete itself? A python script can delete itself and it knows where it's located (look at sys.argv). But this is really a very silly and entirely useless kind of protection. All the user would have to do, is make a backup. If you want a demo version, it's better to distribute a version which is not feature-complete. Depending on how paranoid you are, you could leave out certain reasonably important functionality completely (e.g. by not shipping modules with the demo which take care of printing reports or importing data - in this case it's impossible to crack the program, since that functionality is simply not present - a cracker would have to implement the missing modules, or steal them from a registered distro) or you could disable/cripple the functionality and re-enable it once the user enters a code (in this case, it's easier to crack the program, but it's also less hassle for you and your customers). Whatever you do, keep in mind that it's relatively simple to go from Python bytecode to Python source code, even when packed with py2exe or similar tools, so elaborate protections schemes are pretty much pointless. Last but not least, ask yourself if your program truly is worth paying for. No disrespect meant, but you might be better off giving the stuff away than going through the hassle of setting up a system for payments, registrations, etc. and getting some small change or nothing at all in return. Does it offer something new, or does it do something significantly better than its competition (don't forget competing open source/freeware products!)? If it doesn't, people won't pay for it anyway and you've wasted your time. -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From python_newbie at vedorian.com Thu Aug 12 19:38:43 2004 From: python_newbie at vedorian.com (Kevin) Date: Thu Aug 12 19:39:14 2004 Subject: [Tutor] The best website to learn Python? Message-ID: <006101c48093$36968b00$30e57218@basp.phub.net.cable.rogers.com> Hello, Well I am a complete newbie to programming of any kind. I had downloaded a piece of python code and took a look at is (a game to be exact). I took a look at the code and just decided that I would like to try and learn python so that I could create my own game someday. The question I have is what is the best python related site for the complete newbie to learn from? I have looked at python.org but it seems a little over the top. I would like to start with something that explains everything in detail. Thanks for any suggestions. Kevin --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.726 / Virus Database: 481 - Release Date: 7/22/04 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040812/cf4c58b6/attachment.htm From kent_johnson at skillsoft.com Thu Aug 12 19:39:36 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Thu Aug 12 19:39:42 2004 Subject: [Tutor] 'import site' failed error In-Reply-To: <411B98E2.5060606@noos.fr> References: <411B46A0.5080608@noos.fr> <6.1.0.6.0.20040812064630.02a11dd0@mail4.skillsoft.com> <411B5061.5000606@noos.fr> <411B98E2.5060606@noos.fr> Message-ID: <6.1.0.6.0.20040812133731.029bd238@mail4.skillsoft.com> You might try to sort out whether it is your embedding that is the problem or your extension code. Does your embedded interpreter work to do something simple like print "Hello", when your extension is not installed? Can you use your extension from the interactive interpreter? import site is something that happens when the interpreter starts up so I suspect the problem is with the embedding, not the extension... Kent At 06:20 PM 8/12/2004 +0200, nik wrote: >I've drawn a blank trying to find how to get PyRun_SimpleFile to run with >the verbose option - I found someone mention it on a wishlist, so perhaps >it isn't possible yet. > >So instead I'm just going to ignore it for the meanwhile, since the >program still seems to output correctly (the good ol' head-in-the-sand >technique). However, if anyone knows how I can sort it out, please let me know. > >thanks, >nik > >nik wrote: > >>Hi Kent, that was a quick reply! >> >>I've embedded the interpreter in a C app, and so the python file is >>called using PyRun_SimpleFile(fp, "demo2.py"); >>so, I'm not too sure how to put the -v option in there (I'm doing some >>websearching on it now). >> >>I tried a simple python file like print "hello", but it didn't come up >>with the import site error, so I guess it's more to do with the embedding >>or my module thingy? >> >>nik >> >>Kent Johnson wrote: >> >>>nik, >>> >>>I guess it is referring to the -v (verbose) option that you can pass to >>>python when you start it up: >>>D:\Projects>python -v >>># installing zipimport hook >>>import zipimport # builtin >>># installed zipimport hook >>># C:\Python23\lib\site.pyc matches C:\Python23\lib\site.py >>>import site # precompiled from C:\Python23\lib\site.pyc >>># C:\Python23\lib\os.pyc matches C:\Python23\lib\os.py >>>import os # precompiled from C:\Python23\lib\os.pyc >>>etc... >>> >>>traceback is the stack trace. So this may give you more specific >>>information about the location and type of failure. Give it a try and >>>let us know what it says! >>> >>>Kent >>> >>>At 12:29 PM 8/12/2004 +0200, nik wrote: >>> >>>>hi, >>>> >>>>I've compiled the example in the Extending and Embedding tutorial >>>>section 2.1 (creating an module with a couple of string objects), and I >>>>get the error >>>> >>>>'import site' failed; use -v for traceback >>>> >>>>even though the correct output is then printed to the screen. >>>> >>>>What does this mean? >>>>Do I need to post my code here (I've made a few modifications)? >>>>How do I do the -v for traceback, and would it be useful to me? >>> >>> >>> >> >> >>_______________________________________________ >>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 project5 at redrival.net Thu Aug 12 19:45:47 2004 From: project5 at redrival.net (Andrei) Date: Thu Aug 12 19:46:29 2004 Subject: [Tutor] Re: The best website to learn Python? References: <006101c48093$36968b00$30e57218@basp.phub.net.cable.rogers.com> Message-ID: Kevin wrote on Thu, 12 Aug 2004 13:38:43 -0400: Hi Kevin, > Well I am a complete newbie to programming of any kind. I had downloaded a piece of python code and took a look at is (a game to be exact). I took a look at the code and just decided that I would like to try and learn python so that I could create my own game someday. The question I have is what is the best python related site for the complete newbie to learn from? I have looked at python.org but it seems a little over the top. I would like to start with something that explains everything in detail. Have a look at the links on: http://python.org/doc/Intros.html I particularly liked "Learning to program", "How to think like a computer scientist" and "Dive into Python" (the last one is not really for beginners I think), but there are lots of good tutorials linked on that page - you're bound to find something that suits your way of thinking/learning. -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From pythonTutor at venix.com Thu Aug 12 19:53:49 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Thu Aug 12 19:53:53 2004 Subject: [Tutor] Looping problem In-Reply-To: <18667.206.53.226.235.1092331277.squirrel@206.53.226.235> References: <18667.206.53.226.235.1092331277.squirrel@206.53.226.235> Message-ID: <1092333227.4946.6.camel@laptop.venix.com> On Thu, 2004-08-12 at 13:21, vicki@thepenguin.org wrote: snipped > while not LTRD_END: > for byte in readString: I do not see any place in this loop where readString gets advanced. Should result really be readString??? Do you need to bind readString to result at the end of the for loop??? > #Check to see if it is a comm word like > if byte == '<': > INSIDE = True > word = byte > elif INSIDE and byte != '>': > word += byte > elif INSIDE and byte == '>': > word += byte > #Check to see if this is the end of the data > if word == '': > port.write('\x03') > result = port.read() > elif word == '': > LTRD_END = True > result = port.read() > print result > result = port.read() > print result > break > #Since this is the end of a comm word, > #reset the loop variable > INSIDE = False > elif INSIDE == False: > port.write(byte) > > But I've got something wrong, because it loops infinitely and doesn't kick > out when it hits the . Can anyone else see it? > > Vicki > > "A pessimist sees the difficulty in every opportunity; an optimist sees > the opportunity in every difficulty." > -- Winston Churchill > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From John.Ertl at fnmoc.navy.mil Thu Aug 12 20:03:00 2004 From: John.Ertl at fnmoc.navy.mil (Ertl, John) Date: Thu Aug 12 19:55:20 2004 Subject: [Tutor] removing from a list Message-ID: All, I am having a problem with remove(). Remove seems to make the for each loop skip over the element that follows the removed element. I have been able to reproduce my problem on a very simple scale. >>>a = ["this",1,"that",5,"what"] >>>for each in a: print each if each == "that" or each == 5: a.remove(each) this 1 that what You can see...the 5 was never checked in the loop but if I print out a...5 is still part of the list. >>> a ['this', 1, 5, 'what'] The element "that" was successfully removed but 5 was never checked and therefore never removed...Is this how remove should work? I also noticed that if I do not have a logical and/or in the checking or I do not actually remove the element there is no problem. Thanks John Ertl From vicki at thepenguin.org Thu Aug 12 20:00:16 2004 From: vicki at thepenguin.org (vicki@thepenguin.org) Date: Thu Aug 12 20:02:31 2004 Subject: [Tutor] Looping problem In-Reply-To: <1092333227.4946.6.camel@laptop.venix.com> References: <18667.206.53.226.235.1092331277.squirrel@206.53.226.235> <1092333227.4946.6.camel@laptop.venix.com> Message-ID: <53824.206.53.226.235.1092333616.squirrel@206.53.226.235> > On Thu, 2004-08-12 at 13:21, vicki@thepenguin.org wrote: > snipped >> while not LTRD_END: >> for byte in readString: > > I do not see any place in this loop where readString gets advanced. > Should result really be readString??? > Do you need to bind readString to result at the end of the for loop??? Doesn't the "for readString in infile.readlines():" automatically iterate through the lines in the file resetting readString each time? --Vicki From kent_johnson at skillsoft.com Thu Aug 12 20:05:10 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Thu Aug 12 20:05:17 2004 Subject: [Tutor] Looping problem In-Reply-To: <18667.206.53.226.235.1092331277.squirrel@206.53.226.235> References: <18667.206.53.226.235.1092331277.squirrel@206.53.226.235> Message-ID: <6.1.0.6.0.20040812135847.02a0f110@mail4.skillsoft.com> Vicki, There is a problem with the loop nesting. The loop "while not LTRD_END:" is inside the readlines() loop. What happens is the program repeats the while not LTRD_END: forever - it gets stuck on the first line. In other words, it keeps processing the first line over and over. Since this line has no , the while loop never exits. One way to fix this might be to put a conditional break at the end of the readlines() loop like this: if LTRD_END: break Another thing I noticed is the indentation is very inconsistent. You are using a mix of tabs and spaces to indent lines. This is not a good idea in Python - you should choose one way to indent. Many people use four spaces, but you can use tabs if you want. The important thing is to be consistent. Kent At 12:21 PM 8/12/2004 -0500, vicki@thepenguin.org wrote: >Okay, I am trying to parse some data which looks something like this: > > > ab11 > 04142069 > 08000000006E > 0414106A > 10169100000000000061 > 10169000000000000060 > 1016934129CD4CCB201E > 10169200000000000062 > 10169500000000000065 > 10169400000000000064 > 20170000000281082A07D4021A0000000815 > >What I need to do is move to the point just after the ab command, and then >send an '\x02' for each , send an '\x03' for each , read in each > after sending the , and recognize when I reach the end of data >and send an '\x04' for the and receive the two s. I wrote the >following: > > > LTRD_START = False > LTRD_END = False > > for readString in infile.readlines(): > word = "" > #Find our place in the input file > if re.search("Load Time Resolve Data",readString): > LTRD_START = True > else: > if re.search("ab11",readString): > print "Do Nothing" > elif LTRD_START: > #Strip off beginning whitespace > readString.lstrip() > #Strip off and send [02] on port > s = string.lstrip(readString) > readString = string.lstrip(s,'') > port.write('\x02') > print readString > > #Reset loop variable > INSIDE = False > #While not at the end of the data > while not LTRD_END: > for byte in readString: > #Check to see if it is a comm word like > if byte == '<': > INSIDE = True > word = byte > elif INSIDE and byte != '>': > word += byte > elif INSIDE and byte == '>': > word += byte > #Check to see if this is the end of the data > if word == '': > port.write('\x03') > result = port.read() > elif word == '': > LTRD_END = True > result = port.read() > print result > result = port.read() > print result > break > #Since this is the end of a comm word, > #reset the loop variable > INSIDE = False > elif INSIDE == False: > port.write(byte) > >But I've got something wrong, because it loops infinitely and doesn't kick >out when it hits the . Can anyone else see it? > >Vicki > >"A pessimist sees the difficulty in every opportunity; an optimist sees >the opportunity in every difficulty." >-- Winston Churchill > > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From vicki at thepenguin.org Thu Aug 12 20:06:29 2004 From: vicki at thepenguin.org (vicki@thepenguin.org) Date: Thu Aug 12 20:08:43 2004 Subject: [Tutor] Looping problem In-Reply-To: <6.1.0.6.0.20040812135847.02a0f110@mail4.skillsoft.com> References: <18667.206.53.226.235.1092331277.squirrel@206.53.226.235> <6.1.0.6.0.20040812135847.02a0f110@mail4.skillsoft.com> Message-ID: <24679.206.53.226.235.1092333989.squirrel@206.53.226.235> > Vicki, > > There is a problem with the loop nesting. The loop "while not LTRD_END:" > is > inside the readlines() loop. What happens is the program repeats the while > not LTRD_END: forever - it gets stuck on the first line. In other words, > it > keeps processing the first line over and over. Since this line has no > , the while loop never exits. > > One way to fix this might be to put a conditional break at the end of the > readlines() loop like this: > if LTRD_END: > break Thanks. I'll try that. > > Another thing I noticed is the indentation is very inconsistent. You are > using a mix of tabs and spaces to indent lines. This is not a good idea in > Python - you should choose one way to indent. Many people use four spaces, > but you can use tabs if you want. The important thing is to be consistent. > > Kent Yes, unfortunately every time I paste into my mailer, I have to fix the spacing, hence the mixture because the mailer recognizes tabs as external commands to go to the next button, etc. It is not that way originally. I use the default tabbing in Python. --vicki From pythonTutor at venix.com Thu Aug 12 20:16:10 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Thu Aug 12 20:16:13 2004 Subject: [Tutor] Looping problem In-Reply-To: <53824.206.53.226.235.1092333616.squirrel@206.53.226.235> References: <18667.206.53.226.235.1092331277.squirrel@206.53.226.235> <1092333227.4946.6.camel@laptop.venix.com> <53824.206.53.226.235.1092333616.squirrel@206.53.226.235> Message-ID: <1092334570.4946.25.camel@laptop.venix.com> On Thu, 2004-08-12 at 14:00, vicki@thepenguin.org wrote: > > On Thu, 2004-08-12 at 13:21, vicki@thepenguin.org wrote: > > snipped > >> while not LTRD_END: > >> for byte in readString: > > > > I do not see any place in this loop where readString gets advanced. > > Should result really be readString??? > > Do you need to bind readString to result at the end of the for loop??? > > Doesn't the "for readString in infile.readlines():" automatically iterate > through the lines in the file resetting readString each time? only if the program breaks back out to advance that loop level. readString is within the while not LTRD_END loop. Perhaps you really want to break on LTRD_END? I did not really try to understand the code as a whole, I just saw that you will likely be processing the same readString over and over. > > --Vicki > > _______________________________________________ > 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 vicki at thepenguin.org Thu Aug 12 20:15:32 2004 From: vicki at thepenguin.org (vicki@thepenguin.org) Date: Thu Aug 12 20:17:47 2004 Subject: [Tutor] Looping problem In-Reply-To: <6.1.0.6.0.20040812135847.02a0f110@mail4.skillsoft.com> References: <18667.206.53.226.235.1092331277.squirrel@206.53.226.235> <6.1.0.6.0.20040812135847.02a0f110@mail4.skillsoft.com> Message-ID: <11549.206.53.226.235.1092334532.squirrel@206.53.226.235> > Vicki, > > There is a problem with the loop nesting. The loop "while not LTRD_END:" > is > inside the readlines() loop. What happens is the program repeats the while > not LTRD_END: forever - it gets stuck on the first line. In other words, > it > keeps processing the first line over and over. Since this line has no > , the while loop never exits. > > One way to fix this might be to put a conditional break at the end of the > readlines() loop like this: > if LTRD_END: But wait, if it is processing the first line only, it will never set the LTRD_END to True since the only EOT is in the last line. I actually had to change my loop to check for an LINE_END flag which gets reset to True when I hit a and reset to False inside to allow the loop to process. Thanks. --vicki From mhansen at cso.atmel.com Thu Aug 12 20:19:18 2004 From: mhansen at cso.atmel.com (Mike Hansen) Date: Thu Aug 12 20:19:22 2004 Subject: [Tutor] Re: Dual interface app In-Reply-To: <20040812172334.844731E4008@bag.python.org> References: <20040812172334.844731E4008@bag.python.org> Message-ID: <411BB4A6.7070403@cso.atmel.com> Thanks Kent. Three modules also occurred to me, and I'll probably do just that. I just needed to verify if I was on the right track. What's nice about Python is that any program/script can become a module. Mike > > Subject: > Re: [Tutor] Dual interface app > From: > Kent Johnson > Date: > Thu, 12 Aug 2004 12:00:19 -0400 > To: > tutor@python.org > > To: > tutor@python.org > > > Your solution is a good one - get the command line program working, > then write a separate cgi interface to the same functions. You may > want to have three modules - the functional module that does the work, > the command line interface module and the cgi module. > > Kent > > At 09:21 AM 8/12/2004 -0600, Mike Hansen wrote: > >> I'm thinking of making an program that can be run from the command >> line or through a web page. The program requires a couple of >> arguments. At first I thought I could check the command line >> arguments, and if they didn't exist check the cgi form values. >> However, I started running into problems when I thought this out >> further. What if someone runs it from a command line and forgets to >> add the arguments? The program will check for command line arguments, >> then it will check the cgi form values and assume it's being called >> from the web interface. The responses would have to be either in text >> or html. >> One solution I thought of was to get the command line interface >> working in one program. Then write another program for the web >> interface importing the command line program and using the common >> functions. >> >> Does anyone have any other ideas? Is there a way to detect if a >> program is being called from the command line vs web without too much >> voodoo? >> >> Mike >> _______________________________________________ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor > > From John.Ertl at fnmoc.navy.mil Thu Aug 12 20:30:34 2004 From: John.Ertl at fnmoc.navy.mil (Ertl, John) Date: Thu Aug 12 20:22:49 2004 Subject: [Tutor] removing from a list Message-ID: Lloyd, Thanks I will give that a try...l have not played with comprehension or filtering before. John Ertl -----Original Message----- From: Lloyd Kvam [mailto:lkvam@venix.com] Sent: Thursday, August 12, 2004 11:09 To: Ertl, John Cc: Tutor Python Subject: Re: [Tutor] removing from a list removing elements from the list that you are iterating through does not work well. The common work-around is to iterate through a copy of the list: for each in a[:]: # use slice notation to create a copy of list Another good alternative is to build a new list, possibly binding it to the same name as the original list. A list comprehension works well for this: a = [each for each in a if each not in ("that",5)] If you make the filtering expression a function, you can also use the filter builtin: a = filter(func, a) I now generally prefer creating a new list using a list comprehension. On Thu, 2004-08-12 at 14:03, Ertl, John wrote: > All, > > I am having a problem with remove(). > Remove seems to make the for each loop skip over the element that follows > the removed element. > > I have been able to reproduce my problem on a very simple scale. > > >>>a = ["this",1,"that",5,"what"] > > >>>for each in a: > print each > if each == "that" or each == 5: > a.remove(each) > > this > 1 > that > what > > You can see...the 5 was never checked in the loop but if I print out a...5 > is still part of the list. > >>> a > ['this', 1, 5, 'what'] > > The element "that" was successfully removed but 5 was never checked and > therefore never removed...Is this how remove should work? > I also noticed that if I do not have a logical and/or in the checking or I > do not actually remove the element there is no problem. > > Thanks > > John Ertl > _______________________________________________ > 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 kent_johnson at skillsoft.com Thu Aug 12 20:23:22 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Thu Aug 12 20:23:25 2004 Subject: [Tutor] removing from a list In-Reply-To: References: Message-ID: <6.1.0.6.0.20040812141551.028c6018@mail4.skillsoft.com> John, You can't do that :-) There is an undesirable interaction between remove and iteration. It is as if you were using this program: >>> a = ["this",1,"that",5,"what"] >>> i=0 >>> while i>> a ['this', 1, 5, 'what'] Conceptually, when you delete a list item, the next item moves into its place. But the iterator doesn't know you did this, so it increments over the (former) next item. It's not the logical 'or' that triggers the problem, it is having two adjacent list elements that you want to delete. One work around is to process the list from the end, for example: >>> a = ["this",1,"that",5,"what"] >>> i=len(a)-1 >>> while i >= 0: ... if a[i]=='that' or a[i]==5: ... del a[i] ... i -= 1 ... >>> a ['this', 1, 'what'] Kent At 11:03 AM 8/12/2004 -0700, Ertl, John wrote: >All, > >I am having a problem with remove(). >Remove seems to make the for each loop skip over the element that follows >the removed element. > >I have been able to reproduce my problem on a very simple scale. > > >>>a = ["this",1,"that",5,"what"] > > >>>for each in a: > print each > if each == "that" or each == 5: > a.remove(each) > >this >1 >that >what > >You can see...the 5 was never checked in the loop but if I print out a...5 >is still part of the list. > >>> a >['this', 1, 5, 'what'] > >The element "that" was successfully removed but 5 was never checked and >therefore never removed...Is this how remove should work? >I also noticed that if I do not have a logical and/or in the checking or I >do not actually remove the element there is no problem. > >Thanks > >John Ertl >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From pythonTutor at venix.com Thu Aug 12 20:25:48 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Thu Aug 12 20:25:52 2004 Subject: [Tutor] removing from a list In-Reply-To: References: Message-ID: <1092335148.4946.34.camel@laptop.venix.com> removing elements from the list that you are iterating through does not work well. The common work-around is to iterate through a copy of the list: for each in a[:]: # use slice notation to create a copy of list Another good alternative is to build a new list, possibly binding it to the same name as the original list. A list comprehension works well for this: a = [each for each in a if each not in ("that",5)] If you make the filtering expression a function, you can also use the filter builtin: a = filter(func, a) I now generally prefer creating a new list using a list comprehension. On Thu, 2004-08-12 at 14:03, Ertl, John wrote: > All, > > I am having a problem with remove(). > Remove seems to make the for each loop skip over the element that follows > the removed element. > > I have been able to reproduce my problem on a very simple scale. > > >>>a = ["this",1,"that",5,"what"] > > >>>for each in a: > print each > if each == "that" or each == 5: > a.remove(each) > > this > 1 > that > what > > You can see...the 5 was never checked in the loop but if I print out a...5 > is still part of the list. > >>> a > ['this', 1, 5, 'what'] > > The element "that" was successfully removed but 5 was never checked and > therefore never removed...Is this how remove should work? > I also noticed that if I do not have a logical and/or in the checking or I > do not actually remove the element there is no problem. > > Thanks > > John Ertl > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From rmkrauter at yahoo.com Thu Aug 12 20:49:42 2004 From: rmkrauter at yahoo.com (Rich Krauter) Date: Thu Aug 12 20:49:45 2004 Subject: [Tutor] Looping problem Message-ID: <20040812184942.63451.qmail@web51401.mail.yahoo.com> Hi Vicki, Here is what I tried; its not fully tested, but maybe it'll help. I just tried to get rid of some of the nested loops. import cStringIO import sys def tokenize(arg): """ Turn each line into a collection of tokens, and return list of tokens. """ arg = arg.strip() tokens = [] tok = '' for c in arg: if c == '<' or c == '>': if tok: tokens.append(tok) tok = '' continue tok += c return tokens if __name__ == '__main__': # pretend sys.stdout is your port port = sys.stdout # substitute what you really want to send token_map = {'ACK': 'send ACK', 'ETX': 'send ETX', 'STX': 'send STX'} f = """Load Time Resolve Data ab11 04142069 08000000006E 0414106A 10169100000000000061 10169000000000000060 1016934129CD4CCB201E 10169200000000000062 10169500000000000065 10169400000000000064 20170000000281082A07D4021A0000000815 """ # pretend string f is your file strIO = cStringIO.StringIO(f) LTRD_START = False for readString in strIO: if "Load Time Resolve Data" in readString: LTRD_START = True continue if "ab11" in readString: continue if LTRD_START: tt = tokenize(readString) for t in tt: if t == 'EOT': print 'Breaking out of loop ...' break if t in token_map: port.write('%s\n'%token_map[t]) else: print t Good luck. Rich From lobow at brturbo.com Fri Aug 13 03:42:45 2004 From: lobow at brturbo.com (Diego Galho Prestes) Date: Thu Aug 12 21:45:48 2004 Subject: [Tutor] How to cal la method when have classes inside another class Message-ID: <1092361365.6794.0.camel@rossum> Hi! I have this case but dont know how to call it... def Class1: def someMethod(): pass def Class2: def otherMethod(): ???call of someMethod??? I want to call someMethod in otherMethod. How can I do this? Diego From alan.gauld at blueyonder.co.uk Thu Aug 12 22:37:40 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Aug 12 22:39:14 2004 Subject: [Tutor] Deleting System Files? References: <20040812090954.74281.qmail@web61002.mail.yahoo.com> Message-ID: <00fc01c480ac$362f8270$6401a8c0@xp> > Can Python delete system files? Yes provided the process has the right permissions. Did you run it as administrator/root? > I tried it importing the module os and using the > function "os.remove" but the computer asks > "xxx.xxx is a system file.Are you sure to remove xxx.xxx ?" But it might not be able to avoid system messages unless you use the os native API calls...assuming its Windoze. > and the programme gives error... Which error? Alan G. From alan.gauld at blueyonder.co.uk Thu Aug 12 22:43:32 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Aug 12 22:45:16 2004 Subject: [Tutor] Self-Deleting References: <20040812115518.43856.qmail@web61008.mail.yahoo.com> Message-ID: <011a01c480ad$087b1c80$6401a8c0@xp> > Can a programme delete itself? Yes but how best to do it depends on the OS. If its Windoze then writing an entry to the RunOnce registry entry is usually the best way to do it. Next time the user restarts the file gets deleted. (And on Windows that will probably be within a day or so! :-) You can also force a restart but thats a tad unfriendly. You could also set a key that prevents use until the deletion takes place. The RunOnce program should not only delete the file but also clean up the registry etc too of course... Unless you want to make sure that they never reinstall for another free trial, in which case leave one key live... Lots of options. In Unix the options are many and varied including just deleting the file directly, setting cron jobs, etc etc... Alan G. From alan.gauld at blueyonder.co.uk Thu Aug 12 22:48:46 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Aug 12 22:50:19 2004 Subject: [Tutor] Error handling in functions / main program References: <200408121709.19091.klas.martelleur@telia.com> Message-ID: <012101c480ad$c3792310$6401a8c0@xp> > Now to my questions: > How much and what type of error handling should be handled by: > 1. The functions > 2 The main program / GUI program. That's a very profound question with no easy answer. The C language takes the approach that the user checks the inputs before passing them - it leads to faster code. Other languages tend to expect the function to do validation - very common in web page development and in financial apps in COBOL.! Python has the tenet of its better to ask forgivness than permission, which tends to be interpreted as put the function code inside a try except and catch the possible erors. If the data is good there is minimal overhead, if its bad you pay the provce but still get a "safe" program. And of course the function can "raise" exceptions for the client program to catch. So no clear cut answer, but maybe a hint. Alan G. From alan.gauld at blueyonder.co.uk Thu Aug 12 22:53:34 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Aug 12 22:55:09 2004 Subject: [Tutor] Dual interface app References: <411B8B17.4010600@cso.atmel.com> Message-ID: <012601c480ae$6f4f7680$6401a8c0@xp> > problems when I thought this out further. What if someone runs it from a > command line and forgets to add the arguments? The program will check > for command line arguments, then it will check the cgi form values and > assume it's being called from the web interface. So put that check inside a try/except clause and if the cgi lookup fails the except can either supply defaults or use raw_input to prompt the user. if len(sys.argv) == argCount: args = sys.argv else: try: args = getCGIvalues() except ????: # whatever the cgi module raises... args = raw_input('gimme the args ') # now process args... > Does anyone have any other ideas? Is there a way to detect if a program > is being called from the command line vs web without too much voodoo? Not sure what happens to __name__ when its a web app, but my guess is its still __main__... HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/ From alan.gauld at blueyonder.co.uk Thu Aug 12 22:58:16 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Aug 12 22:59:47 2004 Subject: [Tutor] Error handling in functions / main program References: <200408121709.19091.klas.martelleur@telia.com><1092324868.4072.81.camel@laptop.venix.com> <6.1.0.6.0.20040812115323.028ed340@mail4.skillsoft.com> Message-ID: <013d01c480af$1742ea70$6401a8c0@xp> > There was a good example of this on the list recently where the main > program had a try/except that just printed an error and exited. As author of that program I'd better point out that I agree. When testing and debugging avoid catch-all excepts at the top level. Only put that in once you are confident it works and use it to shelter the user from unfriendly error messages. > The logging module can help with this - you can put detailed error messages > in a log file and simple messages in the UI. This too is good advice, even with the catchall except you should log the error and display a friendly message to the user - best of both worlds. In my defence the logging module didn't exist when I wrote the book and dealing with the traceback manually was too advanced for my audience... :-) Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/ From alan.gauld at blueyonder.co.uk Thu Aug 12 23:01:58 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Aug 12 23:03:28 2004 Subject: [Tutor] Begin on Start-up References: <20040812161211.91691.qmail@web61008.mail.yahoo.com> Message-ID: <014701c480af$9b65f900$6401a8c0@xp> > Can a python programme set itself so that it will be launched every start-up? > If yes how? Yes but again it depends on the OS. If you are on Windows you can either create a shortcut in the Start->Programs->Startup group, just as you would to run any program on startup. Or you can put it in the Run registry entry. In Unix systems its usually best to use the shell startup file: .cshrc/.login on csh derivitives and .profile on Bourne shell derivitives If you want it before uuser login you need the startup files which varies from Unix version to vesion, but often found under the etc directories. Alan G. From alan.gauld at blueyonder.co.uk Thu Aug 12 23:06:56 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Aug 12 23:08:28 2004 Subject: [Tutor] Creating a complex python object References: <411B9DFA.5090709@noos.fr> Message-ID: <015001c480b0$4ccded60$6401a8c0@xp> > With a filled myStructure instance being the object I want to pass to > the python script. > > .... > > Is this the right list for this kind of question, or should I be going > to C++-sig? While we may have experts here who can help I suspect its well beyond the scope of the tutor list which is for newbies to Python and Programming too. If you got as far as you have I suspect you are already beyond the stage where this list is for you. I'd try either comp.lang.python or the C++ Sig. The latter should definitely be able to help. Alan G. From alan.gauld at blueyonder.co.uk Thu Aug 12 23:27:20 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Aug 12 23:28:52 2004 Subject: [Tutor] The best website to learn Python? References: <006101c48093$36968b00$30e57218@basp.phub.net.cable.rogers.com> Message-ID: <017101c480b3$26ea09f0$6401a8c0@xp> > The question I have is what is the best python related > site for the complete newbie to learn from? There are several on the Python.org website in the non programmers intro's section. They all have slightly different emphasis. Mine is designed to teach basic programming skills to experienced computer users and uses Python (as well as VBScript and JavaScript) to illustrate the points. Josh Caglieri's is a more hands on approach focussed on Python but at the expense of understanding principles or explaining jargon. How to Think Like a CS focuses on teaching Computer Science principles, and sometimes misses out some of the more practical aspects. (IMHO!) I haven't looked at the LiveWeire one but it gets good feedback. Best thing to do is try one, or two. Find which seems to jive with your way of learning and stick to it. If you hit specific problems post questions here. ny of the above will get you to the point where you should sail through the official tutor with no problems (everyone should do the official tutor because it is really good and covers lots of the clever features of Puython that a beginners tutor can't and is kept up to date with language changes in each release) How to think like... and mine are both available in paper books too. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/ From alan.gauld at blueyonder.co.uk Thu Aug 12 23:39:32 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Aug 12 23:41:02 2004 Subject: [Tutor] How to cal la method when have classes inside another class References: <1092361365.6794.0.camel@rossum> Message-ID: <019e01c480b4$dadd2090$6401a8c0@xp> > Hi! I have this case but dont know how to call it... > > > def Class1: > def someMethod(): > pass > def Class2: > def otherMethod(): > ???call of someMethod??? > > I want to call someMethod in otherMethod. How can I do this? First question. Are you trying to create classes or functions? You are actually creating functions not classes. Well almost, because a function definition needs a pair of parentheses after it. So either you want: class Class1: ... or def Class1(): ... If its a function then you can indeed define nested functions inside. If its a class then the methods should have an instance reference as the first parameter, usually called self: class Class1: def method1(self): pass def method2(self): self.method1() Is that what you want? Or do you really want to create a nested class ala Java? If so I don't know of any way for a methjod of the nested class to call a method of the outer class - the outer class is invisible to the inner. But I confess I've never had a need to use inner classes in Python. Why do you feel you need to resort to this? What are you trying to do that requires it? Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/ From my.mailing.lists at noos.fr Fri Aug 13 01:08:23 2004 From: my.mailing.lists at noos.fr (nik) Date: Fri Aug 13 01:09:33 2004 Subject: [Tutor] Creating a complex python object In-Reply-To: <015001c480b0$4ccded60$6401a8c0@xp> References: <411B9DFA.5090709@noos.fr> <015001c480b0$4ccded60$6401a8c0@xp> Message-ID: <411BF867.7030908@noos.fr> Thanks Alan, I've heard that embedding the interpreter is fairly rare, so I did wonder if this was the right place. I'll move my query on to C++ Si g and hope they're kind to me. In the mean time I'll keep lurking on this list, there's still a lot to python that baffles me (like just what is the difference between a tuple and a list? :-) ). thanks, nik Alan Gauld wrote: >>With a filled myStructure instance being the object I want to pass >> >> >to > > >>the python script. >> >>.... >> >>Is this the right list for this kind of question, or should I be >> >> >going > > >>to C++-sig? >> >> > >While we may have experts here who can help I suspect its well beyond >the scope of the tutor list which is for newbies to Python and >Programming too. If you got as far as you have I suspect you are >already beyond the stage where this list is for you. I'd try either >comp.lang.python or the C++ Sig. The latter should definitely be able >to help. > >Alan G. > > > > From my.mailing.lists at noos.fr Fri Aug 13 01:11:34 2004 From: my.mailing.lists at noos.fr (nik) Date: Fri Aug 13 01:12:39 2004 Subject: [Tutor] Creating a complex python object In-Reply-To: <015001c480b0$4ccded60$6401a8c0@xp> References: <411B9DFA.5090709@noos.fr> <015001c480b0$4ccded60$6401a8c0@xp> Message-ID: <411BF926.5050101@noos.fr> Thanks Alan, I've heard that embedding the interpreter and doing this kind of thins is fairly rare, so I did wonder if this was the right place. I'll move my query on to C++ Si g and hope they're kind to me. In the mean time I'll keep lurking on this list, there's still a lot to python that baffles me (like just what is the difference between a tuple and a list? :-) ). thanks, nik Alan Gauld wrote: >>With a filled myStructure instance being the object I want to pass >> >> >to > > >>the python script. >> >>.... >> >>Is this the right list for this kind of question, or should I be >> >> >going > > >>to C++-sig? >> >> > >While we may have experts here who can help I suspect its well beyond >the scope of the tutor list which is for newbies to Python and >Programming too. If you got as far as you have I suspect you are >already beyond the stage where this list is for you. I'd try either >comp.lang.python or the C++ Sig. The latter should definitely be able >to help. > >Alan G. > > > > From ps_python at yahoo.com Fri Aug 13 01:25:06 2004 From: ps_python at yahoo.com (kumar s) Date: Fri Aug 13 01:25:11 2004 Subject: [Tutor] avoid split function In-Reply-To: <1092361365.6794.0.camel@rossum> Message-ID: <20040812232506.96207.qmail@web53708.mail.yahoo.com> Dear group, I am a newbie to Python. I am grinding my abilities in list datatypes and fuctions. I am trying to avoid .split() function to process a string. My programs follows: m = [] y = [] a = "This is a test" for i in range(0,len(a)): if a[i] == " ": print y elif a[i] != " ": y.append(a[i]) m.append(y[0:]) I wanted to push "This" in to m as m = ['This'] I know i can do this using: c = a.split() I just wanted to avoid using split and make it work. The output I always get is y = ['T','h','i','s','i','s','a','t','e','s','t'] I created m because I wanted to push each element of y(y = ['T','h','i','s']) to m to make it ['This']. Can any one help me please suggest some tricks of how I could do that. Thank you. PS __________________________________ Do you Yahoo!? New and Improved Yahoo! Mail - Send 10MB messages! http://promotions.yahoo.com/new_mail From r2b2 at myway.com Fri Aug 13 02:08:08 2004 From: r2b2 at myway.com (r2b2) Date: Fri Aug 13 02:08:17 2004 Subject: [Tutor] pdf files Message-ID: <20040813000808.3DC8A39B5@mprdmxin.myway.com> looking for a basic code using reportlabs package ( or any package ) to convert an existing text file to a .pdf file. convert document.txt to document.pdf thanks _______________________________________________ No banners. No pop-ups. No kidding. Make My Way your home on the Web - http://www.myway.com From david at graniteweb.com Fri Aug 13 04:53:05 2004 From: david at graniteweb.com (David Rock) Date: Fri Aug 13 04:53:09 2004 Subject: [Tutor] avoid split function In-Reply-To: <20040812232506.96207.qmail@web53708.mail.yahoo.com> References: <1092361365.6794.0.camel@rossum> <20040812232506.96207.qmail@web53708.mail.yahoo.com> Message-ID: <20040813025305.GA8984@wdfs.attbi.com> * kumar s [2004-08-12 16:25]: > Dear group, > I am a newbie to Python. I am grinding my abilities > in list datatypes and fuctions. > > I am trying to avoid .split() function to process a > string. > > My programs follows: > > m = [] > y = [] > > a = "This is a test" > > for i in range(0,len(a)): > if a[i] == " ": > print y > elif a[i] != " ": > y.append(a[i]) > m.append(y[0:]) idx=0 m = [] a = "This is a test" for i in range(0,len(a)): if a[i] != ' ': try: m[idx] = m[idx]+a[i] except: m.append(a[i]) else: idx += 1 Just out of curiosity, why the interest in reinventing the wheel? -- David Rock david@graniteweb.com -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20040812/ffb98d53/attachment.pgp From seamonkeys at gmail.com Fri Aug 13 05:00:19 2004 From: seamonkeys at gmail.com (Britt Green) Date: Fri Aug 13 05:00:27 2004 Subject: [Tutor] Python spawning extra processes Message-ID: <305be88204081220003f5378f1@mail.gmail.com> Hey all! I've encountered something odd that I'm hoping someone can clarify for me. I've coded a very simple chat server in Python, using the Twisted libraries. From Windows XP, I launch it from Idle and do my thing. I then quit it by pressing CTRL-C in the Python shell. If I then go into my Task Manager, I see that the pythonw.exe process started by the program is still there. Executing the script creates another process that doesn't go away when I terminate the program. I noticed this today when I saw I had 30+ pythonw.exe processes going! I'm wondering what's causing this and how to get it to stop. Cheers! Britt From flaxeater at yahoo.com Fri Aug 13 05:11:51 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Fri Aug 13 05:11:55 2004 Subject: [Tutor] Creating a complex python object Message-ID: <20040813031151.90024.qmail@web52604.mail.yahoo.com> >In the mean time I'll keep lurking on this list, there's still a lot to python that baffles me (like just what is the difference between a tuple and a list? :-) ). I thought I would answer the tuple list thing. I did not understand why have tuple's until I learned that tuples being immutable are faster and easier on memory. __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From flaxeater at yahoo.com Fri Aug 13 05:17:35 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Fri Aug 13 05:17:38 2004 Subject: [Tutor] removing from a list Message-ID: <20040813031735.67560.qmail@web52608.mail.yahoo.com> Lloyd Kvam wrote: > >a = [each for each in a if each not in ("that",5)] > > > This comprehension blew my Mind. Let me paraphrase this and please correct me if I'm wronng. return every 'each' in a if that 'each' is not that or 5? is that right? __________________________________ Do you Yahoo!? Yahoo! Mail - You care about security. So do we. http://promotions.yahoo.com/new_mail From flaxeater at yahoo.com Fri Aug 13 05:29:39 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Fri Aug 13 05:29:43 2004 Subject: [Tutor] avoid split function Message-ID: <20040813032939.73828.qmail@web52609.mail.yahoo.com> David Rock wrote: >idx=0 >m = [] >a = "This is a test" > >for i in range(0,len(a)): > if a[i] != ' ': > try: > m[idx] = m[idx]+a[i] > except: > m.append(a[i]) > else: > idx += 1 > >Just out of curiosity, why the interest in reinventing the wheel? > > Just thought I'd give my take without index counting. a="This is a test" def split(string): m=[] temp="" for l in a: if l==" ": m.append(temp) temp="" else: temp=temp + l m.append(temp) return m print split(a) __________________________________ Do you Yahoo!? Yahoo! Mail is new and improved - Check it out! http://promotions.yahoo.com/new_mail From alan.gauld at blueyonder.co.uk Fri Aug 13 05:53:54 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Aug 13 05:55:20 2004 Subject: [Tutor] avoid split function References: <20040812232506.96207.qmail@web53708.mail.yahoo.com> Message-ID: <01e501c480e9$274b5440$6401a8c0@xp> > a = "This is a test" > > for i in range(0,len(a)): > if a[i] == " ": > print y > elif a[i] != " ": > y.append(a[i]) > m.append(y[0:]) Thiis is easier like this: for i in a: if i == " ": print y else: y.append(i) m.append(y[:]) #not sure what you think this is doing! > I wanted to push "This" in to m as m = ['This'] > I know i can do this using: > > c = a.split() OK, I'd suggest using while loops: i = 0 while a[i]: while a[i] != " " m.append(a[i]) i += 1 y.append[m] i += 1 Which should give a list of lists in y y => [[T,h,i,s],[i,s],....] You could also use functional programming tools like list comprehensions I suspect. Note that the code above is not tested, but hopefully its a starter. Alan G. From python at bernardlebel.com Fri Aug 13 11:05:44 2004 From: python at bernardlebel.com (Bernard Lebel) Date: Fri Aug 13 11:05:55 2004 Subject: [Tutor] python-mysql Message-ID: <002d01c48114$ba114700$0d01a8c0@studioaction.local> Hello, Does anyone have any experience with mysql-python 1.0.0 win32? I installed it, it seems to work, I can connect to the sql database. However, few things seem not to work. Here is the connection code: import _mysql sql = _mysql # host (server) sHost = 'xxx.xxx.x.x' # uid (user) sUser = 'xsi_client' # pwd (password) sPwd = 'XSIBatchServe' # database sDB = 'XSI_R' # Connect to database by creating a database obect oCon = sql.connection( sHost, sUser, sPwd , sDB ) I know I am connected because if I run print oCon I get this message: <_mysql.connection open to 'xxx.xxx.x.x' at a96db8> I also have access to all the module functions on the oCon object. However the problem is that I can't go further. I'm trying to build a query: oQuery = oCon.query oQueryResult = oQuery( ' SELECT from_rule, where_rule, order_rule ' + ' FROM clients LEFT JOIN rules ON rules.id=clients.rule_id' + ' WHERE clients.c_id=' + str(31) ) Now if I run print str( oQueryResult ) I get None If I run "oCon.query.__doc__", I am told to use cursor() to create a cursor, then use cursor.execute() to execute a query. Ok, fine, but it seems I can't create cursor!! I tried "oCursor = oCon.cursor()" and "oCursor = oCon.query.cursor()", but no luck. Soooo I'm stuck! Anyone has any advice? I posted this on the python-mysql SourceForce forum page, but got no reply. Thanks in advance Bernard From linux-user at softhome.net Wed Aug 11 18:31:20 2004 From: linux-user at softhome.net (Conrad) Date: Fri Aug 13 11:59:43 2004 Subject: [Tutor] speed issue Message-ID: <1092241880.15907.18.camel@radiol> Hey tutors, I'm trying to solve this problem: http://spoj.sphere.pl/?a=problem&pcode=PICAD. Basically you are given 10 test cases. The first line in the test contains two numbers, the beginning and end of a sequence of numbers. ie. 5 10 would equal 5 6 7 8 9 10 The next line contains one number, z, this number represents how many other sequences of numbers you will get. After that you are given z lines all containing 2 numbers which mark the beginning and end of a sequence of numbers. ie. 4 3 5 6 7 1 10 2 8 The task is to figure out which number occurs the most from the original sequence in the given sequences. My solution is here, but the two for loops really slow it down, can anyone point out how to speed this code up. It takes input from stdin. (./program.py < test_file) I appreciate any help. Conrad #!/usr/bin/python import sys input_file = sys.stdin intervals = {} period = [0,0] def interval(): possible = input_file.readline().split() period[0] = (int(possible[0])) period[1] = (int(possible[1])) #Next two lines slow it down ((O^2)?) for x in range(period[0], period[1] + 1): intervals[str(x)] = 0 def find_vals(): interviewed = int(input_file.readline()) for x in range(interviewed): time_range = map(int, input_file.readline().split()) if time_range[0] < period[0]: time_range[0] = period[0] if time_range[1] > period[1]: time_range[1] = period[1] #This also slows it way down for x in range(time_range[0], time_range[1] + 1): intervals[str(x)] += 1 for x in range(10): interval() find_vals() print min(intervals.values()), max(intervals.values()) intervals = {} Here is my test file: 2 8 8 2 3 1 5 7 10 2 6 4 7 1 2 1 2 1 2 2 5 3 4 6 3 7 1 2 5 10 4 1 8 5 8 7 10 8 9 2 5 3 4 6 3 7 1 2 5 10 4 1 8 5 8 7 10 8 9 2 5 3 4 6 3 7 1 2 5 10 4 1 8 5 8 7 10 8 9 2 5 3 4 6 3 7 1 2 5 10 4 1 8 5 8 7 10 8 9 2 5 3 4 6 3 7 1 2 5 10 4 1 8 5 8 7 10 8 9 2 5 3 4 6 3 7 1 2 5 10 4 1 8 5 8 7 10 8 9 2 5 3 4 6 3 7 1 2 5 10 4 1 8 5 8 7 10 8 9 2 5 3 4 6 3 7 1 2 5 10 4 1 8 5 8 7 10 8 9 2 5 3 4 6 3 7 1 2 5 10 4 1 8 5 8 7 10 8 9 2 5 3 4 6 3 7 1 2 From alipolatel at yahoo.com Fri Aug 13 12:07:14 2004 From: alipolatel at yahoo.com (Ali Polatel) Date: Fri Aug 13 12:07:17 2004 Subject: [Tutor] What's wrong with this? Message-ID: <20040813100714.80991.qmail@web61007.mail.yahoo.com> Dear Friends and Tutors, Thanx for all your previous answers I have a new problem I am writing a python script which will connect to Internet Chess Club via telnet(the IP of the server is '65.245.208.34' and the port I want is 5056) Connecting works fine : "import telnetlib telnetlib.Telnet(host='65.245.208.34',port='5056')" Now the server asks for username and password... I want the programme to login as guest so : "a=telnetlib.Telnet(host='65.245.208.34',port='5056') a.read_until('login:') a.write('guest \n')" Now programme is connected to the server.Now I want to type commands and such things...Before I write a command I should do "a.read_until('aics%')" to get the command line. But the problem starts here.Some announces and chats come from the server and the server seems like that "xxx shouts: hi all aics% bbb shouts:hi again aics%_" The real command line is the second "aics%" but the programme types "a.read_until('aics%') only once so that when I type in a command programme doesn't send the command to the server. So I should make the programme type "a.read_until('aics%')" every 5 seconds or so... Can anyone show me how and where to do this change? Below is the script : "def icc(): a=telnetlib.Telnet(host='65.245.208.34',port='5056') print str(a.read_until('login:')) a.write('guest') a.write('\n') a.read_until('aics%') a.write('-ch 1\n') a.read_until('aics%') a.write('-ch 165\n') a.read_until('aics%') a.write('set shout 0\n') a.read_until('aics%') a.write('set sshout 0\n') a.read_until('aics%') print str(a.read_until('aics%')) for x in range(500000): d=raw_input(Command :>') a.write(str(d)) a.write('\n') print str(a.read_until('aics%')) Regards, Ali Polatel --------------------------------- Do you Yahoo!? Yahoo! Mail is new and improved - Check it out! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040813/2f0a7cf2/attachment.htm From kent_johnson at skillsoft.com Fri Aug 13 12:45:11 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Aug 13 12:45:48 2004 Subject: [Tutor] avoid split function In-Reply-To: <20040813032939.73828.qmail@web52609.mail.yahoo.com> References: <20040813032939.73828.qmail@web52609.mail.yahoo.com> Message-ID: <6.1.0.6.0.20040813063704.028ed518@mail4.skillsoft.com> Thank you for showing the best way to iterate over a string! But be careful of the boundary conditions. With your definition, splitting an empty string returns a list containing an empty string (split('') == ['']) whereas splitting an empty string with the system split returns an empty list (''.split() == []) Also mind your names - your function arg is named 'string' but your loop iterates over 'a'. Kent At 08:29 PM 8/12/2004 -0700, Chad Crabtree wrote: >Just thought I'd give my take without index counting. >a="This is a test" >def split(string): > m=[] > temp="" > for l in a: > if l==" ": > m.append(temp) > temp="" > else: > temp=temp + l > m.append(temp) > return m >print split(a) From my.mailing.lists at noos.fr Fri Aug 13 13:12:49 2004 From: my.mailing.lists at noos.fr (nik) Date: Fri Aug 13 13:12:57 2004 Subject: [Tutor] 'import site' failed error In-Reply-To: <6.1.0.6.0.20040812133731.029bd238@mail4.skillsoft.com> References: <411B46A0.5080608@noos.fr> <6.1.0.6.0.20040812064630.02a11dd0@mail4.skillsoft.com> <411B5061.5000606@noos.fr> <411B98E2.5060606@noos.fr> <6.1.0.6.0.20040812133731.029bd238@mail4.skillsoft.com> Message-ID: <411CA231.9040306@noos.fr> Cutting my code down to a minimum still brings up the import site error. I now have; demo.c: #include "Python.h" main(int argc, char **argv) { Py_Initialize(); Py_Finalize(); return 0; } (I've pasted the makefile at the bottom of the email, I can't remember where I initially took that from). which doesn't leave much, other than something missing on my computer or a path problem? I'm on a fresh install of mandrake 10, with the only messiness being that python 2.3.3 was pre-installed, but I've built 2.3.4 - can they exist happily side by side, or do you think I need to remove 2.3.3 somehow? python -V returns 2.3.3 since that version is first in the PATH.... Kent Johnson wrote: > You might try to sort out whether it is your embedding that is the > problem or your extension code. Does your embedded interpreter work to > do something simple like print "Hello", when your extension is not > installed? Can you use your extension from the interactive interpreter? > > import site is something that happens when the interpreter starts up > so I suspect the problem is with the embedding, not the extension... > > Kent > > At 06:20 PM 8/12/2004 +0200, nik wrote: > >> I've drawn a blank trying to find how to get PyRun_SimpleFile to run >> with the verbose option - I found someone mention it on a wishlist, >> so perhaps it isn't possible yet. >> >> So instead I'm just going to ignore it for the meanwhile, since the >> program still seems to output correctly (the good ol' >> head-in-the-sand technique). However, if anyone knows how I can sort >> it out, please let me know. >> >> thanks, >> nik >> >> nik wrote: >> >>> Hi Kent, that was a quick reply! >>> >>> I've embedded the interpreter in a C app, and so the python file is >>> called using PyRun_SimpleFile(fp, "demo2.py"); >>> so, I'm not too sure how to put the -v option in there (I'm doing >>> some websearching on it now). >>> >>> I tried a simple python file like print "hello", but it didn't come >>> up with the import site error, so I guess it's more to do with the >>> embedding or my module thingy? >>> >>> nik >>> >>> Kent Johnson wrote: >>> >>>> nik, >>>> >>>> I guess it is referring to the -v (verbose) option that you can >>>> pass to python when you start it up: >>>> D:\Projects>python -v >>>> # installing zipimport hook >>>> import zipimport # builtin >>>> # installed zipimport hook >>>> # C:\Python23\lib\site.pyc matches C:\Python23\lib\site.py >>>> import site # precompiled from C:\Python23\lib\site.pyc >>>> # C:\Python23\lib\os.pyc matches C:\Python23\lib\os.py >>>> import os # precompiled from C:\Python23\lib\os.pyc >>>> etc... >>>> >>>> traceback is the stack trace. So this may give you more specific >>>> information about the location and type of failure. Give it a try >>>> and let us know what it says! >>>> >>>> Kent >>>> >>>> At 12:29 PM 8/12/2004 +0200, nik wrote: >>>> >>>>> hi, >>>>> >>>>> I've compiled the example in the Extending and Embedding tutorial >>>>> section 2.1 (creating an module with a couple of string objects), >>>>> and I get the error >>>>> >>>>> 'import site' failed; use -v for traceback >>>>> >>>>> even though the correct output is then printed to the screen. >>>>> >>>>> What does this mean? >>>>> Do I need to post my code here (I've made a few modifications)? >>>>> How do I do the -v for traceback, and would it be useful to me? >>>> >>>> >>>> >>>> >>> >>> >>> _______________________________________________ >>> 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 > > # Makefile for embedded Python use demo. # (This version tailored for my Red Hat Linux 6.1 setup; # edit lines marked with XXX.) # XXX The compiler you are using CC= gcc # XXX Top of the build tree and source tree blddir= /home/nik/Python-2.3.4 srcdir= /home/nik/Python-2.3.4 # Python version VERSION= 2.3 # Compiler flags OPT= -ggdb INCLUDES= -I$(srcdir)/Include -I$(blddir) CFLAGS= $(OPT) CPPFLAGS= $(INCLUDES) # The Python library LIBPYTHON= $(blddir)/libpython$(VERSION).a # XXX edit LIBS (in particular) to match $(blddir)/Modules/Makefile LIBS= -lnsl -ldl -lreadline -ltermcap -lieee -lpthread -lutil LDFLAGS= -Xlinker -export-dynamic SYSLIBS= -lm MODLIBS= ALLLIBS= $(LIBPYTHON) $(MODLIBS) $(LIBS) $(SYSLIBS) # Build the demo applications all: demo demo: demo.o $(CC) $(LDFLAGS) demo.o $(ALLLIBS) -o demo # Administrative targets test: demo ./demo clean: -rm -f *.o core clobber: clean -rm -f *~ @* '#'* demo realclean: clobber From kent_johnson at skillsoft.com Fri Aug 13 13:33:48 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Aug 13 13:33:59 2004 Subject: [Tutor] speed issue In-Reply-To: <1092241880.15907.18.camel@radiol> References: <1092241880.15907.18.camel@radiol> Message-ID: <6.1.0.6.0.20040813072748.028ab2e0@mail4.skillsoft.com> Conrad, How fast do you need this to be? On my computer it completes instantly. The for loops should be fast, dict operations in Python are pretty fast. I don't think they are O(n^2). A few things you could do to squeeze a little bit out of it: - You can use integers as your dict keys - there is no need to convert to strings, e.g. use interval[x] instead of interval[str(x)]. Actually you could make interval a list instead of a map, that would probably be faster. - period and timerange could be split into two variables, that might save a little time. But these are very minor improvements. I don't see any obvious time-killers in your code. HTH, Kent At 09:31 AM 8/11/2004 -0700, Conrad wrote: >Hey tutors, > >I'm trying to solve this problem: >http://spoj.sphere.pl/?a=problem&pcode=PICAD. > >Basically you are given 10 test cases. The first line in the test >contains two numbers, the beginning and end of a sequence of numbers. >ie. >5 10 >would equal >5 6 7 8 9 10 >The next line contains one number, z, this number represents how many >other sequences of numbers you will get. >After that you are given z lines all containing 2 numbers which mark the >beginning and end of a sequence of numbers. >ie. >4 >3 5 >6 7 >1 10 >2 8 > >The task is to figure out which number occurs the most from the original >sequence in the given sequences. > >My solution is here, but the two for loops really slow it down, can >anyone point out how to speed this code up. It takes input from stdin. >(./program.py < test_file) > >I appreciate any help. > >Conrad > >#!/usr/bin/python > >import sys > >input_file = sys.stdin > >intervals = {} >period = [0,0] > >def interval(): > possible = input_file.readline().split() > period[0] = (int(possible[0])) > period[1] = (int(possible[1])) > #Next two lines slow it down ((O^2)?) > for x in range(period[0], period[1] + 1): > intervals[str(x)] = 0 > >def find_vals(): > interviewed = int(input_file.readline()) > for x in range(interviewed): > time_range = map(int, input_file.readline().split()) > if time_range[0] < period[0]: > time_range[0] = period[0] > if time_range[1] > period[1]: > time_range[1] = period[1] > #This also slows it way down > for x in range(time_range[0], time_range[1] + 1): > intervals[str(x)] += 1 > >for x in range(10): > interval() > find_vals() > print min(intervals.values()), max(intervals.values()) > intervals = {} > > >Here is my test file: >2 8 >8 >2 3 >1 5 >7 10 >2 6 >4 7 >1 2 >1 2 >1 2 >2 5 >3 >4 6 >3 7 >1 2 >5 10 >4 >1 8 >5 8 >7 10 >8 9 >2 5 >3 >4 6 >3 7 >1 2 >5 10 >4 >1 8 >5 8 >7 10 >8 9 >2 5 >3 >4 6 >3 7 >1 2 >5 10 >4 >1 8 >5 8 >7 10 >8 9 >2 5 >3 >4 6 >3 7 >1 2 >5 10 >4 >1 8 >5 8 >7 10 >8 9 >2 5 >3 >4 6 >3 7 >1 2 >5 10 >4 >1 8 >5 8 >7 10 >8 9 >2 5 >3 >4 6 >3 7 >1 2 >5 10 >4 >1 8 >5 8 >7 10 >8 9 >2 5 >3 >4 6 >3 7 >1 2 >5 10 >4 >1 8 >5 8 >7 10 >8 9 >2 5 >3 >4 6 >3 7 >1 2 >5 10 >4 >1 8 >5 8 >7 10 >8 9 >2 5 >3 >4 6 >3 7 >1 2 >5 10 >4 >1 8 >5 8 >7 10 >8 9 >2 5 >3 >4 6 >3 7 >1 2 > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From my.mailing.lists at noos.fr Fri Aug 13 13:42:51 2004 From: my.mailing.lists at noos.fr (nik) Date: Fri Aug 13 13:42:58 2004 Subject: [Tutor] 'import site' failed error In-Reply-To: <411CA231.9040306@noos.fr> References: <411B46A0.5080608@noos.fr> <6.1.0.6.0.20040812064630.02a11dd0@mail4.skillsoft.com> <411B5061.5000606@noos.fr> <411B98E2.5060606@noos.fr> <6.1.0.6.0.20040812133731.029bd238@mail4.skillsoft.com> <411CA231.9040306@noos.fr> Message-ID: <411CA93B.4@noos.fr> I've got a bit closer, but no cigar. Doing python -v shows the import site error before the interactive prompt appears (why didn't I notice this before?), and then doing export PATH=$PATH:/usr/lib/python2.3 (where site.py exists) makes that error go away. Unfortunately, the error remains for my C app :-( Probably almost there now though.... btw, for that complex structure question, I took it to C++-Sig, but in a flash of inspiration I realised I could pass it as a single XML string, and let the user use the xml.dom module. Life suddenly got a lot easier. nik nik wrote: > Cutting my code down to a minimum still brings up the import site > error. I now have; > > demo.c: > #include "Python.h" > main(int argc, char **argv) > { > Py_Initialize(); > Py_Finalize(); return 0; > } > > (I've pasted the makefile at the bottom of the email, I can't remember > where I initially took that from). > > which doesn't leave much, other than something missing on my computer > or a path problem? I'm on a fresh install of mandrake 10, with the > only messiness being that python 2.3.3 was pre-installed, but I've > built 2.3.4 - can they exist happily side by side, or do you think I > need to remove 2.3.3 somehow? python -V returns 2.3.3 since that > version is first in the PATH.... > > Kent Johnson wrote: > >> You might try to sort out whether it is your embedding that is the >> problem or your extension code. Does your embedded interpreter work >> to do something simple like print "Hello", when your extension is not >> installed? Can you use your extension from the interactive interpreter? >> >> import site is something that happens when the interpreter starts up >> so I suspect the problem is with the embedding, not the extension... >> >> Kent >> >> At 06:20 PM 8/12/2004 +0200, nik wrote: >> >>> I've drawn a blank trying to find how to get PyRun_SimpleFile to run >>> with the verbose option - I found someone mention it on a wishlist, >>> so perhaps it isn't possible yet. >>> >>> So instead I'm just going to ignore it for the meanwhile, since the >>> program still seems to output correctly (the good ol' >>> head-in-the-sand technique). However, if anyone knows how I can sort >>> it out, please let me know. >>> >>> thanks, >>> nik >>> >>> nik wrote: >>> >>>> Hi Kent, that was a quick reply! >>>> >>>> I've embedded the interpreter in a C app, and so the python file is >>>> called using PyRun_SimpleFile(fp, "demo2.py"); >>>> so, I'm not too sure how to put the -v option in there (I'm doing >>>> some websearching on it now). >>>> >>>> I tried a simple python file like print "hello", but it didn't come >>>> up with the import site error, so I guess it's more to do with the >>>> embedding or my module thingy? >>>> >>>> nik >>>> >>>> Kent Johnson wrote: >>>> >>>>> nik, >>>>> >>>>> I guess it is referring to the -v (verbose) option that you can >>>>> pass to python when you start it up: >>>>> D:\Projects>python -v >>>>> # installing zipimport hook >>>>> import zipimport # builtin >>>>> # installed zipimport hook >>>>> # C:\Python23\lib\site.pyc matches C:\Python23\lib\site.py >>>>> import site # precompiled from C:\Python23\lib\site.pyc >>>>> # C:\Python23\lib\os.pyc matches C:\Python23\lib\os.py >>>>> import os # precompiled from C:\Python23\lib\os.pyc >>>>> etc... >>>>> >>>>> traceback is the stack trace. So this may give you more specific >>>>> information about the location and type of failure. Give it a try >>>>> and let us know what it says! >>>>> >>>>> Kent >>>>> >>>>> At 12:29 PM 8/12/2004 +0200, nik wrote: >>>>> >>>>>> hi, >>>>>> >>>>>> I've compiled the example in the Extending and Embedding tutorial >>>>>> section 2.1 (creating an module with a couple of string objects), >>>>>> and I get the error >>>>>> >>>>>> 'import site' failed; use -v for traceback >>>>>> >>>>>> even though the correct output is then printed to the screen. >>>>>> >>>>>> What does this mean? >>>>>> Do I need to post my code here (I've made a few modifications)? >>>>>> How do I do the -v for traceback, and would it be useful to me? >>>>> >>>>> >>>>> >>>>> >>>>> >>>> >>>> >>>> _______________________________________________ >>>> 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 >> >> > # Makefile for embedded Python use demo. > # (This version tailored for my Red Hat Linux 6.1 setup; > # edit lines marked with XXX.) > > # XXX The compiler you are using > CC= gcc > > # XXX Top of the build tree and source tree > blddir= /home/nik/Python-2.3.4 > srcdir= /home/nik/Python-2.3.4 > > # Python version > VERSION= 2.3 > > # Compiler flags > OPT= -ggdb > INCLUDES= -I$(srcdir)/Include -I$(blddir) > CFLAGS= $(OPT) > CPPFLAGS= $(INCLUDES) > > # The Python library > LIBPYTHON= $(blddir)/libpython$(VERSION).a > > # XXX edit LIBS (in particular) to match $(blddir)/Modules/Makefile > LIBS= -lnsl -ldl -lreadline -ltermcap -lieee -lpthread -lutil > LDFLAGS= -Xlinker -export-dynamic > SYSLIBS= -lm > MODLIBS= ALLLIBS= $(LIBPYTHON) $(MODLIBS) $(LIBS) $(SYSLIBS) > > # Build the demo applications > all: demo > demo: demo.o > $(CC) $(LDFLAGS) demo.o $(ALLLIBS) -o demo > > # Administrative targets > > test: demo > ./demo > > clean: > -rm -f *.o core > > clobber: clean > -rm -f *~ @* '#'* demo > > realclean: clobber > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From ps_python at yahoo.com Fri Aug 13 13:57:02 2004 From: ps_python at yahoo.com (kumar s) Date: Fri Aug 13 13:57:04 2004 Subject: [Tutor] avoid split function In-Reply-To: <20040813025305.GA8984@wdfs.attbi.com> Message-ID: <20040813115702.85832.qmail@web53703.mail.yahoo.com> Thanks David, to me this is a practice session in understanding and using list functions. just a matter of practice. When I executed the code that I get the answer: ['Th', 'is', 'is', 'at', 'es', 't'] How can I get ['This', 'is', 'a', 'test'] Thank you. SK --- David Rock wrote: > * kumar s [2004-08-12 16:25]: > > Dear group, > > I am a newbie to Python. I am grinding my > abilities > > in list datatypes and fuctions. > > > > I am trying to avoid .split() function to process > a > > string. > > > > My programs follows: > > > > m = [] > > y = [] > > > > a = "This is a test" > > > > for i in range(0,len(a)): > > if a[i] == " ": > > print y > > elif a[i] != " ": > > y.append(a[i]) > > m.append(y[0:]) > > idx=0 > m = [] > a = "This is a test" > > for i in range(0,len(a)): > if a[i] != ' ': > try: > m[idx] = m[idx]+a[i] > except: > m.append(a[i]) > else: > idx += 1 > > Just out of curiosity, why the interest in > reinventing the wheel? > > -- > David Rock > david@graniteweb.com > > ATTACHMENT part 1.2 application/pgp-signature > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From pythonTutor at venix.com Fri Aug 13 14:25:17 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Fri Aug 13 14:25:21 2004 Subject: [Tutor] removing from a list In-Reply-To: <20040813031735.67560.qmail@web52608.mail.yahoo.com> References: <20040813031735.67560.qmail@web52608.mail.yahoo.com> Message-ID: <1092399917.2085.9.camel@laptop.venix.com> On Thu, 2004-08-12 at 23:17, Chad Crabtree wrote: > Lloyd Kvam wrote: > > > > >a = [each for each in a if each not in ("that",5)] > > > > > > > This comprehension blew my Mind. Let me paraphrase this and please > correct me if I'm wronng. > > return every 'each' in a if that 'each' is not that or 5? > > is that right? Correct. I did not actually test it. If you look back in the thread you'll see the sample data for the list named a, and the code this was derived from. This is the style I normally use now when removing elements from a list: use a list comprehension based on the original list bind it to the original name > > > > __________________________________ > Do you Yahoo!? > Yahoo! Mail - You care about security. So do we. > http://promotions.yahoo.com/new_mail > _______________________________________________ > 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 python-tutor at vs.megalink.ru Fri Aug 13 14:34:31 2004 From: python-tutor at vs.megalink.ru (Vsevolod Sipakov) Date: Fri Aug 13 14:34:42 2004 Subject: [Tutor] Me again In-Reply-To: <007001c47ff6$2b0b4de0$bc4ebb18@hochstein> References: <007001c47ff6$2b0b4de0$bc4ebb18@hochstein> Message-ID: <20040813123431.GA9555@megalink.ru> Hello, On Wed, Aug 11, 2004 at 06:54:33PM -0400, jason hochstein wrote: > This is what I get when using the %. > > l_input=[] > > while True: > s = raw_input("Type number. Hit enter for more or type quit to finish: ") > > if s == "quit": > break > else: > l_input.append(float(s)) > > for i in l_input: > average = sum(l_input) / len(l_input) > middle = len(l_input) % 2 don't use the loop, average should be computed ONCE. def average(l): return sum(l) / len(l) and median can be computed like this: def median(l): half = len(l) // 2 if (len(l)%2)==1: return l[half] else: return sum(l[half-1:half+1])/2.0 print "The mean of this list is", average(l_input) print "The median of this list is", median(l_input) -- Vsevolod Sipakov From bwinton at latte.ca Fri Aug 13 15:21:36 2004 From: bwinton at latte.ca (Blake Winton) Date: Fri Aug 13 15:21:40 2004 Subject: [Tutor] How to cal la method when have classes inside another class In-Reply-To: <019e01c480b4$dadd2090$6401a8c0@xp> References: <1092361365.6794.0.camel@rossum> <019e01c480b4$dadd2090$6401a8c0@xp> Message-ID: <411CC060.8020605@latte.ca> Alan Gauld wrote: >>class Class1: >> def someMethod(): >> pass >> class Class2: >> def otherMethod(): >> # ???call of someMethod??? >>I want to call someMethod in otherMethod. How can I do this? I'm going to assume that you really want nested classes, and point you at the following page: http://www.brpreiss.com/books/opus7/html/page598.html Which says: The methods of a nested class may access the instance attributes of the nested class instance but not of any outer class instance. Or, in other words: You can't. (There's a little more information here: http://mail.python.org/pipermail/python-list/2002-February/085830.html ) > If so I don't know of any way for a methjod of the nested class to > call a method of the outer class - the outer class is invisible to the > inner. But I confess I've never had a need to use inner classes in Python. > Why do you feel you need to resort to this? What are you trying to do that > requires it? This is probably the most important question. A lot of the times I need to use nested or inner classes in Java are made unnecessary by Python. Perhaps if you show us what you really want to do (as opposed to how you want to do it), we can offer other, more Pythonic suggestions. Later, Blake. From rdm at rcblue.com Fri Aug 13 15:21:47 2004 From: rdm at rcblue.com (Dick Moores) Date: Fri Aug 13 15:21:51 2004 Subject: [Tutor] Me again Message-ID: <6.1.2.0.2.20040813062112.04be4290@rcblue.com> Vsevolod Sipakov wrote at 05:34 8/13/2004: >def average(l): > return sum(l) / len(l) >>> l = [1,2,3,4,4] >>> print average(l) 2 Shouldn't this be: >>> def average(l): return sum(l)*1.0 / len(l) >>> l = [1,2,3,4,4] >>> print average(l) 2.8 Dick Moores From python_newbie at vedorian.com Fri Aug 13 15:37:12 2004 From: python_newbie at vedorian.com (Kevin) Date: Fri Aug 13 15:37:42 2004 Subject: [Tutor] The shabang line? Message-ID: <002301c4813a$a3fd76c0$30e57218@basp.phub.net.cable.rogers.com> if you have a python program that has multipul files ie: main.py, defs.py, objects.py, if you put the shabang line in the main.py and that file is required to start the program, do the reset of the files need the same line in order for the program to work? --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.726 / Virus Database: 481 - Release Date: 7/22/04 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040813/cb321235/attachment.html From askoose at sandia.gov Fri Aug 13 16:13:03 2004 From: askoose at sandia.gov (Kooser, Ara S) Date: Fri Aug 13 16:13:26 2004 Subject: [Tutor] pdf files Message-ID: <9A4B2157EFDBE546BECD68C62AC3B1C81738F3C1@es05snlnt.sandia.gov> I think there is a python program at the useless python site for convert .txt to .pdf. ara "There is something to be learned from a rainstorm. When meeting with a sudden shower, you try not to get wet and run quickly along the road. But doing such things as passing under the eaves of houses, you still get wet. When you are resolved from the beginning, you will not be perplexed, though you still get the same soaking." - Yamamoto Tsunetomo -----Original Message----- From: r2b2 [mailto:r2b2@myway.com] Sent: Thursday, August 12, 2004 6:08 PM To: tutor@python.org Subject: [Tutor] pdf files looking for a basic code using reportlabs package ( or any package ) to convert an existing text file to a .pdf file. convert document.txt to document.pdf thanks _______________________________________________ No banners. No pop-ups. No kidding. Make My Way your home on the Web - http://www.myway.com _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From flaxeater at yahoo.com Fri Aug 13 16:33:36 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Fri Aug 13 16:33:40 2004 Subject: [Tutor] avoid split function Message-ID: <20040813143336.71874.qmail@web52601.mail.yahoo.com> Well I'm abashed. I wrote it out as a long string of code then put it into a function without really thinking it through. Thank you for you critique. I didn't even think of the empty string issue. Here's a better one with the additional error checking a="This is a test" def split(astr): m=[] temp="" if astr=='': return [] for l in astr: if l==" ": m.append(temp) temp="" else: temp=temp + l m.append(temp) return m ####output#### >>> ['This', 'is', 'a', 'test'] [] ['this', 'might', 'be', 'a', 'test', 'I', "don't", 'know'] Kent Johnson wrote: > Thank you for showing the best way to iterate over a string! But be > careful of the boundary conditions. With your definition, splitting an > empty string returns a list containing an empty string (split('') == > ['']) whereas splitting an empty string with the system split returns > an empty list (''.split() == []) > > Also mind your names - your function arg is named 'string' but your > loop iterates over 'a'. > > Kent > > At 08:29 PM 8/12/2004 -0700, Chad Crabtree wrote: > >> Just thought I'd give my take without index counting. >> a="This is a test" >> def split(string): >> m=[] >> temp="" >> for l in a: >> if l==" ": >> m.append(temp) >> temp="" >> else: >> temp=temp + l >> m.append(temp) >> return m >> print split(a) > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > __________________________________ Do you Yahoo!? Yahoo! Mail is new and improved - Check it out! http://promotions.yahoo.com/new_mail From s.varun at gmail.com Fri Aug 13 16:37:38 2004 From: s.varun at gmail.com (Varun Soundararajan) Date: Fri Aug 13 16:37:47 2004 Subject: [Tutor] The best website to learn Python? In-Reply-To: <006101c48093$36968b00$30e57218@basp.phub.net.cable.rogers.com> References: <006101c48093$36968b00$30e57218@basp.phub.net.cable.rogers.com> Message-ID: <32b5ee760408130737709d41bf@mail.gmail.com> Hi, Alan's tutor is really cool. Have a look at that, bcoz i also read his tutor and found it helpful. Great work. Ofcourse, python.org hosts a good set of tutors. Have a look at them. -Varun ----- Original Message ----- From: Kevin Date: Thu, 12 Aug 2004 13:38:43 -0400 Subject: [Tutor] The best website to learn Python? To: tutor@python.org Cc: tutor@python.org Hello, Well I am a complete newbie to programming of any kind. I had downloaded a piece of python code and took a look at is (a game to be exact). I took a look at the code and just decided that I would like to try and learn python so that I could create my own game someday. The question I have is what is the best python related site for the complete newbie to learn from? I have looked at python.org but it seems a little over the top. I would like to start with something that explains everything in detail. Thanks for any suggestions. Kevin --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.726 / Virus Database: 481 - Release Date: 7/22/04 From flaxeater at yahoo.com Fri Aug 13 16:47:49 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Fri Aug 13 16:47:51 2004 Subject: [Tutor] How to cal la method when have classes inside another class Message-ID: <20040813144749.76562.qmail@web52601.mail.yahoo.com> Perhaps you could pass the method in to the nested classes init paramater like class aClass: def afunc(self,x): pass class bClass: def __init__(self,amethod) self.method=amethod I think this would make afunc act like it's a class method of bClass however I'm not sure. And I'm not really sure how to investigate that. Blake Winton wrote: > Alan Gauld wrote: > >>> class Class1: >>> def someMethod(): >>> pass >>> class Class2: >>> def otherMethod(): >>> # ???call of someMethod??? >>> I want to call someMethod in otherMethod. How can I do this? >> > > I'm going to assume that you really want nested classes, and point you > at the following page: > http://www.brpreiss.com/books/opus7/html/page598.html > > Which says: > The methods of a nested class may access the instance attributes of > the nested class instance but not of any outer class instance. > > Or, in other words: > You can't. __________________________________ Do you Yahoo!? New and Improved Yahoo! Mail - Send 10MB messages! http://promotions.yahoo.com/new_mail From flaxeater at yahoo.com Fri Aug 13 16:48:43 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Fri Aug 13 16:48:47 2004 Subject: [Tutor] The shabang line? Message-ID: <20040813144843.43274.qmail@web52602.mail.yahoo.com> Kevin wrote: > if you have a python program that has multipul files ie: main.py, > defs.py, objects.py, if you put the shabang line in the main.py and > that file is required to start the program, do the reset of the files > need the same line in order for the program to work? > I don't know for sure. Why dont' you try it out. __________________________________ Do you Yahoo!? Yahoo! Mail Address AutoComplete - You start. We finish. http://promotions.yahoo.com/new_mail From kent_johnson at skillsoft.com Fri Aug 13 16:54:57 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Aug 13 16:55:01 2004 Subject: [Tutor] avoid split function In-Reply-To: <20040813143336.71874.qmail@web52601.mail.yahoo.com> References: <20040813143336.71874.qmail@web52601.mail.yahoo.com> Message-ID: <6.1.0.6.0.20040813105143.02a38350@mail4.skillsoft.com> As long as I am being picky, I'll point out that there are quite a few special cases to consider. I don't think either David or Chad's solution duplicates the behavior of string.split() on all of them. (Hmm, sounds like a good opportunity to learn about unittest :-) >>> 'abc de'.split() # Multiple spaces between words ['abc', 'de'] >>> 'abc'.split() # Just one word ['abc'] >>> ''.split() # Empty string [] >>> 'abc '.split() # Trailing spaces ['abc'] >>> ' abc'.split() # Leading spaces ['abc'] Kent At 07:33 AM 8/13/2004 -0700, Chad Crabtree wrote: >Well I'm abashed. I wrote it out as a long string of code then put >it >into a function without really thinking it through. Thank you for >you >critique. I didn't even think of the empty string issue. Here's a >better one with the additional error checking >a="This is a test" >def split(astr): > m=[] > temp="" > if astr=='': > return [] > for l in astr: > if l==" ": > m.append(temp) > temp="" > else: > temp=temp + l > m.append(temp) > return m > >####output#### > >>> ['This', 'is', 'a', 'test'] >[] >['this', 'might', 'be', 'a', 'test', 'I', "don't", 'know'] > >Kent Johnson wrote: > > > Thank you for showing the best way to iterate over a string! But be > > > careful of the boundary conditions. With your definition, splitting >an > > empty string returns a list containing an empty string (split('') >== > > ['']) whereas splitting an empty string with the system split >returns > > an empty list (''.split() == []) > > > > Also mind your names - your function arg is named 'string' but your > > > loop iterates over 'a'. > > > > Kent > > > > At 08:29 PM 8/12/2004 -0700, Chad Crabtree wrote: > > > >> Just thought I'd give my take without index counting. > >> a="This is a test" > >> def split(string): > >> m=[] > >> temp="" > >> for l in a: > >> if l==" ": > >> m.append(temp) > >> temp="" > >> else: > >> temp=temp + l > >> m.append(temp) > >> return m > >> print split(a) > > > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > >__________________________________ >Do you Yahoo!? >Yahoo! Mail is new and improved - Check it out! >http://promotions.yahoo.com/new_mail From bgailer at alum.rpi.edu Fri Aug 13 17:06:12 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri Aug 13 17:03:25 2004 Subject: [Tutor] The shabang line? In-Reply-To: <002301c4813a$a3fd76c0$30e57218@basp.phub.net.cable.rogers. com> References: <002301c4813a$a3fd76c0$30e57218@basp.phub.net.cable.rogers.com> Message-ID: <6.1.0.6.0.20040813090446.03eb09b8@mail.mric.net> At 07:37 AM 8/13/2004, Kevin wrote: >if you have a python program that has multipul files ie: main.py, defs.py, >objects.py, if you put the shabang line in the main.py and that file is >required to start the program, do the reset of the files need the same >line in order for the program to work? If main.py imports the others, then the others don't need shabang. OTOH shabang can be there, since it is seen by python as a comment. Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040813/65f345a4/attachment.html From flaxeater at yahoo.com Fri Aug 13 17:49:56 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Fri Aug 13 17:50:12 2004 Subject: [Tutor] avoid split function Message-ID: <20040813154956.61495.qmail@web52607.mail.yahoo.com> Kent Johnson wrote: > As long as I am being picky, I'll point out that there are quite a few > special cases to consider. I don't think either David or Chad's > solution duplicates the behavior of string.split() on all of them. > (Hmm, sounds like a good opportunity to learn about unittest :-) > > >>> 'abc de'.split() # Multiple spaces between words > ['abc', 'de'] > > >>> 'abc'.split() # Just one word > ['abc'] > > >>> ''.split() # Empty string > [] > > >>> 'abc '.split() # Trailing spaces > ['abc'] > > >>> ' abc'.split() # Leading spaces > ['abc'] > > Kent > Not the complete functionality of ''.split() but close. And there is some unit tests right? I tried to be a bit more general to add in optional separators. I'm not sure why this got my goat. It was fun however. def split(astr,sep=('','\n','\t',' ')): m=[] temp="" if astr in sep: return [] for l in astr: if l in sep: m.append(temp) temp="" else: temp=temp + l m.append(temp) m=[x for x in m if x not in sep] #remove blank elements return m print split('this is a test') print split('abc,de',',') print split('\n') print split(' abc') print split('\tabc') print split('\nabc') print split('abc ') print split('abc de') print split('') print split("this might be a test I don't know") __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From kent_johnson at skillsoft.com Fri Aug 13 19:09:29 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Aug 13 19:09:32 2004 Subject: [Tutor] avoid split function In-Reply-To: <20040813154956.61495.qmail@web52607.mail.yahoo.com> References: <20040813154956.61495.qmail@web52607.mail.yahoo.com> Message-ID: <6.1.0.6.0.20040813130441.02a34098@mail4.skillsoft.com> Better :-) Actually this passes all of my original tests, but there is a problem with the optional sep parameter - your algorithm depends on sep containing the empty string. Try your examples with sep=(' ',) (a tuple containing one string which contains a single space). Also a more natural API would probably take a string for the sep argument and either allow any character in the string as a separator (like what you do) or use the entire string as the separator (which is what string.split() does...) I feel like the troll under the bridge today, biting everyone who tries to cross :-) I hope it is educational! Kent At 08:49 AM 8/13/2004 -0700, Chad Crabtree wrote: >Not the complete functionality of ''.split() but close. >And there is some unit tests right? I tried to be a bit more general >to >add in optional separators. I'm not sure why this got my goat. It >was >fun however. > >def split(astr,sep=('','\n','\t',' ')): > m=[] > temp="" > if astr in sep: > return [] > for l in astr: > if l in sep: > m.append(temp) > temp="" > else: > temp=temp + l > m.append(temp) > m=[x for x in m if x not in sep] #remove blank elements > return m > >print split('this is a test') >print split('abc,de',',') >print split('\n') >print split(' abc') >print split('\tabc') >print split('\nabc') >print split('abc ') >print split('abc de') >print split('') >print split("this might be a test I don't know") > > >__________________________________________________ >Do You Yahoo!? >Tired of spam? Yahoo! Mail has the best spam protection around >http://mail.yahoo.com From lobow at brturbo.com Sat Aug 14 01:13:24 2004 From: lobow at brturbo.com (Diego Galho Prestes) Date: Fri Aug 13 19:16:34 2004 Subject: [Tutor] How to cal la method when have classes inside another class In-Reply-To: <019e01c480b4$dadd2090$6401a8c0@xp> References: <1092361365.6794.0.camel@rossum> <019e01c480b4$dadd2090$6401a8c0@xp> Message-ID: <1092438804.12971.5.camel@rossum> On Thu, 2004-08-12 at 12:39, Alan Gauld wrote: > > Hi! I have this case but dont know how to call it... > > > > > > def Class1: > > def someMethod(): > > pass > > def Class2: > > def otherMethod(): > > ???call of someMethod??? > > > > I want to call someMethod in otherMethod. How can I do this? > > > First question. Are you trying to create classes or functions? > You are actually creating functions not classes. Well almost, > because a function definition needs a pair of parentheses after it. True. I typed it wrong. It was classes. > So either you want: > > class Class1: > ... > > or > > def Class1(): > ... > > If its a function then you can indeed define nested functions inside. > If its a class then the methods should have an instance reference as > the first parameter, usually called self: > > class Class1: > def method1(self): > pass > def method2(self): > self.method1() > > Is that what you want? Or do you really want to create a nested > class ala Java? > > If so I don't know of any way for a methjod of the nested class to > call > a method of the outer class - the outer class is invisible to the > inner. > But I confess I've never had a need to use inner classes in Python. > Why > do you feel you need to resort to this? What are you trying to do that > requires it? It was suposed to be like an "other part" of the program but that will only be used just be one class. Thats why I thougth about use this. But I was thinking and Ill put the classes in the same level of identation. > > Alan G > Author of the Learn to Program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From dyoo at hkn.eecs.berkeley.edu Fri Aug 13 19:37:32 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Aug 13 19:37:41 2004 Subject: [Tutor] python-mysql In-Reply-To: <002d01c48114$ba114700$0d01a8c0@studioaction.local> Message-ID: On Fri, 13 Aug 2004, Bernard Lebel wrote: > Does anyone have any experience with mysql-python 1.0.0 win32? I > installed it, it seems to work, I can connect to the sql database. > However, few things seem not to work. Here is the connection code: > import _mysql > sql = _mysql Hi Bernard, Do not use the underlying '_mysql' module if you can help it. That module is not meant to be used directly by us; it's a module for the 'MySQLdb' module. Use 'MySQLdb' instead. > If I run "oCon.query.__doc__", I am told to use cursor() to create a cursor, > then use cursor.execute() to execute a query. Ok, fine, but it seems I can't > create cursor!! > I tried "oCursor = oCon.cursor()" and "oCursor = oCon.query.cursor()", but > no luck. This sounds like a consequence of using _mysql instead of MySQLdb. _mysql provides the primitives that MySQLdb uses, so the documentation may apply to MySQLdb instead. Here's an example of MySQLdb: ### >>> import MySQLdb >>> conn = MySQLdb.connect(host='localhost', port=3306, db='pub') >>> cursor = conn.cursor() >>> cursor.execute("select name from pub_term where name like 'photo%'") 64L >>> cursor.fetchone() ('photoinhibition',) >>> cursor.fetchone() ('photomorphogenesis',) >>> cursor.fetchone() ('photoperiod',) >>> cursor.fetchone() ('photoprotection',) ### Hope this helps! From alipolatel at yahoo.com Fri Aug 13 19:40:34 2004 From: alipolatel at yahoo.com (Ali Polatel) Date: Fri Aug 13 19:40:37 2004 Subject: [Tutor] Another prob with Telnet Message-ID: <20040813174034.56833.qmail@web61007.mail.yahoo.com> Friends, I write a programme which connects to FICS via telnet but this site has an interesting property...instead of pressing enter one should press "ctrl+j" to enter commands etc. Any ideas to make this work in python? regards __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040813/26215d7f/attachment.html From dyoo at hkn.eecs.berkeley.edu Fri Aug 13 19:53:26 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Aug 13 19:53:30 2004 Subject: [Tutor] Another prob with Telnet In-Reply-To: <20040813174034.56833.qmail@web61007.mail.yahoo.com> Message-ID: On Fri, 13 Aug 2004, Ali Polatel wrote: > I write a programme which connects to FICS via telnet but this site has > an interesting property...instead of pressing enter one should press > "ctrl+j" to enter commands etc. Any ideas to make this work in python? Hi Ali, But Control-j is the newline character; are you sure that pressing enter doesn't do the trick? http://www.robelle.com/library/smugbook/ascii.txt contains a table that shows a map between the "control" keys and what they really stand for. Good luck to you. From pythonTutor at venix.com Fri Aug 13 20:09:38 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Fri Aug 13 20:09:43 2004 Subject: [Tutor] Another prob with Telnet In-Reply-To: References: Message-ID: <1092420578.2418.67.camel@laptop.venix.com> telnet applications usually map the enter key to transmit \n local applications often see the enter key as \r If you are writing the character through your code to the telnet connection you may be writing \r (ctrl+m). If you need to explicitly write other ctrl characters, ctrl+a == chr(1) ctrl+b == chr(2) etc. On Fri, 2004-08-13 at 13:53, Danny Yoo wrote: > On Fri, 13 Aug 2004, Ali Polatel wrote: > > > I write a programme which connects to FICS via telnet but this site has > > an interesting property...instead of pressing enter one should press > > "ctrl+j" to enter commands etc. Any ideas to make this work in python? > > > Hi Ali, > > But Control-j is the newline character; are you sure that pressing enter > doesn't do the trick? > > > http://www.robelle.com/library/smugbook/ascii.txt > > contains a table that shows a map between the "control" keys and what they > really stand for. > > > Good luck to you. > > _______________________________________________ > 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 jeff at ccvcorp.com Fri Aug 13 20:13:19 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri Aug 13 20:12:34 2004 Subject: [Tutor] Creating a complex python object In-Reply-To: <20040813031151.90024.qmail@web52604.mail.yahoo.com> References: <20040813031151.90024.qmail@web52604.mail.yahoo.com> Message-ID: <411D04BF.70601@ccvcorp.com> Chad Crabtree wrote: > >In the mean time I'll keep lurking on this list, there's still a > lot > to python that baffles me (like just what is the difference between a > tuple and a list? :-) ). > > I thought I would answer the tuple list thing. I did not understand > why > have tuple's until I learned that tuples being immutable are faster > and > easier on memory. Actually, speed and memory considerations are only incidental. One of the most important reasons that Python has both (mutable) lists and (immutable) tuples is because dictionaries don't work with mutable keys. If you stuck something into a dictionary that was keyed on a list, and then that list changed, you'd never be able to get that dictionary value back. But dictionaries are an important part of Python (many internal data structures are effectively dictionaries, among other things), and it's very valuable to be able to use a group of items as keys -- for example, a dictionary showing grid locations is much cleaner if you can key off of (x, y), rather than having a dictionary at x that has another dictionary that's keyed off of y. So, dictionaries are the reason that we have tuples. But once we *have* them, they tend to grow other differences... The common usage, now, is that lists usually contain a sequence of similar things, whereas tuples are usually more like a record, grouping together dissimilar things that are conceptually related. Thus, for example, in the date-time tuple returned by time.gmtime() each position within the tuple represents a different thing. In contrast, each position in a list represents a different instance, but all of the contents are the same type of thing. This distinction is just convention, of course, and there's nothing forcing you to follow it, but you'll find that just about every standard library module (and most other code, as well) will follow this guideline. Jeff Shannon Technician/Programmer Credit International From dyoo at hkn.eecs.berkeley.edu Fri Aug 13 20:18:38 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Aug 13 20:18:45 2004 Subject: [Tutor] speed issue In-Reply-To: <1092241880.15907.18.camel@radiol> Message-ID: On Wed, 11 Aug 2004, Conrad wrote: > > def interval(): > possible = input_file.readline().split() > period[0] = (int(possible[0])) > period[1] = (int(possible[1])) > #Next two lines slow it down ((O^2)?) > for x in range(period[0], period[1] + 1): > intervals[str(x)] = 0 > > def find_vals(): > interviewed = int(input_file.readline()) > for x in range(interviewed): > time_range = map(int, input_file.readline().split()) > if time_range[0] < period[0]: > time_range[0] = period[0] > if time_range[1] > period[1]: > time_range[1] = period[1] > #This also slows it way down > for x in range(time_range[0], time_range[1] + 1): > intervals[str(x)] += 1 Hi Conrad, Ok, I see, so you're keeping an intervals dictionary, and then whenever someone passes by, for that interval that they stay, you raise the "people" count. This seems fine: this approach should give correct results. I think that you can avoid doing some string->int conversions. There are places where you do: intervals[str(x)] = 0 and it should be possible to just say: intervals[x] = 0 Integers are perfectly ok as dictionary keys. On small numbers your program is fine. But there is one problem with the approach, and it has to do with the way it behaves when the problem scales: it starts chugging as soon as the intervals get really large. According to: http://spoj.sphere.pl/?a=problem&pcode=PICAD you can expect to see intervals between: 0<=p<=k<=100000000. So a hideous test case that your program should consider is: ### 0 100000000 5000 0 100000000 0 100000000 0 100000000 0 100000000 0 100000000 0 100000000 .... [you get the idea] ### You know what your program is going to do in this case, and you know that it's doing a heck of a lot of work. It's basically making an interval one hundred million elements long, and then, element by element, incrementing each about five thousand times. The big problem here is that by physically representing each interval as a dense set, the run-time is proportional to the length of the intervals it deals with. If you can just represent your intervals as endpoints, then that may help speed up the program, but then the program will have to adjust to this change in interval representation. So in short: there's no really good way of making your program any faster except by change of algorithm. Good luck to you! From bgailer at alum.rpi.edu Fri Aug 13 20:40:39 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri Aug 13 20:37:54 2004 Subject: [Tutor] Creating a complex python object In-Reply-To: <411D04BF.70601@ccvcorp.com> References: <20040813031151.90024.qmail@web52604.mail.yahoo.com> <411D04BF.70601@ccvcorp.com> Message-ID: <6.1.0.6.0.20040813123907.027227a8@mail.mric.net> At 12:13 PM 8/13/2004, Jeff Shannon wrote: >Chad Crabtree wrote: >> >In the mean time I'll keep lurking on this list, there's still a >>lot to python that baffles me (like just what is the difference between a >>tuple and a list? :-) ). >>I thought I would answer the tuple list thing. I did not understand >>why have tuple's until I learned that tuples being immutable are faster >>and easier on memory. > >Actually, speed and memory considerations are only incidental. > >One of the most important reasons that Python has both (mutable) lists and >(immutable) tuples is because dictionaries don't work with mutable >keys. If you stuck something into a dictionary that was keyed on a list, >and then that list changed, you'd never be able to get that dictionary >value back. But dictionaries are an important part of Python (many >internal data structures are effectively dictionaries, among other >things), and it's very valuable to be able to use a group of items as >keys -- for example, a dictionary showing grid locations is much cleaner >if you can key off of (x, y), rather than having a dictionary at x that >has another dictionary that's keyed off of y. > >So, dictionaries are the reason that we have tuples. But once we *have* >them, they tend to grow other differences... > >The common usage, now, is that lists usually contain a sequence of similar >things, whereas tuples are usually more like a record, grouping together >dissimilar things that are conceptually related. Thus, for example, in the >date-time tuple returned by time.gmtime() each position within the tuple >represents a different thing. In contrast, each position in a list >represents a different instance, but all of the contents are the same type >of thing. This distinction is just convention, of course, and there's >nothing forcing you to follow it, but you'll find that just about every >standard library module (and most other code, as well) will follow this >guideline. Darn - and just today I created a mechanism using a list in which the 1st element is a string and the rest integer. Sigh. Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From bigapple631 at optonline.net Fri Aug 13 21:30:49 2004 From: bigapple631 at optonline.net (jason hochstein) Date: Fri Aug 13 21:31:58 2004 Subject: [Tutor] import probs Message-ID: <007b01c4816c$09dac5c0$bc4ebb18@hochstein> I am trying to figure out why my I can't get one module to import to the other. Here is what I have. print "Welcome to the age program." print "This program will determine whether you are a child, adult, legal to drink beer or a senior citizen." age = input("How old are you? ") if age < (18): print "Congratulations, your a kid." elif age == (19 or 20): print "Congratulations, you're an adult." elif age >= (21) and age < (65): print "Congratulations, you're old enough to drink." elif age > (65): print "Congratulations, you're a senior citizen. You get a discount for being old." import add print " Thank you for trying this product. Please come again." exit = input () here is what the import add is: def add(): print "Your age divided by 2 is", age / 2 print "Your age times 10 is", age * 10 print "I hope this works. " They are both in the same directory on my c drive as well. It wont import it.?? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040813/e203b786/attachment.html From bigapple631 at optonline.net Fri Aug 13 21:33:10 2004 From: bigapple631 at optonline.net (jason hochstein) Date: Fri Aug 13 21:34:03 2004 Subject: [Tutor] Re: import probs Message-ID: <008801c4816c$5e2ac990$bc4ebb18@hochstein> this is the error I get. >> Welcome to the age program. This program will determine whether you are a child, adult, legal to drink beer or a senior citizen. Congratulations, you're old enough to drink. Thank you for trying this product. Please come again. Traceback (most recent call last): File "C:\Python23\Lib\site-packages\Pythonwin\pywin\framework\scriptutils.py", line 310, in RunScript exec codeObject in __main__.__dict__ File "C:\Documents and Settings\Jason\My Documents\Touro Docs\python documents\Assignments\AGE.py", line 24, in ? exit = input () File "C:\Python23\Lib\site-packages\Pythonwin\pywin\framework\app.py", line 368, in Win32Input return eval(raw_input(prompt)) File "", line 0 ^ SyntaxError: unexpected EOF while parsing >>> ----- Original Message ----- From: jason hochstein To: tutor@python.org Sent: Friday, August 13, 2004 3:30 PM Subject: import probs I am trying to figure out why my I can't get one module to import to the other. Here is what I have. print "Welcome to the age program." print "This program will determine whether you are a child, adult, legal to drink beer or a senior citizen." age = input("How old are you? ") if age < (18): print "Congratulations, your a kid." elif age == (19 or 20): print "Congratulations, you're an adult." elif age >= (21) and age < (65): print "Congratulations, you're old enough to drink." elif age > (65): print "Congratulations, you're a senior citizen. You get a discount for being old." import add print " Thank you for trying this product. Please come again." exit = input () here is what the import add is: def add(): print "Your age divided by 2 is", age / 2 print "Your age times 10 is", age * 10 print "I hope this works. " They are both in the same directory on my c drive as well. It wont import it.?? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040813/bed954dd/attachment.htm From python at bernardlebel.com Sat Aug 14 00:02:13 2004 From: python at bernardlebel.com (Bernard Lebel) Date: Fri Aug 13 22:59:59 2004 Subject: [Tutor] Number of elements in a list Message-ID: <002f01c48181$32320640$2901a8c0@atyss> A very basic question: how can I print the number of elements in a list? I'm not talking about the elements, just their count... Something like print myList.length or print myList.count Thanks Bernard From python at bernardlebel.com Sat Aug 14 00:07:06 2004 From: python at bernardlebel.com (Bernard Lebel) Date: Fri Aug 13 23:04:50 2004 Subject: [Tutor] Number of elements in a list References: <002f01c48181$32320640$2901a8c0@atyss> Message-ID: <003a01c48181$e0b1ced0$2901a8c0@atyss> Forget that. len() is what I was after. ----- Original Message ----- From: "Bernard Lebel" To: Sent: Friday, August 13, 2004 11:02 PM Subject: [Tutor] Number of elements in a list > A very basic question: how can I print the number of elements in a list? I'm > not talking about the elements, just their count... > > Something like > > print myList.length > or > print myList.count > > > Thanks > Bernard > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From nick at javacat.f2s.com Fri Aug 13 23:07:52 2004 From: nick at javacat.f2s.com (Nick Lunt) Date: Fri Aug 13 23:05:37 2004 Subject: [Tutor] Number of elements in a list In-Reply-To: <002f01c48181$32320640$2901a8c0@atyss> Message-ID: Hi Bernard, try looking here for info about lists http://docs.python.org/tut/node5.html#SECTION005140000000000000000 basically: >>>mylist = [1,2,3,4] >>>print len(mylist) 4 :) Nick. -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org]On Behalf Of Bernard Lebel Sent: 13 August 2004 23:02 To: tutor@python.org Subject: [Tutor] Number of elements in a list A very basic question: how can I print the number of elements in a list? I'm not talking about the elements, just their count... Something like print myList.length or print myList.count Thanks Bernard _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From kent_johnson at skillsoft.com Fri Aug 13 23:08:45 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Aug 13 23:08:50 2004 Subject: [Tutor] Number of elements in a list In-Reply-To: <002f01c48181$32320640$2901a8c0@atyss> References: <002f01c48181$32320640$2901a8c0@atyss> Message-ID: <6.1.0.6.0.20040813170735.02a27e78@mail4.skillsoft.com> print len(myList) It's not a member function, it's a builtin. Kent At 11:02 PM 8/13/2004 +0100, Bernard Lebel wrote: >A very basic question: how can I print the number of elements in a list? I'm >not talking about the elements, just their count... > >Something like > >print myList.length >or >print myList.count > > >Thanks >Bernard > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From alan.gauld at blueyonder.co.uk Fri Aug 13 23:08:16 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Aug 13 23:09:36 2004 Subject: [Tutor] Another prob with Telnet References: Message-ID: <00b701c48179$a75b2210$6401a8c0@xp> > > I write a programme which connects to FICS via telnet but this site has > > an interesting property...instead of pressing enter one should press > > "ctrl+j" to enter commands etc. Any ideas to make this work in python? > > But Control-j is the newline character; are you sure that pressing enter > doesn't do the trick? Ctrl-j is the line feed character. Ctrl-M is the Enter character Which, depending on OS can be interpreted as a linefeed, a carriage return or a combination of both. > http://www.robelle.com/library/smugbook/ascii.txt > > contains a table that shows a map between the "control" keys and what they > really stand for. Going back to my old teletype days when we didn't have no steenkin' Enter keys... :-) Alan G. From python at kapitalisten.no Fri Aug 13 23:17:28 2004 From: python at kapitalisten.no (=?iso-8859-1?Q?=D8yvind?=) Date: Fri Aug 13 23:17:37 2004 Subject: [Tutor] RE troubles Message-ID: <4162.193.216.211.151.1092431848.squirrel@mail.sporck.net> I am trying to make sense of the RE module and get the correct output. I have a document where there are five instances of a word or a sentence. How many characters or what kind of characters are unknown. I have downloaded Kodos, but can't get any wiser. What will the expression I should use be? I know that the word is following "target="_top">" and is before " word1 sentence 2 Message-ID: <001501c48186$1992fa40$6401a8c0@xp> > I am trying to figure out why my I can't get one module to > import to the other. Here is what I have. You probably need to set the python path so that Python knows where to find it. The old way of doing this was through setting an Environment Variable PYTHONPATH and that still works. Alternatively you can create a .pth file in your Python folder that lists the folders with modules in them. Being old fashioned I've bever tried that but am assured it works! :-) BUT, You have a few more problems in your program: > print "Welcome to the age program." > print "This program will determine whether you are a child, adult, legal to drink beer or a senior citizen." > age = input("How old are you? ") > if age < (18): > > print "Congratulations, your a kid." > > elif age == (19 or 20): THis will always be true because Python treats any non zero number as being True. Thus it sees the line above as elif age = (True or True) and (True or True) is always True and if age is non zero it will be True too, so age == True is True! > elif age >= (21) and age < (65): > print "Congratulations, you're old enough to drink." This is better. But in Python(unlike most languages you can shorten it to: elif 21 <= age <= 65: which is esier to read. > import add This simply imports the add module but doesn't actually execute anything except the definition in add.py, you never actually use the add() function. For that you'd need to have a line like: add.add() But even then it won't work because the add() function in add.py doesn't know about the age variable in your top module, so you need to change the definition of add() to take a parameter, like this: > here is what the import add is: > > def add(age): # <--ADD AGE Parameter > print "Your age divided by 2 is", age / 2 > print "Your age times 10 is", age * 10 > print "I hope this works. " So to summarize you need to: 1) add your module folder to a .pth file in your python installation folder 2) Fix the age = (x or y) problem 3) add a paramater to add() 4) call the add.add() function after you import it. Try that and see how you get on. Alan G. From alan.gauld at blueyonder.co.uk Sat Aug 14 00:38:39 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Aug 14 00:39:52 2004 Subject: [Tutor] Number of elements in a list References: <002f01c48181$32320640$2901a8c0@atyss> Message-ID: <001c01c48186$473394a0$6401a8c0@xp> > print myList.length print len(myList) Its a function not a method for historical reasons, and because it works on all sorts of things not just lists... Alan G. From python_newbie at vedorian.com Sat Aug 14 00:24:34 2004 From: python_newbie at vedorian.com (Kevin) Date: Sat Aug 14 01:03:14 2004 Subject: [Tutor] Wich of these books are better to learn from? Message-ID: <000a01c48184$5003a9a0$30e57218@basp.phub.net.cable.rogers.com> My book store only has these to python books out of these two which is better? Python Bible 2.1 or O'Reilly's Learn python? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040813/97e12da7/attachment.htm From dyoo at hkn.eecs.berkeley.edu Sat Aug 14 01:15:44 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Aug 14 01:15:50 2004 Subject: [Tutor] RE troubles In-Reply-To: <4162.193.216.211.151.1092431848.squirrel@mail.sporck.net> Message-ID: On Fri, 13 Aug 2004, [iso-8859-1] =D8yvind wrote: > I am trying to make sense of the RE module and get the correct output. I > have a document where there are five instances of a word or a sentence. > How many characters or what kind of characters are unknown. I have > downloaded Kodos, but can't get any wiser. Hello! "Kodos"? Oh, you mean the Kodos regular expression debugger. http://kodos.sourceforge.net/ Cool; I didn't know about this one. > I know that the word is following "target=3D"_top">" and is before "<= a > href=3Djavascript". So the document will contain five instances of: > > target=3D"_top"> word1 target=3D"_top">sentence 2 and so forth.... > > How do I get them out? Can you show us what you have tried so far? You can probably get what you want by doing something like this: ### >>> regex =3D re.compile(r"""\| =2E.. (.*?) =2E.. \|""", re.VERBOSE) >>> ### The above is a regular expression that will hunt for things between pipe symbols. For example, we can use findall(): ### >>> regex.findall(" |this is| a test of the |emergency| |broadcast system|") ['this is', 'emergency', 'broadcast system'] ### and get all the "piped" words in a snap. The slightly tricky part of the pattern above is the use a wildcard (.*) to grab at the content in between. We have to make sure that the match is "nongreedy", by adding a question mark to the wildcard. (.*?) What does it mean for a match to be greedy? Let's see what happens if we leave the question mark off: ### >>> regex =3D re.compile(r"""\| =2E.. (.*) =2E.. \|""", re.VERBOSE) >>> >>> regex.findall(" |this is| a test of the |emergency| |broadcast system|") ['this is| a test of the |emergency| |broadcast system'] ### When we search for all occurrences of things between pipes, this time we get just one element. The regular expression engine is giving us an answer that's technically true, since the thing it found was surrounded by pipes. But it's not giving us a minimally correct answer, which is why we call it "greedy". You may find the Python Regex HOWTO useful, as it explains these concepts: http://www.amk.ca/python/howto/regex/ Hope this helps! From my.mailing.lists at noos.fr Sat Aug 14 01:16:05 2004 From: my.mailing.lists at noos.fr (nik) Date: Sat Aug 14 01:16:15 2004 Subject: [Tutor] Creating a complex python object In-Reply-To: <6.1.0.6.0.20040813123907.027227a8@mail.mric.net> References: <20040813031151.90024.qmail@web52604.mail.yahoo.com> <411D04BF.70601@ccvcorp.com> <6.1.0.6.0.20040813123907.027227a8@mail.mric.net> Message-ID: <411D4BB5.4030508@noos.fr> Bob Gailer wrote: > At 12:13 PM 8/13/2004, Jeff Shannon wrote: > >> Chad Crabtree wrote: >> >>> >In the mean time I'll keep lurking on this list, there's still a >>> lot to python that baffles me (like just what is the difference >>> between a >>> tuple and a list? :-) ). >>> I thought I would answer the tuple list thing. I did not understand >>> why have tuple's until I learned that tuples being immutable are faster >>> and easier on memory. >> >> >> Actually, speed and memory considerations are only incidental. >> >> One of the most important reasons that Python has both (mutable) >> lists and (immutable) tuples is because dictionaries don't work with >> mutable keys. If you stuck something into a dictionary that was >> keyed on a list, and then that list changed, you'd never be able to >> get that dictionary value back. But dictionaries are an important >> part of Python (many internal data structures are effectively >> dictionaries, among other things), and it's very valuable to be able >> to use a group of items as keys -- for example, a dictionary showing >> grid locations is much cleaner if you can key off of (x, y), rather >> than having a dictionary at x that has another dictionary that's >> keyed off of y. >> >> So, dictionaries are the reason that we have tuples. But once we >> *have* them, they tend to grow other differences... >> >> The common usage, now, is that lists usually contain a sequence of >> similar things, whereas tuples are usually more like a record, >> grouping together dissimilar things that are conceptually related. >> Thus, for example, in the date-time tuple returned by time.gmtime() >> each position within the tuple represents a different thing. In >> contrast, each position in a list represents a different instance, >> but all of the contents are the same type of thing. This distinction >> is just convention, of course, and there's nothing forcing you to >> follow it, but you'll find that just about every standard library >> module (and most other code, as well) will follow this guideline. > > > Darn - and just today I created a mechanism using a list in which the > 1st element is a string and the rest integer. Sigh. > I've seen the homogeneous vs heterogeneous description of lists and tuples, but pure convention doesn't seem to be a very good argument for it. There must be a good practical reason that it's settled in that form - why didn't it settle in the opposite fashion; lists=heterogeneous, tuples=homogeneous? Is it the immutability of the tuple, or the fact you can't use a list as a key that's pushed it in that direction, or was it really as simple as one guy in the early days saying 'I prefer this convention'? From missive at hotmail.com Sat Aug 14 01:06:35 2004 From: missive at hotmail.com (Lee Harr) Date: Sat Aug 14 01:18:43 2004 Subject: [Tutor] Re: RE troubles Message-ID: >I am trying to make sense of the RE module and get the correct output. I >have a document where there are five instances of a word or a sentence. >How many characters or what kind of characters are unknown. I have >downloaded Kodos, but can't get any wiser. What will the expression I >should use be? > Have you ever tried a "visual regexp editor" ? KDE has a real nice one called (oddly enough) kregexpeditor. Might be worth a try... _________________________________________________________________ Tired of spam? Get advanced junk mail protection with MSN 8. http://join.msn.com/?page=features/junkmail From jeff at ccvcorp.com Sat Aug 14 01:26:59 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Sat Aug 14 01:26:14 2004 Subject: [Tutor] Creating a complex python object In-Reply-To: <411D4BB5.4030508@noos.fr> References: <20040813031151.90024.qmail@web52604.mail.yahoo.com> <411D04BF.70601@ccvcorp.com> <6.1.0.6.0.20040813123907.027227a8@mail.mric.net> <411D4BB5.4030508@noos.fr> Message-ID: <411D4E43.4040908@ccvcorp.com> nik wrote: >> At 12:13 PM 8/13/2004, Jeff Shannon wrote: >>> The common usage, now, is that lists usually contain a sequence of >>> similar things, whereas tuples are usually more like a record, >>> grouping together dissimilar things that are conceptually related. >>> Thus, for example, in the date-time tuple returned by time.gmtime() >>> each position within the tuple represents a different thing. In >>> contrast, each position in a list represents a different instance, >>> but all of the contents are the same type of thing. This distinction >>> is just convention, of course, and there's nothing forcing you to >>> follow it, but you'll find that just about every standard library >>> module (and most other code, as well) will follow this guideline. >> > I've seen the homogeneous vs heterogeneous description of lists and > tuples, but pure convention doesn't seem to be a very good argument for > it. There must be a good practical reason that it's settled in that form > - why didn't it settle in the opposite fashion; lists=heterogeneous, > tuples=homogeneous? Is it the immutability of the tuple, or the fact you > can't use a list as a key that's pushed it in that direction, or was it > really as simple as one guy in the early days saying 'I prefer this > convention'? I suspect that the immutable nature of tuples makes them seem a little more... distinct. Consider the case where some fields of a record are empty. Because lists can vary in length, you're not used to the thought of "empty" slots in a list; in contrast, tuples (once created) don't change in size, so they seem more natural as something with "empty" slots. (Of course, this may be a side effect of my already thinking of tuples as records, rather than a cause, but it sounds good to me. ;) ) Jeff Shannon Technician/Programmer Credit International From dyoo at hkn.eecs.berkeley.edu Sat Aug 14 01:33:05 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Aug 14 01:33:14 2004 Subject: [Tutor] Creating a complex python object In-Reply-To: <411D4BB5.4030508@noos.fr> Message-ID: > > Darn - and just today I created a mechanism using a list in which the > > 1st element is a string and the rest integer. Sigh. > > > I've seen the homogeneous vs heterogeneous description of lists and > tuples, but pure convention doesn't seem to be a very good argument for > it. There must be a good practical reason Hi Nik, Not necessarily "practical". *grin* In the math world, mathematicians use tuples just as a programmer uses structured records. As a concrete example, when mathematicians talk about "graphs", they might say something like this: A graph G is defined to be a 2-tuple (V, E), where V is a set of verticles, and E is a set of edges. Another concrete example from a mathy point of view is the relational algebra (the theory behind SQL databases). According to relational algebra, a table "relation" is made up of a set of tuples. Wikipedia has a nice article that talks about the term "tuple" in both math and computer science contexts: http://en.wikipedia.org/wiki/Tuple So that's why we'd say that tuples are heterogeneous things: they've always been meant to represent fixed-size records. They are not designed to expand or contract in size, which is why we'd say that they're "immutable". So the way that Python uses tuples isn't really too far from their original math definition. > Is it the immutability of the tuple, or the fact you can't use a list as > a key that's pushed it in that direction, or was it really as simple as > one guy in the early days saying 'I prefer this convention'? At least from this point of view, it's not accidental that tuples are heterogeneous and immutable: that's their definition from years of mathematical usage. Don't blame just Guido. *grin* Hope this helps! From Dragonfirebane at aol.com Sat Aug 14 02:28:56 2004 From: Dragonfirebane at aol.com (Dragonfirebane@aol.com) Date: Sat Aug 14 02:29:06 2004 Subject: [Tutor] making a number slide game Message-ID: <1e9.2783730b.2e4eb6c8@aol.com> Hello all, I'm trying to make a non-GUI (for now) Python representation of the handheld tile-sliding game where there are numbered tiles from 1 to 15 in a 4 x 4 square with one empty square, the point of the game being to arrange them in order from 1 to 15. I remember a while ago (June 2004) there was a post regarding using sentinels to define the border of a minesweeper field (http://mail.python.org/pipermail/tutor/2004-June/029990.html), but i didn't quite understand it at the time and the archives only show it as a text file. I'd be grateful if anyone'd be willing to help me out by explaining sentinels to define the edge of a field (so that the program can check where in the field the empty space is, and if the collected user move is next to the space w/o getting an IndexError). The following is my code, which works up to the first move, as i have not yet programmed the rest and don't know where to start. #### import random numbers = [] play = True for i in range(1, 16): numbers.append('%02d' % i) while play: ranum = random.sample(numbers, 15) ranum.append(' ') posit = ['1A','2A','3A','4A','1B','2B','3B','4B','1C','2C','3C','4C','1D','2D','3D','4D'] posum = dict(zip(posit, ranum)) rposm = dict(zip(ranum, posit)) field = """------------------------------------- | | | | | | %s | %s | %s | %s | | | | | | ------------------------------------- | | | | | | %s | %s | %s | %s | | | | | | ------------------------------------- | | | | | | %s | %s | %s | %s | | | | | | ------------------------------------- | | | | | | %s | %s | %s | %s | | | | | | -------------------------------------""" % (posum['1A'], posum['2A'], posum['3A'], posum['4A'], posum['1B'], posum['2B'], posum['3B'], posum['4B'], posum['1C'], posum['2C'], posum['3C'], posum['4C'], posum['1D'], posum['2D'], posum['3D'], posum['4D']) print field move = raw_input("Enter number of tile you wish to move: ") if move not in (posum['4C'], posum['3D']): move = raw_input("Please select a tile bordering the blank space: ") else: pass if move == posum['4C']: posum['4D'] = posum['4C'] posum['4C'] = ' ' if move == posum['3D']: posum['4D'] = posum['3D'] posum['3D'] = ' ' field = """------------------------------------- | | | | | | %s | %s | %s | %s | | | | | | ------------------------------------- | | | | | | %s | %s | %s | %s | | | | | | ------------------------------------- | | | | | | %s | %s | %s | %s | | | | | | ------------------------------------- | | | | | | %s | %s | %s | %s | | | | | | -------------------------------------""" % (posum['1A'], posum['2A'], posum['3A'], posum['4A'], posum['1B'], posum['2B'], posum['3B'], posum['4B'], posum['1C'], posum['2C'], posum['3C'], posum['4C'], posum['1D'], posum['2D'], posum['3D'], posum['4D']) print field play = False ##until i program past the first move, so that the loop won't continue in the first move forever ### Thanks in advance, Orri Email: dragonfirebane@aol.com AIM: singingxduck Programming Python for the fun of it. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040813/8e041a3d/attachment.html From s4046441 at student.uq.edu.au Sat Aug 14 02:48:22 2004 From: s4046441 at student.uq.edu.au (Ms Soo Chong) Date: Sat Aug 14 02:48:30 2004 Subject: [Tutor] Questions again Message-ID: Hi all, Sorry I'm still new to python so if you happened to see a stupid question asked from me, just bear with it. ;p I have questions on PostgreSQL module. Referred to the help given by python tutor, I managed to import pg and did some queries on the interactive window. However, I don't quite understand the differences between old module "pg" and the newer module "pgDB" (http://www.pygresql.org/README.txt). Besides, I read through some tutorials and book, they all used cursor objects, can I use cursor objects too or I have to use other commands? FYI, I'm using the older module "pg" now. If I have to use other command, please kindly state them down too. THANK YOU IN ADVANCE... OS: Linux Looking forward to hear from you. Cheers, Shufen From s4046441 at student.uq.edu.au Sat Aug 14 02:55:33 2004 From: s4046441 at student.uq.edu.au (Ms Soo Chong) Date: Sat Aug 14 02:55:40 2004 Subject: [Tutor] More Questions Message-ID: Hi all, Is me again... I have some questions for cgi module too. >From this website, I found a rather useful tutorial regrading cgi module, http://www.cs.virginia.edu/~lab2q/lesson_7/ but unfortunately, the output is not available for some reasons. Thus, I tried the same script on my system and it showed a blank page in my web browser. Is there anything wrong with the script below? Because, I wanted to try something about cgi module and see if I can get the connection working between cgi and python. Thank you in advance. #!/usr/bin/python # Import the CGI module import cgi # Required header that tells the browser how to render the HTML. print "Content-Type: text/html\n\n" # Define function to generate HTML form. def generate_form(): print "\n" print "\n" print "\tInfo Form\n" print "\n" print "\n" print "\t

Please, enter your name and age.

\n" print "\t\n" print "\t\t\n" print "\t\t\n" print "\t\t\n" print "\t
Name:
Age:
\n" print "\t\n" print "\t\n" print "\t\n" print "\n" print "\n" # Define function display data. def display_data(name, age): print "\n" print "\n" print "\tInfo Form\n" print "\n" print "\n" print name, ", you are", age, "years old." print "\n" print "\n" # Define main function. def main(): form = cgi.FieldStorage() if (form.has_key("action") and form.has_key("name") \ and form.has_key("age")): if (form["action"].value == "display"): display_data(form["name"].value, form["age"].value) else: generate_form() # Call main function. main() Cheers From kent_johnson at skillsoft.com Sat Aug 14 03:22:20 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sat Aug 14 03:22:28 2004 Subject: [Tutor] Another reason to use functions - testability Message-ID: <6.1.0.6.0.20040813211714.02a4f518@mail4.skillsoft.com> I just was reminded of another good reason to break a program into functions - for testability. If your program is a single linear sequence, you have to test it as a whole - give some inputs, see what comes out. There is no way to test the pieces. If you don't get the expected result, you have to inspect the whole program to see where the problem is. If you write the program as small functions, you can write unit tests for each function individually. If a test fails you just have a small amount of code to look at to find the problem. When the tests succeed you have confidence that the pieces are working as expected. Then you can combine them to something bigger. Kent From python-tutor at vs.megalink.ru Sat Aug 14 03:44:40 2004 From: python-tutor at vs.megalink.ru (Vsevolod Sipakov) Date: Sat Aug 14 03:44:44 2004 Subject: [Tutor] Me again In-Reply-To: <6.1.2.0.2.20040813062112.04be4290@rcblue.com> References: <6.1.2.0.2.20040813062112.04be4290@rcblue.com> Message-ID: <20040814014440.GB21324@megalink.ru> Hi, On Fri, Aug 13, 2004 at 06:21:47AM -0700, Dick Moores wrote: > Vsevolod Sipakov wrote at 05:34 8/13/2004: > >def average(l): > > return sum(l) / len(l) > > >>> l = [1,2,3,4,4] > >>> print average(l) > 2 > > Shouldn't this be: > >>> def average(l): > return sum(l)*1.0 / len(l) Oops... :-) Note to self: Use unittest. Always. > >>> l = [1,2,3,4,4] > >>> print average(l) > 2.8 -- Vsevolod Sipakov From rmkrauter at yahoo.com Sat Aug 14 04:37:59 2004 From: rmkrauter at yahoo.com (Rich Krauter) Date: Sat Aug 14 04:37:48 2004 Subject: [Tutor] making a number slide game In-Reply-To: <1e9.2783730b.2e4eb6c8@aol.com> References: <1e9.2783730b.2e4eb6c8@aol.com> Message-ID: <411D7B07.8020102@yahoo.com> Dragonfirebane@aol.com wrote: > Hello all, > > I'm trying to make a non-GUI (for now) Python representation of the handheld > tile-sliding game where there are numbered tiles from 1 to 15 in a 4 x 4 > square with one empty square, the point of the game being to arrange them in order > from 1 to 15. I remember a while ago (June 2004) there was a post regarding > using sentinels to define the border of a minesweeper field > (http://mail.python.org/pipermail/tutor/2004-June/029990.html), but i didn't quite understand it > at the time and the archives only show it as a text file. I'd be grateful if > anyone'd be willing to help me out by explaining sentinels to define the edge of > a field (so that the program can check where in the field the empty space is, > and if the collected user move is next to the space w/o getting an > IndexError). The following is my code, which works up to the first move, as i have not > yet programmed the rest and don't know where to start. > Hi Dfb, The link you posted contains good advice; that said, I tried the following (more or less ignoring the good advice): import random blank_char = ' ' size = 16 numbers = range(1,size) ranum = random.sample(numbers, size-1) ranum.append(blank_char) # no diagonal moves allowed neighbors = [[1,4], [0,2,5], [1,3,6], [2,7], [0,5,8], [1,4,6,9], [2,5,7,10], [3,6,11], [4,9,12], [5,8,10,13], [6,9,11,14], [7,10,15], [8,13], [9,12,14], [10,13,15], [11,14]] field = """ ------------------------------------- | | | | | | %s | %s | %s | %s | | | | | | ------------------------------------- | | | | | | %s | %s | %s | %s | | | | | | ------------------------------------- | | | | | | %s | %s | %s | %s | | | | | | ------------------------------------- | | | | | | %s | %s | %s | %s | | | | | | ------------------------------------- """ play = True while play: print field%(tuple(['%2s'%n for n in ranum])) move = int(raw_input("Enter number of tile you wish to move: ")) if move >= size: print 'Invalid choice' continue elif move <= 0: break move_index = ranum.index(move) blank_index = ranum.index(blank_char) if blank_index in neighbors[move_index]: # valid move, so swap the values ranum[move_index] = blank_char ranum[blank_index] = move else: print 'Invalid move' I tried to separate the board creation from the game-playing; but did very little error checking. e.g. if the user passes in a letter the program will choke, etc., etc. I used a 1-d list of known size (your 'ranum' list) to create the board, so it was easy to check for boundary cases - i.e. I didn't need 'sentinels'. Also, I cheated by hard-wiring the allowable moves in the 'neighbors' list, which is ok for this size board, but anything larger would be a pain to hardwire. The 'neighbors' list could probably be generated; in the meantime, I figured I'd send this along. Good luck. Rich From david at graniteweb.com Sat Aug 14 06:59:20 2004 From: david at graniteweb.com (David Rock) Date: Sat Aug 14 06:59:29 2004 Subject: [Tutor] avoid split function In-Reply-To: <6.1.0.6.0.20040813105143.02a38350@mail4.skillsoft.com> References: <20040813143336.71874.qmail@web52601.mail.yahoo.com> <6.1.0.6.0.20040813105143.02a38350@mail4.skillsoft.com> Message-ID: <20040814045920.GA2905@wdfs.attbi.com> * Kent Johnson [2004-08-13 10:54]: > As long as I am being picky, I'll point out that there are quite a few > special cases to consider. I don't think either David or Chad's solution > duplicates the behavior of string.split() on all of them. (Hmm, sounds like > a good opportunity to learn about unittest :-) > > >>> 'abc de'.split() # Multiple spaces between words > ['abc', 'de'] > > >>> 'abc'.split() # Just one word > ['abc'] > > >>> ''.split() # Empty string > [] > > >>> 'abc '.split() # Trailing spaces > ['abc'] > > >>> ' abc'.split() # Leading spaces > ['abc'] I had thought about most of these, but like I asked originally, there is a reason that split() already exists. I suppose the most correct answer would have been "read the split() source" :-) -- David Rock david@graniteweb.com -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20040813/434ac27e/attachment-0001.pgp From rdm at rcblue.com Sat Aug 14 11:29:54 2004 From: rdm at rcblue.com (Dick Moores) Date: Sat Aug 14 11:29:57 2004 Subject: [Tutor] What is "in-line code"? Message-ID: <6.1.2.0.2.20040814021946.05d04458@rcblue.com> I've been trying to read Guido van Rossum's essay, "Python Patterns - An Optimization Anecdote" (). There are many things I don't understand in it, but I'll ask about only one. What is "in-line code"? It appears in the Conclusion section, in "Try to use map(), filter() or reduce() to replace an explicit for loop, but only if you can use a built-in function: map with a built-in function beats for loop, but a for loop with in-line code beats map with a lambda function!" Also, "in-lining" is mentioned in "Avoid calling functions written in Python in your inner loop. This includes lambdas. In-lining the inner loop can save a lot of time." Thanks, tutors. Dick Moores From kent_johnson at skillsoft.com Sat Aug 14 13:38:04 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sat Aug 14 13:38:44 2004 Subject: [Tutor] What is "in-line code"? In-Reply-To: <6.1.2.0.2.20040814021946.05d04458@rcblue.com> References: <6.1.2.0.2.20040814021946.05d04458@rcblue.com> Message-ID: <6.1.0.6.0.20040814071846.02a4ead8@mail4.skillsoft.com> By 'in-line code' he means code written in C, i.e. using builtin capabilities of Python rather than user-written code. For example this function is an example of reduce with lambda (not in-line): def f2(list): return reduce(lambda string, item: string + chr(item), list, "") When this runs, the interpreter has to call back into user code for the lambda. reduce() itself is written in C but the callback function is not. This is a significant performance hit. On the other hand, in this function def f6(list): return string.joinfields(map(chr, list), "") the callback is a builtin (chr()) so the map operation is entirely in C (in-line) and it is very fast. Note the article you cite is out-of-date in a few minor ways. The usual way to join a list is now with the join method of the string, so f6 might be written as def f6(list): return "".join(map(chr, list)) The string module is implemented in Python and string.joinfields(word, sep) delegates to sep.join(words), so this version would probably be faster in modern Python. Second, the timeit module replaces Guido's homebrew timing function. You might be also be interested in this recent post: http://mail.python.org/pipermail/tutor/2004-July/030787.html I'm kind of an optimization junkie so feel free to ask more questions :-) Kent At 02:29 AM 8/14/2004 -0700, Dick Moores wrote: >I've been trying to read Guido van Rossum's essay, "Python Patterns - An >Optimization Anecdote" (). >There are many things I don't understand in it, but I'll ask about only >one. What is "in-line code"? It appears in the Conclusion section, in "Try >to use map(), filter() or reduce() to replace an explicit for loop, but >only if you can use a built-in function: map with a built-in function >beats for loop, but a for loop with in-line code beats map with a lambda >function!" > >Also, "in-lining" is mentioned in "Avoid calling functions written in >Python in your inner loop. This includes lambdas. In-lining the inner loop >can save a lot of time." > >Thanks, tutors. > >Dick Moores > > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From missive at hotmail.com Sat Aug 14 14:43:59 2004 From: missive at hotmail.com (Lee Harr) Date: Sat Aug 14 14:44:03 2004 Subject: [Tutor] Re: What is "in-line code"? Message-ID: >(). There are many things >I don't understand in it, but I'll ask about only one. What is "in-line >code"? It appears in the Conclusion section, in "Try to use map(), >filter() or reduce() to replace an explicit for loop, but only if you can >use a built-in function: map with a built-in function beats for loop, but >a for loop with in-line code beats map with a lambda function!" > >Also, "in-lining" is mentioned in "Avoid calling functions written in >Python in your inner loop. This includes lambdas. In-lining the inner >loop can save a lot of time." > "In-line" just means that the code is written out right there in the body of the loop, instead of being in a separate function which the loop calls. For example ... # Not In-line >>>def add2(a, b): ... return a + b ... >>>pairs = [(1, 2), (3, 4), (5, 6)] >>>for pair in pairs: ... print add2(pair[0], pair[1]) ... 3 7 11 # Same result with In-line code >>>for pair in pairs: ... print pair[0] + pair[1] ... 3 7 11 So, if what you are doing is very simple, you might choose not to separate out add2() and just write the code in-line. In python, functions calls are relatively "heavy" and if the pairs list has many many elements you could get a noticeable speedup. C compilers (and probably other languages too...) allow you to mark some functions or methods as "in-line", which is nice since it allows you to show the code as a separate entity (which helps maintenance) but get the speed-up of actually copying the code in to the body of the loop. A different (but related?) optimization would be "unrolling" where the code of the for loop is actually copied over and over instead of wasting the time to jump back to the beginning of the code for the next iteration. _________________________________________________________________ Protect your PC - get McAfee.com VirusScan Online http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963 From kent_johnson at skillsoft.com Sat Aug 14 14:54:45 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sat Aug 14 14:54:50 2004 Subject: [Tutor] Re: What is "in-line code"? In-Reply-To: References: Message-ID: <6.1.0.6.0.20040814085014.02a4e5b8@mail4.skillsoft.com> Obviously Lee's answer is different than mine. I think Lee is right =:-) Lee's answer is definitely the conventional meaning of in-line. I thought from the context that Guido was talking about Python vs C but on second reading I see Lee's interpretation also works. That said, it is still true that for optimization, you should prefer functions written in C over functions written in Python. Calling a Python function in a loop is slower than in-line code in a loop is slower than moving the whole loop to C. Kent At 05:13 PM 8/14/2004 +0430, Lee Harr wrote: "In-line" just means that the code is written out right there >in the body of the loop, instead of being in a separate >function which the loop calls. For example ... > ># Not In-line >>>>def add2(a, b): >... return a + b >... >>>>pairs = [(1, 2), (3, 4), (5, 6)] >>>>for pair in pairs: >... print add2(pair[0], pair[1]) >... >3 >7 >11 > > ># Same result with In-line code >>>>for pair in pairs: >... print pair[0] + pair[1] >... >3 >7 >11 > > >So, if what you are doing is very simple, you might choose not to >separate out add2() and just write the code in-line. > >In python, functions calls are relatively "heavy" and if the pairs >list has many many elements you could get a noticeable speedup. > >C compilers (and probably other languages too...) allow you to mark >some functions or methods as "in-line", which is nice since it allows >you to show the code as a separate entity (which helps maintenance) >but get the speed-up of actually copying the code in to the body >of the loop. > >A different (but related?) optimization would be "unrolling" where the >code of the for loop is actually copied over and over instead of >wasting the time to jump back to the beginning of the code for the >next iteration. > >_________________________________________________________________ >Protect your PC - get McAfee.com VirusScan Online >http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963 > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From alan.gauld at blueyonder.co.uk Sat Aug 14 15:50:55 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Aug 14 16:01:32 2004 Subject: [Tutor] What is "in-line code"? References: <6.1.2.0.2.20040814021946.05d04458@rcblue.com> Message-ID: <008301c48207$0ec9baa0$6401a8c0@xp> > What is "in-line code"? Code that appears in-line. In other words its not in a function. This is the flip side of the recent thread about why not to write linear programs... Thus: def add4(x): return x+4 for n in range(5): print add4(n) Uses a function but we can write the same using inline cde instead: for n in range(5): print n + 4 This is faster because it avoids the need for a function call, and function calls in Python are significant speed hits. So where you might need to speed up a loop you can often do quite a lot by deconstructing a function used inside the loop into in-line code. In the case above it's obvious but with longer functions you might have a lot of code to retype, especialoly if the function is used in several places, so you wind up maintaining the code both in the function and in the loop. Its a trade off of convenience versus speed. > It appears in the Conclusion section, in "Try to use map(), > filter() or reduce() to replace an explicit for loop, but only if you can > use a built-in function: So he is saying that the overhead of calling a python function is greater than the savings of using map. (Nowadays we would use a comprehension in most cases where map() was used - which is faster still) HTH, Alan G. From alipolatel at yahoo.com Sat Aug 14 16:49:07 2004 From: alipolatel at yahoo.com (Ali Polatel) Date: Sat Aug 14 16:49:11 2004 Subject: [Tutor] Tkinter the great Message-ID: <20040814144907.89742.qmail@web61004.mail.yahoo.com> Friends I wrote a programme with Tkinter... I have converted it into an exe file with py2exe Now when I run it still there is a dos box behind it :( How can i get rid of it? Regards --------------------------------- Do you Yahoo!? Yahoo! Mail - 50x more storage than other providers! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040814/641d4661/attachment.htm From alipolatel at yahoo.com Sat Aug 14 17:25:21 2004 From: alipolatel at yahoo.com (Ali Polatel) Date: Sat Aug 14 17:25:24 2004 Subject: [Tutor] Another prob with Telnet In-Reply-To: <00b701c48179$a75b2210$6401a8c0@xp> Message-ID: <20040814152521.78161.qmail@web61005.mail.yahoo.com> I looked up the web-site http://www.robelle.com/library/smugbook/ascii.txt but couldn't understand anything : "LF 12 10 a ^J Line Feed" What should I type in my programme script to make it work? Regards, --------------------------------- Do you Yahoo!? Yahoo! Mail - 50x more storage than other providers! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040814/57b716f7/attachment.html From klas.martelleur at telia.com Sat Aug 14 17:50:53 2004 From: klas.martelleur at telia.com (Klas Marteleur) Date: Sat Aug 14 17:40:54 2004 Subject: [Tutor] Entry box + browse button Message-ID: <200408141750.53778.klas.martelleur@telia.com> Hi again My very advanced convert program is developing very fast :) I am now working with my fancy GUI and i would like to have the possibility to enter filenames in "Entry boxes" as well as the possibility to browse files. See my fancy screenshot attached to this mail :) I can write a filename in the entry boxes but i dont understand what i need to do to get the browse function to work. Here somewere is were i am at at the moment.... #############snip############ self.infile ="/home/klas/Python_filer/Tragic/ebom_from_file_wider.txt" self.inputEntry = Entry(master) self.inputEntry.insert(INSERT,self.infile) self.inputEntry.grid(row=0,column=1) #############snip############ self.inputBrowseButton = Button(master, command = self.openFile) self.inputBrowseButton.configure(text = "Browse") self.inputBrowseButton.grid(row=0,column=2) #############snip############ def openFile(self): import tkFileDialog self.infile=tkFileDialog.askopenfilename() #############snip############ First i thought that if i just changed the value "self.infile" in the "def openFile" function that the entry would change. But i realize now that is not that easy..... I am thinking.... bind.... hmmmm?? Could some nice person guide me in the right direction :) Thanks Klas -------------- next part -------------- A non-text attachment was scrubbed... Name: Convert.jpg Type: image/jpeg Size: 14301 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20040814/79c68560/Convert-0001.jpg From rdm at rcblue.com Sat Aug 14 17:45:05 2004 From: rdm at rcblue.com (Dick Moores) Date: Sat Aug 14 17:45:09 2004 Subject: [Tutor] _Object Thinking_, by David West Message-ID: <6.1.2.0.2.20040814083146.04f0bec0@rcblue.com> I was in a Barnes & Noble last night looking at _Code Complete_ (2nd ed.), mentioned by Mike Hansen recently. I've ordered a cheap copy through Amazon. I also noticed an interesting but difficult book, _Object Thinking_, by David West, (Microsoft Press, 2004). I'm wondering what the tutors think of this book. Here's a link to the book on Amazon: http://tinyurl.com/6zypm Dick Moores From pythonTutor at venix.com Sat Aug 14 18:10:04 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Sat Aug 14 18:10:21 2004 Subject: [Tutor] Another prob with Telnet In-Reply-To: <20040814152521.78161.qmail@web61005.mail.yahoo.com> References: <20040814152521.78161.qmail@web61005.mail.yahoo.com> Message-ID: <1092499803.7921.14.camel@laptop.venix.com> On Sat, 2004-08-14 at 11:25, Ali Polatel wrote: > I looked up the web-site > http://www.robelle.com/library/smugbook/ascii.txt but couldn't > understand anything : > "LF 12 10 a ^J Line Feed" LF short name for the character 12 value of character in octal 10 value of character in decimal a value of character in hex ^J keystroke on keyboard (ctrl+j) Line Feed long name for character. The python builtin functions ord and chr are the most useful for dealing with character values. chr takes an integer value and returns the corresponding string character. ord takes a string character and returns its integer value. ord('\n') == 10 chr(10) == '\n' The column of decimal values is generally the most useful when working with ord and chr. > What should I type in my programme script to make it work? assume fp is your file type object fp.write('\n') # should write a linefeed fp.write(chr(10)) # should also write a linefeed You may need to use fp.flush() to force your output out of the buffer. > Regards, > > > > ______________________________________________________________________ > Do you Yahoo!? > Yahoo! Mail - 50x more storage than other providers! > > ______________________________________________________________________ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From alan.gauld at blueyonder.co.uk Sat Aug 14 18:40:31 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Aug 14 18:41:32 2004 Subject: [Tutor] Entry box + browse button References: <200408141750.53778.klas.martelleur@telia.com> Message-ID: <00a501c4821d$6a497d00$6401a8c0@xp> > I can write a filename in the entry boxes but i dont understand what i need to > do to get the browse function to work. Here somewere is were i am at at the > moment.... There is no standard file browser dialog - this is a major gap in Tkinter, or at least in the Python MegaWidgets (PMW), which is where I'd expect to find it... There are some available on the net, try the Vaults of Parnassus as a starting point or this page here as an (untried!) example. http://home.cfl.rr.com/genecash/tree.html Alan G. > > #############snip############ > > self.infile ="/home/klas/Python_filer/Tragic/ebom_from_file_wider.txt" > self.inputEntry = Entry(master) > self.inputEntry.insert(INSERT,self.infile) > self.inputEntry.grid(row=0,column=1) > > #############snip############ > > self.inputBrowseButton = Button(master, command = self.openFile) > self.inputBrowseButton.configure(text = "Browse") > self.inputBrowseButton.grid(row=0,column=2) > > #############snip############ > > def openFile(self): > import tkFileDialog > self.infile=tkFileDialog.askopenfilename() > > #############snip############ > > First i thought that if i just changed the value "self.infile" in the "def > openFile" function that the entry would change. But i realize now that is not > that easy..... I am thinking.... bind.... hmmmm?? > > Could some nice person guide me in the right direction :) > > Thanks > Klas From alan.gauld at blueyonder.co.uk Sat Aug 14 19:42:43 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Aug 14 19:43:43 2004 Subject: [Tutor] Another prob with Telnet References: <20040814152521.78161.qmail@web61005.mail.yahoo.com> Message-ID: <00af01c48226$1a52f930$6401a8c0@xp> > I looked up the web-site but couldn't understand anything : > "LF 12 10 a ^J Line Feed" LF = nmonic abbreviation 12 = octal value 10 = decimal value a = hex value So to send the LF ASCII character we would semd any of: 012 10 0xa > What should I type in my programme script to make it work? And to insert that into a string use chr() like print "This string ends with a line feed" + chr(10) HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/ From rdm at rcblue.com Sat Aug 14 21:06:04 2004 From: rdm at rcblue.com (Dick Moores) Date: Sat Aug 14 21:06:51 2004 Subject: [Tutor] problem with time module Message-ID: <6.1.2.0.2.20040814115248.0445c008@rcblue.com> From the time module doc at , I expected mktime(localtime()) and time() to be approx. 7*3600 seconds apart (I'm on the U.S. west coast, in -0700). But they're not: >>> from time import * >>> mktime(localtime());time() 1092510279.0 1092510279.2650001 Have I misunderstood something? Thanks, tutors. Dick Moores Win XP, Python 2.3.4 From klas.martelleur at telia.com Sat Aug 14 21:19:38 2004 From: klas.martelleur at telia.com (Klas Marteleur) Date: Sat Aug 14 21:09:40 2004 Subject: [Tutor] Entry box + browse button In-Reply-To: <00a501c4821d$6a497d00$6401a8c0@xp> References: <200408141750.53778.klas.martelleur@telia.com> <00a501c4821d$6a497d00$6401a8c0@xp> Message-ID: <200408142119.38941.klas.martelleur@telia.com> hmm Alan! I am not sure i understand you correctly . The tkFiledialog module workes for me (see screenshot) but i dont know how to combine it with the "Entry" box. i want to have the possibility to Either enter filepath in the box Or browse after the file using tkFileDialog. I dont know how to combine the two choices. is it possible to have that choice? Regards Klas l?rdagen den 14 augusti 2004 18.40 skrev Alan Gauld: > > I can write a filename in the entry boxes but i dont understand what > > i need to > > > do to get the browse function to work. Here somewere is were i am at > > at the > > > moment.... > > There is no standard file browser dialog - this is a major gap in > Tkinter, or at least in the Python MegaWidgets (PMW), which is > where I'd expect to find it... > > There are some available on the net, try the Vaults of Parnassus > as a starting point or this page here as an (untried!) example. > > http://home.cfl.rr.com/genecash/tree.html > > Alan G. > > > #############snip############ > > > > self.infile > > ="/home/klas/Python_filer/Tragic/ebom_from_file_wider.txt" > > > self.inputEntry = Entry(master) > > self.inputEntry.insert(INSERT,self.infile) > > self.inputEntry.grid(row=0,column=1) > > > > #############snip############ > > > > self.inputBrowseButton = Button(master, command = > > self.openFile) > > > self.inputBrowseButton.configure(text = "Browse") > > self.inputBrowseButton.grid(row=0,column=2) > > > > #############snip############ > > > > def openFile(self): > > import tkFileDialog > > self.infile=tkFileDialog.askopenfilename() > > > > #############snip############ > > > > First i thought that if i just changed the value "self.infile" in > > the "def > > > openFile" function that the entry would change. But i realize now > > that is not > > > that easy..... I am thinking.... bind.... hmmmm?? > > > > Could some nice person guide me in the right direction :) > > > > Thanks > > Klas -------------- next part -------------- A non-text attachment was scrubbed... Name: filedialog.jpg Type: image/jpeg Size: 19421 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20040814/400c217a/filedialog-0001.jpg From rdm at rcblue.com Sat Aug 14 21:20:46 2004 From: rdm at rcblue.com (Dick Moores) Date: Sat Aug 14 21:20:53 2004 Subject: [Tutor] What is "in-line code"? In-Reply-To: <6.1.0.6.0.20040814071846.02a4ead8@mail4.skillsoft.com> References: <6.1.2.0.2.20040814021946.05d04458@rcblue.com> <6.1.0.6.0.20040814071846.02a4ead8@mail4.skillsoft.com> Message-ID: <6.1.2.0.2.20040814051336.02b17220@rcblue.com> Kent Johnson, Alan Gauld, and Lee Harr, Thanks very much for your mutually complementary explanations. Dick Moores From alan.gauld at blueyonder.co.uk Sat Aug 14 21:24:40 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Aug 14 21:25:40 2004 Subject: [Tutor] Entry box + browse button References: <200408141750.53778.klas.martelleur@telia.com> <00a501c4821d$6a497d00$6401a8c0@xp> <200408142119.38941.klas.martelleur@telia.com> Message-ID: <00ba01c48234$58844430$6401a8c0@xp> > The tkFiledialog module workes for me Oops! Spoke too soon. I had a search through Grayson's Tkinter book and he doesn't appear to have a reference to that one!... Just checked again and now that I know what to look for, sure enough it's there, but only one example so far as I see.. > i want to have the possibility to Either enter filepath > in the box Or browse after the file using tkFileDialog. > I dont know how to combine the two choices. >From what I'm reading you just have a method attached to your browe button that launches the dialog. The return value appears to be the selected filename. What have you tried and how did it fail? Sorry for the bad steer, Alan G. From alan.gauld at blueyonder.co.uk Sat Aug 14 21:35:41 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Aug 14 21:36:40 2004 Subject: [Tutor] _Object Thinking_, by David West References: <6.1.2.0.2.20040814083146.04f0bec0@rcblue.com> Message-ID: <00c901c48235$e26a2060$6401a8c0@xp> > I was in a Barnes & Noble last night looking at _Code Complete_ (2nd > ed.), mentioned by Mike Hansen recently. I've ordered a cheap copy > through Amazon. Classic book and every software engineer should own (and read!) a copy. > I also noticed an interesting but difficult book, _Object Thinking_, by > David West, (Microsoft Press, 2004). I'm wondering what the tutors think > of this book. Here's a link to the book on Amazon: http://tinyurl.com/6zypm I haven't read it but from the reviews I'd expect: 1) its theoretical rather than practice based, which is normally most useful after you have the basics of OOP syntax etc well understood 2) It's jumping on the "Agile Methods" bandwagon which is sweeeping the industry just now. Agile methods are effective within their domain(*), and that domain matches the area where languages like Python live, so there might be a good match for readers of this group. But on a cautionary note: theoretical book on OO tend to become very abstract very quickly, and often don't translate well into everyday practice. (And I've read a lot of 'em!) If you want to understand OOP I'd still recommend something like Timothy Budds classic OOP book or Grady Booch's classic OOA/D first. But this is purely based on reading the Amazon blurb and I may well add it to my list of things to read whe I get the time. Alan G. (*)And for a good objective study of where that domain is I recommend Boehm's "Balancing Agility and Discipline". From rdm at rcblue.com Sat Aug 14 22:03:52 2004 From: rdm at rcblue.com (Dick Moores) Date: Sat Aug 14 22:03:55 2004 Subject: [Tutor] _Object Thinking_, by David West In-Reply-To: <00c901c48235$e26a2060$6401a8c0@xp> References: <6.1.2.0.2.20040814083146.04f0bec0@rcblue.com> <00c901c48235$e26a2060$6401a8c0@xp> Message-ID: <6.1.2.0.2.20040814124140.05d04458@rcblue.com> Alan Gauld wrote at 12:35 8/14/2004: > > I also noticed an interesting but difficult book, _Object Thinking_, >by > > David West, (Microsoft Press, 2004). I'm wondering what the tutors >think > > of this book. Here's a link to the book on Amazon: >http://tinyurl.com/6zypm > >I haven't read it but from the reviews I'd expect: >1) its theoretical rather than practice based, which is normally > most useful after you have the basics of OOP syntax etc well > understood >2) It's jumping on the "Agile Methods" bandwagon which is sweeeping > the industry just now. Agile methods are effective within their > domain(*), and that domain matches the area where languages like > Python live, so there might be a good match for readers of this > group. > >But on a cautionary note: theoretical book on OO tend to become >very abstract very quickly, and often don't translate well into >everyday practice. (And I've read a lot of 'em!) > >If you want to understand OOP I'd still recommend something like >Timothy Budds classic OOP book or Grady Booch's classic OOA/D first. Is this the Budds book: http://tinyurl.com/6v68l ? My local library has "Object-oriented analysis and design with applications" by Grady Booch. I assume this is the one you mean? I'm 6th in line for the one copy. And there are several very inexpensive copies available through Bookfinder.com. Dick Moores From klas.martelleur at telia.com Sat Aug 14 23:10:19 2004 From: klas.martelleur at telia.com (Klas Marteleur) Date: Sat Aug 14 23:00:17 2004 Subject: [Tutor] Entry box + browse button In-Reply-To: <00ba01c48234$58844430$6401a8c0@xp> References: <200408141750.53778.klas.martelleur@telia.com> <200408142119.38941.klas.martelleur@telia.com> <00ba01c48234$58844430$6401a8c0@xp> Message-ID: <200408142310.19287.klas.martelleur@telia.com> I dont know what to try actually. Some idea i had was to call a function from the "command" in self.inputBrowseButton (self.openFile) and change the value of self.infile in that function. But i am not so sure about that idea anymore. Some other idea i had was to "bind" a button the "inputEntry" but i have no idea how to do that, i am just fumbling in the dark.... I could really need some guidance :) Here is how my gui program loos at the moment #!/usr/bin/python from Tkinter import * class CreateEbom(Frame): def __init__(self, master): self.myMaster = master self.myMaster.title('Tragic Converter BETA 0.1') self.myContainer1 = Grid() self.inputFile = Label(master, text="Input file:") self.inputFile.grid(row=0, sticky=E) self.outputFile = Label(master,text="Output file:") self.outputFile.grid(row=1, sticky=E) self.infile = "/home/klas/Python_filer/Tragic/ebom_from_file_wider.txt" self.inputEntry = Entry(master) self.inputEntry.insert(INSERT,self.infile) self.inputEntry.grid(row=0,column=1) self.outfile = "/home/klas/Python_filer/Tragic/output.txt" self.outputEntry = Entry(master) self.outputEntry.insert(INSERT,self.outfile) self.outputEntry.grid(row=1,column=1) self.inputBrowseButton = Button(master, command = self.openFile) self.inputBrowseButton.configure(text = "Browse") self.inputBrowseButton.grid(row=0,column=2) self.outputBrowseButton = Button(master, command = self.callback) self.outputBrowseButton.configure(text = "Browse") self.outputBrowseButton.grid(row=1,column=2) self.latestRevisonLabel = Label(master,text="Latest rev:") self.latestRevisonLabel.grid(row=2, sticky=E) self.var = IntVar() self.latestRevisionCheckbutton = Checkbutton(master,variable=self.var, command=self.checkButton) self.latestRevisionCheckbutton.grid(row=2,column=1,sticky=W) self.convertButton = Button(master, command = self.doProcessFiles) self.convertButton.configure(text="Convert") self.convertButton.grid(row=3,column=1,sticky=E) self.exitButton = Button(master, command = self.doExit) self.exitButton.configure(text="Exit") self.exitButton.grid(row=3,column=2,sticky=E) self.designedByLabel = Label(master,text="This program is designed in Python by Klas Marteleur") self.designedByLabel.grid(row=4,column=0,columnspan=3,sticky=S) def callback(self): print "Called the callback!" def checkButton(self): print "Variable is", self.var.get() def openFile(self): import tkFileDialog infile=tkFileDialog.askopenfilename() def doProcessFiles(self): from createEbom import * inputFileName = self.inputEntry.get() outputFileName = self.outputEntry.get() latestRevision = self.var.get() processFiles(inputFileName,outputFileName,latestRevision) def doExit(self): import sys sys.exit() return print "\n"*100 # a simple way to clear the screen print "Starting..." root = Tk() createebom = CreateEbom(root) root.mainloop() print "Shutdown in progress..." print "Done!" From bgailer at alum.rpi.edu Sat Aug 14 23:04:06 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sat Aug 14 23:01:02 2004 Subject: {Spam?} [Tutor] problem with time module In-Reply-To: <6.1.2.0.2.20040814115248.0445c008@rcblue.com> References: <6.1.2.0.2.20040814115248.0445c008@rcblue.com> Message-ID: <6.1.0.6.0.20040814150304.0271ff90@mail.mric.net> At 01:06 PM 8/14/2004, Dick Moores wrote: > From the time module doc at >, >I expected mktime(localtime()) and time() to be approx. 7*3600 seconds >apart (I'm on the U.S. west coast, in -0700). > >But they're not: > > >>> from time import * > >>> mktime(localtime());time() >1092510279.0 >1092510279.2650001 Try: mktime(gmtime())-time() This suggests that time() is giving the local time rather than GMT. Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From rdm at rcblue.com Sat Aug 14 23:54:56 2004 From: rdm at rcblue.com (Dick Moores) Date: Sat Aug 14 23:54:58 2004 Subject: [Tutor] problem with time module In-Reply-To: <6.1.0.6.0.20040814150304.0271ff90@mail.mric.net> References: <6.1.2.0.2.20040814115248.0445c008@rcblue.com> <6.1.0.6.0.20040814150304.0271ff90@mail.mric.net> Message-ID: <6.1.2.0.2.20040814145103.050e0ec0@rcblue.com> Bob Gailer wrote at 14:04 8/14/2004: >At 01:06 PM 8/14/2004, Dick Moores wrote: >> From the time module doc at >>, >>I expected mktime(localtime()) and time() to be approx. 7*3600 seconds >>apart (I'm on the U.S. west coast, in -0700). >> >>But they're not: >> >> >>> from time import * >> >>> mktime(localtime());time() >>1092510279.0 >>1092510279.2650001 > >Try: >mktime(gmtime())-time() > >This suggests that time() is giving the local time rather than GMT. Or mktime(gmtime());time() Thanks. Yes, that was my point. Dick Moores From kent_johnson at skillsoft.com Sun Aug 15 00:07:01 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sun Aug 15 00:07:09 2004 Subject: [Tutor] Entry box + browse button In-Reply-To: <200408142310.19287.klas.martelleur@telia.com> References: <200408141750.53778.klas.martelleur@telia.com> <200408142119.38941.klas.martelleur@telia.com> <00ba01c48234$58844430$6401a8c0@xp> <200408142310.19287.klas.martelleur@telia.com> Message-ID: <6.1.0.6.0.20040814180014.02a4cc18@mail4.skillsoft.com> Klas, One thing you can do is connect the entry widgets to Tk Variables. Then any change to the Variable will be reflected in the Entry and vice versa. By having the Browse button set the Variable it will show up in the Entry. In doProcessFiles() you read the value of the Variable. Here are the changes needed to your program to set this up for the input file: - Create infile and inputEntry like this: self.infile = StringVar() self.infile.set("/home/klas/Python_filer/Tragic/ebom_from_file_wider.txt") self.inputEntry = Entry(master) self.inputEntry["textvariable"] = self.infile self.inputEntry.grid(row=0,column=1) - openFile() looks like this: def openFile(self): import tkFileDialog self.infile.set(tkFileDialog.askopenfilename()) - In doProcessFiles() change inputFileName = self.inputEntry.get() to inputFileName = self.infile.get() You have to make similar changes for the outputEntry. I hope I have correctly understood what you are trying to do! Kent http://www.kentsjohnson.com At 11:10 PM 8/14/2004 +0200, Klas Marteleur wrote: >I dont know what to try actually. > >Some idea i had was to call a function from the "command" in >self.inputBrowseButton (self.openFile) and change the value of self.infile in >that function. But i am not so sure about that idea anymore. > >Some other idea i had was to "bind" a button the "inputEntry" but i have no >idea how to do that, i am just fumbling in the dark.... > >I could really need some guidance :) From klas.martelleur at telia.com Sun Aug 15 00:17:58 2004 From: klas.martelleur at telia.com (Klas Marteleur) Date: Sun Aug 15 00:07:57 2004 Subject: [Tutor] Entry box + browse button SOLVED In-Reply-To: <200408142310.19287.klas.martelleur@telia.com> References: <200408141750.53778.klas.martelleur@telia.com> <00ba01c48234$58844430$6401a8c0@xp> <200408142310.19287.klas.martelleur@telia.com> Message-ID: <200408150017.58784.klas.martelleur@telia.com> Hi again Actually i wasnt that far from the solution as i was thinking. The thing was to delete the text in the box before trying to add a new one (otherwise the new filename gets appended after the default one. This is what i did: I added two functions. One to call from the "inputBrowseButton" function and one to call from the "outputBrowseButton" function. def openInFile(self): import tkFileDialog infile = tkFileDialog.askopenfilename() self.inputEntry.delete(0,END) # Clean the default Entry self.inputEntry.insert(INSERT,infile) def saveAsFile(self): import tkFileDialog outfile = tkFileDialog.asksaveasfilename() self.outputEntry.delete(0,END) # Clean the default Entry self.outputEntry.insert(INSERT, outfile) Klas From s4046441 at student.uq.edu.au Sun Aug 15 00:13:38 2004 From: s4046441 at student.uq.edu.au (Ms Soo Chong) Date: Sun Aug 15 00:13:43 2004 Subject: [Tutor] Problem with CGI module Message-ID: Hi all, Is me again... I resend this message in case the previous one was overlooked. Can someone out there help me please. Thank you I have some questions for cgi module too. >From this website, I found a rather useful tutorial regrading cgi module, http://www.cs.virginia.edu/~lab2q/lesson_7/ but unfortunately, the output is not available for some reasons. Thus, I tried the same script on my system and it showed a blank page in my web browser. Is there anything wrong with the script below? Because, I wanted to try something about cgi module and see if I can get the connection working between cgi and python. Thank you in advance. #!/usr/bin/python # Import the CGI module import cgi # Required header that tells the browser how to render the HTML. print "Content-Type: text/html\n\n" # Define function to generate HTML form. def generate_form(): print "\n" print "\n" print "\tInfo Form\n" print "\n" print "\n" print "\t

Please, enter your name and age.

\n" print "\t\n" print "\t\t\n" print "\t\t\n" print "\t\t\n" print "\t
Name:
Age:
\n" print "\t\n" print "\t\n" print "\t\n" print "\n" print "\n" # Define function display data. def display_data(name, age): print "\n" print "\n" print "\tInfo Form\n" print "\n" print "\n" print name, ", you are", age, "years old." print "\n" print "\n" # Define main function. def main(): form = cgi.FieldStorage() if (form.has_key("action") and form.has_key("name") \ and form.has_key("age")): if (form["action"].value == "display"): display_data(form["name"].value, form["age"].value) else: generate_form() # Call main function. main() Cheers From s4046441 at student.uq.edu.au Sun Aug 15 00:16:06 2004 From: s4046441 at student.uq.edu.au (Ms Soo Chong) Date: Sun Aug 15 00:16:13 2004 Subject: [Tutor] Problem with PostgreSQL module Message-ID: Hi all, I resend this message too, just in case the previous one was overlooked. I really hope to hear from you guys soon. Sorry I'm still new to python so if you happened to see a stupid question asked from me, just bear with it. ;p I have questions on PostgreSQL module. Referred to the help given by python tutor, I managed to import pg and did some queries on the interactive window. However, I don't quite understand the differences between old module "pg" and the newer module "pgDB" (http://www.pygresql.org/README.txt). Besides, I read through some tutorials and book, they all used cursor objects, can I use cursor objects too or I have to use other commands? FYI, I'm using the older module "pg" now. If I have to use other command, please kindly state them down too. THANK YOU IN ADVANCE... OS: Linux Looking forward to hear from you. Cheers, Shufen From Dragonfirebane at aol.com Sun Aug 15 01:04:26 2004 From: Dragonfirebane at aol.com (Dragonfirebane@aol.com) Date: Sun Aug 15 01:04:34 2004 Subject: [Tutor] Comma at the end of a print command Message-ID: <105.4e0de8f7.2e4ff47a@aol.com> Hello all, I know that when you put a comma at the end of a print command, the next printed object will be printed on the same line, separated by a space. Is there a way to do this without the space separation? i.e.: def mod(): import msvcrt model = msvcrt.getch() if model == '1': print model(*) model = msvcrt.getch() ##to get the next number print model would output: 12 , printing the numbers one at a time, if '12' were inputed. as it is, the output is: 1 2 , which isn't what i want. So in other words: is there a way to provide 'real-time' printing without the space separation? The reason I'm using msvcrt.getch() is because if the number doesn't begin with a 1, then it must be below 10, as the choices are from 2 to 15; which would make it easier (no need to hit enter) to process the choice. * insert unknown symbol here Email: dragonfirebane@aol.com AIM: singingxduck Programming Python for the fun of it. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040814/febb95c2/attachment.htm From kent_johnson at skillsoft.com Sun Aug 15 02:07:45 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sun Aug 15 02:07:52 2004 Subject: [Tutor] Problem with PostgreSQL module In-Reply-To: References: Message-ID: <6.1.0.6.0.20040814195530.02a4c1d8@mail4.skillsoft.com> Shufen, pgdb uses the Python DB-API. This is a standardized API for database interface from Python. If you use DB-API your program will fairly portable between databases. (There are still some differences, for example SQL dialects, but DB-API helps.) DB-API supports cursors so the examples you are looking at are probably using this module. DB-API is documented here: http://www.python.org/peps/pep-0249.html pg was written before DB-API was standardized so it is specific to PostgreSQL. You should be able to tell which module the tutorials and books are using by looking at the import statements in their sample programs. HTH, Kent At 08:16 AM 8/15/2004 +1000, Ms Soo Chong wrote: >Hi all, > >I resend this message too, just in case the previous one was overlooked. > >I really hope to hear from you guys soon. > >Sorry I'm still new to python so if you happened to see a stupid question >asked from >me, just bear with it. ;p > >I have questions on PostgreSQL module. > >Referred to the help given by python tutor, I managed to import pg and did >some >queries on the interactive window. However, I don't quite understand the >differences >between old module "pg" and the newer module "pgDB" >(http://www.pygresql.org/README.txt). Besides, I read through some >tutorials and book, >they all used cursor objects, can I use cursor objects too or I have to >use other >commands? FYI, I'm using the older module "pg" now. If I have to use other >command, >please kindly state them down too. > >THANK YOU IN ADVANCE... > >OS: Linux > >Looking forward to hear from you. > >Cheers, >Shufen > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From kent_johnson at skillsoft.com Sun Aug 15 02:10:42 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sun Aug 15 02:10:48 2004 Subject: [Tutor] Problem with CGI module In-Reply-To: References: Message-ID: <6.1.0.6.0.20040814200841.02a4bf48@mail4.skillsoft.com> Shufen, Are you sure you have the CGI configured correctly in your web server? Do you see any errors in the server log when you try to access the CGI? What do you see in the browser if you ask it to View Source? Kent At 08:13 AM 8/15/2004 +1000, Ms Soo Chong wrote: >Hi all, > >Is me again... > >I resend this message in case the previous one was overlooked. > >Can someone out there help me please. Thank you > >I have some questions for cgi module too. > >From this website, I found a rather useful tutorial regrading cgi module, >http://www.cs.virginia.edu/~lab2q/lesson_7/ but unfortunately, the output >is not >available for some reasons. Thus, I tried the same script on my system and >it showed a >blank page in my web browser. Is there anything wrong with the script >below? Because, >I wanted to try something about cgi module and see if I can get the >connection working >between cgi and python. From kent_johnson at skillsoft.com Sun Aug 15 02:18:07 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sun Aug 15 02:18:16 2004 Subject: [Tutor] Comma at the end of a print command In-Reply-To: <105.4e0de8f7.2e4ff47a@aol.com> References: <105.4e0de8f7.2e4ff47a@aol.com> Message-ID: <6.1.0.6.0.20040814201347.02a4bb70@mail4.skillsoft.com> Output with print will always separate values with spaces. If you want finer control you can write directly to sys.stdout (which is what print does). For example: >>> print 1,;print 2 1 2 >>> import sys >>> sys.stdout.write('1');sys.stdout.write('2') 12>>> Note that write() will never append a newline to the string you give it; if you want a newline you have to specify it yourself. Also note that a more common way to eliminate spaces in print statements is to format your output with %, but that won't work in this case. Kent At 07:04 PM 8/14/2004 -0400, Dragonfirebane@aol.com wrote: >Hello all, > >I know that when you put a comma at the end of a print command, the next >printed object will be printed on the same line, separated by a space. Is >there a way to do this without the space separation? i.e.: > >def mod(): > import msvcrt > model = msvcrt.getch() > if model == '1': > print model(*) > model = msvcrt.getch() ##to get the next number > print model > >would output: > >12 > >, printing the numbers one at a time, if '12' were inputed. as it is, the >output is: > >1 2 > >, which isn't what i want. So in other words: is there a way to provide >'real-time' printing without the space separation? The reason I'm using >msvcrt.getch() is because if the number doesn't begin with a 1, then it >must be below 10, as the choices are from 2 to 15; which would make it >easier (no need to hit enter) to process the choice. > >* insert unknown symbol here > >Email: dragonfirebane@aol.com >AIM: singingxduck >Programming Python for the fun of it. >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From dyoo at hkn.eecs.berkeley.edu Sun Aug 15 03:33:44 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Aug 15 03:33:48 2004 Subject: [Tutor] Starting to write a scanf-like module for Python Message-ID: Hi everyone, I thought it might make a nice weekend project to write scanf for Python; it's nowhere near done yet, but it's sorta working... *grin* http://hkn.eecs.berkeley.edu/~dyoo/python/scanf.py I want to gauge some input from folks on the list to see if this might be useful for folks. A lot of programming assignments will assume that the implementing language is something like C, and with it, taylor the input to take advantage of C's scanf() input function. But Python doesn't have this by default, and it's slightly annoying to have to manually do a lot of input stream munging to simulate something simple like: scanf("%d %d", &x, &y); /* C code to read two integers, with any amount of whitespace between the two */ And regular expression solutions to this have always felt a little off, since Python's regular expression library works on strings, not file streams. So that's what this 'scanf' module is supposed to help with. Here's an example of it in action: ### >>> from scanf import scanf >>> scanf("%d %d") 3 1 (3, 1) >>> scanf("%s%s") hello world ('hello', 'world') >>> scanf("%d / %d / %d") 2004/08/14 (2004, 8, 14) >>> scanf.scanf("%s hello") danny hello ('danny',) >>> scanf.scanf("%s hello") danny hi Traceback (most recent call last): File "", line 1, in ? File "scanf.py", line 146, in scanf return bscanf(STDIN, formatString) File "scanf.py", line 162, in bscanf return parser(buffer) File "scanf.py", line 310, in f raise IncompleteCaptureError, (e, tuple(results)) scanf.IncompleteCaptureError: (, ('danny',)) ### It doesn't support everything that C's scanf can do yet, and probably never will. I'm just trying to implement just enough to make it easy to do the stuff from Programming Challenges without having to worry too much about input/output. But if there's something that folks feel really should be in the module, I'll try to be receptive. Hope this helps! From tim.peters at gmail.com Sun Aug 15 06:51:38 2004 From: tim.peters at gmail.com (Tim Peters) Date: Sun Aug 15 06:51:47 2004 Subject: [Tutor] problem with time module In-Reply-To: <6.1.2.0.2.20040814115248.0445c008@rcblue.com> References: <6.1.2.0.2.20040814115248.0445c008@rcblue.com> Message-ID: <1f7befae04081421514e9a1be4@mail.gmail.com> [Dick Moores] > From the time module doc at > , > I expected mktime(localtime()) and time() to be approx. 7*3600 seconds > apart (I'm on the U.S. west coast, in -0700). I don't know how you're reading the docs. There are two ways of representing time in that module: 1. Timestamps, which are floats. These are always seconds from the epoch, as measured in UTC. No exceptions. 2. struct_time thingies. These are broken out into year, month, etc. They don't contain time zone info explicitly, but correct interpretation requires anyway that you know which time zone was intended. mktime() assumes its input is expressed in local time; there's nothing in the time module that converts a UTC struct_time to a timestamp, although calendar.timegm() does that. localtime() creates a #2. mktime(localtime()) produces a #1, so must be UTC. time() produces a #1, so must also be UTC. Therefore I expect the same result from both, although mktime()'s input doesn't have a fraction-of-a-second member so I expect an exact integer (in floating format) form mktime(). > But they're not: Good ! > >>> from time import * > >>> mktime(localtime());time() > 1092510279.0 > 1092510279.2650001 > > Have I misunderstood something? Yes, but since you didn't lay out your reasoning, I can't guess which step got off track. From s4046441 at student.uq.edu.au Sun Aug 15 07:39:28 2004 From: s4046441 at student.uq.edu.au (Ms Soo Chong) Date: Sun Aug 15 07:39:34 2004 Subject: [Tutor] Problem with CGI module Message-ID: Hi Kent, I'm not 100% sure that the CGI is configured correctly in my web server. I did not see any error message when I try to access the CGI. When I view source code, it is a blank page. What should I try next? looking forward to hear for you. Thank you. Shufen ----- Original Message ----- From: Kent Johnson Date: Sunday, August 15, 2004 10:10 am Subject: Re: [Tutor] Problem with CGI module > Shufen, > > Are you sure you have the CGI configured correctly in your web > server? Do > you see any errors in the server log when you try to access the > CGI? What > do you see in the browser if you ask it to View Source? > > Kent > > At 08:13 AM 8/15/2004 +1000, Ms Soo Chong wrote: > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From rdm at rcblue.com Sun Aug 15 07:39:43 2004 From: rdm at rcblue.com (Dick Moores) Date: Sun Aug 15 07:39:49 2004 Subject: [Tutor] problem with time module In-Reply-To: <1f7befae04081421514e9a1be4@mail.gmail.com> References: <6.1.2.0.2.20040814115248.0445c008@rcblue.com> <1f7befae04081421514e9a1be4@mail.gmail.com> Message-ID: <6.1.2.0.2.20040814221356.0230bec0@rcblue.com> Tim Peters wrote at 21:51 8/14/2004: >[Dick Moores] > > From the time module doc at > > , > > I expected mktime(localtime()) and time() to be approx. 7*3600 seconds > > apart (I'm on the U.S. west coast, in -0700). > >I don't know how you're reading the docs. There are two ways of >representing time in that module: > >1. Timestamps, which are floats. These are always seconds from the epoch, > as measured in UTC. No exceptions. > >2. struct_time thingies. These are broken out into year, month, etc. They > don't contain time zone info explicitly, but correct interpretation > requires > anyway that you know which time zone was intended. mktime() assumes > its input is expressed in local time; there's nothing in the time > module that > converts a UTC struct_time to a timestamp, although calendar.timegm() > does that. > >localtime() creates a #2. mktime(localtime()) produces a #1, so must >be UTC. time() produces a #1, so must also be UTC. Therefore I >expect the same result from both, although mktime()'s input doesn't >have a fraction-of-a-second member so I expect an exact integer (in >floating format) form mktime(). > > > But they're not: > >Good ! > > > >>> from time import * > > >>> mktime(localtime());time() > > 1092510279.0 > > 1092510279.2650001 > > > > Have I misunderstood something? > >Yes, but since you didn't lay out your reasoning, I can't guess which >step got off track. OK, here's my reasoning. From the doc, "mktime( t) This is the inverse function of localtime(). Its argument is the struct_time or full 9-tuple (since the dst flag is needed; use -1 as the dst flag if it is unknown) which expresses the time in local time, not UTC. It returns a floating point number, for compatibility with time(). If the input value cannot be represented as a valid time, either OverflowError or ValueError will be raised (which depends on whether the invalid value is caught by Python or the underlying C libraries). The earliest date for which it can generate a time is platform-dependent." If mktime(t) is the inverse of localtime(), I thought this implied that the floating point number mktime(localtime()) returned would be seconds from the epoch based on my local time. I saw nothing that said that all timestamps are based on UTC (although I can see now that it's a Good Thing they are). I did understand that time() is based on UTC. Therefore I concluded that mktime(localtime()) should be about 7 hours less than time(). Thanks very much for your lucid clarification. Dick Moores From hans at zephyrfalcon.org Sun Aug 15 07:49:16 2004 From: hans at zephyrfalcon.org (Hans Nowak) Date: Sun Aug 15 07:49:45 2004 Subject: [Tutor] Re: Starting to write a scanf-like module for Python In-Reply-To: References: Message-ID: <411EF95C.6070801@zephyrfalcon.org> Danny Yoo wrote: > I thought it might make a nice weekend project to write scanf for Python; > it's nowhere near done yet, but it's sorta working... *grin* Looks interesting, but I'm not sure if use raw_input is used all that often. This would be extra useful if it could read from arbitrary files. Maybe something like f = open("blah.txt", "r") # I want/expect a string and three integers s, i1, i2, i3 = fscanf(f, "%s %d %d %d") ...? -- Hans Nowak (hans@zephyrfalcon.org) http://zephyrfalcon.org/ From dyoo at hkn.eecs.berkeley.edu Sun Aug 15 09:06:06 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Aug 15 09:06:54 2004 Subject: [Tutor] Re: Starting to write a scanf-like module for Python In-Reply-To: <411EF95C.6070801@zephyrfalcon.org> Message-ID: On Sun, 15 Aug 2004, Hans Nowak wrote: > Danny Yoo wrote: > > > I thought it might make a nice weekend project to write scanf for Python; > > it's nowhere near done yet, but it's sorta working... *grin* > > Looks interesting, but I'm not sure if use raw_input is used all that > often. This would be extra useful if it could read from arbitrary > files. Maybe something like > > f = open("blah.txt", "r") > # I want/expect a string and three integers > s, i1, i2, i3 = fscanf(f, "%s %d %d %d") Hi Hans, ### >>> import scanf >>> scanf.fscanf >>> f = open("/usr/share/dict/words") >>> scanf.fscanf(f, "%s") ('A',) >>> scanf.fscanf(f, "%s") ('a',) >>> scanf.fscanf(f, "%s") ('aa',) >>> scanf.fscanf(f, "%s") ('aal',) >>> scanf.fscanf(f, "%s") ('aalii',) >>> scanf.fscanf(f, "%s") ('aam',) >>> scanf.fscanf(f, "%s") ('Aani',) >>> scanf.fscanf(f, "%s") ('aardvark',) >>> scanf.fscanf(f, "%s") ('aardwolf',) ### *grin* From dyoo at hkn.eecs.berkeley.edu Sun Aug 15 09:22:51 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Aug 15 09:22:55 2004 Subject: [Tutor] Tkinter the great In-Reply-To: <20040814144907.89742.qmail@web61004.mail.yahoo.com> Message-ID: On Sat, 14 Aug 2004, Ali Polatel wrote: > Friends I wrote a programme with Tkinter... > I have converted it into an exe file with py2exe > Now when I run it still there is a dos box behind it :( > How can i get rid of it? Hi Ali, Ah, this one is easy to fix: rename your program from '.py' to '.pyw'. In Windows, a '.pyw' Python program won't request a console, so that should do the trick. Alternatively, pass the '-w' option to py2exe. Try: python setup.py py2exe --help for a complete list of extra options for py2exe. Good luck to you! From alan.gauld at blueyonder.co.uk Sun Aug 15 09:44:36 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Aug 15 09:46:31 2004 Subject: [Tutor] Entry box + browse button References: <200408141750.53778.klas.martelleur@telia.com> <200408142119.38941.klas.martelleur@telia.com> <00ba01c48234$58844430$6401a8c0@xp> <200408142310.19287.klas.martelleur@telia.com> Message-ID: <00da01c4829b$b89b8c40$6401a8c0@xp> > Some idea i had was to call a function from the "command" in > self.inputBrowseButton (self.openFile) and change the value of self.infile in > that function. But i am not so sure about that idea anymore. Thats pretty close. The simplest way is two nearly identical methods: def browseInput(self) name = tkFileDialog.askopenfilename() self.inputEntry.insert(INSERT,name) def browseInput(self) name = tkFileDialog.askopenfilename() self.outputEntry.insert(INSERT,name) and set those as the command options in the two browse buttons: self.inputBrowseButton = Button(master, command = self.browseInput) self.outputBrowseButton = Button(master, command = self.browseOutput) We can be slightly more clever than that by writing a single browse method def setFilename(self, entry=self.inputEntry): name = tkFileDialog.askopenfilename() entry.inset(INSERT,name) And use a lambda to pass the appropriate widget: self.inputBrowseButton = Button(master, command = lambda : self.setFilename(self.inputEntry)) self.outputBrowseButton = Button(master, command = lambda : self.setFilename(self.outputEntry)) HTH. Alan G. From alan.gauld at blueyonder.co.uk Sun Aug 15 09:50:08 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Aug 15 09:51:59 2004 Subject: [Tutor] _Object Thinking_, by David West References: <6.1.2.0.2.20040814083146.04f0bec0@rcblue.com><00c901c48235$e26a2060$6401a8c0@xp> <6.1.2.0.2.20040814124140.05d04458@rcblue.com> Message-ID: <00f301c4829c$7cbe93b0$6401a8c0@xp> > >If you want to understand OOP I'd still recommend something like > >Timothy Budds classic OOP book or Grady Booch's classic OOA/D first. > > Is this the Budds book: http://tinyurl.com/6v68l ? Yes, but I'd borrow this one if you can rather than buy it. > My local library has "Object-oriented analysis and design with > applications" by Grady Booch. I assume this is the one you mean? I'm 6th > in line for the one copy. And there are several very inexpensive copies > available through Bookfinder.com. I'd buy a copy if you can. I bought mine (1st edition) in 1992 and still refer to it several times a year. The notation has now been superceded by UML but the principles of design are still absolutely valid. I also prefer the first edition to the second because it uses mnultiple OO languages whereas the second focuses only on C++ (which was flavor of the day at the time). Alan G. From alan.gauld at blueyonder.co.uk Sun Aug 15 09:54:17 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Aug 15 09:56:17 2004 Subject: [Tutor] Entry box + browse button SOLVED References: <200408141750.53778.klas.martelleur@telia.com><00ba01c48234$58844430$6401a8c0@xp><200408142310.19287.klas.martelleur@telia.com> <200408150017.58784.klas.martelleur@telia.com> Message-ID: <010201c4829d$16465180$6401a8c0@xp> > Actually i wasnt that far from the solution as i was thinking. The thing was > to delete the text in the box before trying to add a new one (otherwise the > new filename gets appended after the default one. Ah yes, I wondered about that but thought the insert method would work... But the use of StrVar() should definitely not require that, I'd forgotten about StrVar! > def openInFile(self): > import tkFileDialog ... > def saveAsFile(self): > import tkFileDialog ... Better not to import in two places, put the import at the top along with the other import lines. Alan G. From alan.gauld at blueyonder.co.uk Sun Aug 15 11:21:25 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Aug 15 11:23:14 2004 Subject: [Tutor] Comma at the end of a print command References: <105.4e0de8f7.2e4ff47a@aol.com> Message-ID: <011701c482a9$3cc98460$6401a8c0@xp> > I know that when you put a comma at the end of a print command, the next > printed object will be printed on the same line, separated by a space. Is there a > way to do this without the space separation? i.e.: I dont think so but you can write to sys.stdout instead and do all the formatting yourself. > def mod(): > import msvcrt > model = msvcrt.getch() > if model == '1': > print model(*) > model = msvcrt.getch() ##to get the next number > print model This is most likely to bring back another 1 or a null character because the time between detecting the 1 and reading getch again is going to be tiny. You will need to loop to detect the user input. Using getch() is much more complex than using raw_input. > 'real-time' printing without the space separation? The reason I'm using > msvcrt.getch() is because if the number doesn't begin with a 1, then it must be below > 10, as the choices are from 2 to 15; which would make it easier (no need to hit > enter) to process the choice. This might seem like a good idea but it does put the onus on your users to be perfect keyboard operators. That is they can never make a mistake because as soon as they hit a key you will process it! Just a consideration... Alan G. From alan.gauld at blueyonder.co.uk Sun Aug 15 11:26:45 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Aug 15 11:28:35 2004 Subject: [Tutor] Starting to write a scanf-like module for Python References: Message-ID: <011e01c482a9$fbc2d470$6401a8c0@xp> > I thought it might make a nice weekend project to write scanf for Python; > it's nowhere near done yet, but it's sorta working... *grin* > > http://hkn.eecs.berkeley.edu/~dyoo/python/scanf.py > > I want to gauge some input from folks on the list to see if this might be > useful for folks. If it were sscanf() it would be really useful. scanf() has so many bugs/features nobody in their right mind uses it do they? It's certainly a certain red flag in a code review if any of my guys ever use raw scanf... [f]gets();sscanf() is the normal pairing. But the principle is good, The ability to easily parse out values from a strng is useful. > It doesn't support everything that C's scanf can do yet, and probably > never will. I'm just trying to implement just enough to make it easy to > do the stuff from Programming Challenges without having to worry too much > about input/output. But if there's something that folks feel really > should be in the module, I'll try to be receptive. Sounds good, but I would seriously consider sscanf() as a better project - and easier - and leave the acquiring the input string to raw_input or file.read() Alan G. From alipolatel at yahoo.com Sun Aug 15 13:28:35 2004 From: alipolatel at yahoo.com (Ali Polatel) Date: Sun Aug 15 13:28:37 2004 Subject: [Tutor] Another prob with Telnet In-Reply-To: <1092499803.7921.14.camel@laptop.venix.com> Message-ID: <20040815112835.43828.qmail@web61004.mail.yahoo.com> Thanks it works! :) --------------------------------- Do you Yahoo!? New and Improved Yahoo! Mail - 100MB free storage! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040815/3fa9ea23/attachment.htm From isrgish at fastem.com Sun Aug 15 14:43:49 2004 From: isrgish at fastem.com (Isr Gish) Date: Sun Aug 15 14:43:54 2004 Subject: [Tutor] pdf files Message-ID: <20040815124353.6419A1E4002@bag.python.org> Hi, -----Original Message----- >From: "r2b2" >Sent: 8/12/04 8:08:08 PM >To: "tutor@python.org" >Subject: [Tutor] pdf files > > > >looking for a basic code using reportlabs package ( or any package ) to convert an existing text file to a .pdf file. > >convert document.txt to document.pdf > There is a program on sourceforge.net. I think its called "xtopdf". All the best, Isr >thanks > >_______________________________________________ >No banners. No pop-ups. No kidding. >Make My Way your home on the Web - http://www.myway.com >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From kent_johnson at skillsoft.com Sun Aug 15 15:59:17 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sun Aug 15 15:59:31 2004 Subject: [Tutor] Problem with CGI module In-Reply-To: References: Message-ID: <6.1.0.6.0.20040815095126.02a4a088@mail4.skillsoft.com> Shufen, Try a very simple CGI that just outputs a static page. You may have a logic error in the code you posted - it looks like there could be some combination of input fields that causes nothing to output. (The indentation in your posting is corrupted so I can't be sure about this.) See what the server request log is reporting when you try to access the CGI. There should be some entry there. Kent At 03:39 PM 8/15/2004 +1000, Ms Soo Chong wrote: >Hi Kent, > >I'm not 100% sure that the CGI is configured >correctly in my web server. > >I did not see any error message when I try to access >the CGI. > >When I view source code, it is a blank page. > >What should I try next? > >looking forward to hear for you. > >Thank you. > >Shufen > >----- Original Message ----- >From: Kent Johnson >Date: Sunday, August 15, 2004 10:10 am >Subject: Re: [Tutor] Problem with CGI module > > > Shufen, > > > > Are you sure you have the CGI configured correctly >in your web > > server? Do > > you see any errors in the server log when you try >to access the > > CGI? What > > do you see in the browser if you ask it to View >Source? > > > > Kent > > > > At 08:13 AM 8/15/2004 +1000, Ms Soo Chong wrote: > > > _______________________________________________ > > 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 Dragonfirebane at aol.com Sun Aug 15 16:49:30 2004 From: Dragonfirebane at aol.com (Dragonfirebane@aol.com) Date: Sun Aug 15 16:49:40 2004 Subject: [Tutor] Comma at the end of a print command Message-ID: <96.124a393c.2e50d1fa@aol.com> In a message dated 8/15/2004 5:23:29 AM Eastern Standard Time, alan.gauld@blueyonder.co.uk writes: > I know that when you put a comma at the end of a print command, the next > printed object will be printed on the same line, separated by a space. Is there a > way to do this without the space separation? i.e.: I dont think so but you can write to sys.stdout instead and do all the formatting yourself. I'll try that, thanks. > def mod(): > import msvcrt > model = msvcrt.getch() > if model == '1': > print model(*) > model = msvcrt.getch() ##to get the next number > print model This is most likely to bring back another 1 or a null character because the time between detecting the 1 and reading getch again is going to be tiny. You will need to loop to detect the user input. Using getch() is much more complex than using raw_input. I've found that using msvcrt.getch() again merely forces the program to wait until the next button pushed and processing it. > 'real-time' printing without the space separation? The reason I'm using > msvcrt.getch() is because if the number doesn't begin with a 1, then it must be below > 10, as the choices are from 2 to 15; which would make it easier (no need to hit > enter) to process the choice. This might seem like a good idea but it does put the onus on your users to be perfect keyboard operators. That is they can never make a mistake because as soon as they hit a key you will process it! Just a consideration... Alan G. Well, since all the choices are numbers, they can use the number pad on the right of the keyboard. Besides, its meant for a game in which each number represents a tile that can slide into an empty space, as in the classic hand-held game. Therefore, if they make a mistake, a) the tile is likely not to be next to the space, which would do nothing but bring up a message requesting they choose a tile next to the space or b) the tile *is* next to the space and if it is not the one they wished to move, they merely select it again to move it back. If you're interested, my code so far is at http://rafb.net/paste/results/D4a3NE47.nln.html. As of right now, the timer seems to work arbitrarily (i don't know why) as does the part that ends the program by breaking the play loop when the user inputs 'stop', 'quit', 'exit', etc. Any suggestions on what's wrong and how to fix it would be apreciated. Thanks, Orri Email: dragonfirebane@aol.com AIM: singingxduck Programming Python for the fun of it. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040815/2d11c95b/attachment.html From alipolatel at yahoo.com Sun Aug 15 18:21:35 2004 From: alipolatel at yahoo.com (Ali Polatel) Date: Sun Aug 15 18:21:38 2004 Subject: [Tutor] Telnet Programme Question Message-ID: <20040815162135.73364.qmail@web61008.mail.yahoo.com> Friends, My telnet programme is going well :) Now I can connect to the server and type-in login name and password easily.... Now I have a more complicated problem The command prompt of the server is 'fics%' First let me show you the script so that you'll understand better : "#!usr/bin/python import telnetlib from sys import exit from time import sleep # PLAY CHESS IN FICS via Telnet!(without timeseal!) a=telnetlib.Telnet(host='64.71.131.140',port='5000') a.read_until('login:') b=str('username'+chr(10)) a.write(b) b=str('passwordl'+chr(10)) a.read_until('password:') a.write(b) print a.read_until('fics%') Until here programme works ok Now I want it to look if there is something in the server(like tells,channel tells etc.) and print if there is any or wait if there is nothing... Also it should be able to get the commands that I type from me meanwhile So I have written the things below but it doesn't work x=0 c=raw_input() while x<999999999: if a.read_until('fics%',timeout=1)<>' ' and c==' ' : print a.read_until('fics%',timeout=1) sleep(1) else: a.write(str(c)+chr(10)) print a.read_until('fics%',timeout=1) c='' c=raw_input() sleep(1) x=x+1 but if I accept no commands(raw-input) s from the user it works perfect. eg: ..."while x<999999999: if a.read_until('fics%',timeout=1)<>' ' print a.read_until('fics%',timeout=1) sleep(1) else:" and so on So what I need is to make the programme wait 1 second for a raw-input and if there is no raw input it should continue his work... Anyone who can solve this? Regards, Ali Polatel --------------------------------- Do you Yahoo!? Yahoo! Mail - 50x more storage than other providers! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040815/d5bfa1aa/attachment.htm From python at bernardlebel.com Sun Aug 15 22:25:24 2004 From: python at bernardlebel.com (Bernard Lebel) Date: Sun Aug 15 21:23:11 2004 Subject: [Tutor] List files in directory Message-ID: <000501c48306$02ffd6a0$2901a8c0@atyss> Hello, Anyone has advice on how to collect filenames from a directory? Right now I'm using os.walk( path... ) to walk an entire directory hierarchy, so if I print the file names well I get all filenames in AND below the current visited directory, not just the ones in the directory: import os # Define root seach path sRoot = 'C:\\__PROJETS\\bernardlebel.com\\img_remote' # Create empty list to store collected folders aDirs = [] # Iterate through root folder to collected folders for oDirPaths, oDirNames, oFiles in os.walk( sRoot, True, None ): # Add folder to list aDirs.append( oDirPaths ) # Check if folders were collected if len( aDirs ) < 1: print 'No folder collected.' else: # Iterate through collected folder to get files for oDir in aDirs: print '_________ Checking folder: _________ ' + oDir for oPaths, oDirs, oDirFiles in os.walk( oDir, True, None ): print oDirFiles Basically if the root folder contains 10 files and two folders each containing 10 files, the code above will print 30 files, then 10 files, then 10 files. I want to print only the files contains in the currently visited directory. Thanks Bernard From ejp at zomething.com Sun Aug 15 22:22:26 2004 From: ejp at zomething.com (EJP) Date: Sun Aug 15 22:22:52 2004 Subject: [Tutor] List files in directory Message-ID: <20040815122226.1719581178.ejp@zomething.com> "Bernard Lebel" wrote: > > Hello, > > Anyone has advice on how to collect filenames from a directory? > I want to print only the files contains in the currently visited directory. This is simple enough that I can help: import os path="C:\\somedirectory" # insert the path to the directory of interest here dirList=os.listdir(path) for fname in dirList: print fname From python at bernardlebel.com Sun Aug 15 23:50:43 2004 From: python at bernardlebel.com (Bernard Lebel) Date: Sun Aug 15 22:48:30 2004 Subject: [Tutor] List files in directory References: <20040815122226.1719581178.ejp@zomething.com> Message-ID: <000a01c48311$ebd6ebb0$2901a8c0@atyss> Thank you very much, glad my question was simple enough to get help ;-) Bernard ----- Original Message ----- From: "EJP" To: "Bernard Lebel" ; Sent: Sunday, August 15, 2004 9:22 PM Subject: Re: [Tutor] List files in directory "Bernard Lebel" wrote: > > Hello, > > Anyone has advice on how to collect filenames from a directory? > I want to print only the files contains in the currently visited directory. This is simple enough that I can help: import os path="C:\\somedirectory" # insert the path to the directory of interest here dirList=os.listdir(path) for fname in dirList: print fname From alan.gauld at blueyonder.co.uk Sun Aug 15 23:59:34 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Mon Aug 16 00:01:15 2004 Subject: [Tutor] Telnet Programme Question References: <20040815162135.73364.qmail@web61008.mail.yahoo.com> Message-ID: <016d01c48313$266a6260$6401a8c0@xp> , > My telnet programme is going well :) I'm impressed you got so far so quickly. However I will just give one more plug for pexpect, it does all of this so much more easily. Since you aren't doing this just for fun you really should consider whether pexpect can do all you need? http://pexpect.sourceforge.net/ BTW I incorrectly called it pyexpect last time... Alan G. From jus500tin at yahoo.com Mon Aug 16 00:22:56 2004 From: jus500tin at yahoo.com (justin ezuma) Date: Mon Aug 16 00:23:02 2004 Subject: [Tutor] (no subject) Message-ID: <20040815222256.4196.qmail@web12907.mail.yahoo.com> dear tutor, I want to learn the python language.Can I get any tutorial(pdf format)? --------------------------------- Do you Yahoo!? Yahoo! Mail Address AutoComplete - You start. We finish. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040815/1cfc0535/attachment.html From askoose at sandia.gov Mon Aug 16 01:03:59 2004 From: askoose at sandia.gov (Kooser, Ara S) Date: Mon Aug 16 01:04:23 2004 Subject: [Tutor] (no subject) Message-ID: <9A4B2157EFDBE546BECD68C62AC3B1C81738F3CB@es05snlnt.sandia.gov> There are several on python.org in .pdf format. and this one as well How to Think Like a Computer Scientist http://www.ibiblio.org/obp/thinkCSpy/ and Alans book as well -----Original Message----- From: justin ezuma To: tutor@python.org Sent: 8/15/2004 4:22 PM Subject: [Tutor] (no subject) dear tutor, I want to learn the python language.Can I get any tutorial(pdf format)? _____ Do you Yahoo!? Yahoo! Mail Address AutoComplete - You start. We finish. <> From clavezza at hotmail.com Mon Aug 16 01:06:46 2004 From: clavezza at hotmail.com (christopher lavezza) Date: Mon Aug 16 01:06:51 2004 Subject: [Tutor] Need help with this source code Message-ID: Can someone please run the source code and give me some help in where I made my mistakes in the source code. Thank you very much. Source code is at the bottom of this email. Chris #!c:\python\python.exe import sys from phone import * #Start of Program b = 1 foo = phonedb() while b != 3: print b print "Welcome to the Phone Database!" print "---written by Chris Lavezza---" print "Please make a selection by typing one of the following options." print print "If you want to add an Employee type the #: 1" print print"For a complete listing of Employees type the #: 2" print print "To see the 'test page' and exit the Database type the #: 3" b = input(':') if b == 1: print "Enter the Employee's full name:" n = raw_input(':') print "Enter the Employee's full telephone number:" p = raw_input(':') print "Enter the telephone number type: (0 = Unknown, 1 = Home, 2 = Work, 3 = Fax, 4 = Cell)" t = raw_input(':') if t == '0': foo.add(n, p, "Unknown") if t == '1': foo.add(n, p, "Home") if t == '2': foo.add(n, p, "Work") if t == '3': foo.add(n, p, "Fax") if t == '4': foo.add(n, p, "Cell") print t if b == 2: print (list) # if not being loaded as a module, run a small test if __name__ == '__main__': foo = phonedb() foo.add('Sean Reifschneider', '970-555-1111', HOME) foo.add('Sean Reifschneider', '970-555-2222', CELL) foo.add('Evelyn Mitchell', '970-555-1111', HOME) foo.add('Chad Varner','970-123-4567',HOME) print 'First lookup:' for entry in foo.lookup('reifsch'): print '%-40s %s (%s)' % ( entry.name, entry.number, entry.showtype() ) print print 'Second lookup:' for entry in foo.lookup('e'): print '%-40s %s (%s)' % ( entry.name, entry.number, entry.showtype() ) _________________________________________________________________ Don’t just search. Find. Check out the new MSN Search! http://search.msn.click-url.com/go/onm00200636ave/direct/01/ From thomi at imail.net.nz Mon Aug 16 03:14:35 2004 From: thomi at imail.net.nz (Thomas Clive Richards) Date: Mon Aug 16 03:14:43 2004 Subject: [Tutor] easy way to make image thumbnails without using PIL? Message-ID: <200408161314.35147.thomi@imail.net.nz> Hi, I'm trying to write a function that takes an image filenme as input and creates a thumbnail in the same directory. At the moment I'm using the Python Imaging Library (PIL). The function looks a bit like this: def GenerateThumbnail(imgpath): try: im = Image.open(imgpath) im.thumbnail((128,128)) b,e = os.path.splitext(imgpath) im.save(b + global_config.THUMBNAIL_EXTENSION + ".png","PNG") except IOError: print "an error occured processing ", imgpath However, PIL doesn't support interlaced PNG images, which happen to be most of the images I want to convert. What's more, I'll be using this script on a web server that I don't own, so I can't use any external packages (like the python ImageMagick bindings for example). Is this possible? I see the "imageop" module, but that seems only to work on bitmaps... Any ideas greatly appreciated. Thanks, -- Thomi Richards, thomi@once.net.nz From tim.peters at gmail.com Mon Aug 16 04:12:19 2004 From: tim.peters at gmail.com (Tim Peters) Date: Mon Aug 16 04:12:22 2004 Subject: [Tutor] problem with time module In-Reply-To: <6.1.2.0.2.20040814221356.0230bec0@rcblue.com> References: <6.1.2.0.2.20040814115248.0445c008@rcblue.com> <1f7befae04081421514e9a1be4@mail.gmail.com> <6.1.2.0.2.20040814221356.0230bec0@rcblue.com> Message-ID: <1f7befae04081519126abbb626@mail.gmail.com> [Dick Moores] > OK, here's my reasoning. From the doc, > > "mktime( t) > > This is the inverse function of localtime(). Its argument is the > struct_time or full 9-tuple (since the dst flag is needed; use -1 as the > dst flag if it is unknown) which expresses the time in local time, not > UTC. ... > " And it really is an inverse: localtime() takes a timestamp and converts to a local struct_time, while mktime() does exactly the opposite. > If mktime(t) is the inverse of localtime(), I thought this implied that > the floating point number mktime(localtime()) returned would be > seconds from the epoch based on my local time. I saw nothing that > said that all timestamps are based on UTC (although I can see now > that it's a Good Thing they are). I did understand that time() is based > on UTC. Therefore I concluded that mktime(localtime()) should be > about 7 hours less than time(). Unfortunately, the time module consists of thin wrappers around the pretty miserable time functions defined by the C language. That's why "everyone knows" what "seconds from the epoch" means, and "everyone knows" too that "seconds from the epoch" means UTC. It sucks, but that's life. If it all possible, I'd encourage you to use the newer datetime module instead. From dyoo at hkn.eecs.berkeley.edu Mon Aug 16 04:46:05 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Aug 16 04:46:09 2004 Subject: [Tutor] Starting to write a scanf-like module for Python In-Reply-To: <011e01c482a9$fbc2d470$6401a8c0@xp> Message-ID: On Sun, 15 Aug 2004, Alan Gauld wrote: > > I thought it might make a nice weekend project to write scanf for > > Python; it's nowhere near done yet, but it's sorta working... *grin* > > > > http://hkn.eecs.berkeley.edu/~dyoo/python/scanf.py > > > > I want to gauge some input from folks on the list to see if this might > > be useful for folks. > > If it were sscanf() it would be really useful. [some text cut] > I would seriously consider sscanf() as a better project - and easier - > and leave the acquiring the input string to raw_input or file.read() Hi Alan, Too late: I had already implemented it. *grin* In fact, I use it for my unit test cases. Here's a sample of what I test: ### def ScanfTests(unittest.TestCase): def testIntegerScanning(self): self.assertEquals((42, 43), sscanf(" 42\n 43 ", "%d %d")) def testWordScanning(self): self.assertEquals(("hello", "world"), sscanf(" hello world", "%s %s")) def testSuppression(self): self.assertEquals((), sscanf(" hello world", "%*s %*s")) ### I do know I need to document the module better, so I'll add some more documentation strings. What this 'scanf' module provides are the following functions: scanf(formatString) -- reads from standard input sscanf(inputString, formatString) -- reads from string input fscanf(inputFile, formatString) -- reads from a file-like object I've also mimicked the 're' module sligthly in the sense that the module allows one to "compile" a format string, and then use the compiled pattern over and over: ### >>> import scanf >>> patternReader = scanf.compile(" (%d, %d) ") >>> patternReader >>> >>> >>> from StringIO import StringIO >>> sampleFile = StringIO(''' ... (3, 3) ... (17, 42) ... (-1, 5) ... ''') >>> sampleBuffer = scanf.CharacterBufferFromFile(sampleFile) >>> patternReader(sampleBuffer) (3, 3) >>> patternReader(sampleBuffer) (17, 42) >>> patternReader(sampleBuffer) (-1, 5) >>> patternReader(sampleBuffer) Traceback (most recent call last): File "", line 1, in ? File "scanf.py", line 310, in f raise IncompleteCaptureError, (e, tuple(results)) scanf.IncompleteCaptureError: (, ()) ### Hmmm... I guess I should simplify the usage here so that the user doesn't have to manually call the internal "CharacterBufferFromFile" thingy. > scanf() has so many bugs/features nobody in their right mind uses it do > they? Yes, that's the problem. So I'm not quite sure what features people really find useful in scanf(). *grin* But I personally need something that does integer and word scanning, so that's what I've implemented so far. I don't mind if this does only a subset of C's scanf(), just as long as it does the most important stuff, the stuff that people actually use with the *scanf() C functions. From dyoo at hkn.eecs.berkeley.edu Mon Aug 16 04:51:45 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Aug 16 04:51:48 2004 Subject: [Tutor] (no subject) In-Reply-To: <9A4B2157EFDBE546BECD68C62AC3B1C81738F3CB@es05snlnt.sandia.gov> Message-ID: On Sun, 15 Aug 2004, Kooser, Ara S wrote: > There are several on python.org in .pdf format. Hi Justin, Here's a link to the PDFs for the official documentation: http://docs.python.org/download.html However, be warned that the official tutorial assumes that you've already programmed before. If you're just starting to learn how to program, I'd strongly recommend looking at another tutorial. *grin* The Beginners Guide has links to tutorials that you may find more approachable. Take a look: http://www.python.org/topics/learn/non-prog.html For the most part, these assume no previous programming experience. All of them are available in HTML format, and can be easily converted to PDF if you really need it. From dyoo at hkn.eecs.berkeley.edu Mon Aug 16 05:06:04 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Aug 16 05:06:08 2004 Subject: [Tutor] Need help with this source code In-Reply-To: Message-ID: On Sun, 15 Aug 2004, christopher lavezza wrote: > Can someone please run the source code and give me some help in where I made > my mistakes in the source code. Thank you very much. Source code is at the > bottom of this email. Hi Christopher, Ummm... ok. What in particular should we look at? It's just not enough to say "My program is broken: help me fix it." We'll do what we can to help point problems out, but we really need your help and input too. Tell us why you think the program is broken. Not only does that will help focus our search, but you might find that it suddenly helps you to see the reason that the program is breaking. And even if we run the program ourselves, we may not not recognize the problem that you are seeing! That is why you need to tell us why you think something is wrong. >From quickly glancing at your program, I can tell you that none of us will be able to run your program. The definition for the 'phone' module that you're using: > from phone import * is one that you've probably written. We simply don't have that module, and so we can't test your program yet. Talk to you later! From rdm at rcblue.com Mon Aug 16 08:34:24 2004 From: rdm at rcblue.com (Dick Moores) Date: Mon Aug 16 08:34:26 2004 Subject: [Tutor] problem with time module In-Reply-To: <1f7befae04081519126abbb626@mail.gmail.com> References: <6.1.2.0.2.20040814115248.0445c008@rcblue.com> <1f7befae04081421514e9a1be4@mail.gmail.com> <6.1.2.0.2.20040814221356.0230bec0@rcblue.com> <1f7befae04081519126abbb626@mail.gmail.com> Message-ID: <6.1.2.0.2.20040815230611.02478b58@rcblue.com> Tim Peters wrote at 19:12 8/15/2004: >[Dick Moores] > > OK, here's my reasoning. From the doc, > > > > "mktime( t) > > > > This is the inverse function of localtime(). Its argument is the > > struct_time or full 9-tuple (since the dst flag is needed; use -1 as the > > dst flag if it is unknown) which expresses the time in local time, not > > UTC. ... > > " > >And it really is an inverse: localtime() takes a timestamp and >converts to a local struct_time, while mktime() does exactly the >opposite. Please forgive me for persisting here, but mktime(t) is not the inverse function of localtime() in the same precise way that pow(n,2) and sqrt(n) are inverses of each other (for n >= 0): >>> from math import sqrt >>> n = 78.56 >>> print pow(sqrt(n),2) 78.56 >>> print sqrt(pow(n,2)) 78.56 Thus my misunderstanding of the doc. > > If mktime(t) is the inverse of localtime(), I thought this implied that > > the floating point number mktime(localtime()) returned would be > > seconds from the epoch based on my local time. I saw nothing that > > said that all timestamps are based on UTC (although I can see now > > that it's a Good Thing they are). I did understand that time() is based > > on UTC. Therefore I concluded that mktime(localtime()) should be > > about 7 hours less than time(). > >Unfortunately, the time module consists of thin wrappers around the >pretty miserable time functions defined by the C language. That's why >"everyone knows" what "seconds from the epoch" means, and >"everyone knows" too that "seconds from the epoch" means UTC. It >sucks, but that's life. If it all possible, I'd encourage you to use >the newer datetime module instead. Thanks, I'll do that. And thanks very much for your assistance, Mr. Peters. Dick Moores From s4046441 at student.uq.edu.au Mon Aug 16 09:06:37 2004 From: s4046441 at student.uq.edu.au (Ms Soo Chong) Date: Mon Aug 16 09:06:44 2004 Subject: [Tutor] Questions on pgDB connection Message-ID: Hi all, I have problem connecting using pgdb module. I read this webpage: 1) http://www.linuxjournal.com/article.php?sid=2605 and 2) http://www/python.org/peps/pep-0249.html. >From these websites I knew that I have to first import the pgdb module then connect but the problem is I don't know what is the connection word to connect to the pgdb/server. Anybody know what I'm talking about? I might sound stupid but I really not sure about the connection stuffs and I have tried lots of method but it just doesn't work for me. The first webpage stated that if you are using the SOLID version, the UNIX pipes are the only method available to connect to the server. So what is the method to connect the server if I'm using pgdb? The second webpage stated that a connect should look like this: e.g. connect(dsn='myhost:MYDB', user='guido', password='234$') and it also stated that other than dsn, the other stuffs such as user and passwd are optional, is it true? my script looks like this: import pgdb db = pgdb.connect(dsn='moncdata', user='username', password='None') I really appreciate if someone out there can give me some help. Thank you in advance. Cheers Shufen From python at bernardlebel.com Mon Aug 16 09:54:11 2004 From: python at bernardlebel.com (Bernard Lebel) Date: Mon Aug 16 09:54:21 2004 Subject: [Tutor] python-mysql References: Message-ID: <000c01c48366$38508380$0d01a8c0@studioaction.local> Hi again, I have another question. I managed to properly install the module, and it works, because I can connect to the database, I can create an object, and I can even send a query and fetch the result. However this time the problem is that when I used to use VBScript and JScript to do the same thing with an activeX object, I could send a second query using arguments obtained from the first, but now it doesn't and I'm not sure why. Here is my code: # Import module import MySQLdb # Create instance sql = MySQLdb # host (server) sHost = 'xxx.xxx.x.x' # uid (user) sUser = 'xsi_client' # pwd (password) sPwd = 'XSIBatchServe' # database sDB = 'XSI_R' # Create connection object oDB = sql.connect( sHost, sUser, sPwd , sDB ) iID = 31 sID = str( iID ) # Execute first query oCursor.execute( ' SELECT from_rule, where_rule, order_rule ' + ' FROM clients LEFT JOIN rules ON rules.id=clients.rule_id' + ' WHERE clients.c_id=' + sID ) # Get first query result oResult1 = oCursor.fetchone() # Define new rules sFrom_rule_orig = oResult1[0] sFrom_rule = sFrom_rule_orig.replace( '$id', sID ) sWhere_rule = str( oResult1[1] ) sOrder_rule = str( oResult1[2] ) # Execute second query oCursor.execute( ' SELECT jobs.job_id, jobs.type_id, tasks.frame, jobs.status_id ' + sFrom_rule + sWhere_rule + sOrder_rule + ' LIMIT 1 ' ) """ This prints 0L """ # Get result for second query, not sure if I'm doing the right thing oResult2 = oCursor.fetchone() >>> print oResult2 None I'm probably doing something wrong here, but with the activeX objects it would have printed something like job_id=integer, type_id=integer, frame=integer, status=integer Thanks Bernard From alipolatel at yahoo.com Mon Aug 16 11:46:49 2004 From: alipolatel at yahoo.com (Ali Polatel) Date: Mon Aug 16 11:46:52 2004 Subject: [Tutor] Tkinter again Message-ID: <20040816094649.6147.qmail@web61009.mail.yahoo.com> I have saved the file as xxx.pyw still couldn't get rid of this DOS box !!! Why is that Regards --------------------------------- Do you Yahoo!? Yahoo! Mail - You care about security. So do we. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040816/1a8d86c7/attachment.htm From python at bernardlebel.com Mon Aug 16 14:58:03 2004 From: python at bernardlebel.com (Bernard Lebel) Date: Mon Aug 16 14:58:09 2004 Subject: [Tutor] python-mysql - please disregard Message-ID: <004201c48390$abb399a0$0d01a8c0@studioaction.local> Please disregard my email. MySQL is as new to me than Python is, so I'm mixing things a little bit. All sorted now. Thanks Bernard ----- Original Message ----- From: "Bernard Lebel" To: Sent: Monday, August 16, 2004 9:54 AM Subject: Re: [Tutor] python-mysql > Hi again, > > I have another question. > I managed to properly install the module, and it works, because I can > connect to the database, I can create an object, and I can even send a query > and fetch the result. > > However this time the problem is that when I used to use VBScript and > JScript to do the same thing with an activeX object, I could send a second > query using arguments obtained from the first, but now it doesn't and I'm > not sure why. Here is my code: > > > > # Import module > import MySQLdb > > # Create instance > sql = MySQLdb > > # host (server) > sHost = 'xxx.xxx.x.x' > > # uid (user) > sUser = 'xsi_client' > > # pwd (password) > sPwd = 'XSIBatchServe' > > # database > sDB = 'XSI_R' > > # Create connection object > oDB = sql.connect( sHost, sUser, sPwd , sDB ) > > iID = 31 > sID = str( iID ) > > # Execute first query > oCursor.execute( ' SELECT from_rule, where_rule, order_rule ' + ' FROM > clients LEFT JOIN rules ON rules.id=clients.rule_id' + ' WHERE > clients.c_id=' + sID ) > > # Get first query result > oResult1 = oCursor.fetchone() > > # Define new rules > sFrom_rule_orig = oResult1[0] > sFrom_rule = sFrom_rule_orig.replace( '$id', sID ) > sWhere_rule = str( oResult1[1] ) > sOrder_rule = str( oResult1[2] ) > > # Execute second query > oCursor.execute( ' SELECT jobs.job_id, jobs.type_id, tasks.frame, > jobs.status_id ' + sFrom_rule + sWhere_rule + sOrder_rule + ' LIMIT 1 ' ) > > """ > This prints > 0L > """ > > # Get result for second query, not sure if I'm doing the right thing > oResult2 = oCursor.fetchone() > > >>> print oResult2 > None > > > I'm probably doing something wrong here, but with the activeX objects it > would have printed something like > job_id=integer, type_id=integer, frame=integer, status=integer > > > > Thanks > Bernard > From s4046441 at student.uq.edu.au Mon Aug 16 15:03:51 2004 From: s4046441 at student.uq.edu.au (Ms Soo Chong) Date: Mon Aug 16 15:03:56 2004 Subject: [Tutor] Problem with CGI module Message-ID: Hi, I tried a very simple CGI and managed to did it! Thank you for python tutor's help. Currently, I'm working on the pg and pgdb module connection. Cheers, Shufen ----- Original Message ----- From: Kent Johnson Date: Sunday, August 15, 2004 11:59 pm Subject: Re: [Tutor] Problem with CGI module > Shufen, > > Try a very simple CGI that just outputs a static page. You may > have a logic > error in the code you posted - it looks like there could be some > combination of input fields that causes nothing to output. (The > indentation > in your posting is corrupted so I can't be sure about this.) > > See what the server request log is reporting when you try to > access the > CGI. There should be some entry there. > > Kent From kent_johnson at skillsoft.com Mon Aug 16 15:18:41 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Mon Aug 16 15:18:46 2004 Subject: [Tutor] Questions on pgDB connection In-Reply-To: References: Message-ID: <6.1.0.6.0.20040816091442.029e0f40@mail4.skillsoft.com> Maybe you need the host name in your connection string. Are you running PostgreSQL on the same machine as your Python script? Then try import pgdb db = pgdb.connect(dsn='localhost:moncdata', user='username', password='None') What error messages are you getting? Good luck, Kent At 05:06 PM 8/16/2004 +1000, Ms Soo Chong wrote: >Hi all, > >I have problem connecting using pgdb module. > >I read this webpage: 1) >http://www.linuxjournal.com/article.php?sid=2605 and >2) http://www/python.org/peps/pep-0249.html. > > >From these websites I knew that I have to first >import the pgdb module then connect but the problem >is I don't know what is the connection word to >connect to the pgdb/server. Anybody know what I'm >talking about? I might sound stupid but I really not >sure about the connection stuffs and I have tried >lots of method but it just doesn't work for me. > >The first webpage stated that if you are using the >SOLID version, the UNIX pipes are the only method >available to connect to the server. So what is the >method to connect the server if I'm using pgdb? > >The second webpage stated that a connect should look >like this: > >e.g. connect(dsn='myhost:MYDB', user='guido', >password='234$') > >and it also stated that other than dsn, the other >stuffs such as user and passwd are optional, is it true? > >my script looks like this: > >import pgdb >db = pgdb.connect(dsn='moncdata', user='username', >password='None') > >I really appreciate if someone out there can give me >some help. > >Thank you in advance. > >Cheers >Shufen > > > > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From andy at andybak.net Mon Aug 16 15:30:37 2004 From: andy at andybak.net (Andy Baker) Date: Mon Aug 16 15:30:11 2004 Subject: [Tutor] easy way to make image thumbnails without using PIL? In-Reply-To: <200408161314.35147.thomi@imail.net.nz> Message-ID: <20040816133007.C77F41E4004@bag.python.org> Is it me or are PIL image filters sorely in need of some updating? Their PSD filter baulks at anything after Photoshop 4 and doesn't seem to like extra alpha channels. I asked on the PIL mailing list but no-one really replied. I made a start at messing around with the source and it looks fixable if I ever get the time. If you feel up to it you might want to see if you could tweak the PNG filter source code. I found it fairly simple to understand the PSD filter even when I had just started getting my head around Python (yay for Python's readability!) > -----Original Message----- > From: tutor-bounces@python.org > [mailto:tutor-bounces@python.org] On Behalf Of Thomas Clive Richards > Sent: 16 August 2004 02:15 > To: tutor@python.org > Subject: [Tutor] easy way to make image thumbnails without using PIL? > > > Hi, > > I'm trying to write a function that takes an image filenme as > input and creates a thumbnail in the same directory. At the > moment I'm using the Python Imaging Library (PIL). The > function looks a bit like this: > > > def GenerateThumbnail(imgpath): > try: > im = Image.open(imgpath) > im.thumbnail((128,128)) > b,e = os.path.splitext(imgpath) > im.save(b + global_config.THUMBNAIL_EXTENSION + ".png","PNG") > except IOError: > print "an error occured processing ", imgpath > > However, PIL doesn't support interlaced PNG images, which > happen to be most of the images I want to convert. > > What's more, I'll be using this script on a web server that I > don't own, so I can't use any external packages (like the > python ImageMagick bindings for example). > > Is this possible? I see the "imageop" module, but that seems > only to work on bitmaps... > > > Any ideas greatly appreciated. > > Thanks, > > -- > > Thomi Richards, > thomi@once.net.nz > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From s4046441 at student.uq.edu.au Mon Aug 16 15:43:24 2004 From: s4046441 at student.uq.edu.au (Ms Soo Chong) Date: Mon Aug 16 15:43:31 2004 Subject: [Tutor] Questions on pgDB connection Message-ID: Hi, Thanks for your prompt reply. PostgreSQL is in the same machine as my python script. Actually, I have already tried this method : import pgdb db = pgdb.connect(dsn='localhost:moncdata', user='username', password='None') The error message showed something related to the password, stating that it is unknown. I'm not very sure about the exact error message, sorry, B'cos I'm currently not in the Uni, therefore, I can't check the message, but mayb I will take it down tomorrow and email python tutor again. I'm not very sure about the problem too and when I got rid of passwd, it will show another error msg about the local host. #moncdata is the name of the database, I'm currently working at. I wonder if there is any useful script around using pgdb? Can someone recommend me, I really need that. Thank you in advance. Cheers, Shufen ----- Original Message ----- From: Kent Johnson Date: Monday, August 16, 2004 11:18 pm Subject: Re: [Tutor] Questions on pgDB connection > Maybe you need the host name in your connection string. Are you > running > PostgreSQL on the same machine as your Python script? Then try > import pgdb > db = pgdb.connect(dsn='localhost:moncdata', user='username', > password='None') > > What error messages are you getting? > > Good luck, > Kent From kent_johnson at skillsoft.com Mon Aug 16 15:58:28 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Mon Aug 16 15:58:39 2004 Subject: [Tutor] Questions on pgDB connection In-Reply-To: References: Message-ID: <6.1.0.6.0.20040816095343.02a02720@mail4.skillsoft.com> Is the password really "None" or is it empty? Maybe you should try db = pgdb.connect(dsn='localhost:moncdata', user='username', password='') Kent At 11:43 PM 8/16/2004 +1000, Ms Soo Chong wrote: >Hi, > >Thanks for your prompt reply. > >PostgreSQL is in the same machine as my python script. >Actually, I have already tried this method : > >import pgdb >db = pgdb.connect(dsn='localhost:moncdata', user='username', > password='None') > >The error message showed something related to the password, >stating that it is unknown. I'm not very sure about the >exact error message, sorry, B'cos I'm currently not in the >Uni, therefore, I can't check the message, but mayb I will >take it down tomorrow and email python tutor again. From s4046441 at student.uq.edu.au Mon Aug 16 15:59:13 2004 From: s4046441 at student.uq.edu.au (Ms Soo Chong) Date: Mon Aug 16 15:59:25 2004 Subject: [Tutor] Question on pg and pgdb module again Message-ID: Hi, Is me again...;p Actually, my supervisor for my thesis had tried something using pg module and I think it worked pretty well at this stage. However, I'm the one responsible to create a web-based browser that do search from the database(moncdata)and display it. So I trying to get the simple stuff working first before I move on to the tough part. I wonder which one to use, so right now I'm trying the pgdb module so that I can at least I'm able to do a comparison between them and reflect them in my thesis report. The following worked well for pg module but not for pgdb module: import pg db = pg.connect("moncdata", user=username, passwd=None) Can anyone give me some good suggestion? Thank you again..... # CGI header lines to tell the browser what to expect. print "Content-type: text/plain" # print "Content-length: ", len(resultString) print "" # We redirect the standard-error stream to the standard-out stream # so that we can see the error text in the browser. import sys sys.stderr = sys.stdout # It seems that we need to have an appropriate username that matches # an entry in the postgresql table of users. import os username = os.environ.get('USER') # print "username: ", username, type(username) if username == None: # Assume that the web server has started this script and has the # username 'apache'. To allow this to access the database, we had # to create a postgresql user of that name and have no password. # This new user is also able to create tables and new users, # otherwise the access seems to be blocked. (This might be a # security problem but only for our database tables.) username = 'apache' # Now, we can get to the database... import pg db = pg.connect("moncdata", user=username, passwd=None) qresult = db.query("select * from shot_descriptions where shot_number = 7399") listOfResults = qresult.dictresult() # Make sure that we have a string. resultString = repr(listOfResults) print "Raw result obtained from database:" print resultString print "" print "Example of pulling the list of dictionary results apart." for record in listOfResults: print "------- start of record -----------" for k in record.keys(): print "key: ", k, " value:", record[k] print "--------- end of record -----------" db.close() Cheers, Shufen From jfabiani at yolo.com Mon Aug 16 18:56:33 2004 From: jfabiani at yolo.com (John Fabiani) Date: Mon Aug 16 19:05:31 2004 Subject: [Tutor] Question on pg and pgdb module again In-Reply-To: References: Message-ID: <200408160956.33406.jfabiani@yolo.com> import pgdb con=pgdb.connect('192.168.1.202:acct_am:johnf:passwd') where '192.168.1.202' = the server could be localhost. acct_am = the database johnf = the user passwd = the password for the user and database John From tim.peters at gmail.com Mon Aug 16 19:35:02 2004 From: tim.peters at gmail.com (Tim Peters) Date: Mon Aug 16 19:35:18 2004 Subject: [Tutor] problem with time module In-Reply-To: <6.1.2.0.2.20040815230611.02478b58@rcblue.com> References: <6.1.2.0.2.20040814115248.0445c008@rcblue.com> <1f7befae04081421514e9a1be4@mail.gmail.com> <6.1.2.0.2.20040814221356.0230bec0@rcblue.com> <1f7befae04081519126abbb626@mail.gmail.com> <6.1.2.0.2.20040815230611.02478b58@rcblue.com> Message-ID: <1f7befae040816103537796cca@mail.gmail.com> [Dick Moores] > Please forgive me for persisting here, but mktime(t) is not the inverse > function of localtime() in the same precise way that pow(n,2) and sqrt > (n) are inverses of each other (for n >= 0): > > >>> from math import sqrt > >>> n = 78.56 > >>> print pow(sqrt(n),2) > 78.56 > >>> print sqrt(pow(n,2)) > 78.56 > > Thus my misunderstanding of the doc. Au contraire: >>> from time import mktime as m, localtime as lt >>> m(lt(0)) 0.0 >>> m(lt(1)) 1.0 >>> m(lt(2)) 2.0 >>> m(lt(123456789)) 123456789.0 >>> They're exact inverses, so long as localtime's argument is an integral value (has no fractional seconds). Because of floating-point rounding errors, they're closer to being exact inverses than sqrt and pow(_, 2)! >>> from math import sqrt >>> pow(sqrt(2), 2) 2.0000000000000004 >>> > ... > And thanks very much for your assistance, Mr. Peters. My father died a long time ago -- I'm just Uncle Timmy . From alan.gauld at blueyonder.co.uk Mon Aug 16 20:29:03 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Mon Aug 16 20:30:30 2004 Subject: [Tutor] (no subject) References: <9A4B2157EFDBE546BECD68C62AC3B1C81738F3CB@es05snlnt.sandia.gov> Message-ID: <018a01c483be$e86e63b0$6401a8c0@xp> > How to Think Like a Computer Scientist > http://www.ibiblio.org/obp/thinkCSpy/ > > and > > Alans book as well And the original online tutor is also in pdf and Palm doc format. The new tutor will also be in PDF once I've finished it and get round to converting it. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/ From rdm at rcblue.com Mon Aug 16 20:38:53 2004 From: rdm at rcblue.com (Dick Moores) Date: Mon Aug 16 20:38:55 2004 Subject: [Tutor] problem with time module In-Reply-To: <1f7befae040816103537796cca@mail.gmail.com> References: <6.1.2.0.2.20040814115248.0445c008@rcblue.com> <1f7befae04081421514e9a1be4@mail.gmail.com> <6.1.2.0.2.20040814221356.0230bec0@rcblue.com> <1f7befae04081519126abbb626@mail.gmail.com> <6.1.2.0.2.20040815230611.02478b58@rcblue.com> <1f7befae040816103537796cca@mail.gmail.com> Message-ID: <6.1.2.0.2.20040816113721.023d0dc8@rcblue.com> Tim Peters wrote at 10:35 8/16/2004: > >>> from time import mktime as m, localtime as lt > >>> m(lt(0)) >0.0 > >>> m(lt(1)) >1.0 > >>> m(lt(2)) >2.0 > >>> m(lt(123456789)) >123456789.0 > >>> > >They're exact inverses, so long as localtime's argument is an integral >value (has no fractional seconds) Yikes! You're right. I've got it now--finally. Thanks again, Dick Moores From dyoo at hkn.eecs.berkeley.edu Mon Aug 16 22:14:14 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Aug 16 22:14:18 2004 Subject: [Tutor] RE troubles (fwd) Message-ID: [Followup to tutor@python.org; =D8yvind figured out a good regex that does nongreedy matching for the problem.] ---------- Forwarded message ---------- Date: Mon, 16 Aug 2004 20:58:42 +0200 (CEST) From: "[iso-8859-1] =D8yvind" To: Danny Yoo Subject: Re: [Tutor] RE troubles >> I know that the word is following "target=3D"_top">" and is before "
= > href=3Djavascript". So the document will contain five instances of: >> >> target=3D"_top"> word1 > target=3D"_top">sentence 2> and so forth.... >> >> How do I get them out? > > > You can probably get what you want by doing something like this: > > ### >>>> regex =3D re.compile(r"""\| > ... (.*?) > ... \|""", re.VERBOSE) >>>> > ### Hello and thanks for the help. I got the following to work. Hopefully it is a good way of doing it... rawstr =3D r"""target=3D"_top">(.*?)\n References: <20040816133007.C77F41E4004@bag.python.org> Message-ID: <200408170917.18532.thomi@imail.net.nz> On Tue, 17 Aug 2004 1:30 am, Andy Baker wrote: > Is it me or are PIL image filters sorely in need of some updating? Their > PSD filter baulks at anything after Photoshop 4 and doesn't seem to like > extra alpha channels. I asked on the PIL mailing list but no-one really > replied. I made a start at messing around with the source and it looks > fixable if I ever get the time. > > If you feel up to it you might want to see if you could tweak the PNG > filter source code. I found it fairly simple to understand the PSD filter > even when I had just started getting my head around Python (yay for > Python's readability!) > I will certainly take alook, but I'm doubtful that I'll be able t fix anything... Thanks for the tip! -- Thomi Richards, thomi@once.net.nz From dyoo at hkn.eecs.berkeley.edu Tue Aug 17 02:30:05 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Aug 17 02:30:12 2004 Subject: [Tutor] Tkinter again In-Reply-To: <20040816094649.6147.qmail@web61009.mail.yahoo.com> Message-ID: On Mon, 16 Aug 2004, Ali Polatel wrote: > I have saved the file as xxx.pyw still couldn't get rid of this DOS box > !!! Hi Ali, (Hmmm... this is slightly hard to debug without access to a Windows machine. *grin*) Ok, let me cover some simple situations first, just in case we're dealing with a simple problem: Did you also update the 'setup.py' file to refer to the '.pyw' program? What does 'setup.py' look like now? Did you re-run the py2exe stuff afterwards? If that didn't work, did you have luck using the '-w' option to py2exe? Good luck to you! From s4046441 at student.uq.edu.au Tue Aug 17 04:03:52 2004 From: s4046441 at student.uq.edu.au (Ms Soo Chong) Date: Tue Aug 17 04:03:58 2004 Subject: [Tutor] Question on pg and pgdb module again Message-ID: Hi, Thanks for the info. So if there is no password for the user and the database, the connection should look like this: import pgdb con=pgdb.connect('192.168.1.202:acct_am:johnf') where '192.168.1.202' = the server could be localhost. acct_am = the database johnf = the user Besides, this program has no userid too, so do I have to define a username as written in my script shown earlier on or I can just connection without the username? Thank you in advance. Shufen ----- Original Message ----- From: John Fabiani Date: Tuesday, August 17, 2004 2:56 am Subject: Re: [Tutor] Question on pg and pgdb module again > import pgdb > con=pgdb.connect('192.168.1.202:acct_am:johnf:passwd') > where '192.168.1.202' = the server could be localhost. > acct_am = the database > johnf = the user > passwd = the password for the user and database > John > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From python at bernardlebel.com Mon Aug 16 23:50:53 2004 From: python at bernardlebel.com (Bernard Lebel) Date: Tue Aug 17 07:11:36 2004 Subject: [Tutor] Comparing to list elements Message-ID: <000501c483db$1c5f4a60$2901a8c0@atyss> Hello, I wish to compare a variable value to the elements from a list. For example: aList = [ 'hi', 'hello', 'welcome' ] sString = 'goodbye' Now I want to check if 'goodbye' is present in aList, and if not, take action. Thanks Bernard From gew75 at hotmail.com Tue Aug 17 07:28:18 2004 From: gew75 at hotmail.com (Glen Wheeler) Date: Tue Aug 17 07:28:26 2004 Subject: [Tutor] Comparing to list elements References: <000501c483db$1c5f4a60$2901a8c0@atyss> Message-ID: I'll present a solution in the form of a list comprehension. That way, if you don't know about these, then it incites further education :). >>> aList = [ 'hi', 'hello', 'welcome' ] >>> sString = 'goodbye' >>> [x for x in aList if x == sString] [] >>> if [x for x in aList if x == sString]: .. print "sString is in aList" .. >>> HTH, Glen ----- Original Message ----- From: "Bernard Lebel" To: Sent: Tuesday, August 17, 2004 7:50 AM Subject: [Tutor] Comparing to list elements > Hello, > > I wish to compare a variable value to the elements from a list. > For example: > > aList = [ 'hi', 'hello', 'welcome' ] > sString = 'goodbye' > > > Now I want to check if 'goodbye' is present in aList, and if not, take > action. > > > Thanks > Bernard > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From milgrom at gmail.com Tue Aug 17 07:41:55 2004 From: milgrom at gmail.com (Alfred Milgrom) Date: Tue Aug 17 07:41:58 2004 Subject: [Tutor] Comparing to list elements In-Reply-To: References: <000501c483db$1c5f4a60$2901a8c0@atyss> Message-ID: <50eadd0a04081622411a9e713@mail.gmail.com> There's an easier way than list comprehension to find out if an element is in a list - use the 'in' operator: if sString in aList: print 'it's there' else: print 'not there' HTH On Tue, 17 Aug 2004 15:28:18 +1000, Glen Wheeler wrote: > > I'll present a solution in the form of a list comprehension. > That way, if you don't know about these, then it incites further education > :). > > >>> aList = [ 'hi', 'hello', 'welcome' ] > >>> sString = 'goodbye' > >>> [x for x in aList if x == sString] > [] > >>> if [x for x in aList if x == sString]: > ... print "sString is in aList" > ... > >>> > > HTH, > Glen > > > > ----- Original Message ----- > From: "Bernard Lebel" > To: > Sent: Tuesday, August 17, 2004 7:50 AM > Subject: [Tutor] Comparing to list elements > > > Hello, > > > > I wish to compare a variable value to the elements from a list. > > For example: > > > > aList = [ 'hi', 'hello', 'welcome' ] > > sString = 'goodbye' > > > > > > Now I want to check if 'goodbye' is present in aList, and if not, take > > action. > > > > > > Thanks > > Bernard From rdm at rcblue.com Tue Aug 17 11:21:15 2004 From: rdm at rcblue.com (Dick Moores) Date: Tue Aug 17 11:21:31 2004 Subject: [Tutor] _Object Thinking_, by David West In-Reply-To: <00f301c4829c$7cbe93b0$6401a8c0@xp> References: <6.1.2.0.2.20040814083146.04f0bec0@rcblue.com> <00c901c48235$e26a2060$6401a8c0@xp> <6.1.2.0.2.20040814124140.05d04458@rcblue.com> <00f301c4829c$7cbe93b0$6401a8c0@xp> Message-ID: <6.1.2.0.2.20040817020049.0247eef0@rcblue.com> Alan Gauld wrote at 00:50 8/15/2004: > > >If you want to understand OOP I'd still recommend something like > > >Timothy Budds classic OOP book or Grady Booch's classic OOA/D >first. > > > > Is this the Budds book: http://tinyurl.com/6v68l ? > >Yes, but I'd borrow this one if you can rather than buy it. Yes. It's expensive. And it's not in my local library. I'll ask them to either buy a copy or get an interlibrary loan. > > My local library has "Object-oriented analysis and design with > > applications" by Grady Booch. I assume this is the one you mean? I'm >6th > > in line for the one copy. And there are several very inexpensive >copies > > available through Bookfinder.com. > >I'd buy a copy if you can. I bought mine (1st edition) in 1992 >and still refer to it several times a year. The notation has >now been superceded by UML but the principles of design are still >absolutely valid. I also prefer the first edition to the second >because it uses mnultiple OO languages whereas the second >focuses only on C++ (which was flavor of the day at the time). Got the 1st edition yesterday for a couple of bucks. And Code Complete (2nd ed.) arrived in the mail. Thanks again, Dick Moores From alipolatel at yahoo.com Tue Aug 17 12:33:41 2004 From: alipolatel at yahoo.com (Ali Polatel) Date: Tue Aug 17 12:33:44 2004 Subject: [Tutor] Tkinter again In-Reply-To: Message-ID: <20040817103341.68107.qmail@web61005.mail.yahoo.com> I have done the first two but what is the -w option of py2exe? Regards --------------------------------- Do you Yahoo!? New and Improved Yahoo! Mail - 100MB free storage! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040817/3b60a57d/attachment.html From cecilwesterhof at xs4all.nl Tue Aug 17 14:43:48 2004 From: cecilwesterhof at xs4all.nl (cecilwesterhof@xs4all.nl) Date: Tue Aug 17 14:43:51 2004 Subject: [Tutor] Python and sockets Message-ID: <12666.193.79.20.178.1092746628.squirrel@webmail.xs4all.nl> I started with python and also with sockets. I wrote a little program to start using sockets. In principle it works okay. There are only two problems: - When I open a socket and it is refused by the server, I just get a socket back, without a signal that the server refused the connection. What do I need to do, to see that the connection is refused? - When I close a socket that has no data waiting, everything works fine. But when I close a socket that still has data to be read. The socket is closed, but the server never sees that it is closed. I tried using shutdown, but this did not change anything. What do I need to do, so that the server sees the close? Does anybody have a good resource for python and sockets? From nick at javacat.f2s.com Tue Aug 17 14:57:30 2004 From: nick at javacat.f2s.com (Nick Lunt) Date: Tue Aug 17 14:55:03 2004 Subject: [Tutor] Python and sockets In-Reply-To: <12666.193.79.20.178.1092746628.squirrel@webmail.xs4all.nl> Message-ID: Theres a book out soon about python socket programming, http://www.compman.co.uk/cgi-win/browse.exe?ref=658967 Also, I find www.twistedmatrix.com much more useful for network programs, and Im still a python beginner. Depends what you want to do though I suppose ;) Regarding your problem, it'd probably be best if you could post some of the offending code ;) Nick. -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org]On Behalf Of cecilwesterhof@xs4all.nl Sent: 17 August 2004 13:44 To: tutor@python.org Subject: [Tutor] Python and sockets I started with python and also with sockets. I wrote a little program to start using sockets. In principle it works okay. There are only two problems: - When I open a socket and it is refused by the server, I just get a socket back, without a signal that the server refused the connection. What do I need to do, to see that the connection is refused? - When I close a socket that has no data waiting, everything works fine. But when I close a socket that still has data to be read. The socket is closed, but the server never sees that it is closed. I tried using shutdown, but this did not change anything. What do I need to do, so that the server sees the close? Does anybody have a good resource for python and sockets? _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From python at bernardlebel.com Tue Aug 17 15:03:39 2004 From: python at bernardlebel.com (Bernard Lebel) Date: Tue Aug 17 15:03:45 2004 Subject: [Tutor] Comparing to list elements References: <000501c483db$1c5f4a60$2901a8c0@atyss> <50eadd0a04081622411a9e713@mail.gmail.com> Message-ID: <008701c4845a$9e4ee470$0d01a8c0@studioaction.local> One word: awesome. I'm amazed how straigthforward Python can be... Bernard ----- Original Message ----- From: "Alfred Milgrom" To: "Glen Wheeler" Cc: "Bernard Lebel" ; Sent: Tuesday, August 17, 2004 7:41 AM Subject: Re: [Tutor] Comparing to list elements > There's an easier way than list comprehension to find out if an > element is in a list - use the 'in' operator: > > if sString in aList: > print 'it's there' > else: > print 'not there' > > HTH > > On Tue, 17 Aug 2004 15:28:18 +1000, Glen Wheeler wrote: > > > > I'll present a solution in the form of a list comprehension. > > That way, if you don't know about these, then it incites further education > > :). > > > > >>> aList = [ 'hi', 'hello', 'welcome' ] > > >>> sString = 'goodbye' > > >>> [x for x in aList if x == sString] > > [] > > >>> if [x for x in aList if x == sString]: > > ... print "sString is in aList" > > ... > > >>> > > > > HTH, > > Glen > > > > > > > > ----- Original Message ----- > > From: "Bernard Lebel" > > To: > > Sent: Tuesday, August 17, 2004 7:50 AM > > Subject: [Tutor] Comparing to list elements > > > > > Hello, > > > > > > I wish to compare a variable value to the elements from a list. > > > For example: > > > > > > aList = [ 'hi', 'hello', 'welcome' ] > > > sString = 'goodbye' > > > > > > > > > Now I want to check if 'goodbye' is present in aList, and if not, take > > > action. > > > > > > > > > Thanks > > > Bernard > > From cecilwesterhof at xs4all.nl Tue Aug 17 15:32:10 2004 From: cecilwesterhof at xs4all.nl (cecilwesterhof@xs4all.nl) Date: Tue Aug 17 15:32:12 2004 Subject: [Tutor] Python and sockets In-Reply-To: References: <12666.193.79.20.178.1092746628.squirrel@webmail.xs4all.nl> Message-ID: <13303.193.79.20.178.1092749530.squirrel@webmail.xs4all.nl> > Theres a book out soon about python socket programming, > http://www.compman.co.uk/cgi-win/browse.exe?ref=658967 I'll keep an eye out for it. > Also, I find www.twistedmatrix.com much more useful for network programs, > and Im still a python beginner. Looks interesting. > Regarding your problem, it'd probably be best if you could post some of > the > offending code ;) Here is the program: #!/bin/python import socket; import sys; import Tkinter; def Connect(): global Connected, Socket; if( Connected == False ): Socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM); Socket.connect(('localhost', 4001)); print "Connected to server"; Connected = True; else: print "Allready connected to server"; def Disconnect(): global Connected, Socket; if( Connected == True ): Socket.shutdown(2); Socket.close(); Socket = ""; print "Disconnected from server"; Connected = False; else: print "Not connected to server"; def Exit(): global Connected, Socket; if( Connected == True ): Socket.close(); print "We zijn klaar"; sys.exit(); def Receive(): global Connected, Socket; if( Connected == True ): Received = Socket.recv(8192); print "Received: ", Received; else: print "Not connected to server"; Socket = ""; Connected = False; Tkinter.Label(text = "Welcome!").pack(); Tkinter.Button(text = "Connect", command = Connect).pack(); Tkinter.Button(text = "Disconnect", command = Disconnect).pack(); Tkinter.Button(text = "Receive", command = Receive).pack(); Tkinter.Button(text = "Exit", command = Exit).pack(); Tkinter.mainloop(); From kent_johnson at skillsoft.com Tue Aug 17 16:14:18 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Tue Aug 17 16:14:18 2004 Subject: [Tutor] Python and sockets In-Reply-To: <12666.193.79.20.178.1092746628.squirrel@webmail.xs4all.nl> References: <12666.193.79.20.178.1092746628.squirrel@webmail.xs4all.nl> Message-ID: <6.1.0.6.0.20040817100727.028c7d90@mail4.skillsoft.com> When I run your program with no server at port 4001 and click Connect, I get a traceback in the console: D:\Personal\Tutor>python sockettest.py Exception in Tkinter callback Traceback (most recent call last): File "C:\Python23\lib\lib-tk\Tkinter.py", line 1345, in __call__ return self.func(*args) File "sockettest.py", line 12, in Connect Socket.connect(('localhost', 4001)); File "", line 1, in connect error: (10061, 'Connection refused') Do you see this when you run it? You can catch the exception in the Connect function if you want to handle it in another way: if( Connected == False ): try: Socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM); Socket.connect(('localhost', 4001)); print "Connected to server"; Connected = True; except socket.error: print "Connection failure" By the way your use of globals to pass the Socket and Connected variables around is a strong hint that you should put Connect(), Disconnect(), Exit() and Receive() into a class with Socket and Connected as fields. Also you do not need semicolons for line endings in Python, you just use semicolons if you want to put two statements on the same line :-) HTH, Kent At 02:43 PM 8/17/2004 +0200, cecilwesterhof@xs4all.nl wrote: >I started with python and also with sockets. I wrote a little program to >start using sockets. In principle it works okay. There are only two >problems: > >- When I open a socket and it is refused by the server, I just get a >socket back, without a signal that the server refused the connection. What >do I need to do, to see that the connection is refused? From python at bernardlebel.com Tue Aug 17 16:32:41 2004 From: python at bernardlebel.com (Bernard Lebel) Date: Tue Aug 17 16:32:48 2004 Subject: [Tutor] os.access(), problems with mode variable Message-ID: <00bc01c48467$0e10daa0$0d01a8c0@studioaction.local> Hello, Trying to test the existence of a file, using the access function from the os module. In the documentation it is said to use F_OK as the mode for such thing. However when I run the code below, I get a "NameError: name 'F_OK' is not defined". Any suggestion? import os sPath = 'C:\\file.txt' if os.access( sPath, F_OK ) == 1: print 'yeah!' else: print 'nah' Thanks in advance Bernard From kraus at hagen-partner.de Tue Aug 17 16:42:45 2004 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Tue Aug 17 16:50:38 2004 Subject: [Tutor] Re: os.access(), problems with mode variable In-Reply-To: <00bc01c48467$0e10daa0$0d01a8c0@studioaction.local> References: <00bc01c48467$0e10daa0$0d01a8c0@studioaction.local> Message-ID: Heyho! Bernard Lebel wrote: > Hello, > > Trying to test the existence of a file, using the access function from the > os module. > In the documentation it is said to use F_OK as the mode for such thing. > However when I run the code below, I get a "NameError: name 'F_OK' is not > defined". > > Any suggestion? > > import os Either add the following line: from os import F_OK > > sPath = 'C:\\file.txt' > > if os.access( sPath, F_OK ) == 1: Or change this if statement to: if os.access( sPath, os.F_OK ) == 1: > print 'yeah!' > else: > print 'nah' > > Thanks in advance > Bernard > HTH, Wolfram From python at bernardlebel.com Tue Aug 17 16:57:02 2004 From: python at bernardlebel.com (Bernard Lebel) Date: Tue Aug 17 16:58:00 2004 Subject: [Tutor] Re: os.access(), problems with mode variable References: <00bc01c48467$0e10daa0$0d01a8c0@studioaction.local> Message-ID: <00ce01c4846a$92d5a010$0d01a8c0@studioaction.local> Thank you very much Wolfram. Bernard ----- Original Message ----- From: "Wolfram Kraus" To: Sent: Tuesday, August 17, 2004 4:42 PM Subject: [Tutor] Re: os.access(), problems with mode variable > Heyho! > > Bernard Lebel wrote: > > Hello, > > > > Trying to test the existence of a file, using the access function from the > > os module. > > In the documentation it is said to use F_OK as the mode for such thing. > > However when I run the code below, I get a "NameError: name 'F_OK' is not > > defined". > > > > Any suggestion? > > > > > import os > Either add the following line: > from os import F_OK > > > > > sPath = 'C:\\file.txt' > > > > if os.access( sPath, F_OK ) == 1: > Or change this if statement to: > if os.access( sPath, os.F_OK ) == 1: > > > print 'yeah!' > > else: > > print 'nah' > > > > Thanks in advance > > Bernard > > > HTH, > Wolfram > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From kent_johnson at skillsoft.com Tue Aug 17 18:09:27 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Tue Aug 17 18:09:35 2004 Subject: [Tutor] os.access(), problems with mode variable In-Reply-To: <00bc01c48467$0e10daa0$0d01a8c0@studioaction.local> References: <00bc01c48467$0e10daa0$0d01a8c0@studioaction.local> Message-ID: <6.1.0.6.0.20040817120140.028a6f18@mail4.skillsoft.com> FWIW you can also use os.path.exists() for this. It's a bit more readable if nothing else: import os sPath = 'C:\\file.txt' if os.path.exists( sPath ): print 'yeah!' else: print 'nah' Kent At 04:32 PM 8/17/2004 +0200, Bernard Lebel wrote: >Hello, > >Trying to test the existence of a file, using the access function from the >os module. >In the documentation it is said to use F_OK as the mode for such thing. >However when I run the code below, I get a "NameError: name 'F_OK' is not >defined". > >Any suggestion? > > >import os > >sPath = 'C:\\file.txt' > >if os.access( sPath, F_OK ) == 1: > print 'yeah!' >else: > print 'nah' > > > > >Thanks in advance >Bernard > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From dyoo at hkn.eecs.berkeley.edu Tue Aug 17 19:16:51 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Aug 17 19:16:54 2004 Subject: [Tutor] RE troubles (fwd) Message-ID: [Forwarding to tutor@python.org. Please don't send questions to me alone: send them to the Tutor list instead. Why limit yourself to just one head, when you can get input from the whole community?] ---------- Forwarded message ---------- Date: Tue, 17 Aug 2004 09:54:12 +0200 (CEST) From: "[iso-8859-1] =D8yvind" To: dyoo@hkn.eecs.berkeley.edu Subject: Re: [Tutor] RE troubles Hello again, I have one more question you hopefully might be able to help me with. I am using the following to extract the words and sentences out of the documents, but it seems like the last character is often missing. Here are a few lines that I would like to extract from: =09
  • coop byggmix
  • christiano ronaldo
  • erop
  • Birgita S=F8strene
  • bademilj=F8 from here I want: coop byggmix christiano ronaldo erop Birgita S=F8strene bademilj=F8 and the code I use to extract is: rawstr =3D r"""target=3D"_top">(.*?)\n Message-ID: On Tue, 17 Aug 2004, Ali Polatel wrote: > I have done the first two but what is the -w option of py2exe? In an earlier email: http://aspn.activestate.com/ASPN/Mail/Message/python-Tutor/2157571 it was mentioned that py2exe takes in optional command line arguments. One of these options is '-w' (or '--windows'), which should disable that console window from popping up. From python_newbie at vedorian.com Tue Aug 17 20:41:52 2004 From: python_newbie at vedorian.com (Kevin) Date: Tue Aug 17 20:42:10 2004 Subject: [Tutor] Random number generation Message-ID: <000c01c48489$dd63aea0$30e57218@basp.phub.net.cable.rogers.com> I am trying to make a simple number guessing game. The only thing that I can't figure out so far is how to get the program to pick a random number? Thanks Kevin --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.726 / Virus Database: 481 - Release Date: 7/22/04 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040817/9aba88b8/attachment.htm From nick at javacat.f2s.com Tue Aug 17 21:13:40 2004 From: nick at javacat.f2s.com (Nick Lunt) Date: Tue Aug 17 21:11:12 2004 Subject: [Tutor] Random number generation In-Reply-To: <000c01c48489$dd63aea0$30e57218@basp.phub.net.cable.rogers.com> Message-ID: Hi Kevin, with the minimal info you've supplied its not easy to be sure what you want. Hows this look [code] from random import randrange rand = randrange(1, 1000) ans = raw_input('Enter an int from 1 to 1000: ') if int(ans) == rand: print 'well done!' else: print 'unlucky!' [/code] This will need to some error trapping in case the user enters a letter for example, also a while loop would be handy so the user has more than one guess ;) This might help http://docs.python.org/tut/node6.html Hope that helps Nick. -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org]On Behalf Of Kevin Sent: 17 August 2004 19:42 To: Python Subject: [Tutor] Random number generation I am trying to make a simple number guessing game. The only thing that I can't figure out so far is how to get the program to pick a random number? Thanks Kevin --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.726 / Virus Database: 481 - Release Date: 7/22/04 From python_newbie at vedorian.com Tue Aug 17 21:15:22 2004 From: python_newbie at vedorian.com (Kevin) Date: Tue Aug 17 21:15:40 2004 Subject: [Tutor] Random number generation References: Message-ID: <000501c4848e$8b7a7f60$30e57218@basp.phub.net.cable.rogers.com> Thats exactly what I was looking for thanks!! ----- Original Message ----- From: "Nick Lunt" To: "Python Tutor" Sent: Tuesday, August 17, 2004 3:13 PM Subject: RE: [Tutor] Random number generation > Hi Kevin, > > with the minimal info you've supplied its not easy to be sure what you want. > > Hows this look > > [code] > > from random import randrange > > rand = randrange(1, 1000) > ans = raw_input('Enter an int from 1 to 1000: ') > > if int(ans) == rand: > print 'well done!' > else: > print 'unlucky!' > > [/code] > > This will need to some error trapping in case the user enters a letter for > example, also a while loop would be handy so the user has more than one > guess ;) > > This might help http://docs.python.org/tut/node6.html > > Hope that helps > Nick. > > > > -----Original Message----- > From: tutor-bounces@python.org [mailto:tutor-bounces@python.org]On Behalf Of > Kevin > Sent: 17 August 2004 19:42 > To: Python > Subject: [Tutor] Random number generation > > > I am trying to make a simple number guessing game. The only thing that I > can't figure out so far is how to get the program to pick a random number? > > Thanks > > Kevin > > > --- > Outgoing mail is certified Virus Free. > Checked by AVG anti-virus system (http://www.grisoft.com). > Version: 6.0.726 / Virus Database: 481 - Release Date: 7/22/04 > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.726 / Virus Database: 481 - Release Date: 7/22/04 From python_newbie at vedorian.com Tue Aug 17 21:31:47 2004 From: python_newbie at vedorian.com (Kevin) Date: Tue Aug 17 21:32:07 2004 Subject: [Tutor] My first python program! Message-ID: <000c01c48490$d6dd4940$30e57218@basp.phub.net.cable.rogers.com> The programm looks a little messed up in email but it looks fine in IDLE But here is the number guessing I just made as my very first programm. Any suggestions on how to improve it would be greate. Kevin def enter(): print """ *************************************** * * * The Number Guessing Game * * By: Cadon * *************************************** ||||||||||||||||||||||||||||||||||||||| + Please enter a choice! + + 1) Enter game + + 2) Exit + +++++++++++++++++++++++++++++++++++++++\r\n""" enter = raw_input("What is your choice? ") if enter == '1': game() else: print '\r\nThank you from looking at the game!' def game(): print "welcome to the number guessing game!\r\n" name = raw_input("What is your name? \r\n") print "Thank you %s, lets continue to the game now!\r\n" % name game2() def game2(): a = randrange(1, 10) guess = int(raw_input("Pick a number from 1 to 10, You only get 5 tries!: \r\n") ) while guess != a: print "Thats not it!\r\n" guess = int(raw_input("Pick a number from 1 to 100, You only get 5 tries!: \r\n") ) else: print "Congrats! that was the correct number!\r\n" ans = raw_input("Would you like to play again?[y/n]: ") if ans == 'y': game2() else: print "Thank you for playing, come back again!\r\n" enter() --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.726 / Virus Database: 481 - Release Date: 7/22/04 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040817/6a63dc45/attachment.html From python_newbie at vedorian.com Tue Aug 17 23:44:20 2004 From: python_newbie at vedorian.com (Kevin) Date: Tue Aug 17 23:44:42 2004 Subject: [Tutor] My first python program! References: <000c01c48490$d6dd4940$30e57218@basp.phub.net.cable.rogers.com> <305be8820408171434418557f2@mail.gmail.com> Message-ID: <000c01c484a3$5d505d20$30e57218@basp.phub.net.cable.rogers.com> Ya I when I copied and pastet the code I missed the import. As for the other ones I forgot to chage the 100 to 10(It was a pain in the but trying to see if the program worked starting from 1 and making my way to 100 lol.). Thanks for the suggestions I will work on that and try and fix it. Kevin ----- Original Message ----- From: "Britt Green" To: "Kevin" Sent: Tuesday, August 17, 2004 5:34 PM Subject: Re: [Tutor] My first python program! > Hi Kevin, > > Your first program looks pretty good. A lot better than my first program! ;) > > Anyways, here's some constructive criticism. I tried to run your > program but got the error: NameError: global name 'randrange' is not > defined. I'm guessing this is because you just forgot to include the > import of the random module in the email. ;) > > In the game2() module, the player is first asked to pick a number from > 1-10. But for every guess thereafter, they have to pick between 1-100! > Eek! It could just be a typo, though. > > The serious bug I found in your program is that the game doesn't end > after five rounds. It ends only when the player correctly guesses the > right number. You should rewrite the while loop so it terminates when > the number of guesses variable reaches five. Otherwise, your program > is a great one, especially for a first attempt! > > Britt > > > ----- Original Message ----- > From: Kevin > Date: Tue, 17 Aug 2004 15:31:47 -0400 > Subject: [Tutor] My first python program! > To: Python > > > The programm looks a little messed up in email but it looks fine in IDLE > But here is the number guessing I just made as my very first programm. > Any suggestions on how to improve it would be greate. > > Kevin > > def enter(): > print """ > *************************************** > * * > * The Number Guessing Game * > * By: Cadon * > *************************************** > ||||||||||||||||||||||||||||||||||||||| > + Please enter a choice! + > + 1) Enter game + > + 2) Exit + > +++++++++++++++++++++++++++++++++++++++\r\n""" > enter = raw_input("What is your choice? ") > if enter == '1': > game() > else: > print '\r\nThank you from looking at the game!' > > > def game(): > print "welcome to the number guessing game!\r\n" > name = raw_input("What is your name? \r\n") > print "Thank you %s, lets continue to the game now!\r\n" % name > game2() > def game2(): > a = randrange(1, 10) > guess = int(raw_input("Pick a number from 1 to 10, You only get 5 > tries!: \r\n") ) > while guess != a: > print "Thats not it!\r\n" > guess = int(raw_input("Pick a number from 1 to 100, You only get > 5 tries!: \r\n") ) > else: > print "Congrats! that was the correct number!\r\n" > ans = raw_input("Would you like to play again?[y/n]: ") > if ans == 'y': > game2() > else: > print "Thank you for playing, come back again!\r\n" > > > enter() > > > > > --- > Outgoing mail is certified Virus Free. > Checked by AVG anti-virus system (http://www.grisoft.com). > Version: 6.0.726 / Virus Database: 481 - Release Date: 7/22/04 > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.726 / Virus Database: 481 - Release Date: 7/22/04 From mhansen at cso.atmel.com Tue Aug 17 23:47:00 2004 From: mhansen at cso.atmel.com (Mike Hansen) Date: Tue Aug 17 23:46:56 2004 Subject: [Tutor] Python and sockets In-Reply-To: <20040817160939.1221C1E400F@bag.python.org> References: <20040817160939.1221C1E400F@bag.python.org> Message-ID: <41227CD4.2080006@cso.atmel.com> Anyone know if Holden's Python Web Programming book covers socket programming? It's pretty cheap on half.com. > > Subject: > RE: [Tutor] Python and sockets > From: > cecilwesterhof@xs4all.nl > Date: > Tue, 17 Aug 2004 15:32:10 +0200 (CEST) > To: > tutor@python.org > > To: > tutor@python.org > > >>Theres a book out soon about python socket programming, >>http://www.compman.co.uk/cgi-win/browse.exe?ref=658967 >> >> > >I'll keep an eye out for it. > > > > From python_newbie at vedorian.com Tue Aug 17 23:58:24 2004 From: python_newbie at vedorian.com (Kevin) Date: Tue Aug 17 23:58:41 2004 Subject: [Tutor] My first python program! References: <000c01c48490$d6dd4940$30e57218@basp.phub.net.cable.rogers.com><305be8820408171434418557f2@mail.gmail.com> <000c01c484a3$5d505d20$30e57218@basp.phub.net.cable.rogers.com> Message-ID: <000701c484a5$520a6620$30e57218@basp.phub.net.cable.rogers.com> Ok here is something I can't figure out I put a define at the top of the program called tries = 5 I need to make this part of the program count down from 5 every time they get a guess wrong. How do I do that? def game2(): a = randrange(1, 10) guess = int(raw_input("Pick a number from 1 to 10, You only get 5 tries!: \r\n") ) while guess != a: print "Thats not it!\r\n" guess = int(raw_input("Pick a number from 1 to 10, You only get 5 tries!: \r\n") ) else: print "Congrats! that was the correct number!\r\n" ans = raw_input("Would you like to play again?[y/n]: ") if ans == 'y': game2() else: while ans != 'n': print "That is not a choice!\r\n" ans = raw_input("Would you like to play again?[y/n]: ") print "Thank you for playing, come back again!\r\n" Thanks Kevin ----- Original Message ----- From: "Kevin" To: "Python" Sent: Tuesday, August 17, 2004 5:44 PM Subject: Re: [Tutor] My first python program! > Ya I when I copied and pastet the code I missed the import. As for the other > ones I forgot to chage the 100 to 10(It was a pain in the but trying to see > if the program worked starting from 1 and making my way to 100 lol.). Thanks > for the suggestions I will work on that and try and fix it. > > Kevin > ----- Original Message ----- > From: "Britt Green" > To: "Kevin" > Sent: Tuesday, August 17, 2004 5:34 PM > Subject: Re: [Tutor] My first python program! > > > > Hi Kevin, > > > > Your first program looks pretty good. A lot better than my first program! > ;) > > > > Anyways, here's some constructive criticism. I tried to run your > > program but got the error: NameError: global name 'randrange' is not > > defined. I'm guessing this is because you just forgot to include the > > import of the random module in the email. ;) > > > > In the game2() module, the player is first asked to pick a number from > > 1-10. But for every guess thereafter, they have to pick between 1-100! > > Eek! It could just be a typo, though. > > > > The serious bug I found in your program is that the game doesn't end > > after five rounds. It ends only when the player correctly guesses the > > right number. You should rewrite the while loop so it terminates when > > the number of guesses variable reaches five. Otherwise, your program > > is a great one, especially for a first attempt! > > > > Britt > > > > > > ----- Original Message ----- > > From: Kevin > > Date: Tue, 17 Aug 2004 15:31:47 -0400 > > Subject: [Tutor] My first python program! > > To: Python > > > > > > The programm looks a little messed up in email but it looks fine in IDLE > > But here is the number guessing I just made as my very first programm. > > Any suggestions on how to improve it would be greate. > > > > Kevin > > > > def enter(): > > print """ > > *************************************** > > * * > > * The Number Guessing Game * > > * By: Cadon * > > *************************************** > > ||||||||||||||||||||||||||||||||||||||| > > + Please enter a choice! + > > + 1) Enter game + > > + 2) Exit + > > +++++++++++++++++++++++++++++++++++++++\r\n""" > > enter = raw_input("What is your choice? ") > > if enter == '1': > > game() > > else: > > print '\r\nThank you from looking at the game!' > > > > > > def game(): > > print "welcome to the number guessing game!\r\n" > > name = raw_input("What is your name? \r\n") > > print "Thank you %s, lets continue to the game now!\r\n" % name > > game2() > > def game2(): > > a = randrange(1, 10) > > guess = int(raw_input("Pick a number from 1 to 10, You only get 5 > > tries!: \r\n") ) > > while guess != a: > > print "Thats not it!\r\n" > > guess = int(raw_input("Pick a number from 1 to 100, You only get > > 5 tries!: \r\n") ) > > else: > > print "Congrats! that was the correct number!\r\n" > > ans = raw_input("Would you like to play again?[y/n]: ") > > if ans == 'y': > > game2() > > else: > > print "Thank you for playing, come back > again!\r\n" > > > > > > enter() > > > > > > > > > > --- > > Outgoing mail is certified Virus Free. > > Checked by AVG anti-virus system (http://www.grisoft.com). > > Version: 6.0.726 / Virus Database: 481 - Release Date: 7/22/04 > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > --- > Outgoing mail is certified Virus Free. > Checked by AVG anti-virus system (http://www.grisoft.com). > Version: 6.0.726 / Virus Database: 481 - Release Date: 7/22/04 > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.726 / Virus Database: 481 - Release Date: 7/22/04 From clavezza at hotmail.com Wed Aug 18 00:00:25 2004 From: clavezza at hotmail.com (christopher lavezza) Date: Wed Aug 18 00:00:29 2004 Subject: [Tutor] Need Help with Source Code Message-ID: could someone take the attachments and run the source code in python and see where I made the mistakes. I am trying to get the source code into an telephone database using python. thank you Chris Lavezza _________________________________________________________________ Don’t just search. Find. Check out the new MSN Search! http://search.msn.click-url.com/go/onm00200636ave/direct/01/ -------------- next part -------------- #!/usr/bin/python # # Simple phone-number database module import shelve import string UNKNOWN = 0 HOME = 1 WORK = 2 FAX = 3 CELL = 4 class phoneentry: def __init__(self, name = 'UNKNOWN', number = 'UNKNOWN', type = 'UNKNOWN'): self.name = name self.number = number self.type = type # create string representation def __repr__(self): return('%s:%d' % ( self.name, self.type )) # fuzzy compare or two items def __cmp__(self, that): this = string.lower(str(self)) that = string.lower(that) if string.find(this, that) >= 0: return(0) return(cmp(this, that)) def showtype(self): if self.type == UNKNOWN: return('UNKNOWN') if self.type == HOME: return('HOME') if self.type == WORK: return('WORK') if self.type == FAX: return('FAX') if self.type == CELL: return('CELLULAR') class phonedb: def __init__(self, dbname = 'c:\phonedata'): self.dbname = dbname; self.shelve = shelve.open(self.dbname); def __del__(self): self.shelve.close() self.shelve = None def add(self, name, number, type): e = phoneentry(name, number, type) self.shelve[str(e)] = e def lookup(self, string): list = [] for key in self.shelve.keys(): e = self.shelve[key] if cmp(e, string) == 0: list.append(e) return(list) -------------- next part -------------- #!c:\python\python.exe import sys from phone import * #Start of Program b = 1 foo = phonedb() while b != 3: print b print "Welcome to the Phone Database!" print "---written by Chris Lavezza---" print "Please make a selection by typing one of the following options." print print "If you want to add an Employee type the #: 1" print print"For a complete listing of Employees type the #: 2" print print "To see the 'test page' and exit the Database type the #: 3" b = input(':') if b == 1: print "Enter the Employee's full name:" n = raw_input(':') print "Enter the Employee's full telephone number:" p = raw_input(':') print "Enter the telephone number type: (0 = UNKNOWN, 1 = HOME, 2 = WORK, 3 = FAX, 4 = CELL)" t = raw_input(':') if t == '0': foo.add(n, p, UNKNOWN) if t == '1': foo.add(n, p, "HOME") if t == '2': foo.add(n, p, "WORK") if t == '3': foo.add(n, p, "FAX") if t == '4': foo.add(n, p, "CELL") print t if b == 2: print (list) # if not being loaded as a module, run a small test if __name__ == '__main__': foo = phonedb() foo.add('Sean Reifschneider', '970-555-1111', HOME) foo.add('Sean Reifschneider', '970-555-2222', CELL) foo.add('Evelyn Mitchell', '970-555-1111', HOME) foo.add('Chad Varner','970-123-4567',HOME) print 'First lookup:' for entry in foo.lookup('reifsch'): print '%-40s %s (%s)' % ( entry.name, entry.number, entry.showtype() ) print print 'Second lookup:' for entry in foo.lookup('e'): print '%-40s %s (%s)' % ( entry.name, entry.number, entry.showtype() ) From python at bernardlebel.com Wed Aug 18 01:39:43 2004 From: python at bernardlebel.com (Bernard Lebel) Date: Wed Aug 18 00:37:29 2004 Subject: [Tutor] Please comment my -first- script Message-ID: <000e01c484b3$7c174a10$2901a8c0@atyss> Hi everyone, All right, I finally managed to write my first full-fledge Python script!! It's not an entirely new idea, because it is actually a rewrite of a JScript script I did several months. That said, the JScript version was 858 lines longs, while the Python version is 192 lines. Granted, the JScript version was not that optimized and the perfect aesthetic example, but it worked. I must admit that Python has a lot of funcitonalities that JScript doesn't have, and that are making life such eaiser. Anyway, what the attaced file does is that it will analyze a directory tree to find sequences of files, and analyse individual sequences to see if files are missing or if files are incomplete (under 1k). Since I work in 3D animation, this is very useful to summarize the results of a rendering for a given shot. The user gives the sequence information, the first file and the last file, and the script does the rest. Sorry about the French strings, but the script is intended for the employees at my company (wich are French). I'd like to have some advice if some things could have been done better. File was renamed to txt for safer internet transfer. Thanks in advance for your time. Bernard -------------- next part -------------- """ Check_Sequence.py Par Bernard Lebel Directeur technique, rendering Action Synth?se, Marseille (France) Ao?t 2004 Check_Sequence.py est la version pour l'interpr?teur Python. Il doit ?tre ex?cut? avec Python IDLE, PythonWin, ou tout autre interpr?teur natif Python. La version Check_Sequence.pys est la version pour XSI, et doit ?tre ex?cut?e dans le Script Editor de XSI. Description: Check_sequence d?tecter les frames manquants dans toutes les passes rendues pour le plan sp?cifi?, et d?tecte aussi les drop-frames (frames pesant moins de 1k. Pour l'instant, tous les dossiers du plan sp?cif? sont ?valu?s. Une version future permettra d'?tre plus s?lectif. Utilisation: Lancer l'interpr?teur Python (en l'occurence, PythonWin). Faire Ctrl+I (File > Import) S?lectionner le script, cliquer OK. Entrer le num?ro de s?quence avec les z?ros qui pr?c?dent, mais sans le S. Entrer le num?ro de plan avec les z?ros qui pr?c?dent, mais sans le P. Entrer le premier frame attendu, sans les z?ros qui pr?c?dent. Entrer le dernier frame attendu, sans les z?ros qui pr?c?dent. Lire le rapport. """ # ----------------------------------------------------- # Import block import os import string # ----------------------------------------------------- # Instantiation block s = string # ----------------------------------------------------- print ' [[ CHECK SEQUENCE ]] ' print '' print ">>>>> IMPORTANT:" print "1. Assurez-vous d'avoir des dossiers propres avant d'executer le script." print "2. N'entrez pas le S et le P dans les numeros de sequence et de plan." print '' sSequence = raw_input( 'Numero de sequence (sans le S): ' ) sPlan = raw_input( 'Numero de plan (sans le P): ' ) iStart = int( raw_input( 'Premier frame: ' ) ) iEnd = int( raw_input( 'Dernier frame: ' ) ) iCount = iEnd - iStart + 1 # Define root search path sRoot = 'C:\\FRAME2\\SEQUENCES\\' + 'S' + sSequence + '\\' + 'P' + sPlan #sRoot = '\\\\Sata-NAS1500\\FRAME2\\SEQUENCES\\' + 'S' + sSequence + '\\' + 'P' + sPlan if os.path.exists( sRoot ) == False: print 'Pas de plan pour le dossier specifie.' else: print '' print '>>>>> INFORMATIONS SUR LE PLAN:' print '1. Dossier du plan: ' + sRoot print '2. Premier frame: ' + str( iStart ) print '3. Dernier frame: ' + str( iEnd ) print '5. Nombre de frames attendus: ' + str( iCount ) print '' print '>>>>> DEBUT DE VERIFICATION DU PLAN' print '' # Iterate through root folder to collected folders for sDirPath, oDirNames, oFiles in os.walk( sRoot, True, None ): # Check if directory contains files if len( oFiles ) > 0: print '_____ Verification de >>>>>>>>>>>> ' + sDirPath # Create empty list to store sequence names aNames = [] # Get name of first file oFirstFile = oFiles[0] # Get first part of the name aFirstName = s.split( oFirstFile, '.' ) # Add first name to list aNames.append( aFirstName[0] ) # Get file extention sExt = '' if len( aFirstName ) == 1: sExt = '' elif len( aFirstName ) == 2: sExt = aFirstName[1] else: sExt = aFirstName[2] # DEBUG #print '>>>>> First file in aNames: ' + str(aNames[0]) # Iterate through files of current directory for oFile in oFiles: # Split file name into elements aName = s.split( oFile, '.' ) # Get first element of file name (sequence name) sName = str(aName[0]) # Check if sequence name is in list of sequence names if sName in aNames: pass else: # Sequence name is not in list, add it aNames.append( sName ) # Iterate through list of sequence names in current directory for sSeqName in aNames: # DEBUG #print 'sSeqName: ' + sSeqName ) # Loop over virtual full sequence to test if file exists for i in range( iCount ): iFrame = i + iStart # Define default file name sPad = str( iFrame ) sFile = sSeqName + '.' + sPad + '.' + sExt #sPath = sDirPath + '\\' + sFile # Loop 5 times with each time an additional leading 0 to the padding to check if the file exists for sZero in range(5): # Compose file path sPath = sDirPath + '\\' + sSeqName + '.' + sPad + '.' + sExt #print 'Trying new pad: ' + sPad # Check if file path is valid if os.path.exists( sPath ) == False: # If file path not valid, add a zero to sPad sPad = s.zfill( sPad, len(sPad) + 1 ) else: # If file path valid, check file size and break the loop for this file # Collect file statistics oStat = os.stat( sPath ) # Check if file size is below 1024 bytes if int( oStat[6] ) < 1024: print ' Missed: ' + sPath else: pass break # The list of possibles paddings came to exhaustion, and a valid file could not be found. else: print ' Absent: ' + sFile print '' # Script completed! print '' print '>>>>> FIN DE VERIFICATION DU PLAN' From dyoo at hkn.eecs.berkeley.edu Wed Aug 18 01:25:28 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Aug 18 01:25:33 2004 Subject: [Tutor] Need Help with Source Code [please tell us what you want us to look at] In-Reply-To: Message-ID: On Tue, 17 Aug 2004, christopher lavezza wrote: > could someone take the attachments and run the source code in python and > see where I made the mistakes. I am trying to get the source code into > an telephone database using python. [Long rant ahead; my apologies!] Hi Chris, Again, please try to explain why you think the program is broken. It is not helpful enough to say "It's broken." and ask us to do a global search throughout the program. What problems do you want us to look at? Are you getting a particular error? Is there a problem with syntax? Or does the program behave in a way that you don't expect? These are the kinds of things we need to know before we dig through code: otherwise, there's no motivating reason that drives our search. In previous correspondence on the Tutor list, folks have asked for more specific information to your questions. If you look at: http://mail.python.org/pipermail/tutor/2004-June/029902.html http://mail.python.org/pipermail/tutor/2004-June/029899.html http://mail.python.org/pipermail/tutor/2004-August/031241.html all responses have a particular pattern. Each asks the equivalent of: "Show us an error message." That's not just because we like seeing error messages, but because it's a crucial part of the problem-solving process. Please try not to treat us like a magical black box that takes in buggy code and churns out unbuggy code. It's very demotivating for me personally; it reminds me too much of what's worst about school and the question->answer mentality that goes with it. We would rather collaborate together with you. The guide, "How To Ask Questions the Smart Way": http://www.catb.org/~esr/faqs/smart-questions.html explains, in more detail, ways to improve your questions so that people will be happy to answer them. Good luck to you. From kent_johnson at skillsoft.com Wed Aug 18 04:43:35 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Wed Aug 18 04:44:15 2004 Subject: [Tutor] Please comment my -first- script In-Reply-To: <000e01c484b3$7c174a10$2901a8c0@atyss> References: <000e01c484b3$7c174a10$2901a8c0@atyss> Message-ID: <6.1.0.6.0.20040817214729.02a4e558@mail4.skillsoft.com> Bernard, This is good work for a first program! I have some small suggestions, nothing major. Most of them are matters of style and idiom, you can choose what you prefer. - You might want to break up the program by using some functions. This will make it more readable and easier to maintain. (I find it easier to write that way, too, but you've already done that :-) For example the section that creates aNames could be a separate function, part of the loop on sSeqName could be broken out. - This import import string s = string can be written as import string as s - split and zfill are instance methods on string objects (as well as functions in the string module), so instead of s.split( oFirstFile, '.' ) you can write oFirstFile.split('.') and similarly for zfill. - Raw strings are handy for Windows path names, instead of 'C:\\FRAME2\\SEQUENCES\\' you can write r'C:\FRAME2\SEQUENCES\' - os.path.join() is a portable way to create paths - though in this case it probably doesn't matter. - Instead of if os.path.exists( sRoot ) == False: I would write if not os.path.exists( sRoot ): - Instead of elif len( aFirstName ) == 2: sExt = aFirstName[1] else: sExt = aFirstName[2] you might be able to use else: sExt = aFirstName[-1] - You might want to use a dict or a set instead of a list for aNames. Sets are good for keeping a collection without duplicates. For example: >>> import sets >>> s=sets.Set() >>> s.add(1) >>> s.add(1) >>> s.add(3) >>> s Set([1, 3]) >>> for i in s: ... print i ... 1 3 Before Python 2.3 dicts were used for this purpose. You have to assign a dummy value to the dict: >>> d={} >>> d[1] = 1 >>> d[1] = 1 >>> d[3] = 3 >>> for i in d.keys(): ... print i ... 1 3 - This loop for i in range( iCount ): iFrame = i + iStart could be written like this: for iFrame in range( iStart, iEnd+1): - You could use os.path.getsize() to find the file size. - Is running time a concern? I don't know how many files you are checking; if it is enough that you notice how long it takes to run, you might want to try a different way of checking the sequences. You program goes through all the files in the directory twice - once to compile aNames, again to check the sequence numbers. When you check the sequence, you can make up to five calls to os.path.exists(). A different way to do this would be to keep a list of the sequence numbers you find, as you iterate the files the first time. If every file is a sequence file with a name in the form sName.00xx.sExt, you could build a dict that maps from sName to a list of integers found. The loop to build the dict would look something like this: aNames = {} for oFile in oFiles: sName, sSeq, sExt = oFile.split('.') aNames.setdefault(sName, []).append(sSeq) The loop to test for missing sequences would be something like this: for sName, sSeqList in aNames.items(): for iFrame in range(iStart, iEnd + 1): # Search in sSeqList for iFrame using a similar loop to what you have now with sZero This only iterates the file list once and it moves the sequence check from a filesystem check to looking at a list. But you have working code so I wouldn't change it unless you have a lot of files! I'm not even certain my method will be faster - the filesystem may have cached all the directory information. Anyway I hope this is helpful. These are all very minor points - I'm not sure any of them are important enough to change working code! Kent At 12:39 AM 8/18/2004 +0100, Bernard Lebel wrote: >Hi everyone, > >All right, I finally managed to write my first full-fledge Python script!! >It's not an entirely new idea, because it is actually a rewrite of a JScript >script I did several months. That said, the JScript version was 858 lines >longs, while the Python version is 192 lines. Granted, the JScript version >was not that optimized and the perfect aesthetic example, but it worked. I >must admit that Python has a lot of funcitonalities that JScript doesn't >have, and that are making life such eaiser. > >Anyway, what the attaced file does is that it will analyze a directory tree >to find sequences of files, and analyse individual sequences to see if files >are missing or if files are incomplete (under 1k). Since I work in 3D >animation, this is very useful to summarize the results of a rendering for a >given shot. The user gives the sequence information, the first file and the >last file, and the script does the rest. >Sorry about the French strings, but the script is intended for the employees >at my company (wich are French). > >I'd like to have some advice if some things could have been done better. >File was renamed to txt for safer internet transfer. > > >Thanks in advance for your time. > >Bernard > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From kent_johnson at skillsoft.com Wed Aug 18 04:49:33 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Wed Aug 18 04:49:37 2004 Subject: [Tutor] Need Help with Source Code In-Reply-To: References: Message-ID: <6.1.0.6.0.20040817224554.0299c238@mail4.skillsoft.com> Chris, Can you tell us what kind of problems you are having? Kent At 05:00 PM 8/17/2004 -0500, christopher lavezza wrote: >X-MIME-Autoconverted: from 8bit to quoted-printable by > smtp-vbr7.xs4all.nl id i7HM0TNX033428 >Content-Type: text/plain; > format=flowed > >could someone take the attachments and run the source code in python and >see where I made the mistakes. I am trying to get the source code into an >telephone database using python. > > >thank you > > >Chris Lavezza > >_________________________________________________________________ >Don't just search. Find. Check out the new MSN Search! >http://search.msn.click-url.com/go/onm00200636ave/direct/01/ > > > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From marilyn at deliberate.com Wed Aug 18 04:53:01 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Wed Aug 18 04:53:05 2004 Subject: [Tutor] Python and sockets Message-ID: For compare and contrast, here's my open_socket method. Well, I'm still developing on it but I think it might be pretty well-behaved by now. I talk directly to _socket and skip the socket class layer. I'm setting up to be a pop email client here. I also skip the poplib layer of stuff. Those libraries introduced some inefficiencies and obscurations for my particular task. However, my code borrows heavily from those libraries. In fact, studying the code for any of the libraries that work through a socket can be quite instructive: telnet, poplib, socket, ... what else? Hope it helps, Marilyn Davis import _socket def open_socket(self, port = 110): if log.level & log.pop: log.it("Host = " + self.host + " port = " + str(port)) possibles = _socket.getaddrinfo(self.host, port, 0, _socket.SOCK_STREAM) for res in possibles: af, socktype, proto, canonname, sa = res try: if log.level & log.verbose: log.it("Trying (" + str(af) + ', ' + str(socktype) + ', ' + str(proto) + ')') self.remote = _socket.socket(af, socktype, proto) if log.level & log.verbose: log.it("Connecting to " + str(sa)) self.remote.connect(sa) except _socket.error, msg: if log.level & log.verbose: log.it("Failed , _socket.error: " + str(msg) ) if self.remote: if log.level & log.verbose: log.it("Couldn't connect to " + str(sa) + ". Closing.") self.remote.close() self.remote = None continue break if not self.remote: self.host_down("Could not open a socket to host = " + self.host + " port = " + str(port)) welcome = self.remote.recv(RESPONSE_BLOCK) if log.level & log.verbose: log.it("Welcome: " + welcome) From s4046441 at student.uq.edu.au Wed Aug 18 05:35:35 2004 From: s4046441 at student.uq.edu.au (Ms Soo Chong) Date: Wed Aug 18 05:35:41 2004 Subject: [Tutor] How do get results shown in a table Message-ID: <111f34113905.113905111f34@uq.edu.au> Hi all, Anyone can guide me along with this: Python 2.2.1 (#1, Aug 30 2002, 12:15:30) [GCC 3.2 20020822 (Red Hat Linux Rawhide 3.2-4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import pg >>> db = pg.connect("moncdata") >>> result = db.query("""SELECT project, blame, date_string, condition from shot_descriptions where shot_number = 8000""") >>> list_of_result = result.getresult() >>> list_of_result [('Hot inlet Scramjet testing', 'AK,MF,TM(optics)', '4/07/03', None)] >>> list_of_result = result.dictresult() >>> list_of_result [{'project': 'Hot inlet Scramjet testing', 'blame': 'AK,MF,TM(optics)', 'condition': None, 'date_string': '4/07/03'}] I am trying to get the list_of_result shown in a table using inserttable but failed. Anyone one can help? Thank you in advance. Cheers, Shufen From guillermo.fernandez at epfl.ch Wed Aug 18 07:28:42 2004 From: guillermo.fernandez at epfl.ch (Guillermo Fernandez Castellanos) Date: Wed Aug 18 07:28:21 2004 Subject: [Tutor] Need Help with Source Code Message-ID: <4122E90A.1040203@epfl.ch> Hi, > could someone take the attachments and run the source code in python > and see > where I made the mistakes. I am trying to get the source code into an > telephone database using python. I runned your code, and tryed to insert a new user on your database: C:\Documents and Settings\Administrator\Desktop>python test3.py If you want to add an Employee type the #: 1 For a complete listing of Employees type the #: 2 To see the 'test page' and exit the Database type the #: 3 :1 Enter the Employee's full name: :guille Enter the Employee's full telephone number: :00210410343 Enter the telephone number type: (0 = UNKNOWN, 1 = HOME, 2 = WORK, 3 = FAX, 4 = CELL) :1 Here comes what interest us: Traceback (most recent call last): File "test3.py", line 33, in ? foo.add(n, p, "HOME") File "C:\Documents and Settings\Administrator\Desktop\phone.py", line 52, in a dd self.shelve[str(e)] = e File "C:\Documents and Settings\Administrator\Desktop\phone.py", line 23, in _ _repr__ return('%s:%d' % ( self.name, self.type )) TypeError: int argument required If you have a look at the error message, it says: File "C:\Documents and Settings\Administrator\Desktop\phone.py", line 23, in _ _repr__ return('%s:%d' % ( self.name, self.type )) TypeError: int argument required If you have a look at your code, line 23 in phone.py: # create string representation def __repr__(self): return('%s:%d' % ( self.name, self.type )) That means there is a problem with the integer argument of self.type, or sayd with other words, that your integer is, well... not an integer :-) Try to find out why, and next time give us directly an error message, will make life easier for everyone :-) Oh... and try also to deal with the random answer bug. Each time you give a random or empty answer, it exits with : To see the 'test page' and exit the Database type the #: 3 : aqadasa or empty line Traceback (most recent call last): File "test3.py", line 21, in ? b = input(':') File "", line 0 ^ SyntaxError: unexpected EOF while parsing or: NameError: name 'aqadasa' is not defined The doc says for "input" among other things: "Consider using the raw_input() function for general input from users." Regards, Guille From s4046441 at student.uq.edu.au Wed Aug 18 08:37:16 2004 From: s4046441 at student.uq.edu.au (Ms Soo Chong) Date: Wed Aug 18 08:37:24 2004 Subject: [Tutor] How to generate a form using cgi Message-ID: <133e4013541e.13541e133e40@uq.edu.au> Hi, Sorry is me again... Can anyone show me a simple example of generating a form using CGI module? Thank you. I got quite confused with this: def main(): form = cgi.FieldStorage() main() Where should I type in the HTML code that generate the form and text box? http://www.python.org/doc/essays/ppt/sd99east/sld041.htm This site shows a typical CGI script. Is this an example of a form? I tried to type in the same stuffs and tried to generate but I got error message. Can someone tell me the reason behind? Thank you. Cheers, Shufen From alan.gauld at blueyonder.co.uk Wed Aug 18 09:21:11 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Aug 18 09:21:05 2004 Subject: [Tutor] My first python program! References: <000c01c48490$d6dd4940$30e57218@basp.phub.net.cable.rogers.com><305be8820408171434418557f2@mail.gmail.com><000c01c484a3$5d505d20$30e57218@basp.phub.net.cable.rogers.com> <000701c484a5$520a6620$30e57218@basp.phub.net.cable.rogers.com> Message-ID: <006701c484f3$f082f490$6401a8c0@xp> > Ok here is something I can't figure out I put a define at the top of the > program called tries = 5 > > I need to make this part of the program count down from 5 every time they > get a guess wrong. How do I do that? > > def game2(): > a = randrange(1, 10) > guess = int(raw_input("Pick a number from 1 to 10, You only get 5 tries!: > \r\n") ) > while guess != a and tries > 0: tries = tries - 1 Boolean operators allow you to combine tests. Take a look at the Raw Materials and Branching topics in my tutorial for more about Boolean values and expressions. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/ From alan.gauld at blueyonder.co.uk Wed Aug 18 09:29:37 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Aug 18 09:29:32 2004 Subject: [Tutor] Please comment my -first- script References: <000e01c484b3$7c174a10$2901a8c0@atyss> Message-ID: <007401c484f5$1e20b350$6401a8c0@xp> > I'd like to have some advice if some things could have been done better. > File was renamed to txt for safer internet transfer. Good idea on the rensame. it means it opens in notepad instead of executing when I double click the attachment. I like it! :-) You dopn't need the s= string line, you can just do: import string as s However I don't think you need the string module at all, you can use the builtin string methods: st = 2a string" words = st.split() etc. Also the filename manipulation can be done with a python module called os.path. It has functions for splitting and joining paths, filenames, checking modification dates etc... Not to mention the path.walk() function for traversing folders. HTH, Alan G. From alan.gauld at blueyonder.co.uk Wed Aug 18 09:55:16 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Aug 18 09:55:14 2004 Subject: [Tutor] Comma at the end of a print command References: <96.124a393c.2e50d1fa@aol.com> Message-ID: <008601c484f8$b4e21dd0$6401a8c0@xp> > > model = msvcrt.getch() > > if model == '1': > > print model(*) > > model = msvcrt.getch() ##to get the next number > > This is most likely to bring back another 1 or a null character > because the time between detecting the 1 and reading getch again > is going to be tiny. You will need to loop to detect the user input. > Using getch() is much more complex than using raw_input. > > I've found that using msvcrt.getch() again merely forces the program to wait > until the next button pushed and processing it. I finally got around to playing with getch() You are absolutely right. I'm sure it didn't used to do that but maybe my memory is playing tricks on me. It certainly makes getch() much easier to use! On a related note the curses library seems to have had a major overhaul and (to an old curses programmer like me) is now really complex with methods and objects scattered all over various modules. Using getch() under curses has now become much more difficult. I will need to rewrite my event-handling tutor topic to reflect this - bummer!! When did this happen? And where have the handy wXXX methods all gone? :-( Alan G. From alan.gauld at blueyonder.co.uk Wed Aug 18 10:06:02 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Aug 18 10:05:56 2004 Subject: [Tutor] Comma at the end of a print command References: <96.124a393c.2e50d1fa@aol.com> Message-ID: <009301c484fa$34809930$6401a8c0@xp> Further to my last message, I've just found the curses tutorial. I've also checked my old Python curses code. Not so big a change, just my memory acting up. I still do most of my curses stuff in raw C and had fdorgotten how much Python tries to wrap curses functions as methods of the window objects. But it does mean that getch works diffrently to how I thought it worked! (ON both windows and curses) So thanks to DragonFire for pointing that out and starting me on this trail of investigation. Could have led to some embarrassing emails from disgruntled Linux users of my tutor! :-) Alan G. From kent_johnson at skillsoft.com Wed Aug 18 12:57:04 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Wed Aug 18 12:57:08 2004 Subject: [Tutor] How to generate a form using cgi In-Reply-To: <133e4013541e.13541e133e40@uq.edu.au> References: <133e4013541e.13541e133e40@uq.edu.au> Message-ID: <6.1.0.6.0.20040818065507.028fafa8@mail4.skillsoft.com> This page has a good example: http://www.devshed.com/c/a/Python/Writing-CGI-Programs-in-Python/5/ At 04:37 PM 8/18/2004 +1000, Ms Soo Chong wrote: >Hi, > >Sorry is me again... > >Can anyone show me a simple example of generating a >form using CGI module? Thank you. > >I got quite confused with this: > >def main(): > form = cgi.FieldStorage() >main() > >Where should I type in the HTML code that generate the >form and text box? > >http://www.python.org/doc/essays/ppt/sd99east/sld041.htm >This site shows a typical CGI script. Is this an >example of a form? I tried to type in the same >stuffs and tried to generate but I got error >message. Can someone tell me the reason behind? >Thank you. > >Cheers, >Shufen > > > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From master_knight at fastmail.fm Wed Aug 18 14:01:54 2004 From: master_knight at fastmail.fm (Ashkan Aliabadi) Date: Wed Aug 18 14:01:57 2004 Subject: [Tutor] Proxy Message-ID: <1092830514.22837.202564483@webmail.messagingengine.com> Hi folks!! Our university doesn't have wget installed on UNIX systems, so as a good programming practice, I managed to write it myself. As you know, it's quite simple, all it needs is a call to urllib.urlretrieve(urladdress). I added some featuers indeed, but there are two things I'm stuck in! First, we have proxy servers here, and I don't know how to transfer data through them ?!! How can i make my prog to transfer data through proxy servers ?!!!! As my prog works all right with direct internet access, but when there are proxies in between it's a real mess. Secondly, how on Earth can I make it work in the background? I though a simple call to thread.start_new_thread(function,args) would do the trick (as it's the case when you are running the prog in the interpreter line by line ) but when I'm about to run it from command line, it seems as my program finishes before the new thread catches the file from the internet, if you know what I mean ;D. Here is the code: imoprt thread, urllib thread.start_new_thread(urllib.urlretrieve,('http://www.python.org',)) #Not enough time to download the file, the program finishes before the th read is done!!! At least thats what I think. I'd be greatful if you folks could help have a nice day, Ashkan(master_knight@fastmail.fm) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040818/d33aa155/attachment.html From python at pointcontrol.com Wed Aug 18 17:46:59 2004 From: python at pointcontrol.com (python@pointcontrol.com) Date: Wed Aug 18 17:47:04 2004 Subject: [Tutor] Attempting to install Boa Constructor Message-ID: <50585.68.159.148.164.1092844019.squirrel@www.pointcontrol.com> Greetings, all. I am new to Python, and am investigating it on the advice of a friend. He does Python development on a Windows box. I'd like to do it on a laptop I have running Fedora. (It was running Redhat 8, but I was getting so many dependency issues trying to get Boa Constructor loaded, I wiped the laptop and started over with Fedora.) I've installed Python 2.3.4 and confirmed that it's what is launching. I've downloaded and run the wxPython 2.4.2.4 rpm. And I've unzipped the boa-constructor-0.2.3.src.zip file. My Python is installed in /usr/local/lib/python2.3, so when the boa-constructor zip file created a directory called boa-constructor-0.2.3, I put that in the python2.3 directory. That makes the path to boa.py /usr/local/lib/python2.3/boa-constructor-0.2.3/boa.py But when I try to get it to run, like this: [barry@dhcppc3 python2.3]$ python /usr/local/lib/python2.3/boa-constructor-0.2.3/boa.py I get: python: can't open file '/usr/local/lib/python2.3/boa-constructor-0.2.3/boa.py' Any ideas what I should be doing differently? All software installs were done by root. This left the permissions for the boa-constrctor files as read/write/no-execute for everyone other than root. Do the files need to be set to be executable? Thanks for any insights you can provide. -- b.r.t. From cmeesters at ucdavis.edu Wed Aug 18 18:43:32 2004 From: cmeesters at ucdavis.edu (Christian Meesters) Date: Wed Aug 18 18:43:58 2004 Subject: [Tutor] redirecting module output Message-ID: <200408181643.i7IGhW6s022048@cucujus.ucdavis.edu> From: cmeesters@ucdavis.edu Subject: redirecting module output Date: August 18, 2004 8:06:22 AM PDT To: tutor@python.org Hi Reading this list is really great. Most contributions are 'just' nice and helpful - in contrast to other forums ... That said, I'd like to address a questions for which I couldn't find a solution, yet. My wish is to embed a program, which at first gave all its output on the shell (stdout), into a GUI (using wxPython, BTW). Core of the original program was a module with a single class (class and module called 'DNA'). The intention is partly to simplify my work, but actually just to train GUI programming, which is new to me. Ok, before I come to the problem, first on how the head of the main script (the GUI part) looks like: -------- import sys import os import wx # import own modules from the 'src' directory import src.DNA import src.NCBIstrip class FindFrame(wx.Frame,src.DNA.DNA): def __init__(self,parent,id,title): wx.Frame.__init__(self,None,-1,"FindSequence") p = wx.Panel(self,-1) # code ... code ... code ... # and later a TxtCtrl-field is initialized: TextField = wx.TextCtrl(p,-1,"Nothing selected, yet.\n\n",size=(500,200),style=wx.TE_MULTILINE) self.TextField = TextField sizer.Add(TextField,(4,1),(1,3),flag=wx.EXPAND) # even more code ... -------- With other words: Nothing but standard. (Or?) Now to the problem: Functions of the 'DNA' class (within the DNA module) printed their output on the shell (stdout). Redirecting stdout to 'TextField' works, but causes a delay: The output is not printed until the process producing it is finished. In the original program I let functions within DNA print something on the shell to indicate that the process is still running and which path of processing is followed. Output as text seems the most sensitive way to accomplish both goals. But how is it possible to redirect the output from the imported DNA-class to 'TextField'? Perhaps something with the conventional TextField.AppendText("anything") altered? How do I have to alter print statements within the DNA class to accomplish this? Or how could I use an indermediate buffer? Well, I hope I made myself clear. Describing this problem wasn't easy ... Thank you very much in advance, Christian From dyoo at hkn.eecs.berkeley.edu Wed Aug 18 19:25:09 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Aug 18 19:26:04 2004 Subject: [Tutor] Need Help with Source Code [please tell us what you want us to look at] (fwd) Message-ID: [Forwarding to tutor@python.org. Can someone else try to help Chris? Thanks.] ---------- Forwarded message ---------- Date: Wed, 18 Aug 2004 12:10:32 -0500 From: christopher lavezza To: dyoo@hkn.eecs.berkeley.edu Subject: Re: [Tutor] Need Help with Source Code [please tell us what you want us to look at] I am getting an error message when I run the script. >From: Danny Yoo >To: christopher lavezza >CC: tutor@python.org >Subject: Re: [Tutor] Need Help with Source Code [please tell us what you >want us to look at] >Date: Tue, 17 Aug 2004 16:25:28 -0700 (PDT) > > > >On Tue, 17 Aug 2004, christopher lavezza wrote: > > > could someone take the attachments and run the source code in python and > > see where I made the mistakes. I am trying to get the source code into > > an telephone database using python. > > >[Long rant ahead; my apologies!] > > >Hi Chris, > >Again, please try to explain why you think the program is broken. It is >not helpful enough to say "It's broken." and ask us to do a global search >throughout the program. > > >What problems do you want us to look at? Are you getting a particular >error? Is there a problem with syntax? Or does the program behave in a >way that you don't expect? These are the kinds of things we need to know >before we dig through code: otherwise, there's no motivating reason that >drives our search. > > >In previous correspondence on the Tutor list, folks have asked for more >specific information to your questions. If you look at: > > http://mail.python.org/pipermail/tutor/2004-June/029902.html > http://mail.python.org/pipermail/tutor/2004-June/029899.html > http://mail.python.org/pipermail/tutor/2004-August/031241.html > >all responses have a particular pattern. Each asks the equivalent of: >"Show us an error message." That's not just because we like seeing error >messages, but because it's a crucial part of the problem-solving process. > > >Please try not to treat us like a magical black box that takes in buggy >code and churns out unbuggy code. It's very demotivating for me >personally; it reminds me too much of what's worst about school and the >question->answer mentality that goes with it. > >We would rather collaborate together with you. > > > >The guide, "How To Ask Questions the Smart Way": > > http://www.catb.org/~esr/faqs/smart-questions.html > >explains, in more detail, ways to improve your questions so that people >will be happy to answer them. > > >Good luck to you. > _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today - it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From pythonTutor at venix.com Wed Aug 18 19:49:31 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Wed Aug 18 19:50:45 2004 Subject: [Tutor] Need Help with Source Code [please tell us what you want us to look at] (fwd) In-Reply-To: References: Message-ID: <1092851370.2092.31.camel@laptop.venix.com> What is the error message? If it is coming from Python there should be a traceback with line numbers. Show us the lines from the source that match the traceback. You need to provide enough information so that we can help you! > ---------- Forwarded message ---------- > Date: Wed, 18 Aug 2004 12:10:32 -0500 > From: christopher lavezza > To: dyoo@hkn.eecs.berkeley.edu > Subject: Re: [Tutor] Need Help with Source Code [please tell us what you > want us to look at] > > I am getting an error message when I run the script. > > > >From: Danny Yoo > >To: christopher lavezza > >CC: tutor@python.org > >Subject: Re: [Tutor] Need Help with Source Code [please tell us what you > >want us to look at] > >Date: Tue, 17 Aug 2004 16:25:28 -0700 (PDT) > > > > > > > >On Tue, 17 Aug 2004, christopher lavezza wrote: > > > > > could someone take the attachments and run the source code in python and > > > see where I made the mistakes. I am trying to get the source code into > > > an telephone database using python. > > > > > >[Long rant ahead; my apologies!] > > > > > >Hi Chris, > > > >Again, please try to explain why you think the program is broken. It is > >not helpful enough to say "It's broken." and ask us to do a global search > >throughout the program. > > > > > >What problems do you want us to look at? Are you getting a particular > >error? Is there a problem with syntax? Or does the program behave in a > >way that you don't expect? These are the kinds of things we need to know > >before we dig through code: otherwise, there's no motivating reason that > >drives our search. > > > > > >In previous correspondence on the Tutor list, folks have asked for more > >specific information to your questions. If you look at: > > > > http://mail.python.org/pipermail/tutor/2004-June/029902.html > > http://mail.python.org/pipermail/tutor/2004-June/029899.html > > http://mail.python.org/pipermail/tutor/2004-August/031241.html > > > >all responses have a particular pattern. Each asks the equivalent of: > >"Show us an error message." That's not just because we like seeing error > >messages, but because it's a crucial part of the problem-solving process. > > > > > >Please try not to treat us like a magical black box that takes in buggy > >code and churns out unbuggy code. It's very demotivating for me > >personally; it reminds me too much of what's worst about school and the > >question->answer mentality that goes with it. > > > >We would rather collaborate together with you. > > > > > > > >The guide, "How To Ask Questions the Smart Way": > > > > http://www.catb.org/~esr/faqs/smart-questions.html > > > >explains, in more detail, ways to improve your questions so that people > >will be happy to answer them. > > > > > >Good luck to you. > > > > _________________________________________________________________ > Express yourself instantly with MSN Messenger! Download today - it's FREE! > http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ > > > > _______________________________________________ > 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 Wed Aug 18 19:51:38 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Aug 18 19:51:43 2004 Subject: [Tutor] Proxy In-Reply-To: <1092830514.22837.202564483@webmail.messagingengine.com> Message-ID: On Wed, 18 Aug 2004, Ashkan Aliabadi wrote: > Our university doesn't have wget installed on UNIX systems, so as a good > programming practice, I managed to write it myself. As you know, it's > quite simple, all it needs is a call to urllib.urlretrieve(urladdress). > I added some featuers indeed, but there are two things I'm stuck in! > First, we have proxy servers here, and I don't know how to transfer data > through them ?!! How can i make my prog to transfer data through proxy > servers ?!!!! [text cut] Hi Ashkan, Breathe. *grin* According to the documentation in: http://www.python.org/doc/lib/module-urllib.html you can pass in an additional "proxy" argument to urllib.urlopen(). Can you use urlopen() instead of urlretrieve()? Also, if you set an environmental variable called 'http_proxy', Python should pick that up. > Secondly, how on Earth can I make it work in the background? I though a > simple call to thread.start_new_thread(function,args) would do the trick > (as it's the case when you are running the prog in the interpreter line > by line ) but when I'm about to run it from command line, it seems as my > program finishes before the new thread catches the file from the > internet, if you know what I mean ;D. > imoprt thread, urllib > thread.start_new_thread(urllib.urlretrieve,('http://www.python.org',)) Instead of 'thread', you may want to use the 'threading' module --- it's a higher-level interface for threads. ### import threading, urllib mythread = threading.Thread(target = urllib.urlretrieve, args = ('http://www.python.org/',)) mythread.start() ### You can ask the system to wait for that thread to finish, by using wait(): ### mythread.wait() ### But are you sure that your thread isn't finishing? The main program thread will normally wait for all its child threads to finish, unless those child threads are "daemons". Odd. urllib.urlretrieve() does write out the retrieved file to disk, but uses some wacky name by default. Perhaps urllib.urlretrieve() is writing the file, but not in the place that you're expecting. In fact, on my system, it dumps the file out to '/tmp'! For your purposes of implementing a wget-like utility, it might be better to try passing the desired filename explicitely to urlretrieve() as an additional 'filename' parameter. Best of wishes to you. From dyoo at hkn.eecs.berkeley.edu Wed Aug 18 19:57:46 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Aug 18 19:57:51 2004 Subject: [Tutor] Attempting to install Boa Constructor In-Reply-To: <50585.68.159.148.164.1092844019.squirrel@www.pointcontrol.com> Message-ID: On Wed, 18 Aug 2004 python@pointcontrol.com wrote: > I've downloaded and run the wxPython 2.4.2.4 rpm. And I've unzipped the > boa-constructor-0.2.3.src.zip file. > > My Python is installed in /usr/local/lib/python2.3, so when the > boa-constructor zip file created a directory called boa-constructor-0.2.3, I > put that in the python2.3 directory. That makes the path to boa.py > /usr/local/lib/python2.3/boa-constructor-0.2.3/boa.py Hello! Let's double check something. Can you try: ls -l /usr/local/lib/python2.3/boa-constructor-0.2.3/boa.py just to make sure that file is there? The error message that you're getting: > [barry@dhcppc3 python2.3]$ python /usr/local/lib/python2.3/boa-constructor-0.2.3/boa.py > python: can't open file '/usr/local/lib/python2.3/boa-constructor-0.2.3/boa.py' suggests that Python can't even open that file. It's possible that the file isn't there. *grin* But it's also possible that there might be permission problems, or perhaps it might be a symbolic link to somewhere that doesn't exist? Dunno, but the output from 'ls -l' should help us figure out what's going on. > All software installs were done by root. This left the permissions for > the boa-constrctor files as read/write/no-execute for everyone other > than root. Do the files need to be set to be executable? No, Python files don't have to be executable. What you did should have worked. Let's double check that it's not a permission problem though, so show us the output of the 'ls -l'. Good luck to you! From alan.gauld at blueyonder.co.uk Wed Aug 18 20:28:42 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Aug 18 20:28:29 2004 Subject: [Tutor] Attempting to install Boa Constructor References: <50585.68.159.148.164.1092844019.squirrel@www.pointcontrol.com> Message-ID: <00e301c48551$30b24090$6401a8c0@xp> > I am new to Python, and am investigating it on the advice of a friend. Probably a good idea, although it does depend on what you want to use it for? > I've installed Python 2.3.4 and confirmed that it's what is launching. > > I've downloaded and run the wxPython 2.4.2.4 rpm. And I've unzipped the > boa-constructor-0.2.3.src.zip file. I assume you want to do GUI development since thats BOAs forte, and wxPython is the GUI framework that BOA uses. > But when I try to get it to run, like this: > [barry@dhcppc3 python2.3]$ python > /usr/local/lib/python2.3/boa-constructor-0.2.3/boa.py > > I get: > python: can't open file > '/usr/local/lib/python2.3/boa-constructor-0.2.3/boa.py' Are the permissions set OK? Can you open the same file using vi say? > Do the files need to be set to be executable? Only if you run Boa without calling python directly. > Thanks for any insights you can provide. The biggest insight might be to suggest you start with something simpler like IDLE? Once you know Python as a programming language you can then set about the relatively advanced topic of GUI development. Trying to learn two advanced subjects (Python and wxPython) at the same time might be tricky and learning Python in plain ol' IDLE will be easier than struggling to install BOA. Just a thought, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/ From jfabiani at yolo.com Wed Aug 18 20:40:04 2004 From: jfabiani at yolo.com (John Fabiani) Date: Wed Aug 18 20:40:14 2004 Subject: [Tutor] Attempting to install Boa Constructor In-Reply-To: References: Message-ID: <200408181140.04841.jfabiani@yolo.com> On Wednesday 18 August 2004 10:57, Danny Yoo wrote: > On Wed, 18 Aug 2004 python@pointcontrol.com wrote: > > I've downloaded and run the wxPython 2.4.2.4 rpm. And I've unzipped the > > boa-constructor-0.2.3.src.zip file. > > > > My Python is installed in /usr/local/lib/python2.3, so when the > > boa-constructor zip file created a directory called > > boa-constructor-0.2.3, I put that in the python2.3 directory. That makes > > the path to boa.py /usr/local/lib/python2.3/boa-constructor-0.2.3/boa.py > > Hello! > > > Let's double check something. Can you try: > > ls -l /usr/local/lib/python2.3/boa-constructor-0.2.3/boa.py > > just to make sure that file is there? > > The error message that you're getting: > > [barry@dhcppc3 python2.3]$ python > > /usr/local/lib/python2.3/boa-constructor-0.2.3/boa.py python: can't open > > file '/usr/local/lib/python2.3/boa-constructor-0.2.3/boa.py' > > suggests that Python can't even open that file. > > It's possible that the file isn't there. *grin* But it's also possible > that there might be permission problems, or perhaps it might be a symbolic > link to somewhere that doesn't exist? Dunno, but the output from 'ls -l' > should help us figure out what's going on. > > > All software installs were done by root. This left the permissions for > > the boa-constrctor files as read/write/no-execute for everyone other > > than root. Do the files need to be set to be executable? > > No, Python files don't have to be executable. What you did should have > worked. Let's double check that it's not a permission problem though, so > show us the output of the 'ls -l'. > > > Good luck to you! > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor In fact if I recall correctly BOA should be in site-packages. John From alan.gauld at blueyonder.co.uk Wed Aug 18 20:44:31 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Aug 18 20:44:18 2004 Subject: [Tutor] redirecting module output References: <200408181643.i7IGhW6s022048@cucujus.ucdavis.edu> Message-ID: <00e801c48553$662c8530$6401a8c0@xp> > Ok, before I come to the problem, first on how the head of > the main script (the GUI part) looks like: > -------- > import sys > import os > import wx > # import own modules from the 'src' directory > import src.DNA > import src.NCBIstrip > > class FindFrame(wx.Frame,src.DNA.DNA): Hmm, FindFrame is not a very OO sounding name - its a verb not a noun. Even if its the "Frame used for Finding" rather than an action I'd query the fact it inherits from DNA. Is it really a "kind of" DNA object or does it use a DNA object? Inheritance which is not truly "kind of" can cause many complications later. > Now to the problem: Functions of the 'DNA' class > (within the DNA module) printed their output on > the shell (stdout). Ah but thats a bad design mistake. Functions should return values not print out things. (Unless they are display functions in which case you'd not be using them in a GUI...) Thus you need to refactor your DNA design to separate presentation from processing - this is a fundamental design principle for any kind of reuse. > functions within DNA print something on the shell to > indicate that the process is still running Generally this will be done in a GUI by either setting a timer to update a progress indicator or by posting events if that is possible. EVent handlers should not really have long running loops in them, and if they must then those loops should run in a separate functionin a separate thread. > how is it possible to redirect the output from the > imported DNA-class to 'TextField'? The best way is to refactor your DNA code to avoid having the functions that do the work printing things. If you have a lot of in;line print statements you might consider calling a function to do the display. You can then write a text version and a GUI version of the function and pass the function as a parameter to the processing engine, like this: def processIT(p1,p2,displayIT=displayText): # long process here for n in xrange(10000 * p1): displayIT("Here is a display string") x = (n * n/N ** 0.3)**2 result = x ** p2 displayIT("finished soon") return result def displayText(s): print s def displayGUI(s): # write your GUI code here pass processIT(1000,0.5,displayGUI) > Well, I hope I made myself clear. Describing this problem wasn't easy ... I hope I made my counter proposal clear? There are ways to procede the way you suggest but they are not a good way going forward. refactoring at this stage will be much easier later on IMHO. Alan G. From alan.gauld at blueyonder.co.uk Wed Aug 18 20:49:37 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Aug 18 20:49:24 2004 Subject: [Tutor] Need Help with Source Code [please tell us what you wantus to look at] (fwd) References: Message-ID: <00ed01c48554$1ca8fb40$6401a8c0@xp> > ---------- Forwarded message ---------- > Date: Wed, 18 Aug 2004 12:10:32 -0500 > From: christopher lavezza > To: dyoo@hkn.eecs.berkeley.edu > Subject: Re: [Tutor] Need Help with Source Code [please tell us what you > want us to look at] > > I am getting an error message when I run the script. What Danny, and others, have been trying to say to you is that we need to know exactly what error message. Be specific. Post the actual text of the error. Python error messages may look obscure to a beginner but they are actually very informative and once you get used to them will usually tell you exactly where to look. So do not post the fact you get "an error message" rather post the actual error message. And ideally the code that generated it, if its not too long! Otherwise we are just guessing or else doing your job for you. We are all volunteers on tutor, our time is as precious to us as yours is to you. So do your share of eliminating the obvious and we will try to help. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/ From python at pointcontrol.com Wed Aug 18 21:02:13 2004 From: python at pointcontrol.com (python@pointcontrol.com) Date: Wed Aug 18 21:02:19 2004 Subject: [Tutor] Attempting to install Boa Constructor - User Error Detected In-Reply-To: References: Message-ID: <50953.68.159.148.164.1092855733.squirrel@www.pointcontrol.com> >> I've downloaded and run the wxPython 2.4.2.4 rpm. And I've unzipped >> the boa-constructor-0.2.3.src.zip file. >> >> My Python is installed in /usr/local/lib/python2.3, so when the >> boa-constructor zip file created a directory called >> boa-constructor-0.2.3, I put that in the python2.3 directory. That >> makes the path to boa.py >> /usr/local/lib/python2.3/boa-constructor-0.2.3/boa.py > > Hello! > > > Let's double check something. Can you try: > > ls -l /usr/local/lib/python2.3/boa-constructor-0.2.3/boa.py When this didn't work, I took a second look at the file in the boa-constructor-0.2.3 directory and found that it's not boa.py, but Boa.py. Heh. Now, at least, that problem is solved and I can move on to more interesting ones... Thanks for the insight, and thanks, also, to Alan G for his suggestions. -- b.r.t. From cmeesters at ucdavis.edu Wed Aug 18 21:13:28 2004 From: cmeesters at ucdavis.edu (Christian Meesters) Date: Wed Aug 18 21:13:31 2004 Subject: [Tutor] redirecting module output Message-ID: Hi Alan, Guess you are right. Back to roots ... I will refactor the module the way you propose. And indeed, I understand your suggestions :-). (Although I fear re-writing / refactoring this will not be all too straight forward ...) As to your comment on the "FindFrame" name: The project name is merely "Find" at this stage. So, I will not take any "complaints" about the name here ;-). But reading your comment tells me that you indeed have a point: I should avoid inheriting the DNA class into the GUI itself. This was a rather stupid idea of mine. But you gave me the solution (implicitly). Thanks. You are right: I was more mixing (and therefore abusing) the DNA class into the GUI then using it a sensitive way. Thank you very much, Christian From kent_johnson at skillsoft.com Wed Aug 18 22:23:17 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Wed Aug 18 22:23:18 2004 Subject: [Tutor] redirecting module output In-Reply-To: <200408181643.i7IGhW6s022048@cucujus.ucdavis.edu> References: <200408181643.i7IGhW6s022048@cucujus.ucdavis.edu> Message-ID: <6.1.0.6.0.20040818155844.028f0740@mail4.skillsoft.com> You might rewrite DNA to output to the Python logging system instead of stdout. Then you can configure the log to send the output where you want to. You could write a log handler that puts the output in your window. You could also use a handler that captures output to a file. I have used this approach in a Java program, it's very nice to have both the GUI display and the file. You could use the wxWindows logging system, though this would make your DNA class depend on wxWindows which probably isn't such a good idea. You could use Alan's idea of passing in a log function to break that dependency. Kent At 09:43 AM 8/18/2004 -0700, Christian Meesters wrote: > From: cmeesters@ucdavis.edu > Subject: redirecting module output > Date: August 18, 2004 8:06:22 AM PDT > To: tutor@python.org > >Hi > >Reading this list is really great. Most contributions are 'just' nice and >helpful - in contrast to >other forums ... > >That said, I'd like to address a questions for which I couldn't find a >solution, yet. My wish is to >embed a program, which at first gave all its output on the shell (stdout), >into a GUI (using >wxPython, BTW). Core of the original program was a module with a single >class (class and >module called 'DNA'). The intention is partly to simplify my work, but >actually just to train GUI >programming, which is new to me. > >Ok, before I come to the problem, first on how the head of the main script >(the GUI part) looks >like: >-------- >import sys >import os >import wx ># import own modules from the 'src' directory >import src.DNA >import src.NCBIstrip > >class FindFrame(wx.Frame,src.DNA.DNA): > def __init__(self,parent,id,title): > wx.Frame.__init__(self,None,-1,"FindSequence") > p = wx.Panel(self,-1) > # code ... code ... code ... > # and later a TxtCtrl-field is initialized: > TextField = wx.TextCtrl(p,-1,"Nothing selected, >yet.\n\n",size=(500,200),style=wx.TE_MULTILINE) > self.TextField = TextField > sizer.Add(TextField,(4,1),(1,3),flag=wx.EXPAND) > # even more code ... > >-------- > >With other words: Nothing but standard. (Or?) > >Now to the problem: Functions of the 'DNA' class (within the DNA module) >printed their output >on the shell (stdout). Redirecting stdout to 'TextField' works, but causes >a delay: The output is >not printed until the process producing it is finished. In the original >program I let functions >within DNA print something on the shell to indicate that the process is >still running and which >path of processing is followed. Output as text seems the most sensitive >way to accomplish both >goals. But how is it possible to redirect the output from the imported >DNA-class to 'TextField'? >Perhaps something with the conventional TextField.AppendText("anything") >altered? How do I >have to alter print statements within the DNA class to accomplish this? Or >how could I use an >indermediate buffer? > >Well, I hope I made myself clear. Describing this problem wasn't easy ... > >Thank you very much in advance, >Christian > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From python at bernardlebel.com Thu Aug 19 00:07:45 2004 From: python at bernardlebel.com (Bernard Lebel) Date: Wed Aug 18 23:05:39 2004 Subject: [Tutor] boolean raw_input Message-ID: <004001c4856f$d1790590$2901a8c0@atyss> Hello, Recently I saw on this list a bit of code that used a boolean expression inside a raw_input call, and of course realized after I deleted the email that I actually need that. If I remember correctly, it was something like: raw_input( 'text', [y/n] ) However trying this didn't work, and I looked through the docs without success. Can anyone tell me the how-to? Thanks Bernard From bgailer at alum.rpi.edu Wed Aug 18 23:12:32 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed Aug 18 23:09:16 2004 Subject: [Tutor] Attempting to install Boa Constructor - User Error Detected In-Reply-To: <50953.68.159.148.164.1092855733.squirrel@www.pointcontrol. com> References: <50953.68.159.148.164.1092855733.squirrel@www.pointcontrol.com> Message-ID: <6.1.0.6.0.20040818150919.04000008@mail.mric.net> [snip] It has often troubled me that programs (python included) report "can't open file" when it is more accurate and useful to report "can't find file". I once went in circles for several hours with MS Tech support over this. They did not even suggest to see if the file were there! So I recommend that in a future version of Python we fix this message. Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From srobb at ccmsi.com Wed Aug 18 23:25:43 2004 From: srobb at ccmsi.com (Steve Robb) Date: Wed Aug 18 23:27:49 2004 Subject: [Tutor] Question regarding character conversion usage. Message-ID: I have a project which requires the conversion of a file from ASCII to EBCDIC. My search on google produced the code by a Don Perterson, with his notes re: "The arrays were taken from the Snippets collection." Don's work looks straightforward and compiles successfully to byte code when I import it. My question is how do I use it? What does the missing piece of code look like that would actually allow me to convert, for instance, file ascii.txt(my input) to the same file as ebcdic.txt(my output)? I understand how to open, update, and close files. What I am not seeing is how I use his routines for the conversion. His code is below. a2eG = [ 0, 1, 2, 3, 55, 45, 46, 47, 22, 5, 37, 11, 12, 13, 14, 15, 16, 17, 18, 19, 60, 61, 50, 38, 24, 25, 63, 39, 28, 29, 30, 31, 64, 79,127,123, 91,108, 80,125, 77, 93, 92, 78,107, 96, 75, 97, 240,241,242,243,244,245,246,247,248,249,122, 94, 76,126,110,111, 124,193,194,195,196,197,198,199,200,201,209,210,211,212,213,214, 215,216,217,226,227,228,229,230,231,232,233, 74,224, 90, 95,109, 121,129,130,131,132,133,134,135,136,137,145,146,147,148,149,150, 151,152,153,162,163,164,165,166,167,168,169,192,106,208,161, 7, 32, 33, 34, 35, 36, 21, 6, 23, 40, 41, 42, 43, 44, 9, 10, 27, 48, 49, 26, 51, 52, 53, 54, 8, 56, 57, 58, 59, 4, 20, 62,225, 65, 66, 67, 68, 69, 70, 71, 72, 73, 81, 82, 83, 84, 85, 86, 87, 88, 89, 98, 99,100,101,102,103,104,105,112,113,114,115,116,117, 118,119,120,128,138,139,140,141,142,143,144,154,155,156,157,158, 159,160,170,171,172,173,174,175,176,177,178,179,180,181,182,183, 184,185,186,187,188,189,190,191,202,203,204,205,206,207,218,219, 220,221,222,223,234,235,236,237,238,239,250,251,252,253,254,255 ] e2aG = [ 0, 1, 2, 3,156, 9,134,127,151,141,142, 11, 12, 13, 14, 15, 16, 17, 18, 19,157,133, 8,135, 24, 25,146,143, 28, 29, 30, 31, 128,129,130,131,132, 10, 23, 27,136,137,138,139,140, 5, 6, 7, 144,145, 22,147,148,149,150, 4,152,153,154,155, 20, 21,158, 26, 32,160,161,162,163,164,165,166,167,168, 91, 46, 60, 40, 43, 33, 38,169,170,171,172,173,174,175,176,177, 93, 36, 42, 41, 59, 94, 45, 47,178,179,180,181,182,183,184,185,124, 44, 37, 95, 62, 63, 186,187,188,189,190,191,192,193,194, 96, 58, 35, 64, 39, 61, 34, 195, 97, 98, 99,100,101,102,103,104,105,196,197,198,199,200,201, 202,106,107,108,109,110,111,112,113,114,203,204,205,206,207,208, 209,126,115,116,117,118,119,120,121,122,210,211,212,213,214,215, 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231, 123, 65, 66, 67, 68, 69, 70, 71, 72, 73,232,233,234,235,236,237, 125, 74, 75, 76, 77, 78, 79, 80, 81, 82,238,239,240,241,242,243, 92,159, 83, 84, 85, 86, 87, 88, 89, 90,244,245,246,247,248,249, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57,250,251,252,253,254,255 ] def AsciiToEbcdic(str): '''Return the ASCII string str in EBCDIC form. ''' global a2eG if type(str) != type(""): raise "Bad data", "Expected a string argument" if len(str) == 0: return str newstr = "" for ix in xrange(len(str)): newstr = newstr + chr(a2eG[ord(str[ix])]) return newstr def EbcdicToAscii(str): global e2aG if type(str) != type(""): raise "Bad data", "Expected a string argument" if len(str) == 0: return str newstr = "" for ix in xrange(len(str)): newstr = newstr + chr(e2aG[ord(str[ix])]) return newstr def Test(): str = "The dog jumped over the lazy brown fox in 1.234567890 seconds" str1 = EbcdicToAscii(AsciiToEbcdic(str)) if str != str1: raise "Test failed" if __name__ == '__main__': Test() From dyoo at hkn.eecs.berkeley.edu Thu Aug 19 00:00:21 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Aug 19 00:01:11 2004 Subject: [Tutor] Attempting to install Boa Constructor - User Error Detected In-Reply-To: <6.1.0.6.0.20040818150919.04000008@mail.mric.net> Message-ID: On Wed, 18 Aug 2004, Bob Gailer wrote: > [snip] > It has often troubled me that programs (python included) report "can't open > file" when it is more accurate and useful to report "can't find file". [meta: skip this message if you're not interested in how Python's C implementation works.] Hi Bob, Hmmm...ok. Out of curiosity, let's see how Python opens up source files. Thank goodness Python is an open-source project! *grin* The relevant source-code opening code for the Python interpreter lives in modules/main.c. /*** modules/main.c ***/ ... if (filename != NULL) { if ((fp = fopen(filename, "r")) == NULL) { fprintf(stderr, "%s: can't open file '%s'\n", argv[0], filename); return 2; } ... /******/ Ok, bingo. So that's where that message is coming from in Python. We can make that error message a lot more informative by using C's perror() or strerror() functions: both functions can look at the standard "errno" error integer, and give a nice description of what really happened. Here's one way to make the error message more informative: /******/ if ((fp = fopen(filename, "r")) == NULL) { /* dyoo: added call to strerror to see if we can improve the state of error messages*/ fprintf(stderr, "%s: can't open file '%s': %s\n", argv[0], filename, strerror(errno)); return 2; } /******/ With this modification, the Python interpreter now says: /******/ [dyoo@shoebox python]$ bin/python filethatdoesnotexist.py bin/python: can't open file 'filethatdoesnotexist.py': No such file or directory /******/ Better! *grin* > So I recommend that in a future version of Python we fix this message. Ok, I'll send a patch over to SourceForge. Let's see if it gets in! *grin* From klappnase at freenet.de Thu Aug 19 00:18:03 2004 From: klappnase at freenet.de (Michael Lange) Date: Thu Aug 19 00:21:29 2004 Subject: [Tutor] boolean raw_input In-Reply-To: <004001c4856f$d1790590$2901a8c0@atyss> References: <004001c4856f$d1790590$2901a8c0@atyss> Message-ID: <20040819001803.007a7319.klappnase@freenet.de> On Wed, 18 Aug 2004 23:07:45 +0100 "Bernard Lebel" wrote: > Hello, > > Recently I saw on this list a bit of code that used a boolean expression > inside a raw_input call, and of course realized after I deleted the email > that I actually need that. If I remember correctly, it was something like: > > raw_input( 'text', [y/n] ) > > However trying this didn't work, and I looked through the docs without > success. Can anyone tell me the how-to? > Bernard, maybe you mean something like this: answer = raw_input('Do you want me to print "hello"? [y/n]') if answer in ('Y', 'y'): print 'hello' Michael From alan.gauld at blueyonder.co.uk Thu Aug 19 00:32:37 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Aug 19 00:32:21 2004 Subject: [Tutor] boolean raw_input References: <004001c4856f$d1790590$2901a8c0@atyss> Message-ID: <011301c48573$43a2c310$6401a8c0@xp> > Recently I saw on this list a bit of code that used a boolean expression > inside a raw_input call, and of course realized after I deleted the email > that I actually need that. > If I remember correctly, it was something like: > > raw_input( 'text', [y/n] ) More, likely it was: raw_input("text [y/n]") ie the default values shown inside the prompt string. raw_input only takes one parameter, a prompt string. The only way I can think of to use boolean expressions inside raw_input is to use a single input line to do two jobs. ie value = raw_input(SomeTest() and "Sometest value:" or "Something else:") Which does the same as: if someTest(): value = raw_input("Sometest value:") else: value = raw_input("Something else:") Other than that I can't think what you mean. Alan G. From alan.gauld at blueyonder.co.uk Thu Aug 19 00:38:03 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Aug 19 00:37:47 2004 Subject: [Tutor] Attempting to install Boa Constructor - User ErrorDetected References: <50953.68.159.148.164.1092855733.squirrel@www.pointcontrol.com> <6.1.0.6.0.20040818150919.04000008@mail.mric.net> Message-ID: <011801c48574$05fcf160$6401a8c0@xp> > It has often troubled me that programs (python included) report "can't open > file" when it is more accurate and useful to report "can't find file". In principle I agree but... > So I recommend that in a future version of Python we fix this message. I believe the problem is at the level of the OS open() call which simply returns an error (-1) with no distinction as to why it failed. Thus Python's open() call would need to be rewritten to do all sorts of tests before trying to open the file (or after detecting the error I suppose...). This would be friendly but make filehandling very slow where multiple files had to be opened. Of course if a proper File object were created that wrapped the low level calls, then normal users could use File("foo") and hard core performance junkies could still use open("foo"). Alan G From python at bernardlebel.com Thu Aug 19 02:22:47 2004 From: python at bernardlebel.com (Bernard Lebel) Date: Thu Aug 19 01:23:11 2004 Subject: [Tutor] Please comment my -first- script References: <000e01c484b3$7c174a10$2901a8c0@atyss> <6.1.0.6.0.20040817214729.02a4e558@mail4.skillsoft.com> Message-ID: <000a01c48583$0899be80$2901a8c0@atyss> Hi Kent, First, thanks a lot for the suggestions. I implemented them all! Regarding the part of your email that I included in this reply, I did a little test, nothing fancy. I ran two versions of the script: one with everything you suggested implemented, and one without the part below (the sequences collecting and iteration statements). To iterate over 302 files and 11 directories, it took about: 1.25 seconds to complete without the code below 0.75 seconds to complete with the code below. It was not easy to implemented, but I think it paid off. It's also 15 lines less! Here is the script again, if anyone is interested. Warning: in py format. Thanks again Bernard ----- Original Message ----- From: "Kent Johnson" > aNames = {} > for oFile in oFiles: > sName, sSeq, sExt = oFile.split('.') > aNames.setdefault(sName, []).append(sSeq) > > The loop to test for missing sequences would be something like this: > for sName, sSeqList in aNames.items(): > for iFrame in range(iStart, iEnd + 1): > # Search in sSeqList for iFrame using a similar loop to what you > have now with sZero -------------- next part -------------- """ Check_Sequence.py Par Bernard Lebel Directeur technique, rendering Action Synthese - Marseille -France- Aout 2004 Check_Sequence.py est la version pour l interpreteur Python. Il doit ?tre execute avec Python IDLE - PythonWin - ou tout autre interpreteur natif Python La version Check_Sequence.pys est la version pour XSI et doit etre executee dans le Script Editor de XSI Description Check_sequence d?tecter les frames manquants dans toutes les passes rendues pour le plan sp?cifie et detecte aussi les drop-frames -frames pesant moins de 1k- Pour l instant, tous les dossiers du plan specifie sont evalues a l'exception des dossiers 2flame et poubelle Une version future permettra d etre plus selectif Utilisation Lancer l interpreteur Python -en l'occurence PythonWin- Faire Ctrl I -File > Import- Selectionner le script - cliquer OK Entrer le num?ro de sequence avec les zeros qui precedent mais sans le S Entrer le numero de plan avec les zeros qui precedent mais sans le P Entrer le premier frame attendu, sans les zeros qui precedent Entrer le dernier frame attendu, sans les zeros qui precedent Lire le rapport Thanks to Kent Johnson for the many suggestions """ # ----------------------------------------------------- # Import block import os # ----------------------------------------------------- print ' [[ CHECK SEQUENCE ]] ' print '' print '>>>>> IMPORTANT:' print "1. Assurez-vous d'avoir des dossiers propres avant d'executer le script." print "2. N'entrez pas le S et le P dans les numeros de sequence et de plan." sSequence = raw_input( 'Numero de sequence (sans le S): ' ) sPlan = raw_input( 'Numero de plan (sans le P): ' ) iStart = int( raw_input( 'Premier frame: ' ) ) iEnd = int( raw_input( 'Dernier frame: ' ) ) iCount = iEnd - iStart + 1 # Define root search path sRoot = os.path.join( 'C:\\FRAME2\\SEQUENCES', 'S' + sSequence, 'P' + sPlan ) #sRoot = os.path.join( '\\\\Sata-NAS1500\\FRAME2\\SEQUENCES', 'S' + sSequence, 'P' + sPlan ) if not os.path.exists( sRoot ): print 'Pas de plan pour le dossier specifie.' else: print '' print '>>>>> INFORMATIONS SUR LE PLAN:' print '1. Dossier du plan: ' + sRoot print '2. Premier frame: ' + str( iStart ) print '3. Dernier frame: ' + str( iEnd ) print '4. Nombre de frames attendus: ' + str( iCount ) print '' print '>>>>> DEBUT DE VERIFICATION DU PLAN' # Iterate through root folder to collected folders for sDirPath, sDirName, oFiles in os.walk( sRoot, True, None ): if '2flame' in sDirName: sDirName.remove( '2flame' ) if 'poubelle' in sDirName: sDirName.remove( 'poubelle' ) # Check if directory contains files if len( oFiles ) > 0: print '' print '_____ Verification de >>>>>>>>>>>> ' + sDirPath # Get file extention sExt = '' # Get name of first file oFirstFile = oFiles[0] # Split name into elements aFirstName = oFirstFile.split( '.' ) if len( aFirstName ) == 1: sExt = '' elif len( aFirstName ) == 2: sExt = aFirstName[1] else: sExt = aFirstName[-1] # Create empty dictionary to store sequences aNames = {} # Iterate through files of current directory for oFile in oFiles: # Check the file size if os.path.getsize( os.path.join( sDirPath, oFile ) ) < 1024: print ' Drop: ' + oFile # Split file name into elements, and assign variables for each of them try: sName, sPad, sExt = oFile.split( '.' ) except ValueError: pass aNames.setdefault( sName, [] ).append( sPad ) # Iterate over each sequence for sName, aPad in aNames.items(): # Now create a virtual sequence of files for iFrame in range( iStart, iEnd + 1 ): # Convert current frame to string sFrame = str( iFrame ) # Give 5 chances to test the existance of the file. At each new attempt, add a 0 to the padding for iZero in range(5): # Check if current padding is found in list of pad numbers if not sFrame in aPad: # Not found, so add a leading 0 to the padding sFrame = sFrame.zfill( len( sFrame ) + 1 ) else: # A match is found, move on to the next sequence. break else: # So we reached here because we could never find a match for the virtual padding and the collected ones. print ' Not found: ' + sName + '.' + str(iFrame) # Script completed! print '' print '>>>>> FIN DE VERIFICATION DU PLAN' From dyoo at hkn.eecs.berkeley.edu Thu Aug 19 01:38:05 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Aug 19 01:38:08 2004 Subject: [Tutor] Exceptions vs error codes In-Reply-To: <011801c48574$05fcf160$6401a8c0@xp> Message-ID: > I believe the problem is at the level of the OS open() call which simply > returns an error (-1) with no distinction as to why it failed. Thus > Python's open() call would need to be rewritten to do all sorts of tests > before trying to open the file (or after detecting the error I > suppose...). This would be friendly but make filehandling very slow > where multiple files had to be opened. Hi Alan, Whenever anything bad happens in C standard library code, the 'errno' global variable is set to something useful. It's pervasive throughout the C library. Good error reporting in C should be, in theory, as simple as a call to perror(). But this facility is also not well known to many C programmers, even experienced ones! Most C tutorials that I've seen don't even mention 'errno' or the standard perror() function. And that's frankly disappointing, because that valuable debugging information is being needlessly suppressed. This is probably a strong reason for exceptions in high-level languages like Python, since exceptions can't be ignored unless deliberately suppressed. In Python code, an unsuccessful file open does raise a great error message: ### >>> open("filethatdoesnotexist.py") Traceback (most recent call last): File "", line 1, in ? IOError: [Errno 2] No such file or directory: 'filethatdoesnotexist.py' ### and so the default is to give these wonderful stack traces that point out exactly what's going on. In order to make turn this into something unhelpful, a programmer will have to deliberately do something like: ### >>> try: ... open("filethatdoesnotexist.py") ... except IOError: ... print "Can't open file" ... Can't open file ### *grin* > Of course if a proper File object were created that wrapped the low > level calls, then normal users could use File("foo") and hard core > performance junkies could still use open("foo"). Not necessary: all of C's system calls set 'errno' when bad things happen. Talk to you later! From dyoo at hkn.eecs.berkeley.edu Thu Aug 19 02:15:30 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Aug 19 02:15:34 2004 Subject: [Tutor] Question regarding character conversion usage. In-Reply-To: Message-ID: On Wed, 18 Aug 2004, Steve Robb wrote: > I have a project which requires the conversion of a file from ASCII to > EBCDIC. My search on google produced the code by a Don Perterson, with > his notes re: "The arrays were taken from the Snippets collection." > Don's work looks straightforward and compiles successfully to byte code > when I import it. My question is how do I use it? What does the > missing piece of code look like that would actually allow me to convert, > for instance, file ascii.txt(my input) to the same file as ebcdic.txt(my > output)? [code cut] Hi Steve, The code you posted provides two functions, "AsciiToEbcdic()" and "ebcdicToAscii()". In particular, asciiToEbcdic() looks like a function that can take a line of ascii, and convert it to a line of ebcdic. So as long as you're working with a single line of something, you should be able to directly apply those functions. > I understand how to open, update, and close files. What I am not seeing > is how I use his routines for the conversion. Ah, ok. Have you ready about how to apply some kind of process across a file? If not, you may want to look at: http://www.freenetpages.co.uk/hp/alan.gauld/tutloops.htm which explains how to apply a process across a sequence, as well as: http://www.freenetpages.co.uk/hp/alan.gauld/tutfiles.htm for some examples of file manipulation. If you have more questions, please feel free to ask. From r2b2 at myway.com Thu Aug 19 02:22:42 2004 From: r2b2 at myway.com (r2b2) Date: Thu Aug 19 02:22:51 2004 Subject: [Tutor] email attachment Message-ID: <20040819002242.58BE9399F@mprdmxin.myway.com> I'm looking for a simple way to attach a file to an email message. I've seen some examples out there but i'm doing some thing wrong. thanks _______________________________________________ No banners. No pop-ups. No kidding. Make My Way your home on the Web - http://www.myway.com From kent_johnson at skillsoft.com Thu Aug 19 04:55:12 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Thu Aug 19 04:55:14 2004 Subject: [Tutor] Question regarding character conversion usage. In-Reply-To: References: Message-ID: <6.1.0.6.0.20040818223638.02a09918@mail4.skillsoft.com> With apologies to the original author who is not here to defend himself and did not ask for the critique, I have to say that this is poorly written code. The use of string concatenation (+) to build up a string is a well-documented bad practice. The preferred way to build up a string is to create a list of components and join the finished list into a single string. The use of an index to iterate over a string is unnecessary. The loop > newstr = "" > for ix in xrange(len(str)): > newstr = newstr + chr(a2eG[ord(str[ix])]) would be better written as buf = [] for c in str: buf.append(chr(a2eG[ord(c)])) newstr = ''.join(buf) or even better newstr = ''.join( [chr(a2eG[ord(c)]) for c in str] ) The call to chr could be eliminated by converting the arrays to hold characters instead of ints. Better yet, use the built-in string.translate() function and do everything in one call. Leaving the definitions of a2eG and e2aG alone, the definitions of AsciiToEbcdic and EbcdicToAscii can be replaced with this: a2eG = ''.join(map(chr, a2eG)) # Convert a2eG to a single string e2aG = ''.join(map(chr, e2aG)) # ditto def AsciiToEbcdic(str): '''Return the ASCII string str in EBCDIC form. ''' global a2eG try: return str.translate(a2eG) except AttributeError: raise "Bad data", "Expected a string argument" def EbcdicToAscii(str): global e2aG try: return str.translate(e2aG) except AttributeError: raise "Bad data", "Expected a string argument" I also took out the test for string type and just catch the exception you will get if it is not. This version runs the Test() method 30 times faster than the original. The difference would most likely be more with a longer string as the performance of repeated string concatenation is O(n^2) Short on tolerance tonight :-) Kent At 04:25 PM 8/18/2004 -0500, Steve Robb wrote: >a2eG = [ > 0, 1, 2, 3, 55, 45, 46, 47, 22, 5, 37, 11, 12, 13, 14, 15, > 16, 17, 18, 19, 60, 61, 50, 38, 24, 25, 63, 39, 28, 29, 30, 31, > 64, 79,127,123, 91,108, 80,125, 77, 93, 92, 78,107, 96, 75, 97, > 240,241,242,243,244,245,246,247,248,249,122, 94, 76,126,110,111, > 124,193,194,195,196,197,198,199,200,201,209,210,211,212,213,214, > 215,216,217,226,227,228,229,230,231,232,233, 74,224, 90, 95,109, > 121,129,130,131,132,133,134,135,136,137,145,146,147,148,149,150, > 151,152,153,162,163,164,165,166,167,168,169,192,106,208,161, 7, > 32, 33, 34, 35, 36, 21, 6, 23, 40, 41, 42, 43, 44, 9, 10, 27, > 48, 49, 26, 51, 52, 53, 54, 8, 56, 57, 58, 59, 4, 20, 62,225, > 65, 66, 67, 68, 69, 70, 71, 72, 73, 81, 82, 83, 84, 85, 86, 87, > 88, 89, 98, 99,100,101,102,103,104,105,112,113,114,115,116,117, > 118,119,120,128,138,139,140,141,142,143,144,154,155,156,157,158, > 159,160,170,171,172,173,174,175,176,177,178,179,180,181,182,183, > 184,185,186,187,188,189,190,191,202,203,204,205,206,207,218,219, > 220,221,222,223,234,235,236,237,238,239,250,251,252,253,254,255 > ] > >e2aG = [ > 0, 1, 2, 3,156, 9,134,127,151,141,142, 11, 12, 13, 14, 15, > 16, 17, 18, 19,157,133, 8,135, 24, 25,146,143, 28, 29, 30, 31, > 128,129,130,131,132, 10, 23, 27,136,137,138,139,140, 5, 6, 7, > 144,145, 22,147,148,149,150, 4,152,153,154,155, 20, 21,158, 26, > 32,160,161,162,163,164,165,166,167,168, 91, 46, 60, 40, 43, 33, > 38,169,170,171,172,173,174,175,176,177, 93, 36, 42, 41, 59, 94, > 45, 47,178,179,180,181,182,183,184,185,124, 44, 37, 95, 62, 63, > 186,187,188,189,190,191,192,193,194, 96, 58, 35, 64, 39, 61, 34, > 195, 97, 98, 99,100,101,102,103,104,105,196,197,198,199,200,201, > 202,106,107,108,109,110,111,112,113,114,203,204,205,206,207,208, > 209,126,115,116,117,118,119,120,121,122,210,211,212,213,214,215, > 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231, > 123, 65, 66, 67, 68, 69, 70, 71, 72, 73,232,233,234,235,236,237, > 125, 74, 75, 76, 77, 78, 79, 80, 81, 82,238,239,240,241,242,243, > 92,159, 83, 84, 85, 86, 87, 88, 89, 90,244,245,246,247,248,249, > 48, 49, 50, 51, 52, 53, 54, 55, 56, 57,250,251,252,253,254,255 >] > >def AsciiToEbcdic(str): > '''Return the ASCII string str in EBCDIC form. > ''' > global a2eG > if type(str) != type(""): > raise "Bad data", "Expected a string argument" > if len(str) == 0: return str > newstr = "" > for ix in xrange(len(str)): > newstr = newstr + chr(a2eG[ord(str[ix])]) > return newstr > >def EbcdicToAscii(str): > global e2aG > if type(str) != type(""): > raise "Bad data", "Expected a string argument" > if len(str) == 0: return str > newstr = "" > for ix in xrange(len(str)): > newstr = newstr + chr(e2aG[ord(str[ix])]) > return newstr > >def Test(): > str = "The dog jumped over the lazy brown fox in 1.234567890 seconds" > str1 = EbcdicToAscii(AsciiToEbcdic(str)) > if str != str1: > raise "Test failed" > >if __name__ == '__main__': > Test() >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From carroll at tjc.com Thu Aug 19 05:19:41 2004 From: carroll at tjc.com (Terry Carroll) Date: Thu Aug 19 05:19:49 2004 Subject: [Tutor] Question regarding character conversion usage. In-Reply-To: Message-ID: On Wed, 18 Aug 2004, Steve Robb wrote: > I have a project which requires the conversion of a file from ASCII to > EBCDIC. My search on google produced the code by a Don Perterson, with his > notes re: "The arrays were taken from the Snippets collection." You can use Python's own routines for this. CP500 appears to be standard EBCDIC. >>> import codecs >>> >>> ebcdic_input = '\xe2\xd7\xc1\xd4' # "SPAM" in EBCDIC >>> >>> e2a = codecs.getdecoder("CP500") >>> a2e = codecs.getencoder("CP500") >>> >>> (asc_out, strlen) = e2a(ebcdic_input) >>> asc_out, strlen (u'SPAM', 4) >>> >>> (ebc_out, strlen) = a2e(asc_out) >>> ebc_out, strlen ('\xe2\xd7\xc1\xd4', 4) It was nice to see a little EBCDIC again. I'm a former architect for Amdahl, which made IBM-compatible mainframes. I grew up on EBCDIC, and never really have learned ASCII intuitively as I did EBCDIC. From iqbala-python at qwestip.net Thu Aug 19 06:22:07 2004 From: iqbala-python at qwestip.net (Asif Iqbal) Date: Thu Aug 19 06:22:09 2004 Subject: [Tutor] Process Taking more than 10% Message-ID: <20040819042207.GA15047@qwestip.net> Hi All I am a newbie in python world. I am looking for a python way to detect processes that are taking more than 10% and then find the user who is using it and send a report to myself and may kill it as well Thanks for the help -- Asif Iqbal PGP Key: 0xE62693C5 KeyServer: pgp.mit.edu There's no place like 127.0.0.1 From python_newbie at vedorian.com Thu Aug 19 06:36:19 2004 From: python_newbie at vedorian.com (Kevin) Date: Thu Aug 19 06:36:38 2004 Subject: [Tutor] What is self? Message-ID: <000c01c485a6$13e42280$30e57218@basp.phub.net.cable.rogers.com> I notice this in a lot of python programs: def name(self): self.something = None what does the self mean? Thanks Kevin --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.740 / Virus Database: 494 - Release Date: 8/16/04 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040819/e0d77f1e/attachment.html From alan.gauld at blueyonder.co.uk Thu Aug 19 08:56:40 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Aug 19 08:56:18 2004 Subject: [Tutor] Re: Exceptions vs error codes References: Message-ID: <011d01c485b9$ae5693d0$6401a8c0@xp> > > I believe the problem is at the level of the OS open() call which simply > > returns an error (-1) with no distinction as to why it failed. Thus > Whenever anything bad happens in C standard library code, the 'errno' > global variable is set to something useful. It's pervasive throughout the > C library. Good error reporting in C should be, in theory, as simple as a > call to perror(). I thought perror was a Unix thing? It doesn't work under Windows, VMS etc? But I've just tried it on XP and....it works! > But this facility is also not well known to many C programmers, even > experienced ones! I've used perror for years on Unix but for some reason believed it wasn't part of the C library but Unix only. Between curses, getch and perror I'm not having a good week! :-) Alan G. From alan.gauld at blueyonder.co.uk Thu Aug 19 09:02:42 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Aug 19 09:02:21 2004 Subject: [Tutor] Question regarding character conversion usage. References: Message-ID: <012e01c485ba$85ec1770$6401a8c0@xp> > def AsciiToEbcdic(str): > '''Return the ASCII string str in EBCDIC form. > ''' > > def EbcdicToAscii(str): > > def Test(): > str = "The dog jumped over the lazy brown fox in 1.234567890 seconds" > str1 = EbcdicToAscii(AsciiToEbcdic(str)) > if str != str1: > raise "Test failed" What do you not understand exactly? He provides two functions, each converting from one string format to the other. The test function demonstrates how to use them. It creates an ASCII string (str), converts it to EBDIC and back again, then checks that the result is the same as the original. What bit of that do you not understand? Alan G. "Out of Sight, Out of mind" -> "Invisible, Lunatic" From python at bernardlebel.com Thu Aug 19 09:07:31 2004 From: python at bernardlebel.com (Bernard Lebel) Date: Thu Aug 19 09:07:36 2004 Subject: [Tutor] boolean raw_input References: <004001c4856f$d1790590$2901a8c0@atyss> <011301c48573$43a2c310$6401a8c0@xp> Message-ID: <002001c485bb$32789b80$0d01a8c0@studioaction.local> Thanks Alan. I thought you could get a checkbox inside a raw_input call. Any suggestion in that regard will be welcomed :-) Bernard ----- Original Message ----- From: "Alan Gauld" To: "Bernard Lebel" ; Sent: Thursday, August 19, 2004 12:32 AM Subject: Re: [Tutor] boolean raw_input > > Recently I saw on this list a bit of code that used a boolean > expression > > inside a raw_input call, and of course realized after I deleted the > email > > that I actually need that. > > > If I remember correctly, it was something like: > > > > raw_input( 'text', [y/n] ) > > More, likely it was: > > raw_input("text [y/n]") > > ie the default values shown inside the prompt string. > raw_input only takes one parameter, a prompt string. > > The only way I can think of to use boolean expressions inside > raw_input is to use a single input line to do two jobs. ie > > value = raw_input(SomeTest() and "Sometest value:" or "Something > else:") > > Which does the same as: > > if someTest(): > value = raw_input("Sometest value:") > else: > value = raw_input("Something else:") > > Other than that I can't think what you mean. > > Alan G. > > > From python at bernardlebel.com Thu Aug 19 09:24:20 2004 From: python at bernardlebel.com (Bernard Lebel) Date: Thu Aug 19 09:24:33 2004 Subject: [Tutor] Please comment my -first- script References: <000e01c484b3$7c174a10$2901a8c0@atyss> <6.1.0.6.0.20040817214729.02a4e558@mail4.skillsoft.com> <000a01c48583$0899be80$2901a8c0@atyss> <6.1.0.6.0.20040818220207.029cb1d0@mail4.skillsoft.com> Message-ID: <003b01c485bd$8fd54b50$0d01a8c0@studioaction.local> Hi Kent, Thanks for these new suggestions, again I implemented them and all is well. See my comments below. ----- Original Message ----- From: "Kent Johnson" To: Sent: Thursday, August 19, 2004 4:15 AM Subject: Re: [Tutor] Please comment my -first- script > Change line 141 to build a list of the integer pads instead of strings: > aNames.setdefault( sName, [] ).append( > int(sPad) ) > > Now your loop to check all the frames becomes just a few lines: > for iFrame in range( iStart, iEnd + 1 ): > if not iFrame in aPad: > # So we reached here > because we could never find a match for the virtual padding and the > collected ones. > print ' Not > found: ' + sName + '.' + str(iFrame) > > Sweet!! Indeed, this is sweet. A big thanks for that. > > - You should put the setdefault() call inside the try block for ValueError, > because if you get the exception then sName and sPad haven't been set (they > will have stale values in them probably): > try: > sName, sPad, sExt = oFile.split( '.' ) > aNames.setdefault( sName, [] > ).append( sPad ) > except ValueError: > pass Well yes, I didn't have the choice to do that, because otherwise the script fails. > > By the way do you understand what the setdefault call is doing? This is one > of the coolest Python idioms I know. (I'll let you figure it out :-) Hum not really. I have looked in the documentation but could not find much details about that. Can you elaborate if you don't mind? Thanks Bernard From alan.gauld at blueyonder.co.uk Thu Aug 19 09:58:14 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Aug 19 09:57:51 2004 Subject: [Tutor] Question regarding character conversion usage. References: Message-ID: <015701c485c2$478b2ef0$6401a8c0@xp> > It was nice to see a little EBCDIC again. I'm a former architect for > Amdahl, which made IBM-compatible mainframes. I grew up on EBCDIC, and > never really have learned ASCII intuitively as I did EBCDIC. Ah, Ahmdal! The memories. 3 Amdhals clustered, with a 600GB online database, c1985 :-) Whatever happened to Ahmdal? Are they still extant? Doing what? Like most of the mainframe companies they seem to have disappeared from the (my?) landscape. And, just to bring Python back in, does anyone know if the is a port of Python to MVS? Alan G. From alan.gauld at blueyonder.co.uk Thu Aug 19 09:59:55 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Aug 19 09:59:34 2004 Subject: [Tutor] Process Taking more than 10% References: <20040819042207.GA15047@qwestip.net> Message-ID: <015c01c485c2$843211c0$6401a8c0@xp> > I am a newbie in python world. I am looking for a python way to detect > processes that are taking more than 10% and then find the user who is > using it and send a report to myself and may kill it as well Which platform? There are easy ways to do this on both Unix and Windows and there are harder ways. But if its only one OS we might as well stick to the easy ways... :-) Alan G. From alan.gauld at blueyonder.co.uk Thu Aug 19 10:14:04 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Aug 19 10:13:41 2004 Subject: [Tutor] What is self? References: <000c01c485a6$13e42280$30e57218@basp.phub.net.cable.rogers.com> Message-ID: <016401c485c4$7e2f74a0$6401a8c0@xp> > I notice this in a lot of python programs: > def name(self): > self.something = None > > what does the self mean? It is shorthand for a reference to the current object. The functions you see written that way are embedded inside classes. When you create an instance of the class the instance has a copy of the data but not the metods. Thus when we send a message to an instance and it calls the corresponding method, it does so via a reference to the class. It passes a reference to itself (self!) to the method so that the class code knows which instance to use. Thus the client code calls the instance. The instance calls the class method, passing a reference to itself The class method then uses the reference to pick up the instance data (the self.something bits) You can see this in action by explicitly calling the class method: >>> class C: ... def __int__(self, val): self.val = val ... def f(self): print "hello, my value is:", self.val ... >>> a = C(27) >>> b = C(42) >>> # first try sending messages to the instances >>> a.f() hello, my value is 27 >>> b.f() hello, my value is 42 >>> # now call the method explicitly >>> C.f(a) hello, my value is 27 I hope that clarifies? If you haven't done OOP yet, don't get too hung up on it. When you do use OOP you still don't need to worry, just follow convention and it will just work! And this reminds me that I intended putting a deeper explanation of self in my rewritten tutor but haven't yet. So another addendum coming up... Thanks for reminding me! :-) Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/ From alan.gauld at blueyonder.co.uk Thu Aug 19 10:17:58 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Aug 19 10:17:36 2004 Subject: [Tutor] boolean raw_input References: <004001c4856f$d1790590$2901a8c0@atyss><011301c48573$43a2c310$6401a8c0@xp> <002001c485bb$32789b80$0d01a8c0@studioaction.local> Message-ID: <016d01c485c5$09ab9db0$6401a8c0@xp> > I thought you could get a checkbox inside a raw_input call. > Any suggestion in that regard will be welcomed :-) raw_input is strictly text based. Check boxes are GUI things. What do you have in mind exactly? Can you show us some hypothetical code that does what you would like, then explain how it would appear to the user? Maybe we can come up with something. or an alternative... As the Aberdonian landlady said to her new lodger: "If there's anything you need just ask, and I'll show you how to get along without it..." :-) Alan G. From carroll at tjc.com Thu Aug 19 10:19:17 2004 From: carroll at tjc.com (Terry Carroll) Date: Thu Aug 19 10:19:21 2004 Subject: [Tutor] Question regarding character conversion usage. In-Reply-To: <015701c485c2$478b2ef0$6401a8c0@xp> Message-ID: On Thu, 19 Aug 2004, Alan Gauld wrote: > Whatever happened to Ahmdal? Are they still extant? Doing what? It's gone. Fujitsu owned just short of 50% of it for the longest time, and finally bought the rest around 1997 or so; after a while they killed off the mainframe business, and not long thereafter, the Amdahl name. Now it's Fujitsu in the old Amdahl buildings (the ones still occupied, anyway). I was laid off in 1994 when the processor I was working on got canned, but it was no big deal, as I was just about to graduate from law school, so it was perfectly timed for a career change for me. I've been a lawyer ever since, and program only for fun now. > And, just to bring Python back in, does anyone know if the is a > port of Python to MVS? But of course! http://www.teaser.fr/~jymengant/mvspython/mvsPythonPort.html From kent_johnson at skillsoft.com Thu Aug 19 16:12:01 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Thu Aug 19 16:12:12 2004 Subject: [Tutor] Please comment my -first- script In-Reply-To: <003b01c485bd$8fd54b50$0d01a8c0@studioaction.local> References: <000e01c484b3$7c174a10$2901a8c0@atyss> <6.1.0.6.0.20040817214729.02a4e558@mail4.skillsoft.com> <000a01c48583$0899be80$2901a8c0@atyss> <6.1.0.6.0.20040818220207.029cb1d0@mail4.skillsoft.com> <003b01c485bd$8fd54b50$0d01a8c0@studioaction.local> Message-ID: <6.1.0.6.0.20040819082159.028e7860@mail4.skillsoft.com> At 09:24 AM 8/19/2004 +0200, Bernard Lebel wrote: > > - You should put the setdefault() call inside the try block for >ValueError, > > because if you get the exception then sName and sPad haven't been set >(they > > will have stale values in them probably): > > try: > > sName, sPad, sExt = >oFile.split( '.' ) > > aNames.setdefault( sName, [] > > ).append( sPad ) > > except ValueError: > > pass > >Well yes, I didn't have the choice to do that, because otherwise the script >fails. That's troubling. How does it fail? > > By the way do you understand what the setdefault call is doing? This is >one > > of the coolest Python idioms I know. (I'll let you figure it out :-) > >Hum not really. I have looked in the documentation but could not find much >details about that. Can you elaborate if you don't mind? OK, let's deconstruct this: aNames.setdefault( sName, [] ).append( sPad ) First, look at aValue = aNames.setdefault(sName, []) This is roughly equivalent to try: aValue = aNames[sName] except KeyError: aValue = [] aNames[sName] = aValue This tries to get the dict value corresponding to sName. If it exists, that's it. If it doesn't exist, it creates a new list, assigns it to aValue, and _also_ stores a reference to the list in aNames. Now aValue and aNames[sName] hold references to the same list. Since lists are mutable, appending to the list changes the list held by aNames. Doing it all in one statement just eliminates the named variable aValue, the effect is the same. Kent From flaxeater at yahoo.com Thu Aug 19 16:41:38 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Thu Aug 19 16:41:41 2004 Subject: [Tutor] improt email, strange from field Message-ID: <20040819144138.5455.qmail@web52606.mail.yahoo.com> When I send emails from my cgi script I try to set the from field to my business name however it says it's from "Imperial Data Services"@server-14.mcc-sys.com even though that is not the email address that sent it. What I would like instead is something either 'Just The Name' like when I receive personal emails and it shows the name of the person. Or perhaps the email I cent it from. Here's the pertinent code email=MIMEText(message) email['Subject']='%s thought you might like this!' %fromname email['From']='"Imperial Data Services"' email['To']=toaddr s = smtplib.SMTP('smtp.imperialws.com') #s.set_debuglevel(1) s.login('info@imperialws.com',passwd) s.sendmail('info@imperialws.com',toaddr, email.as_string()) s.close() Any help would be greatly appreciated. _______________________________ Do you Yahoo!? Win 1 of 4,000 free domain names from Yahoo! Enter now. http://promotions.yahoo.com/goldrush From kent_johnson at skillsoft.com Thu Aug 19 17:21:21 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Thu Aug 19 17:21:37 2004 Subject: [Tutor] improt email, strange from field In-Reply-To: <20040819144138.5455.qmail@web52606.mail.yahoo.com> References: <20040819144138.5455.qmail@web52606.mail.yahoo.com> Message-ID: <6.1.0.6.0.20040819111855.029cf728@mail4.skillsoft.com> If you use '"Imperial Data Services" ' as the value for both email['From'] and the first argument to sendmail I think it will do what you want. Kent At 07:41 AM 8/19/2004 -0700, Chad Crabtree wrote: >When I send emails from my cgi script I try to set the from field to >my >business name however it says it's from >"Imperial Data Services"@server-14.mcc-sys.com even though that is >not >the email address that sent it. >What I would like instead is something either 'Just The Name' like >when >I receive personal emails and it shows the name of the person. Or >perhaps the email I cent it from. > > >Here's the pertinent code > > email=MIMEText(message) > email['Subject']='%s thought you might like this!' %fromname > email['From']='"Imperial Data Services"' > email['To']=toaddr > s = smtplib.SMTP('smtp.imperialws.com') > #s.set_debuglevel(1) > s.login('info@imperialws.com',passwd) > s.sendmail('info@imperialws.com',toaddr, email.as_string()) > s.close() > >Any help would be greatly appreciated. > > > >_______________________________ >Do you Yahoo!? >Win 1 of 4,000 free domain names from Yahoo! Enter now. >http://promotions.yahoo.com/goldrush >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From klas.martelleur at telia.com Thu Aug 19 18:08:24 2004 From: klas.martelleur at telia.com (Klas Marteleur) Date: Thu Aug 19 17:57:32 2004 Subject: [Tutor] .pyw and .py on a window$ box Message-ID: <200408191808.24484.klas.martelleur@telia.com> Hi I have python problem that is probably related to windows but i am not sure. Hopfully my favourite maillist can help me :) However this is the case: I have python installed on my windows box at work. Under the python installation folder i have created two files. One called "createEbomNew.py" which is my main program and a file called "createEbomGUI.pyw" which is my gui. When i run "createEbomGUI.pyw" it workes as expected. If i rename the program to "createEbomGUI.py", and "dubble click" on the file it also workes as expected (except from that a dos window appear). But when i "dubble click" on the "createEbomGUI.pyw", It brings up the gui alright with no dos window but the program wont work (I get no respone when i "push the buttons"). Has anybody seen this problem? Klas From klas.martelleur at telia.com Thu Aug 19 18:18:18 2004 From: klas.martelleur at telia.com (Klas Marteleur) Date: Thu Aug 19 18:07:26 2004 Subject: [Tutor] Re: .pyw and .py on a window$ box In-Reply-To: <200408191808.24484.klas.martelleur@telia.com> References: <200408191808.24484.klas.martelleur@telia.com> Message-ID: <200408191818.18862.klas.martelleur@telia.com> i need to clearify one sentence in my previous mail ...When i run createEbomGUI.pyw" from IDLE it workes as expected..... Klas > Hi > I have python problem that is probably related to windows but i am not > sure. Hopfully my favourite maillist can help me :) > However this is the case: > > I have python installed on my windows box at work. Under the python > installation folder i have created two files. One called "createEbomNew.py" > which is my main program and a file called "createEbomGUI.pyw" which is my > gui. > > When i run "createEbomGUI.pyw" it workes as expected. > > If i rename the program to "createEbomGUI.py", and "dubble click" on the > file it also workes as expected (except from that a dos window appear). > > But when i "dubble click" on the "createEbomGUI.pyw", It brings up the gui > alright with no dos window but the program wont work (I get no respone when > i "push the buttons"). > > Has anybody seen this problem? > > Klas From flaxeater at yahoo.com Thu Aug 19 19:06:31 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Thu Aug 19 19:06:35 2004 Subject: [Tutor] improt email, strange from field Message-ID: <20040819170632.64861.qmail@web52607.mail.yahoo.com> Kent Johnson wrote: > If you use '"Imperial Data Services" ' as the > value for both email['From'] and the first argument to sendmail I > think it will do what you want. > > Kent > Ok Thanks that worked as prescribed. Thank you both Kent and David __________________________________ Do you Yahoo!? New and Improved Yahoo! Mail - 100MB free storage! http://promotions.yahoo.com/new_mail From iqbala-python at qwestip.net Thu Aug 19 19:14:15 2004 From: iqbala-python at qwestip.net (Asif Iqbal) Date: Thu Aug 19 19:14:18 2004 Subject: [Tutor] Process Taking more than 10% In-Reply-To: <015c01c485c2$843211c0$6401a8c0@xp> References: <20040819042207.GA15047@qwestip.net> <015c01c485c2$843211c0$6401a8c0@xp> Message-ID: <20040819171415.GB15047@qwestip.net> On Thu, Aug 19, 2004 at 08:59:55AM +0100, Alan Gauld wrote: > > I am a newbie in python world. I am looking for a python way to > detect > > processes that are taking more than 10% and then find the user who > is > > using it and send a report to myself and may kill it as well > > Which platform? Solaris SPARC > There are easy ways to do this on both Unix and Windows and > there are harder ways. But if its only one OS we might as > well stick to the easy ways... :-) > > Alan G. > > -- Asif Iqbal PGP Key: 0xE62693C5 KeyServer: pgp.mit.edu There's no place like 127.0.0.1 From visional_freeman at yahoo.com Thu Aug 19 19:42:15 2004 From: visional_freeman at yahoo.com (ivan low) Date: Thu Aug 19 19:43:50 2004 Subject: [Tutor] How to build a function? Message-ID: <4124E677.5090701@yahoo.com> Hi, I was reading a book about building a function but I just not quite get it. Does anybody know where can I find more of this building function tutorial on the net? Or if anybody have time, could you kindly show me some example? Ivan From learning.python at dbmail.dk Thu Aug 19 21:20:53 2004 From: learning.python at dbmail.dk (Ole Jensen) Date: Thu Aug 19 21:22:29 2004 Subject: [Tutor] How to build a function? References: <4124E677.5090701@yahoo.com> Message-ID: <001901c48621$a56a33e0$92c48f52@allmycore> > Hi, I was reading a book about building a function but I just not quite > get it. > Does anybody know where can I find more of this building function > tutorial on the net? > Or if anybody have time, could you kindly show me some example? > > Ivan > I like this short tutorial http://hetland.org/python/instant-hacking if you browse down the page there is a section called "Bigger Programs - Abstraction" that deals with defining functions. Below that it goes further in to functions. Basicly a function needs to be defined and then called e.g.: >>> def square(x): print x*x >>> square(5) 25 >>> square(2.5) 6.25 >>> square(-3) 9 Regards Ole From python at bernardlebel.com Fri Aug 20 00:23:05 2004 From: python at bernardlebel.com (Bernard Lebel) Date: Thu Aug 19 23:20:48 2004 Subject: [Tutor] boolean raw_input References: <004001c4856f$d1790590$2901a8c0@atyss><011301c48573$43a2c310$6401a8c0@xp> <002001c485bb$32789b80$0d01a8c0@studioaction.local> <016d01c485c5$09ab9db0$6401a8c0@xp> Message-ID: <002601c4863b$1ac64390$2901a8c0@atyss> > raw_input is strictly text based. Check boxes are GUI things. > What do you have in mind exactly? Can you show us some > hypothetical code that does what you would like, then > explain how it would appear to the user? Hum well, it concerns my Check_Sequence script that I posted for comments. The main problem for the people who use it is that it is more or less democratic. If you let it run as is, it will visit all directories under the root directory. You can exclude in advance few directories, but the problem remain: if a user wants to "check" only specific folder because he doesn't have to waste to get errors about things he's not concerned about and such, an easy way to handle that would be to have 3 prompts that will ask if he wants to visit a certain folder or not. Each prompt being for a different folder. Right now I use the y/n approach, it works well, but still, users are generally very picky about these things and would be more interested in the real deal. Any advice? > As the Aberdonian landlady said to her new lodger: > "If there's anything you need just ask, and I'll show you > how to get along without it..." :-) I like the sound of that ;-) Bernard From joe at omc-international.com.au Fri Aug 20 00:57:25 2004 From: joe at omc-international.com.au (Joe Healy) Date: Fri Aug 20 00:57:33 2004 Subject: [Tutor] Process Taking more than 10% In-Reply-To: <015c01c485c2$843211c0$6401a8c0@xp> References: <20040819042207.GA15047@qwestip.net> <015c01c485c2$843211c0$6401a8c0@xp> Message-ID: <41253055.5090305@omc-international.com.au> Alan Gauld wrote: >Which platform? >There are easy ways to do this on both Unix and Windows and >there are harder ways. But if its only one OS we might as >well stick to the easy ways... :-) > > > I think on linux you would use popen and ps, but how is it done on windows? Thanks Joe Healy From python_newbie at vedorian.com Fri Aug 20 01:08:07 2004 From: python_newbie at vedorian.com (Kevin) Date: Fri Aug 20 01:08:19 2004 Subject: [Tutor] A suggestion! Message-ID: <001001c48641$644d4bc0$30e57218@basp.phub.net.cable.rogers.com> I have 2 websites gameweave.com, and vedorian.com. I wanted to create a python site that was directed to games created with python. With a message board where people can post questions and answers to python game creations questions. Do you think that it would be kind of pointless, do to the many python sites and mailing lists? Or are there any sites dedicated to games created in python? Thanks for any input Kevin --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.740 / Virus Database: 494 - Release Date: 8/16/04 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040819/f3edc841/attachment.html From shitizb at yahoo.com Fri Aug 20 01:25:22 2004 From: shitizb at yahoo.com (Shitiz Bansal) Date: Fri Aug 20 01:25:31 2004 Subject: [Tutor] Process Taking more than 10% In-Reply-To: <41253055.5090305@omc-international.com.au> Message-ID: <20040819232522.31122.qmail@web53807.mail.yahoo.com> Joe Healy wrote:Alan Gauld wrote: >Which platform? >There are easy ways to do this on both Unix and Windows and >there are harder ways. But if its only one OS we might as >well stick to the easy ways... :-) > > > I think on linux you would use popen and ps, but how is it done on windows? Thanks Joe Healy _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor --------------------------------- Do you Yahoo!? Win 1 of 4,000 free domain names from Yahoo! Enter now. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040819/eaeba46a/attachment.html From orbitz at ezabel.com Fri Aug 20 01:25:03 2004 From: orbitz at ezabel.com (orbitz) Date: Fri Aug 20 01:37:09 2004 Subject: [Tutor] Weird speed issue with mysql vs php Message-ID: <412536CF.60508@ezabel.com> Hello I have a situation where I'm rewriting a bunch of legacy PHP code in python. This issue I'm having is my python program takes about 4.5 hours to write and the PHP equivalent takes about 15 minutes. The program performs a bunch of SQL queries on a MySQL query, and then sends an email with this data. The longest query is limited to 20 results all the time. The odd thing is in my python one it looks like most of the work is being done on the mysql end and doesn't use up much CPU, while the PHP one looks like it uses up a lot of CPU and much on the mysql side. I'm double checking to make sure I didn't put a loop somewhere where there should not be or something silly, but does anyone have any ideas where my issue could be? I profiled my app and nothing looks *too* odd so I'm somewhat stumped as to why the original version is so fast. Also, I use the StringIO class where ever I'm appending long strings together and what not to speed things up. Any suggestions would be very appreciated, thank you. From kent_johnson at skillsoft.com Fri Aug 20 01:38:59 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Aug 20 01:38:57 2004 Subject: [Tutor] boolean raw_input In-Reply-To: <002601c4863b$1ac64390$2901a8c0@atyss> References: <004001c4856f$d1790590$2901a8c0@atyss> <011301c48573$43a2c310$6401a8c0@xp> <002001c485bb$32789b80$0d01a8c0@studioaction.local> <016d01c485c5$09ab9db0$6401a8c0@xp> <002601c4863b$1ac64390$2901a8c0@atyss> Message-ID: <6.1.0.6.0.20040819192351.02a0f4b8@mail4.skillsoft.com> Maybe you should use a GUI to allow the user to pick the directory to check? Or take it as a command line argument? Someone recently posted code that uses Tkinter to get a file path. Kent At 11:23 PM 8/19/2004 +0100, Bernard Lebel wrote: > > raw_input is strictly text based. Check boxes are GUI things. > > What do you have in mind exactly? Can you show us some > > hypothetical code that does what you would like, then > > explain how it would appear to the user? > >Hum well, it concerns my Check_Sequence script that I posted for comments. >The main problem for the people who use it is that it is more or less >democratic. If you let it run as is, it will visit all directories under the >root directory. You can exclude in advance few directories, but the problem >remain: if a user wants to "check" only specific folder because he doesn't >have to waste to get errors about things he's not concerned about and such, >an easy way to handle that would be to have 3 prompts that will ask if he >wants to visit a certain folder or not. Each prompt being for a different >folder. > >Right now I use the y/n approach, it works well, but still, users are >generally very picky about these things and would be more interested in the >real deal. > >Any advice? > > > > As the Aberdonian landlady said to her new lodger: > > "If there's anything you need just ask, and I'll show you > > how to get along without it..." :-) > >I like the sound of that ;-) > > >Bernard > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From shitizb at yahoo.com Fri Aug 20 01:53:44 2004 From: shitizb at yahoo.com (Shitiz Bansal) Date: Fri Aug 20 01:53:46 2004 Subject: [Tutor] lisp Message-ID: <20040819235344.79768.qmail@web53805.mail.yahoo.com> I am sorry for asking a non python related question here. I read about LISP and want to try it out. I searched the net but could not locate the installation package(though i did see a lot of good tutorials). Can anybody tell me where i can find it(preferably a windows version). --------------------------------- Do you Yahoo!? Yahoo! Mail is new and improved - Check it out! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040819/ad884473/attachment.htm From joe at omc-international.com.au Fri Aug 20 02:08:13 2004 From: joe at omc-international.com.au (Joe Healy) Date: Fri Aug 20 02:08:19 2004 Subject: [Tutor] Process Taking more than 10% In-Reply-To: <20040819232522.31122.qmail@web53807.mail.yahoo.com> References: <20040819232522.31122.qmail@web53807.mail.yahoo.com> Message-ID: <412540ED.7000002@omc-international.com.au> Thanks, gave me something to google for. I ended up finding the following worked (for my purposes (to get a list of processes)): import win32pdh # clear the cache (not an issue for me but seemed to be needed if repeating) win32pdh.EnumObjects(None, None, 0, 1) junk, instances = win32pdh.EnumObjectItems(None,None,"process", \ win32pdh.PERF_DETAIL_WIZARD) print instances from a thread in comp.lang.python (doing a ps in windows (is application XYZZT running?)) Thanks. Joe Shitiz Bansal wrote: > > > */Joe Healy /* wrote: > > Alan Gauld wrote: > > >Which platform? > >There are easy ways to do this on both Unix and Windows and > >there are harder ways. But if its only one OS we might as > >well stick to the easy ways... :-) > > > > > > > I think on linux you would use popen and ps, but how is it done on > windows? > > Thanks > > > Joe Healy > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > ------------------------------------------------------------------------ > Do you Yahoo!? > Win 1 of 4,000 free domain names from Yahoo! Enter now > . > >------------------------------------------------------------------------ > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > -- ________________________________________________________ Joe Healy | Engineer OMC-International | 6 Paterson St | Abbotsford, VIC 3067 Melbourne | Australia Phone +61 (3) 9412 6500 | Fax +61 (3) 9415 9105 www.omc-international.com.au Dedicated to safer and more efficient shipping. CONFIDENTIAL COMMUNICATIONS. The information contained in this e-mail is confidential and may be subject to legal professional privilege. It is intended solely for the addressee. If you received this correspondence by mistake, please promptly inform us by reply e-mail or by telephoning +61 3 9412 6500 and then delete the e-mail and destroy any printed copy. You must not disclose, copy or rely on any part of this correspondence if you are not the intended recipient. From bgailer at alum.rpi.edu Fri Aug 20 02:36:46 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri Aug 20 02:33:17 2004 Subject: [Tutor] lisp In-Reply-To: <20040819235344.79768.qmail@web53805.mail.yahoo.com> References: <20040819235344.79768.qmail@web53805.mail.yahoo.com> Message-ID: <6.1.0.6.0.20040819183626.0400aeb0@mail.mric.net> At 05:53 PM 8/19/2004, Shitiz Bansal wrote: >I am sorry for asking a non python related question here. >I read about LISP and want to try it out. I searched the net but could not >locate the installation package(though i did see a lot of good tutorials). >Can anybody tell me where i can find it(preferably a windows version). Take a look at http://clisp.cons.org/ Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From shitizb at yahoo.com Fri Aug 20 02:41:33 2004 From: shitizb at yahoo.com (Shitiz Bansal) Date: Fri Aug 20 02:41:37 2004 Subject: [Tutor] lisp In-Reply-To: <6.1.0.6.0.20040819183626.0400aeb0@mail.mric.net> Message-ID: <20040820004133.49776.qmail@web53809.mail.yahoo.com> thanks bob, it didnt help though. i think a windows version of LISP doesnt exist...is it true? Bob Gailer wrote: At 05:53 PM 8/19/2004, Shitiz Bansal wrote: >I am sorry for asking a non python related question here. >I read about LISP and want to try it out. I searched the net but could not >locate the installation package(though i did see a lot of good tutorials). >Can anybody tell me where i can find it(preferably a windows version). Take a look at http://clisp.cons.org/ Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell --------------------------------- Do you Yahoo!? New and Improved Yahoo! Mail - Send 10MB messages! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040819/5eba95b8/attachment.html From kent_johnson at skillsoft.com Fri Aug 20 03:30:03 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Aug 20 03:30:04 2004 Subject: [Tutor] boolean raw_input In-Reply-To: <002601c4863b$1ac64390$2901a8c0@atyss> References: <004001c4856f$d1790590$2901a8c0@atyss> <011301c48573$43a2c310$6401a8c0@xp> <002001c485bb$32789b80$0d01a8c0@studioaction.local> <016d01c485c5$09ab9db0$6401a8c0@xp> <002601c4863b$1ac64390$2901a8c0@atyss> Message-ID: <6.1.0.6.0.20040819212434.02a12da0@mail4.skillsoft.com> The diropenbox function in EasyGui might be just what you need. Or you could use multchoicebox() to present a list of possible directories and let the user pick the one(s) of interest. http://www.ferg.org/easygui/index.html Kent At 11:23 PM 8/19/2004 +0100, Bernard Lebel wrote: > > raw_input is strictly text based. Check boxes are GUI things. > > What do you have in mind exactly? Can you show us some > > hypothetical code that does what you would like, then > > explain how it would appear to the user? > >Hum well, it concerns my Check_Sequence script that I posted for comments. >The main problem for the people who use it is that it is more or less >democratic. If you let it run as is, it will visit all directories under the >root directory. You can exclude in advance few directories, but the problem >remain: if a user wants to "check" only specific folder because he doesn't >have to waste to get errors about things he's not concerned about and such, >an easy way to handle that would be to have 3 prompts that will ask if he >wants to visit a certain folder or not. Each prompt being for a different >folder. > >Right now I use the y/n approach, it works well, but still, users are >generally very picky about these things and would be more interested in the >real deal. > >Any advice? > > > > As the Aberdonian landlady said to her new lodger: > > "If there's anything you need just ask, and I'll show you > > how to get along without it..." :-) > >I like the sound of that ;-) > > >Bernard > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From orbitz at ezabel.com Fri Aug 20 03:50:27 2004 From: orbitz at ezabel.com (orbitz) Date: Fri Aug 20 04:02:34 2004 Subject: [Tutor] lisp In-Reply-To: <20040820004133.49776.qmail@web53809.mail.yahoo.com> References: <20040820004133.49776.qmail@web53809.mail.yahoo.com> Message-ID: <412558E3.1060709@ezabel.com> http://www.lispworks.com/downloads/lw-personal-edition.html You can also look up allegro cl (I think that's the name). They are trials and limited but better than nothing. Also http://drorbitz.ath.cx/~orbitz/bookmarks.html has a lisp/scheme section. By the way there are plenty of other more on topic places you could have asked this. Shitiz Bansal wrote: > thanks bob, it didnt help though. > i think a windows version of LISP doesnt exist...is it true? > > > */Bob Gailer /* wrote: > > At 05:53 PM 8/19/2004, Shitiz Bansal wrote: > >I am sorry for asking a non python related question here. > >I read about LISP and want to try it out. I searched the net but > could not > >locate the installation package(though i did see a lot of good > tutorials). > >Can anybody tell me where i can find it(preferably a windows > version). > > Take a look at http://clisp.cons.org/ > > Bob Gailer > bgailer@alum.rpi.edu > 303 442 2625 home > 720 938 2625 cell > > ------------------------------------------------------------------------ > Do you Yahoo!? > New and Improved Yahoo! Mail > > - Send 10MB messages! > >------------------------------------------------------------------------ > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > From tim at johnsons-web.com Fri Aug 20 05:03:54 2004 From: tim at johnsons-web.com (Tim Johnson) Date: Fri Aug 20 04:58:04 2004 Subject: [Tutor] lisp In-Reply-To: <20040819235344.79768.qmail@web53805.mail.yahoo.com> References: <20040819235344.79768.qmail@web53805.mail.yahoo.com> Message-ID: <20040820030354.GB3800@johnsons-web.com> * Shitiz Bansal [040819 16:13]: > I am sorry for asking a non python related question here. > I read about LISP and want to try it out. I searched the net but could > not locate the installation package(though i did see a lot of good > tutorials). Here's a connection between lisp and python: emacs and xemacs host very nice 'IDE's for python. Emacs and xemacs are both programmable in elisp, which is sort of a subset of lisp. - tim - -- Tim Johnson http://www.alaska-internet-solutions.com From alan.gauld at blueyonder.co.uk Fri Aug 20 05:40:23 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Aug 20 05:39:46 2004 Subject: [Tutor] Re: .pyw and .py on a window$ box References: <200408191808.24484.klas.martelleur@telia.com> <200408191818.18862.klas.martelleur@telia.com> Message-ID: <01af01c48667$6cc17df0$6401a8c0@xp> > i need to clearify one sentence in my previous mail > > ...When i run createEbomGUI.pyw" from IDLE it workes as expected..... You mean you open the file in an IDLE edit window and then hit F5? > > If i rename the program to "createEbomGUI.py", and "dubble click" on the > > file it also workes as expected (except from that a dos window appear). > > > > But when i "dubble click" on the "createEbomGUI.pyw", It brings up the gui > > alright with no dos window but the program wont work (I get no respone when > > i "push the buttons"). The only thing I can think of is that you still have some raw_input() or input() statements in your program that are trying to read input from the nonn existent dos box? Could it be something like that? Alan G From alan.gauld at blueyonder.co.uk Fri Aug 20 05:48:52 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Aug 20 05:48:16 2004 Subject: [Tutor] How to build a function? References: <4124E677.5090701@yahoo.com> Message-ID: <01b901c48668$9c4b2e30$6401a8c0@xp> > Does anybody know where can I find more of this building function > tutorial on the net? Try my tutor topic on Modules and Functions: Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/ From alan.gauld at blueyonder.co.uk Fri Aug 20 05:53:01 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Aug 20 05:52:25 2004 Subject: [Tutor] boolean raw_input References: <004001c4856f$d1790590$2901a8c0@atyss><011301c48573$43a2c310$6401a8c0@xp><002001c485bb$32789b80$0d01a8c0@studioaction.local><016d01c485c5$09ab9db0$6401a8c0@xp> <002601c4863b$1ac64390$2901a8c0@atyss> Message-ID: <01c001c48669$30a2f310$6401a8c0@xp> > Right now I use the y/n approach, it works well, but still, users are > generally very picky about these things and would be more interested in the > real deal. One option for poer users might be to allow them to specify a regular expression pattern for the folder names to be searched. Then simply test each folder against that. Alternatively you could just build a GUI! Alan G. From alan.gauld at blueyonder.co.uk Fri Aug 20 05:55:22 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Aug 20 05:54:46 2004 Subject: [Tutor] Process Taking more than 10% References: <20040819042207.GA15047@qwestip.net><015c01c485c2$843211c0$6401a8c0@xp> <41253055.5090305@omc-international.com.au> Message-ID: <01c501c48669$84a217c0$6401a8c0@xp> > >There are easy ways to do this on both Unix and Windows and > >there are harder ways. But if its only one OS we might as > >well stick to the easy ways... :-) > I think on linux you would use popen and ps, Nope, the easy way is to use ps and awk... > but how is it done on windows? Assuming NT/W2K/XP Open Task Manager, look at processes and sort by CPU... :-) In both cases Python is the harder route. Right tool for the job... ;-) Alan G. From alan.gauld at blueyonder.co.uk Fri Aug 20 05:58:00 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Aug 20 05:57:23 2004 Subject: [Tutor] lisp References: <20040819235344.79768.qmail@web53805.mail.yahoo.com> Message-ID: <01e201c48669$e2acf3d0$6401a8c0@xp> > I am sorry for asking a non python related question here. > I read about LISP and want to try it out. The best places to start are with Scheme - the PLT opackage is good or CLISP (More standard than Scheme) They both have install packages on their respective web sites. LIsp is a lot like Python but with extra parens... Alan G. From alan.gauld at blueyonder.co.uk Fri Aug 20 05:59:35 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Aug 20 05:58:58 2004 Subject: [Tutor] lisp References: <20040820004133.49776.qmail@web53809.mail.yahoo.com> Message-ID: <01ee01c4866a$1b279210$6401a8c0@xp> > i think a windows version of LISP doesnt exist...is it true? NO, there are lots of Windows Lisps. I have both XLISP and CLISP (and a couple of commercial versions!) And PLT Scheme runs on Windows too. Alan G. From rdm at rcblue.com Fri Aug 20 07:53:54 2004 From: rdm at rcblue.com (Dick Moores) Date: Fri Aug 20 07:55:16 2004 Subject: [Tutor] puzzled by main() Message-ID: <6.1.2.0.2.20040819223458.05416fc8@rcblue.com> I wrote intSpell.py for practice with integers, strings and modules. It works fine by itself, but I'd like to figure out how to use it as a module which I can import and use as intSpell(n). Is my use of main() the problem? Or if not, what should I do? intSpell.py will take an integer n and create a string that spells out n. Not completely, but as shown by these examples: 123000000 -> 123 million 12008787987-> 12 billion, 8 million, 787 thousand, 987 123000879870 -> 123 billion, 879 thousand, 870 Thanks, tutors. Dick Moores -------------- next part -------------- def convertNToString(n): "convert integer to string" return str(n) def regularizeFirstGroup(s): "prepend enough zeros, if any needed, to make a group of 3 digits: 45-> 045" if len(s) % 3 != 0: numOfZerosToPrepend = 3 - (len(s) % 3) stringOfZerosToPrepend = "0" * numOfZerosToPrepend s = stringOfZerosToPrepend + s return s else: return s # example: illionNum of group "345" in "111345666000" is "2" def ComputeIllionNum(s): "find illionNum of group" illionNum = len(s) / 3 - 1 return illionNum #example: illionName of group "111" in "111345666000" is "billion" def illionNumToName(illionNum): "find illionName of group, given its illionNum" names = [ \ "", "thousand", "million", "billion", "trillion", "quadrillion", "quintillion", "sextillion", "septillion", "octillion", "nonillion", "decillion", "undecillion", "duodecillion", "tredecillion", "quattuordecillion", "quindecillion", "sexdecillion", "septendecillion", "octodecillion", "novemdecillion", "vigintillion"] illionName = names[illionNum] return illionName def extractGroup(s): "get group to work on" group = s[:3] return group def stripFrontZeros(r): "strip zeros at front of group, if any. E.g., 045 -> 45, 003 -> 3" if int(r) == 0: return "" while r[0] == "0": r = r[1:] return r def prepareGroupForPrinting(group): "use stripFrontZeros(group) on group" return stripFrontZeros(group) def main(): s = convertNToString(n) s = regularizeFirstGroup(s) a = "" # work on each group in turn, from first group to end group of s for index in range(0,len(s),3): illionNum = ComputeIllionNum(s[index:]) illionName = illionNumToName(illionNum) group = extractGroup(s[index:]) group = prepareGroupForPrinting(group) # don't print illionName if group is originally "000" if group == "": illionName = "" continue a = a + " " + group + " " + illionName + "," # remove final " ," or "," if a[-2:] == " ,": a = a[:-2] else: a = a[:-1] answer = a return answer if __name__=='__main__': n = 12008787987 print main() From rdm at rcblue.com Fri Aug 20 08:05:01 2004 From: rdm at rcblue.com (Dick Moores) Date: Fri Aug 20 08:05:15 2004 Subject: [Tutor] puzzled by main() In-Reply-To: <6.1.2.0.2.20040819223458.05416fc8@rcblue.com> References: <6.1.2.0.2.20040819223458.05416fc8@rcblue.com> Message-ID: <6.1.2.0.2.20040819230224.0508ed60@rcblue.com> Should I have attached intSpell.py as a text file? Dick Moores -------------- next part -------------- def convertNToString(n): "convert integer to string" return str(n) def regularizeFirstGroup(s): "prepend enough zeros, if any needed, to make a group of 3 digits: 45-> 045" if len(s) % 3 != 0: numOfZerosToPrepend = 3 - (len(s) % 3) stringOfZerosToPrepend = "0" * numOfZerosToPrepend s = stringOfZerosToPrepend + s return s else: return s # example: illionNum of group "345" in "111345666000" is "2" def ComputeIllionNum(s): "find illionNum of group" illionNum = len(s) / 3 - 1 return illionNum #example: illionName of group "111" in "111345666000" is "billion" def illionNumToName(illionNum): "find illionName of group, given its illionNum" names = [ \ "", "thousand", "million", "billion", "trillion", "quadrillion", "quintillion", "sextillion", "septillion", "octillion", "nonillion", "decillion", "undecillion", "duodecillion", "tredecillion", "quattuordecillion", "quindecillion", "sexdecillion", "septendecillion", "octodecillion", "novemdecillion", "vigintillion"] illionName = names[illionNum] return illionName def extractGroup(s): "get group to work on" group = s[:3] return group def stripFrontZeros(r): "strip zeros at front of group, if any. E.g., 045 -> 45, 003 -> 3" if int(r) == 0: return "" while r[0] == "0": r = r[1:] return r def prepareGroupForPrinting(group): "use stripFrontZeros(group) on group" return stripFrontZeros(group) def main(): s = convertNToString(n) s = regularizeFirstGroup(s) a = "" # work on each group in turn, from first group to end group of s for index in range(0,len(s),3): illionNum = ComputeIllionNum(s[index:]) illionName = illionNumToName(illionNum) group = extractGroup(s[index:]) group = prepareGroupForPrinting(group) # don't print illionName if group is originally "000" if group == "": illionName = "" continue a = a + " " + group + " " + illionName + "," # remove final " ," or "," if a[-2:] == " ,": a = a[:-2] else: a = a[:-1] answer = a return answer if __name__=='__main__': n = 12008787987 print main() From dyoo at hkn.eecs.berkeley.edu Fri Aug 20 08:12:54 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Aug 20 08:12:57 2004 Subject: [Tutor] scanf-1.0 tested and about to release In-Reply-To: Message-ID: > I thought it might make a nice weekend project to write scanf for > Python; it's nowhere near done yet, but it's sorta working... *grin* > > http://hkn.eecs.berkeley.edu/~dyoo/python/scanf.py Hi everyone, Ok, I've gotten everything implemented that I really wanted to implement. If anyone wants to play with this 'scanf' module before I formally announce it on comp.lang.python and PyPI, here's a link to the latest version: http://hkn.eecs.berkeley.edu/~dyoo/python/scanf/scanf-1.0.tar.gz I'll eventually write a web page for it, but my fingers are tired, so I'd better take a break. Here's some of what it does: ### >>> import scanf >>> scanf.sscanf("3.1415926 seventeen 42! Hut!", "%f %s %d") (3.1415926000000001, 'seventeen', 42) >>> from StringIO import StringIO >>> sampleFile = StringIO(""" ... 3, 17 ... 4, 19 ... 1, -5 ... 16, 25""") >>> scanf.fscanf(sampleFile, "%d, %d") (3, 17) >>> scanf.fscanf(sampleFile, "%d, %d") (4, 19) >>> scanf.fscanf(sampleFile, "%d, %d") (1, -5) >>> scanf.fscanf(sampleFile, "%d, %d") (16, 25) >>> scanf.fscanf(sampleFile, "%d, %d") Traceback (most recent call last): File "", line 1, in ? File "./scanf.py", line 350, in fscanf return bscanf(buffer, formatString) File "./scanf.py", line 362, in bscanf return parser(buffer) File "./scanf.py", line 523, in __call__ raise IncompleteCaptureError, (e, tuple(results)) scanf.IncompleteCaptureError: (, ()) ### At least this should help wean the Python beginners who were recovering C programmers in a past life. *grin* Hope this amuses someone out there! From dyoo at hkn.eecs.berkeley.edu Fri Aug 20 08:40:10 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Aug 20 08:40:13 2004 Subject: [Tutor] Re: Exceptions vs error codes In-Reply-To: <011d01c485b9$ae5693d0$6401a8c0@xp> Message-ID: On Thu, 19 Aug 2004, Alan Gauld wrote: > I thought perror was a Unix thing? It doesn't work under Windows, VMS > etc? But I've just tried it on XP and....it works! Hi Alan, Ah, I didn't think about that! I've always thought that perror() was standard; I can't imagine life without it. *grin* Let me check something... Here's what the man page on OS X says about perror()'s history: ### STANDARDS The perror() and strerror() functions conform to ISO/IEC 9899:1999 (``ISO C99''). The strerror_r() function conforms to IEEE Std 1003.1-2001 (``POSIX.1''). HISTORY The strerror() and perror() functions first appeared in 4.4BSD. The strerror_r() function was implemented in FreeBSD 4.4 by Wes Peters . ### Wow. Ok, so it looks like perror() was incorporated into Standard C, so that's probably why it works on XP now. But you're right: not all C systems have had it. > I've used perror for years on Unix but for some reason believed it > wasn't part of the C library but Unix only. > > Between curses, getch and perror I'm not having a good week! :-) No, no, I should be apologizing. I was wrong about the history there. By the way, though, it looks like the patch did get in, after all! https://sourceforge.net/tracker/?func=detail&atid=305470&aid=1011822&group_id=5470 http://cvs.sourceforge.net/viewcvs.py/python/python/dist/src/Modules/main.c?r1=1.82&r2=1.83 Good closure on the whole episode. *grin* The next version of Python should give a better error message when a mistyped file is passed in. Martin Loewis extended the patch's behavior to account for systems without the strerror() function. From dyoo at hkn.eecs.berkeley.edu Fri Aug 20 08:54:50 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Aug 20 08:54:55 2004 Subject: [Tutor] A suggestion! In-Reply-To: <001001c48641$644d4bc0$30e57218@basp.phub.net.cable.rogers.com> Message-ID: On Thu, 19 Aug 2004, Kevin wrote: > I have 2 websites gameweave.com, and vedorian.com. I wanted to create a > python site that was directed to games created with python. With a > message board where people can post questions and answers to python game > creations questions. Do you think that it would be kind of pointless, do > to the many python sites and mailing lists? Or are there any sites > dedicated to games created in python? Hi Kevin, You probably want to take advantage of the pygame folks: http://pygame.org/ http://www.pygame.org/info.shtml#links It might be worthwhile to contribute to their project, since they have a lot of mindshare among the Python game community. Best of wishes to you! From dyoo at hkn.eecs.berkeley.edu Fri Aug 20 09:05:37 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Aug 20 09:05:51 2004 Subject: [Tutor] Weird speed issue with mysql vs php In-Reply-To: <412536CF.60508@ezabel.com> Message-ID: On Thu, 19 Aug 2004, orbitz wrote: > Hello I have a situation where I'm rewriting a bunch of legacy PHP code > in python. This issue I'm having is my python program takes about 4.5 > hours to write and the PHP equivalent takes about 15 minutes. Hello! Ok, that's very odd. I think we need to see the code, both the PHP and the Python code if possible. The performance difference shouldn't be that striking. But since it is, let's see if we can find why. One thing that might be happening is the following: MySQLdb's default cursor type is a client-site cursor. People have in the past found that switching to a server side cursor type makes their database programs much faster. It looks something like: ### import MySQLdb.cursors import MySQLdb conn = MySQLdb.connect(db=mydatabase, cursorclass=MySQLdb.cursors.SSCursor) ### But from what you mentioned earlier: > The longest query is limited to 20 results all the time. the result set here is so small that I can't believe that the cursor type would contribute so much. So I think we'll need to look at the code closely. Can you post if up, or link it from a web site if it's large? Good luck to you! From dyoo at hkn.eecs.berkeley.edu Fri Aug 20 09:47:16 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Aug 20 09:47:19 2004 Subject: [Tutor] puzzled by main() In-Reply-To: <6.1.2.0.2.20040819223458.05416fc8@rcblue.com> Message-ID: On Thu, 19 Aug 2004, Dick Moores wrote: > I wrote intSpell.py for practice with integers, strings and modules. It > works fine by itself, but I'd like to figure out how to use it as a > module which I can import and use as intSpell(n). Hi Dick, Sounds good! Let's take a look. > Is my use of main() the problem? Or if not, what should I do? One thing to clarify here: a module can provide more than one function to the outside world, so Python has no idea that main() is function you mean when you say: ### import intSpell print intSpell.intSpell(42) ### With what you have right now, it looks more like: ### import intSpell print intSpell.main() ### which probably isn't what you want. So you have to, well, spell it out to Python. *grin* Rename the main() function to intSpell(). Also, modify it so it takes in 'n' as a parameter. Otherwise, we won't be able to say: intSpell.intSpell(n) for any given n. If you have more questions on this, please feel free to ask. Also, take a look at the first two sections of: http://www.python.org/doc/tut/node8.html The official tutorial has a good example with the "fibonacci numbers module" that's similar in spirit to what you're doing with a number-spelling module. Good luck! From python at bernardlebel.com Fri Aug 20 10:38:14 2004 From: python at bernardlebel.com (Bernard Lebel) Date: Fri Aug 20 10:38:26 2004 Subject: [Tutor] Testing network folder Message-ID: <007501c48691$09489c70$0d01a8c0@studioaction.local> Hello, I'm trying something very basic, but for the life of I'm getting what I expect. I try to test the existence of a directory located on a network computer, using a UNC path. import os os.path.exists( '\\\\machineName\\sharedFolder' ) Always return False. I'm on Windows XP, the target machine is a Windows machine, and there is a samba server between us. When I type \\machineName\sharedFolder in my Windows Explorer, well, I get there immediately. Is there anything I should be aware of? Thanks Bernard From python at bernardlebel.com Fri Aug 20 10:46:19 2004 From: python at bernardlebel.com (Bernard Lebel) Date: Fri Aug 20 10:46:30 2004 Subject: [Tutor] Testing network folder References: <007501c48691$09489c70$0d01a8c0@studioaction.local> Message-ID: <007a01c48692$2a2fcf20$0d01a8c0@studioaction.local> I should precise that if I use os.path.exists( '\\\\machineName\\sharedFolder\\anotherFolder' ) It works (returns true). I'm even more confused now! Bernard ----- Original Message ----- From: "Bernard Lebel" To: Sent: Friday, August 20, 2004 10:38 AM Subject: [Tutor] Testing network folder > Hello, > > I'm trying something very basic, but for the life of I'm getting what I > expect. > I try to test the existence of a directory located on a network computer, > using a UNC path. > > import os > os.path.exists( '\\\\machineName\\sharedFolder' ) > > Always return False. > I'm on Windows XP, the target machine is a Windows machine, and there is a > samba server between us. > When I type > \\machineName\sharedFolder > in my Windows Explorer, well, I get there immediately. > > Is there anything I should be aware of? > > > Thanks > Bernard > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From rdm at rcblue.com Fri Aug 20 12:44:20 2004 From: rdm at rcblue.com (Dick Moores) Date: Fri Aug 20 12:44:32 2004 Subject: [Tutor] puzzled by main() In-Reply-To: References: <6.1.2.0.2.20040819223458.05416fc8@rcblue.com> Message-ID: <6.1.2.0.2.20040820034220.04f83b50@rcblue.com> Danny Yoo wrote at 00:47 8/20/2004: >On Thu, 19 Aug 2004, Dick Moores wrote: > > > I wrote intSpell.py for practice with integers, strings and modules. It > > works fine by itself, but I'd like to figure out how to use it as a > > module which I can import and use as intSpell(n). > >Hi Dick, > >Sounds good! Let's take a look. > > > > Is my use of main() the problem? Or if not, what should I do? > > >One thing to clarify here: a module can provide more than one function to >the outside world, so Python has no idea that main() is function you mean >when you say: > >### >import intSpell >print intSpell.intSpell(42) >### > >With what you have right now, it looks more like: > >### >import intSpell >print intSpell.main() >### > >which probably isn't what you want. > > >So you have to, well, spell it out to Python. *grin* Rename the main() >function to intSpell(). Also, modify it so it takes in 'n' as a >parameter. Otherwise, we won't be able to say: > > intSpell.intSpell(n) > >for any given n. Thanks for clearing that up, Danny. After renaming main() it's working fine now with import intSpell intSpell.intSpell(n) Dick Moores From kent_johnson at skillsoft.com Fri Aug 20 13:06:17 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Aug 20 13:06:18 2004 Subject: [Tutor] Re: Exceptions vs error codes In-Reply-To: References: <011d01c485b9$ae5693d0$6401a8c0@xp> Message-ID: <6.1.0.6.0.20040820070332.0292da70@mail4.skillsoft.com> K&R second edition (the ANSI C version, published in 1988) includes perror(), errno and strerror(). Kent At 11:40 PM 8/19/2004 -0700, Danny Yoo wrote: >Ah, I didn't think about that! I've always thought that perror() was >standard; I can't imagine life without it. *grin* Let me check >something... Here's what the man page on OS X says about perror()'s >history: > > >### >STANDARDS > The perror() and strerror() functions conform to ISO/IEC 9899:1999 > (``ISO C99''). The strerror_r() function conforms to IEEE Std > 1003.1-2001 (``POSIX.1''). > >HISTORY > The strerror() and perror() functions first appeared in 4.4BSD. The > strerror_r() function was implemented in FreeBSD 4.4 by Wes Peters > . >### > >Wow. Ok, so it looks like perror() was incorporated into Standard C, so >that's probably why it works on XP now. But you're right: not all C >systems have had it. > > > I've used perror for years on Unix but for some reason believed it > > wasn't part of the C library but Unix only. > > > > Between curses, getch and perror I'm not having a good week! :-) > >No, no, I should be apologizing. I was wrong about the history there. > > > >By the way, though, it looks like the patch did get in, after all! > >https://sourceforge.net/tracker/?func=detail&atid=305470&aid=1011822&group_id=5470 >http://cvs.sourceforge.net/viewcvs.py/python/python/dist/src/Modules/main.c?r1=1.82&r2=1.83 > >Good closure on the whole episode. *grin* The next version of Python >should give a better error message when a mistyped file is passed in. >Martin Loewis extended the patch's behavior to account for systems without >the strerror() function. > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From pietenmariankaldewaij at planet.nl Fri Aug 20 13:35:43 2004 From: pietenmariankaldewaij at planet.nl (Piet Kaldewaij) Date: Fri Aug 20 13:38:17 2004 Subject: [Tutor] py to exe Message-ID: <000a01c486a9$d3d89cc0$9600000a@lan> Hello, I've a question about convertin .py-files to windows.exe-files. I installed Py2exe....... I choose an example named 'Boolean' to change in an exe.file This is the text of my setupfile: #setup.py from distutils.core import setup import py2exe setup(console=["boolean.py"]) Trying to compile I see this in DOS: C:\>C:\PYTHON23\python setup.py py2exe File "setup.py", line 1 Python 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit (Intel)] on win 32 ^ SyntaxError: invalid syntax Have you any idea the compiler doesn't work? greetings,see you.................... -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040820/ebee6c06/attachment.html From flaxeater at yahoo.com Fri Aug 20 16:08:36 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Fri Aug 20 16:08:39 2004 Subject: [Tutor] Process Taking more than 10% Message-ID: <20040820140836.99297.qmail@web52603.mail.yahoo.com> It just occurred to me that there must be a command line process monitor and terminator. I found one http://www.beyondlogic.org/solutions/processutil/processutil.htm It would not be to big a problem to moniter and parse it's output and aggregate the averages. Alan Gauld wrote: >>>There are easy ways to do this on both Unix and Windows and >>>there are harder ways. But if its only one OS we might as >>>well stick to the easy ways... :-) >>> >>> > > > >>I think on linux you would use popen and ps, >> >> > >Nope, the easy way is to use ps and awk... > > > >>but how is it done on windows? >> >> > >Assuming NT/W2K/XP >Open Task Manager, look at processes and sort by CPU... :-) > >In both cases Python is the harder route. Right tool for >the job... ;-) > >Alan G. >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From python_newbie at vedorian.com Fri Aug 20 16:16:19 2004 From: python_newbie at vedorian.com (Kevin) Date: Fri Aug 20 16:16:30 2004 Subject: [Tutor] Useing Functions Message-ID: <000c01c486c0$4385c6e0$30e57218@basp.phub.net.cable.rogers.com> Is it better to put everything in a def function, so that instead of having to rewrite it all out over and over youc an just reuse the function? ie: a def function that asks if you would like to conitue and to answer yes or no. so that you can use it many times if you need to? Thanks Kevin --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.740 / Virus Database: 494 - Release Date: 8/16/04 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040820/a9845bdb/attachment.html From mhansen at cso.atmel.com Fri Aug 20 16:45:14 2004 From: mhansen at cso.atmel.com (Mike Hansen) Date: Fri Aug 20 16:45:05 2004 Subject: [Tutor] Komodo Message-ID: <41260E7A.6080407@cso.atmel.com> I just upgraded from Activestate's Komodo 2.5.2 to 3.0. I really like the new code browser. For Python programs it shows all the functions, global variables, and imports in one pane/frame. When you click on a function in that pane/frame, the doc string for the function appears in another pane/frame and the editor jumps to that function. Very cool. I think Scite does some of this, but I don't know if Scite does code completion or syntax checking. Anyone know? Speaking of syntax checking, is there a tool that checks your syntax in Python without having to run the code. In Perl, you can do Perl -c yourprogram.pl, and it will give you the syntax errors. Although Komodo has syntax checking built in, I sometimes do some Python development on OSX. There doesn't seem to be an OSX port of Komodo, so I'd need something else to check the syntax of a Python program. Mike From kent_johnson at skillsoft.com Fri Aug 20 17:05:01 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Aug 20 17:05:19 2004 Subject: [Tutor] Useing Functions In-Reply-To: <000c01c486c0$4385c6e0$30e57218@basp.phub.net.cable.rogers. com> References: <000c01c486c0$4385c6e0$30e57218@basp.phub.net.cable.rogers.com> Message-ID: <6.1.0.6.0.20040820110211.02a04458@mail4.skillsoft.com> Yes. Definitely. If you have repeated code, putting it in a function is usually a good choice. It reduces duplication, makes the rest of the code easier to read and makes it easy to change the (no longer) repeated code if necessary. Kent At 10:16 AM 8/20/2004 -0400, Kevin wrote: >Is it better to put everything in a def function, so that instead of >having to rewrite it all out over and over youc an just reuse the >function? ie: a def function that asks if you would like to conitue and to >answer yes or no. so that you can use it many times if you need to? > >Thanks >Kevin > > >--- >Outgoing mail is certified Virus Free. >Checked by AVG anti-virus system >(http://www.grisoft.com). >Version: 6.0.740 / Virus Database: 494 - Release Date: 8/16/04 >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From klas.martelleur at telia.com Fri Aug 20 17:59:53 2004 From: klas.martelleur at telia.com (Klas Marteleur) Date: Fri Aug 20 17:48:51 2004 Subject: [Tutor] Re: .pyw and .py on a window$ box SOLVED In-Reply-To: <01af01c48667$6cc17df0$6401a8c0@xp> References: <200408191808.24484.klas.martelleur@telia.com> <200408191818.18862.klas.martelleur@telia.com> <01af01c48667$6cc17df0$6401a8c0@xp> Message-ID: <200408201759.53140.klas.martelleur@telia.com> I was thinking "How do i normaly solve this kind of problems on a windows box..." hmm... a couple of reboots and a couple of installs / reinstalls. However it seemd to work this time as well :) i have no idea what went wrong in the first place.... Klas fredagen den 20 augusti 2004 05.40 skrev Alan Gauld: > > i need to clearify one sentence in my previous mail > > > > ...When i run createEbomGUI.pyw" from IDLE it workes as > > expected..... > > You mean you open the file in an IDLE edit window > and then hit F5? > > > > If i rename the program to "createEbomGUI.py", and "dubble click" > > on the > > > > file it also workes as expected (except from that a dos window > > appear). > > > > But when i "dubble click" on the "createEbomGUI.pyw", It brings > > up the gui > > > > alright with no dos window but the program wont work (I get no > > respone when > > > > i "push the buttons"). > > The only thing I can think of is that you still have some raw_input() > or input() statements in your program that are trying to read input > from the nonn existent dos box? > > Could it be something like that? > > Alan G From pythonTutor at venix.com Fri Aug 20 17:56:28 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Fri Aug 20 17:57:33 2004 Subject: [Tutor] Komodo In-Reply-To: <41260E7A.6080407@cso.atmel.com> References: <41260E7A.6080407@cso.atmel.com> Message-ID: <1093017387.2291.37.camel@laptop.venix.com> Importing your code checks the syntax. It does actually execute your module, but if the working code is protected by if __name__ == '__main__': then your functions and classes will not get invoked. pychecker is included with the recent Python distributions. It checks your code for inconsistent usage. The old C lint utility did the same for C programs before the C language syntax was tightened to allow the compiler to catch most problems. On Fri, 2004-08-20 at 10:45, Mike Hansen wrote: > I just upgraded from Activestate's Komodo 2.5.2 to 3.0. I really like > the new code browser. For Python programs it shows all the functions, > global variables, and imports in one pane/frame. When you click on a > function in that pane/frame, the doc string for the function appears in > another pane/frame and the editor jumps to that function. Very cool. I > think Scite does some of this, but I don't know if Scite does code > completion or syntax checking. Anyone know? > > Speaking of syntax checking, is there a tool that checks your syntax in > Python without having to run the code. In Perl, you can do Perl -c > yourprogram.pl, and it will give you the syntax errors. Although Komodo > has syntax checking built in, I sometimes do some Python development on > OSX. There doesn't seem to be an OSX port of Komodo, so I'd need > something else to check the syntax of a Python program. > > Mike > _______________________________________________ > 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 flaxeater at yahoo.com Fri Aug 20 19:34:49 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Fri Aug 20 19:34:52 2004 Subject: [Tutor] Useing Functions Message-ID: <20040820173449.60804.qmail@web52608.mail.yahoo.com> Use Functions. Very Very Important, it's the product of millions of years of evolution. So yes use functions. Kevin wrote: > Is it better to put everything in a def function, so that instead of > having to rewrite it all out over and over youc an just reuse the > function? ie: a def function that asks if you would like to conitue > and to answer yes or no. so that you can use it many times if you need to? > > Thanks > Kevin > > > --- > Outgoing mail is certified Virus Free. > Checked by AVG anti-virus system (http://www.grisoft.com). > Version: 6.0.740 / Virus Database: 494 - Release Date: 8/16/04 > >------------------------------------------------------------------------ > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > _______________________________ Do you Yahoo!? Win 1 of 4,000 free domain names from Yahoo! Enter now. http://promotions.yahoo.com/goldrush From python at bernardlebel.com Fri Aug 20 19:35:01 2004 From: python at bernardlebel.com (Bernard Lebel) Date: Fri Aug 20 19:35:10 2004 Subject: [Tutor] Remote processes Message-ID: <018001c486dc$06470020$0d01a8c0@studioaction.local> Hello, Is there any way to launch and kill processes on remote computers using Python? I'd like to build an utility to do just that (to control my renderfarm). The only I found so far is os.path.spawn*( ), wich create a local process. Thanks Bernard From kent_johnson at skillsoft.com Fri Aug 20 19:50:03 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Aug 20 19:50:27 2004 Subject: [Tutor] Useing Functions In-Reply-To: <20040820173449.60804.qmail@web52608.mail.yahoo.com> References: <20040820173449.60804.qmail@web52608.mail.yahoo.com> Message-ID: <6.1.0.6.0.20040820134827.028e9270@mail4.skillsoft.com> Yes, I think functions first appeared about the time that programs first started to walk upright :-) Kent At 10:34 AM 8/20/2004 -0700, Chad Crabtree wrote: >Use Functions. Very Very Important, it's the product of millions of >years of evolution. So yes use functions. > >Kevin wrote: > > > Is it better to put everything in a def function, so that instead >of > > having to rewrite it all out over and over youc an just reuse the > > function? ie: a def function that asks if you would like to conitue > > > and to answer yes or no. so that you can use it many times if you >need to? > > > > Thanks > > Kevin > > > > > > --- > > Outgoing mail is certified Virus Free. > > Checked by AVG anti-virus system (http://www.grisoft.com). > > Version: 6.0.740 / Virus Database: 494 - Release Date: 8/16/04 > > > >------------------------------------------------------------------------ > > > >_______________________________________________ > >Tutor maillist - Tutor@python.org > >http://mail.python.org/mailman/listinfo/tutor > > > > > > > > >_______________________________ >Do you Yahoo!? >Win 1 of 4,000 free domain names from Yahoo! Enter now. >http://promotions.yahoo.com/goldrush >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From bgailer at alum.rpi.edu Fri Aug 20 19:57:20 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri Aug 20 19:53:48 2004 Subject: [Tutor] Useing Functions In-Reply-To: <20040820173449.60804.qmail@web52608.mail.yahoo.com> References: <20040820173449.60804.qmail@web52608.mail.yahoo.com> Message-ID: <6.1.0.6.0.20040820115552.026d3c88@mail.mric.net> At 11:34 AM 8/20/2004, Chad Crabtree wrote: >Use Functions. Very Very Important, it's the product of millions of >years of evolution. So yes use functions. And also learn object-oriented programming so you can take advantage of Python classes. Skillful use of classes and functions makes programming great. Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From jeff at ccvcorp.com Fri Aug 20 20:28:40 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri Aug 20 20:28:07 2004 Subject: [Tutor] Testing network folder In-Reply-To: <007a01c48692$2a2fcf20$0d01a8c0@studioaction.local> References: <007501c48691$09489c70$0d01a8c0@studioaction.local> <007a01c48692$2a2fcf20$0d01a8c0@studioaction.local> Message-ID: <412642D8.5060704@ccvcorp.com> Bernard Lebel wrote: > I should precise that if I use > os.path.exists( '\\\\machineName\\sharedFolder\\anotherFolder' ) > > It works (returns true). > I'm even more confused now! > > ----- Original Message ----- > From: "Bernard Lebel" > >>I'm trying something very basic, but for the life of I'm getting what I >>expect. >>I try to test the existence of a directory located on a network computer, >>using a UNC path. >> >>import os >>os.path.exists( '\\\\machineName\\sharedFolder' ) >> >>Always return False. This is one of the tricky corners of Windows networking. The problem seems to be that '\\machineName\shardFolder' isn't really a file path, quite. You're naming a UNC share, which is a much closer equivalent to a drive letter than to a directory. Windows will *treat* it as a directory, in most cases, but not always... Jeff Shannon Technician/Programmer Credit International From python at pointcontrol.com Fri Aug 20 20:29:32 2004 From: python at pointcontrol.com (python@pointcontrol.com) Date: Fri Aug 20 20:29:36 2004 Subject: [Tutor] Installing wxPython on fresh Fedora box - failed dependency Message-ID: <50048.65.4.31.86.1093026572.squirrel@www.pointcontrol.com> Greetings. I'm new to both Linux and Python, and trying to kill two birds with one stone by setting up a Python development laptop using Fedora. (Glutton for punishment?) The Fedora Core 1 installation is fresh, from .iso images I downloaded this week from a mirror of the Redhat site. I made sure I had it install all the development tools during the install (using the GUI installer). The first thing I did (after setting up users) was go to python.org and get these Python version 2.3.4 RPMs: python2.3-2.3.4-3pydotorg.i386.rpm python2.3-devel-2.3.4-3pydotorg.i386.rpm python2.3-docs-2.3.4-3pydotorg.i386.rpm python2.3-tkinter-2.3.4-3pydotorg.i386.rpm python2.3-tools-2.3.4-3pydotorg.i386.rpm These reported no errors using rpm -ivh *.rpm from a root login. Next, I went to wxpython.org to get these RPMs: wxPythonGTK2-py2.3-2.4.2.4-1.src.rpm wxPythonGTK-devel-2.4.2.4-1.i386.rpm wxPythonGTK-py2.3-2.4.2.4-1.i386.rpm wxPythonGTK-py2.3-2.4.2.4-1.src.rpm Note that I'm getting version 2.4.2.4 because my intent is to use Boa Constructor, and it is not yet compatible with the newer wxPython release. But when I tried to install these, wxPythonGTK-py2.3-2.4.2.4-1.i386.rpm (the third one in the above list) gave me the error: Error: Failed dependencies: libstdc++-libc6.2-2.so.3 is needed by wxPythonGTK-py2.3-2.4.2.4-1 My problem is that I'm new enough with Linux that, while I have a sematic understanding of the error message, I have no idea how to resolve it. I had thought that all the necessary libraries would have been installed when I put Fedora on the box, or at least when I upgraded my Python install. Is it possible that something just got missed in the Fedora install? At this point, if I wipe the laptop (again) and reinstall, I've lost nothing but time (and that's to be expected in this kind of journey anyway). Any suggestions as to my best course of action would be most appreciated. -- b.r.t. From jeff at ccvcorp.com Fri Aug 20 20:40:30 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri Aug 20 20:39:54 2004 Subject: [Tutor] Useing Functions In-Reply-To: <20040820173449.60804.qmail@web52608.mail.yahoo.com> References: <20040820173449.60804.qmail@web52608.mail.yahoo.com> Message-ID: <4126459E.2080306@ccvcorp.com> Chad Crabtree wrote: > Use Functions. Very Very Important, it's the product of millions of > years of evolution. So yes use functions. At work, I do a lot of programming in a very old dialect of Basic that doesn't *have* proper functions, or any concept of variable scope. (You can create "external subroutines", a separate program file that acts as a function, and which can only return values through the use of its (by-reference) parameters, but that's fairly awkward.) After years of working in an environment where a longish program is loaded with gotos, gosubs, and page after page of deeply nested if/then/else statements... Trust me, you *want* to use functions as much as practical. Oh, how I wish I could use functions here! (Let's be honest, I wish I could use Python instead of Basic, but somehow I don't expect a port of Python to the Pick database virtual OS anytime soon... :P ) Anyhow, yes. Functions good. OO and classes even better. Use them and appreciate them, for life without them is ugly and scary. Jeff Shannon Technician/Programmer Credit International From dyoo at hkn.eecs.berkeley.edu Fri Aug 20 20:40:40 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Aug 20 20:40:45 2004 Subject: [Tutor] Remote processes In-Reply-To: <018001c486dc$06470020$0d01a8c0@studioaction.local> Message-ID: On Fri, 20 Aug 2004, Bernard Lebel wrote: > Is there any way to launch and kill processes on remote computers using > Python? I'd like to build an utility to do just that (to control my > renderfarm). > > The only I found so far is os.path.spawn*( ), wich create a local > process. Hi Bernard, One approach you may want to consider is Remote Procedure Call (RPC). This involves writing a small server to do the work, and a client to get the server to do the work. *grin* Your server can run on the remote computers, and all it needs to do is accept and do what the request asks. Your server can then call os.path.spawn(), given information in the request. You can do this kind of remote procedure call through several mechanisms. One of the easier ones is in the xmlrpc libraries: http://www.python.org/doc/lib/module-xmlrpclib.html http://www.python.org/doc/lib/module-SimpleXMLRPCServer.html You may want to also look into the Twisted Python project: they provide the tools for writing good servers: http://www.twistedmatrix.com/ Their tutorial on building a "finger" utility is wondefully simple (well, at least the first few chapters! *grin*): http://www.twistedmatrix.com/documents/current/howto/tutorial/index You can probably adjust it from doing 'finger' to running renderfarm jobs. Twisted also has mechanisms for handling security: you may not want just any person to get your remote computers to run jobs without the proper credentials. Best of wishes to you! From orbitz at ezabel.com Fri Aug 20 20:55:52 2004 From: orbitz at ezabel.com (orbitz) Date: Fri Aug 20 20:55:59 2004 Subject: [Tutor] Remote processes In-Reply-To: <018001c486dc$06470020$0d01a8c0@studioaction.local> References: <018001c486dc$06470020$0d01a8c0@studioaction.local> Message-ID: <41264938.3020100@ezabel.com> You'll need some sort of server/client setup. Check out twisted (google for twistedmatrix), it provides RPC stuff you can use, and provides a powerful/fast/easy to use series of classes/api to create your own protocol. Bernard Lebel wrote: >Hello, > >Is there any way to launch and kill processes on remote computers using >Python? I'd like to build an utility to do just that (to control my >renderfarm). > >The only I found so far is os.path.spawn*( ), wich create a local process. > > >Thanks >Bernard > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > From alan.gauld at blueyonder.co.uk Fri Aug 20 21:11:40 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Aug 20 21:10:54 2004 Subject: [Tutor] puzzled by main() References: <6.1.2.0.2.20040819223458.05416fc8@rcblue.com> <6.1.2.0.2.20040819230224.0508ed60@rcblue.com> Message-ID: <003001c486e9$865b9f70$6401a8c0@xp> > Should I have attached intSpell.py as a text file? Well I prefer it, but others may not. The module looks fine to me. What makes you think you cannot uise it as a module? Have you tried? What happened? Alan G. From alan.gauld at blueyonder.co.uk Fri Aug 20 21:21:01 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Aug 20 21:20:15 2004 Subject: [Tutor] Re: Exceptions vs error codes References: <011d01c485b9$ae5693d0$6401a8c0@xp> <6.1.0.6.0.20040820070332.0292da70@mail4.skillsoft.com> Message-ID: <005801c486ea$d4cdc1a0$6401a8c0@xp> > K&R second edition (the ANSI C version, published in 1988) includes > perror(), errno and strerror(). > Yes, I really have no good reason for ever doubting its existence on Windows. I just checked and even my old MS DOS Mix C compiler (1986?) supported it (albeit with a limited set of error strings) and both my Borland and Microsoft compilers (c1992-5) have had perror() since Windows 3 appeared at least. I really don't know why I never used it on Windows except that the Windows API has its own file opening/closing functions and thus its own error reporting calls. Maybe I just assumed that since they were there perror() wasn't... Who knows... But entirely my error (no pun intended!). Alan G. From alan.gauld at blueyonder.co.uk Fri Aug 20 21:22:13 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Aug 20 21:21:26 2004 Subject: [Tutor] Process Taking more than 10% References: <20040820140836.99297.qmail@web52603.mail.yahoo.com> Message-ID: <005f01c486ea$ff84a990$6401a8c0@xp> Or top, this is available on both *nix and Windows. There is even wintop for a slightly GUIified version. Alan G ----- Original Message ----- From: "Chad Crabtree" To: "Alan Gauld" Cc: Sent: Friday, August 20, 2004 3:08 PM Subject: Re: [Tutor] Process Taking more than 10% > It just occurred to me that there must be a command line process > monitor > and terminator. I found one > http://www.beyondlogic.org/solutions/processutil/processutil.htm > It would not be to big a problem to moniter and parse it's output and > > aggregate the averages. > > Alan Gauld wrote: > > >>>There are easy ways to do this on both Unix and Windows and > >>>there are harder ways. But if its only one OS we might as > >>>well stick to the easy ways... :-) > >>> > >>> > > > > > > > >>I think on linux you would use popen and ps, > >> > >> > > > >Nope, the easy way is to use ps and awk... > > > > > > > >>but how is it done on windows? > >> > >> > > > >Assuming NT/W2K/XP > >Open Task Manager, look at processes and sort by CPU... :-) > > > >In both cases Python is the harder route. Right tool for > >the job... ;-) > > > >Alan G. > >_______________________________________________ > >Tutor maillist - Tutor@python.org > >http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > > > __________________________________________________ > Do You Yahoo!? > Tired of spam? Yahoo! Mail has the best spam protection around > http://mail.yahoo.com > > From alan.gauld at blueyonder.co.uk Fri Aug 20 21:24:02 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Aug 20 21:23:14 2004 Subject: [Tutor] Useing Functions References: <000c01c486c0$4385c6e0$30e57218@basp.phub.net.cable.rogers.com> Message-ID: <006701c486eb$4083ea00$6401a8c0@xp> > Is it better to put everything in a def function, so that > instead of having to rewrite it all out over and over > you can just reuse the function? Yes, if you can reuse it put it in a function, thats largely what they are there for. Not only easier to use but easier to fix too - only one place to change... Then collect related functions in a file and you have a module that you can reuse across projects too. Alan G. From alan.gauld at blueyonder.co.uk Fri Aug 20 21:26:19 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Aug 20 21:25:31 2004 Subject: [Tutor] Komodo References: <41260E7A.6080407@cso.atmel.com> Message-ID: <006e01c486eb$91d1d160$6401a8c0@xp> > think Scite does some of this, but I don't know if Scite does code > completion or syntax checking. Anyone know? NOt sure about Scite but Pythonwin (with the same scintilla engine) certainly does. > Speaking of syntax checking, is there a tool that checks your syntax in > Python without having to run the code. In Perl, you can do Perl -c I believe there is a pylint project on sourceforge which has a python tool for strict checking of python code. Named after the C checker lint... Alan G From vicki at thepenguin.org Fri Aug 20 21:26:13 2004 From: vicki at thepenguin.org (vicki@thepenguin.org) Date: Fri Aug 20 21:28:30 2004 Subject: [Tutor] executing a function in a different file and class Message-ID: <26269.206.53.226.235.1093029973.squirrel@206.53.226.235> Okay, I have written a logging function to allow me to pass a string and a mask to determine which places to log to. The LogMessage function is not contained within a class and looks like this: def LogMessage(self, message, whichfiles): '''This function logs a message which is passed into it. The whichfiles variable determines to where the message gets logged: doswindow, outputfile, outputwin.''' #LOG_STDIO, LOG_OUTFILE, LOG_GUI = (4,2,1) if whichfiles == 0: LogMessage("Why did you call this function if you weren't going to log to anywhere?",LOG_STDIO|LOG_GUI) if whichfiles & LOG_STDIO: print message if whichfiles & LOG_OUTFILE: outfile.write(message) if whichfiles & LOG_GUI: self.outputbox.SetLabel(message) If I call this function from anywhere within a class in the same file, I can use it fine. I created a second file with a function defined in it, and I can't call the LogMessage function from there. I get the following error: Traceback (most recent call last): File "F:\wxComTool1.1.py", line 2591, in CommandCallback self.SendCommand(self.selection, self.arguments) File "F:\wxComTool1.1.py", line 308, in SendCommand self.ProcessCommand(command, arguments) File "F:\wxComTool1.1.py", line 2064, in ProcessCommand mydata.ParseTRD(self,port) File "F:\mydata.py", line 87, in ParseTRD LogMessage(self,"Sent " +byte+"\n",LOG_STDIO|LOG_OUTFILE) NameError: global name 'LogMessage' is not defined The new function looks like: import wx, re, string, time def ParseTRD(self, port): [SNIP] LogMessage(self,"Sent " +byte+"\n",LOG_STDIO|LOG_OUTFILE) I am very weak on my OO understanding, or actually on my functional understanding since I understand the concepts pretty well. Can I not pass the LogMessage function in somehow? What is the appropriate way to do this? Vicki "A pessimist sees the difficulty in every opportunity; an optimist sees the opportunity in every difficulty." -- Winston Churchill From jeff at ccvcorp.com Fri Aug 20 21:34:18 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri Aug 20 21:33:43 2004 Subject: [Tutor] executing a function in a different file and class In-Reply-To: <26269.206.53.226.235.1093029973.squirrel@206.53.226.235> References: <26269.206.53.226.235.1093029973.squirrel@206.53.226.235> Message-ID: <4126523A.5050708@ccvcorp.com> vicki@thepenguin.org wrote: > Okay, I have written a logging function to allow me to pass a string and a > mask to determine which places to log to. The LogMessage function is not > contained within a class and looks like this: > [...] > If I call this function from anywhere within a class in the same file, I > can use it fine. I created a second file with a function defined in it, > and I can't call the LogMessage function from there. You just need to import the file that LogMessage is in. Say that LogMessage is in a file called MyLog.py. Now, in another file that you want to use it in, you can simply do this: import MyLog # .... Mylog.LogMessage("Foo!") Hope that helps... Jeff Shannon Technician/Programmer Credit International From python_newbie at vedorian.com Fri Aug 20 21:36:48 2004 From: python_newbie at vedorian.com (Kevin) Date: Fri Aug 20 21:36:56 2004 Subject: [Tutor] Useing Functions References: <000c01c486c0$4385c6e0$30e57218@basp.phub.net.cable.rogers.com> <006701c486eb$4083ea00$6401a8c0@xp> Message-ID: <001601c486ed$0904d7e0$30e57218@basp.phub.net.cable.rogers.com> I mande a simple module called define.py just to try it out. However when put import defines in the main file I get an error: Traceback (most recent call last): File "C:\WINDOWS\Desktop\files\python\test.py", line 5, in ? YesNo(x, y) NameError: name 'YesNo' is not defined however when I put from define import YesNo it works fine. Why will it not work in the ladder half? ----- Original Message ----- From: "Alan Gauld" To: "Kevin" ; "Python" Sent: Friday, August 20, 2004 3:24 PM Subject: Re: [Tutor] Useing Functions > > > Is it better to put everything in a def function, so that > > instead of having to rewrite it all out over and over > > you can just reuse the function? > > Yes, if you can reuse it put it in a function, thats largely > what they are there for. Not only easier to use but easier to > fix too - only one place to change... > > Then collect related functions in a file and you have a module > that you can reuse across projects too. > > Alan G. > > --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.740 / Virus Database: 494 - Release Date: 8/16/04 From Francis.Moore at shaws.co.uk Tue Aug 10 10:45:48 2004 From: Francis.Moore at shaws.co.uk (Francis Moore) Date: Fri Aug 20 21:38:21 2004 Subject: [Tutor] Source code samples Message-ID: <6081EBC21D52F744B484088BBBE665C32EEBA4@sbserver.shaws.local> From: Lennart Andersen [mailto:lennart@rogers.com] > Where can I get a really good book on how to read source code You might want to try: Code Reading Volume 1; The Open Source perspective Author: Diomidis Spinellis, Publisher: Addison-Wesley ISBN: 0201799405 I think it's C-based rather than Python-based, but it might still be what you're after. HTH, Francis. CONFIDENTIALITY NOTICE This communication contains information which is confidential and may also be privileged. It is for the exclusive use of the intended recipient(s). If you are not the intended recipient(s) please note that any distribution, copying or use of this communication or the information in it is strictly prohibited. If you have received this communication in error please notify us by e-mail or by telephone (+44(0) 1322 621100) and then delete the e-mail and any copies of it. This communication is from Shaw & Sons Limited whose registered office is at Shaway House, 21 Bourne Park, Bourne Road, Crayford, Kent DA1 4BZ. The views expressed in this communication may not be the views held by Shaw & Sons Limited. This message has been checked for all known viruses by McAfee VirusScan. From dprestes at atlas.ucpel.tche.br Fri Aug 13 03:16:10 2004 From: dprestes at atlas.ucpel.tche.br (Diego Galho Prestes) Date: Fri Aug 20 21:38:28 2004 Subject: [Tutor] How to call a method when have classes inside another class Message-ID: <1092359770.6538.3.camel@rossum> Hi! I have this case but dont know how to call it... def Class1: def someMethod(): pass def Class2: def otherMethod(): ???call of someMethod??? I want to call someMethod in otherMethod. How can I do this? Diego From adsl5lcq at tpg.com.au Fri Aug 13 05:16:16 2004 From: adsl5lcq at tpg.com.au (Glen Wheeler) Date: Fri Aug 20 21:38:32 2004 Subject: [Tutor] Python spawning extra processes References: <305be88204081220003f5378f1@mail.gmail.com> Message-ID: <075701c480e3$e704cec0$2614f5dc@GrOpteron> Hi Britt, I believe this is something to do with Tkinter. Try running the program from the command prompt. I myself never use my IDE (win32all for me) to run programs, always scripts (/batch) and always the command prompt. When I did alot of Tkinter programming (a few years ago now...may have memory issues ;) I recall that terminating the program by CTRL+ALT+DEL still left a ghost process. This is why I suggest execution from the shell. HTH, Glen PS. I'm using a different account to post this because my other e-mail is dying...hope this does not offend the list admins. ----- Original Message ----- From: "Britt Green" To: Sent: Friday, August 13, 2004 1:00 PM Subject: [Tutor] Python spawning extra processes > Hey all! > > I've encountered something odd that I'm hoping someone can clarify for > me. I've coded a very simple chat server in Python, using the Twisted > libraries. From Windows XP, I launch it from Idle and do my thing. I > then quit it by pressing CTRL-C in the Python shell. > > If I then go into my Task Manager, I see that the pythonw.exe process > started by the program is still there. Executing the script creates > another process that doesn't go away when I terminate the program. I > noticed this today when I saw I had 30+ pythonw.exe processes going! > > I'm wondering what's causing this and how to get it to stop. > > Cheers! > > Britt > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From misterstaypuff at yahoo.com Sat Aug 14 09:21:37 2004 From: misterstaypuff at yahoo.com (Joe Music) Date: Fri Aug 20 21:38:35 2004 Subject: [Tutor] overloading object for printing? Message-ID: <20040814072137.27950.qmail@web51004.mail.yahoo.com> Is there some equivalent in Python to the to_s() method in Java which a class can overload in order to customize the output of an object? Thanks. _______________________________ Do you Yahoo!? Express yourself with Y! Messenger! Free. Download now. http://messenger.yahoo.com From alan.gauld at blueyonder.co.uk Fri Aug 20 05:48:06 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Aug 20 21:38:38 2004 Subject: [Tutor] Process Taking more than 10% References: <20040819042207.GA15047@qwestip.net><015c01c485c2$843211c0$6401a8c0@xp> <20040819171415.GB15047@qwestip.net> Message-ID: <01b401c48668$80b2f8b0$6401a8c0@xp> > > > processes that are taking more than 10% and then find the user who > > Solaris SPARC > In that case I'd use os.popen("ps -") and then write a function to split the results to extract the CPU. Use that in a list comprehension to filter out the values you want. Pseudo code: ------------- def getCPU(aLine): return float(line.split[N]) processes = os.popen("ps command").read() highCPU = [pid for pid in processes if getCCPU(pid) > 10] print highCPU ------------- Of course you can do the same thing in a single shell line using awk... $ ps - | awk "{if $N > 10 print $0}" HTH, Alan G From vicki at thepenguin.org Fri Aug 20 21:42:53 2004 From: vicki at thepenguin.org (vicki@thepenguin.org) Date: Fri Aug 20 21:45:17 2004 Subject: [Tutor] executing a function in a different file and class In-Reply-To: <4126523A.5050708@ccvcorp.com> References: <26269.206.53.226.235.1093029973.squirrel@206.53.226.235> <4126523A.5050708@ccvcorp.com> Message-ID: <57301.206.53.226.235.1093030973.squirrel@206.53.226.235> > vicki@thepenguin.org wrote: >> Okay, I have written a logging function to allow me to pass a string and >> a >> mask to determine which places to log to. The LogMessage function is not >> contained within a class and looks like this: >> [...] >> If I call this function from anywhere within a class in the same file, I >> can use it fine. I created a second file with a function defined in it, >> and I can't call the LogMessage function from there. > > You just need to import the file that LogMessage is in. > > Say that LogMessage is in a file called MyLog.py. Now, in another > file that you want to use it in, you can simply do this: > > import MyLog > > # .... > > Mylog.LogMessage("Foo!") > > Hope that helps... Okay Jeff, I thought of this, but it seemed wrong since I would be importing the original file that contains the function which is calling the function which is attempting to log (in the house that Jack built). Let me be more clear. I have file A which contains most of the code for my program and file B which only contains the new function. Code in file A calls the function in file B which then calls the Logging function which is in file A. I could just move the new function into file A eliminating the whole problem, but I would rather learn the proper way to do this. I think part of the problem is that this particular implementation does not lend itself to OOP principles. --Vicki From dyoo at hkn.eecs.berkeley.edu Fri Aug 20 21:53:12 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Aug 20 21:53:19 2004 Subject: [Tutor] Useing Functions In-Reply-To: <4126459E.2080306@ccvcorp.com> Message-ID: On Fri, 20 Aug 2004, Jeff Shannon wrote: > Chad Crabtree wrote: > > > Use Functions. Very Very Important, it's the product of millions of > > years of evolution. So yes use functions. > > At work, I do a lot of programming in a very old dialect of Basic that > doesn't *have* proper functions, or any concept of variable scope. > (You can create "external subroutines", a separate program file that > acts as a function, and which can only return values through the use of > its (by-reference) parameters, but that's fairly awkward.) [some text cut] > Oh, how I wish I could use functions here! Hi Jeff, Hmmm! Sorry for taking this in an askew direction, but how difficult would it be to write a preprocessor? You could write your programs in a kind of superset of Basic that has subroutines. This superset wouldn't be directly executable, but would be input into a preprocessor. This preprocessor could then transform that super-Basic back into regular Basic, and handle all the awkwardness of subroutine linkage, behind the scenes. One of the powerful ideas of computation is that programs can themselves produce other programs. Since Basic is such a basic language, the syntax processing involved in this might not even be too hideous. Is there a specification on this old Basic dialect that we could look at? Just out of curiosity, of course... *grin* Talk to you later! From dyoo at hkn.eecs.berkeley.edu Fri Aug 20 21:59:32 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Aug 20 21:59:35 2004 Subject: [Tutor] overloading object for printing? In-Reply-To: <20040814072137.27950.qmail@web51004.mail.yahoo.com> Message-ID: On Sat, 14 Aug 2004, Joe Music wrote: > Is there some equivalent in Python to the to_s() method in Java which a > class can overload in order to customize the output of an object? > Thanks. Hi Joe, Yes, there is a builtin function called str() that takes anything, and returns a string representation. In Python, str() works on everything, since all things are objects, even "primitive" things like integers: ### >>> str(42) '42' >>> str([1, 2, 3]) '[1, 2, 3]' >>> class Foo: ... pass ... >>> f = Foo() >>> str(f) '<__main__.Foo instance at 0x402d382c>' ### Classes that define an __str__() method can customize the way that they react to str(): ### >>> class Bar: ... def __str__(self): ... return "Bar bar!" ... >>> b = Bar() >>> str(b) 'Bar bar!' ### See: http://www.python.org/doc/ref/specialnames.html for a complete list of "special" method names that allow us to hook Python-specific behavior into our classes. Good luck to you! From alan.gauld at blueyonder.co.uk Fri Aug 20 22:06:20 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Aug 20 22:06:06 2004 Subject: [Tutor] Useing Functions References: <20040820173449.60804.qmail@web52608.mail.yahoo.com> <4126459E.2080306@ccvcorp.com> Message-ID: <00a501c486f1$28fb61a0$6401a8c0@xp> > be honest, I wish I could use Python instead of Basic, but somehow I > don't expect a port of Python to the Pick database virtual OS anytime > soon... :P ) Ah, what a week for memories. First Amdhal, now Pick. I think it was around '87 I came across Pick. I didn't know it was still being used. Is it ancient legacy or are they still supporting it. Dick Pick was the guy running the company if I recall? They did have a Unix wrapper for Pick at one time... but then again, going by the performance of my memory this week, maybe not! :-( Alan G. From alan.gauld at blueyonder.co.uk Fri Aug 20 22:10:50 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Aug 20 22:10:03 2004 Subject: [Tutor] Useing Functions References: <000c01c486c0$4385c6e0$30e57218@basp.phub.net.cable.rogers.com><006701c486eb$4083ea00$6401a8c0@xp> <001601c486ed$0904d7e0$30e57218@basp.phub.net.cable.rogers.com> Message-ID: <00c901c486f1$ca3de1f0$6401a8c0@xp> > I mande a simple module called define.py just to try it out. However when > put import defines in the main file I get an error: Traceback (most recent > call last): > File "C:\WINDOWS\Desktop\files\python\test.py", line 5, in ? > YesNo(x, y) > NameError: name 'YesNo' is not defined > > however when I put from define import YesNo > it works fine. Why will it not work in the ladder half? Without seeing the code that causes the error I can only guess. Did you remember to precede your function with the module name? import defines defines.YesNo(x,y) Have a look at my modules and functions topic in my tuor it covers how to create functions and modules and use them. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/ From dyoo at hkn.eecs.berkeley.edu Fri Aug 20 22:14:00 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Aug 20 22:14:03 2004 Subject: [Tutor] How to call a method [REPEAT: sorry, admin at fault here] In-Reply-To: <1092359770.6538.3.camel@rossum> Message-ID: On Thu, 12 Aug 2004, Diego Galho Prestes wrote: > Hi! I have this case but dont know how to call it... > > > def Class1: > def someMethod(): > pass > def Class2: > def otherMethod(): > ???call of someMethod??? > > I want to call someMethod in otherMethod. How can I do this? Sorry, this is my fault; this thread had already been answered. http://mail.python.org/pipermail/tutor/2004-August/031400.html I was clearing up the mailing list queue, and didn't see that this message had been posted already. From alan.gauld at blueyonder.co.uk Fri Aug 20 22:15:22 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Aug 20 22:14:35 2004 Subject: [Tutor] overloading object for printing? References: <20040814072137.27950.qmail@web51004.mail.yahoo.com> Message-ID: <00d401c486f2$6c768210$6401a8c0@xp> > Is there some equivalent in Python to the to_s() > method in Java which a class can overload in order to > customize the output of an object? Thanks. Sorry, what does to_s() do exactly? Its not listed in any of my 3 Java books. At a guess the __repr__() or __str__() methods might be what you want but without knowing what to_s() does I can only guess. Alan G. From nick at javacat.f2s.com Fri Aug 20 22:36:28 2004 From: nick at javacat.f2s.com (Nick Lunt) Date: Fri Aug 20 22:33:54 2004 Subject: FW: [Tutor] overloading object for printing? Message-ID: Oops, I sent this directly to Alan by mistake, sorry Alan. Nick. -----Original Message----- From: Nick Lunt [mailto:nick@javacat.f2s.com] Sent: 20 August 2004 21:35 To: Alan Gauld Subject: RE: [Tutor] overloading object for printing? -----Original Message----- From: tutor-bounces+nick=javacat.f2s.com@python.org [mailto:tutor-bounces+nick=javacat.f2s.com@python.org]On Behalf Of Alan Gauld Sent: 20 August 2004 21:15 To: Joe Music; tutor@python.org Subject: Re: [Tutor] overloading object for printing? >Sorry, what does to_s() do exactly? >Its not listed in any of my 3 Java books. > >At a guess the __repr__() or __str__() methods might >be what you want but without knowing what to_s() does >I can only guess. This may be off topic, but to_s() is rubys version of pythons str() :) Nick. From Manon.Lamothe at ingcanada.com Fri Aug 20 22:44:15 2004 From: Manon.Lamothe at ingcanada.com (Manon.Lamothe@ingcanada.com) Date: Fri Aug 20 22:44:21 2004 Subject: [Tutor] replacing a string in files in a directory Message-ID: This is my code bbvardir = '/home/bb/bb19c/ext/manon' bbvarfiles = os.listdir(bbvardir) for item in bbvarfiles: dirfile = os.path.join(bbvardir, item) print '_______________________________________' bbfile = open(dirfile, 'r+') lines = bbfile.readlines() if len(lines) >= 1: firstline = lines[0].strip() print 'firstline ' + firstline colour = firstline.split()[0] print 'colour ' + colour if colour == 'red': withchange = string.replace(firstline,'red','green_green') # withchnage = withchange + '\n' print 'withchange: ' + withchange bbfile.seek(0) bbfile.writelines(withchange) bbfile.close() my replacement string is longer than the original one, and when I write the replacement in the file, the second line is overwritten. This is the original file: red bonjour tous le monde 1 ceci est ma 2ieme ligne ici red and the final file: green_green bonjour tous le monde 1 t ma 2ieme ligne ici red How can I fix that code ? _________________ Manon Lamothe ---------------- This email transmission may contain personal information. By collecting, using or disclosing any of the information contained herein, you hereby agree to abide by our Company's Privacy Promise and all applicable privacy laws. Our Privacy Promise is available at: www.ingcanada.com. If you are not the intended recipient, or if you have any questions, please contact the sender. ------------------ Ce courriel pourrait contenir des renseignements personnels. En recueillant, en utilisant ou en communiquant tout renseignement qui y figure, vous vous engagez ? vous conformer ? la Promesse en mati?re de protection de la vie priv?e publi?e par notre entreprise ainsi qu'? toute loi canadienne applicable. Notre promesse en mati?re de protection de la vie priv?e est publi?e ? www.ingcanada.com. Si vous n'?tes pas le destinataire indiqu? ou si vous avez des questions, veuillez communiquer avec l'exp?diteur. From vicki at thepenguin.org Fri Aug 20 23:03:50 2004 From: vicki at thepenguin.org (vicki@thepenguin.org) Date: Fri Aug 20 23:06:15 2004 Subject: [Tutor] executing a function in a different file and class In-Reply-To: <4126523A.5050708@ccvcorp.com> References: <26269.206.53.226.235.1093029973.squirrel@206.53.226.235> <4126523A.5050708@ccvcorp.com> Message-ID: <47082.206.53.226.235.1093035830.squirrel@206.53.226.235> > vicki@thepenguin.org wrote: >> Okay, I have written a logging function to allow me to pass a string and >> a >> mask to determine which places to log to. The LogMessage function is not >> contained within a class and looks like this: >> [...] >> If I call this function from anywhere within a class in the same file, I >> can use it fine. I created a second file with a function defined in it, >> and I can't call the LogMessage function from there. > > You just need to import the file that LogMessage is in. > > Say that LogMessage is in a file called MyLog.py. Now, in another > file that you want to use it in, you can simply do this: > > import MyLog > > # .... > > Mylog.LogMessage("Foo!") > > Hope that helps... > > Jeff Shannon Okay, now I have a complication from this same question. I can call the function after the import, but it doesn't see the logfile name which was declared as global within the class inside file A but is not global enough to be seen by the function in file B. I guess I could pass the filepointer to the function in file B but that will require me to change all the calls in both files to this function. Is there a way to make the filepointer truly global in the program space rather than just in the class space? I know the caveats of globals and believe that in this case, I am willing to do it anyway. So how does one make a global truly global? I might decide to change each function call, but I would really like to know how to do this anyway. --Vicki To simplify, I have this: file A: function1, Class1 with other functions which call function1 file B: function2 which calls function1 but can't see a variable which was declared as global inside Class1. From python at pointcontrol.com Fri Aug 20 23:17:36 2004 From: python at pointcontrol.com (python@pointcontrol.com) Date: Fri Aug 20 23:17:41 2004 Subject: Never mind: Re: [Tutor] Installing wxPython on fresh Fedora box - failed dependency In-Reply-To: <50048.65.4.31.86.1093026572.squirrel@www.pointcontrol.com> References: <50048.65.4.31.86.1093026572.squirrel@www.pointcontrol.com> Message-ID: <50360.65.4.31.86.1093036656.squirrel@www.pointcontrol.com> Please disregard the earlier post about a failed dependency. I found an RPM that provided the missing file (compat-libstdc++-7.3-2.96.118). Thanks. -- b.r.t. From jeff at ccvcorp.com Fri Aug 20 23:21:25 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri Aug 20 23:20:50 2004 Subject: [Tutor] executing a function in a different file and class In-Reply-To: <57301.206.53.226.235.1093030973.squirrel@206.53.226.235> References: <26269.206.53.226.235.1093029973.squirrel@206.53.226.235> <4126523A.5050708@ccvcorp.com> <57301.206.53.226.235.1093030973.squirrel@206.53.226.235> Message-ID: <41266B55.8030001@ccvcorp.com> vicki@thepenguin.org wrote: >>You just need to import the file that LogMessage is in. > > Okay Jeff, I thought of this, but it seemed wrong since I would be > importing the original file that contains the function which is calling > the function which is attempting to log (in the house that Jack built). > Let me be more clear. I have file A which contains most of the code for my > program and file B which only contains the new function. Code in file A > calls the function in file B which then calls the Logging function which > is in file A. I could just move the new function into file A eliminating > the whole problem, but I would rather learn the proper way to do this. I > think part of the problem is that this particular implementation does not > lend itself to OOP principles. That's a good question, actually. You're getting into design principles rather than coding principles, here, but it's good to have an idea about design from the start. For me, in any case where I have enough code that I want to split it into more than one file, I try to find all of the conceptual units of the program, and then put each of those units into a separate file. Some of those conceptual units may not require much code, so the file may be pretty short, but that's okay -- better to have a number of short files, each of which handles a particular topic, than fewer long files which may combine several concepts. If each file represents a particular concept, then you can focus on just that when you're working on that file, and not worry about it when you're working on a different concept. Often, for OO programming, it works well to have each major class have its own file. Sometimes you'll have several classes that work closely together, and they can go in the same file -- especially if one or more of those classes is likely to be only used from another one. In the case that you mention, I'd pull your LogMessage() function out into a third file, and have A and B both import that file to use LogMessage(). It may be that this function is the only thing that's in your logging module, and that's fine. You might also have some helper functions for LogMessage(); if so, those would also go in that file. Jeff Shannon Technician/Programmer Credit International From pythonTutor at venix.com Fri Aug 20 23:33:21 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Fri Aug 20 23:33:36 2004 Subject: [Tutor] executing a function in a different file and class In-Reply-To: <47082.206.53.226.235.1093035830.squirrel@206.53.226.235> References: <26269.206.53.226.235.1093029973.squirrel@206.53.226.235> <4126523A.5050708@ccvcorp.com> <47082.206.53.226.235.1093035830.squirrel@206.53.226.235> Message-ID: <1093037601.2362.13.camel@laptop.venix.com> On Fri, 2004-08-20 at 17:03, vicki@thepenguin.org wrote: (snipped) > To simplify, I have this: > > file A: function1, Class1 with other functions which call function1 > file B: function2 which calls function1 but can't see a variable which was > declared as global inside Class1. Unless one of the experts says otherwise, there is no overarching name space (except builtins in some sense). Each file represents a separate name space. Python will try to resolve names in your current name space. If you import a file, you can reference that name space explicitly by using the file name. Presumably file_A has a line that says: import file_B and file_B has a line that says import file_A (These are circular imports and can lead to grief.) >From file_B you could write open(file_A.global_file_name) I think this is what you are asking for. The fact that these files are so mutually dependent on each other suggests that you might want to combine them into one file OR put the shared pieces into file_C so that both A and B import file_C, but no longer import each other. You would still be able to reference file_C.global_file_name HTH -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From jeff at ccvcorp.com Fri Aug 20 23:39:11 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri Aug 20 23:38:34 2004 Subject: [Tutor] Useing Functions In-Reply-To: <00a501c486f1$28fb61a0$6401a8c0@xp> References: <20040820173449.60804.qmail@web52608.mail.yahoo.com> <4126459E.2080306@ccvcorp.com> <00a501c486f1$28fb61a0$6401a8c0@xp> Message-ID: <41266F7F.6090900@ccvcorp.com> Alan Gauld wrote: >>be honest, I wish I could use Python instead of Basic, but somehow I >>don't expect a port of Python to the Pick database virtual OS >>anytime soon... :P ) > > Ah, what a week for memories. First Amdhal, now Pick. > I think it was around '87 I came across Pick. I didn't know > it was still being used. Is it ancient legacy or are they > still supporting it. It's still being supported -- I believe there's a couple of different implementations of Pick (we're using the D3 implementation from, IIRC, Raining Data). This job (where I've been for ~6 years now) is the first place I've run across Pick; it seems to have a very small but devoted following. (The programmers/consultants who use Pick, seem to want to do *everything* through Pick. Personally, I'll be just as happy to never touch it again once I leave this job...) > They did have a Unix wrapper for Pick at one time... > but then again, going by the performance of my memory > this week, maybe not! :-( Our system runs as a virtual OS on top of Linux. In theory, one can move data back and forth between Pick and Linux. In practice, it's much easier to import data *into* Pick than to export out of Pick. There is a C api, and an ODBC wrapper as well, but we don't use them. The real problem, here, is that most of this company's business is handled through a huge, ungainly assemblage of scripts and programs that have been built up over the last 15+ years. I'm primarily a maintenance programmer, making slight tweaks to existing code rather than creating whole new systems. And the head consultant, who's written most of the code and who understands the system far better than anyone else, isn't very interested in the infrastructure work that'd be necessary to enable Unix-to-Pick operations. He's come to programming from the business side, rather than the engineering side, so he's (mostly) happy with what he already knows... and that *doesn't* include C or Python. (Of four full-and-part-time IT staff, only the two most-junior (which includes me) know any C, and only I know any Python. The other guy is now doing a lot of Perl/PHP work to integrate our website with parts of our database, which is a start...) I've been writing a variety of our Unix-side (and client PC-side) scripts and small programs in Python, and I've been slowly trying to get more and more of our work done in that environment, but I don't think I'll ever be able to get our core applications outside of the Pick box. Jeff Shannon Technician/Programmer Credit International From jeff at ccvcorp.com Fri Aug 20 23:47:21 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri Aug 20 23:46:46 2004 Subject: [Tutor] executing a function in a different file and class In-Reply-To: <47082.206.53.226.235.1093035830.squirrel@206.53.226.235> References: <26269.206.53.226.235.1093029973.squirrel@206.53.226.235> <4126523A.5050708@ccvcorp.com> <47082.206.53.226.235.1093035830.squirrel@206.53.226.235> Message-ID: <41267169.3040405@ccvcorp.com> vicki@thepenguin.org wrote: > Okay, now I have a complication from this same question. I can call the > function after the import, but it doesn't see the logfile name which was > declared as global within the class inside file A but is not global enough > to be seen by the function in file B. I guess I could pass the filepointer > to the function in file B but that will require me to change all the calls > in both files to this function. Is there a way to make the filepointer > truly global in the program space rather than just in the class space? Well, following my other advice (to put the logging function in an entirely separate module), you should move the logfile name into that module as well. Conceptually, your main code shouldn't care *where* the log is kept; that's all the responsibility of your logging module. You might want to have another function in that logging module that'll allow you main code to set the filename (and maybe the location). This function would have to be called before you started logging anything, of course, but it could be as simple as modifying a logging-module global variable. By the way, are you at all familiar with the logging package that's included in Python 2.3+ ? (It's also available for 2.2, but not included.) It's very flexible, and can be used in a fairly simple manner. (Of course, even if you *do* switch over to using the standard logging package, it's still a good thing to discuss the principles behind separating code into multiple files...) Jeff Shannon Technician/Programmer Credit International From jonathan.hayward at pobox.com Sat Aug 21 00:02:51 2004 From: jonathan.hayward at pobox.com (Jonathan Hayward) Date: Sat Aug 21 00:03:02 2004 Subject: [Tutor] Novice programming errors Message-ID: <4126750B.6050002@pobox.com> To the beginners and people like Danny Yoo who answer a lot of questions... I'm doing some research and would like to get a feel for common novice errors. I'm interested both in syntax errors that cause compilation errors, and things like division by zero or key errors. To new programmers especially, could you give me specific examples of errors you've struggled with? Many thanks, -- ++ Jonathan Hayward, jonathan.hayward@pobox.com ** To see an award-winning website with stories, essays, artwork, ** games, and a four-dimensional maze, why not visit my home page? ** All of this is waiting for you at http://JonathansCorner.com From alan.gauld at blueyonder.co.uk Sat Aug 21 00:06:26 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Aug 21 00:05:37 2004 Subject: [Tutor] executing a function in a different file and class References: <26269.206.53.226.235.1093029973.squirrel@206.53.226.235><4126523A.5050708@ccvcorp.com> <47082.206.53.226.235.1093035830.squirrel@206.53.226.235> Message-ID: <011601c48701$f0522990$6401a8c0@xp> > Okay, now I have a complication from this same question. I can call the > function after the import, but it doesn't see the logfile name which was > declared as global within the class inside file A I'm not sure what you mean here but if you just used the global keyword that simply means that assignments to that name will affect the module level variable of the same name. It does nothing to the class per se. > but is not global enough to be seen by the function in file B. If File B can see File A(coz it imported it) then it can see the global variable by preceding it with A import A A.globalVar > I guess I could pass the filepointer to the function in file B Which is usually a good idea - its why you should try to avoid using global variables. Passing parameters iis nearly always better. But it may not be needed here. > in both files to this function. Is there a way to make the filepointer > truly global in the program space rather than just in the class space? Python doesn't support true golobal variables but the namespace control allows you to import the module with makes all names in it indirectly visible, import someModule print someModule.someVariable or to import specific names from someModule import someVariable print someVariable or to import all names - usually a bad idea: from someModule import * print someVariable > know the caveats of globals and believe that in this case, I am willing to > do it anyway. So how does one make a global truly global? Thats such a yucky idea that Python won't let you, but it does provide the import controls described above which allow you to fake it on a file by file basis. HTH, Alan G. From jeff at ccvcorp.com Sat Aug 21 00:17:19 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Sat Aug 21 00:16:49 2004 Subject: [Tutor] Useing Functions In-Reply-To: References: Message-ID: <4126786F.4080805@ccvcorp.com> Danny Yoo wrote: > Hi Jeff, > > Hmmm! Sorry for taking this in an askew direction, but how difficult > would it be to write a preprocessor? You could write your programs in a > kind of superset of Basic that has subroutines. This superset wouldn't be > directly executable, but would be input into a preprocessor. This > preprocessor could then transform that super-Basic back into regular > Basic, and handle all the awkwardness of subroutine linkage, behind the > scenes. That should be possible, at least in principle, yes. Of course, one of the big concerns I'd have to address is namespace collision -- in essence, every basic program gets stored in the same "directory". [The Pick VM has a radically different filesystem architecture than the arbitrary-depth trees of unix and windows/dos. The depth of the tree is strictly defined by the OS. In essence, everything is a database table (except tables are called "files"); each program is an "item" (record) in one of these files (tables), and each line is an attribute (field) of that item. All of our tools expect that all Basic programs (whether standalone or subroutines) will be in one file, and all of our UHL scripts (shell scripts, essentially) will be in a second file. I'm not sure how much work it'd be to allow multiple "files" to contain executable code...] Because all programs are in the same namespace, having lots of independent subroutines is also awkward -- there's currently 6756 items there, which is a lot of names to check for collisions! We have some naming conventions which help, but those have changed over the years... [As a side note, I've also been lamenting the difficulty of using CVS with our system. It would require always editing files in Unixland (or Windowsland), and importing/exporting files from the database with every save/load. That's not too hard, but our senior developer prefers to keep using the internal editor that he's very familiar with, so we'd have only a partial record in CVS...] So, yes, I could write a preprocessor that'd take my super-Basic source code and save each function as a separate subroutine. Of course, for this to be effective I'd also need to be able to edit existing programs written by someone else. This would require scanning PickBasic source to find all of the called subroutines and then including them. Of course, the real problem here is that the other developers are used to writing long spaghetti code. Even if I used this myself, I'd have a hard time convincing the senior developer that the way he's been programming for the last 15-20 years isn't good enough... (It's also possible that there's better tools that he just hasn't bothered to learn, and therefore I've never seen.) > Is there a specification on this old Basic dialect that we could look at? > Just out of curiosity, of course... *grin* Well, it's not a spec, but a quick search on Google turns up http://www.jes.com/pb/ -- an online version of an introductory Pick/Basic book. Jeff Shannon Technician/Programmer Credit International From s4046441 at student.uq.edu.au Sat Aug 21 00:53:21 2004 From: s4046441 at student.uq.edu.au (Ms Soo Chong) Date: Sat Aug 21 00:53:26 2004 Subject: [Tutor] Questions on CGI script Message-ID: <18447d189ed1.189ed118447d@uq.edu.au> Thanks Kent for the useful example but I'm still having some problem. I tried the typing the code (from the webpage) and generate it, hope to see some output and learn from there. But it shows Server Error on the web browser. (After reading through the example - Writing CGI programs in python, I thought I understand whats going on but in fact maybe not, since I still failed to generate a form and output.) http://www.devshed.com/c/a/Python/Writing-CGI-Programs-in-Python I wanna to display a text box where user type their query msg and a submit box to process the query. Should I create another html file and open in read mode in my actual script? Then, import cgi form = cgi.FieldStorage() It may be simple to alot of people but sorry I don't really understand the procedure of writing a cgi script. Can someone please help me by giving a simple example on generating a search and displaying the result? Greatly appreciated. I have been trying for the past two days without bothering python tutors but I still can't get it done. HELP. Thank you in advance. Shufen From klappnase at freenet.de Sat Aug 21 01:32:03 2004 From: klappnase at freenet.de (Michael Lange) Date: Sat Aug 21 01:35:32 2004 Subject: [Tutor] replacing a string in files in a directory In-Reply-To: References: Message-ID: <20040821013203.2714db81.klappnase@freenet.de> On Fri, 20 Aug 2004 16:44:15 -0400 Manon.Lamothe@ingcanada.com wrote: > This is my code > > bbvardir = '/home/bb/bb19c/ext/manon' > bbvarfiles = os.listdir(bbvardir) > > for item in bbvarfiles: > dirfile = os.path.join(bbvardir, item) > print '_______________________________________' > bbfile = open(dirfile, 'r+') > lines = bbfile.readlines() > if len(lines) >= 1: > firstline = lines[0].strip() > print 'firstline ' + firstline > colour = firstline.split()[0] > print 'colour ' + colour > if colour == 'red': > withchange = string.replace(firstline,'red','green_green') > # withchnage = withchange + '\n' > print 'withchange: ' + withchange > bbfile.seek(0) > bbfile.writelines(withchange) > > bbfile.close() > > my replacement string is longer than the original one, and when I write the > replacement in the file, the second line is overwritten. > > This is the original file: > red bonjour tous le monde 1 > ceci est ma 2ieme ligne ici > red > > and the final file: > green_green bonjour tous le monde 1 > t ma 2ieme ligne ici > red > > How can I fix that code ? > Hi Manon, if you just want to change the first line in your files, you might want to have a look at the fileinput module, which has very nice methods for this. With fileinput.input(filename, inplace=1) you can iterate over the lines in the file and change it's contents on the fly; and with fileinput.isfirstline() you can check if the current line is the first line in the file. I hope this helps Michael From python_newbie at vedorian.com Sat Aug 21 04:10:18 2004 From: python_newbie at vedorian.com (Kevin) Date: Sat Aug 21 04:10:25 2004 Subject: [Tutor] Useing Functions References: <000c01c486c0$4385c6e0$30e57218@basp.phub.net.cable.rogers.com><006701c486eb$4083ea00$6401a8c0@xp> <001601c486ed$0904d7e0$30e57218@basp.phub.net.cable.rogers.com> <00c901c486f1$ca3de1f0$6401a8c0@xp> Message-ID: <000901c48724$01c55ae0$30e57218@basp.phub.net.cable.rogers.com> Ok I know exactly what I did wrong with that when I put in: import define, I did not call it right instead of define.YesNo(x,y) I was calling it just YesNo(x,y). Thats why it was working with from define import YesNo Kevin ----- Original Message ----- From: "Alan Gauld" To: "Kevin" ; "Python" Sent: Friday, August 20, 2004 4:10 PM Subject: Re: [Tutor] Useing Functions > > > I mande a simple module called define.py just to try it out. However > when > > put import defines in the main file I get an error: Traceback > (most recent > > call last): > > File "C:\WINDOWS\Desktop\files\python\test.py", line 5, in ? > > YesNo(x, y) > > NameError: name 'YesNo' is not defined > > > > however when I put from define import YesNo > > it works fine. Why will it not work in the ladder half? > > Without seeing the code that causes the error I can only guess. > > Did you remember to precede your function with the module name? > > import defines > defines.YesNo(x,y) > > Have a look at my modules and functions topic in my tuor it > covers how to create functions and modules and use them. > > Alan G > Author of the Learn to Program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/ > > > --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.740 / Virus Database: 494 - Release Date: 8/16/04 From python at bernardlebel.com Sat Aug 21 13:58:03 2004 From: python at bernardlebel.com (Bernard Lebel) Date: Sat Aug 21 12:55:44 2004 Subject: [Tutor] Problem with file() Message-ID: <003e01c48776$1f079da0$2901a8c0@atyss> Hello, I'm writing a little module that has few classes, and each classes few functions. The first class has a function that allows to read a text file and add the entries of the text to a list, and the list is returned. When I do the operation with command line in PythonWin, without the class and function definitions, no problem. When I import the module and run the function, I get an error: oExtList = file( sListPath, 'r' ) Traceback (most recent call last): File "", line 1, in ? File "C:\Python23\lib\ClientsManager\__init__.py", line 104, in getextlist oExtList = file( sListPath, 'r' ) TypeError: this constructor takes no arguments I call the function this way: import ClientsManager as cm cl = cm.client() aClients = cl.getextlist() Duh? Here is the full code: class client: def getextlist( self, aClients = [], sListPath = '', iOp = 2 ): """ Will modify an existing client list using an external file list. You can choose to add to the list or remove from the list the clients listed in the external list. For instances, user computers on a floor generally give a non-standard name to their computer, so you might find convenient to add/remove their names to the aClients list by querying an external file with the list of computer names. iOp specifies the operation to perform: 0: append 1: remove """ if sListPath == '': sListPath = raw_input( 'Full path to external list (use "\\\\" to separate directories): ' ) if iOp < 0 or iOp > 1: iOp = int( raw_input( 'Type of operation (0-append, 1-remove): ' ) ) if iOp < 0 or iOp > 1: print ( 'You must enter 0 or 1!' ) else: if not os.path.exists( sListPath ): print 'Provided list path invalid' else: # Get list file oExtList = file( sListPath ) # Get list elements aExtList = oExtList.readlines() # Remove end of lines characters for sClient1 in aExtList: sClient2 = sClient1.strip( '\n' ) if iOp == 0: aClients.append( sClient2 ) else: aClients.remove( sClient2 ) return aClients Thanks Bernard From kent_johnson at skillsoft.com Sat Aug 21 14:44:06 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sat Aug 21 14:44:20 2004 Subject: [Tutor] Questions on CGI script In-Reply-To: <18447d189ed1.189ed118447d@uq.edu.au> References: <18447d189ed1.189ed118447d@uq.edu.au> Message-ID: <6.1.0.6.0.20040821083406.028f38b0@mail4.skillsoft.com> Shufen, What are the details of the Server Error? VoidSpace has a few CGI examples you could look at. cgi-shell is very simple example - it creates a form with one entry field that accepts a shell command. When you submit the form it executes the command and shows you the result. http://www.voidspace.org.uk/atlantibots/cgi-shell.py nangram is a more complex example - http://www.voidspace.org.uk/atlantibots/pythonutils.html#nana Kent At 08:53 AM 8/21/2004 +1000, Ms Soo Chong wrote: >Thanks Kent for the useful example but I'm still having some problem. >I tried the typing the code (from the webpage) and generate it, hope to >see some output >and learn from there. But it shows Server Error on the web browser. (After >reading >through the example - Writing CGI programs in python, I thought I >understand whats >going on but in fact maybe not, since I still failed to generate a form >and output.) > >http://www.devshed.com/c/a/Python/Writing-CGI-Programs-in-Python > >I wanna to display a text box where user type their query msg and a submit >box to >process the query. Should I create another html file and open in read mode >in my actual script? Then, > >import cgi >form = cgi.FieldStorage() > >It may be simple to alot of people but sorry I don't really understand the >procedure >of writing a cgi script. Can someone please help me by giving a simple >example on >generating a search and displaying the result? Greatly appreciated. > >I have been trying for the past two days without bothering python tutors >but I still can't get it done. HELP. > >Thank you in advance. > >Shufen > > > > > > > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From kent_johnson at skillsoft.com Sat Aug 21 14:57:14 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sat Aug 21 14:57:18 2004 Subject: [Tutor] Problem with file() In-Reply-To: <003e01c48776$1f079da0$2901a8c0@atyss> References: <003e01c48776$1f079da0$2901a8c0@atyss> Message-ID: <6.1.0.6.0.20040821084900.028f3390@mail4.skillsoft.com> Bernard, You don't seem to have included the code containing the problem. The traceback shows the error occurring at line 104 of __init__.py and you seem to have included ClientsManager.py. Have you perhaps redefined 'file' in __init__.py? It's easy to do... BTW from what you have shown here, using a class to hold the getextlist() function may be overkill. Classes are great when you have several functions that have to work together, for example sharing common data in fields. If you have independent functions that you want to group together for convenience/modularity/testing/reuse, you can make them global functions in a separate module without creating a class. Kent At 12:58 PM 8/21/2004 +0100, Bernard Lebel wrote: >Hello, > >I'm writing a little module that has few classes, and each classes few >functions. The first class has a function that allows to read a text file >and add the entries of the text to a list, and the list is returned. > >When I do the operation with command line in PythonWin, without the class >and function definitions, no problem. When I import the module and run the >function, I get an error: > >oExtList = file( sListPath, 'r' ) > >Traceback (most recent call last): > File "", line 1, in ? > File "C:\Python23\lib\ClientsManager\__init__.py", line 104, in getextlist > oExtList = file( sListPath, 'r' ) >TypeError: this constructor takes no arguments > >I call the function this way: >import ClientsManager as cm >cl = cm.client() >aClients = cl.getextlist() > > > >Duh? > > >Here is the full code: > > > >class client: > > def getextlist( self, aClients = [], sListPath = '', iOp = 2 ): > > """ > Will modify an existing client list using an external file list. > You can choose to add to the list or remove from the list the clients > listed in the external list. > > For instances, user computers on a floor generally give a non-standard > name to their computer, so you might find convenient to add/remove their >names > to the aClients list by querying an external file with the list of >computer names. > > iOp specifies the operation to perform: > 0: append > 1: remove > """ > > if sListPath == '': > sListPath = raw_input( 'Full path to external list (use "\\\\" to >separate directories): ' ) > > if iOp < 0 or iOp > 1: > iOp = int( raw_input( 'Type of operation (0-append, 1-remove): ' ) ) > > if iOp < 0 or iOp > 1: > print ( 'You must enter 0 or 1!' ) > else: > if not os.path.exists( sListPath ): > print 'Provided list path invalid' > else: > # Get list file > oExtList = file( sListPath ) > > # Get list elements > aExtList = oExtList.readlines() > > # Remove end of lines characters > for sClient1 in aExtList: > sClient2 = sClient1.strip( '\n' ) > > if iOp == 0: > aClients.append( sClient2 ) > else: > aClients.remove( sClient2 ) > > return aClients > > > >Thanks >Bernard > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From s4046441 at student.uq.edu.au Sat Aug 21 15:10:23 2004 From: s4046441 at student.uq.edu.au (Ms Soo Chong) Date: Sat Aug 21 15:10:29 2004 Subject: [Tutor] Questions on CGI script Message-ID: <18f04318f9cd.18f9cd18f043@uq.edu.au> Hi, Kent, thank you so much for your reply. I will take a good look of the cgi-shell and try it out tommorrow morning. I will send you the Server Error if I happened to meet it again (hopefully NOT). Anyway, should I create another .html file for the form or type it in the script? Thank you anyway for your help. Shufen ----- Original Message ----- From: Kent Johnson Date: Saturday, August 21, 2004 10:44 pm Subject: Re: [Tutor] Questions on CGI script > Shufen, > > What are the details of the Server Error? > > VoidSpace has a few CGI examples you could look at. > cgi-shell is very simple example - it creates a form with one > entry field > that accepts a shell command. When you submit the form it executes > the > command and shows you the result. > http://www.voidspace.org.uk/atlantibots/cgi-shell.py > > nangram is a more complex example - > http://www.voidspace.org.uk/atlantibots/pythonutils.html#nana > > Kent > > At 08:53 AM 8/21/2004 +1000, Ms Soo Chong wrote: > >Thanks Kent for the useful example but I'm still having some problem. > >I tried the typing the code (from the webpage) and generate it, > hope to > >see some output > >and learn from there. But it shows Server Error on the web > browser. (After > >reading > >through the example - Writing CGI programs in python, I thought I > >understand whats > >going on but in fact maybe not, since I still failed to generate > a form > >and output.) > > > >http://www.devshed.com/c/a/Python/Writing-CGI-Programs-in-Python > > > >I wanna to display a text box where user type their query msg and > a submit > >box to > >process the query. Should I create another html file and open in > read mode > >in my actual script? Then, > > > >import cgi > >form = cgi.FieldStorage() > > > >It may be simple to alot of people but sorry I don't really > understand the > >procedure > >of writing a cgi script. Can someone please help me by giving a > simple > >example on > >generating a search and displaying the result? Greatly appreciated. > > > >I have been trying for the past two days without bothering python > tutors > >but I still can't get it done. HELP. > > > >Thank you in advance. > > > >Shufen > > > > > > > > > > > > > > > > > >_______________________________________________ > >Tutor maillist - Tutor@python.org > >http://mail.python.org/mailman/listinfo/tutor > > From klas.martelleur at telia.com Sat Aug 21 15:47:23 2004 From: klas.martelleur at telia.com (Klas Marteleur) Date: Sat Aug 21 15:36:12 2004 Subject: [Tutor] Frames and the grid manager Message-ID: <200408211547.23865.klas.martelleur@telia.com> Hi I have desigend a small gui for my convert program. I have used the grid manager and placed everything in the master frame. I now plan to expand my program a bit more to make it possible to convert a few other types of files. I then think it would be best to separate my gui into frames. Alan has examples of frames and the pack manager in his book but do i design frames when i am using the grid manager? If someone could ilustrate that for me for example by having the input section of my program as a separate frame inside the master frame, i would be very greatful. (please also take a look at my way of exiting the program... seems like its something wrong with it, i dont get a clean exit) Here is my program #!/usr/bin/python #################################################################### ##Module: createEbomGUI ##Created: Klas Marteleur, 2004, 08, 15 ## ##Function: ##GUI for createEbom2 ##Changelog: ## version 0.1: ## Initial Beta release ## version 0.11: ## Path fixes ## version 0.2: ## def modifyList completly rewritten because of changes in inputfile ## #################################################################### from Tkinter import * import tkFileDialog, sys class CreateEbom(Frame): def __init__(self, master): # Create master frame self.myMaster = master self.myMaster.title('Tragic Converter BETA 0.2') self.myMaster.geometry('+450+400') self.myContainer1 = Grid() # Create input file label self.inputFile = Label(master, text="Input file:") self.inputFile.grid(row=0, sticky=E) # Create output file label self.outputFile = Label(master,text="Output file:") self.outputFile.grid(row=1, sticky=E) # Create inputfile entry box #self.infile = "C:\users\default\input.1" self.infile = "/home/klas/Python_filer/Tragic/ebom_from_file_wider.txt" self.inputEntry = Entry(master) self.inputEntry.insert(INSERT,self.infile) self.inputEntry.grid(row=0,column=1) # Create outputfile entry box #self.outfile = "C:\CreateEbom\output.txt" self.outfile = "/home/klas/Python_filer/Tragic/output.txt" self.outputEntry = Entry(master) self.outputEntry.insert(INSERT,self.outfile) self.outputEntry.grid(row=1,column=1) # Create input browse button self.inputBrowseButton = Button(master, command = self.openInFile) self.inputBrowseButton.configure(text = "Browse") self.inputBrowseButton.grid(row=0,column=2) # Create output browse button self.outputBrowseButton = Button(master, command = self.saveAsFile) self.outputBrowseButton.configure(text = "Browse") self.outputBrowseButton.grid(row=1,column=2) # Create latest revision label self.latestRevisonLabel = Label(master,text="Use rev.") self.latestRevisonLabel.grid(row=2, sticky=E) # Create latest revision check button self.var = IntVar() self.latestRevisionCheckbutton = Checkbutton(master,variable=self.var, command=self.checkButton) self.latestRevisionCheckbutton.grid(row=2,column=1,sticky=W) # Create convert button self.convertButton = Button(master, command = self.doProcessFiles) self.convertButton.configure(text="Convert") self.convertButton.grid(row=3,column=1,sticky=E) # Create exit button self.exitButton = Button(master, command = self.doExit) self.exitButton.configure(text="Exit") self.exitButton.grid(row=3,column=2,sticky=E) # Create designed by label self.designedByLabel = Label(master,text="This program is designed in Python by Klas Marteleur. Tel. 21116",font=("Arial", 7), fg="red") self.designedByLabel.grid(row=4,column=0,columnspan=3,sticky=S) # Add Python logo photo = PhotoImage(file="/home/klas/Python_filer/Tragic/PythonPoweredSmall.gif") self.logo = Label(master,image=photo) self.logo.photo = photo self.logo .grid(row=3,column=0) # Temporary function def callback(self): print "Called the callback!" # Check button function def checkButton(self): print "\n"*50 print """The value of the "Use rev." button is: """, self.var.get() if self.var.get() == 0: print "\nThis means that the LATEST revison of each item shall be used in Magic.\nThis is the NORMAL most used setting" else: print "\nThis means that the revision of each item used in in Magic,\nshall be as specified in the drawing table\nUSE WITH CARE" # Open file function def openInFile(self): infile = tkFileDialog.askopenfilename(initialdir="D:\users\default",filetypes=[("ProE output files",".1"),("All files","*")]) self.inputEntry.delete(0,END) self.inputEntry.insert(INSERT,infile) print "\n"*50 print "The infile is now specified to: ", infile # Save as function def saveAsFile(self): outfile = tkFileDialog.asksaveasfilename(initialdir="C:\Create Ebom From File",defaultextension=".txt",filetypes=[("Text files",".txt"),("All files","*")]) self.outputEntry.delete(0,END) self.outputEntry.insert(INSERT, outfile) print "\n"*50 print "The outfile is now specified to: ", outfile # Process files function def doProcessFiles(self): from createEbomNew import * from tkMessageBox import * inputFileName = self.inputEntry.get() outputFileName = self.outputEntry.get() print "\n"*50 print "Inputfile = ", inputFileName, print "Outputfile = ", outputFileName latestRevision = self.var.get() processFilesEbom(inputFileName,outputFileName,latestRevision) print "+---------------------+" print "| CONVERTING COMPLETE |" print "+---------------------+" showinfo("Convert Complete", "Convert Complete\n\n Program Exits") self.myMaster.destroy() sys.exit() # Exit function def doExit(self): self.myMaster.destroy() sys.exit() print "\n"*100 # a simple way to clear the screen print "Starting..." root = Tk() createebom = CreateEbom(root) root.mainloop() print "Shutdown in progress..." print "Done!" Thanks Klas From kent_johnson at skillsoft.com Sat Aug 21 15:37:00 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sat Aug 21 15:37:53 2004 Subject: [Tutor] Questions on CGI script In-Reply-To: <18447d189ed1.189ed118447d@uq.edu.au> References: <18447d189ed1.189ed118447d@uq.edu.au> Message-ID: <6.1.0.6.0.20040821093229.028f0e68@mail4.skillsoft.com> OK here is a really simple Python CGI. The first time it is accessed it puts up a form with a text box. When you submit, it echoes back what you typed. I used cgitb to enable more debugging information - for example if there is a syntax error in the script it will give a useful error message in the browser. See if you can get this working. Then you can modify it to do what you want. Kent import cgi import cgitb; cgitb.enable() # Turn on CGI debugging info # HTTP headers print 'Status: 200 OK' print 'Content-type: text/html' print # HTML head print '''Test CGI''' # Get the form fields, if any form = cgi.FieldStorage() if not form.has_key("data"): # No form data means this is the first access; output the form print '''
    Type your data here:

    ''' else: # We do have form data; just show it print 'You typed: ' print form.getvalue('data') # HTML end print '' At 08:53 AM 8/21/2004 +1000, Ms Soo Chong wrote: >Thanks Kent for the useful example but I'm still having some problem. >I tried the typing the code (from the webpage) and generate it, hope to >see some output >and learn from there. But it shows Server Error on the web browser. (After >reading >through the example - Writing CGI programs in python, I thought I >understand whats >going on but in fact maybe not, since I still failed to generate a form >and output.) > >http://www.devshed.com/c/a/Python/Writing-CGI-Programs-in-Python > >I wanna to display a text box where user type their query msg and a submit >box to >process the query. Should I create another html file and open in read mode >in my actual script? Then, > >import cgi >form = cgi.FieldStorage() > >It may be simple to alot of people but sorry I don't really understand the >procedure >of writing a cgi script. Can someone please help me by giving a simple >example on >generating a search and displaying the result? Greatly appreciated. > >I have been trying for the past two days without bothering python tutors >but I still can't get it done. HELP. > >Thank you in advance. > >Shufen > > > > > > > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From python at bernardlebel.com Sat Aug 21 16:52:48 2004 From: python at bernardlebel.com (Bernard Lebel) Date: Sat Aug 21 15:50:30 2004 Subject: [Tutor] Problem with file() References: <003e01c48776$1f079da0$2901a8c0@atyss> <6.1.0.6.0.20040821084900.028f3390@mail4.skillsoft.com> Message-ID: <000e01c4878e$8886d4e0$2901a8c0@atyss> > You don't seem to have included the code containing the problem. The > traceback shows the error occurring at line 104 of __init__.py and you seem > to have included ClientsManager.py. The code is from __init__.py. The module is called ClientsManager. Right now there is only a __init__.py file, containing all classes and functions. > > Have you perhaps redefined 'file' in __init__.py? It's easy to do... > You are absolutely right. I have a class named file. Stupid me. When renamed to cmFile, it works now. > BTW from what you have shown here, using a class to hold the getextlist() > function may be overkill. Classes are great when you have several functions > that have to work together, for example sharing common data in fields. If > you have independent functions that you want to group together for > convenience/modularity/testing/reuse, you can make them global functions in > a separate module without creating a class. Well you might be right. The classes are there mostly to encapsulate few functions instead of having them all under the same level. But the module has versatile functions: one is to work on a "client list", wich is the cmClient class, while the other classes use the list. For instance, the cmFile class is to copy, move and delete files over a large number of computers, and the cmServices class is to handle remote processes of this list. Like I said right now everything sits in the __init__.py file. I will definitely give a try to your separte module setup suggestion. Thanks Bernard > > Kent > > At 12:58 PM 8/21/2004 +0100, Bernard Lebel wrote: > >Hello, > > > >I'm writing a little module that has few classes, and each classes few > >functions. The first class has a function that allows to read a text file > >and add the entries of the text to a list, and the list is returned. > > > >When I do the operation with command line in PythonWin, without the class > >and function definitions, no problem. When I import the module and run th e > >function, I get an error: > > > >oExtList = file( sListPath, 'r' ) > > > >Traceback (most recent call last): > > File "", line 1, in ? > > File "C:\Python23\lib\ClientsManager\__init__.py", line 104, in getextlist > > oExtList = file( sListPath, 'r' ) > >TypeError: this constructor takes no arguments > > > >I call the function this way: > >import ClientsManager as cm > >cl = cm.client() > >aClients = cl.getextlist() > > > > > > > >Duh? > > > > > >Here is the full code: > > > > > > > >class client: > > > > def getextlist( self, aClients = [], sListPath = '', iOp = 2 ): > > > > """ > > Will modify an existing client list using an external file list. > > You can choose to add to the list or remove from the list the clients > > listed in the external list. > > > > For instances, user computers on a floor generally give a non-standard > > name to their computer, so you might find convenient to add/remove their > >names > > to the aClients list by querying an external file with the list of > >computer names. > > > > iOp specifies the operation to perform: > > 0: append > > 1: remove > > """ > > > > if sListPath == '': > > sListPath = raw_input( 'Full path to external list (use "\\\\" to > >separate directories): ' ) > > > > if iOp < 0 or iOp > 1: > > iOp = int( raw_input( 'Type of operation (0-append, 1-remove): ' ) ) > > > > if iOp < 0 or iOp > 1: > > print ( 'You must enter 0 or 1!' ) > > else: > > if not os.path.exists( sListPath ): > > print 'Provided list path invalid' > > else: > > # Get list file > > oExtList = file( sListPath ) > > > > # Get list elements > > aExtList = oExtList.readlines() > > > > # Remove end of lines characters > > for sClient1 in aExtList: > > sClient2 = sClient1.strip( '\n' ) > > > > if iOp == 0: > > aClients.append( sClient2 ) > > else: > > aClients.remove( sClient2 ) > > > > return aClients > > > > > > > >Thanks > >Bernard > > > >_______________________________________________ > >Tutor maillist - Tutor@python.org > >http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From kent_johnson at skillsoft.com Sat Aug 21 16:43:06 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sat Aug 21 16:43:12 2004 Subject: [Tutor] Problem with file() In-Reply-To: <000e01c4878e$8886d4e0$2901a8c0@atyss> References: <003e01c48776$1f079da0$2901a8c0@atyss> <6.1.0.6.0.20040821084900.028f3390@mail4.skillsoft.com> <000e01c4878e$8886d4e0$2901a8c0@atyss> Message-ID: <6.1.0.6.0.20040821103335.028f0800@mail4.skillsoft.com> From your description, I think I would try a procedural design to start. You can use different modules to hold different kinds of functions on a client list. The main program would create a client list and pass it to various functions to get some work done. It's possible that the client list itself should be a class that either extends list or wraps a list. This would be appropriate if you have several functions that operate on the list, such as getextlist(). These functions could become methods of ClientList. You could take this one step further and add higher level functions to ClientList such as copying and deleting files. These methods could use helper functions from your functional modules. Alternatively you could have a way to execute a function on each member of the ClientList. But this is likely overkill, from what you have said so far. Start with the functional organization. Keep an eye out for common operations on the client list or functions that take similar parameter lists. These will show you where you might want to create some classes. The code will tell you when it is time to use classes. Kent At 03:52 PM 8/21/2004 +0100, Bernard Lebel wrote: > > BTW from what you have shown here, using a class to hold the getextlist() > > function may be overkill. Classes are great when you have several >functions > > that have to work together, for example sharing common data in fields. If > > you have independent functions that you want to group together for > > convenience/modularity/testing/reuse, you can make them global functions >in > > a separate module without creating a class. > >Well you might be right. The classes are there mostly to encapsulate few >functions instead of having them all under the same level. But the module >has versatile functions: one is to work on a "client list", wich is the >cmClient class, while the other classes use the list. For instance, the >cmFile class is to copy, move and delete files over a large number of >computers, and the cmServices class is to handle remote processes of this >list. > >Like I said right now everything sits in the __init__.py file. I will >definitely give a try to your separte module setup suggestion. From python_newbie at vedorian.com Sat Aug 21 19:23:32 2004 From: python_newbie at vedorian.com (Kevin) Date: Sat Aug 21 19:23:44 2004 Subject: [Tutor] Exeption errors Message-ID: <000a01c487a3$95504020$30e57218@basp.phub.net.cable.rogers.com> I am playing around with Exeption Errors this is the code I did: x=raw_input("Enter a number: ") try: while int(x) != 1: print "Thats not 1" x=raw_input("Enter a number: ") except ValueError: print "that is not a number" it works to a point when I type in a number that is not a one it will keep saying Thats not 1, but when I put in a letter it will say that is not a number and then exit the program. How do I make it look again? Thanks Kevin --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.740 / Virus Database: 494 - Release Date: 8/16/04 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040821/cd833cbb/attachment.htm From python_newbie at vedorian.com Sat Aug 21 19:28:09 2004 From: python_newbie at vedorian.com (Kevin) Date: Sat Aug 21 19:28:16 2004 Subject: [Tutor] Exeption errors References: <000a01c487a3$95504020$30e57218@basp.phub.net.cable.rogers.com> Message-ID: <001201c487a4$3a606a40$30e57218@basp.phub.net.cable.rogers.com> I just changed the code to look like this and it works good. Is there a simpler way to do this? def one(): x=raw_input("Enter a number: ") try: while int(x) != 1: print "Thats not 1" x=raw_input("Enter a number: ") except ValueError: print "that is not a number" one() else: print "Thats the number 1!!" one() ----- Original Message ----- From: Kevin To: Python Sent: Saturday, August 21, 2004 1:23 PM Subject: [Tutor] Exeption errors I am playing around with Exeption Errors this is the code I did: x=raw_input("Enter a number: ") try: while int(x) != 1: print "Thats not 1" x=raw_input("Enter a number: ") except ValueError: print "that is not a number" it works to a point when I type in a number that is not a one it will keep saying Thats not 1, but when I put in a letter it will say that is not a number and then exit the program. How do I make it look again? Thanks Kevin --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.740 / Virus Database: 494 - Release Date: 8/16/04 ------------------------------------------------------------------------------ _______________________________________________ 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/20040821/0aff75af/attachment.html From dyoo at hkn.eecs.berkeley.edu Sat Aug 21 19:43:52 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Aug 21 19:44:01 2004 Subject: [Tutor] Problem with file() In-Reply-To: <003e01c48776$1f079da0$2901a8c0@atyss> Message-ID: On Sat, 21 Aug 2004, Bernard Lebel wrote: > oExtList = file( sListPath, 'r' ) > > Traceback (most recent call last): > File "", line 1, in ? > File "C:\Python23\lib\ClientsManager\__init__.py", line 104, in getextlist > oExtList = file( sListPath, 'r' ) > TypeError: this constructor takes no arguments Hi Bernard, The error says that it's having a problem calling: oExtList = file( sListPath, 'r' ) but there's no such line that I can see in your posted code. The closest thing I see to is is: > oExtList = file( sListPath ) Is it possible that you edited your code before or after getting the error message? I don't think the error message is correctly pointing to the right line. Are you sure you're posting up the updated code? Here's one way to get the "this constructor takes no arguments" kind of error: ### >>> class Foo: ... pass ... >>> Foo(1, 2, 3) Traceback (most recent call last): File "", line 1, in ? TypeError: this constructor takes no arguments ### So the error is trying to say that a class is being instantiated incorrectly, but I don't see where yet. It might help if you attach: C:\Python23\lib\ClientsManager\__init__.py in your next reply; let us check something. Good luck to you. From kent_johnson at skillsoft.com Sat Aug 21 20:00:44 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sat Aug 21 20:01:55 2004 Subject: [Tutor] Exeption errors In-Reply-To: <000a01c487a3$95504020$30e57218@basp.phub.net.cable.rogers. com> References: <000a01c487a3$95504020$30e57218@basp.phub.net.cable.rogers.com> Message-ID: <6.1.0.6.0.20040821135453.0287fbb8@mail4.skillsoft.com> Kevin, You have to get the try block into the loop, so the loop will continue after an exception is raised. This is a little tricky because the loop condition (int(x) != 1) itself is raising the exception. One solution is to use an infinite loop with a break condition, like this: while True: x=raw_input("Enter a number: ") try: x=int(x) if x==1: break print "Thats not 1" except ValueError: print "that is not a number" I prefer this form of the loop anyway because it doesn't duplicate the input code. In general instead of this: x = doSomething() while not someCondition(x): x = doSomething() I prefer this: while True: x = doSomething() if someCondition(x): break Kent At 01:23 PM 8/21/2004 -0400, Kevin wrote: >I am playing around with Exeption Errors this is the code I did: >x=raw_input("Enter a number: ") >try: > while int(x) != 1: > print "Thats not 1" > x=raw_input("Enter a number: ") >except ValueError: > print "that is not a number" > >it works to a point when I type in a number that is not a one it will keep >saying Thats not 1, but when I put in a letter it will say that is not a >number and then exit the program. How do I make it look again? > >Thanks >Kevin > > >--- >Outgoing mail is certified Virus Free. >Checked by AVG anti-virus system >(http://www.grisoft.com). >Version: 6.0.740 / Virus Database: 494 - Release Date: 8/16/04 >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From alan.gauld at blueyonder.co.uk Sat Aug 21 20:28:25 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Aug 21 20:27:23 2004 Subject: [Tutor] Frames and the grid manager References: <200408211547.23865.klas.martelleur@telia.com> Message-ID: <014e01c487ac$a60a3cf0$6401a8c0@xp> Hi Klas, > I have desigend a small gui for my convert program. I > have used the grid manager and placed everything in the > master frame. I now plan to expand my program a bit > more to make it possible to convert a few other types > of files. I then think it would be best to separate > my gui into frames. Frames are just widgets like any other widget. You can use them with the grid or packer or placer. You just treat the whole frame as a unit. In fact you can even use the packer to place controls inside a frame with is itself placed via a grid. Or you can use a grid in the Frame but the packer to stack up the frames. This is how I tend to build my GUIs - I use a grid or the packer to build frames which make up horizontal strips of my interface and then pack the frames on top of each other to form the final outer frame. For example: menuFrame toolbarFrame inputFrame displayFrame buttonFame statusFrame Or if I wanted the buttons down the right hand side I'd put the menu and toolbar along the top then create a grid with the input & display on the left, the buttons on the right and finally the statusbar at the bottom. Using frames for building GUIs is a lot like using functions to write code, you can very easily move things around and reorganize the GUI using frames. This is one reason I find most graphical GUI builders counter productive, its much faster to reshape a GUI when I'm using the Python prompt and a few predefined frames than moving stuff about in a GUI builder. Have you tried creating a frame with some of your controls in and putting it onto your grid? What problems did you get? Alan G. From pythonTutor at venix.com Sat Aug 21 20:29:34 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Sat Aug 21 20:29:39 2004 Subject: [Tutor] Exeption errors In-Reply-To: <6.1.0.6.0.20040821135453.0287fbb8@mail4.skillsoft.com> References: <000a01c487a3$95504020$30e57218@basp.phub.net.cable.rogers.com> <6.1.0.6.0.20040821135453.0287fbb8@mail4.skillsoft.com> Message-ID: <1093112974.2185.43.camel@laptop.venix.com> One quibble. It is best to limit the try block to exactly what we mean to be testing. I'd recommend changing the code to look like this. while True: x=raw_input("Enter a number: ") try: x=int(x) # put the except immediately after what we mean to try except ValueError: print "that is not a number" # put the rest of the "normal processing" in a try/else block else: if x==1: break print "Thats not 1" On Sat, 2004-08-21 at 14:00, Kent Johnson wrote: > Kevin, > > You have to get the try block into the loop, so the loop will continue > after an exception is raised. This is a little tricky because the loop > condition (int(x) != 1) itself is raising the exception. > > One solution is to use an infinite loop with a break condition, like this: > while True: > x=raw_input("Enter a number: ") > try: > x=int(x) > if x==1: > break > > print "Thats not 1" > except ValueError: > print "that is not a number" > > I prefer this form of the loop anyway because it doesn't duplicate the > input code. In general instead of this: > x = doSomething() > while not someCondition(x): > x = doSomething() > > I prefer this: > while True: > x = doSomething() > if someCondition(x): > break > > Kent > > At 01:23 PM 8/21/2004 -0400, Kevin wrote: > >I am playing around with Exeption Errors this is the code I did: > >x=raw_input("Enter a number: ") > >try: > > while int(x) != 1: > > print "Thats not 1" > > x=raw_input("Enter a number: ") > >except ValueError: > > print "that is not a number" > > > >it works to a point when I type in a number that is not a one it will keep > >saying Thats not 1, but when I put in a letter it will say that is not a > >number and then exit the program. How do I make it look again? > > > >Thanks > >Kevin > > > > > >--- > >Outgoing mail is certified Virus Free. > >Checked by AVG anti-virus system > >(http://www.grisoft.com). > >Version: 6.0.740 / Virus Database: 494 - Release Date: 8/16/04 > >_______________________________________________ > >Tutor maillist - Tutor@python.org > >http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From Cantkirby at aol.com Sat Aug 21 20:56:26 2004 From: Cantkirby at aol.com (Cantkirby@aol.com) Date: Sat Aug 21 21:06:43 2004 Subject: [Tutor] Removal from Mail list Message-ID: <1cc.292fd2a7.2e58f4da@aol.com> Please take me off your e-mail list. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040821/cc7cd40f/attachment.html From alan.gauld at blueyonder.co.uk Sat Aug 21 21:12:48 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Aug 21 21:11:45 2004 Subject: [Tutor] Problem with file() References: <003e01c48776$1f079da0$2901a8c0@atyss><6.1.0.6.0.20040821084900.028f3390@mail4.skillsoft.com> <000e01c4878e$8886d4e0$2901a8c0@atyss> Message-ID: <015e01c487b2$d938c000$6401a8c0@xp> > > You don't seem to have included the code containing the problem. The > > traceback shows the error occurring at line 104 of __init__.py and you > seem > > to have included ClientsManager.py. > > The code is from __init__.py. The module is called ClientsManager. Right now > there is only a __init__.py file, containing all classes and functions. I'm confused. How can the module name be different to the file name? And naming a file __init__.py is probably a bad idea since anything with two underscores usually signifies something from the innards of Python itself. Or have you stumbled across some deep black magic of python that I haven't seen before?! Alan G From alan.gauld at blueyonder.co.uk Sat Aug 21 21:18:32 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Aug 21 21:17:29 2004 Subject: [Tutor] Exeption errors References: <000a01c487a3$95504020$30e57218@basp.phub.net.cable.rogers.com> Message-ID: <016801c487b3$a6282100$6401a8c0@xp> > it works to a point when I type in a number that is not a one it > will keep saying Thats not 1, but when I put in a letter it will > say that is not a number and then exit the program. Which is what you told it to do! :-) > How do I make it look again? Put the try/except inside the loop. while True: x=raw_input("Enter a number: ") try: if int(x) != 1: print "That's not 1" else: break except ValueError: print "that is not a number" Note the break line to exit the loop when a 1 is entered. Alan G. From python at bernardlebel.com Sat Aug 21 22:21:51 2004 From: python at bernardlebel.com (Bernard Lebel) Date: Sat Aug 21 21:19:35 2004 Subject: [Tutor] Problem with file() References: <003e01c48776$1f079da0$2901a8c0@atyss><6.1.0.6.0.20040821084900.028f3390@mail4.skillsoft.com> <000e01c4878e$8886d4e0$2901a8c0@atyss> <015e01c487b2$d938c000$6401a8c0@xp> Message-ID: <003001c487bc$80231240$2901a8c0@atyss> > > > You don't seem to have included the code containing the problem. > The > > > traceback shows the error occurring at line 104 of __init__.py and > you > > seem > > > to have included ClientsManager.py. > > > > The code is from __init__.py. The module is called ClientsManager. > Right now > > there is only a __init__.py file, containing all classes and > functions. > > I'm confused. How can the module name be different to the file name? > > And naming a file __init__.py is probably a bad idea since anything > with two underscores usually signifies something from the innards > of Python itself. > > Or have you stumbled across some deep black magic of python that > I haven't seen before?! > > Alan G > I rather that this black magic is the result of my inexperience with Python. There is no file called ClientsManager.py. There is however a folder of that name, placed in the Lib folder. I added the folder path to the Python paths. It seems to work perfectly so far..... unless there are some traps I should be aware of? Thanks Bernard From alan.gauld at blueyonder.co.uk Sat Aug 21 21:23:22 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Aug 21 21:22:18 2004 Subject: [Tutor] Frames and the grid manager References: <200408211547.23865.klas.martelleur@telia.com> <014e01c487ac$a60a3cf0$6401a8c0@xp> Message-ID: <017301c487b4$52e6b190$6401a8c0@xp> Hmm, This bit wasn't as clear as it should be: > menuFrame > toolbarFrame > inputFrame > displayFrame > buttonFame > statusFrame > > Or if I wanted the buttons down the right hand side I'd put > the menu and toolbar along the top then create a grid with > the input & display on the left, the buttons on the right > and finally the statusbar at the bottom. ie. I'd *pack* the menu bar and toolbar frames then create a new *grid* frame for the input and display on the left and buttons on the right. I'd then *pack* that in the original and finally *pack* the status bar. Hope that's clearer now. Alan g From bigapple631 at optonline.net Sat Aug 21 21:41:50 2004 From: bigapple631 at optonline.net (jason hochstein) Date: Sat Aug 21 21:41:53 2004 Subject: [Tutor] Class, input Message-ID: <000801c487b6$e70af870$bc4ebb18@hochstein> Hello,alI. am trying to get this program to allow the user to enter the money amounts and I also need it to stamp the date each time it returns info at the end. 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 a = Account(1000.00) a.deposit(550.23) a.deposit(100) a.withdraw(50) print a.getbalance() -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040821/aa6917ad/attachment.htm From PBoa at seznam.cz Sat Aug 21 22:31:07 2004 From: PBoa at seznam.cz (Pavel Brabec) Date: Sat Aug 21 22:31:01 2004 Subject: [Tutor] Infinite program Message-ID: <4127B10B.5050101@seznam.cz> Hi there, I have a program written in a single module. It should ask user what to do, than do it and ask what to do again. But I do not know how to re-execute efficiently the program. I tried 2 functions calling themselves ( e.g. function Ask() will call function DoIt() that will call function Ask() that will call...). I am beginner with programming but I think that this is not ideal flow of execution (reading Traceback is a horror) :-( and I do not think how to archive similar functionality. I have also tried to play with Built-In function reload() but i do not want to reload another imported module, I want to reload the one from which I am calling the reload(). Is there a possibility to do something like that? Regards, Pavel Brabec -- In the beginning was the word and the word was content-type: plain/text From python at bernardlebel.com Sat Aug 21 23:37:43 2004 From: python at bernardlebel.com (Bernard Lebel) Date: Sat Aug 21 22:35:38 2004 Subject: [Tutor] Infinite program References: <4127B10B.5050101@seznam.cz> Message-ID: <000a01c487c7$1c58a670$2901a8c0@atyss> Use a while loop. It will keep repeating until a false condition is met. Example: bRedo = True while bRedo == True: if .....: do something else: bRedo = False Cheers Bernard ----- Original Message ----- From: "Pavel Brabec" To: Sent: Saturday, August 21, 2004 9:31 PM Subject: [Tutor] Infinite program > Hi there, > > I have a program written in a single module. It should ask user what to > do, than do it and ask what to do again. But I do not know how to > re-execute efficiently the program. I tried 2 functions calling > themselves ( e.g. function Ask() will call function DoIt() that will > call function Ask() that will call...). I am beginner with programming > but I think that this is not ideal flow of execution (reading Traceback > is a horror) :-( and I do not think how to archive similar functionality. > > I have also tried to play with Built-In function reload() but i do not > want to reload another imported module, I want to reload the one from > which I am calling the reload(). Is there a possibility to do something > like that? > > Regards, > Pavel Brabec > > -- > In the beginning was the word > and the word was content-type: plain/text > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From klas.martelleur at telia.com Sat Aug 21 22:53:19 2004 From: klas.martelleur at telia.com (Klas Marteleur) Date: Sat Aug 21 22:53:05 2004 Subject: [Tutor] Frames and the grid manager In-Reply-To: <014e01c487ac$a60a3cf0$6401a8c0@xp> References: <200408211547.23865.klas.martelleur@telia.com> <014e01c487ac$a60a3cf0$6401a8c0@xp> Message-ID: <200408212253.19971.klas.martelleur@telia.com> Alan thanks for your reply I now think i have a little clearer picture of how to design my GUI. But how do i actually put some of my controls in another frame? If i would like for example to put my two push buttons in a separate frame, put that frame on row 3 column 2 in my master frame, and place my two buttons side by side in that frame using grid. How would the code look like? ..... # Create convert button self.convertButton = Button(master, command = self.doProcessFiles) self.convertButton.configure(text="Convert") self.convertButton.grid(row=3,column=1,sticky=E) # Create exit button self.exitButton = Button(master, command = self.doExit) self.exitButton.configure(text="Exit") self.exitButton.grid(row=3,column=2,sticky=E) ...... Many thanks for your patience with me. i really start enjoying python. Good brain exercice :) Klas From alan.gauld at blueyonder.co.uk Sat Aug 21 23:25:11 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Aug 21 23:24:06 2004 Subject: [Tutor] Frames and the grid manager References: <200408211547.23865.klas.martelleur@telia.com><014e01c487ac$a60a3cf0$6401a8c0@xp> <200408212253.19971.klas.martelleur@telia.com> Message-ID: <002201c487c5$5787a130$6401a8c0@xp> > If i would like for example to put my two push buttons in a separate frame, > put that frame on row 3 column 2 in my master frame, Just create a Frame (with the top frame as ots master) and make that the master of the buttons. Exactly as you do with the top level frame, it literally is no different to the top level frame of your GUI. win = Frame(top) butFrame = Frame(win) b1 = Button(butFrame) b1.pack() b2 = Button(butFrame) b2.pack() butFrame.pack() Ugly but should work.... Now just use grid instead of pack()... Alan G. From alan.gauld at blueyonder.co.uk Sat Aug 21 23:46:20 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Aug 21 23:45:14 2004 Subject: [Tutor] Problem with file() References: <003e01c48776$1f079da0$2901a8c0@atyss><6.1.0.6.0.20040821084900.028f3390@mail4.skillsoft.com><000e01c4878e$8886d4e0$2901a8c0@atyss><015e01c487b2$d938c000$6401a8c0@xp> <003001c487bc$80231240$2901a8c0@atyss> Message-ID: <003701c487c8$4b9966d0$6401a8c0@xp> > > And naming a file __init__.py is probably a bad idea since anything > > with two underscores usually signifies something from the innards > > of Python itself. > There is no file called ClientsManager.py. There is however a folder of that > name, placed in the Lib folder. I added the folder path to the Python paths. OK, What you have done is create a package not a module. The __init__.py is indeed a bit of Python magic that should really only be used for doing initialisation of the package (setting global values etc) and is rarely used in my experience (it just needs to exist since that's what tells Python that it's dealing with a package!) Normally what you'd do is a) Just create a file called ClientsManager.py located in a folder in your sys.path list. This thus becomes a module that you can import. Or, b) If it's a significant project with multiple related modules you might create a folder with a descriptive name and place an empty __init__.py file in the folder - thus making the folder a package. Then put all your modules (xxx.py, yyy.py etc) in there. You can then import your files with: import MyPackage.MyModule1, MyPackage.MyModule2 from MyPackage import MyModule3 etc. What you have done works because you are importing the package name which magically executes the __init__.py file. And by putting your code in the __init__.py file it does appear to function like a module. But that's extra work for you, more diskspace used, harder to distribute to others(coz they need to create a folder instead of just copy a file) and harder to maintain because all your code will wind up in files called __init__.py and most text editors will list filenames only not full paths... But thanks for the remninder because its so rare for me to create packages in Python that I'd forgotten all about __init__.py until you mentioned you created a folder... :-) HTH, Alan G. From iqbala-python at qwestip.net Sun Aug 22 00:26:03 2004 From: iqbala-python at qwestip.net (Asif Iqbal) Date: Sun Aug 22 00:26:06 2004 Subject: [Tutor] Process Taking more than 10% In-Reply-To: <01c501c48669$84a217c0$6401a8c0@xp> References: <41253055.5090305@omc-international.com.au> <01c501c48669$84a217c0$6401a8c0@xp> Message-ID: <20040821222602.GI15047@qwestip.net> On Fri, Aug 20, 2004 at 04:55:22AM +0100, Alan Gauld wrote: > > >There are easy ways to do this on both Unix and Windows and > > >there are harder ways. But if its only one OS we might as > > >well stick to the easy ways... :-) > > > I think on linux you would use popen and ps, > > Nope, the easy way is to use ps and awk... > > > but how is it done on windows? > > Assuming NT/W2K/XP > Open Task Manager, look at processes and sort by CPU... :-) I saw in perl a pkg called Proc::ProcessList that has a variable called pctcpu that has the CPU percentage of all a process Anything similar for Python? I really don't want to use that Perl module since it has a lot of requirements Thanks > > In both cases Python is the harder route. Right tool for > the job... ;-) > > Alan G. > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Asif Iqbal PGP Key: 0xE62693C5 KeyServer: pgp.mit.edu There's no place like 127.0.0.1 From idiot1 at netzero.net Sun Aug 22 00:34:42 2004 From: idiot1 at netzero.net (Kirk Bailey) Date: Sun Aug 22 00:35:41 2004 Subject: [Tutor] Captain concrete writes again! Message-ID: <4127CE02.8040805@netzero.net> Yep, I'm still here, and it's time to write some software. I just recovered from a disk drive wipe out thanks to a nasty virus that managed to get past my anti virus- the configuration was not sufficiently paranoid, and I lost a lot of stuff. Well, enough is enough, everything is going to get backed up onto my server. So I am taking the image unloader script for wikinehesa, and the image previewing script, and twisting both of them to suit to my evil intent- uploading and downloading any file I wish to/from one only predefined directory, 'archive' on a website of mine. While thinking of this, I thought the gang here might take some small interest in this for their own personal use. Now as is, it handles files just fine, go one and only one directory, the /images dir. This is simple to change. And the inventory program creates links to IMAGES in the images dir- so I change it to show ALL images in the images dir, and it should sing nicely. Binging it all together like your mother in law's best potato dumplings the next day is a simple html page with 2 forms- one to upload, one to download. Now the scripts are still on the slab in the lab, but this is the front end web page: http://www.tinylist.org/filearchive.shtml Now here is the interesting issue- one file, 2, or 3? For instance, consider a script with NO input provided. It pops out the page that link displays. Give it a GET command of DISPLAY, the thing pops out a page with all the files as links. Give it a POST method, it establishes a connection and uploads the file, and pops out a display page- but this is a rather complex script and a total rewrite. Minor modifications of 2 existing scripts and the things get the job done quick and simple. Anyone want to comment on this, make suggestions, evil lymerics, or just kick the can around? -- -Blessed Be! Kirk Bailey kniht http://www.tinylist-org/ Freedom software +-----+ Free list services -http://www.listville.net/ | BOX | http://www.howlermonkey.net/ - Free Email service +-----+ In HER Service- http://www.pinellasintergroupsociety.org/ think http://www.sacredelectron.org/ - my personal screed pit. From iqbala-python at qwestip.net Sun Aug 22 00:36:10 2004 From: iqbala-python at qwestip.net (Asif Iqbal) Date: Sun Aug 22 00:36:12 2004 Subject: [Tutor] Removal from Mail list In-Reply-To: <1cc.292fd2a7.2e58f4da@aol.com> References: <1cc.292fd2a7.2e58f4da@aol.com> Message-ID: <20040821223610.GJ15047@qwestip.net> On Sat, Aug 21, 2004 at 02:56:26PM -0400, Cantkirby@aol.com wrote: > Please take me off your e-mail list. > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor mailto:tutor-request@python.org?subject=unsubscribe -- Asif Iqbal PGP Key: 0xE62693C5 KeyServer: pgp.mit.edu There's no place like 127.0.0.1 From idiot1 at netzero.net Sun Aug 22 01:43:25 2004 From: idiot1 at netzero.net (Kirk Bailey) Date: Sun Aug 22 02:12:25 2004 Subject: [Tutor] RE:Captain concrete writes again! Message-ID: <4127DE1D.9080907@netzero.net> ok, the lister is working, you can click it now. Think I'll get a soda and then write the other half of the utility. Bless me, I love this language... -- -Blessed Be! Kirk Bailey kniht http://www.tinylist-org/ Freedom software +-----+ Free list services -http://www.listville.net/ | BOX | http://www.howlermonkey.net/ - Free Email service +-----+ In HER Service- http://www.pinellasintergroupsociety.org/ think http://www.sacredelectron.org/ - my personal screed pit. From dyoo at hkn.eecs.berkeley.edu Sun Aug 22 05:20:39 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Aug 22 05:20:43 2004 Subject: [Tutor] Class, input In-Reply-To: <000801c487b6$e70af870$bc4ebb18@hochstein> Message-ID: On Sat, 21 Aug 2004, jason hochstein wrote: > Hello,alI. am trying to get this program to allow the user to enter the > money amounts and I also need it to stamp the date each time it returns > info at the end. [code cut] Hi Jason, Ok, you've stated a "home assignment"-style question. But what kind of problems are you running into? Are you having problems getting a timestamp, or are you having trouble getting user input, or something else? Please be more specific about what thing you'd like help with. Otherwise, the question devolves into "Please finish my homework assignment," which is something most Tutor volunteers will not touch. We've just gone through this sort of thing a few days ago: http://mail.python.org/pipermail/tutor/2004-August/031286.html I don't want to be grumpy again. Ask a better question. *grin* From dyoo at hkn.eecs.berkeley.edu Sun Aug 22 05:49:15 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Aug 22 05:49:23 2004 Subject: [Tutor] Process Taking more than 10% In-Reply-To: <20040821222602.GI15047@qwestip.net> Message-ID: On Sat, 21 Aug 2004, Asif Iqbal wrote: > On Fri, Aug 20, 2004 at 04:55:22AM +0100, Alan Gauld wrote: > > > >There are easy ways to do this on both Unix and Windows and there > > > >are harder ways. But if its only one OS we might as well stick to > > > >the easy ways... :-) > > > > > I think on linux you would use popen and ps, > > > > Nope, the easy way is to use ps and awk... > > > > > but how is it done on windows? > > > > Assuming NT/W2K/XP > > Open Task Manager, look at processes and sort by CPU... :-) > > I saw in perl a pkg called Proc::ProcessList that has a variable called > pctcpu that has the CPU percentage of all a process Hi Asif, There is a module in SciPy (scipy1.proc) that does it for Linux: http://www.scipy.org/cvs/viewcvs/map?rmurl=http%3A//scipy.net/cgi-bin/viewcvsx.cgi/scipy1/proc.py%3Frev%3DHEAD%26content-type%3Dtext/vnd.viewcvs-markup There's another for Windows: http://tgolden.sc.sabren.com/python/wmi.html A strong need for unification exists that has not been filled yet. At the moment, I can't find a single Python module that tries to abstract the process handling of different architectures as Perl's Proc::ProcessTable. And people have asked for it before: http://groups.google.com/groups?q=processtable+python&hl=en&lr=&ie=UTF-8&selm=abru9d.3vshe85.1%40kserver.org&rnum=1 Hope this helps! From dyoo at hkn.eecs.berkeley.edu Sun Aug 22 05:57:22 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Aug 22 05:57:30 2004 Subject: [Tutor] Infinite program In-Reply-To: <4127B10B.5050101@seznam.cz> Message-ID: On Sat, 21 Aug 2004, Pavel Brabec wrote: > I have also tried to play with Built-In function reload() but i do not > want to reload another imported module, I want to reload the one from > which I am calling the reload(). Is there a possibility to do something > like that? Hi Pavel, Ah! reload() is not meant to be used as a way to do "looping" iteration. It's really meant to do a refresh on a particular module during an interactive Python session. So don't do that. *grin* Instead, I think you're looking for loops. The tutorials in: http://www.python.org/topics/learn/non-prog.html show what loops are and how to make them work. In particular: http://www.honors.montana.edu/~jjc/easytut/easytut/node6.html#SECTION00610000000000000000 http://www.freenetpages.co.uk/hp/alan.gauld/tutloops.htm should be really helpful: they have examples that show how to ask for something, over and over. Good luck to you! From s4046441 at student.uq.edu.au Sun Aug 22 06:14:53 2004 From: s4046441 at student.uq.edu.au (Ms Soo Chong) Date: Sun Aug 22 06:15:02 2004 Subject: [Tutor] Questions on CGI script Message-ID: <1987b419acaa.19acaa1987b4@uq.edu.au> An embedded message was scrubbed... From: Ms Soo Chong Subject: Re: [Tutor] Questions on CGI script Date: Sun, 22 Aug 2004 14:13:51 +1000 Size: 957 Url: http://mail.python.org/pipermail/tutor/attachments/20040822/9a5575f3/attachment-0001.mht From s4046441 at student.uq.edu.au Sun Aug 22 06:21:56 2004 From: s4046441 at student.uq.edu.au (Ms Soo Chong) Date: Sun Aug 22 06:22:02 2004 Subject: [Tutor] Server Error Message-ID: <17762617c87f.17c87f177626@uq.edu.au> Hi, Server error! The server encountered an internal error and was unable to complete your request. Error message: Premature end of script headers: basic4.py If you think this is a server error, please contact the webmaster Error 500 localhost Sun 22 Aug 2004 14:09:07 EST Apache/2.0.40 (Red Hat Linux) Kent, above shows the server error I got for another cgi script. That is when I type in the cgi script shown in: Writing CGI Programs in Python - Putting the pieces together. http://www.devshed.com/c/a/python/writing-cgi-programs-in-python I don't know why I encountered the server error. Please advice. Thank you. Shufen From dyoo at hkn.eecs.berkeley.edu Sun Aug 22 06:35:05 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Aug 22 06:35:17 2004 Subject: [Tutor] executing a function in a different file and class In-Reply-To: <011601c48701$f0522990$6401a8c0@xp> Message-ID: > Python doesn't support true golobal variables [text cut] > > So how does one make a global truly global? > > Thats such a yucky idea that Python won't let you, but it does provide > the import controls described above which allow you to fake it on a file > by file basis. Hi Vicki, Actually, it is possible to do something truly ugly here. It involves injecting something into the __builtins__ dictionary. [Warning to others: please do NOT do this in either testing or production code!] ### $ cat foo.py __builtins__['variable'] = "hello" $ cat bar.py import foo print variable $ python bar.py hello ### This '__builtins__' dictionary houses all of the Python builtins. Injecting your own variable there should make it visible everywhere. That being said, using this mechanism casually is almost certainly a Bad Idea. We show it, reluctantly, only because you asked. *grin* It's bad because, if we use this hack frequently, then looking at code like: ### import foo, bar, baz print variable ### there is no really good way of knowing where in the world the definition of 'variable' came from. Did it come from 'foo', or 'bar', 'or 'baz'? Any maintainer of the code will end up having to do global searches for global variables, and that's just silly: modules are meant to enforce modularity! So don't inject your own variables into __builtins__. Use the 'from some_module import some_name' mechanism instead, because it's semantically similar enough to how C's does 'extern', but with the advantage of documenting which module a 'global' is coming from. ### $ cat foo_fixed.py variable = 'hello' $ cat bar_fixed.py from foo_fixed import variable print variable $ python bar_fixed.py hello ### Hope this helps! From dyoo at hkn.eecs.berkeley.edu Sun Aug 22 06:44:12 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Aug 22 06:44:16 2004 Subject: [Tutor] Server Error In-Reply-To: <17762617c87f.17c87f177626@uq.edu.au> Message-ID: On Sun, 22 Aug 2004, Ms Soo Chong wrote: > Server error! > > The server encountered an internal error and was > unable to complete your request. > > Error message: > Premature end of script headers: basic4.py > > If you think this is a server error, please contact > the webmaster [text cut] > I don't know why I encountered the server error. > Please advice. Hi Shufen, The default error message that Apache HTTPD sends us is practically useless. *grin* We need to get the system to tell us more. Put the following at the very top of your Python program, right after the 'import cgi' statement: ### import cgitb; cgitb.enable() ### This enables the 'cgi traceback' module, which should show much better debugging messages than 'Premature end of script headers'. Devshed doesn't mention this in their tutorial only because the tutorial was written a year before 'cgitb' became part of the Standard Library. But now that it's widely available, let's use it. *grin* You can read more about 'cgitb' here: http://www.python.org/doc/lib/module-cgitb.html It'll also help if we can see the contents of 'basic4.py': can you post it up on the list? Good luck to you! From s4046441 at student.uq.edu.au Sun Aug 22 08:02:11 2004 From: s4046441 at student.uq.edu.au (Ms Soo Chong) Date: Sun Aug 22 08:02:17 2004 Subject: [Tutor] Server Error Message-ID: <176aed17be95.17be95176aed@uq.edu.au> Hi, Thanks Danny for your prompt reply. Actually, the server error shown in my previous mail includes import cgitb; cgitb.enable(), thats why I don't understand. Sorry that I didn't make myself clear. But still thanks to you. The following is my basic4.py, please help me to take a look. I sort of typed in word by word as shown in devshed. So please pardon me if I typed in some stuffs that is not needed. ;D ################################################################### #!/usr/bin/python #Created on: 20/08/04 import sys sys.stderr = sys.stdin #Import the regular expression module. import re #Import the CGI module. import cgi import cgitb; cgitb.enable() #Specify the filename of the template file. TemplateFile = "/html/sf/template.html" #Specify the filename of the form to show the user. FormFile = "/html/sf/form.html" #Define a new function called Display. #it takes one parameter - a string to Display. def Display(Content): TemplateHandle = open(TemplateFile, "r") #open in read mode only. #read the entire file as a string TemplateInput = TemplateHandle.read() TemplateHandle.close() #close the file. #This defines an exception string in case #our template file is messed up. BadTemplateException = "There was a problem with the HTML template." SubResult = re.subn("