From dyoo at hkn.eecs.berkeley.edu Sun Oct 1 04:54:07 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 30 Sep 2006 19:54:07 -0700 (PDT) Subject: [Tutor] Monte Carlo method modules & references In-Reply-To: <581.60dfd21.325037e9@aol.com> References: <581.60dfd21.325037e9@aol.com> Message-ID: > I am searching for monte carlo and two- person game, also monte carlo > statistical ampling distribution. Thanks. Hi William, Ok... so what do you need help in? If you're asking how to do research on those subjects, we're probably not the best people to ask. This group is dedicated to helping with general programming in Python, with a slant toward beginners. If you have a programming question, that's something we can really sink our teeth into. Otherwise, we won't claim any special expertise on simulation methods. Have you done a few Google searches with the term "monte carlo"? There's a whole bunch of useful material that can be found with a good search engine. You may also want to look at a resource like the Wikipedia, which has quite a lot of material on monte carlo methods. From ml.cyresse at gmail.com Sun Oct 1 13:53:49 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Mon, 02 Oct 2006 00:53:49 +1300 Subject: [Tutor] difflib - restoring from a unified diff? Message-ID: <451FAC4D.2000305@gmail.com> Hi all, I'm writing a wiki at the moment, and I want to store unified diffs to allow easy reverting between versions of a document. It appears that difflib.restore() can only generate original text from diffs returned from ndiff() or compare() which store the full text of both versions. As this offers no efficiency in storage space over storing the actual text, it doesn't much serve my purpose - does anyone know of a 3rd party module that, given a text and a unified diff, can return the altered text? I can probably write one myself if I sweat a bit, but I'd much rather use any pre-existing modules. Regards, Liam Clarke From rdm at rcblue.com Sun Oct 1 15:03:00 2006 From: rdm at rcblue.com (Dick Moores) Date: Sun, 01 Oct 2006 06:03:00 -0700 Subject: [Tutor] Puzzled by print lst.sort() In-Reply-To: <20060930203724.GB1458@madhosh.dhoomketu.net.in> References: <7.0.1.0.2.20060930030312.07015bb8@rcblue.com> <451E4558.3000101@gmail.com> <7.0.1.0.2.20060930044209.06497910@rcblue.com> <451E5E0E.2000002@gmail.com> <7.0.1.0.2.20060930104527.06b19950@rcblue.com> <20060930203724.GB1458@madhosh.dhoomketu.net.in> Message-ID: <7.0.1.0.2.20061001054738.06fc8460@rcblue.com> At 01:37 PM 9/30/2006, Shantanoo Mahajan wrote: >Maybe following is helpful: > > >>> a=[3,2,1] > >>> b=a[:] > >>> b.sort() > >>> c=sorted(a) > >>> print a,b,c > >>> [3, 2, 1] [1, 2, 3] [1, 2, 3] > >>> > >Shantanoo Sorry to be dense, but I don't see what showing what happens to a copy of list a adds to the explanation: >>> a = [3,2,1] >>> b = a[:] >>> b.sort() >>> b [1, 2, 3] >>> given that: >>> a = [3,2,1] >>> a.sort() >>> a [1, 2, 3] >>> I suppose I've misunderstood how you were trying to assist me. Thanks, Dick From ml.cyresse at gmail.com Sun Oct 1 15:15:47 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Mon, 02 Oct 2006 02:15:47 +1300 Subject: [Tutor] Puzzled by print lst.sort() In-Reply-To: <7.0.1.0.2.20061001054738.06fc8460@rcblue.com> References: <7.0.1.0.2.20060930030312.07015bb8@rcblue.com> <451E4558.3000101@gmail.com> <7.0.1.0.2.20060930044209.06497910@rcblue.com> <451E5E0E.2000002@gmail.com> <7.0.1.0.2.20060930104527.06b19950@rcblue.com> <20060930203724.GB1458@madhosh.dhoomketu.net.in> <7.0.1.0.2.20061001054738.06fc8460@rcblue.com> Message-ID: <451FBF83.9040203@gmail.com> Dick Moores wrote: > At 01:37 PM 9/30/2006, Shantanoo Mahajan wrote: > >> Maybe following is helpful: >> >> >>>>> a=[3,2,1] >>>>> b=a[:] >>>>> b.sort() >>>>> c=sorted(a) >>>>> print a,b,c >>>>> [3, 2, 1] [1, 2, 3] [1, 2, 3] >>>>> >>>>> >> Shantanoo >> > > Sorry to be dense, but I don't see what showing what happens to a > copy of list a adds to the explanation: > >>> a = [3,2,1] > >>> b = a[:] > >>> b.sort() > >>> b > [1, 2, 3] > >>> > > given that: > > >>> a = [3,2,1] > >>> a.sort() > >>> a > [1, 2, 3] > >>> > > I suppose I've misunderstood how you were trying to assist me. > > Thanks, > > Dick > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > I think what Shantanoo was getting at was the reference thing, i.e., >>> a = [3,2,1] >>> b = a[:] >>> b.sort() >>> a [3, 2, 1] >>> b [1, 2, 3] >>> As opposed to >>> a = [3,2,1] >>> b = a >>> b.sort() >>> a [1, 2, 3] >>> b [1, 2, 3] >>> You may not always have access to Python 2.4. Regards, Liam Clarke From ph34r_th3_d4rkn3s at hotmail.com Sun Oct 1 15:17:42 2006 From: ph34r_th3_d4rkn3s at hotmail.com (mike viceano) Date: Sun, 01 Oct 2006 07:17:42 -0600 Subject: [Tutor] error message Message-ID: hello i wrote a litle program ware you pick a number and the computer guesses it and i recently decided to make it so it dosint reguess numbers but now i get a error message here is the program def number(number): from random import randrange guess=randrange(number*2) print guess guessed.append(guess) guesses=1 guessed=[] while guess !=number: guess=randrage(number*2) if guess not in guessed: guessed.append(guess) #here is ware the problem is guesses=guesses+1 print"i got the number",number,"number","in",guesses,"guesses" and here is the error Traceback (most recent call last): File "", line 1, in -toplevel- guess.number(10) File "/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/site-packages/guess.py", line 5, in number guessed.append(guess) UnboundLocalError: local variable 'guessed' referenced before assignment any help is great _________________________________________________________________ Express yourself - download free Windows Live Messenger themes! http://clk.atdmt.com/MSN/go/msnnkwme0020000001msn/direct/01/?href=http://imagine-msn.com/themes/vibe/default.aspx?locale=en-us&source=hmtagline From kent37 at tds.net Sun Oct 1 15:50:50 2006 From: kent37 at tds.net (Kent Johnson) Date: Sun, 01 Oct 2006 09:50:50 -0400 Subject: [Tutor] difflib - restoring from a unified diff? In-Reply-To: <451FAC4D.2000305@gmail.com> References: <451FAC4D.2000305@gmail.com> Message-ID: <451FC7BA.7060004@tds.net> Liam Clarke wrote: > Hi all, > > I'm writing a wiki at the moment, and I want to store unified diffs to > allow easy reverting between versions of a document. It appears that > difflib.restore() can only generate original text from diffs returned > from ndiff() or compare() which store the full text of both versions. > > As this offers no efficiency in storage space over storing the actual > text, it doesn't much serve my purpose - does anyone know of a 3rd party > module that, given a text and a unified diff, can return the altered > text? I can probably write one myself if I sweat a bit, but I'd much > rather use any pre-existing modules. I don't see a python module for this but you could use os.system() to invoke patch. Kent From kent37 at tds.net Sun Oct 1 15:56:00 2006 From: kent37 at tds.net (Kent Johnson) Date: Sun, 01 Oct 2006 09:56:00 -0400 Subject: [Tutor] error message In-Reply-To: References: Message-ID: <451FC8F0.2090306@tds.net> mike viceano wrote: > hello i wrote a litle program ware you pick a number and the computer > guesses it and i recently decided to make it so it dosint reguess > numbers but now i get a error message > > here is the program > > def number(number): > from random import randrange > guess=randrange(number*2) > print guess > guessed.append(guess) > guesses=1 > guessed=[] > while guess !=number: > guess=randrage(number*2) > if guess not in guessed: > guessed.append(guess) #here is ware the problem is > guesses=guesses+1 > print"i got the number",number,"number","in",guesses,"guesses" > > and here is the error > > Traceback (most recent call last): > File "", line 1, in -toplevel- > guess.number(10) > File > "/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/site-packages/guess.py", > line 5, in number > guessed.append(guess) > UnboundLocalError: local variable 'guessed' referenced before assignment It pays to read the traceback carefully, this one is giving you a lot of good clues. First, the error is at line 5. This is the *first* line with "guessed.append(guess)", not the one you have commented. Second, the error message is that 'guessed' is referenced before assignment. Where is 'guessed' assigned? Two lines later, on line 7 with "guessed=[]" Do you know how to fix it now? Kent From andrew.arobert at gmail.com Sun Oct 1 17:52:34 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Sun, 01 Oct 2006 11:52:34 -0400 Subject: [Tutor] Python code to split and reassemble files Message-ID: <451FE442.70205@gmail.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi guys, Awhile back, I believe I saw a cookbook recipe for splitting and reassembling text/binary files. Does anyone know where this or something similar can be found? I am working on a file transfer mechanism via MQSeries and breaking large files to smaller chunks would improve efficiency. - -- Thank you, Andrew Robert Senior MQ Engineer Information Technologies MFS Investment Management Phone: 617-954-5882 E-mail: arobert at mfs.com Linux User Number: #201204 -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.1 (MingW32) Comment: GnuPT 2.7.2 iD4DBQFFH+RCDvn/4H0LjDwRAtQQAKCeKSCHnsKa5tXye6/bJHm551hyrgCVEp2K aScfnRPpxVgjJPyM/zqo3Q== =6LHh -----END PGP SIGNATURE----- From andrew.arobert at gmail.com Sun Oct 1 18:11:43 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Sun, 01 Oct 2006 12:11:43 -0400 Subject: [Tutor] Python code to split and reassemble files In-Reply-To: <451FE442.70205@gmail.com> References: <451FE442.70205@gmail.com> Message-ID: <451FE8BF.8090006@gmail.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Never mind.. :) found it at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/224800 However, if someone has something better, I would be very interested. Andrew Robert wrote: > Hi guys, > > Awhile back, I believe I saw a cookbook recipe for splitting and > reassembling text/binary files. > > Does anyone know where this or something similar can be found? > > I am working on a file transfer mechanism via MQSeries and breaking > large files to smaller chunks would improve efficiency. > -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.1 (MingW32) Comment: GnuPT 2.7.2 iD8DBQFFH+i/Dvn/4H0LjDwRAr6dAJ48jTQzjWNPEfB3RLkOk9Z93QOalQCcDubg Fv7y2wpg/kEgt+f6vZwfkdA= =4c84 -----END PGP SIGNATURE----- From kent37 at tds.net Sun Oct 1 18:18:37 2006 From: kent37 at tds.net (Kent Johnson) Date: Sun, 01 Oct 2006 12:18:37 -0400 Subject: [Tutor] Python code to split and reassemble files In-Reply-To: <451FE442.70205@gmail.com> References: <451FE442.70205@gmail.com> Message-ID: <451FEA5D.1010807@tds.net> Andrew Robert wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Hi guys, > > Awhile back, I believe I saw a cookbook recipe for splitting and > reassembling text/binary files. > > Does anyone know where this or something similar can be found? Searching the cookbook for 'split file' finds this: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/224800 Kent From kefka.palazzo1 at gmail.com Sun Oct 1 20:19:50 2006 From: kefka.palazzo1 at gmail.com (Kefka Palazzo) Date: Sun, 1 Oct 2006 14:19:50 -0400 Subject: [Tutor] Help Message-ID: OK, first of all, I just started learning python a few hours ago so deal with me here. I'm picking up quite fast on Python since I took a C++ class a year ago when i was 13. However, before I go deep into learning it, I want to know if Python will work for the purpouses I need. I am trying to learn a programming language good for programming entire games (core functions too) similar to both the Final Fantasy and Metroid series. From the book I'm learning from (Python Programming for the Absolute Beginner, by Michael Dawsom) it seems like within a week or two I'll have a basic grasp on most of the functions, but I want to know if it will be worth it for what I need it for or if I would be better off learning something different (and harder >.<) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061001/899c9ccc/attachment.html From gtnorton at earthlink.net Sun Oct 1 21:20:39 2006 From: gtnorton at earthlink.net (Glenn T Norton) Date: Sun, 01 Oct 2006 14:20:39 -0500 Subject: [Tutor] Help In-Reply-To: References: Message-ID: <45201507.8070209@earthlink.net> Kefka Palazzo wrote: > OK, first of all, I just started learning python a few hours ago so > deal with me here. > > I'm picking up quite fast on Python since I took a C++ class a year > ago when i was 13. However, before I go deep into learning it, I want > to know if Python will work for the purpouses I need. > > I am trying to learn a programming language good for programming > entire games (core functions too) similar to both the Final Fantasy > and Metroid series. From the book I'm learning from (Python > Programming for the Absolute Beginner, by Michael Dawsom) it seems > like within a week or two I'll have a basic grasp on most of the > functions, but I want to know if it will be worth it for what I need > it for or if I would be better off learning something different (and > harder >.<) > >------------------------------------------------------------------------ > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > I'm not a game writer, but there a good quote on the home page from Firaxis Games http://www.python.org/about/quotes/ ( bottom of page ) Good Luck, Glenn -- "What's an Ear? ... A Jar and with a War of course! " Why Programmers are Lonely - Reason #14 Glenn Norton Application Developer Nebraska.gov 1-402-471-2777 glenn at nebraska.gov From wescpy at gmail.com Sun Oct 1 21:49:44 2006 From: wescpy at gmail.com (wesley chun) Date: Sun, 1 Oct 2006 12:49:44 -0700 Subject: [Tutor] Help In-Reply-To: References: Message-ID: <78b3a9580610011249u298b09c8g42b33e1ea1e6507e@mail.gmail.com> > I am trying to learn a programming language good for programming entire > games (core functions too) check out the PyGame engine: http://pygame.org download the games written on top of PyGame that appear to match the functionality you're looking for. if you learn Python at the same time, tweaking those games and changing their functionality will help you learn it even faster. good luck! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From kent37 at tds.net Sun Oct 1 23:20:59 2006 From: kent37 at tds.net (Kent Johnson) Date: Sun, 01 Oct 2006 17:20:59 -0400 Subject: [Tutor] Help In-Reply-To: <78b3a9580610011249u298b09c8g42b33e1ea1e6507e@mail.gmail.com> References: <78b3a9580610011249u298b09c8g42b33e1ea1e6507e@mail.gmail.com> Message-ID: <4520313B.6070403@tds.net> wesley chun wrote: >> I am trying to learn a programming language good for programming entire >> games (core functions too) > > check out the PyGame engine: > http://pygame.org > > download the games written on top of PyGame that appear to match the > functionality you're looking for. if you learn Python at the same > time, tweaking those games and changing their functionality will help > you learn it even faster. You should also look at the PyGame Challenge web site: http://www.pyweek.org/ I'm not a game writer either but I have a few thoughts...my impression is that Python and PyGame are a good foundation for hobbyist games. The PyGame and PyWeek games are good examples. I doubt that you could write a commercial quality game like Final Fantasy using just these tools though. Commercial games have highly optimized game engines. Some of them use Python as scripting engines for high-level game play; I doubt that any commercial games use Python for their core game engine. On the other hand, you are a long way from being able to write Final Fantasy. You need to start small and develop your skills. Python and PyGame should be well suited for this. You might want to read this: http://tinyurl.com/hc6xc which says in part, "Starcraft, Everquest and Quake were all made by teams of professionals who had budgets usually million dollar plus. More importantly though, all of these games were made by people with a lot of experience at making games. They did not just decide to make games and turned out mega-hit games, they started out small and worked their way up. This is the point that anyone who is interested in getting into game development needs to understand and repeat, repeat, repeat until it becomes such a part of your mindset that you couldn?t possibly understand life without this self evident, universal truth." and here are more links: http://en.wikipedia.org/wiki/Game_programming http://www-cs-students.stanford.edu/~amitp/gameprog.html I found these all by Googling "game programming language"; there are many more interesting links there. Good luck, Kent From willshattuck at gmail.com Mon Oct 2 01:38:07 2006 From: willshattuck at gmail.com (Will Shattuck) Date: Sun, 1 Oct 2006 16:38:07 -0700 Subject: [Tutor] Creating Adventure Games Python Port - Chapter 2 Message-ID: Hi all, I thought that it would be a great idea to learn Python while porting the BASIC code from this book. So I printed all the pages, have them "bound" by a big binder clip, and read through the first bit. In Chapter 2 there is a type of "Choose Your Own Adventure" type section. Since I didn't have two quarters, but I did have my laptop, I put together a quick "pycoin.py" program to "flip" the coins. Since I am an extreme beginner I thought I would submit it for review. Here you go: ============================= import random coin1 = 0 coin2 = 0 coin1 = random.randint(1, 10) coin2 = random.randint(1, 10) if coin1 <= 5: print "Coin1 is Heads" else: print "Coin1 is Tails" if coin2 <= 5: print "Coin2 is Heads" else: print "Coin2 is Tails" ============================= -- Will Shattuck ( willshattuck.at.gmail.com ) Home Page: http://www.thewholeclan.com/will When you get to your wit's end, you'll find God lives there. From willshattuck at gmail.com Mon Oct 2 01:40:52 2006 From: willshattuck at gmail.com (Will Shattuck) Date: Sun, 1 Oct 2006 16:40:52 -0700 Subject: [Tutor] Is my Python install hosed? Message-ID: I'm going through the tutorial "Learning to Program" at http://www.freenetpages.co.uk/hp/alan.gauld/. I reached the section talking about sys.exit(). I typed it in as indicated, but I received errors rather than it actually exiting the Python Shell windows generated when starting IDLE. Here is the text: ============================== >>> import sys >>> sys.exit() Traceback (most recent call last): File "", line 1, in -toplevel- sys.exit() SystemExit ============================== I seem to have issues running some programs from the web, but not others. I do make sure that the prereqs are met. Thanks for any help, Will -- Will Shattuck ( willshattuck.at.gmail.com ) Home Page: http://www.thewholeclan.com/will When you get to your wit's end, you'll find God lives there. From john at fouhy.net Mon Oct 2 01:52:06 2006 From: john at fouhy.net (John Fouhy) Date: Mon, 2 Oct 2006 12:52:06 +1300 Subject: [Tutor] Is my Python install hosed? In-Reply-To: References: Message-ID: <5e58f2e40610011652k29fa7364u8527ad4f92174d02@mail.gmail.com> On 02/10/06, Will Shattuck wrote: > I'm going through the tutorial "Learning to Program" at > http://www.freenetpages.co.uk/hp/alan.gauld/. I reached the section > talking about sys.exit(). I typed it in as indicated, but I received > errors rather than it actually exiting the Python Shell windows > generated when starting IDLE. Here is the text: > > ============================== > >>> import sys > >>> sys.exit() > > Traceback (most recent call last): > File "", line 1, in -toplevel- > sys.exit() > SystemExit > ============================== Nah, I get that too. I think it's an IDLE thing. >From the command line: Python 2.4.3 (#1, Mar 30 2006, 11:02:16) [GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> raise SystemExit Morpork:~ repton$ >From IDLE: IDLE 1.1.3 >>> raise SystemExit Traceback (most recent call last): File "", line 1, in -toplevel- raise SystemExit SystemExit >>> IDLE will just be catching the exception, I guess. You can do it yourself: >>> try: ... sys.exit() ... except SystemExit: ... print 'Not exiting!' ... Not exiting! -- John. From willshattuck at gmail.com Mon Oct 2 01:59:19 2006 From: willshattuck at gmail.com (Will Shattuck) Date: Sun, 1 Oct 2006 16:59:19 -0700 Subject: [Tutor] Is my Python install hosed? In-Reply-To: <5e58f2e40610011652k29fa7364u8527ad4f92174d02@mail.gmail.com> References: <5e58f2e40610011652k29fa7364u8527ad4f92174d02@mail.gmail.com> Message-ID: On 10/1/06, John Fouhy wrote: > On 02/10/06, Will Shattuck wrote: > > I'm going through the tutorial "Learning to Program" at > > http://www.freenetpages.co.uk/hp/alan.gauld/. I reached the section > > talking about sys.exit(). I typed it in as indicated, but I received > > errors rather than it actually exiting the Python Shell windows > > generated when starting IDLE. Here is the text: > > [...] > IDLE will just be catching the exception, I guess. You can do it yourself: > > >>> try: > ... sys.exit() > ... except SystemExit: > ... print 'Not exiting!' > ... > Not exiting! > > -- > John. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Thanks, didn't know about the Python command prompt. Worked there. Thanks :) Will From rdm at rcblue.com Mon Oct 2 02:02:11 2006 From: rdm at rcblue.com (Dick Moores) Date: Sun, 01 Oct 2006 17:02:11 -0700 Subject: [Tutor] Creating Adventure Games Python Port - Chapter 2 In-Reply-To: References: Message-ID: <7.0.1.0.2.20061001165722.035153d0@rcblue.com> At 04:38 PM 10/1/2006, Will Shattuck wrote: >Hi all, > >I thought that it would be a great idea to learn Python while porting >the BASIC code from this book. So I printed all the pages, have them >"bound" by a big binder clip, and read through the first bit. > >In Chapter 2 there is a type of "Choose Your Own Adventure" type >section. Since I didn't have two quarters, but I did have my laptop, >I put together a quick "pycoin.py" program to "flip" the coins. Since >I am an extreme beginner I thought I would submit it for review. Here >you go: > >============================= >import random > >coin1 = 0 >coin2 = 0 > >coin1 = random.randint(1, 10) >coin2 = random.randint(1, 10) > >if coin1 <= 5: > print "Coin1 is Heads" >else: > print "Coin1 is Tails" > >if coin2 <= 5: > print "Coin2 is Heads" >else: > print "Coin2 is Tails" >============================= Works fine, but instead of coin1 = random.randint(1, 10) coin2 = random.randint(1, 10) you could simplify by using coin1 = random.randrange(2) coin2 = random.randrange(2) and adjusting the rest of your code accordingly. Dick Moores From kent37 at tds.net Mon Oct 2 03:44:05 2006 From: kent37 at tds.net (Kent Johnson) Date: Sun, 01 Oct 2006 21:44:05 -0400 Subject: [Tutor] Creating Adventure Games Python Port - Chapter 2 In-Reply-To: <7.0.1.0.2.20061001165722.035153d0@rcblue.com> References: <7.0.1.0.2.20061001165722.035153d0@rcblue.com> Message-ID: <45206EE5.3080704@tds.net> Dick Moores wrote: > Works fine, but instead of > coin1 = random.randint(1, 10) > coin2 = random.randint(1, 10) > > you could simplify by using > coin1 = random.randrange(2) > coin2 = random.randrange(2) or maybe random sample: In [22]: random.sample(('heads', 'tails'), 1)[0] Out[22]: 'tails' Kent From admin at mynewno.com Sun Oct 1 11:26:28 2006 From: admin at mynewno.com (MyNewNo) Date: Sun, 1 Oct 2006 14:56:28 +0530 Subject: [Tutor] Changing Mobile and Landline Number no more a problem Message-ID: <20061001092628312.8DJafWuHFEsSiyCwCubJ@mail7.securedc.com> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061001/4f56ea91/attachment.html From paulino1 at sapo.pt Mon Oct 2 01:46:04 2006 From: paulino1 at sapo.pt (Paulino) Date: Mon, 02 Oct 2006 00:46:04 +0100 Subject: [Tutor] database web app, what tool? In-Reply-To: References: Message-ID: <4520533C.9090500@sapo.pt> Hi! Im a very biginner in programming and I started with python, witch I found much easier tahn i thought. I want to build an intranet page in my organization that shows some data from our financial aplication's database. For the starting point I would like it to show invoices lists per supplier and link each line to a pdf image of the selected invoice that is stored in a determined folder. The aim is only to make querys and show the results. No updates, nor insert's The database is MS SQL 2005 Right now I connect to the database via pymssql, and i can retrieve data and send it to a wx.Grid or to a reportlab pdf file, with platypus tables (a couple of months ago i would say i'd never be able to do it... and now i want to do more...) Now I want to send it to the browser so the administration can see it every time they need. What tool is more suitable? There are so many options! Zope-Plone have it's own web server, so less config is required. But i can't find any recipe or tutorial usefull for this task... there is also django, turbogears, webware, apache and mod-python..... Thank you Paulino From kent37 at tds.net Mon Oct 2 03:48:43 2006 From: kent37 at tds.net (Kent Johnson) Date: Sun, 01 Oct 2006 21:48:43 -0400 Subject: [Tutor] Changing Mobile and Landline Number no more a problem In-Reply-To: <20061001092628312.8DJafWuHFEsSiyCwCubJ@mail7.securedc.com> References: <20061001092628312.8DJafWuHFEsSiyCwCubJ@mail7.securedc.com> Message-ID: <45206FFB.9080106@tds.net> Sorry, a slip of the mouse let that through. Kent From john at fouhy.net Mon Oct 2 03:58:17 2006 From: john at fouhy.net (John Fouhy) Date: Mon, 2 Oct 2006 14:58:17 +1300 Subject: [Tutor] Creating Adventure Games Python Port - Chapter 2 In-Reply-To: <45206EE5.3080704@tds.net> References: <7.0.1.0.2.20061001165722.035153d0@rcblue.com> <45206EE5.3080704@tds.net> Message-ID: <5e58f2e40610011858k3e558a1bx2a94eff690fdb61b@mail.gmail.com> On 02/10/06, Kent Johnson wrote: > or maybe random sample: > In [22]: random.sample(('heads', 'tails'), 1)[0] > Out[22]: 'tails' I think random.choice would be a better option here: >>> random.choice(['heads', 'tails']) 'tails' >>> [random.choice(['heads', 'tails']) for i in range(10)] ['tails', 'tails', 'heads', 'tails', 'tails', 'tails', 'heads', 'heads', 'heads', 'heads'] -- John. From agilfoy at frontiernet.net Mon Oct 2 03:51:50 2006 From: agilfoy at frontiernet.net (Alan Gilfoy) Date: Mon, 02 Oct 2006 01:51:50 +0000 Subject: [Tutor] One of my 'baby step' programs Message-ID: <20061002015150.ox2ayuidpugcoc00@webmail.frontiernet.net> -code block- number = 3 running = True while running: guess = int(raw_input("Please enter a number : ")) #lets user guess a number if guess == number: print "Yay, you got the right number, good for you. But you don't get any prizes. Do I look like a walking ATM to you?" running = False #this causes the guess-again loop to start. elif guess < number: print "No, my number is higher than that" else: print "No, my number is lower than that." else: print "The number-guessing loop is over." print "Done." -end code block- Darnit, it's very simple, but I still like the fac tthat is does something to user input. From agilfoy at frontiernet.net Mon Oct 2 03:50:19 2006 From: agilfoy at frontiernet.net (Alan Gilfoy) Date: Mon, 02 Oct 2006 01:50:19 +0000 Subject: [Tutor] senior project Message-ID: <20061002015019.xkof1zhsi20oowcc@webmail.frontiernet.net> I am a senior at the School Without Walls in Rochester, NY. As such, I get to do a senior project. I decided to work on computer programming, since that is sometihng that I certianly think can hold my interest throughout the school year. (despite my compute rinteresat, I've never done anything much more advanced than HTML, for some reason) One of my community advisers suggested I start with Python. (he also suggested this mailing list) So far, I've liked the http://swaroopch.info/text/Byte_of_Python:Main_Page tutorial, for basics. From marc_a_poulin at yahoo.com Mon Oct 2 04:46:07 2006 From: marc_a_poulin at yahoo.com (Marc Poulin) Date: Sun, 1 Oct 2006 19:46:07 -0700 (PDT) Subject: [Tutor] Help In-Reply-To: Message-ID: <20061002024607.82989.qmail@web34102.mail.mud.yahoo.com> --- Kefka Palazzo wrote: > I am trying to learn a programming language good for > programming entire > games (core functions too) similar to both the Final > Fantasy and Metroid > series. From the book I'm learning from (Python > Programming for the Absolute > Beginner, by Michael Dawsom) it seems like within a > week or two I'll have a > basic grasp on most of the functions, but I want to > know if it will be worth > it for what I need it for or if I would be better > off learning something > different (and harder >.<) >From the http://panda3d.org website: Panda3D is a 3D engine: a library of subroutines for 3D rendering and game development. The library is C++ with a set of Python bindings. Game development with Panda3D usually consists of writing a Python program that controls the the Panda3D library. Panda3D was developed by Disney for their massively multiplayer online game, Toontown. It was released as free software in 2002. Panda3D is now developed jointly by Disney and Carnegie Mellon University's Entertainment Technology Center __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From willshattuck at gmail.com Mon Oct 2 05:06:38 2006 From: willshattuck at gmail.com (Will Shattuck) Date: Sun, 1 Oct 2006 20:06:38 -0700 Subject: [Tutor] Creating Adventure Games Python Port - Chapter 2 In-Reply-To: <5e58f2e40610011858k3e558a1bx2a94eff690fdb61b@mail.gmail.com> References: <7.0.1.0.2.20061001165722.035153d0@rcblue.com> <45206EE5.3080704@tds.net> <5e58f2e40610011858k3e558a1bx2a94eff690fdb61b@mail.gmail.com> Message-ID: On 10/1/06, John Fouhy wrote: > On 02/10/06, Kent Johnson wrote: > > or maybe random sample: > > In [22]: random.sample(('heads', 'tails'), 1)[0] > > Out[22]: 'tails' > > I think random.choice would be a better option here: > > >>> random.choice(['heads', 'tails']) > 'tails' > >>> [random.choice(['heads', 'tails']) for i in range(10)] > ['tails', 'tails', 'heads', 'tails', 'tails', 'tails', 'heads', > 'heads', 'heads', 'heads'] > Thanks all. My main intent is to keep it simple. I may expand some of these code samples into my own sort or tutorial on python. Some say that if you can teach something to others then you know that you know the subject. I'll research these out and pick what fits for me. Thanks all :) Will -- Will Shattuck ( willshattuck.at.gmail.com ) Home Page: http://www.thewholeclan.com/will When you get to your wit's end, you'll find God lives there. From ml.cyresse at gmail.com Mon Oct 2 05:28:33 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Mon, 02 Oct 2006 16:28:33 +1300 Subject: [Tutor] database web app, what tool? In-Reply-To: <4520533C.9090500@sapo.pt> References: <4520533C.9090500@sapo.pt> Message-ID: <45208761.1010207@gmail.com> Paulino wrote: Hi Paulino, Tough question that. What is your existing web server? That'd be a good starting point. Zope/Plone are great, but they have a steep learning curve that doesn't seem essential to what you're doing. Django is simpler, but once again, doesn't immediately fit to what you're trying to do, but it could do. I'd say just a straight mod_python would be simplest, to be honest, but it really depends on what you're doing. Regards, Liam Clarke > Hi! > > Im a very biginner in programming and I started with python, witch I > found much easier tahn i thought. > > I want to build an intranet page in my organization that shows some data > from our financial aplication's database. > > For the starting point I would like it to show invoices lists per > supplier and link each line to a pdf image of the selected invoice that > is stored in a determined folder. > > The aim is only to make querys and show the results. No updates, nor > insert's > > The database is MS SQL 2005 > > > > Right now I connect to the database via pymssql, and i can retrieve data > and send it to a wx.Grid or to a reportlab pdf file, with platypus > tables (a couple of months ago i would say i'd never be able to do it... > and now i want to do more...) > > Now I want to send it to the browser so the administration can see it > every time they need. > > > What tool is more suitable? > > There are so many options! > > Zope-Plone have it's own web server, so less config is required. But i > can't find any recipe or tutorial usefull for this task... > > there is also django, turbogears, webware, apache and mod-python..... > > > Thank you > > > Paulino > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From wescpy at gmail.com Mon Oct 2 06:13:32 2006 From: wescpy at gmail.com (wesley chun) Date: Sun, 1 Oct 2006 21:13:32 -0700 Subject: [Tutor] senior project In-Reply-To: <20061002015019.xkof1zhsi20oowcc@webmail.frontiernet.net> References: <20061002015019.xkof1zhsi20oowcc@webmail.frontiernet.net> Message-ID: <78b3a9580610012113t6ab721fna94a2f1630acb88e@mail.gmail.com> > One of my community advisers suggested I start with Python. (he also > suggested this mailing list) take a look at "how to think like a computer scientist" by downey, elkner, etc. it was originally written for C++ and Java but Jeff Elkner, a high school programming AP instructor, ported it to Python. there are dead tree and online versions available. http://www.ibiblio.org/obp/thinkCSpy/ good luck! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From rdm at rcblue.com Mon Oct 2 06:28:24 2006 From: rdm at rcblue.com (Dick Moores) Date: Sun, 01 Oct 2006 21:28:24 -0700 Subject: [Tutor] timeit at the command line Message-ID: <7.0.1.0.2.20061001210313.03c93d58@rcblue.com> C:\>python -m timeit -s"x=0" "while x<100:" " x+=1" 10000000 loops, best of 3: 0.123 usec per loop C:\>python -m timeit -s"for x in range(100):" " x+=1" Traceback (most recent call last): File "E:\Python25\lib\runpy.py", line 95, in run_module filename, loader, alter_sys) File "E:\Python25\lib\runpy.py", line 52, in _run_module_code mod_name, mod_fname, mod_loader) File "E:\Python25\lib\runpy.py", line 32, in _run_code exec code in run_globals File "E:\Python25\lib\timeit.py", line 285, in sys.exit(main()) File "E:\Python25\lib\timeit.py", line 249, in main t = Timer(stmt, setup, timer) File "E:\Python25\lib\timeit.py", line 116, in __init__ code = compile(src, dummy_src_name, "exec") File "", line 4 _t0 = _timer() ^ IndentationError: expected an indented block Is there a better way to indicate the indentation of " x+=1" (2 spaces in this case) ? For me, this usually works in a while loop, but so far, never in a for loop. says: "A multi-line statement may be given by specifying each line as a separate statement argument; indented lines are possible by enclosing an argument in quotes and using leading spaces. Multiple -s options are treated similarly." Thanks, Dick Moores From rabidpoobear at gmail.com Mon Oct 2 06:49:31 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sun, 01 Oct 2006 23:49:31 -0500 Subject: [Tutor] One of my 'baby step' programs In-Reply-To: <20061002015150.ox2ayuidpugcoc00@webmail.frontiernet.net> References: <20061002015150.ox2ayuidpugcoc00@webmail.frontiernet.net> Message-ID: <45209A5B.3060901@gmail.com> Alan Gilfoy wrote: > -code block- > > number = 3 > running = True > > while running: > guess = int(raw_input("Please enter a number : ")) #lets user guess a number > > if guess == number: > print "Yay, you got the right number, good for you. But you > don't get any prizes. Do I look like a walking ATM to you?" > running = False #this causes the guess-again loop to start. > elif guess < number: > print "No, my number is higher than that" > else: > print "No, my number is lower than that." > > else: > print "The number-guessing loop is over." > I had no idea you could have an 'else' tied to a 'while' loop. Interesting.... > print "Done." > > -end code block- > > Darnit, it's very simple, but I still like the fac tthat is does > something to user input. > you should look into the 'random' module. You can generate a random integer with the random.randint() function. Then us programmers who peek at your code can't cheat and choose 3 every time :) Good luck on your project! Any idea what it'll be yet? -Luke From john at fouhy.net Mon Oct 2 06:58:36 2006 From: john at fouhy.net (John Fouhy) Date: Mon, 2 Oct 2006 17:58:36 +1300 Subject: [Tutor] One of my 'baby step' programs In-Reply-To: <45209A5B.3060901@gmail.com> References: <20061002015150.ox2ayuidpugcoc00@webmail.frontiernet.net> <45209A5B.3060901@gmail.com> Message-ID: <5e58f2e40610012158t3ac1c733lc277588f2a5c7940@mail.gmail.com> On 02/10/06, Luke Paireepinart wrote: > I had no idea you could have an 'else' tied to a 'while' loop. > Interesting.... It allows you to distinguish between exiting the loop via a break and exiting the loop normally. eg: >>> for i in range(10): ... break ... else: ... print 'foo' ... >>> for i in range(10): ... pass ... else: ... print 'foo' ... foo >>> There was a discussion of for..else linked in Dr Dobb's Python URL recently: http://groups.google.com/group/comp.lang.python/browse_thread/thread/bc1d8038e65c449/ -- John. From rdm at rcblue.com Mon Oct 2 07:28:57 2006 From: rdm at rcblue.com (Dick Moores) Date: Sun, 01 Oct 2006 22:28:57 -0700 Subject: [Tutor] One of my 'baby step' programs In-Reply-To: <45209A5B.3060901@gmail.com> References: <20061002015150.ox2ayuidpugcoc00@webmail.frontiernet.net> <45209A5B.3060901@gmail.com> Message-ID: <7.0.1.0.2.20061001221312.05a6c9b0@rcblue.com> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061001/0fba7834/attachment.html From kent37 at tds.net Mon Oct 2 12:03:43 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 02 Oct 2006 06:03:43 -0400 Subject: [Tutor] One of my 'baby step' programs In-Reply-To: <45209A5B.3060901@gmail.com> References: <20061002015150.ox2ayuidpugcoc00@webmail.frontiernet.net> <45209A5B.3060901@gmail.com> Message-ID: <4520E3FF.9010003@tds.net> Luke Paireepinart wrote: > Alan Gilfoy wrote: >> -code block- >> >> number = 3 >> running = True >> >> while running: >> guess = int(raw_input("Please enter a number : ")) #lets user guess a number >> >> if guess == number: >> print "Yay, you got the right number, good for you. But you >> don't get any prizes. Do I look like a walking ATM to you?" >> running = False #this causes the guess-again loop to start. >> elif guess < number: >> print "No, my number is higher than that" >> else: >> print "No, my number is lower than that." >> >> else: >> print "The number-guessing loop is over." >> > I had no idea you could have an 'else' tied to a 'while' loop. > Interesting.... It's useful but in this case not necessary - since there is no 'break' within the loop, the 'else' clause will always be executed. That is correct behaviour in this case, so it would be better to leave out the else and just have the print. Kent From kent37 at tds.net Mon Oct 2 12:04:41 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 02 Oct 2006 06:04:41 -0400 Subject: [Tutor] senior project In-Reply-To: <20061002015019.xkof1zhsi20oowcc@webmail.frontiernet.net> References: <20061002015019.xkof1zhsi20oowcc@webmail.frontiernet.net> Message-ID: <4520E439.2050508@tds.net> Alan Gilfoy wrote: > I am a senior at the School Without Walls in Rochester, NY. As such, I > get to do a senior project. I decided to work on computer programming, > since that is sometihng that I certianly think can hold my interest > throughout the school year. > > (despite my compute rinteresat, I've never done anything much more > advanced than HTML, for some reason) > > One of my community advisers suggested I start with Python. (he also > suggested this mailing list) Welcome to Python! And congratulations for having a great advisor ;) > > So far, I've liked the > http://swaroopch.info/text/Byte_of_Python:Main_Page tutorial, for > basics. Are you asking for more suggestions? Kent From kent37 at tds.net Mon Oct 2 12:08:24 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 02 Oct 2006 06:08:24 -0400 Subject: [Tutor] timeit at the command line In-Reply-To: <7.0.1.0.2.20061001210313.03c93d58@rcblue.com> References: <7.0.1.0.2.20061001210313.03c93d58@rcblue.com> Message-ID: <4520E518.3030606@tds.net> Dick Moores wrote: > C:\>python -m timeit -s"x=0" "while x<100:" " x+=1" > 10000000 loops, best of 3: 0.123 usec per loop > > C:\>python -m timeit -s"for x in range(100):" " x+=1" > Traceback (most recent call last): > File "E:\Python25\lib\runpy.py", line 95, in run_module > filename, loader, alter_sys) > File "E:\Python25\lib\runpy.py", line 52, in _run_module_code > mod_name, mod_fname, mod_loader) > File "E:\Python25\lib\runpy.py", line 32, in _run_code > exec code in run_globals > File "E:\Python25\lib\timeit.py", line 285, in > sys.exit(main()) > File "E:\Python25\lib\timeit.py", line 249, in main > t = Timer(stmt, setup, timer) > File "E:\Python25\lib\timeit.py", line 116, in __init__ > code = compile(src, dummy_src_name, "exec") > File "", line 4 > _t0 = _timer() > ^ > IndentationError: expected an indented block > > > Is there a better way to indicate the indentation of " x+=1" (2 > spaces in this case) ? For me, this usually works in a while loop, > but so far, never in a for loop. Strange, your example works for me in Python 2.4 and 2.5: D:\>python -m timeit -s"x=0" "while x<100:" " x+=1" 10000000 loops, best of 3: 0.102 usec per loop Are you using 2.5 final or one of the earlier releases? Kent From rdm at rcblue.com Mon Oct 2 12:15:50 2006 From: rdm at rcblue.com (Dick Moores) Date: Mon, 02 Oct 2006 03:15:50 -0700 Subject: [Tutor] timeit at the command line In-Reply-To: <4520E518.3030606@tds.net> References: <7.0.1.0.2.20061001210313.03c93d58@rcblue.com> <4520E518.3030606@tds.net> Message-ID: <7.0.1.0.2.20061002031414.0614a650@rcblue.com> At 03:08 AM 10/2/2006, Kent Johnson wrote: >Dick Moores wrote: > > C:\>python -m timeit -s"x=0" "while x<100:" " x+=1" > > 10000000 loops, best of 3: 0.123 usec per loop > > > > C:\>python -m timeit -s"for x in range(100):" " x+=1" > > Traceback (most recent call last): > > File "E:\Python25\lib\runpy.py", line 95, in run_module > > filename, loader, alter_sys) > > File "E:\Python25\lib\runpy.py", line 52, in _run_module_code > > mod_name, mod_fname, mod_loader) > > File "E:\Python25\lib\runpy.py", line 32, in _run_code > > exec code in run_globals > > File "E:\Python25\lib\timeit.py", line 285, in > > sys.exit(main()) > > File "E:\Python25\lib\timeit.py", line 249, in main > > t = Timer(stmt, setup, timer) > > File "E:\Python25\lib\timeit.py", line 116, in __init__ > > code = compile(src, dummy_src_name, "exec") > > File "", line 4 > > _t0 = _timer() > > ^ > > IndentationError: expected an indented block > > > > > > Is there a better way to indicate the indentation of " x+=1" (2 > > spaces in this case) ? For me, this usually works in a while loop, > > but so far, never in a for loop. > >Strange, your example works for me in Python 2.4 and 2.5: >D:\>python -m timeit -s"x=0" "while x<100:" " x+=1" >10000000 loops, best of 3: 0.102 usec per loop > >Are you using 2.5 final or one of the earlier releases? 2.5 final. Dick From silence_for_unknown at yahoo.com Mon Oct 2 13:07:49 2006 From: silence_for_unknown at yahoo.com (Xie Chao) Date: Mon, 2 Oct 2006 04:07:49 -0700 (PDT) Subject: [Tutor] how to make a reference to part of list? Message-ID: <20061002110749.22422.qmail@web55208.mail.re4.yahoo.com> Namely, if list1 = {1, 2, 3}, and I wanna make a reference, say "ref", to list1's sublist (which is also of type list), say {2, 3}, so that when I make change to ref[0], then list1[1] will be changed! But how can I make such a reference, 3x! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061002/f373dc02/attachment.htm From agilfoy at frontiernet.net Mon Oct 2 13:34:36 2006 From: agilfoy at frontiernet.net (Alan Gilfoy) Date: Mon, 02 Oct 2006 11:34:36 +0000 Subject: [Tutor] My number-guessing program In-Reply-To: <45209A5B.3060901@gmail.com> References: <20061002015150.ox2ayuidpugcoc00@webmail.frontiernet.net> <45209A5B.3060901@gmail.com> Message-ID: <20061002113436.hsvg87haqqiso44g@webmail.frontiernet.net> Yeah, that's what the wiki-based tutorial mentioned. In fact, Lee Harr (my community adviser) also suggested using a random number. Quoting Luke Paireepinart : > Alan Gilfoy wrote: (the start of the code for my number-guessing thingamajig) >> >> else: >> print "The number-guessing loop is over." >> (some more code) My line: number = 3 Would I use 'number = random.randint()' in place of that, to have the relevant number be random? From kent37 at tds.net Mon Oct 2 13:57:31 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 02 Oct 2006 07:57:31 -0400 Subject: [Tutor] how to make a reference to part of list? In-Reply-To: <20061002110749.22422.qmail@web55208.mail.re4.yahoo.com> References: <20061002110749.22422.qmail@web55208.mail.re4.yahoo.com> Message-ID: <4520FEAB.5060902@tds.net> Xie Chao wrote: > Namely, if list1 = {1, 2, 3}, and I wanna make a reference, say > "ref", to list1's sublist (which is also of type list), say {2, 3}, so > that when I make change to ref[0], then list1[1] will be changed! > But how can I make such a reference, 3x! There is nothing built-in to Python that will let you do this. I don't think it would be too hard to write a class that does what you want for basic indexing operations. I would start with a copy of UserList (in module UserList). If you go beyond simple indexing and slicing I think you will have trouble. Say you have a class RefList that does what you want, and suppose you have a = [1, 2, 3] b = RefList(a, 1, 2) b is [2, 3] c = RefList(a, 0, 1) c is [1, 2] Now what is the result of d=b+c? Is it a RefList with two references to a, that looks like [1, 2, 2, 3]? What is the value of d after d[1] = 0? Is it [1, 0, 0, 3]? Can you say more about why you want to do this? Maybe there is another solution. By the way list literals in Python are written with square brackets [] not curly braces {}. Kent From silence_for_unknown at yahoo.com Mon Oct 2 14:18:24 2006 From: silence_for_unknown at yahoo.com (Xie Chao) Date: Mon, 2 Oct 2006 05:18:24 -0700 (PDT) Subject: [Tutor] how to make a reference to part of list? Message-ID: <20061002121824.52800.qmail@web55207.mail.re4.yahoo.com> 3Q very much! What I really want to get is a c-style array, a pointer to the beginning of part of a list (or whatever alike). for example, I want to mutate part of a list, of course, I can achieve this by passing the pair list and (begin, end) as parameters. but in some case, this manner is quite tedious and in efficient (I think so, at least in C-style language it is so)! I don't wanna get the '+' operator (which is powerful tool in scripting language), so I ignore this problem. thank you all the same! maybe this prolem looks silly, since I've just begun to study scripting language. ----- Original Message ---- From: Kent Johnson Cc: tutor at python.org Sent: Monday, October 2, 2006 7:57:31 PM Subject: Re: [Tutor] how to make a reference to part of list? Xie Chao wrote: > Namely, if list1 = {1, 2, 3}, and I wanna make a reference, say > "ref", to list1's sublist (which is also of type list), say {2, 3}, so > that when I make change to ref[0], then list1[1] will be changed! > But how can I make such a reference, 3x! There is nothing built-in to Python that will let you do this. I don't think it would be too hard to write a class that does what you want for basic indexing operations. I would start with a copy of UserList (in module UserList). If you go beyond simple indexing and slicing I think you will have trouble. Say you have a class RefList that does what you want, and suppose you have a = [1, 2, 3] b = RefList(a, 1, 2) b is [2, 3] c = RefList(a, 0, 1) c is [1, 2] Now what is the result of d=b+c? Is it a RefList with two references to a, that looks like [1, 2, 2, 3]? What is the value of d after d[1] = 0? Is it [1, 0, 0, 3]? Can you say more about why you want to do this? Maybe there is another solution. By the way list literals in Python are written with square brackets [] not curly braces {}. Kent _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061002/45df4cfc/attachment.htm From kent37 at tds.net Mon Oct 2 14:49:05 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 02 Oct 2006 08:49:05 -0400 Subject: [Tutor] how to make a reference to part of list? In-Reply-To: <20061002121824.52800.qmail@web55207.mail.re4.yahoo.com> References: <20061002121824.52800.qmail@web55207.mail.re4.yahoo.com> Message-ID: <45210AC1.90300@tds.net> Xie Chao wrote: > 3Q very much! > What I really want to get is a c-style array, a pointer to the > beginning of part of a list (or whatever alike). for example, I want to > mutate part of a list, of course, I can achieve this by passing the pair > list and (begin, end) as parameters. but in some case, this manner > is quite tedious and in efficient (I think so, at least in C-style > language it is so)! > I don't wanna get the '+' operator (which is powerful tool in > scripting language), so I ignore this problem. thank you all the same! > maybe this prolem looks silly, since I've just begun to > study scripting language. Take a look at numpy, it seems to do what you want: In [2]: from numpy import * In [4]: a=arange(10) In [5]: a Out[5]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) In [6]: b=a[3:5] In [7]: b Out[7]: array([3, 4]) In [8]: b[0]=10 In [9]: b Out[9]: array([10, 4]) In [10]: a Out[10]: array([ 0, 1, 2, 10, 4, 5, 6, 7, 8, 9]) http://numpy.scipy.org/ Kent From rabidpoobear at gmail.com Mon Oct 2 15:24:48 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 02 Oct 2006 08:24:48 -0500 Subject: [Tutor] My number-guessing program In-Reply-To: <20061002113436.hsvg87haqqiso44g@webmail.frontiernet.net> References: <20061002015150.ox2ayuidpugcoc00@webmail.frontiernet.net> <45209A5B.3060901@gmail.com> <20061002113436.hsvg87haqqiso44g@webmail.frontiernet.net> Message-ID: <45211320.20304@gmail.com> > > > My line: number = 3 > Would I use 'number = random.randint()' in place of that, to have the > relevant number be random? yes, but remember that random.randint takes 2 arguments, the endpoints. E.G. random.randint(1,10) would be equivalent to random.choice(range(1,11)) or random.choice([1,2,3,4,5,6,7,8,9,10]) Note that the random.randint function includes both endpoints (I.E. the numbers are 1-10 including 10) but the range() function doesn't include the last endpoint. HTH -Luke From dyoo at hkn.eecs.berkeley.edu Mon Oct 2 17:37:22 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 2 Oct 2006 08:37:22 -0700 (PDT) Subject: [Tutor] how to make a reference to part of list? In-Reply-To: <20061002121824.52800.qmail@web55207.mail.re4.yahoo.com> References: <20061002121824.52800.qmail@web55207.mail.re4.yahoo.com> Message-ID: > for example, I want to mutate part of a list, of course, I can achieve > this by passing the pair list and (begin, end) as parameters. but in > some case, this manner is quite tedious and in efficient I'm not sure what you mean by "inefficient". What do you think a "pointer" is, if not what you just described? *grin* Conceptually, a pointer is some arrow directed at some other thing. Here's a possible implementation of what you're asking: ########################################################### class ListPointer: def __init__(self, L, i): """Creates a pointer into the i'th element of L.""" self.L = L self.i = i def deref(self): """Returns the value pointed to.""" return self.L[self.i] def mutate(self, value): """Mutates the list value that we point to.""" self.L[self.i] = value ########################################################### For example: ##################################### >>> l = ["hello", "world", "testing"] >>> p = ListPointer(l, 1) >>> p.deref() 'world' >>> p.mutate("universe") >>> p.deref() 'universe' >>> l ['hello', 'universe', 'testing'] ##################################### At the moment, this class allows point mutations, and could probably be adjusted to work with slices. That being said, can you explain what the purpose is? There may be some other effective way to do what you're trying to do, without the additional level of indirection that pointers impose. From eric at ericwalstad.com Mon Oct 2 18:28:47 2006 From: eric at ericwalstad.com (Eric Walstad) Date: Mon, 02 Oct 2006 09:28:47 -0700 Subject: [Tutor] database web app, what tool? In-Reply-To: <45208761.1010207@gmail.com> References: <4520533C.9090500@sapo.pt> <45208761.1010207@gmail.com> Message-ID: <45213E3F.5080306@ericwalstad.com> Hey Paulino, I'm a Django fan but from your description, a simple CGI app might do nicely. Heck, you've already got the code written, just wrap it in a CGI script that formats your list of records in HTML and serve the script from your (already setup?) apache or even from your workstation with Python's CGI server. Best, Eric. Liam Clarke wrote: > Paulino wrote: > > Hi Paulino, > > Tough question that. What is your existing web server? That'd be a good > starting point. Zope/Plone are great, but they have a steep learning > curve that doesn't seem essential to what you're doing. Django is > simpler, but once again, doesn't immediately fit to what you're trying > to do, but it could do. > > I'd say just a straight mod_python would be simplest, to be honest, but > it really depends on what you're doing. > > Regards, > > Liam Clarke >> Hi! >> >> Im a very biginner in programming and I started with python, witch I >> found much easier tahn i thought. >> >> I want to build an intranet page in my organization that shows some data >> from our financial aplication's database. >> >> For the starting point I would like it to show invoices lists per >> supplier and link each line to a pdf image of the selected invoice that >> is stored in a determined folder. >> >> The aim is only to make querys and show the results. No updates, nor >> insert's >> >> The database is MS SQL 2005 >> >> >> >> Right now I connect to the database via pymssql, and i can retrieve data >> and send it to a wx.Grid or to a reportlab pdf file, with platypus >> tables (a couple of months ago i would say i'd never be able to do it... >> and now i want to do more...) >> >> Now I want to send it to the browser so the administration can see it >> every time they need. >> >> >> What tool is more suitable? >> >> There are so many options! >> >> Zope-Plone have it's own web server, so less config is required. But i >> can't find any recipe or tutorial usefull for this task... >> >> there is also django, turbogears, webware, apache and mod-python..... >> >> >> Thank you >> >> >> Paulino From eric at ericwalstad.com Mon Oct 2 18:16:36 2006 From: eric at ericwalstad.com (Eric Walstad) Date: Mon, 02 Oct 2006 09:16:36 -0700 Subject: [Tutor] Python code to split and reassemble files In-Reply-To: <451FE8BF.8090006@gmail.com> References: <451FE442.70205@gmail.com> <451FE8BF.8090006@gmail.com> Message-ID: <45213B64.5040307@ericwalstad.com> Andrew Robert wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Never mind.. :) > > > found it at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/224800 > > However, if someone has something better, I would be very interested. Hi Andrew, If you are on a *nix machine you could use split and cat: """ SPLIT(1) NAME split - split a file into pieces SYNOPSIS split [OPTION] [INPUT [PREFIX]] DESCRIPTION Output fixed-size pieces of INPUT to PREFIXaa, PREFIXab, ...; default size is 1000 lines, and default PREFIX is ?x?. """ """ CAT(1) NAME cat - concatenate files and print on the standard output SYNOPSIS cat [OPTION] [FILE]... DESCRIPTION Concatenate FILE(s), or standard input, to standard output. """ From john at fouhy.net Mon Oct 2 22:40:27 2006 From: john at fouhy.net (John Fouhy) Date: Tue, 3 Oct 2006 09:40:27 +1300 Subject: [Tutor] One of my 'baby step' programs In-Reply-To: <20061002115800.c9uy1eianm88wcs4@webmail.frontiernet.net> References: <20061002015150.ox2ayuidpugcoc00@webmail.frontiernet.net> <45209A5B.3060901@gmail.com> <5e58f2e40610012158t3ac1c733lc277588f2a5c7940@mail.gmail.com> <20061002115800.c9uy1eianm88wcs4@webmail.frontiernet.net> Message-ID: <5e58f2e40610021340s7a872ceeh33c4d3e8769462b9@mail.gmail.com> On 03/10/06, Alan Gilfoy wrote: > > >>>> for i in range(10): > > ... break > > ... else: > > ... print 'foo' > > ... > >>>> for i in range(10): > > ... pass > > ... else: > > ... print 'foo' > > ... > > foo > >>>> > > pardon the newb question, but what do these code lines do? They demonstrate when the else: clause in a for statement gets executed. Spaces sometimes get lost in email, so I'll write them again, with underscores instead of spaces: for i in range(10): ____break else: ____print 'foo' In this case, the for loop will exit because of the break statement, and so the else: clause will not execute. for i in range(10): ____pass else: ____print 'foo' In this case, the loop body is just 'pass', which is python's do-nothing statement. So the loop will exit normally, and the else: clause will execute (resulting in the string 'foo' being printed). Does this help? -- John. From john at fouhy.net Mon Oct 2 22:55:52 2006 From: john at fouhy.net (John Fouhy) Date: Tue, 3 Oct 2006 09:55:52 +1300 Subject: [Tutor] My number-guessing program In-Reply-To: <45211320.20304@gmail.com> References: <20061002015150.ox2ayuidpugcoc00@webmail.frontiernet.net> <45209A5B.3060901@gmail.com> <20061002113436.hsvg87haqqiso44g@webmail.frontiernet.net> <45211320.20304@gmail.com> Message-ID: <5e58f2e40610021355n732b5b10k5d87137c51c69f90@mail.gmail.com> On 03/10/06, Luke Paireepinart wrote: > Note that the random.randint function includes both endpoints (I.E. the > numbers are 1-10 including 10) > but the range() function doesn't include the last endpoint. Which is why (in my not-so-humble opinion :-) ) we should tell people to use random.randrange instead of random.randint! (random.randrange takes up to 3 arguments with exactly the same meanings as range()) -- John. From rdm at rcblue.com Tue Oct 3 05:13:49 2006 From: rdm at rcblue.com (Dick Moores) Date: Mon, 02 Oct 2006 20:13:49 -0700 Subject: [Tutor] timeit at the command line In-Reply-To: <5e58f2e40610021350j5f6a138fkac2e38071095f69b@mail.gmail.co m> References: <7.0.1.0.2.20061001210313.03c93d58@rcblue.com> <5e58f2e40610021350j5f6a138fkac2e38071095f69b@mail.gmail.com> Message-ID: <7.0.1.0.2.20061002195421.03ee70f0@rcblue.com> At 01:50 PM 10/2/2006, John Fouhy wrote: >On 02/10/06, Dick Moores wrote: >>C:\>python -m timeit -s"for x in range(100):" " x+=1" >>Traceback (most recent call last): > >The -s option specifies the setup code. In this case, you don't have >any setup code. Try this: > >python -m timeit "for x in range(100):" " x += 1" > >HTH! > >-- >John. Terrific! E:\Python25\dev>python -m timeit "for x in range(100):" " x += 1" 100000 loops, best of 3: 14.9 usec per loop So with python -m timeit -s"x=0" "while x<100:" " x+=1" 10000000 loops, best of 3: 0.123 usec per loop I DID have setup code, the "x=0". I now notice that if the "x=0" is not stated as the setup code, the time difference is enormous, 132-to-1 in this case. python -m timeit -s"x=0" "while x<100:" " x+=1" 10000000 loops, best of 3: 0.116 usec per loop python -m timeit "x=0" "while x<100:" " x+=1" 100000 loops, best of 3: 15.3 usec per loop Thanks, John. Dick From ml.cyresse at gmail.com Tue Oct 3 06:05:59 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Tue, 03 Oct 2006 17:05:59 +1300 Subject: [Tutor] [Fwd: Re: database web app, what tool?] Message-ID: <4521E1A7.8020105@gmail.com> -------- Original Message -------- Subject: Re: [Tutor] database web app, what tool? Date: Mon, 02 Oct 2006 09:33:28 +0100 From: paulino1 at sapo.pt To: Liam Clarke References: <4520533C.9090500 at sapo.pt> <45208761.1010207 at gmail.com> Thank you Liam, Our web server is IIS, but it would be no problem to use another one for this particular purpose. I'v been looking for information on how to design tables for the web with python, without succes so far. Can you point me any tutorial? Paulino Citando Liam Clarke : > Paulino wrote: > > Hi Paulino, > > Tough question that. What is your existing web server? That'd be a good > starting point. Zope/Plone are great, but they have a steep learning > curve that doesn't seem essential to what you're doing. Django is > simpler, but once again, doesn't immediately fit to what you're trying > to do, but it could do. > > I'd say just a straight mod_python would be simplest, to be honest, but > it really depends on what you're doing. > > Regards, > > Liam Clarke > > Hi! > > > > Im a very biginner in programming and I started with python, witch I > > found much easier tahn i thought. > > > > I want to build an intranet page in my organization that shows some data > > from our financial aplication's database. > > > > For the starting point I would like it to show invoices lists per > > supplier and link each line to a pdf image of the selected invoice that > > is stored in a determined folder. > > > > The aim is only to make querys and show the results. No updates, nor > > insert's > > > > The database is MS SQL 2005 > > > > > > > > Right now I connect to the database via pymssql, and i can retrieve data > > and send it to a wx.Grid or to a reportlab pdf file, with platypus > > tables (a couple of months ago i would say i'd never be able to do it... > > and now i want to do more...) > > > > Now I want to send it to the browser so the administration can see it > > every time they need. > > > > > > What tool is more suitable? > > > > There are so many options! > > > > Zope-Plone have it's own web server, so less config is required. But i > > can't find any recipe or tutorial usefull for this task... > > > > there is also django, turbogears, webware, apache and mod-python..... > > > > > > Thank you > > > > > > Paulino > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > From Christopher.Hatherly at anu.edu.au Tue Oct 3 06:12:28 2006 From: Christopher.Hatherly at anu.edu.au (Christopher Hatherly) Date: Tue, 3 Oct 2006 14:12:28 +1000 Subject: [Tutor] Number guessing game Message-ID: Hi, I'm brand new to Python, and almost brand new to programming. I'm teaching myself slowly through a 'Python Programming for the Absolute Beginner' book, which is great so far. One of the challenge problems though, was to write a script for a number guessing game, where you pick a number and the computer tries to guess. It took me a couple of days to get this working, and some of it is pretty messy. In particular, the 'Guess = ...' line, and the responses[] list' that I used. I'm happy that this works, but would like to know how to do it better! If anyone could suggest any improvements, that'd be great! Cheers Chris print """ Welcome to the 'guess the Number' game!!! Your job is to pick a number and my job is to try and figure it out." After each guess, tell me if I'm too high or too low." I've only got 7 goes to guess the number though ..." """ raw_input("\nPress enter when you're ready.") guess = 50 responses = [guess, 0] guess_number = 0 number = int(raw_input("\nPick a number between 1 and 100: ")) print "\nOK, guess number", guess_number +1, "is", guess while (guess != number) and guess_number < 6: high_low = raw_input("\nToo High or too Low (H/L)? ") if high_low == "H": print "Darn, too high!" guess = responses[guess_number]-(round(abs(responses[guess_number]-responses[gue ss_number-1])/2)) print "I have", 5 - guess_number, "guesses remaining." guess_number += 1 responses = responses[:guess_number] + [guess] raw_input ("\nPress enter to continue.") print "\nOK, guess number", guess_number +1, "is", int(guess) elif high_low == "L": print "Darn, too low!" guess = responses[guess_number]+(round(abs(responses[guess_number]-responses[gue ss_number-1])/2)) print "I have", 5 - guess_number, "guesses remaining." guess_number += 1 responses = responses[:guess_number] + [guess] raw_input ("\nPress enter to continue.") print "\nOK, guess number", guess_number +1, "is", int(guess) else: print "Sorry, I didn't understand that." if guess == number: print "\nHoorah!!! I got the number!!!" print "The number was ", number print "and I only took", guess_number + 1, "guesses." else: how_close = abs(guess - number) print "\nToo bad. The number was", number print "I was", int(how_close), "off getting it right." raw_input("\n\nPress the enter key to exit.\n") From rabidpoobear at gmail.com Tue Oct 3 07:02:57 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 03 Oct 2006 00:02:57 -0500 Subject: [Tutor] Number guessing game In-Reply-To: References: Message-ID: <4521EF01.8020508@gmail.com> Christopher Hatherly wrote: > Hi, > I'm brand new to Python, and almost brand new to programming. I'm > teaching myself slowly through a 'Python Programming for the Absolute > Beginner' book, which is great so far. Awesome, I'm always happy to hear of budding pythonistas :D > One of the challenge problems > though, was to write a script for a number guessing game, where you pick > a number and the computer tries to guess. It took me a couple of days to > get this working, and some of it is pretty messy. In particular, the > 'Guess = ...' line, and the > responses[] list' that I used. I'm happy that this works, but would like > to know how to do it better! If anyone could suggest any improvements, > that'd be great! > As you'll see below, I didn't look through your code to comment on individual things. I thought that if you saw the code I wrote you might get some new ideas and such, which you could carry over and improve your own code, rather than just giving you direct 'change this line to this'-type stuff. If this doesn't help you at all and you want me to go through your code and comment on specific points you could improve it, I'll certainly do so, I just thought this might be more helpful. Now, I'll take you through the thinking process I'd go through to make this program. First: What is it we want the program to do? 1. Greet the user. 2. Ask the user for a number 3. Generate a number. 4. Compare this generated number with the user's number. 5. If the generated number is the same as the user's number, goto 7. 6. Otherwise, goto 4. repeat up to (max guesses) times, then goto 7. 7. Tell the user if we managed to guess the number correctly. 8. Say goodbye to the user. Okay, let's see what variables we'll need for this. 1. The greeting string. 2. The user's number. 3. The generated number. 4. How many guesses we're allowed to make. 5. Whether the guessing was successful. 6. We'll also include the range to guess the numbers, just to add an extra feature, so we'll need min and max variables. 7. A goodbye string. We'll also need to use the random module to generate our guesses, so we don't always guess the same number. #start-code. #Number-Guesser.py #license = Public Domain #original author: Luke Paireepinart #we'll need the random module to make our guesses import random #set up these variables we decided were necessary. #initializing variables like this is helpful because #it helps people who're reading your code understand what your #variables are, for the most part, and what you'll probably use them for. #so make sure they all have nice descriptive names. greeting = """ Welcome to the number-guessing game. Hope you enjoy this! Hit enter to continue. """ goodbye = "Thanks for playing the number-guessing game!" usernum = 0 guessednum = 0 maxguesses = 5 guessed = False min_guess = 0 max_guess = 100 #First order of business: greeting the user. raw_input(greeting) #now we want to get a number from him, #and we'll store it in our usernum variable. #we're going to assume the nice-user scenario where they know #that by 'number' you mean 'integer' and not 'random gibberish.' #you could use a try: -> except: block here, if you couldn't trust #the user. usernum = int(raw_input("What is your number? ")) #once we have this number, we want to start up a loop #that will continue to guess until it either gets the number right #or runs out of guesses. x = 0 #x is an arbitrary loop variable. while x < maxguesses: #we'll loop until we reach the maximum guess limit. #we're using random.randrange because it behaves like range(), as John pointed out earlier. #this means if you call 'random.randrange(0,100)' the number will be 0 or 99 or anywhere #in between, but not 100. change the following line to either #'random.randrange(min_guess,max_guess+1)' or 'random.randint(min_guess,max_guess)' #if you want to include both endpoints. guessednum = random.randrange(min_guess,max_guess) #now that we have the guessed number, let's compare it to the user's number. if usernum == guessednum: #if we guessed right :) guessed = True break#let's get out of the loop since we're sure we guessed correctly. elif usernum < guessednum: #we guessed too high. #the following line has what's called a 'string substitution.' #all of the '%s' items are replaced by the items in the parenthesis to the left of the string, #after the %. print "We guessed %s instead of %s, which is %s bigger than your number." % (guessednum,usernum,guessednum-usernum) elif usernum > guessednum: #we guessed too low. print "We guessed %s instead of %s, which is %s less than your number." % (guessednum,usernum,usernum-guessednum) #and finally, increment our loop-variable so we can keep track of how many times through #we've gone. x += 1 #now that the loop has ended, there are two outcomes: #a. we guessed correctly, and b. we guessed incorrectly. if guessed: #option a. #we'll tell them we got it right. print "We guessed your number, %s!" % usernum else: #option b. #we'll tell them they win. print "We couldn't guess %s, you win!" % usernum #the game's over, so we'll say goodbye. print goodbye #---------------------------End of File. I hope this helps you in some way. Good Luck on your learnin'! -Luke From rdm at rcblue.com Tue Oct 3 08:51:52 2006 From: rdm at rcblue.com (Dick Moores) Date: Mon, 02 Oct 2006 23:51:52 -0700 Subject: [Tutor] What is a Python "project"? Message-ID: <7.0.1.0.2.20061002233717.0698dcd8@rcblue.com> I tried out Wing IDE Personal () off and on for 30 days, and then, finding it easy to use (probably because it's designed for Python), decided to buy it. I'm happy with it, and very pleased with the fast response from technical support available by email. I've never written anything in Python other than single-file scripts. WingIDE has the ability to handle "projects", which apparently consist of files and "packages". But what is a project? What does a project have that can't be put into a single .py file script? Thanks, Dick Moores From rdm at rcblue.com Tue Oct 3 11:46:52 2006 From: rdm at rcblue.com (Dick Moores) Date: Tue, 03 Oct 2006 02:46:52 -0700 Subject: [Tutor] what is "user time" in os.times()? Message-ID: <7.0.1.0.2.20061003021116.069a0008@rcblue.com> In a recent(ongoing?) thread on python-list, "PATCH: Speed up direct string concatenation by 20+%!", Larry Hastings, the op, says he computed his benchmark times using "sum(os.times()[:2])". Curious, I looked up os.times and tried it out on a little script I wrote to demonstrate the Law of Large Numbers (to myself): ================================================== # coinFlip.py import time, os from random import choice heads, tails = 0, 0 flips = 1000000 timeStart = time.time() for x in xrange(flips): coin = choice(["heads", "tails"]) if coin == "heads": heads += 1 else: tails += 1 timeEnd = time.time() osTimes = os.times difference = abs(heads - tails) print " flips heads tails diff %" print flips, heads, tails, difference, 100 - (100*difference*1.0/flips), "per cent" print "Time was %.4g seconds" % (timeEnd - timeStart) print "os.times() is", osTimes() ====================================================== >>> Evaluating 1coinFlip.py flips heads tails diff % 1000000 500902 499098 1804 99.8196 per cent Time was 4.156 seconds os.times() is (0.3125, 4.015625, 0.0, 0.0, 0.0) >>> From the os module doc for times(): "Return a 5-tuple of floating point numbers indicating accumulated (processor or other) times, in seconds. The items are: user time, system time, children's user time, children's system time, and elapsed real time since a fixed point in the past, in that order. See the Unix manual page times(2) or the corresponding Windows Platform API documentation. Availability: Macintosh, Unix, Windows." Now, I won't ask (yet) about what the 3rd, 4th, and 5th elements of the 5-tuple are, but I'd like to know what the first one, user time, is. Who is this ghost in the machine? The man page times(2) was no help, to me anyway. () Dick Moores http://www.bigbiz.com/cgi-bin/manpage?times From kent37 at tds.net Tue Oct 3 12:05:50 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 03 Oct 2006 06:05:50 -0400 Subject: [Tutor] timeit at the command line In-Reply-To: <7.0.1.0.2.20061002195421.03ee70f0@rcblue.com> References: <7.0.1.0.2.20061001210313.03c93d58@rcblue.com> <5e58f2e40610021350j5f6a138fkac2e38071095f69b@mail.gmail.com> <7.0.1.0.2.20061002195421.03ee70f0@rcblue.com> Message-ID: <452235FE.9090902@tds.net> Dick Moores wrote: > I DID have setup code, the "x=0". I now notice that if the "x=0" is > not stated as the setup code, the time difference is enormous, > 132-to-1 in this case. > > python -m timeit -s"x=0" "while x<100:" " x+=1" > 10000000 loops, best of 3: 0.116 usec per loop > > python -m timeit "x=0" "while x<100:" " x+=1" > 100000 loops, best of 3: 15.3 usec per loop timeit runs the setup code once, then runs the timed code many times with the timer running. If "x=0" is outside the loop, then the while loop only runs once, because x == 100 after the first time through the loop. So your first version is effectively timing this: setup: x=100 timed code: while x<100: x+=1 which is of course a lot faster than actually running the loopp 100 times. Kent From rdm at rcblue.com Tue Oct 3 12:19:44 2006 From: rdm at rcblue.com (Dick Moores) Date: Tue, 03 Oct 2006 03:19:44 -0700 Subject: [Tutor] Is there Python code for accessing an object's reference count? Message-ID: <7.0.1.0.2.20061003030543.03f0fc90@rcblue.com> Is there Python code for accessing an object's reference count? And does it matter to Python what this count is, other than whether it is zero or greater than zero (for garbage collection)? Thanks, Dick Moores From andre.roberge at gmail.com Tue Oct 3 12:25:19 2006 From: andre.roberge at gmail.com (Andre Roberge) Date: Tue, 3 Oct 2006 07:25:19 -0300 Subject: [Tutor] Is there Python code for accessing an object's reference count? In-Reply-To: <7.0.1.0.2.20061003030543.03f0fc90@rcblue.com> References: <7.0.1.0.2.20061003030543.03f0fc90@rcblue.com> Message-ID: <7528bcdd0610030325w79666951w7456748aa145840@mail.gmail.com> On 10/3/06, Dick Moores wrote: > Is there Python code for accessing an object's reference count? See sys.getrefcount. Andr? Roberge > > And does it matter to Python what this count is, other than whether > it is zero or greater than zero (for garbage collection)? > > Thanks, > > Dick Moores > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From rdm at rcblue.com Tue Oct 3 13:21:23 2006 From: rdm at rcblue.com (Dick Moores) Date: Tue, 03 Oct 2006 04:21:23 -0700 Subject: [Tutor] Is there Python code for accessing an object's reference count? In-Reply-To: <7528bcdd0610030325w79666951w7456748aa145840@mail.gmail.com > References: <7.0.1.0.2.20061003030543.03f0fc90@rcblue.com> <7528bcdd0610030325w79666951w7456748aa145840@mail.gmail.com> Message-ID: <7.0.1.0.2.20061003035702.06a8a390@rcblue.com> At 03:25 AM 10/3/2006, Andre Roberge wrote: >On 10/3/06, Dick Moores wrote: > > Is there Python code for accessing an object's reference count? > >See sys.getrefcount. Fascinating. And surprising. >>> from sys import getrefcount >>> getrefcount(1) 493 >>> getrefcount(2) 157 >>> getrefcount(3) 60 >>> getrefcount(22) 12 >>> getrefcount(222) 3 >>> getrefcount(222234523452345345) 2 >>> getrefcount(2.23452345345) 2 >>> That refcount for 1 (and 2, 3, and 12) is puzzling to me. I closed python, called python, and tried it again. Essentially no change. When would this go to zero? Only when I shut off my computer? I just answered that last question by shutting off my computer, and found >>> from sys import getrefcount >>> getrefcount(1) 493 >>> q = 1 >>> getrefcount(1) 499 >>> w = 1 >>> getrefcount(1) 500 >>> del w >>> getrefcount(1) 499 >>> q = 2 >>> getrefcount(1) 498 >>> Still 493. Why? Then after "q = 1", 499, not 494. Why? The other refcounts, after w=1, del w, and q=2, are as I expected. Thanks, Dick From rdm at rcblue.com Tue Oct 3 13:25:18 2006 From: rdm at rcblue.com (Dick Moores) Date: Tue, 03 Oct 2006 04:25:18 -0700 Subject: [Tutor] timeit at the command line In-Reply-To: <452235FE.9090902@tds.net> References: <7.0.1.0.2.20061001210313.03c93d58@rcblue.com> <5e58f2e40610021350j5f6a138fkac2e38071095f69b@mail.gmail.com> <7.0.1.0.2.20061002195421.03ee70f0@rcblue.com> <452235FE.9090902@tds.net> Message-ID: <7.0.1.0.2.20061003042319.053e3298@rcblue.com> At 03:05 AM 10/3/2006, Kent Johnson wrote: >Dick Moores wrote: > > I DID have setup code, the "x=0". I now notice that if the "x=0" is > > not stated as the setup code, the time difference is enormous, > > 132-to-1 in this case. > > > > python -m timeit -s"x=0" "while x<100:" " x+=1" > > 10000000 loops, best of 3: 0.116 usec per loop > > > > python -m timeit "x=0" "while x<100:" " x+=1" > > 100000 loops, best of 3: 15.3 usec per loop > >timeit runs the setup code once, then runs the timed code many times >with the timer running. If "x=0" is outside the loop, then the while >loop only runs once, because x == 100 after the first time through the >loop. So your first version is effectively timing this: > >setup: >x=100 > >timed code: >while x<100: > x+=1 > >which is of course a lot faster than actually running the loopp 100 times. Thanks, Kent. I was beginning to understand this, and now you've nailed it down for me. Dick From kent37 at tds.net Tue Oct 3 13:35:11 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 03 Oct 2006 07:35:11 -0400 Subject: [Tutor] timeit at the command line In-Reply-To: <7.0.1.0.2.20061003042319.053e3298@rcblue.com> References: <7.0.1.0.2.20061001210313.03c93d58@rcblue.com> <5e58f2e40610021350j5f6a138fkac2e38071095f69b@mail.gmail.com> <7.0.1.0.2.20061002195421.03ee70f0@rcblue.com> <452235FE.9090902@tds.net> <7.0.1.0.2.20061003042319.053e3298@rcblue.com> Message-ID: <45224AEF.2000301@tds.net> Dick Moores wrote: > At 03:05 AM 10/3/2006, Kent Johnson wrote: >> timeit runs the setup code once, then runs the timed code many times >> with the timer running. If "x=0" is outside the loop, then the while >> loop only runs once, because x == 100 after the first time through the >> loop. So your first version is effectively timing this: >> >> setup: >> x=100 >> >> timed code: >> while x<100: >> x+=1 >> >> which is of course a lot faster than actually running the loopp 100 times. > > Thanks, Kent. I was beginning to understand this, and now you've > nailed it down for me. You might want to look at the source, timeit.py. There is a code template (called 'template') near the beginning. Your setup and timed code are inserted into the template, then it is compiled and run. One of the dangers of timeit is that you may time something different than what you think you are timing, as you did. It's an easy mistake to make and hard to protect against. Kent From kent37 at tds.net Tue Oct 3 13:44:35 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 03 Oct 2006 07:44:35 -0400 Subject: [Tutor] Is there Python code for accessing an object's reference count? In-Reply-To: <7.0.1.0.2.20061003035702.06a8a390@rcblue.com> References: <7.0.1.0.2.20061003030543.03f0fc90@rcblue.com> <7528bcdd0610030325w79666951w7456748aa145840@mail.gmail.com> <7.0.1.0.2.20061003035702.06a8a390@rcblue.com> Message-ID: <45224D23.9040303@tds.net> Dick Moores wrote: > At 03:25 AM 10/3/2006, Andre Roberge wrote: >> On 10/3/06, Dick Moores wrote: >>> Is there Python code for accessing an object's reference count? >> See sys.getrefcount. > > Fascinating. And surprising. > >>> from sys import getrefcount > >>> getrefcount(1) > 493 > >>> getrefcount(2) > 157 > >>> getrefcount(3) > 60 > >>> getrefcount(22) > 12 > >>> getrefcount(222) > 3 > >>> getrefcount(222234523452345345) > 2 > >>> getrefcount(2.23452345345) > 2 > >>> > > That refcount for 1 (and 2, 3, and 12) is puzzling to me. I closed > python, called python, and tried it again. Essentially no change. > When would this go to zero? Only when I shut off my computer? When you exit Python. There are quite a few modules loaded automatically when Python starts up. It's not too surprising that a few of them reference 1. For example, defining a function that uses a constant creates a reference to the constant: In [2]: sys.getrefcount(100) Out[2]: 43 In [3]: def foo(): ...: return 100 ...: In [4]: sys.getrefcount(100) Out[4]: 44 Kent From rdm at rcblue.com Tue Oct 3 14:01:27 2006 From: rdm at rcblue.com (Dick Moores) Date: Tue, 03 Oct 2006 05:01:27 -0700 Subject: [Tutor] Is there Python code for accessing an object's reference count? In-Reply-To: <45224D23.9040303@tds.net> References: <7.0.1.0.2.20061003030543.03f0fc90@rcblue.com> <7528bcdd0610030325w79666951w7456748aa145840@mail.gmail.com> <7.0.1.0.2.20061003035702.06a8a390@rcblue.com> <45224D23.9040303@tds.net> Message-ID: <7.0.1.0.2.20061003045911.05600890@rcblue.com> At 04:44 AM 10/3/2006, Kent Johnson wrote: >Dick Moores wrote: > > At 03:25 AM 10/3/2006, Andre Roberge wrote: > >> On 10/3/06, Dick Moores wrote: > >>> Is there Python code for accessing an object's reference count? > >> See sys.getrefcount. > > > > Fascinating. And surprising. > > >>> from sys import getrefcount > > >>> getrefcount(1) > > 493 > > >>> getrefcount(2) > > 157 > > >>> getrefcount(3) > > 60 > > >>> getrefcount(22) > > 12 > > >>> getrefcount(222) > > 3 > > >>> getrefcount(222234523452345345) > > 2 > > >>> getrefcount(2.23452345345) > > 2 > > >>> > > > > That refcount for 1 (and 2, 3, and 12) is puzzling to me. I closed > > python, called python, and tried it again. Essentially no change. > > When would this go to zero? Only when I shut off my computer? > >When you exit Python. > >There are quite a few modules loaded automatically when Python starts >up. It's not too surprising that a few of them reference 1. For example, >defining a function that uses a constant creates a reference to the >constant: >In [2]: sys.getrefcount(100) >Out[2]: 43 > >In [3]: def foo(): > ...: return 100 > ...: > >In [4]: sys.getrefcount(100) >Out[4]: 44 Ah, got it. Thanks again, Kent. Dick From rdm at rcblue.com Tue Oct 3 14:31:39 2006 From: rdm at rcblue.com (Dick Moores) Date: Tue, 03 Oct 2006 05:31:39 -0700 Subject: [Tutor] timeit at the command line In-Reply-To: <45224AEF.2000301@tds.net> References: <7.0.1.0.2.20061001210313.03c93d58@rcblue.com> <5e58f2e40610021350j5f6a138fkac2e38071095f69b@mail.gmail.com> <7.0.1.0.2.20061002195421.03ee70f0@rcblue.com> <452235FE.9090902@tds.net> <7.0.1.0.2.20061003042319.053e3298@rcblue.com> <45224AEF.2000301@tds.net> Message-ID: <7.0.1.0.2.20061003051757.05768518@rcblue.com> At 04:35 AM 10/3/2006, Kent Johnson wrote: >Dick Moores wrote: > > At 03:05 AM 10/3/2006, Kent Johnson wrote: > >> timeit runs the setup code once, then runs the timed code many times > >> with the timer running. If "x=0" is outside the loop, then the while > >> loop only runs once, because x == 100 after the first time through the > >> loop. So your first version is effectively timing this: > >> > >> setup: > >> x=100 > >> > >> timed code: > >> while x<100: > >> x+=1 > >> > >> which is of course a lot faster than actually running the loopp 100 times. > > > > Thanks, Kent. I was beginning to understand this, and now you've > > nailed it down for me. > >You might want to look at the source, timeit.py. There is a code >template (called 'template') near the beginning. Your setup and timed >code are inserted into the template, then it is compiled and run. Very interesting. I thought a line of that template looked familiar. I was seeing "_t0 = _timer()" regularly when I had the -s option set without any setup: C:\>python -m timeit -r 3 -s"for x in range(10000):" " x*x" Traceback (most recent call last): File "E:\Python25\lib\runpy.py", line 95, in run_module filename, loader, alter_sys) File "E:\Python25\lib\runpy.py", line 52, in _run_module_co mod_name, mod_fname, mod_loader) File "E:\Python25\lib\runpy.py", line 32, in _run_code exec code in run_globals File "E:\Python25\lib\timeit.py", line 285, in sys.exit(main()) File "E:\Python25\lib\timeit.py", line 249, in main t = Timer(stmt, setup, timer) File "E:\Python25\lib\timeit.py", line 116, in __init__ code = compile(src, dummy_src_name, "exec") File "", line 4 _t0 = _timer() ^ But I don't understand what the error has to do with _t0 . That's OK, don't bother to explain. I don't understand classes yet anyway. Should get into them soon, with Wes Chun's book. >One of the dangers of timeit is that you may time something different >than what you think you are timing, as you did. It's an easy mistake to >make and hard to protect against. Yes. thanks, Kent. Dick >Kent > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor From kent37 at tds.net Tue Oct 3 14:54:56 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 03 Oct 2006 08:54:56 -0400 Subject: [Tutor] timeit at the command line In-Reply-To: <7.0.1.0.2.20061003051757.05768518@rcblue.com> References: <7.0.1.0.2.20061001210313.03c93d58@rcblue.com> <5e58f2e40610021350j5f6a138fkac2e38071095f69b@mail.gmail.com> <7.0.1.0.2.20061002195421.03ee70f0@rcblue.com> <452235FE.9090902@tds.net> <7.0.1.0.2.20061003042319.053e3298@rcblue.com> <45224AEF.2000301@tds.net> <7.0.1.0.2.20061003051757.05768518@rcblue.com> Message-ID: <45225DA0.6040808@tds.net> Dick Moores wrote: > Very interesting. I thought a line of that template looked familiar. > I was seeing "_t0 = _timer()" regularly when I had the -s option set > without any setup: > > C:\>python -m timeit -r 3 -s"for x in range(10000):" " x*x" > Traceback (most recent call last): > File "E:\Python25\lib\runpy.py", line 95, in run_module > filename, loader, alter_sys) > File "E:\Python25\lib\runpy.py", line 52, in _run_module_co > mod_name, mod_fname, mod_loader) > File "E:\Python25\lib\runpy.py", line 32, in _run_code > exec code in run_globals > File "E:\Python25\lib\timeit.py", line 285, in > sys.exit(main()) > File "E:\Python25\lib\timeit.py", line 249, in main > t = Timer(stmt, setup, timer) > File "E:\Python25\lib\timeit.py", line 116, in __init__ > code = compile(src, dummy_src_name, "exec") > File "", line 4 > _t0 = _timer() > ^ > But I don't understand what the error has to do with _t0 . That's OK, > don't bother to explain. I don't understand classes yet anyway. > Should get into them soon, with Wes Chun's book. If you substitute your code into the template by hand and look at the actual exception (not shown above) you should see the problem. It doesn't have anything to do with classes. Kent Kent From rdm at rcblue.com Tue Oct 3 15:47:32 2006 From: rdm at rcblue.com (Dick Moores) Date: Tue, 03 Oct 2006 06:47:32 -0700 Subject: [Tutor] timeit at the command line In-Reply-To: <45225DA0.6040808@tds.net> References: <7.0.1.0.2.20061001210313.03c93d58@rcblue.com> <5e58f2e40610021350j5f6a138fkac2e38071095f69b@mail.gmail.com> <7.0.1.0.2.20061002195421.03ee70f0@rcblue.com> <452235FE.9090902@tds.net> <7.0.1.0.2.20061003042319.053e3298@rcblue.com> <45224AEF.2000301@tds.net> <7.0.1.0.2.20061003051757.05768518@rcblue.com> <45225DA0.6040808@tds.net> Message-ID: <7.0.1.0.2.20061003063912.06222a30@rcblue.com> At 05:54 AM 10/3/2006, Kent Johnson wrote: >Dick Moores wrote: >>Very interesting. I thought a line of that template looked >>familiar. I was seeing "_t0 = _timer()" regularly when I had the -s >>option set without any setup: >>C:\>python -m timeit -r 3 -s"for x in range(10000):" " x*x" >>Traceback (most recent call last): >> File "E:\Python25\lib\runpy.py", line 95, in run_module >> filename, loader, alter_sys) >> File "E:\Python25\lib\runpy.py", line 52, in _run_module_co >> mod_name, mod_fname, mod_loader) >> File "E:\Python25\lib\runpy.py", line 32, in _run_code >> exec code in run_globals >> File "E:\Python25\lib\timeit.py", line 285, in >> sys.exit(main()) >> File "E:\Python25\lib\timeit.py", line 249, in main >> t = Timer(stmt, setup, timer) >> File "E:\Python25\lib\timeit.py", line 116, in __init__ >> code = compile(src, dummy_src_name, "exec") >> File "", line 4 >> _t0 = _timer() >> ^ >>But I don't understand what the error has to do with _t0 . That's >>OK, don't bother to explain. I don't understand classes yet anyway. >>Should get into them soon, with Wes Chun's book. > >If you substitute your code into the template by hand and look at >the actual exception (not shown above) you should see the problem. >It doesn't have anything to do with classes. I meant timeit.py has classes. OK, I called timeit.py with this template: template = """ def inner(_it, _timer): %(setup)s _t0 = _timer() for _i in _it: %("x=0" "while x<100": " x*x")s _t1 = _timer() return _t1 - _t0 """ And got this error: E:\Python25\Scripts-NotMine>timeit.py Traceback (most recent call last): File "E:\Python25\Scripts-NotMine\timeit.py", li sys.exit(main()) File "E:\Python25\Scripts-NotMine\timeit.py", li t = Timer(stmt, setup, timer) File "E:\Python25\Scripts-NotMine\timeit.py", li src = template % {'stmt': stmt, 'setup': setup KeyError: '"x=0" "while x<100": " x*x"' So what's the error? I've probably misunderstood how to do the substitution.. Dick From kent37 at tds.net Tue Oct 3 16:08:07 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 03 Oct 2006 10:08:07 -0400 Subject: [Tutor] timeit at the command line In-Reply-To: <7.0.1.0.2.20061003063912.06222a30@rcblue.com> References: <7.0.1.0.2.20061001210313.03c93d58@rcblue.com> <5e58f2e40610021350j5f6a138fkac2e38071095f69b@mail.gmail.com> <7.0.1.0.2.20061002195421.03ee70f0@rcblue.com> <452235FE.9090902@tds.net> <7.0.1.0.2.20061003042319.053e3298@rcblue.com> <45224AEF.2000301@tds.net> <7.0.1.0.2.20061003051757.05768518@rcblue.com> <45225DA0.6040808@tds.net> <7.0.1.0.2.20061003063912.06222a30@rcblue.com> Message-ID: <45226EC7.6080304@tds.net> Dick Moores wrote: > At 05:54 AM 10/3/2006, Kent Johnson wrote: >> Dick Moores wrote: >>> Very interesting. I thought a line of that template looked >>> familiar. I was seeing "_t0 = _timer()" regularly when I had the -s >>> option set without any setup: >>> C:\>python -m timeit -r 3 -s"for x in range(10000):" " x*x" >>> Traceback (most recent call last): >>> File "E:\Python25\lib\runpy.py", line 95, in run_module >>> filename, loader, alter_sys) >>> File "E:\Python25\lib\runpy.py", line 52, in _run_module_co >>> mod_name, mod_fname, mod_loader) >>> File "E:\Python25\lib\runpy.py", line 32, in _run_code >>> exec code in run_globals >>> File "E:\Python25\lib\timeit.py", line 285, in >>> sys.exit(main()) >>> File "E:\Python25\lib\timeit.py", line 249, in main >>> t = Timer(stmt, setup, timer) >>> File "E:\Python25\lib\timeit.py", line 116, in __init__ >>> code = compile(src, dummy_src_name, "exec") >>> File "", line 4 >>> _t0 = _timer() >>> ^ >>> But I don't understand what the error has to do with _t0 . That's >>> OK, don't bother to explain. I don't understand classes yet anyway. >>> Should get into them soon, with Wes Chun's book. >> If you substitute your code into the template by hand and look at >> the actual exception (not shown above) you should see the problem. >> It doesn't have anything to do with classes. > > I meant timeit.py has classes. > > OK, I called timeit.py with this template: > > template = """ > def inner(_it, _timer): > %(setup)s > _t0 = _timer() > for _i in _it: > %("x=0" "while x<100": " x*x")s > _t1 = _timer() > return _t1 - _t0 > """ OK, let's go back to your first example and I will explain in more detail. timeit.py contains this template: template = """ def inner(_it, _timer): %(setup)s _t0 = _timer() for _i in _it: %(stmt)s _t1 = _timer() return _t1 - _t0 """ Whatever you specify for setup code is substituted for %(setup)s; the timed statement is substituted for %(stmt)s. This is done using standard string formatting operations. The result of the substitutions is a function definition which is compiled and run. So if you run python -m timeit -s"for x in range(10000):" " x*x" the generated function looks like this: def inner(_it, _timer): for x in range(10000): _t0 = _timer() for _i in _it: x*x _t1 = _timer() return _t1 - _t0 The for statement should begin an indented block; the next statement is *not* indented, so you get an IndentationError. Does that help? Kent From carloslara at web.de Tue Oct 3 17:00:27 2006 From: carloslara at web.de (Carlos) Date: Tue, 03 Oct 2006 17:00:27 +0200 Subject: [Tutor] CGKit Message-ID: <45227B0B.70000@web.de> Hi, I'm new to python and have been trying to install CGKit, it has a bunch of dependencies that I have to install. /At this point /the problem that I have is that I need to install Py++, I already installed pygccxml and GCC-XML. To install Py++ I downloaded it, and extracted it, next I opened a windows command prompt and went to the corresponding directory, then I typed "python setup.py install" this is supposed to install the package? Because I only get a message from windows that states that to install anything I must go to the control panel. Can you tell me where is the mistake? By the way, has someone managed to install CGKit and can guide me in the process? I'm having a lot of trouble with it. This is the page, just in case http://cgkit.sourceforge.net Thanks Carlos From rdm at rcblue.com Tue Oct 3 17:01:06 2006 From: rdm at rcblue.com (Dick Moores) Date: Tue, 03 Oct 2006 08:01:06 -0700 Subject: [Tutor] what is "user time" in os.times()? Message-ID: <7.0.1.0.2.20061003080042.06529e58@rcblue.com> At 05:24 AM 10/3/2006, Michael P. Reilly wrote: >It is not really a "ghost". On most systems, there is a split >between what happens while you are a "user" and what happens deep >inside the operation "system". The function is showing you how much >time elapsed while in those two areas of the system. > >To show you what I mean, take a simple program that writes to the disk: > >def show_me_the_spam(breakfast): > file = open("spam.txt", "w") > for i in range(10: > print >>file, "spam, spam, %s and spam" % breakfast > file.close() >show_me_the_spam("eggs") (0.25, 0.15625, 0.0, 0.0, 0.0) run included creating spam.txt (0.171875, 0.09375, 0.0, 0.0, 0.0) after spam.txt already there The (user time)/(system time) ratios are 1.6 and 1.83, respectively. For my coinFlip.py I got (0.3125, 4.015625, 0.0, 0.0, 0.0) the (user time)/(system time) ratio was 0.079. Why the big difference? From your explanation I would have thought that your script would have a LOWER ratio than coinFlip.py because of the file operations. Here's coinFlips.py and its result again: ================================================== # coinFlip.py import time, os from random import choice heads, tails = 0, 0 flips = 1000000 timeStart = time.time() for x in xrange(flips): coin = choice(["heads", "tails"]) if coin == "heads": heads += 1 else: tails += 1 timeEnd = time.time() osTimes = os.times difference = abs(heads - tails) print " flips heads tails diff %" print flips, heads, tails, difference, 100 - (100*difference*1.0/flips), "per cent" print "Time was %.4g seconds" % (timeEnd - timeStart) print "os.times() is", osTimes() ====================================================== >>> Evaluating 1coinFlip.py flips heads tails diff % 1000000 500902 499098 1804 99.8196 per cent Time was 4.156 seconds os.times() is (0.3125, 4.015625, 0.0, 0.0, 0.0) >>> If I reduce flips from 1000000 to 1000, I get >>> Evaluating 1coinFlip.py flips heads tails diff % 1000 482 518 36 96.4 per cent Time was 0.016 seconds os.times() is (0.296875, 0.09375, 0.0, 0.0, 0.0) >>> with a ratio of 3.17. So what's happening during the 1,000,000 loop that's put into "system" space? >Most of the execution of the program would happen as the "user"; >things like calling functions, evaluating string parameters, >counting in the loop. > >But the parts that would need to talk to hardware, parts that might >be dangerous to have the program have direct control over or might >need to be shared with other programs at the same time (like a >printer or a keyboard or a disk drive) - these parts of the program >are hidden underneath function calls and statements like "open" and >"print" and put into a "system" space. > >How much time you spend in "system" and "user" space tells you how >CPU and resource intensive your program is. > >The 3rd and 4th values are the same, but cumulative for all that >programs "children". A program can spawn subprocesses to help it >(see os.system and the like). > >All the above times are CPU times - time spent while the program has >been using fractions of CPU seconds. The last value shows that >actual real duration of the program, similar to your (timeEnd - >timeStart), but a bit more accurate. (Though it appears that value >isn't supported on your system?) My system is a Dell Dimension 4600i running Windows XP Professional Service Pack 2 (build 2600). Why wouldn't that value be supported? Should I call Dell? Bang on MS's door? (I live about a mile away.) I feel a bit cheated. ;) Thanks, Michael, for your extended answer.. Dick From rdm at rcblue.com Tue Oct 3 17:13:52 2006 From: rdm at rcblue.com (Dick Moores) Date: Tue, 03 Oct 2006 08:13:52 -0700 Subject: [Tutor] timeit at the command line In-Reply-To: <45226EC7.6080304@tds.net> References: <7.0.1.0.2.20061001210313.03c93d58@rcblue.com> <5e58f2e40610021350j5f6a138fkac2e38071095f69b@mail.gmail.com> <7.0.1.0.2.20061002195421.03ee70f0@rcblue.com> <452235FE.9090902@tds.net> <7.0.1.0.2.20061003042319.053e3298@rcblue.com> <45224AEF.2000301@tds.net> <7.0.1.0.2.20061003051757.05768518@rcblue.com> <45225DA0.6040808@tds.net> <7.0.1.0.2.20061003063912.06222a30@rcblue.com> <45226EC7.6080304@tds.net> Message-ID: <7.0.1.0.2.20061003080233.063b1fe8@rcblue.com> At 07:08 AM 10/3/2006, Kent Johnson wrote: >Dick Moores wrote: > > At 05:54 AM 10/3/2006, Kent Johnson wrote: > >> Dick Moores wrote: > >>> Very interesting. I thought a line of that template looked > >>> familiar. I was seeing "_t0 = _timer()" regularly when I had the -s > >>> option set without any setup: > >>> C:\>python -m timeit -r 3 -s"for x in range(10000):" " x*x" > >>> Traceback (most recent call last): > >>> File "E:\Python25\lib\runpy.py", line 95, in run_module > >>> filename, loader, alter_sys) > >>> File "E:\Python25\lib\runpy.py", line 52, in _run_module_co > >>> mod_name, mod_fname, mod_loader) > >>> File "E:\Python25\lib\runpy.py", line 32, in _run_code > >>> exec code in run_globals > >>> File "E:\Python25\lib\timeit.py", line 285, in > >>> sys.exit(main()) > >>> File "E:\Python25\lib\timeit.py", line 249, in main > >>> t = Timer(stmt, setup, timer) > >>> File "E:\Python25\lib\timeit.py", line 116, in __init__ > >>> code = compile(src, dummy_src_name, "exec") > >>> File "", line 4 > >>> _t0 = _timer() > >>> ^ > >>> But I don't understand what the error has to do with _t0 . That's > >>> OK, don't bother to explain. I don't understand classes yet anyway. > >>> Should get into them soon, with Wes Chun's book. > >> If you substitute your code into the template by hand and look at > >> the actual exception (not shown above) you should see the problem. > >> It doesn't have anything to do with classes. > > > > I meant timeit.py has classes. > > > > OK, I called timeit.py with this template: > > > > template = """ > > def inner(_it, _timer): > > %(setup)s > > _t0 = _timer() > > for _i in _it: > > %("x=0" "while x<100": " x*x")s > > _t1 = _timer() > > return _t1 - _t0 > > """ > >OK, let's go back to your first example and I will explain in more detail. Sorry to be so dumb. >timeit.py contains this template: >template = """ >def inner(_it, _timer): > %(setup)s > _t0 = _timer() > for _i in _it: > %(stmt)s > _t1 = _timer() > return _t1 - _t0 >""" > >Whatever you specify for setup code is substituted for %(setup)s; the >timed statement is substituted for %(stmt)s. This is done using standard >string formatting operations. The result of the substitutions is a >function definition which is compiled and run. > >So if you run >python -m timeit -s"for x in range(10000):" " x*x" > >the generated function looks like this: >def inner(_it, _timer): > for x in range(10000): > _t0 = _timer() > for _i in _it: > x*x > _t1 = _timer() > return _t1 - _t0 > >The for statement should begin an indented block; the next statement is >*not* indented, so you get an IndentationError. Yes, that's exactly what I got when using timeit with that code at the command line, which I didn't understand. John Fouhy explained it. >Does that help? Yes, you've shown me a couple of things. How to substitute in a template. How it can be useful to look at the code of modules. And in this case I'll be able to use that template in a copy of timeit.py without going to the command line, with which I usually struggle. Thanks again, again. Dick >Kent > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor From rabidpoobear at gmail.com Tue Oct 3 17:24:20 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 03 Oct 2006 10:24:20 -0500 Subject: [Tutor] CGKit In-Reply-To: <45227B0B.70000@web.de> References: <45227B0B.70000@web.de> Message-ID: <452280A4.1020908@gmail.com> > To install Py++ I downloaded it, and extracted it, next I > opened a windows command prompt and went to the corresponding directory, > then I typed "python setup.py install" this is supposed to install the > package? Because I only get a message from windows that states that to > install anything I must go to the control panel. It would be helpful if you included the actual error message here. > Can you tell me where > is the mistake? > Maybe python isn't in your path. try this: path = %path%;c:/python24 python setup.py install From arcege at gmail.com Tue Oct 3 18:07:21 2006 From: arcege at gmail.com (Michael P. Reilly) Date: Tue, 3 Oct 2006 12:07:21 -0400 Subject: [Tutor] what is "user time" in os.times()? In-Reply-To: <7.0.1.0.2.20061003080042.06529e58@rcblue.com> References: <7.0.1.0.2.20061003080042.06529e58@rcblue.com> Message-ID: <7e5ba9220610030907h23e1b118vae7f0fc93949387d@mail.gmail.com> Dang; sorry, thought I hit "Reply to all". I ran your program on two separate systems, three versions of Python here at work: 1. Pent M 2GHz/Windows XP Pro, running Cygwin Python 2.4.3: flips heads tails diff % 1000000 499598 500402 804 99.9196 per cent Time was 2.863 seconds os.times() is (2.5779999999999998, 0.156, 0.0, 0.0, 14526.053) 2. AMD Opteron/Linux RHE 4, running Python 2.2.3: flips heads tails diff % 1000000 499111 500889 1778 99.8222 per cent Time was 6.972 seconds os.times() is (6.9699999999999998, 0.02, 0.0, 0.0, 3496342.9399999999) 3. Pent M 2GHz/Windows XP Pro, running Windows Python 2.4.3: flips heads tails diff % 1000000 499667 500333 666 99.9334 per cent Time was 2.172 seconds os.times() is (0.265625, 2.125, 0.0, 0.0, 0.0) The second machine is a workhorse doing a lot, and it is also a virtual machine. The first and third is my work laptop - notice that the difference between cygwin (Posix/UNIX) and Windows is how the user/system time is computed. And also how the real time is returned. The Windows APIs might swap values or might just handle things differently. I can't say without a lot more research. -Arcege On 10/3/06, Dick Moores wrote: > > At 05:24 AM 10/3/2006, Michael P. Reilly wrote: > >It is not really a "ghost". On most systems, there is a split > >between what happens while you are a "user" and what happens deep > >inside the operation "system". The function is showing you how much > >time elapsed while in those two areas of the system. > > > >To show you what I mean, take a simple program that writes to the disk: > > > >def show_me_the_spam(breakfast): > > file = open("spam.txt", "w") > > for i in range(10: > > print >>file, "spam, spam, %s and spam" % breakfast > > file.close() > >show_me_the_spam("eggs") > > (0.25, 0.15625, 0.0, 0.0, 0.0) run included creating spam.txt > (0.171875, 0.09375, 0.0, 0.0, 0.0) after spam.txt already there > > The (user time)/(system time) ratios are 1.6 and 1.83, respectively. > > For my coinFlip.py I got > (0.3125, 4.015625, 0.0, 0.0, 0.0) > > the (user time)/(system time) ratio was 0.079. Why the big > difference? From your explanation I would have thought that your > script would have a LOWER ratio than coinFlip.py because of the file > operations. > > Here's coinFlips.py and its result again: > > ================================================== > # coinFlip.py > > import time, os > from random import choice > > heads, tails = 0, 0 > flips = 1000000 > > timeStart = time.time() > for x in xrange(flips): > coin = choice(["heads", "tails"]) > if coin == "heads": > heads += 1 > else: > tails += 1 > > timeEnd = time.time() > osTimes = os.times > difference = abs(heads - tails) > print " flips heads tails diff %" > print flips, heads, tails, difference, 100 - > (100*difference*1.0/flips), "per cent" > print "Time was %.4g seconds" % (timeEnd - timeStart) > print "os.times() is", osTimes() > ====================================================== > > >>> > Evaluating 1coinFlip.py > flips heads tails diff % > 1000000 500902 499098 1804 99.8196 per cent > Time was 4.156 seconds > os.times() is (0.3125, 4.015625, 0.0, 0.0, 0.0) > >>> > > > If I reduce flips from 1000000 to 1000, I get > >>> > Evaluating 1coinFlip.py > flips heads tails diff % > 1000 482 518 36 96.4 per cent > Time was 0.016 seconds > os.times() is (0.296875, 0.09375, 0.0, 0.0, 0.0) > >>> > > with a ratio of 3.17. So what's happening during the 1,000,000 loop > that's put into "system" space? > > >Most of the execution of the program would happen as the "user"; > >things like calling functions, evaluating string parameters, > >counting in the loop. > > > >But the parts that would need to talk to hardware, parts that might > >be dangerous to have the program have direct control over or might > >need to be shared with other programs at the same time (like a > >printer or a keyboard or a disk drive) - these parts of the program > >are hidden underneath function calls and statements like "open" and > >"print" and put into a "system" space. > > > >How much time you spend in "system" and "user" space tells you how > >CPU and resource intensive your program is. > > > >The 3rd and 4th values are the same, but cumulative for all that > >programs "children". A program can spawn subprocesses to help it > >(see os.system and the like). > > > >All the above times are CPU times - time spent while the program has > >been using fractions of CPU seconds. The last value shows that > >actual real duration of the program, similar to your (timeEnd - > >timeStart), but a bit more accurate. (Though it appears that value > >isn't supported on your system?) > > My system is > a Dell Dimension 4600i running Windows XP Professional Service Pack > 2 (build 2600). > > Why wouldn't that value be supported? Should I call Dell? Bang on > MS's door? (I live about a mile away.) I feel a bit cheated. ;) > > Thanks, Michael, for your extended answer.. > > Dick > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- There's so many different worlds, So many different suns. And we have just one world, But we live in different ones. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061003/d74fa19f/attachment.htm From kent37 at tds.net Tue Oct 3 18:28:02 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 03 Oct 2006 12:28:02 -0400 Subject: [Tutor] CGKit In-Reply-To: <45227B0B.70000@web.de> References: <45227B0B.70000@web.de> Message-ID: <45228F92.30906@tds.net> Carlos wrote: > Hi, > > I'm new to python and have been trying to install CGKit, it has a bunch > of dependencies that I have to install. /At this point /the problem that > I have is that I need to install Py++, I already installed pygccxml and > GCC-XML. To install Py++ I downloaded it, and extracted it, next I > opened a windows command prompt and went to the corresponding directory, > then I typed "python setup.py install" this is supposed to install the > package? Because I only get a message from windows that states that to > install anything I must go to the control panel. Can you tell me where > is the mistake? It looks like you are trying to build CGKit from source on a Windows machine. If you are on Windows you should download the binary installer (.exe) for the Python version you are using and run that. According to this page: http://cgkit.sourceforge.net/doc2/externaldeps.html if you use only the "general purpose modules" then the only external dependency is Python itself. So see if you can get that much working first. Kent From Mike.Hansen at atmel.com Tue Oct 3 18:50:03 2006 From: Mike.Hansen at atmel.com (Mike Hansen) Date: Tue, 3 Oct 2006 10:50:03 -0600 Subject: [Tutor] [Fwd: Re: database web app, what tool?] Message-ID: <57B026980605A64F9B23484C5659E32E3582E7@poccso.US.ad.atmel.com> > To: Liam Clarke > References: > <4520533C.9090500 at sapo.pt> <45208761.1010207 at gmail.com> > > > > Thank you Liam, > > > Our web server is IIS, but it would be no problem to use > another one for this > particular purpose. > > I'v been looking for information on how to design tables for > the web with > python, without succes so far. Can you point me any tutorial? > > > Paulino > > Do you mean HTML tables? If so, it'd probably be best to use a templating system like cheetah. If you want to do it "the hard way", you can do it from your python program with print statements.(print "...") I think there's a module out there that can generate HTML for you. I'm not sure how far you've gone with doing web programming with python. You might look at this article http://www.devshed.com/c/a/Python/Writing-CGI-Programs-in-Python/ Mike From Mike.Hansen at atmel.com Tue Oct 3 19:01:58 2006 From: Mike.Hansen at atmel.com (Mike Hansen) Date: Tue, 3 Oct 2006 11:01:58 -0600 Subject: [Tutor] What is a Python "project"? Message-ID: <57B026980605A64F9B23484C5659E32E3582F1@poccso.US.ad.atmel.com> > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of Dick Moores > Sent: Tuesday, October 03, 2006 12:52 AM > To: tutor at python.org > Subject: [Tutor] What is a Python "project"? > > I tried out Wing IDE Personal > () off and on for 30 days, and > then, finding it easy to use (probably because it's designed for > Python), decided to buy it. I'm happy with it, and very pleased with > the fast response from technical support available by email. > > I've never written anything in Python other than single-file scripts. > WingIDE has the ability to handle "projects", which apparently > consist of files and "packages". But what is a project? What does a > project have that can't be put into a single .py file script? > > Thanks, > > Dick Moores > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > When your apps start getting larger, you'll find that you want to put common functions into modules that you can hopefully reuse for other programs. http://docs.python.org/tut/node8.html I've been doing some web programming, so my "projects" consist of cheetah template files, CSS, config files, a handful of python modules... I hope that helps. Mike From kent37 at tds.net Tue Oct 3 19:50:39 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 03 Oct 2006 13:50:39 -0400 Subject: [Tutor] What is a Python "project"? In-Reply-To: <7.0.1.0.2.20061002233717.0698dcd8@rcblue.com> References: <7.0.1.0.2.20061002233717.0698dcd8@rcblue.com> Message-ID: <4522A2EF.9000508@tds.net> Dick Moores wrote: > I tried out Wing IDE Personal > () off and on for 30 days, and > then, finding it easy to use (probably because it's designed for > Python), decided to buy it. I'm happy with it, and very pleased with > the fast response from technical support available by email. > > I've never written anything in Python other than single-file scripts. > WingIDE has the ability to handle "projects", which apparently > consist of files and "packages". But what is a project? What does a > project have that can't be put into a single .py file script? When a program gets big enough, it is awkward to put everything into a single .py file. Breaking the program up into modules or packages makes it easier to understand, navigate and test the code. You might have test code in a separate module from the code being tested and utility scripts that are not part of the main program. You could have a command-line front end and a GUI front end. Also you might have non-Python files in the project such as configuration files, templates, localization resources, build scripts, files needed by tests... Kent From rdm at rcblue.com Tue Oct 3 20:21:23 2006 From: rdm at rcblue.com (Dick Moores) Date: Tue, 03 Oct 2006 11:21:23 -0700 Subject: [Tutor] question about sys.path and importing Message-ID: <7.0.1.0.2.20061003105954.0670da48@rcblue.com> This morning I was sternly warned by Wingware support not to leave my module of useful functions in Python25\Lib. So I put it in a subfolder in site-packages I named "mine". Importing of or from that module, mycalc.py goes well, to my surprise, because of >>> import sys >>> [x for x in sys.path if "site-packages" in x] ['e:\\Python25\\lib\\site-packages', 'e:\\Python25\\lib\\site-packages\\win32', 'e:\\Python25\\lib\\site-packages\\win32\\lib', 'e:\\Python25\\lib\\site-packages\\Pythonwin', 'e:\\Python25\\lib\\site-packages\\wx-2.6-msw-unicode'] >>> in which "mine" isn't included, even though other folders in site-packages are. Can someone explain this, please? Dick Moores From kent37 at tds.net Tue Oct 3 20:38:04 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 03 Oct 2006 14:38:04 -0400 Subject: [Tutor] question about sys.path and importing In-Reply-To: <7.0.1.0.2.20061003105954.0670da48@rcblue.com> References: <7.0.1.0.2.20061003105954.0670da48@rcblue.com> Message-ID: <4522AE0C.5080301@tds.net> Dick Moores wrote: > This morning I was sternly warned by Wingware support not to leave my > module of useful functions in Python25\Lib. So I put it in a > subfolder in site-packages I named "mine". Importing of or from that > module, mycalc.py goes well, to my surprise, because of > > >>> import sys > >>> [x for x in sys.path if "site-packages" in x] > ['e:\\Python25\\lib\\site-packages', > 'e:\\Python25\\lib\\site-packages\\win32', > 'e:\\Python25\\lib\\site-packages\\win32\\lib', > 'e:\\Python25\\lib\\site-packages\\Pythonwin', > 'e:\\Python25\\lib\\site-packages\\wx-2.6-msw-unicode'] > >>> > > in which "mine" isn't included, even though other folders in site-packages are. > > Can someone explain this, please? If the program that does the import is also in site-packages\mine, that would explain it. When you run a script its directory is added to sys.path. Normally you will need to either - make 'mine' be a package, by creating an empty file named site-packages\mine\__init__.py, and changing your imports to include the package name (from mine import mycalc), or - add site-packages\mine to sys.path, maybe by creating a .pth file. http://www.python.org/doc/2.4.3/lib/module-site.html Gee, maybe I should just invite you over and we can talk ;) Kent From rdm at rcblue.com Tue Oct 3 20:41:16 2006 From: rdm at rcblue.com (Dick Moores) Date: Tue, 03 Oct 2006 11:41:16 -0700 Subject: [Tutor] What is a Python "project"? In-Reply-To: <57B026980605A64F9B23484C5659E32E3582F1@poccso.US.ad.atmel. com> References: <57B026980605A64F9B23484C5659E32E3582F1@poccso.US.ad.atmel.com> Message-ID: <7.0.1.0.2.20061003112250.069236f0@rcblue.com> At 10:01 AM 10/3/2006, Mike Hansen wrote: > > > > -----Original Message----- > > From: tutor-bounces at python.org > > [mailto:tutor-bounces at python.org] On Behalf Of Dick Moores > > Sent: Tuesday, October 03, 2006 12:52 AM > > To: tutor at python.org > > Subject: [Tutor] What is a Python "project"? > > > > I tried out Wing IDE Personal > > () off and on for 30 days, and > > then, finding it easy to use (probably because it's designed for > > Python), decided to buy it. I'm happy with it, and very pleased with > > the fast response from technical support available by email. > > > > I've never written anything in Python other than single-file scripts. > > WingIDE has the ability to handle "projects", which apparently > > consist of files and "packages". But what is a project? What does a > > project have that can't be put into a single .py file script? > > > > Thanks, > > > > Dick Moores > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > >When your apps start getting larger, you'll find that you want to put >common functions into modules that you can hopefully reuse for other >programs. Yes, I already have done this. But in scripts I write I simply import the functions I want from that module. I don't think in terms of making a project. Maybe I've missed your point? >http://docs.python.org/tut/node8.html Now, that page has a lot of stuff I didn't know. Thanks! Maybe I should read the whole tutorial. I see that's it's been updated for 2.5. And it's by GvR. http://docs.python.org/tut/tut.html >I've been doing some web programming, so my "projects" consist of >cheetah template files, CSS, config files, a handful of python >modules... Why do you make python modules part of a project? They can be used without copying them around, can't they? Or is it that by a project is meant in part a list of pointers to all the files you mean for that program to use, and you don't actually have to copy or move them so they are all in the same folder/directory? Thanks, Mike. Dick From rdm at rcblue.com Tue Oct 3 21:14:19 2006 From: rdm at rcblue.com (Dick Moores) Date: Tue, 03 Oct 2006 12:14:19 -0700 Subject: [Tutor] question about sys.path and importing In-Reply-To: <4522AE0C.5080301@tds.net> References: <7.0.1.0.2.20061003105954.0670da48@rcblue.com> <4522AE0C.5080301@tds.net> Message-ID: <7.0.1.0.2.20061003120356.069712d0@rcblue.com> At 11:38 AM 10/3/2006, Kent Johnson wrote: >Normally you will need to either >- make 'mine' be a package, by creating an empty file named >site-packages\mine\__init__.py, and changing your imports to include the >package name (from mine import mycalc), or >- add site-packages\mine to sys.path, maybe by creating a .pth file. >http://www.python.org/doc/2.4.3/lib/module-site.html I went with your first way, and it works with a script in python25\dev: # 1test-8.py from mine import mycalc print mycalc.numberCommas(12341234123) >>> Evaluating 1test-8.py 12,341,234,123 But fails here: # 1test-9.py from mine import mycalc from mycalc import numberCommas print numberCommas(12341234123) >>> Evaluating 1test-9.py Traceback (most recent call last): File "", line 1, in ImportError: No module named mycalc >>> I guess I can live with that. >Gee, maybe I should just invite you over and we can talk ;) Careful now. I just might show up! Dick From Mike.Hansen at atmel.com Tue Oct 3 21:25:54 2006 From: Mike.Hansen at atmel.com (Mike Hansen) Date: Tue, 3 Oct 2006 13:25:54 -0600 Subject: [Tutor] What is a Python "project"? Message-ID: <57B026980605A64F9B23484C5659E32E358328@poccso.US.ad.atmel.com> > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of Dick Moores > Sent: Tuesday, October 03, 2006 12:41 PM > To: tutor at python.org > Subject: Re: [Tutor] What is a Python "project"? > > At 10:01 AM 10/3/2006, Mike Hansen wrote: > > > > > > > -----Original Message----- > > > From: tutor-bounces at python.org > > > [mailto:tutor-bounces at python.org] On Behalf Of Dick Moores > > > Sent: Tuesday, October 03, 2006 12:52 AM > > > To: tutor at python.org > > > Subject: [Tutor] What is a Python "project"? > > > > > > I tried out Wing IDE Personal > > > () off and on for > 30 days, and > > > then, finding it easy to use (probably because it's designed for > > > Python), decided to buy it. I'm happy with it, and very > pleased with > > > the fast response from technical support available by email. > > > > > > I've never written anything in Python other than > single-file scripts. > > > WingIDE has the ability to handle "projects", which apparently > > > consist of files and "packages". But what is a project? > What does a > > > project have that can't be put into a single .py file script? > > > > > > Thanks, > > > > > > Dick Moores > > > > > > _______________________________________________ > > > Tutor maillist - Tutor at python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > >When your apps start getting larger, you'll find that you want to put > >common functions into modules that you can hopefully reuse for other > >programs. > > Yes, I already have done this. But in scripts I write I simply import > the functions I want from that module. I don't think in terms of > making a project. Maybe I've missed your point? > > >http://docs.python.org/tut/node8.html > > Now, that page has a lot of stuff I didn't know. Thanks! Maybe I > should read the whole tutorial. I see that's it's been updated for > 2.5. And it's by GvR. http://docs.python.org/tut/tut.html > > >I've been doing some web programming, so my "projects" consist of > >cheetah template files, CSS, config files, a handful of python > >modules... > > Why do you make python modules part of a project? They can be used > without copying them around, can't they? Or is it that by a project > is meant in part a list of pointers to all the files you mean for > that program to use, and you don't actually have to copy or move them > so they are all in the same folder/directory? > > Thanks, Mike. > > Dick > I use Komodo and VIM. With Komodo, a project is just a collection of related files. I'd imagine that WingIDE does something similar. You set up a project and add files to them. It's just a way to keep organized. As far as the python modules in my project, they are ones that I've written not 3rd party stuff. If the day comes that I use my own modules in more than one application/project, I'll probably move them to site packages. Mike From kent37 at tds.net Tue Oct 3 21:30:56 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 03 Oct 2006 15:30:56 -0400 Subject: [Tutor] question about sys.path and importing In-Reply-To: <7.0.1.0.2.20061003120356.069712d0@rcblue.com> References: <7.0.1.0.2.20061003105954.0670da48@rcblue.com> <4522AE0C.5080301@tds.net> <7.0.1.0.2.20061003120356.069712d0@rcblue.com> Message-ID: <4522BA70.3010100@tds.net> Dick Moores wrote: > At 11:38 AM 10/3/2006, Kent Johnson wrote: >> Normally you will need to either >> - make 'mine' be a package, by creating an empty file named >> site-packages\mine\__init__.py, and changing your imports to include the >> package name (from mine import mycalc), or >> - add site-packages\mine to sys.path, maybe by creating a .pth file. >> http://www.python.org/doc/2.4.3/lib/module-site.html > > I went with your first way, and it works with a script in python25\dev: > # 1test-8.py > from mine import mycalc > print mycalc.numberCommas(12341234123) > > >>> > Evaluating 1test-8.py > 12,341,234,123 > > But fails here: > # 1test-9.py > from mine import mycalc > from mycalc import numberCommas > print numberCommas(12341234123) > > >>> > Evaluating 1test-9.py > Traceback (most recent call last): > File "", line 1, in > ImportError: No module named mycalc > >>> Well this is different code. Try what you did in the first one: from mine import mycalc print mycalc.numberCommas(12341234123) or from mine.mycalc import numberCommas Kent From pyro9219 at gmail.com Tue Oct 3 23:08:55 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Tue, 3 Oct 2006 14:08:55 -0700 Subject: [Tutor] Keycodes Message-ID: Is it possible to capture keycodes for things like ctrl/alt/shift? I've made a script using msvcrt but it seems to skips most of the non alphanumeric keys. Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061003/8ee26e41/attachment.html From rabidpoobear at gmail.com Tue Oct 3 23:10:04 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 03 Oct 2006 16:10:04 -0500 Subject: [Tutor] Keycodes In-Reply-To: References: Message-ID: <4522D1AC.8060905@gmail.com> Chris Hengge wrote: > Is it possible to capture keycodes for things like ctrl/alt/shift? > > I've made a script using msvcrt but it seems to skips most of the non > alphanumeric keys. > > Thanks. You can in Pygame. I don't know about msvcrt. > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From carloslara at web.de Tue Oct 3 23:18:39 2006 From: carloslara at web.de (Carlos) Date: Tue, 03 Oct 2006 23:18:39 +0200 Subject: [Tutor] CGKit Message-ID: <4522D3AF.9050807@web.de> Thanks Luke and Kent, To get CGKit running I need to do two different things: First the Python Computer Graphics Kit is composed by an "cgkit-2.0.0alpha6.win32-py2.4.exe" file and some dependencies that are PyProtocols, numarray, PyOpenGL, PIL, pygame, PyODE and pySerial, with the exception of PyProtocols I have installed all of them. When I try to install PyProtocols from the command prompt it tells me that " The .NET Framework SDK needs to be installed before building extensions for Python." I went to Microsoft and installed the "Microsoft .NET Framework SDK v2.0", but the problem persists. The second part is the Python Maya Plug-In. I think that this is the tricky one, it is asking me to install Py++, that I have already installed. Now my problem comes when I have to compile the source code with Boost.Python, this one asks for Boost Jam and Boost. I have been trying to install this things but still have no clue at how. Thanks for your help Carlos From rdm at rcblue.com Wed Oct 4 00:02:19 2006 From: rdm at rcblue.com (Dick Moores) Date: Tue, 03 Oct 2006 15:02:19 -0700 Subject: [Tutor] question about sys.path and importing Message-ID: <7.0.1.0.2.20061003150209.069d3d98@rcblue.com> At 12:30 PM 10/3/2006, you wrote: >Dick Moores wrote: >>At 11:38 AM 10/3/2006, Kent Johnson wrote: >>>Normally you will need to either >>>- make 'mine' be a package, by creating an empty file named >>>site-packages\mine\__init__.py, and changing your imports to include the >>>package name (from mine import mycalc), or >>>- add site-packages\mine to sys.path, maybe by creating a .pth file. >>>http://www.python.org/doc/2.4.3/lib/module-site.html >>I went with your first way, and it works with a script in python25\dev: >># 1test-8.py >>from mine import mycalc >>print mycalc.numberCommas(12341234123) >> >>> >>Evaluating 1test-8.py >>12,341,234,123 >>But fails here: >># 1test-9.py >>from mine import mycalc >>from mycalc import numberCommas >>print numberCommas(12341234123) >> >>> >>Evaluating 1test-9.py >>Traceback (most recent call last): >> File "", line 1, in >>ImportError: No module named mycalc >> >>> > >Well this is different code. Yes, that was my point. Sorry I didn't make that clear. >Try what you did in the first one: >from mine import mycalc >print mycalc.numberCommas(12341234123) > >or >from mine.mycalc import numberCommas Good! Didn't know I could do "from mine.mycalc import numberCommas". Thanks, Dick From broek at cc.umanitoba.ca Wed Oct 4 00:00:35 2006 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Tue, 03 Oct 2006 17:00:35 -0500 Subject: [Tutor] What is a Python "project"? In-Reply-To: <7.0.1.0.2.20061003112250.069236f0@rcblue.com> References: <57B026980605A64F9B23484C5659E32E3582F1@poccso.US.ad.atmel.com> <7.0.1.0.2.20061003112250.069236f0@rcblue.com> Message-ID: <4522DD83.30905@cc.umanitoba.ca> Dick Moores said unto the world upon 03/10/06 01:41 PM: > At 10:01 AM 10/3/2006, Mike Hansen wrote: >> I've been doing some web programming, so my "projects" consist of >> cheetah template files, CSS, config files, a handful of python >> modules... > > Why do you make python modules part of a project? They can be used > without copying them around, can't they? Or is it that by a project > is meant in part a list of pointers to all the files you mean for > that program to use, and you don't actually have to copy or move them > so they are all in the same folder/directory? > > Thanks, Mike. > > Dick Hi Dick, I've never used Wing, but unless its `project' concept is radically different than many other editors, it isn't about organizing the files on disk. Rather, it is about organizing a group of files into a collection the editor can open in one swell foop. The idea is to liberate you from having to recall just where the files live and allow you to merely open a group of related files and get on with what you're up to. (It is sort of like saving a group of tabs in firefox.) Best, Brian vdB From wohlgemuth at ucdavis.edu Wed Oct 4 00:38:36 2006 From: wohlgemuth at ucdavis.edu (gert wohlgemuth) Date: Tue, 3 Oct 2006 15:38:36 -0700 Subject: [Tutor] byte[] array Message-ID: <4522e66a.43b22ef0.07ad.ffffa559@mx.gmail.com> Hi, I'm used to java byte arrays (byte[]) and need the same type in python, cause we have a couple of established web services, which return a byte[] or take a byte[] as parameter. As anybody an idea how I can do this in python? Thx, g. From ph34r_th3_d4rkn3s at hotmail.com Wed Oct 4 02:19:41 2006 From: ph34r_th3_d4rkn3s at hotmail.com (mike viceano) Date: Tue, 03 Oct 2006 18:19:41 -0600 Subject: [Tutor] number game Message-ID: i wrote a program that guesses number in the most effective way i could think of but i keep running into endless loops any help fixing it would be great :) here it is: def num(number): r=input("range >") ran=range(r+1) guess=r/2 print guess guesses=1 while guess!=number: if guess < number: guess= ((r-guess)/2)+guess print guess guesses=guesses+1 elif guess > number: guess= ((r-guess)/2)-guess print guess guesses=guesses+1 print "i got the number",number,"in",guesses,"guesses" my only idea is to make it so it dosint re guess numbers but i would rather just find out what is wrong and fix it _________________________________________________________________ Express yourself - download free Windows Live Messenger themes! http://clk.atdmt.com/MSN/go/msnnkwme0020000001msn/direct/01/?href=http://imagine-msn.com/themes/vibe/default.aspx?locale=en-us&source=hmtagline From halamillo at wsu.edu Wed Oct 4 02:16:25 2006 From: halamillo at wsu.edu (halamillo) Date: Tue, 3 Oct 2006 17:16:25 -0700 Subject: [Tutor] Random Variable at root Message-ID: Hello, I'm a really-green-to-python Biology Grad Student. I;m starting this code so I can assign either a 0 or a 1 at a root node that I will later evolve throughout a tree, but for some reason it is not printing the rootState value. I know its probably a really stupid mistake, but I can't seem to work it out. Can anyone give me insight why? Thanks. import random from random import random as rnd from math import exp class Root: """Single Node in a Tree""" def __init__( self, rootState ): self._rootState = rootState # random choice for root state from a list for i in range(1): rootState = random.choice([0, 1]) def __str__( self ): """Root string representation""" return str( self._rootState ) print "The character state at the root is %0.f" % rootState Hugo Alamillo Biological Sciences 265 Eastlick PO Box 644236 Washington State University Pullman, WA 99164 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061003/7c6b977c/attachment.html From sisson.j at gmail.com Tue Oct 3 20:57:30 2006 From: sisson.j at gmail.com (Jonathon Sisson) Date: Tue, 03 Oct 2006 13:57:30 -0500 Subject: [Tutor] number game In-Reply-To: References: Message-ID: <4522B29A.3040208@gmail.com> Mike, The algorithm you use is what causes the infinite loop (it cycles through the same numbers repeatedly). I've updated the code and I'll post it here: def num(number): r=input("range >") ran=range(r+1) guess=r/2 print guess guesses=1 min = 0 max = r while guess!=number: if guess < number: min = guess else: max = guess guess = (min + max) / 2 guesses += 1 print guess print "i got the number",number,"in",guesses,"guesses" mike viceano wrote: > i wrote a program that guesses number in the most effective way i could > think of but i keep running into endless loops any help fixing it would be > great :) > > here it is: > > > def num(number): > r=input("range >") > ran=range(r+1) > guess=r/2 > print guess > guesses=1 > while guess!=number: > if guess < number: > guess= ((r-guess)/2)+guess > print guess > guesses=guesses+1 > elif guess > number: > guess= ((r-guess)/2)-guess > print guess > guesses=guesses+1 > print "i got the number",number,"in",guesses,"guesses" > > > > my only idea is to make it so it dosint re guess numbers but i would rather > just find out what is wrong > and fix it > > _________________________________________________________________ > Express yourself - download free Windows Live Messenger themes! > http://clk.atdmt.com/MSN/go/msnnkwme0020000001msn/direct/01/?href=http://imagine-msn.com/themes/vibe/default.aspx?locale=en-us&source=hmtagline > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From eric at ericwalstad.com Wed Oct 4 03:42:03 2006 From: eric at ericwalstad.com (Eric Walstad) Date: Tue, 03 Oct 2006 18:42:03 -0700 Subject: [Tutor] Random Variable at root In-Reply-To: References: Message-ID: <4523116B.5080601@ericwalstad.com> Hi Hugo, halamillo wrote: > I;m starting this > code so I can assign either a 0 or a 1 at a root node that I will later > evolve throughout a tree, but for some reason it is not printing the > rootState value. It's not clear to me which variable you are trying to assign a zero or one. Here's my guess at how you are wanting to use your class: >>> import random >>> from random import random as rnd >>> >>> >>> class Root: ... """Single Node in a Tree""" ... def __init__(self, rootState): ... self._rootState = rootState ... # random choice for root state from a list ... self._rootState = random.choice([0, 1]) ... def __str__(self): ... return str( self._rootState ) ... >>> >>> >>> rs = 99 >>> r = Root(rootState=rs) >>> print rs 99 >>> print r 0 >>> print "The character state at the root is %0.f" % float(r._rootState) The character state at the root is 0 Note: 1. I removed the loop in your __init__method because it was simply making two random choices when one should do. 2. I assigned the random choice to the class' _rootState attribute, not the rootState argument to the __init__ method. You can also make a "rootState" property of the class so that the last line, above, would look like: >>> print "The character state at the root is %0.f" % float(r.rootState) I hope that helps. Eric. From sisson.j at gmail.com Tue Oct 3 22:16:52 2006 From: sisson.j at gmail.com (Jonathon Sisson) Date: Tue, 03 Oct 2006 15:16:52 -0500 Subject: [Tutor] Random Variable at root In-Reply-To: References: Message-ID: <4522C534.30400@gmail.com> Hugo, You need to create an instance of the Root class before you can call rootState in your final print statement. Your code doesn't do this. A class is merely a template, something like blueprints to a house. For you to be able to unlock the front door (for instance), you need to actually build a specific "instance" of the house first. "313 Hillcrest Lane" and "4214 Willowbrook Drive" might be two houses that have the same blueprint, but maintain different states from each other because they are different "instances" of class House. To make this work, remove the final print statement and replace it with this: # instantiates ("builds") a copy of the Root class and names it "root" root = Root(0) print "The character state at the root is %0.f" % root._rootState Note the change to the end of the print statement. Your code has rootState, mine has root._rootState (the specific instance of Root, followed by the "dot" operator, followed by the attribute or method you are trying to access). I'm a bit confused as to whether you intended _rootState to be a copy of the *original* value passed in, with rootState maintaining a copy of the *current* value, or if that is a typo. Please elaborate. Hope this helps clear up confusion (as opposed to creating more...heh). Jonathon halamillo wrote: > Hello, > I'm a really-green-to-python Biology Grad Student. I;m starting this > code so I can assign either a 0 or a 1 at a root node that I will > later evolve throughout a tree, but for some reason it is not printing > the rootState value. I know its probably a really stupid mistake, but > I can't seem to work it out. Can anyone give me insight why? Thanks. > > import random > from random import random as rnd > from math import exp > > > class Root: > """Single Node in a Tree""" > > def __init__( self, rootState ): > > > self._rootState = rootState > > # random choice for root state from a list > for i in range(1): > rootState = random.choice([0, 1]) > > > def __str__( self ): > """Root string representation""" > > > return str( self._rootState ) > print "The character state at the root is %0.f" % rootState > > > Hugo Alamillo > Biological Sciences > 265 Eastlick > PO Box 644236 > Washington State University > Pullman, WA 99164 > > > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From cappy2112 at gmail.com Wed Oct 4 04:08:37 2006 From: cappy2112 at gmail.com (Tony Cappellini) Date: Tue, 3 Oct 2006 19:08:37 -0700 Subject: [Tutor] What not to put in __init__() Message-ID: <8249c4ac0610031908u699d0effm82d63e2f23a54ce6@mail.gmail.com> I've just inherited a lot of python code to maintain. The __init__ functions in many of the classes are very long- some over 100 lines. I like to keep functions/methods short & readable at a glance, if possible. 1. Is it good methodology to move some code from _init__ to it's own method within the class? For example there are many for loops with several levles of nested if statements within them. I'd like to move each of these for/if chunks to distinct methods, so to simplify the look of __init__, without modifying how it works. thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061003/60bb06a2/attachment.htm From kent37 at tds.net Wed Oct 4 04:22:26 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 03 Oct 2006 22:22:26 -0400 Subject: [Tutor] byte[] array In-Reply-To: <4522e66a.43b22ef0.07ad.ffffa559@mx.gmail.com> References: <4522e66a.43b22ef0.07ad.ffffa559@mx.gmail.com> Message-ID: <45231AE2.7040606@tds.net> gert wohlgemuth wrote: > Hi, > > I'm used to java byte arrays (byte[]) and need the same type in python, > cause we have a couple of established web services, which return a byte[] or > take a byte[] as parameter. > > As anybody an idea how I can do this in python? A string can be used as a byte array. The struct module can help if you need to pack and unpack binary values into a string. Kent From kent37 at tds.net Wed Oct 4 04:26:08 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 03 Oct 2006 22:26:08 -0400 Subject: [Tutor] What not to put in __init__() In-Reply-To: <8249c4ac0610031908u699d0effm82d63e2f23a54ce6@mail.gmail.com> References: <8249c4ac0610031908u699d0effm82d63e2f23a54ce6@mail.gmail.com> Message-ID: <45231BC0.8050604@tds.net> Tony Cappellini wrote: > > I've just inherited a lot of python code to maintain. > > The __init__ functions in many of the classes are very long- some over > 100 lines. > > I like to keep functions/methods short & readable at a glance, if possible. > > 1. Is it good methodology to move some code from _init__ to it's own > method within the class? Sure. __init__() is just another method, there's no reason not to break it up if that will make it more readable. You might prefix the names of the new functions with _ to indicate that they are implementation details, not part of the public interface. I once worked on a Java class that had a 1000-line constructor, so consider yourself lucky :-) > > > For example there are many for loops with several levles of nested if > statements within them. > I'd like to move each of these for/if chunks to distinct methods, so to > simplify the look of __init__, without modifying how it works. Go for it. You might want to write some unit tests first if you don't have any. Kent From hokkakada at khmeros.info Wed Oct 4 06:15:01 2006 From: hokkakada at khmeros.info (hok kakada) Date: Wed, 4 Oct 2006 11:15:01 +0700 Subject: [Tutor] save configuration of one application. Message-ID: <200610041115.01688.hokkakada@khmeros.info> Hi, Can anybody guide me how to write the code for configure one application? For example, I want to set Font and Color for a textbox; later when the application is opened again. the previous font is set. So, which related function are used to form this feature? Thanks, da From rabidpoobear at gmail.com Wed Oct 4 06:43:17 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 03 Oct 2006 23:43:17 -0500 Subject: [Tutor] save configuration of one application. In-Reply-To: <200610041115.01688.hokkakada@khmeros.info> References: <200610041115.01688.hokkakada@khmeros.info> Message-ID: <45233BE5.9060301@gmail.com> hok kakada wrote: > Hi, > > Can anybody guide me how to write the code for configure one application? > For example, I want to set Font and Color for a textbox; later when the > application is opened again. the previous font is set. > > So, which related function are used to form this feature? > you can make a config.ini file and use that one module that parses ini files. I can't remember what it's called. configparser I think, but I wouldn't bet my life on it :) Or you could just write the settings out to a file. Even better, if you're not making a real-world application and/or you can trust your users not to muck around with stuff, just make all your settings in a class in a module you import. Eg: #---- config.py class Settings(object): font = 'Veranda' color = 'Black' #----- program.py from config import Settings print Settings.color #---- Hope that makes sense. If you choose to go the latter route, keep in mind that modules are compiled to .pyc files upon importation, so you'll have to remove those anytime you modify config.py or the old code will be used instead. -Luke From john at fouhy.net Wed Oct 4 06:54:07 2006 From: john at fouhy.net (John Fouhy) Date: Wed, 4 Oct 2006 17:54:07 +1300 Subject: [Tutor] save configuration of one application. In-Reply-To: <45233BE5.9060301@gmail.com> References: <200610041115.01688.hokkakada@khmeros.info> <45233BE5.9060301@gmail.com> Message-ID: <5e58f2e40610032154m436d1e6fo17417d686f0dcbf5@mail.gmail.com> On 04/10/06, Luke Paireepinart wrote: > you can make a config.ini file and use that one module that parses ini > files. > I can't remember what it's called. > configparser I think, but I wouldn't bet my life on it :) Yes, ConfigParser. The docs for ConfigParser are a bit confusing in places (IMO), but there are people here who can help if you get stuck. > Or you could just write the settings out to a file. Using ConfigParser means your configuratino files will be human-readable and human-editable. If you don't care about that, you could stick them in a dictionary and use pickle to write it to a file. Or use the shelve module. > If you choose to go the latter route, keep in mind that modules are > compiled to .pyc files upon importation, > so you'll have to remove those anytime you modify config.py or the old > code will be used instead. The python interpreter should check the timestamps on foo.py vs foo.pyc, and recompile if it thinks things have changed. -- John. From jjk.saji at gmail.com Wed Oct 4 07:47:49 2006 From: jjk.saji at gmail.com (Joseph John) Date: Wed, 4 Oct 2006 09:47:49 +0400 Subject: [Tutor] Integer division Help requested Message-ID: <8fbe2e10610032247l5203f331r869345b7d1c2407b@mail.gmail.com> HI All I am trying out python I understoon when 7/3 gives "2" But I cannot understand , when i give 7/-3 gives resuls "-3" I feel 7/3 should give -2 since integer divison returns floor Advice requested Thanks Joseph John -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061004/c798432b/attachment.html From rabidpoobear at gmail.com Wed Oct 4 07:56:18 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 04 Oct 2006 00:56:18 -0500 Subject: [Tutor] Integer division Help requested In-Reply-To: <8fbe2e10610032247l5203f331r869345b7d1c2407b@mail.gmail.com> References: <8fbe2e10610032247l5203f331r869345b7d1c2407b@mail.gmail.com> Message-ID: <45234D02.1020300@gmail.com> Joseph John wrote: > HI All > I am trying out python > I understoon when > 7/3 gives "2" > But I cannot understand , > when i give 7/-3 gives resuls "-3" > I feel > 7/3 should give -2 > > since integer divison returns floor > Advice requested > Thanks > Joseph John > >>> import math >>> math.floor(-3.2) -4.0 >>> math.floor(-4.1) -5.0 >>> math.floor(4.1) 4.0 The floor is the next lowest integer to the float. floor(-3.000000001) will be -4 floor(3.99999999) will be 3 HTH, -Luke > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From arunkumarpg at gmail.com Wed Oct 4 11:00:09 2006 From: arunkumarpg at gmail.com (Arun Kumar PG) Date: Wed, 4 Oct 2006 14:30:09 +0530 Subject: [Tutor] Suggestions required on Gaming Message-ID: <3cffff920610040200o9604662lece3c7fd28e6ed66@mail.gmail.com> Hi All Python lovers! I want to develop a Car racing game using Python. I was looking for the libraries which I should use for the same. Some of the options are below and I want you suggestions about the best set of tools and APIs as per your experiences: - PyGame - Panda3D - Pixie for rendering - RenderMan - What else ? I will really appreciate if you guys could please let me know the right set of tools and APIs as per your experience. Thanks, - Arun -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061004/c5d39286/attachment.htm From rabidpoobear at gmail.com Wed Oct 4 11:05:14 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 04 Oct 2006 04:05:14 -0500 Subject: [Tutor] Suggestions required on Gaming In-Reply-To: <3cffff920610040200o9604662lece3c7fd28e6ed66@mail.gmail.com> References: <3cffff920610040200o9604662lece3c7fd28e6ed66@mail.gmail.com> Message-ID: <4523794A.1020502@gmail.com> Arun Kumar PG wrote: > Hi All Python lovers! > > > I want to develop a Car racing game using Python. I was looking for > the libraries which I should use for the same. Some of the options are > below and I want you suggestions about the best set of tools and APIs > as per your experiences: > > - PyGame > - Panda3D > - Pixie for rendering > - RenderMan > - What else ? > > I will really appreciate if you guys could please let me know the > right set of tools and APIs as per your experience. Need more info. There are many types of car-racing games. Do you want it to be 3d, 2d? first-person, third-person, top-down, etc. The correct tool is the one which does the specific job best. We don't know what the job is so we can't help you choose a tool. -Luke From arunkumarpg at gmail.com Wed Oct 4 11:09:13 2006 From: arunkumarpg at gmail.com (Arun Kumar PG) Date: Wed, 4 Oct 2006 14:39:13 +0530 Subject: [Tutor] Suggestions required on Gaming In-Reply-To: <4523794A.1020502@gmail.com> References: <3cffff920610040200o9604662lece3c7fd28e6ed66@mail.gmail.com> <4523794A.1020502@gmail.com> Message-ID: <3cffff920610040209g486538f4l6097a21fd9438385@mail.gmail.com> Thanks Luke. I want to make a 3-D car race game between two players. And yes its gonna be a networked game where each user will be using his/her own PC and playing. - Arun On 10/4/06, Luke Paireepinart wrote: > > Arun Kumar PG wrote: > > Hi All Python lovers! > > > > > > I want to develop a Car racing game using Python. I was looking for > > the libraries which I should use for the same. Some of the options are > > below and I want you suggestions about the best set of tools and APIs > > as per your experiences: > > > > - PyGame > > - Panda3D > > - Pixie for rendering > > - RenderMan > > - What else ? > > > > I will really appreciate if you guys could please let me know the > > right set of tools and APIs as per your experience. > Need more info. > There are many types of car-racing games. > Do you want it to be 3d, 2d? first-person, third-person, top-down, etc. > The correct tool is the one which does the specific job best. > We don't know what the job is so we can't help you choose a tool. > -Luke > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061004/ca210ead/attachment.html From arunkumarpg at gmail.com Wed Oct 4 11:10:30 2006 From: arunkumarpg at gmail.com (Arun Kumar PG) Date: Wed, 4 Oct 2006 14:40:30 +0530 Subject: [Tutor] Suggestions required on Gaming In-Reply-To: <3cffff920610040209g486538f4l6097a21fd9438385@mail.gmail.com> References: <3cffff920610040200o9604662lece3c7fd28e6ed66@mail.gmail.com> <4523794A.1020502@gmail.com> <3cffff920610040209g486538f4l6097a21fd9438385@mail.gmail.com> Message-ID: <3cffff920610040210v741851evbcc969786922c355@mail.gmail.com> Also, my idea is to have a centralised Python server which acts as a dispachter to send the coordinate and other information to the gaming clients. On 10/4/06, Arun Kumar PG wrote: > > Thanks Luke. > > I want to make a 3-D car race game between two players. And yes its gonna > be a networked game where each user will be using his/her own PC and > playing. > > - Arun > > > On 10/4/06, Luke Paireepinart wrote: > > > > Arun Kumar PG wrote: > > > Hi All Python lovers! > > > > > > > > > I want to develop a Car racing game using Python. I was looking for > > > the libraries which I should use for the same. Some of the options are > > > > > below and I want you suggestions about the best set of tools and APIs > > > as per your experiences: > > > > > > - PyGame > > > - Panda3D > > > - Pixie for rendering > > > - RenderMan > > > - What else ? > > > > > > I will really appreciate if you guys could please let me know the > > > right set of tools and APIs as per your experience. > > Need more info. > > There are many types of car-racing games. > > Do you want it to be 3d, 2d? first-person, third-person, top-down, etc. > > The correct tool is the one which does the specific job best. > > We don't know what the job is so we can't help you choose a tool. > > -Luke > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061004/71f4f68e/attachment.htm From rabidpoobear at gmail.com Wed Oct 4 11:14:34 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 04 Oct 2006 04:14:34 -0500 Subject: [Tutor] Suggestions required on Gaming In-Reply-To: <3cffff920610040209g486538f4l6097a21fd9438385@mail.gmail.com> References: <3cffff920610040200o9604662lece3c7fd28e6ed66@mail.gmail.com> <4523794A.1020502@gmail.com> <3cffff920610040209g486538f4l6097a21fd9438385@mail.gmail.com> Message-ID: <45237B7A.90209@gmail.com> Arun Kumar PG wrote: > Thanks Luke. > > I want to make a 3-D car race game between two players. And yes its > gonna be a networked game where each user will be using his/her own > PC and playing. If you want it to be 3d, you have a couple'o choices... Pygame with the PyopenGL interface, Panda3d, Soya, PyOgre, and perhaps others. The only one I've used was Panda3d, and I didn't get very far, so I can't comment on that. I can say, though, I've played Disney's Toontown game, which is a 3d mmorpg made with Panda3d, so yes, it's possible to make 3d networked games in Python :) >Also, my idea is to have a centralised Python server which acts as a dispachter to send the coordinate and other information to the gaming clients. For your networking, you'll probably want to use Twisted. HTH, -Luke > > - Arun > > > On 10/4/06, *Luke Paireepinart* > wrote: > > Arun Kumar PG wrote: > > Hi All Python lovers! > > > > > > I want to develop a Car racing game using Python. I was looking for > > the libraries which I should use for the same. Some of the > options are > > below and I want you suggestions about the best set of tools and > APIs > > as per your experiences: > > > > - PyGame > > - Panda3D > > - Pixie for rendering > > - RenderMan > > - What else ? > > > > I will really appreciate if you guys could please let me know the > > right set of tools and APIs as per your experience. > Need more info. > There are many types of car-racing games. > Do you want it to be 3d, 2d? first-person, third-person, top-down, > etc. > The correct tool is the one which does the specific job best. > We don't know what the job is so we can't help you choose a tool. > -Luke > > From arunkumarpg at gmail.com Wed Oct 4 11:19:35 2006 From: arunkumarpg at gmail.com (Arun Kumar PG) Date: Wed, 4 Oct 2006 14:49:35 +0530 Subject: [Tutor] Suggestions required on Gaming In-Reply-To: <45237B7A.90209@gmail.com> References: <3cffff920610040200o9604662lece3c7fd28e6ed66@mail.gmail.com> <4523794A.1020502@gmail.com> <3cffff920610040209g486538f4l6097a21fd9438385@mail.gmail.com> <45237B7A.90209@gmail.com> Message-ID: <3cffff920610040219u58844371pc13350c131d8c545@mail.gmail.com> Thanks Luke! This is helpful :) - Arun On 10/4/06, Luke Paireepinart wrote: > > Arun Kumar PG wrote: > > Thanks Luke. > > > > I want to make a 3-D car race game between two players. And yes its > > gonna be a networked game where each user will be using his/her own > > PC and playing. > If you want it to be 3d, you have a couple'o choices... > Pygame with the PyopenGL interface, > Panda3d, > Soya, > PyOgre, > and perhaps others. > The only one I've used was Panda3d, and I didn't get very far, so I > can't comment on that. I can say, though, > I've played Disney's Toontown game, which is a 3d mmorpg made with > Panda3d, so yes, it's possible to make 3d networked games in Python :) > > >Also, my idea is to have a centralised Python server which acts as a > dispachter to send the coordinate and other information to the gaming > clients. > > For your networking, you'll probably want to use Twisted. > > HTH, > -Luke > > > > - Arun > > > > > > On 10/4/06, *Luke Paireepinart* > > wrote: > > > > Arun Kumar PG wrote: > > > Hi All Python lovers! > > > > > > > > > I want to develop a Car racing game using Python. I was looking > for > > > the libraries which I should use for the same. Some of the > > options are > > > below and I want you suggestions about the best set of tools and > > APIs > > > as per your experiences: > > > > > > - PyGame > > > - Panda3D > > > - Pixie for rendering > > > - RenderMan > > > - What else ? > > > > > > I will really appreciate if you guys could please let me know the > > > right set of tools and APIs as per your experience. > > Need more info. > > There are many types of car-racing games. > > Do you want it to be 3d, 2d? first-person, third-person, top-down, > > etc. > > The correct tool is the one which does the specific job best. > > We don't know what the job is so we can't help you choose a tool. > > -Luke > > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061004/5d2da467/attachment.htm From kent37 at tds.net Wed Oct 4 11:48:16 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 04 Oct 2006 05:48:16 -0400 Subject: [Tutor] CGKit In-Reply-To: <4522D3AF.9050807@web.de> References: <4522D3AF.9050807@web.de> Message-ID: <45238360.4090607@tds.net> Carlos wrote: > Thanks Luke and Kent, > > To get CGKit running I need to do two different things: > > First the Python Computer Graphics Kit is composed by an > "cgkit-2.0.0alpha6.win32-py2.4.exe" file and some dependencies that are > PyProtocols, numarray, PyOpenGL, PIL, pygame, PyODE and pySerial, with > the exception of PyProtocols I have installed all of them. When I try to > install PyProtocols from the command prompt it tells me that " The .NET > Framework SDK needs to be installed before building extensions for > Python." I went to Microsoft and installed the "Microsoft .NET Framework > SDK v2.0", but the problem persists. > > The second part is the Python Maya Plug-In. I think that this is the > tricky one, it is asking me to install Py++, that I have already > installed. Now my problem comes when I have to compile the source code > with Boost.Python, this one asks for Boost Jam and Boost. I have been > trying to install this things but still have no clue at how. Use the compiled plug-in. This page: http://cgkit.sourceforge.net/mayadoc/install.html says to copy sourcepy.mll to the Maya plug-in directory. Python extensions for Windows are usually distributed as binaries because so many people do not have the resources and knowledge to compile them. I don't see anything in the Maya plugin docs to indicate that you have to build it from source. Kent From Matthew.Warren at Digica.com Wed Oct 4 11:27:18 2006 From: Matthew.Warren at Digica.com (Matthew Warren) Date: Wed, 4 Oct 2006 10:27:18 +0100 Subject: [Tutor] Creating Adventure Games Python Port - Chapter 2 In-Reply-To: Message-ID: > ============================= > import random > > coin1 = 0 > coin2 = 0 > > coin1 = random.randint(1, 10) > coin2 = random.randint(1, 10) > > if coin1 <= 5: > print "Coin1 is Heads" > else: > print "Coin1 is Tails" > > if coin2 <= 5: > print "Coin2 is Heads" > else: > print "Coin2 is Tails" > ============================= This one does the same thing. Thought I'd post it to help your learning along :) import random for coin in [1,2]: if random.randint(0,1): print "Coin",coin,"is Heads" else: print "Coin",coin,"is Tails" Matt. This email is confidential and may be privileged. If you are not the intended recipient please notify the sender immediately and delete the email from your computer. You should not copy the email, use it for any purpose or disclose its contents to any other person. Please note that any views or opinions presented in this email may be personal to the author and do not necessarily represent the views or opinions of Digica. It is the responsibility of the recipient to check this email for the presence of viruses. Digica accepts no liability for any damage caused by any virus transmitted by this email. UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UK Reception Tel: + 44 (0) 115 977 1177 Support Centre: 0845 607 7070 Fax: + 44 (0) 115 977 7000 http://www.digica.com SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South Africa Tel: + 27 (0) 21 957 4900 Fax: + 27 (0) 21 948 3135 http://www.digica.com From kent37 at tds.net Wed Oct 4 11:56:22 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 04 Oct 2006 05:56:22 -0400 Subject: [Tutor] Help In-Reply-To: References: Message-ID: <45238546.9080401@tds.net> Matthew Warren wrote: > I think eve-online is written in stackless python, they make quite a > dealy about it on their site www.eve-online.com although I cant find the > page myself right now due to filters in the way. Yes, I think you're right that they use stackless. CCP Games was a sponsor of the "Need for Speed" Python sprint in Rekjavik last summer and Christian Tismer, creator of stackless, was a participant. Kent From Matthew.Warren at Digica.com Wed Oct 4 11:12:38 2006 From: Matthew.Warren at Digica.com (Matthew Warren) Date: Wed, 4 Oct 2006 10:12:38 +0100 Subject: [Tutor] Help In-Reply-To: <4520313B.6070403@tds.net> Message-ID: I think eve-online is written in stackless python, they make quite a dealy about it on their site www.eve-online.com although I cant find the page myself right now due to filters in the way. > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of Kent Johnson > Sent: 01 October 2006 22:21 > Cc: tutor at python.org > Subject: Re: [Tutor] Help > > wesley chun wrote: > >> I am trying to learn a programming language good for > programming entire > >> games (core functions too) > > > > check out the PyGame engine: > > http://pygame.org > > > > download the games written on top of PyGame that appear to match the > > functionality you're looking for. if you learn Python at the same > > time, tweaking those games and changing their functionality > will help > > you learn it even faster. > > You should also look at the PyGame Challenge web site: > http://www.pyweek.org/ > > I'm not a game writer either but I have a few thoughts...my > impression > is that Python and PyGame are a good foundation for hobbyist > games. The > PyGame and PyWeek games are good examples. I doubt that you > could write > a commercial quality game like Final Fantasy using just these tools > though. Commercial games have highly optimized game engines. Some of > them use Python as scripting engines for high-level game > play; I doubt > that any commercial games use Python for their core game engine. > > On the other hand, you are a long way from being able to write Final > Fantasy. You need to start small and develop your skills. Python and > PyGame should be well suited for this. > > You might want to read this: > http://tinyurl.com/hc6xc > > which says in part, "Starcraft, Everquest and Quake were all made by > teams of professionals who had budgets usually million dollar > plus. More > importantly though, all of these games were made by people > with a lot of > experience at making games. They did not just decide to make > games and > turned out mega-hit games, they started out small and worked > their way > up. This is the point that anyone who is interested in > getting into game > development needs to understand and repeat, repeat, repeat until it > becomes such a part of your mindset that you couldn't possibly > understand life without this self evident, universal truth." > > and here are more links: > http://en.wikipedia.org/wiki/Game_programming > http://www-cs-students.stanford.edu/~amitp/gameprog.html > > I found these all by Googling "game programming language"; there are > many more interesting links there. > > Good luck, > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > > This email is confidential and may be privileged. If you are not the intended recipient please notify the sender immediately and delete the email from your computer. You should not copy the email, use it for any purpose or disclose its contents to any other person. Please note that any views or opinions presented in this email may be personal to the author and do not necessarily represent the views or opinions of Digica. It is the responsibility of the recipient to check this email for the presence of viruses. Digica accepts no liability for any damage caused by any virus transmitted by this email. UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UK Reception Tel: + 44 (0) 115 977 1177 Support Centre: 0845 607 7070 Fax: + 44 (0) 115 977 7000 http://www.digica.com SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South Africa Tel: + 27 (0) 21 957 4900 Fax: + 27 (0) 21 948 3135 http://www.digica.com From kent37 at tds.net Wed Oct 4 12:02:58 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 04 Oct 2006 06:02:58 -0400 Subject: [Tutor] [Fwd: guess] Message-ID: <452386D2.6090308@tds.net> Forwarding to the list -------- Original Message -------- Subject: guess Date: Tue, 03 Oct 2006 18:12:08 -0600 From: mike viceano To: kent37 at tds.net hey i added another guessing feature that shuld guess the number in the most effective way but i keep getting into endless loops thought you might want it any help with the loops would be great def number(number): ran=input("range >") ran=ran+1 from random import randrange guessed=[] guess=randrange(ran) print guess guessed.append(guess) guesses=1 guessed=[] while guess !=number: guess=randrange(ran) if guess not in guessed: guessed.append(guess) guesses=guesses+1 print guess print"i got the number",number,"in",guesses,"guesses" def num(number): r=input("range >") ran=range(r+1) guess=r/2 print guess guesses=1 while guess!=number: if guess < number: guess= ((r-guess)/2)+guess print guess guesses=guesses+1 elif guess > number: guess= ((r-guess)/2)-guess print guess guesses=guesses+1 print "i got the number",number,"in",guesses,"guesses" _________________________________________________________________ Be seen and heard with Windows Live Messenger and Microsoft LifeCams http://clk.atdmt.com/MSN/go/msnnkwme0020000001msn/direct/01/?href=http://www.microsoft.com/hardware/digitalcommunication/default.mspx?locale=en-us&source=hmtagline From andreengels at gmail.com Wed Oct 4 12:37:43 2006 From: andreengels at gmail.com (Andre Engels) Date: Wed, 4 Oct 2006 12:37:43 +0200 Subject: [Tutor] [Fwd: guess] In-Reply-To: <452386D2.6090308@tds.net> References: <452386D2.6090308@tds.net> Message-ID: <6faf39c90610040337o3c8f161du89f8d5a94166919f@mail.gmail.com> 2006/10/4, Kent Johnson : > hey i added another guessing feature that shuld guess the number in the > most > effective way > but i keep getting into endless loops thought you might want it > any help with the loops would be great What's the value of number? Where is it defined? If number is not an integer or number > ran, then you will indeed end up in an infinite loop. -- Andre Engels, andreengels at gmail.com ICQ: 6260644 -- Skype: a_engels From ajkadri at googlemail.com Wed Oct 4 15:37:13 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Wed, 4 Oct 2006 14:37:13 +0100 Subject: [Tutor] Help me with two dimensional arrays in Python Message-ID: Hi folks, I am stuck.. Please help me with implementing two dimensional array in Python. Thanks. -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061004/c7a71d12/attachment.htm From rabidpoobear at gmail.com Wed Oct 4 15:49:51 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 04 Oct 2006 08:49:51 -0500 Subject: [Tutor] Help me with two dimensional arrays in Python In-Reply-To: References: Message-ID: <4523BBFF.8000001@gmail.com> Asrarahmed Kadri wrote: > > Hi folks, > > I am stuck.. Please help me with implementing two dimensional array in > Python. > There are no such things as arrays in Python, silly! I can help you with a two-dimensional list, though :) Okay, imagine that a list of integers (or any other objects) is a single object itself, that keeps track of the integers (or other objects) for you in whatever order you want. somelist = [1,2,3,4,5] anotherlist = [6,7,8,9,10] Now what you want out of a two-dimensional list is where there are multiple inner lists, with each individual list being a full row, right? so... two_dimensional = [somelist,anotherlist] Or: two_dimensional = [ [1,2,3,4,5] , [6,7,8,9,10] ] This isn't a homework question, right? Good luck, -Luke From kent37 at tds.net Wed Oct 4 16:05:37 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 04 Oct 2006 10:05:37 -0400 Subject: [Tutor] Help me with two dimensional arrays in Python In-Reply-To: References: Message-ID: <4523BFB1.60906@tds.net> Asrarahmed Kadri wrote: > > Hi folks, > > I am stuck.. Please help me with implementing two dimensional array in > Python. Nested lists are the simplest way though beware the gotcha shown here: http://www.python.org/doc/faq/programming/#how-do-i-create-a-multidimensional-list You can also use a dict with tuple indices, e.g. d[1,2] = 3 Numpy is an extension designed for high-performance numerical work, it includes a multidimensional array type: http://numpy.scipy.org// Kent From dkuhlman at rexx.com Wed Oct 4 18:51:35 2006 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Wed, 4 Oct 2006 09:51:35 -0700 Subject: [Tutor] [Fwd: Re: database web app, what tool?] In-Reply-To: <4521E1A7.8020105@gmail.com> References: <4521E1A7.8020105@gmail.com> Message-ID: <20061004165135.GA89691@cutter.rexx.com> On Tue, Oct 03, 2006 at 05:05:59PM +1300, Liam Clarke wrote: > > > -------- Original Message -------- > Subject: Re: [Tutor] database web app, what tool? > Date: Mon, 02 Oct 2006 09:33:28 +0100 > From: paulino1 at sapo.pt > To: Liam Clarke > References: > <4520533C.9090500 at sapo.pt> <45208761.1010207 at gmail.com> > > > > Thank you Liam, > > > Our web server is IIS, but it would be no problem to use another one for this > particular purpose. > > I'v been looking for information on how to design tables for the web with > python, without succes so far. Can you point me any tutorial? > This video is a huge download, but is very well done. It's also quite entertaining. Take a look at "Better Web App Development", which you can find here: http://seankelly.tv/videos It compares Zope/Plone, TurboGears, Django, and others. Warning: It's done by someone who is very positive about Python, and is, therefore, quite biased. And, if you have not already found it, you may want to look at the following page in the Python Wiki: http://wiki.python.org/moin/WebFrameworks Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From nephish at gmail.com Wed Oct 4 19:35:05 2006 From: nephish at gmail.com (shawn bright) Date: Wed, 4 Oct 2006 12:35:05 -0500 Subject: [Tutor] revisiting struct and bytes again. Message-ID: <384c93600610041035r18f8f9f7ubfeb91c468886faa@mail.gmail.com> Hey there, this time my question is a bit simpler. i can make a byte a string or number or whatever now. Up to the number 255. I now have a problem with something that comes in as a 4 byte representation of the number of seconds since 1970. I have been using ord(byte) to make sense of the messages so far, but i don't know how to add bytes greater than 255. the c program that sends us these defines the variable as an unsigned long int. anyone know how to make these four bytes a number of seconds ? thanks sk -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061004/d89d47ce/attachment.htm From ajkadri at googlemail.com Wed Oct 4 19:38:09 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Wed, 4 Oct 2006 18:38:09 +0100 Subject: [Tutor] Help me with two dimensional arrays in Python In-Reply-To: <4523BFB1.60906@tds.net> References: <4523BFB1.60906@tds.net> Message-ID: I am looking for something like this: int arr[5][5]; // C statement; declaring an array of 5 * 5 size Is there an easy and clean way to achieve this in python??? Thanks On 10/4/06, Kent Johnson wrote: > > Asrarahmed Kadri wrote: > > > > Hi folks, > > > > I am stuck.. Please help me with implementing two dimensional array in > > Python. > > Nested lists are the simplest way though beware the gotcha shown here: > > http://www.python.org/doc/faq/programming/#how-do-i-create-a-multidimensional-list > > You can also use a dict with tuple indices, e.g. > d[1,2] = 3 > > Numpy is an extension designed for high-performance numerical work, it > includes a multidimensional array type: > http://numpy.scipy.org// > > Kent > > -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061004/8e10145a/attachment.html From kent37 at tds.net Wed Oct 4 19:56:10 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 04 Oct 2006 13:56:10 -0400 Subject: [Tutor] Help me with two dimensional arrays in Python In-Reply-To: References: <4523BFB1.60906@tds.net> Message-ID: <4523F5BA.7080401@tds.net> Asrarahmed Kadri wrote: > > I am looking for something like this: > > int arr[5][5]; // C statement; declaring an array of 5 * 5 size > > Is there an easy and clean way to achieve this in python??? Can you say something about your use case? If I had to guess I would say numpy is what you are looking for. Did you look at my suggestions? Are you a Python beginner? Kent > > Thanks > > > > On 10/4/06, *Kent Johnson* > wrote: > > Asrarahmed Kadri wrote: > > > > Hi folks, > > > > I am stuck.. Please help me with implementing two dimensional > array in > > Python. > > Nested lists are the simplest way though beware the gotcha shown here: > http://www.python.org/doc/faq/programming/#how-do-i-create-a-multidimensional-list > > > You can also use a dict with tuple indices, e.g. > d[1,2] = 3 > > Numpy is an extension designed for high-performance numerical work, it > includes a multidimensional array type: > http://numpy.scipy.org// > > Kent > > > > > -- > To HIM you shall return. From rabidpoobear at gmail.com Wed Oct 4 19:56:55 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 04 Oct 2006 12:56:55 -0500 Subject: [Tutor] revisiting struct and bytes again. In-Reply-To: <384c93600610041035r18f8f9f7ubfeb91c468886faa@mail.gmail.com> References: <384c93600610041035r18f8f9f7ubfeb91c468886faa@mail.gmail.com> Message-ID: <4523F5E7.2070206@gmail.com> shawn bright wrote: > Hey there, > > this time my question is a bit simpler. > i can make a byte a string or number or whatever now. Up to the number > 255. > I now have a problem with something that comes in as a 4 byte > representation of > the number of seconds since 1970. > I have been using ord(byte) to make sense of the messages so far, but > i don't know how to add bytes greater than 255. > > the c program that sends us these defines the variable as an unsigned > long int. > > anyone know how to make these four bytes a number of seconds ? > if you used struct it'd be easier, but... do you know what order the bytes are in? if they're big-endian just ord each individually and then you'll have a 4 digit base 256 number convert this to base 10 so you can see what it is in regular integers and use the time module to convert. sorry I can't give more detail, I have to run, i'm late for class. -Luke > thanks > > sk > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Wed Oct 4 20:01:18 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 04 Oct 2006 14:01:18 -0400 Subject: [Tutor] revisiting struct and bytes again. In-Reply-To: <384c93600610041035r18f8f9f7ubfeb91c468886faa@mail.gmail.com> References: <384c93600610041035r18f8f9f7ubfeb91c468886faa@mail.gmail.com> Message-ID: <4523F6EE.2070703@tds.net> shawn bright wrote: > Hey there, > > this time my question is a bit simpler. > i can make a byte a string or number or whatever now. Up to the number 255. > I now have a problem with something that comes in as a 4 byte > representation of > the number of seconds since 1970. > I have been using ord(byte) to make sense of the messages so far, but i > don't know how to add bytes greater than 255. > > the c program that sends us these defines the variable as an unsigned > long int. > > anyone know how to make these four bytes a number of seconds ? See the struct module. You may need to know the byte order of the data. In [1]: from struct import unpack In [2]: unpack('I', '\x01\x02\x03\x04') Out[2]: (67305985,) In [3]: unpack('I', '\x01\x02\x03\x04') Out[4]: (16909060,) Kent From mwhite3 at ttsd.k12.or.us Wed Oct 4 19:55:19 2006 From: mwhite3 at ttsd.k12.or.us (Matthew White) Date: Wed, 4 Oct 2006 10:55:19 -0700 Subject: [Tutor] Help me with two dimensional arrays in Python In-Reply-To: References: <4523BFB1.60906@tds.net> Message-ID: <20061004175519.GI5007@ttsd.k12.or.us> Asrarahmed, How about something like this: >>> arr = [] >>> arr.append(['Blue', 'Yellow', 'Green', 'Brown', 'White']) >>> arr[0][0] 'Blue' >>> arr.append(['Up', 'Down', 'Left', 'Right', 'Center']) >>> arr[1][4] 'Center' Is this what you were thinking of? -mtw On Wed, Oct 04, 2006 at 06:38:09PM +0100, Asrarahmed Kadri (ajkadri at googlemail.com) wrote: > I am looking for something like this: > > int arr[5][5]; // C statement; declaring an array of 5 * 5 size > > Is there an easy and clean way to achieve this in python??? > > Thanks > > > > On 10/4/06, Kent Johnson wrote: > > > >Asrarahmed Kadri wrote: > >> > >> Hi folks, > >> > >> I am stuck.. Please help me with implementing two dimensional array in > >> Python. > > > >Nested lists are the simplest way though beware the gotcha shown here: > > > >http://www.python.org/doc/faq/programming/#how-do-i-create-a-multidimensional-list > > > >You can also use a dict with tuple indices, e.g. > >d[1,2] = 3 > > > >Numpy is an extension designed for high-performance numerical work, it > >includes a multidimensional array type: > >http://numpy.scipy.org// > > > >Kent > > > > > > > -- > To HIM you shall return. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Wed Oct 4 21:23:09 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 4 Oct 2006 20:23:09 +0100 Subject: [Tutor] guess] References: <452386D2.6090308@tds.net> Message-ID: > def number(number): > ran=input("range >") > ran=ran+1 > from random import randrange > guessed=[] > guess=randrange(ran) > print guess > guessed.append(guess) > guesses=1 > guessed=[] <---- Why do you reset guessed to an empty list > here? also couldn't the whole chunk above be moved into the loop? see below > while guess !=number: > guess=randrange(ran) > if guess not in guessed: > guessed.append(guess) > guesses=guesses+1 > print guess > > print"i got the number",number,"in",guesses,"guesses" # keep imports outside functions. from random import randrange def number(number): ran=input("range >") + 1 guessed=[] guesses = 0 # need to initialise it first guess=randrange(ran) while guess != number: if guess not in guessed: guessed.append(guess) guesses += 1 print guess guess=randrange(ran) print "i got the number",number,"in",guesses,"guesses" You might also want to add a check to see if ran < number Also I'm not sure why you don;t count duplicate guesses? But that's your choice I suppose. However if you counted them you can remove the list entirely... Does that help? -- Alan Gauld Back from vacation... From dyoo at hkn.eecs.berkeley.edu Wed Oct 4 23:11:54 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 4 Oct 2006 14:11:54 -0700 (PDT) Subject: [Tutor] Integer division Help requested In-Reply-To: <45234D02.1020300@gmail.com> References: <8fbe2e10610032247l5203f331r869345b7d1c2407b@mail.gmail.com> <45234D02.1020300@gmail.com> Message-ID: >> I feel >> 7/3 should give -2 >> >> since integer divison returns floor > > The floor is the next lowest integer to the float. > floor(-3.000000001) will be -4 > floor(3.99999999) will be 3 Hi Joseph, If it helps, draw out the floor function out on a piece of graph paper. ^ | 2| x==O | 1| x==O | <---------x==O-------> | x==O | x==O | | V I'm using the "x==O" to try to graphically draw out the half-open intervals. If you believe this diagram, then the results you're seeing from integer division should make sense. From dyoo at hkn.eecs.berkeley.edu Wed Oct 4 23:20:34 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 4 Oct 2006 14:20:34 -0700 (PDT) Subject: [Tutor] Help me with two dimensional arrays in Python In-Reply-To: <20061004175519.GI5007@ttsd.k12.or.us> References: <4523BFB1.60906@tds.net> <20061004175519.GI5007@ttsd.k12.or.us> Message-ID: >>>> I am stuck.. Please help me with implementing two dimensional array >>>> in Python. Hi Asrarahmed, What do you need a two-dimensional array for? This is a serious question: what's your application? What are you trying to represent, and why? As a glib possible answer: you can use a dictionary to map 2-tuples to values. If you think about it, that's almost what a 2d array does in other languages. ################## points = {} points[(3, 4)] = 1 points[(1, 7)] = 2 ################## But this may not be the right approach for your problem. Tell us more of what you are trying to do. From tpc247 at gmail.com Thu Oct 5 11:14:29 2006 From: tpc247 at gmail.com (tpc247 at gmail.com) Date: Thu, 5 Oct 2006 02:14:29 -0700 Subject: [Tutor] How do I make a variable that refers to an object have the same label as the object's name ? Message-ID: question for the Python crowd: when creating a series of objects, where each object represents a field from a submitted html form, how do I make variables that reference the objects be the same as the names of the respective objects ? For example, I have a class called Datum: class Datum: def __init__(self, key, value, required=None, label=None): self.key = key self.value = value self.required = required self.label = label and a dictionary of submitted values: some_dict = {'applicant_full_name':'John Smith', 'applicant_address_line_1':'100 Main Street', 'applicant_city':'Anytown', 'applicant_state':'WY', 'applicant_postal_code':'55555', 'country':'US', ' applicant_email':'jsmith at server.gov', 'applicant_telephone':'555 555 5555'} and I created a list of objects like so: some_list = [] for key, value in some_dict.items(): some_datum = Datum(key, value) some_list.append(some_datum) so now I have a list of Datum instances called some_list, and I would like to make it so I can refer to each respective Datum instance by its Datum.key, e.g., applicant_full_name would refer to the Datum instance with key 'applicant_full_name' and applicant_full_name.value would give me "John Smith." I tried: for x in some_list: some_string = "%s = %s" % (x.key, x) eval(some_string) and got: Traceback (most recent call last): File "", line 4, in -toplevel- eval(some_string) File "", line 1 applicant_state = <__main__.Datum instance at 0x009745F8> ^ SyntaxError: invalid syntax Am I doing something wrong ? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061005/9bb92b99/attachment.htm From alan.gauld at btinternet.com Thu Oct 5 11:38:22 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 5 Oct 2006 10:38:22 +0100 Subject: [Tutor] How do I make a variable that refers to an object have thesame label as the object's name ? References: Message-ID: > when creating a series of objects, where each object represents a > field from > a submitted html form, how do I make variables that reference the > objects be > the same as the names of the respective objects ? The usual solution for this is to use a dictionary keyed by object name. There is an example of this technique in my OOP topic in my tutor using bank accounts keyed by account number - under the heading "Collections of Objects". There are other solutions based on modifying the global namerspace but thats messy IMHO and makes your code very dependant on the pre-knowledge of the fields passed which can introduce maintenance problems later. Using a dictionary your code becomes: > class Datum: > def __init__(self, value, required=None, label=None): > self.value = value > self.required = required > self.label = label > > and a dictionary of submitted values: > > some_dict = {'applicant_full_name':'John Smith', > 'applicant_address_line_1':'100 Main Street', > 'applicant_city':'Anytown', > 'applicant_state':'WY', 'applicant_postal_code':'55555', > 'country':'US', ' > applicant_email':'jsmith at server.gov', 'applicant_telephone':'555 555 > 5555'} > > and I created a list of objects like so: > > some_list = {} > for key, value in some_dict.items(): > some_list[key] = Datum(value) > to make it so I can refer to each respective Datum instance by its > Datum.key, > e.g., applicant_full_name would refer to the Datum instance with key > 'applicant_full_name' and applicant_full_name.value would give me > "John > Smith." I tried: print some_list['applicant_full_name'].value > for x in some_list: > some_string = "%s = %s" % (x.key, x) > eval(some_string) You would need exec() not eval but... eval and exec both have serious security implications and should be avoided where possible. Hopefully the dictionary technique achieves what you want? -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From halamillo at mail.wsu.edu Thu Oct 5 08:05:55 2006 From: halamillo at mail.wsu.edu (halamillo at mail.wsu.edu) Date: Wed, 4 Oct 2006 23:05:55 -0700 (PDT) Subject: [Tutor] module loading Message-ID: <62253.68.69.187.156.1160028355.squirrel@www.mail.wsu.edu> Newbie BioGrad student here (again): First, thanks for the help on the root node variable last time. It was most helpful! Now, I am trying to load a new module into MacPython, but after doing $ python setup.py install, or $ python setup.py build, then $ python setup.py the files on the module I downloaded are the following: DEVELOPERS Legal.htm PKG-INFO Src customize.py rpm_build.sh Demo Lib Packages Test makeclean.sh rpm_install.sh INSTALL MANIFEST README build makedist.bat setup.cfg Include Misc RPM.README changes.txt makedist.sh setup.py The INSTALL file says I don't need to configure the module if I'm running versions greater than OSX, which I am, but when I run the setup file in the last line of a bunch of erros it tells me the gcc failed. Thanks again for your help. You guys rock. Hugo Alamillo 265 Eastlick Biological Sciences PO Box 644236 Pullman, WA 99164-4236 509-432-6869 https://www.wsu.edu/~halamillo/ From ajkadri at googlemail.com Thu Oct 5 13:01:12 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Thu, 5 Oct 2006 12:01:12 +0100 Subject: [Tutor] Help me with two dimensional arrays in Python In-Reply-To: <20061004175519.GI5007@ttsd.k12.or.us> References: <4523BFB1.60906@tds.net> <20061004175519.GI5007@ttsd.k12.or.us> Message-ID: Its something very close. What I want is: 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 This can be done using arrays, right or is there any other way?? My logic in C is: int arr[5][5]; for (i=0;i<5;i++) { flag = 0; for (j=0;j<=i;j++) { if (flag == 0 || j == i) // print 1 if the array element is the first or the last number { arr[i][j] = 1; flag = 1; } arr[i][j] = arr[i-1][j-1] + arr[i-1][j]; } thanks. On 10/4/06, Matthew White wrote: > > Asrarahmed, > > How about something like this: > > >>> arr = [] > >>> arr.append(['Blue', 'Yellow', 'Green', 'Brown', 'White']) > >>> arr[0][0] > 'Blue' > >>> arr.append(['Up', 'Down', 'Left', 'Right', 'Center']) > >>> arr[1][4] > 'Center' > > Is this what you were thinking of? > > -mtw > > > On Wed, Oct 04, 2006 at 06:38:09PM +0100, Asrarahmed Kadri ( > ajkadri at googlemail.com) wrote: > > I am looking for something like this: > > > > int arr[5][5]; // C statement; declaring an array of 5 * 5 size > > > > Is there an easy and clean way to achieve this in python??? > > > > Thanks > > > > > > > > On 10/4/06, Kent Johnson wrote: > > > > > >Asrarahmed Kadri wrote: > > >> > > >> Hi folks, > > >> > > >> I am stuck.. Please help me with implementing two dimensional array > in > > >> Python. > > > > > >Nested lists are the simplest way though beware the gotcha shown here: > > > > > > > http://www.python.org/doc/faq/programming/#how-do-i-create-a-multidimensional-list > > > > > >You can also use a dict with tuple indices, e.g. > > >d[1,2] = 3 > > > > > >Numpy is an extension designed for high-performance numerical work, it > > >includes a multidimensional array type: > > >http://numpy.scipy.org// > > > > > >Kent > > > > > > > > > > > > -- > > To HIM you shall return. > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061005/e68595ba/attachment.html From frank.hoffsummer at gmail.com Thu Oct 5 15:41:39 2006 From: frank.hoffsummer at gmail.com (frank h.) Date: Thu, 5 Oct 2006 15:41:39 +0200 Subject: [Tutor] from string to variable name Message-ID: <60fae7c30610050641k4e120671q2ccfff7bfad1c1a2@mail.gmail.com> hello, i have a string variable that contains a name that I want to use as a variablename putting aside questions of why I would like to do that - i this possible at all? so I want to assign a value to a variable whos name is available only as a string to me. that variable does not exist yet in the local namespace. from: t = "myvar" to: myvar = 3 is this possible? something like setattr? thanks for any insight you might have -frank -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061005/ab3607dd/attachment.htm From rabidpoobear at gmail.com Thu Oct 5 15:49:14 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 05 Oct 2006 08:49:14 -0500 Subject: [Tutor] from string to variable name In-Reply-To: <60fae7c30610050641k4e120671q2ccfff7bfad1c1a2@mail.gmail.com> References: <60fae7c30610050641k4e120671q2ccfff7bfad1c1a2@mail.gmail.com> Message-ID: <45250D5A.9070202@gmail.com> frank h. wrote: > hello, i have a string variable that contains a name that I want to > use as a variablename > putting aside questions of why I would like to do that - i this > possible at all? > > so I want to assign a value to a variable whos name is available only > as a string to me. > that variable does not exist yet in the local namespace. > > from: t = "myvar" > to: myvar = 3 > > is this possible? something like setattr? > thanks for any insight you might have I think the point of dictionaries is to get this same basic functionality without polluting the namespaces. You won't let us ask you 'why' you want to do this, but I'll ask you: Why don't you want to use a dictionary? Do you want to know if it's _Possible_ just so you'll know, or do you actually want to use this for something? If you just want to know if it's possible, I believe it is. But consider: if you don't know the variable name until runtime, how are you going to refer to the variable later in your code? It would be, insofar as I can tell, useless to do this. > -frank -Luke From rabidpoobear at gmail.com Thu Oct 5 15:54:30 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 05 Oct 2006 08:54:30 -0500 Subject: [Tutor] Help me with two dimensional arrays in Python In-Reply-To: References: <4523BFB1.60906@tds.net> <20061004175519.GI5007@ttsd.k12.or.us> Message-ID: <45250E96.8050806@gmail.com> Asrarahmed Kadri wrote: > Its something very close. > What I want is: > > 1 > 1 1 > 1 2 1 > 1 3 3 1 > 1 4 6 4 1 > > This can be done using arrays, right or is there any other way?? They're not arrays, they're lists! arrays imply contiguous memory blocks and single data types. Lists are neither of these. > My logic in C is: > > int arr[5][5]; > for (i=0;i<5;i++) > { > flag = 0; > for (j=0;j<=i;j++) > { > if (flag == 0 || j == i) // print 1 if the array element is the > first or the last number > { > arr[i][j] = 1; > flag = 1; > } > arr[i][j] = arr[i-1][j-1] + arr[i-1][j]; > } Yes, you could do this in Python. I'm guessing it'd be something like this: lst = [] for x in range(5): tmp = [] for y in range(x): if y == 0: tmp.append(1) else: tmp.append(tmp[y-1]) #this line would be different lst.append(tmp) That's the best I can do. HTH, -Luke From Mike.Hansen at atmel.com Thu Oct 5 16:07:30 2006 From: Mike.Hansen at atmel.com (Mike Hansen) Date: Thu, 5 Oct 2006 08:07:30 -0600 Subject: [Tutor] module loading Message-ID: <57B026980605A64F9B23484C5659E32E35845C@poccso.US.ad.atmel.com> > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of halamillo at mail.wsu.edu > Sent: Thursday, October 05, 2006 12:06 AM > To: tutor at python.org > Subject: [Tutor] module loading > > Newbie BioGrad student here (again): > > First, thanks for the help on the root node variable last time. It was > most helpful! > > Now, I am trying to load a new module into MacPython, but > after doing $ > python setup.py install, or $ python setup.py build, then $ python > setup.py > > the files on the module I downloaded are the following: > > DEVELOPERS Legal.htm PKG-INFO Src > customize.py rpm_build.sh > Demo Lib Packages Test > makeclean.sh rpm_install.sh > INSTALL MANIFEST README build > makedist.bat setup.cfg > Include Misc RPM.README changes.txt > makedist.sh setup.py > > > The INSTALL file says I don't need to configure the module if > I'm running > versions greater than OSX, which I am, but when I run the > setup file in > the last line of a bunch of erros it tells me the gcc failed. > > > Thanks again for your help. You guys rock. > > > > Hugo Alamillo > 265 Eastlick > Biological Sciences > PO Box 644236 > Pullman, WA 99164-4236 > 509-432-6869 > https://www.wsu.edu/~halamillo/ > > You might try asking this on the python mac mail list. They are extremely helpful. http://www.python.org/community/sigs/current/pythonmac-sig/ Mike From rabidpoobear at gmail.com Thu Oct 5 16:17:51 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 05 Oct 2006 09:17:51 -0500 Subject: [Tutor] [Fwd: Re: from string to variable name] Message-ID: <4525140F.1090403@gmail.com> OOPS, forwarding my reply to frank. I accidentally sent it straight to him. -------------- next part -------------- An embedded message was scrubbed... From: Luke Paireepinart Subject: Re: [Tutor] from string to variable name Date: Thu, 05 Oct 2006 09:17:19 -0500 Size: 2013 Url: http://mail.python.org/pipermail/tutor/attachments/20061005/a6158726/attachment.mht From carloslara at web.de Thu Oct 5 16:18:15 2006 From: carloslara at web.de (Carlos) Date: Thu, 05 Oct 2006 16:18:15 +0200 Subject: [Tutor] CGKit In-Reply-To: <45238360.4090607@tds.net> References: <4522D3AF.9050807@web.de> <45238360.4090607@tds.net> Message-ID: <45251427.20504@web.de> Hi Kent, Probably I'm totally missing something, but... I think there is not a compiled plug-in, if you go here http://cgkit.sourceforge.net/#download you are going to see that : " The Maya Python package (i.e. the Maya plug in and the actual Python package) is a separate package that can be downloaded from the above page as well. Currently, only the sources are available." The pages that you are pointing are installation instructions, but they not point to the compiled plug-in. If you go to the project download page you will see the cgkit and maya sections, inside the maya section there are some files, but none of them is the plug-in itself, only the sources (I think). I have found that you can compile the plug-ins with scons instead of boost and seems to be easier. I just need to now how to set some paths. Here is what the readme of the file says: "The plugin is built using SCons (www.scons.org). If necessary, you can do customizations in a file config.py where you can set additional include paths and library paths in the lists CPPPATH and LIBPATH. Example: CPPPATH = ["...path1...", "...path2...", ...] LIBPATH = ["...path1...", "...path2...", ...] You have to make sure that the Maya SDK and the Python SDK can be found. To compile the plugin you have to call "scons" in the root directory of the sourcepy plugin (where the SConstruct file is located). If everything went fine, the result will be in the bin subdirectory (the file will be called sourcepy.mll or sourcepy.so) from where you can copy it to any convenient place where Maya is able to find it." I hope that someone can tell me how to do this. Carlos "" Thanks Carlos Kent Johnson wrote: > Carlos wrote: >> Thanks Luke and Kent, >> >> To get CGKit running I need to do two different things: >> >> First the Python Computer Graphics Kit is composed by an >> "cgkit-2.0.0alpha6.win32-py2.4.exe" file and some dependencies that >> are PyProtocols, numarray, PyOpenGL, PIL, pygame, PyODE and pySerial, >> with the exception of PyProtocols I have installed all of them. When >> I try to install PyProtocols from the command prompt it tells me that >> " The .NET Framework SDK needs to be installed before building >> extensions for Python." I went to Microsoft and installed the >> "Microsoft .NET Framework SDK v2.0", but the problem persists. >> >> The second part is the Python Maya Plug-In. I think that this is the >> tricky one, it is asking me to install Py++, that I have already >> installed. Now my problem comes when I have to compile the source >> code with Boost.Python, this one asks for Boost Jam and Boost. I have >> been trying to install this things but still have no clue at how. > > Use the compiled plug-in. This page: > http://cgkit.sourceforge.net/mayadoc/install.html > says to copy sourcepy.mll to the Maya plug-in directory. > > Python extensions for Windows are usually distributed as binaries > because so many people do not have the resources and knowledge to > compile them. I don't see anything in the Maya plugin docs to indicate > that you have to build it from source. > > Kent > > > From ajkadri at googlemail.com Thu Oct 5 16:19:39 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Thu, 5 Oct 2006 15:19:39 +0100 Subject: [Tutor] Help me with two dimensional arrays in Python In-Reply-To: <45250E96.8050806@gmail.com> References: <4523BFB1.60906@tds.net> <20061004175519.GI5007@ttsd.k12.or.us> <45250E96.8050806@gmail.com> Message-ID: Thank you so much. I am trying to implement. I hope I can do it. A gentle note: This is not a homework question. I am learning python as a part of my Project work. On 10/5/06, Luke Paireepinart wrote: > > Asrarahmed Kadri wrote: > > Its something very close. > > What I want is: > > > > 1 > > 1 1 > > 1 2 1 > > 1 3 3 1 > > 1 4 6 4 1 > > > > This can be done using arrays, right or is there any other way?? > They're not arrays, they're lists! > arrays imply contiguous memory blocks and single data types. > Lists are neither of these. > > My logic in C is: > > > > int arr[5][5]; > > for (i=0;i<5;i++) > > { > > flag = 0; > > for (j=0;j<=i;j++) > > { > > if (flag == 0 || j == i) // print 1 if the array element is the > > first or the last number > > { > > arr[i][j] = 1; > > flag = 1; > > } > > arr[i][j] = arr[i-1][j-1] + arr[i-1][j]; > > } > Yes, you could do this in Python. > I'm guessing it'd be something like this: > > lst = [] > for x in range(5): > tmp = [] > for y in range(x): > if y == 0: > tmp.append(1) > else: > tmp.append(tmp[y-1]) #this line would be different > lst.append(tmp) > > That's the best I can do. > > HTH, > -Luke > -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061005/50ce6304/attachment.html From kent37 at tds.net Thu Oct 5 16:26:19 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 05 Oct 2006 10:26:19 -0400 Subject: [Tutor] Help me with two dimensional arrays in Python In-Reply-To: References: <4523BFB1.60906@tds.net> <20061004175519.GI5007@ttsd.k12.or.us> Message-ID: <4525160B.3040709@tds.net> Asrarahmed Kadri wrote: > Its something very close. > What I want is: > > 1 > 1 1 > 1 2 1 > 1 3 3 1 > 1 4 6 4 1 > > This can be done using arrays, right or is there any other way?? Is this a homework assignment? A list of lists seems like the appropriate way to represent this, especially since it is not actually a square array. Here is a simpler example that might give you some ideas: In [5]: b=[] In [6]: for i in range(5): ...: b.append(range(i)) ...: ...: In [7]: b Out[7]: [[], [0], [0, 1], [0, 1, 2], [0, 1, 2, 3]] Kent From kent37 at tds.net Thu Oct 5 16:32:05 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 05 Oct 2006 10:32:05 -0400 Subject: [Tutor] CGKit In-Reply-To: <45251427.20504@web.de> References: <4522D3AF.9050807@web.de> <45238360.4090607@tds.net> <45251427.20504@web.de> Message-ID: <45251765.2040309@tds.net> Carlos wrote: > Hi Kent, > > Probably I'm totally missing something, but... No, your analysis looks correct to me. Sorry, this goes beyond my ability to help you. Is there a Maya or CGKit mailing list where you can ask? The compiled plugin may be available from another source. Kent > > I think there is not a compiled plug-in, if you go here > http://cgkit.sourceforge.net/#download you are going to see that : " The > Maya Python package (i.e. the Maya plug in and the actual Python > package) is a separate package that can be downloaded from the above > page as well. Currently, only the sources are available." > > The pages that you are pointing are installation instructions, but they > not point to the compiled plug-in. If you go to the project download > page you will see the cgkit and > maya sections, inside the maya section there are some files, but none of > them is the plug-in itself, only the sources (I think). I have found > that you can compile the plug-ins with scons instead of boost and seems > to be easier. I just need to now how to set some paths. Here is what the > readme of the file says: > > > "The plugin is built using SCons (www.scons.org). If necessary, you can > do customizations in a file config.py where you can set additional > include paths and library paths in the lists CPPPATH and LIBPATH. Example: > > CPPPATH = ["...path1...", "...path2...", ...] > LIBPATH = ["...path1...", "...path2...", ...] > > You have to make sure that the Maya SDK and the Python SDK can be found. > To compile the plugin you have to call "scons" in the root directory of > the sourcepy plugin (where the SConstruct file is located). If > everything went fine, the result will be in the bin subdirectory (the > file will be called sourcepy.mll or sourcepy.so) from where you can copy > it to any convenient place where Maya is able to find it." > > I hope that someone can tell me how to do this. > Carlos > > > > "" > > Thanks > Carlos > > Kent Johnson wrote: >> Carlos wrote: >>> Thanks Luke and Kent, >>> >>> To get CGKit running I need to do two different things: >>> >>> First the Python Computer Graphics Kit is composed by an >>> "cgkit-2.0.0alpha6.win32-py2.4.exe" file and some dependencies that >>> are PyProtocols, numarray, PyOpenGL, PIL, pygame, PyODE and pySerial, >>> with the exception of PyProtocols I have installed all of them. When >>> I try to install PyProtocols from the command prompt it tells me that >>> " The .NET Framework SDK needs to be installed before building >>> extensions for Python." I went to Microsoft and installed the >>> "Microsoft .NET Framework SDK v2.0", but the problem persists. >>> >>> The second part is the Python Maya Plug-In. I think that this is the >>> tricky one, it is asking me to install Py++, that I have already >>> installed. Now my problem comes when I have to compile the source >>> code with Boost.Python, this one asks for Boost Jam and Boost. I have >>> been trying to install this things but still have no clue at how. >> Use the compiled plug-in. This page: >> http://cgkit.sourceforge.net/mayadoc/install.html >> says to copy sourcepy.mll to the Maya plug-in directory. >> >> Python extensions for Windows are usually distributed as binaries >> because so many people do not have the resources and knowledge to >> compile them. I don't see anything in the Maya plugin docs to indicate >> that you have to build it from source. >> >> Kent >> >> >> > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From ajkadri at googlemail.com Thu Oct 5 16:36:45 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Thu, 5 Oct 2006 15:36:45 +0100 Subject: [Tutor] Luke, thanks a lot , here is the perfect code (as per ur suggestion) Message-ID: #Implementation of Pascal Triangle num_of_lines = input("How many lines you want to display") list1 = [] for i in range(num_of_lines): flag = 0 tmp = [] for j in range(i+1): if flag == 0 or j == i: tmp.append(1) # for the first or teh last element of the line flag = 1 else: tmp.append(list1[i-1][j-1]+list1[i-1][j]) # for rest, add teh numbers in previous row list1.append(tmp) # this code prints the Pascal triangle for i in range(num_of_lines): for j in range(i+1): print list1[i][j], print Output for num_lines = 5: 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 ----------------------------- THNAKS ONCE MORE. On 10/5/06, Asrarahmed Kadri wrote: > > Thank you so much. > I am trying to implement. I hope I can do it. > > A gentle note: This is not a homework question. > I am learning python as a part of my Project work. > > > > On 10/5/06, Luke Paireepinart wrote: > > > > Asrarahmed Kadri wrote: > > > Its something very close. > > > What I want is: > > > > > > 1 > > > 1 1 > > > 1 2 1 > > > 1 3 3 1 > > > 1 4 6 4 1 > > > > > > This can be done using arrays, right or is there any other way?? > > They're not arrays, they're lists! > > arrays imply contiguous memory blocks and single data types. > > Lists are neither of these. > > > My logic in C is: > > > > > > int arr[5][5]; > > > for (i=0;i<5;i++) > > > { > > > flag = 0; > > > for (j=0;j<=i;j++) > > > { > > > if (flag == 0 || j == i) // print 1 if the array element is the > > > first or the last number > > > { > > > arr[i][j] = 1; > > > flag = 1; > > > } > > > arr[i][j] = arr[i-1][j-1] + arr[i-1][j]; > > > } > > Yes, you could do this in Python. > > I'm guessing it'd be something like this: > > > > lst = [] > > for x in range(5): > > tmp = [] > > for y in range(x): > > if y == 0: > > tmp.append(1) > > else: > > tmp.append(tmp[y-1]) #this line would be different > > lst.append(tmp) > > > > That's the best I can do. > > > > HTH, > > -Luke > > > > > > -- > To HIM you shall return. > -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061005/e23e0a9e/attachment.html From python at venix.com Thu Oct 5 17:22:18 2006 From: python at venix.com (Python) Date: Thu, 05 Oct 2006 11:22:18 -0400 Subject: [Tutor] [Fwd: Re: from string to variable name] In-Reply-To: <4525140F.1090403@gmail.com> References: <4525140F.1090403@gmail.com> Message-ID: <1160061738.8103.62.camel@www.venix.com> On Thu, 2006-10-05 at 09:17 -0500, Luke Paireepinart wrote: (actually from Frank) > > I have a parameterized string template, I publish it using > > > > print mytemplate % locals() Original post asked to create variable in local namespace from string. > so I want to assign a value to a variable whos name is available only > as a string to me. > that variable does not exist yet in the local namespace. > > from: t = "myvar" > to: myvar = 3 You can do something like: templatevars = dict(locals()) # copy of locals templatevars[t] = 3 print mytemplate % templatevars It is OK for templatevars to have extra variables. You will get a KeyError if templatevars is missing a value. -- Lloyd Kvam Venix Corp From kent37 at tds.net Thu Oct 5 17:25:46 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 05 Oct 2006 11:25:46 -0400 Subject: [Tutor] Luke, thanks a lot , here is the perfect code (as per ur suggestion) In-Reply-To: References: Message-ID: <452523FA.3060601@tds.net> Asrarahmed Kadri wrote: > #Implementation of Pascal Triangle > > num_of_lines = input("How many lines you want to display") > > list1 = [] > > for i in range(num_of_lines): > flag = 0 > tmp = [] > for j in range(i+1): > if flag == 0 or j == i: > tmp.append(1) # for the first or teh last element of the line > flag = 1 > else: > tmp.append(list1[i-1][j-1]+list1[i-1][j]) # for rest, add > teh numbers in previous row > > list1.append(tmp) That's good. You could shorten it a little by getting rid of flag and just testing for j==0 or j==i. Here is another way to do it, it requires priming the output with the first row but the loop is a little shorter: In [1]: binom = [[1]] In [3]: for i in range(5): ...: prev = binom[i] ...: next = [1] + [ prev[j]+prev[j+1] for j in range(len(prev)-1) ] + [1] ...: binom.append(next) ...: ...: In [4]: binom Out[4]: [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1], [1, 5, 10, 10, 5, 1]] There's a truly hideous one-liner hidden in your solution. It uses nested list comprehensions, a hack to refer to the list being built within a list comp, and the new conditional expression. Be careful who you show this too, it may scare dogs and small children ;) It does actually work: list1 = [ [ locals()["_[1]"][i-1][j-1]+locals()["_[1]"][i-1][j] if (j != 0 and j != i) else 1 for j in range(i+1) ] for i in range(num_of_lines) ] Now we know why conditional expressions were added to Python 2.5! See this recipe for details about the locals() hack: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/204297 Sorry I couldn't resist :-) Kent From 3dbernard at gmail.com Thu Oct 5 17:33:17 2006 From: 3dbernard at gmail.com (Bernard Lebel) Date: Thu, 5 Oct 2006 11:33:17 -0400 Subject: [Tutor] OT: Book(s) about linux Message-ID: <61d0e2b40610050833gb425b8fye4bcab6219b54e03@mail.gmail.com> Hello, Sorry to use this list for such an OT subject. But I want to get hands down with Linux, and am looking for a book or two on the subject. I'm looking for information about installation, configuration, optimisation, and management of the Linux OS. Thanks Bernard From kent37 at tds.net Thu Oct 5 17:36:55 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 05 Oct 2006 11:36:55 -0400 Subject: [Tutor] [Fwd: Re: from string to variable name] In-Reply-To: <1160061738.8103.62.camel@www.venix.com> References: <4525140F.1090403@gmail.com> <1160061738.8103.62.camel@www.venix.com> Message-ID: <45252697.8030904@tds.net> Python wrote: > On Thu, 2006-10-05 at 09:17 -0500, Luke Paireepinart wrote: > (actually from Frank) >>> I have a parameterized string template, I publish it using >>> >>> print mytemplate % locals() > Original post asked to create variable in local namespace from string. >> so I want to assign a value to a variable whos name is available only >> as a string to me. >> that variable does not exist yet in the local namespace. >> >> from: t = "myvar" >> to: myvar = 3 > > You can do something like: > templatevars = dict(locals()) # copy of locals > templatevars[t] = 3 > print mytemplate % templatevars > > It is OK for templatevars to have extra variables. You will get a > KeyError if templatevars is missing a value. A slight variation, if you have multiple values you want to accumulate in a dict, would be something like this using dict.update(): templatevars = {} ... templatevars['t'] = 3 ... templatevars['u'] = 4 ... templatevars.update(locals()) print mytemplate % templatevars Kent From dkuhlman at rexx.com Thu Oct 5 18:07:59 2006 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Thu, 5 Oct 2006 09:07:59 -0700 Subject: [Tutor] OT: Book(s) about linux In-Reply-To: <61d0e2b40610050833gb425b8fye4bcab6219b54e03@mail.gmail.com> References: <61d0e2b40610050833gb425b8fye4bcab6219b54e03@mail.gmail.com> Message-ID: <20061005160759.GA6609@cutter.rexx.com> On Thu, Oct 05, 2006 at 11:33:17AM -0400, Bernard Lebel wrote: > Hello, > > Sorry to use this list for such an OT subject. But I want to get hands > down with Linux, and am looking for a book or two on the subject. > > I'm looking for information about installation, configuration, > optimisation, and management of the Linux OS. > You are right. It's off-topic for us. Once you have picked a Linux distribution, you are likely to get more help at the Web site dedicated to that distribution. For example, I'm on Ubuntu/Kubuntu, so http://www.ubuntu.com/ is helpful. For lots of documentation, start here: http://www.linux.org/books/index.html http://www.linux.org/docs/ http://tldp.org/ Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From python at venix.com Thu Oct 5 18:19:39 2006 From: python at venix.com (Python) Date: Thu, 05 Oct 2006 12:19:39 -0400 Subject: [Tutor] OT: Book(s) about linux In-Reply-To: <61d0e2b40610050833gb425b8fye4bcab6219b54e03@mail.gmail.com> References: <61d0e2b40610050833gb425b8fye4bcab6219b54e03@mail.gmail.com> Message-ID: <1160065179.8103.84.camel@www.venix.com> On Thu, 2006-10-05 at 11:33 -0400, Bernard Lebel wrote: > Hello, > > Sorry to use this list for such an OT subject. But I want to get hands > down with Linux, and am looking for a book or two on the subject. > > I'm looking for information about installation, configuration, > optimisation, and management of the Linux OS. If you are new to Linux, you're likely to be best helped by a book that matches your distribution, e.g. "Ubuntu Linux" or "Ubuntu Unleashed". (Not to push you to Ubuntu; I'm running Fedora myself.) These books provide shallow coverage of everything and will give the background needed to make good use of the system documentation. They will also point you to yum, synaptic, smart or whatever package management system makes sense with your chosen distribution. The package managers greatly simplify system administration. There are books devoted to packages: SSH, Sendmail, DNS/Bind, Apache, Samba, etc. so you may need to get additional books depending on how you use your computer. "Linux in a Nutshell" (mine is 5th edition) provides a useful reference. There are also books like "Linux Debugging and Performance Tuning" which are more system oriented. "Moving to the Linux Business Desktop" is useful for finding your way among all of the available desktop applications. Linux is a pretty broad subject so there's a huge range of books from which to pick. > > > > Thanks > Bernard > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From rdm at rcblue.com Thu Oct 5 19:10:39 2006 From: rdm at rcblue.com (Dick Moores) Date: Thu, 05 Oct 2006 10:10:39 -0700 Subject: [Tutor] What is a Python "project"? In-Reply-To: <4522DD83.30905@cc.umanitoba.ca> References: <57B026980605A64F9B23484C5659E32E3582F1@poccso.US.ad.atmel.com> <7.0.1.0.2.20061003112250.069236f0@rcblue.com> <4522DD83.30905@cc.umanitoba.ca> Message-ID: <7.0.1.0.2.20061005095943.01100828@rcblue.com> At 03:00 PM 10/3/2006, Brian van den Broek wrote: >I've never used Wing, but unless its `project' concept is radically >different than many other editors, it isn't about organizing the files >on disk. Rather, it is about organizing a group of files into a >collection the editor can open in one swell foop. The idea is to >liberate you from having to recall just where the files live and allow >you to merely open a group of related files and get on with what >you're up to. (It is sort of like saving a group of tabs in firefox.) > >Best, > >Brian vdB I thought I'd check with Wingware support: ========email to Winware support================ I asked the Python Tutor list what a project is, and got many answers. Does this one correctly characterize what a project means with WingIDE? "I've never used Wing, but unless its `project' concept is radically different than many other editors, it isn't about organizing the files on disk. Rather, it is about organizing a group of files into a collection the editor can open in one swell foop. The idea is to liberate you from having to recall just where the files live and allow you to merely open a group of related files and get on with what you're up to. (It is sort of like saving a group of tabs in firefox.)" Thanks, Dick Moores =============================================== =============reply from Wingware support============ Not quite. A project is the set of files that you write that compose an application -- or a set of related scripts. They're files that are related to one, well, project ;). Wing displays all of the files in the project pane, lets you search all files in the project easily, displays all classes defined in the project, among other things (at least in the Pro version). Project files also can share common setting such as python executable, environment variable. One file may also be set as the main debug file so it's the one always run when you press the start debug icon or F5. You might have all files in a project open at once in a small project, but you probably don't want them all open once you get over maybe 10 files. John ========================================= ===========email to Wingware support=========== Thanks for all that info, John. But is his point correct that the files in a project don't need to be together in the same folder, nor do they need to be moved at all in order to participate in the project (I've fleshed his point out a bit)? Dick ========================================== =========reply from Wingware support============ Yes, the files don't need to be in the same folder. As a practical matter, it's a good idea to put them in a small number of folders though. Otherwise, they'd be scattered all over the disk. Cheers, John =========================================== Dick Moores From carloslara at web.de Thu Oct 5 19:55:54 2006 From: carloslara at web.de (Carlos) Date: Thu, 05 Oct 2006 19:55:54 +0200 Subject: [Tutor] CGKit Message-ID: <4525472A.5070501@web.de> Hi Kent, Thanks for the info, I will send a mail to the plug-in developer. I didnt mention this before, Im an architect and my master thesis semester is beginning now. Last semester I was introduced to what is somehow known as morphogenetic design, to programming and to python. From that semester a small python script came, that generated a structure composed by struts and tensor cables inside of maya, anyway, this semester I want to use programming again, this stuff has really convinced me that can be useful in the design field. My idea is to create a script that will deal with the spatial organization of a housing block, it would be very interesting to see it generating a number of solutions and evolving them a number of times until it can find an "optimum" solution. What I would like to know is, does this sounds too complex for a newcomer like me? If by chance anyone has some experience that can share I would be grateful. I know that this is a little off topic, in the future I will try to keep this more centered on python. Best Regards Carlos From ajkadri at googlemail.com Thu Oct 5 21:14:40 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Thu, 5 Oct 2006 20:14:40 +0100 Subject: [Tutor] Luke, thanks a lot , here is the perfect code (as per ur suggestion) In-Reply-To: <452523FA.3060601@tds.net> References: <452523FA.3060601@tds.net> Message-ID: On 10/5/06, Kent Johnson wrote: > > Asrarahmed Kadri wrote: > > #Implementation of Pascal Triangle > > > > num_of_lines = input("How many lines you want to display") > > > > list1 = [] > > > > for i in range(num_of_lines): > > flag = 0 > > tmp = [] > > for j in range(i+1): > > if flag == 0 or j == i: > > tmp.append(1) # for the first or teh last element of the > line > > flag = 1 > > else: > > tmp.append(list1[i-1][j-1]+list1[i-1][j]) # for rest, add > > teh numbers in previous row > > > > list1.append(tmp) > > That's good. You could shorten it a little by getting rid of flag and > just testing for j==0 or j==i. Here is another way to do it, it requires > priming the output with the first row but the loop is a little shorter: > > In [1]: binom = [[1]] > > In [3]: for i in range(5): > ...: prev = binom[i] > ...: next = [1] + [ prev[j]+prev[j+1] for j in > range(len(prev)-1) ] + [1] > ...: binom.append(next) > ...: > ...: > > In [4]: binom > Out[4]: [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1], [1, 5, > 10, 10, 5, 1]] > > There's a truly hideous one-liner hidden in your solution. It uses > nested list comprehensions, a hack to refer to the list being built > within a list comp, and the new conditional expression. Be careful who > you show this too, it may scare dogs and small children ;) It does > actually work: What is this??? I cannot understand a single character.. Explain this in length. *list1 = [ [ locals()["_[1]"][i-1][j-1]+locals()["_[1]"][i-1][j] if (j != > 0 and j != i) else 1 for j in range(i+1) ] for i in range(num_of_lines) ] > > *Now we know why conditional expressions were added to Python 2.5! See > this recipe for details about the locals() hack: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/204297 > > Sorry I couldn't resist :-) > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061005/897a556b/attachment.htm From sisson.j at gmail.com Thu Oct 5 16:45:42 2006 From: sisson.j at gmail.com (Jonathon Sisson) Date: Thu, 05 Oct 2006 09:45:42 -0500 Subject: [Tutor] OT: Book(s) about linux In-Reply-To: <1160065179.8103.84.camel@www.venix.com> References: <61d0e2b40610050833gb425b8fye4bcab6219b54e03@mail.gmail.com> <1160065179.8103.84.camel@www.venix.com> Message-ID: <45251A96.6050002@gmail.com> Hello Bernard... Just to give you a pointer about Linux: If you're new, Fedora and Ubuntu are both relatively easy to learn, but powerful (I've never used Ubuntu (or Debian, for that matter), but I hear that Ubuntu is a really great distro). Stay away from Slackware and Gentoo, at least until you've had the chance to familiarize yourself with Linux. I made the mistake of attempting a stage 1 Gentoo install on a PII machine with hardly any experience. (Fortunately, the PII was so slow that I had time to read the manual completely before each step). It booted up fine when I was done, but it was rough (even with extensive documentation ). I'm not saying that Slackware and Gentoo are useless, as both are *extremely* powerful OS's (Gentoo is my favorite OS other than OpenBSD). They do require quite a bit of knowledge just to get them installed, however, and therefore are not good choices for someone just beginning with Linux. Jonathon Python wrote: > On Thu, 2006-10-05 at 11:33 -0400, Bernard Lebel wrote: >> Hello, >> >> Sorry to use this list for such an OT subject. But I want to get hands >> down with Linux, and am looking for a book or two on the subject. >> >> I'm looking for information about installation, configuration, >> optimisation, and management of the Linux OS. > > If you are new to Linux, you're likely to be best helped by a book that > matches your distribution, e.g. "Ubuntu Linux" or "Ubuntu Unleashed". > (Not to push you to Ubuntu; I'm running Fedora myself.) These books > provide shallow coverage of everything and will give the background > needed to make good use of the system documentation. They will also > point you to yum, synaptic, smart or whatever package management system > makes sense with your chosen distribution. The package managers greatly > simplify system administration. > > There are books devoted to packages: SSH, Sendmail, DNS/Bind, Apache, > Samba, etc. so you may need to get additional books depending on how you > use your computer. "Linux in a Nutshell" (mine is 5th edition) provides > a useful reference. There are also books like "Linux Debugging and > Performance Tuning" which are more system oriented. "Moving to the > Linux Business Desktop" is useful for finding your way among all of the > available desktop applications. Linux is a pretty broad subject so > there's a huge range of books from which to pick. > >> >> >> Thanks >> Bernard >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor From sisson.j at gmail.com Thu Oct 5 17:02:46 2006 From: sisson.j at gmail.com (Jonathon Sisson) Date: Thu, 05 Oct 2006 10:02:46 -0500 Subject: [Tutor] from string to variable name In-Reply-To: <45250D5A.9070202@gmail.com> References: <60fae7c30610050641k4e120671q2ccfff7bfad1c1a2@mail.gmail.com> <45250D5A.9070202@gmail.com> Message-ID: <45251E96.20701@gmail.com> By "string variable that contains a name that I want to use as a variablename" do you mean something like this: myString = "rotationalSpeed" rotationalSpeed = 4500 ?? In Python a dictionary is an excellent solution to this problem. The only other way to accomplish this (to my knowledge) is in PHP (not trying to steer you away from Python, just giving some info): var myString = "rotationalSpeed"; $$myString = 4500; echo $rotationalSpeed; results in 4500. This is called "variable variables" in PHP and it can get hairy if done in a sloppy manner. I'm going to make the same recommendation that Luke did. Dictionaries are powerful structures. I recently wrote a Python script to parse an English dictionary file and build Markov models out of the words contained in the file (no, it wasn't for school, or work, or anything...I was just really, really bored). Rather than declaring an int to hold the frequency information for every letter, digram, and trigram possible (a total of 18,278 declarations), I used the letter, digram, or trigram as a key into a dictionary. Now I can do simple lookups by individual letters, digrams, or trigrams and see the frequency information without having to reference thousands of variables, and as an added side effect, only the letters, digrams, and trigrams that actually occur require storage. Jonathon Luke Paireepinart wrote: > frank h. wrote: >> hello, i have a string variable that contains a name that I want to >> use as a variablename >> putting aside questions of why I would like to do that - i this >> possible at all? >> >> so I want to assign a value to a variable whos name is available only >> as a string to me. >> that variable does not exist yet in the local namespace. >> >> from: t = "myvar" >> to: myvar = 3 >> >> is this possible? something like setattr? >> thanks for any insight you might have > I think the point of dictionaries is to get this same basic > functionality without polluting the namespaces. > You won't let us ask you 'why' you want to do this, > but I'll ask you: Why don't you want to use a dictionary? > Do you want to know if it's _Possible_ just so you'll know, > or do you actually want to use this for something? > If you just want to know if it's possible, I believe it is. > But consider: > if you don't know the variable name until runtime, > how are you going to refer to the variable later in your code? > It would be, insofar as I can tell, useless to do this. >> -frank > -Luke > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Thu Oct 5 22:51:23 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 5 Oct 2006 21:51:23 +0100 Subject: [Tutor] Book(s) about linux References: <61d0e2b40610050833gb425b8fye4bcab6219b54e03@mail.gmail.com> Message-ID: "Bernard Lebel" <3dbernard at gmail.com> wrote in message news:61d0e2b40610050833gb425b8fye4bcab6219b54e03 at mail.gmail.com... > Sorry to use this list for such an OT subject. But I want to get > hands > down with Linux, and am looking for a book or two on the subject. > > I'm looking for information about installation, configuration, > optimisation, and management of the Linux OS. Personally I think the best general guide is the O'Reilly book "Running Linux" I've bought the 1st, 2nd and 3rd editions of this book although I suspect there may be a 4th by now. I also bought Red Hat Linux unleashed and thought it a waste of money, so beware, there is junk out there as well as good stuff. Although there are differences between distros these are mainly around package formats and installation tools. I have used 4 distros over the years (since 1992) and there is little difference once it is up and running. The main things to learn are the generic Unix principles and these are common to all distros. So any good generic Unix book will be helpful. Personally I've stopped using Linux since I bought an Apple Mac and installed Cygwin on my XP box. Between them these provide all the Unix tools I need. I still have Mandrake 9 (now madriva?) installed on an old box but it hasn't spun its disks for nearly a year... HTH, Alan G. From kent37 at tds.net Fri Oct 6 00:40:54 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 05 Oct 2006 18:40:54 -0400 Subject: [Tutor] Luke, thanks a lot , here is the perfect code (as per ur suggestion) In-Reply-To: References: <452523FA.3060601@tds.net> Message-ID: <452589F6.9030500@tds.net> Asrarahmed Kadri wrote: > What is this??? I cannot understand a single character.. Explain this in > length. > > *list1 = [ [ locals()["_[1]"][i-1][j-1]+locals()["_[1]"][i-1][j] if > (j != > 0 and j != i) else 1 for j in range(i+1) ] for i in > range(num_of_lines) ] OK, I guess I asked for that. Remember, I did say this was hideous, I would never use this for anything other than a newsgroup posting. Here is your original code, more or less: list1 = [] for i in range(5): flag = 0 tmp = [] for j in range(i+1): if flag == 0 or j == i: tmp.append(1) flag = 1 else: tmp.append(list1[i-1][j-1]+list1[i-1][j]) list1.append(tmp) First let's get rid of flag, it isn't needed: list1 = [] for i in range(5): tmp = [] for j in range(i+1): if j == 0 or j == i: tmp.append(1) else: tmp.append(list1[i-1][j-1]+list1[i-1][j]) list1.append(tmp) Now replace the inner if/else with a conditional expression inside the call to append(). A conditional expression has the form (a if b else c) where b is the condition being tested and a and c are the two values. The if/else becomes this monster: tmp.append(list1[i-1][j-1]+list1[i-1][j] if (j!=0 and j!=i) else 1) I inverted the condition so I could put the more common case first. Now the whole program looks like this: list1 = [] for i in range(5): tmp = [] for j in range(i+1): tmp.append(list1[i-1][j-1]+list1[i-1][j] if (j!=0 and j!=i) else 1) list1.append(tmp) The inner loop is now ready to be replaced with a list comprehension. In general, a loop of the form tmp = [] for i in x: tmp.append(f(i)) can be replaced with the equivalent list comprehension tmp = [ f(i) for i in x ] With this change the program is down to this: list1 = [] for i in range(5): tmp = [ list1[i-1][j-1]+list1[i-1][j] if (j!=0 and j!=i) else 1 for j in range(i+1) ] list1.append(tmp) This is again in the form of a loop that can be replaced by a list comprehension, this time to create list1. The problem is that the expression in the list comprehension has to refer to the list being built, and this list is not normally available because the name has not yet been bound. This is where the cookbook hack comes in play - within a list comprehension, the list being built can be referenced as locals()["_[1]"]. Refer to the cookbook recipe for details. So within the list comp, list1[i-1][j-1] becomes locals()["_[1]"][i-1][j-1] and list1[i-1][j] becomes locals()["_[1]"][i-1][j]. This brings us to the final form: list1 = [ [ locals()["_[1]"][i-1][j-1]+locals()["_[1]"][i-1][j] if (j!=0 and j!=i) else 1 for j in range(i+1) ] for i in range(5) ] or, with slightly nicer formatting: list1 = [ [ locals()["_[1]"][i-1][j-1]+locals()["_[1]"][i-1][j] if (j!=0 and j!=i) else 1 for j in range(i+1) ] for i in range(5) ] Kent From wescpy at gmail.com Fri Oct 6 01:30:20 2006 From: wescpy at gmail.com (wesley chun) Date: Thu, 5 Oct 2006 16:30:20 -0700 Subject: [Tutor] from string to variable name In-Reply-To: <60fae7c30610050641k4e120671q2ccfff7bfad1c1a2@mail.gmail.com> References: <60fae7c30610050641k4e120671q2ccfff7bfad1c1a2@mail.gmail.com> Message-ID: <78b3a9580610051630w68e4f36ele38a04e6f52a1fd9@mail.gmail.com> On 10/5/06, frank h. wrote: > hello, i have a string variable that contains a name that I want to use as > a variablename setattr() won't work because that's only for objects which have attributes. you're talking about creating a (global or local) variable. i will also recommend you use a dictionary too... it's flexible and powerful. but if you *have* to do it, to paraphrase jonathon's example: >>> myString = 'rotationalSpeed' >>> exec '%s = 4500' % myString >>> print rotationalSpeed 4500 it's ugly but works. this example is more useful if you're planning on dynamically-generated lots of Python code to execute, not just a single assignment like this. good luck! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From dpotter at nc.rr.com Fri Oct 6 11:29:02 2006 From: dpotter at nc.rr.com (Doug Potter) Date: Fri, 06 Oct 2006 05:29:02 -0400 Subject: [Tutor] question about looping. Message-ID: <452621DE.7070200@nc.rr.com> Hi, I at trying to create a bunch of text files in a single directory on a Linux system, something like this. import os routers = ['adnc-6321', 'adnp-2341', 'adnw-2632'] for i in routers: os.system('/bin/touch' %s) % i of course this dosn't work. Is there a simple way to get this done? Thanks for your time. From ajkadri at googlemail.com Fri Oct 6 11:51:10 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Fri, 6 Oct 2006 10:51:10 +0100 Subject: [Tutor] Luke, thanks a lot , here is the perfect code (as per ur suggestion) In-Reply-To: <452589F6.9030500@tds.net> References: <452523FA.3060601@tds.net> <452589F6.9030500@tds.net> Message-ID: Thanks for the detailed explanation. I read it and understood a bit. Rest in the leisure time. Enjoy the recipes.......... Regards, Asrar On 10/5/06, Kent Johnson wrote: > > Asrarahmed Kadri wrote: > > What is this??? I cannot understand a single character.. Explain this in > > length. > > > > *list1 = [ [ locals()["_[1]"][i-1][j-1]+locals()["_[1]"][i-1][j] if > > (j != > > 0 and j != i) else 1 for j in range(i+1) ] for i in > > range(num_of_lines) ] > > OK, I guess I asked for that. Remember, I did say this was hideous, I > would never use this for anything other than a newsgroup posting. > > Here is your original code, more or less: > > list1 = [] > for i in range(5): > flag = 0 > tmp = [] > for j in range(i+1): > if flag == 0 or j == i: > tmp.append(1) > flag = 1 > else: > tmp.append(list1[i-1][j-1]+list1[i-1][j]) > list1.append(tmp) > > First let's get rid of flag, it isn't needed: > > list1 = [] > for i in range(5): > tmp = [] > for j in range(i+1): > if j == 0 or j == i: > tmp.append(1) > else: > tmp.append(list1[i-1][j-1]+list1[i-1][j]) > list1.append(tmp) > > Now replace the inner if/else with a conditional expression inside the > call to append(). A conditional expression has the form (a if b else c) > where b is the condition being tested and a and c are the two values. > The if/else becomes this monster: > > tmp.append(list1[i-1][j-1]+list1[i-1][j] if (j!=0 and j!=i) else 1) > > I inverted the condition so I could put the more common case first. Now > the whole program looks like this: > > list1 = [] > for i in range(5): > tmp = [] > for j in range(i+1): > tmp.append(list1[i-1][j-1]+list1[i-1][j] if (j!=0 and j!=i) else > 1) > list1.append(tmp) > > The inner loop is now ready to be replaced with a list comprehension. In > general, a loop of the form > > tmp = [] > for i in x: > tmp.append(f(i)) > > can be replaced with the equivalent list comprehension > > tmp = [ f(i) for i in x ] > > With this change the program is down to this: > > list1 = [] > for i in range(5): > tmp = [ list1[i-1][j-1]+list1[i-1][j] if (j!=0 and j!=i) else 1 for > j in range(i+1) ] > list1.append(tmp) > > This is again in the form of a loop that can be replaced by a list > comprehension, this time to create list1. The problem is that the > expression in the list comprehension has to refer to the list being > built, and this list is not normally available because the name has not > yet been bound. This is where the cookbook hack comes in play - within a > list comprehension, the list being built can be referenced as > locals()["_[1]"]. Refer to the cookbook recipe for details. > > So within the list comp, > list1[i-1][j-1] becomes locals()["_[1]"][i-1][j-1] and > list1[i-1][j] becomes locals()["_[1]"][i-1][j]. > > This brings us to the final form: > > list1 = [ [ locals()["_[1]"][i-1][j-1]+locals()["_[1]"][i-1][j] if (j!=0 > and j!=i) else 1 for j in range(i+1) ] for i in range(5) ] > > or, with slightly nicer formatting: > > list1 = [ > [ locals()["_[1]"][i-1][j-1]+locals()["_[1]"][i-1][j] if (j!=0 and > j!=i) else 1 > for j in range(i+1) > ] for i in range(5) > ] > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061006/23ffed6a/attachment.htm From kent37 at tds.net Fri Oct 6 11:53:44 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 06 Oct 2006 05:53:44 -0400 Subject: [Tutor] question about looping. In-Reply-To: <452621DE.7070200@nc.rr.com> References: <452621DE.7070200@nc.rr.com> Message-ID: <452627A8.7080207@tds.net> Doug Potter wrote: > Hi, > > I at trying to create a bunch of text files in a single directory on a > Linux system, > something like this. > > import os > > routers = ['adnc-6321', 'adnp-2341', 'adnw-2632'] > > for i in routers: > os.system('/bin/touch' %s) % i I think you're close, just a little out of order. Think about it this way: - first you need to create a string containing the command, using the string formatting operations. '/bin/touch %s' % i will do that. Note the %s is part of the string, and the % i is part of the formatting expression. - next you pass the formatted string to os.system(). So the whole formatting expression has to go inside the parentheses - the value of the expression is passed to os.system(): os.system('/bin/touch %s' % i) You could also do this without calling out to the system - just open a file for writing and close it again: open(i, 'w').close() Kent From ajkadri at googlemail.com Fri Oct 6 14:39:07 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Fri, 6 Oct 2006 13:39:07 +0100 Subject: [Tutor] Trying tio emulate "diff" command of UNIX - please help Message-ID: # This program emulates the diff command of UNIX import sys from stringCompare import stringcmp # this is a module which has stringcmp function that compares two strings fname1 = raw_input("Enter a file name to be read:\t") fname2 = raw_input("Enter a file name to be read:\t") fd1 = open(fname1,"r") fd2 = open(fname2,"r") done = 0 line_counter = 0 while not done: aLine1 = fd1.readline() aLine2 = fd2.readline() if (aLine1 == "" or aLine2 == ""): # test whether you have reached the end of file done = 1 else: line_counter += 1 # get the line number string1 = aLine1.split() # split the line into a list containing words string2 = aLine2.split() len1 = len(string1) len2 = len(string2) if len1 > len2: t = len1 else: t = len2 i = 0 while (i < t): cmp_res = stringcmp(string1[i],string2[i]) if cmp_res != 0: column = i done = 1 print "The difference is lies in the ", line_counter ,"line and column ", column Can someone help me with what is wrong in this code; when I am running it gets stuck. thanks in anticipation. Regards, Asrar -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061006/c754e3ba/attachment.html From Senthil_OR at Dell.com Fri Oct 6 15:11:32 2006 From: Senthil_OR at Dell.com (Senthil_OR at Dell.com) Date: Fri, 6 Oct 2006 18:41:32 +0530 Subject: [Tutor] Trying tio emulate "diff" command of UNIX - please help In-Reply-To: Message-ID: Hi, Your program does not emulate the diff command of Unix. Please do a diff in unix and experience yourselves. Where is cmp_res = stringcmp(string1[i],string2[i]) stringcmp() function written? Moreover, if you Python Documentation install (or python.org accessible) search for difflib and Differ Example. That should give you a good start. Thanks, -- Senthil ________________________________ From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Asrarahmed Kadri Sent: Friday, October 06, 2006 6:09 PM To: tutor at python.org Subject: [Tutor] Trying tio emulate "diff" command of UNIX - please help # This program emulates the diff command of UNIX import sys from stringCompare import stringcmp # this is a module which has stringcmp function that compares two strings fname1 = raw_input("Enter a file name to be read:\t") fname2 = raw_input("Enter a file name to be read:\t") fd1 = open(fname1,"r") fd2 = open(fname2,"r") done = 0 line_counter = 0 while not done: aLine1 = fd1.readline() aLine2 = fd2.readline() if (aLine1 == "" or aLine2 == ""): # test whether you have reached the end of file done = 1 else: line_counter += 1 # get the line number string1 = aLine1.split() # split the line into a list containing words string2 = aLine2.split () len1 = len(string1) len2 = len(string2) if len1 > len2: t = len1 else: t = len2 i = 0 while (i < t): cmp_res = stringcmp(string1[i],string2[i]) if cmp_res != 0: column = i done = 1 print "The difference is lies in the ", line_counter ,"line and column ", column Can someone help me with what is wrong in this code; when I am running it gets stuck. thanks in anticipation. Regards, Asrar -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061006/9fa1ae77/attachment.htm From chanson at ttsd.k12.or.us Fri Oct 6 16:38:00 2006 From: chanson at ttsd.k12.or.us (Carlos Hanson) Date: Fri, 06 Oct 2006 07:38:00 -0700 Subject: [Tutor] question about looping. In-Reply-To: <452621DE.7070200@nc.rr.com> References: <452621DE.7070200@nc.rr.com> Message-ID: <45266A48.9080306@ttsd.k12.or.us> Doug Potter wrote: > Hi, > > I at trying to create a bunch of text files in a single directory on a > Linux system, > something like this. > > import os > > routers = ['adnc-6321', 'adnp-2341', 'adnw-2632'] > > for i in routers: > os.system('/bin/touch' %s) % i > > of course this dosn't work. try using the following: for i in routers: os.system('/bin/touch %s' % i) > Is there a simple way to get this done? You can also use the builtin file object: for i in routers: f = file(i, 'w') f.close() > Thanks for your time. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Carlos Hanson Web Specialist Tigard-Tualatin School District 503.431.4053 From alan.gauld at btinternet.com Fri Oct 6 18:17:02 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 6 Oct 2006 17:17:02 +0100 Subject: [Tutor] Trying tio emulate "diff" command of UNIX - please help References: Message-ID: Some general thoughts: > import sys > from stringCompare import stringcmp # this is a module which has > stringcmp > > fname1 = raw_input("Enter a file name to be read:\t") > fname2 = raw_input("Enter a file name to be read:\t") > > fd1 = open(fname1,"r") > fd2 = open(fname2,"r") > > > done = False Use Boolean value instead of 1/0 > line_counter = 0 > while not done: > aLine1 = fd1.readline() > aLine2 = fd2.readline() > > if (aLine1 == "" or aLine2 == ""): # test whether you have > reached the > end of file > done = 1 assign directly to done, using a boolean test: done = not (aLine1 and aLine2) and miss out the if/else test. > line_counter += 1 # get the line number > string1 = aLine1.split() # split the line into a > list containing words > string2 = aLine2.split() Not sure why you are splitting the lines into words. You call them columns but they are really words of varying length. Why not just compare the lines as a whole? if aLine1 != aLine2: print "The difference lies in line", line_counter Then you can find the first characters that differ: diff = [t1==t2 for t1,t2 in zip(line1,line2)].index(False) print "and start at character", diff It's not exactly equivalent to your code of course but it seems to me to be more accurate... If you must use words, apply the spolit only when you know its needed: words1 = aLine1.split() words2 = aLine2.split() diff = [w1==w2 for w1,w2 in zip(words1,words2)].index(False) print "and start at word",diff HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From ajkadri at googlemail.com Fri Oct 6 21:27:15 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Fri, 6 Oct 2006 20:27:15 +0100 Subject: [Tutor] Trying tio emulate "diff" command of UNIX - please help In-Reply-To: References: Message-ID: Thanks Alan, but can you please explain me what this line does: diff = [t1==t2 for t1,t2 in zip(line1,line2)].index(False) On 10/6/06, Alan Gauld wrote: > > Some general thoughts: > > > import sys > > from stringCompare import stringcmp # this is a module which has > > stringcmp > > > > fname1 = raw_input("Enter a file name to be read:\t") > > fname2 = raw_input("Enter a file name to be read:\t") > > > > fd1 = open(fname1,"r") > > fd2 = open(fname2,"r") > > > > > > done = False > > Use Boolean value instead of 1/0 > > > line_counter = 0 > > while not done: > > aLine1 = fd1.readline() > > aLine2 = fd2.readline() > > > > if (aLine1 == "" or aLine2 == ""): # test whether you have > > reached the > > end of file > > done = 1 > > assign directly to done, using a boolean test: > > done = not (aLine1 and aLine2) > > and miss out the if/else test. > > > line_counter += 1 # get the line number > > string1 = aLine1.split() # split the line into a > > list containing words > > string2 = aLine2.split() > > Not sure why you are splitting the lines into words. > You call them columns but they are really words of > varying length. Why not just compare the lines as a whole? > > if aLine1 != aLine2: > print "The difference lies in line", line_counter > > Then you can find the first characters that differ: > > diff = [t1==t2 for t1,t2 in zip(line1,line2)].index(False) > print "and start at character", diff > > It's not exactly equivalent to your code of course but it seems to me > to be more accurate... > > If you must use words, apply the spolit only when you know its needed: > > words1 = aLine1.split() > words2 = aLine2.split() > diff = [w1==w2 for w1,w2 in zip(words1,words2)].index(False) > print "and start at word",diff > > HTH, > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061006/b6cce2cc/attachment.html From remailer at ka3nam.com Fri Oct 6 22:47:14 2006 From: remailer at ka3nam.com (Bennett, Joe) Date: Fri, 06 Oct 2006 13:47:14 -0700 Subject: [Tutor] Share variables between py scripts Message-ID: <20061006134713.45be410680a12a4c1a2b20f2b7c6db34.1f0d5d97d3.wbe@email.secureserver.net> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061006/7343ad6b/attachment.html From ajkadri at googlemail.com Sat Oct 7 00:24:01 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Fri, 6 Oct 2006 23:24:01 +0100 Subject: [Tutor] Help: how to detect which key is pressed Message-ID: I am writing a simple program and in that I want to add some sort of interactiveness. I have designed a menu which gives the user an option to select one out of the following four keys: d, l, n or e. Can any one tell me how to determine which key has been pressed by the user. Thanks. Regards, Asrar -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061006/4b0457aa/attachment.htm From eric at ericwalstad.com Sat Oct 7 01:25:37 2006 From: eric at ericwalstad.com (Eric Walstad) Date: Fri, 06 Oct 2006 16:25:37 -0700 Subject: [Tutor] Share variables between py scripts In-Reply-To: <20061006134713.45be410680a12a4c1a2b20f2b7c6db34.1f0d5d97d3.wbe@email.secureserver.net> References: <20061006134713.45be410680a12a4c1a2b20f2b7c6db34.1f0d5d97d3.wbe@email.secureserver.net> Message-ID: <4526E5F1.6050907@ericwalstad.com> Bennett, Joe wrote: > Can anyone direct me to some documentation on how to take variables from > one py script, execute and pass them to another script? Then I need to > get data back from the executed script? I've been searching Google and I > see information, but I am in need of some examples... > > > Thanks! > > > -Joe Hi Joe, If possible, just "run" your script (B) from within the second script (A). I'd rephrase that as "in module a, import and use variables, functions and/or classes from module b": ##### Script B (script_b.py) ##### my_b_variable = '' def my_b_function(var): return "Hello World: %s" % var class MyBClass: # an empty class pass #### End Script B ##### ##### Script A (script_a.py) ##### from script_b import my_b_variable, my_b_function, MyBClass def my_a_function(var): my_a_variable = MyBClass() # or my_a_variable = my_b_variable # or my_a_variable = my_b_function(var) # etc return my_A_variable if __name__ == '__main__': # this A script is being called from the command line # do whatever you like in here, like run a function: import sys command_line_arg = sys.argv[1] print my_A_function(command_line_arg) #### End Script A ##### $ python script_a.py foo Hello World: foo I hope that wasn't too remedial for you and that it's helpful. Search the docs for 'functions' and 'import' for more info. Best, Eric. From tpc247 at gmail.com Sat Oct 7 03:44:01 2006 From: tpc247 at gmail.com (tpc247 at gmail.com) Date: Fri, 6 Oct 2006 18:44:01 -0700 Subject: [Tutor] when I create an instance of a class that inherits from Python dictionary, my data disappears Message-ID: hi all, I would like to create a class that specializes Python dictionary. I would like an instance of this class to store objects representing html form data, and I would like to have an instance of this Data_Set class be able to use the Python dictionary method pop to remove objects as I see fit. I defined the following: class Data_Set(dict): def __init__(self, dict_of_datum_objects, required=None): self.keys = dict_of_datum_objects.keys self.values = dict_of_datum_objects.values self.required = required For some reason, whenever I create an instance of this class with data, all I get is an empty dictionary. As soon as I redefine my class to no longer inherit from Python dictionary, then I get expected behavior, but now I don't have benefit of Python dictionary methods such as pop and has_key: sdso = Data_Set({'full_name':'full_name_obj', 'address_line_1':'address_line_1_obj'}) >>> sdso {} >>> class Data_Set: def __init__(self, dict_of_datum, required=None): self.keys = dict_of_datum.keys self.values = dict_of_datum.values self.items = dict_of_datum.items self.required = required >>> sdso = Data_Set({'full_name':'full_name_obj', 'address_line_1':'address_line_1_obj'}) >>> sdso <__main__.Data_Set instance at 0x419690ac> >>> sdso.keys() ['full_name', 'address_line_1'] >>> sdso.pop('full_name') Traceback (most recent call last): File "", line 1, in -toplevel- sdso.pop('full_name') AttributeError: Data_Set instance has no attribute 'pop' Am I doing something wrong ? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061006/69644c9f/attachment.htm From alan.gauld at btinternet.com Sat Oct 7 00:21:09 2006 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Fri, 6 Oct 2006 23:21:09 +0100 (BST) Subject: [Tutor] Trying tio emulate "diff" command of UNIX - please help In-Reply-To: Message-ID: <20061006222109.23737.qmail@web86105.mail.ird.yahoo.com> > Thanks Alan, but can you please explain me what this line > does: > diff = [t1==t2 for t1,t2 in zip(line1,line2)].index(False) > I'll unfold it somewhat: mix = zip(a,b) produces a list of tuples: [(a1,b1)(a2,b2),(a3,b3)] t1 == t2 produces a boolean result either True or False for t1,t2 in mix unpacks each tuple from the zipped list Putting it back together in long hand mix = zip(aLine1,aLine2) results = [] for t1,t2 in mix: if t1 == t2: results.append(True) else: results.append(False) diff = results.index(False) finds the index of the first instance of False in results Lets look at it as a comprehension again: diff = [t1==t2 for t1,t2 in zip(aLine1,aLine2)].index(False) Does that make sense now? Can you see the various bits at work? Alan G. ___________________________________________________________ To help you stay safe and secure online, we've developed the all new Yahoo! Security Centre. http://uk.security.yahoo.com From rabidpoobear at gmail.com Sat Oct 7 04:39:26 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 06 Oct 2006 21:39:26 -0500 Subject: [Tutor] Help: how to detect which key is pressed In-Reply-To: References: Message-ID: <4527135E.4040407@gmail.com> Asrarahmed Kadri wrote: > > > I am writing a simple program and in that I want to add some sort of > interactiveness. > I have designed a menu which gives the user an option to select one > out of the following four keys: d, l, n or e. > Can any one tell me how to determine which key has been pressed by the > user. Asrarahmed: Please refer to: http://www.freenetpages.co.uk/hp/alan.gauld/ for information on how to do this. specifically, http://www.freenetpages.co.uk/hp/alan.gauld/tutinput.htm You should work through this tutorial, not just the specific section on User Input, but the whole site. It will cover the most common questions that people new to Python have. Good Luck, -Luke From bgailer at alum.rpi.edu Sat Oct 7 06:03:20 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri, 06 Oct 2006 21:03:20 -0700 Subject: [Tutor] when I create an instance of a class that inherits from Python dictionary, my data disappears In-Reply-To: References: Message-ID: <45272708.1090801@alum.rpi.edu> tpc247 at gmail.com wrote: > hi all, I would like to create a class that specializes Python > dictionary. I would like an instance of this class to store objects > representing html form data, and I would like to have an instance of > this Data_Set class be able to use the Python dictionary method pop to > remove objects as I see fit. I defined the following: > > class Data_Set(dict): > def __init__(self, dict_of_datum_objects, required=None): > self.keys = dict_of_datum_objects.keys > self.values = dict_of_datum_objects.values > self.required = required > > For some reason, whenever I create an instance of this class with > data, all I get is an empty dictionary. As soon as I redefine my > class to no longer inherit from Python dictionary, then I get expected > behavior, but now I don't have benefit of Python dictionary methods > such as pop and has_key: > > sdso = Data_Set({'full_name':'full_name_obj', > 'address_line_1':'address_line_1_obj'}) > >>> sdso > {} > >>> class Data_Set: > def __init__(self, dict_of_datum, required=None): > self.keys = dict_of_datum.keys > self.values = dict_of_datum.values > self.items = dict_of_datum.items > self.required = required > > > >>> sdso = Data_Set({'full_name':'full_name_obj', > 'address_line_1':'address_line_1_obj'}) > >>> sdso > <__main__.Data_Set instance at 0x419690ac> > >>> sdso.keys() > ['full_name', 'address_line_1'] > >>> sdso.pop('full_name') > > Traceback (most recent call last): > File "", line 1, in -toplevel- > sdso.pop('full_name') > AttributeError: Data_Set instance has no attribute 'pop' > > Am I doing something wrong ? Err, yes. You are assuming that assigning to self.keys and self.values creates dictionary entries. All that actually does is assign the 2 lists to 2 attributes. Try instead self.update(dict_of_datum_objects). -- Bob Gailer just up the road in El Cerrito 510-978-4454 From contact at endarion.com Sat Oct 7 09:33:27 2006 From: contact at endarion.com (Michael Shulman) Date: Sat, 07 Oct 2006 03:33:27 -0400 Subject: [Tutor] Point in polygon intro please~! Message-ID: <45275847.2090004@endarion.com> Hello, I'm very new to both python and OpenGL, but I'm catching on pretty quick, and trying to make a little game. I'm stuck on being able to do this point-in-polygon test though. Everyone seems to say that I should create a ray and see how many sides of a polygon it intersects, (even vs odd) but I have no idea how to go about setting this up. I'm trying to have a 5-point polygon made from a list of trailing mouse positions (len(mouselist)=5, obviously), and checking to see if a bunch of points in a separate list (len(pointlist)=20) ever fall within the resultant polygon. The lists and program are all setup, but too large to copy here. It all works by itself though, so I just need to find out how to do this test. Any help on how to set something like this up would be extremely appreciated. Thank you very much for your time, ~Mike From kent37 at tds.net Sat Oct 7 14:46:07 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 07 Oct 2006 08:46:07 -0400 Subject: [Tutor] when I create an instance of a class that inherits from Python dictionary, my data disappears In-Reply-To: <45272708.1090801@alum.rpi.edu> References: <45272708.1090801@alum.rpi.edu> Message-ID: <4527A18F.2070801@tds.net> Bob Gailer wrote: > tpc247 at gmail.com wrote: >> hi all, I would like to create a class that specializes Python >> dictionary. I would like an instance of this class to store objects >> representing html form data, and I would like to have an instance of >> this Data_Set class be able to use the Python dictionary method pop to >> remove objects as I see fit. I defined the following: >> >> class Data_Set(dict): >> def __init__(self, dict_of_datum_objects, required=None): >> self.keys = dict_of_datum_objects.keys >> self.values = dict_of_datum_objects.values >> self.required = required >> >> For some reason, whenever I create an instance of this class with >> data, all I get is an empty dictionary. >> Am I doing something wrong ? > Err, yes. You are assuming that assigning to self.keys and self.values > creates dictionary entries. All that actually does is assign the 2 lists > to 2 attributes. > > Try instead self.update(dict_of_datum_objects). In general, when you create a subclass, the subclass __init__() method should call the base class __init__(). Otherwise the base class is not initialized. That is what you see - you get an empty dict. The syntax for the call to the base class __init__() is a little strange, it looks like this: base.__init__(self, args) where base is the name of the base class and args are the arguments for the base class __init__() method. As Bob points out, you are also making unwarranted assumptions about the way dict stores its data. Try this: def __init__(self, dict_of_datum_objects, required=None): dict.__init__(self, dict_of_datum_objects) self.required = required Kent From picioslug at gmail.com Sat Oct 7 15:07:36 2006 From: picioslug at gmail.com (Picio) Date: Sat, 7 Oct 2006 15:07:36 +0200 Subject: [Tutor] python RMI Message-ID: <825bef0c0610070607w5310f46ahceb9d8c277c7333d@mail.gmail.com> Salve, dovrei usare python per due progettini universitari, su RMI e l'altro sui Web Services. Ho notato che esiste PyRO, preferirei per? sentire voi sull'argomento: cosa uso per l'RMI (esiste qualche libreria,modulo....) cosa uso per i Web Services Accetto anche suggerimenti tipo "dai un'occhiata qui.." ovvero verso fonti di documentazione. Grazie anticipatamente. Daniele From kent37 at tds.net Sat Oct 7 15:23:01 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 07 Oct 2006 09:23:01 -0400 Subject: [Tutor] Point in polygon intro please~! In-Reply-To: <45275847.2090004@endarion.com> References: <45275847.2090004@endarion.com> Message-ID: <4527AA35.4030000@tds.net> Michael Shulman wrote: > Hello, I'm very new to both python and OpenGL, but I'm catching on > pretty quick, > and trying to make a little game. I'm stuck on being able to do this > point-in-polygon test though. > Everyone seems to say that I should create a ray and see how many sides > of a polygon it intersects, (even vs odd) > but I have no idea how to go about setting this up. Googling 'python point polygon' finds quite a few useful pages including this Python implementation: http://www.ariel.com.au/a/python-point-int-poly.html Other links of interest: http://www.faqs.org/faqs/graphics/algorithms-faq/ see 2.03 http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html Kent From alan.gauld at btinternet.com Sat Oct 7 18:21:04 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 7 Oct 2006 17:21:04 +0100 Subject: [Tutor] python RMI References: <825bef0c0610070607w5310f46ahceb9d8c277c7333d@mail.gmail.com> Message-ID: Non parlo l'italiano in modo da l'per mezzo dei mezzi di traduzione di Google. Il Python offre parecchi attrezzi per i servizi di fotoricettore compreso sostegno XML/RPC e SOAP http://docs.python.org/lib/module-xmlrpclib.html http://soapy.sourceforge.net/ Potete essere pi? specifici circa di che cosa avete bisogno? Potete usare la documentazione inglese? HTH PS. Any Italian speakers on the list who can cover this? -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld/italian/ "Picio" wrote in message news:825bef0c0610070607w5310f46ahceb9d8c277c7333d at mail.gmail.com... Salve, dovrei usare python per due progettini universitari, su RMI e l'altro sui Web Services. Ho notato che esiste PyRO, preferirei per? sentire voi sull'argomento: cosa uso per l'RMI (esiste qualche libreria,modulo....) cosa uso per i Web Services Accetto anche suggerimenti tipo "dai un'occhiata qui.." ovvero verso fonti di documentazione. Grazie anticipatamente. Daniele _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From kent37 at tds.net Sat Oct 7 18:56:01 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 07 Oct 2006 12:56:01 -0400 Subject: [Tutor] python RMI In-Reply-To: <825bef0c0610070607w5310f46ahceb9d8c277c7333d@mail.gmail.com> References: <825bef0c0610070607w5310f46ahceb9d8c277c7333d@mail.gmail.com> Message-ID: <4527DC21.9060906@tds.net> Picio wrote: > Salve, > dovrei usare python per due progettini universitari, su RMI e l'altro > sui Web Services. You might have better luck asking in it.comp.lang.python: http://groups.google.com/group/it.comp.lang.python Kent From mc_anjo at tamu.edu Sat Oct 7 16:05:45 2006 From: mc_anjo at tamu.edu (Chris Smith) Date: Sat, 07 Oct 2006 09:05:45 -0500 Subject: [Tutor] error help Message-ID: I'm writing a numerical program for an assignment at school. So the code of my program isn't too long I've coded the formulas, which are rather long, as funcions. However when I try to run my program I keep getting one of two errors. The first happens when I do a test run of my code with the test portion of the code at the bottom. It keeps popping up an error message that says that my import statement is spaced incorrectly. It's not supposed to be indented at all and I can't figure out why it's popping up at all. If I try moving the test portion of the code up to the top it gives me "Token Error: EOF in multi-line statement". I don't understand this one because I try to have the last line be the one with the return statement of my last function and when the error happens it adds a line to my code and the error pops up. Can anyone tell me why I'm having these error or what I can do to get around them? Chris Smith -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: elen636_hw4_6b.py Url: http://mail.python.org/pipermail/tutor/attachments/20061007/c1fb4b2a/attachment.asc From mail.roma1 at gmail.com Sat Oct 7 23:23:08 2006 From: mail.roma1 at gmail.com (Ivan Furone) Date: Sat, 7 Oct 2006 22:23:08 +0100 Subject: [Tutor] python RMI In-Reply-To: References: <825bef0c0610070607w5310f46ahceb9d8c277c7333d@mail.gmail.com> Message-ID: <6122a57a0610071423w36d0cb28l4f86146dbd157065@mail.gmail.com> Il 07/10/06, Alan Gauld ha scritto: > > > PS. Any Italian speakers on the list who can cover this? I think I can as far it's possible,Alan! :-) "Picio" wrote in message > news:825bef0c0610070607w5310f46ahceb9d8c277c7333d at mail.gmail.com... > Salve, > dovrei usare python per due progettini universitari, su RMI e l'altro > sui Web Services. > Ho notato che esiste PyRO, preferirei per? sentire voi sull'argomento: > > cosa uso per l'RMI (esiste qualche libreria,modulo....) > cosa uso per i Web Services Ciao, Per quanto riguarda l'RMI vale la pena di dare un'occhiata a quest'esempio,anche se in inglese in quanto il codice e'di per se abbastanza comprensibile: http://www.daimi.au.dk/~mailund/scripting2005/lecture-notes/rmi.html Per quanto riguarda i web services,e'impossibile darti una risposta precisa senza poter conoscere i servizi che devi (o dovresti) utilizzare; prova a girare nella standard library,magari a guardare XML-RPC come altri ti hanno gia'detto;comunque,se cerchi qualcosa di piu'dedicato usa Twisted che e'sicuramente l'eccellenza nel campo della programmazione di rete in Python per completezza e maturita'del codice. Mentre per eventuali ritocchi e implementazione di particolari funzionalita'di basso livello esiste dpkt.. Fai la tua scelta,spero di essere stato esaustivo. > ______________________________ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061007/8c5ff700/attachment.htm From geoframer at gmail.com Sat Oct 7 23:35:05 2006 From: geoframer at gmail.com (Geoframer) Date: Sat, 7 Oct 2006 23:35:05 +0200 Subject: [Tutor] Can my code be optimized any further (speed-wise)? Message-ID: <5d8e35a70610071435t6b768925t35e00fb74b11d42d@mail.gmail.com> Hi everyone, The last few days i've been learning python and have been doing this by trying to solve problems for a programming competition. One particular problem is bugging me. I have already solved it but my solution does not compute in the set time-condition. I know for a fact that this particular problem is solvable in the time-limit using Python, so i was wondering if my solution is maybe inefficitient code-wise. If my code can't be optimized for speed any more i must be missing something and should labor hard to find a new algorithm ;-). The problem is to compute the number of trailing zero's in factorials (n! = 1*2*3*4*.......*n). with n <= 1000000000 My solution is as follows (a = times to read a number (b) to process) : --------------------------------------------------------------------------- a = input() for i in range(a): lst = (5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125, 9765625, 48828125, 244140625) ans = 0 b = input() for i in lst: if i <= b: ans += b//i print ans ---------------------------------------------------------------------------- Please, if you have suggestions to improve the speed of this algorithm give an argumentation as to why a certain something is faster. That would allow me to learn to program faster algorithms in Python al together instead of just in this problem. Kind regards - Geofram P.s. I know python is probably not the best language for these kinds of problems (I can code it in C or C++), it just bugs me that it's possible and my solution is failing... ;-) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061007/3ecd30c3/attachment.html From geoframer at gmail.com Sat Oct 7 23:53:39 2006 From: geoframer at gmail.com (Geoframer) Date: Sat, 7 Oct 2006 23:53:39 +0200 Subject: [Tutor] error help In-Reply-To: References: Message-ID: <5d8e35a70610071453i365e03dh89e27be90ba991a7@mail.gmail.com> The main problem from what i can tell is that the number of '(' and ')' you use in declarations (and maybe even functions) are not correct. Take for instance : u0prime = beta*(sqrt(d**2 +(h +length1)**2) - h +length1)) You open 3 '(' and close 4 ')' . The problem is not the little test code at the end (as you illustrated yourself by moving it up and getting a different error). The "Token Error: EOF in multi-line statement" usually means you made an error using too many or too little ()'s. I suggest carefully re-examining your code and check if everything is entered correctly using the right amount of ()'s ;-) Hope this helps some. Ciao - Geofram On 10/7/06, Chris Smith wrote: > > I'm writing a numerical program for an assignment at school. So the code > of my program isn't too long I've coded the formulas, which are rather > long, as funcions. However when I try to run my program I keep getting > one of two errors. The first happens when I do a test run of my code > with the test portion of the code at the bottom. It keeps popping up an > error message that says that my import statement is spaced incorrectly. > It's not supposed to be indented at all and I can't figure out why it's > popping up at all. If I try moving the test portion of the code up to > the top it gives me "Token Error: EOF in multi-line statement". I don't > understand this one because I try to have the last line be the one with > the return statement of my last function and when the error happens it > adds a line to my code and the error pops up. > > Can anyone tell me why I'm having these error or what I can do to get > around them? > > Chris Smith > > > #Functions for Numerical Program > #---------------------------------- > ### The sine and cosine integrals are taken from Abramowitz and Stegun. > ### Only use the first 6 terms of the summation in the sine and cosine > ### integrals. > > > def Si(x): > sine_integral = x - x**3/18. + x**5/600. - x**7/35280. \ > + x**9/3265920. + x**11/439084800. > return sine_integral > > def Ci(x): > # Euler's constant > Euler_const = 0.5772156649 > > cosine_integral = Euler_const + log(x) - x**2/4. + x**4/96. \ > - x**6/4320. + x**8/322560. + x**10/36288000 > return cosine_integral > > > def Mutual_impedance(length1, length2, stagger, d): > """ > Mutual impedance formulas for Parallel in Echelon Configuration > The formulas are taken from a paper by Howard King, "Mutual Impedance > of Unequal Length Antennas in Echelon" > > NOTE: all measurements should be entered in wavelengths > """ > > # stagger (this is the vertical separation between antenna centers) > # d (this is the horizontal separation between the antennas) > # length1 and length2 (this is the half length of the antennas) > > # vertical separation between center of antenna 1 and bottom of > antenna 2 > h = stagger - length2 > > # wave propagation constant and eta > beta = 2*pi > > # formulas to put into mutual impedance equation > u0 = beta*(sqrt(d**2 +(h -length1)**2) +(h -length1)) > v0 = beta*(sqrt(d**2 +(h -length1)**2) -(h -length1)) > u0prime = beta*(sqrt(d**2 +(h +length1)**2) - h +length1)) > v0prime = beta*(sqrt(d**2 +(h +length1)**2) +(h +length1)) > u1 = beta*(sqrt(d**2 +(h -length1 +length2)**2) +(h -length1 > +length2)) > v1 = beta*(sqrt(d**2 +(h -length1 +length2)**2) - h -length1 > +length2)) > u2 = beta*(sqrt(d**2 +(h +length1 +length2)**2) -(h +length1 > +length2)) > v2 = beta*(sqrt(d**2 +(h +length1 +length2)**2) +(h +length1 > +length2)) > u3 = beta*(sqrt(d**2 +(h -length1 +2*length2)**2) +(h -length1 > +2*length2)) > v3 = beta*(sqrt(d**2 +(h -length1 +2*length2)**2) -(h -length1 > +2*length2)) > u4 = beta*(sqrt(d**2 +(h +length1 +2*length2)**2) -(h +length1 > +2*length2)) > v4 = beta*(sqrt(d**2 +(h +length1 +2*length2)**2) +(h +length1 > +2*length2)) > w1 = beta*(sqrt(d**2 +h**2) -h) > y1 = beta*(sqrt(d**2 +h**2) +h) > w2 = beta*(sqrt(d**2 +(h +length2)**2) -(h +length2)) > y2 = beta*(sqrt(d**2 +(h +length2)**2) +(h +length2)) > w3 = beta*(sqrt(d**2 +(h +2*length2)**2) -(h +2*length2)) > y3 = beta*(sqrt(d**2 +(h +2*length2)**2) +(h +2*length2)) > > R12 = 15*(cos(beta*(length1 - h))*(Ci(u0) +Ci(v0) -Ci(u1) -Ci(v1)) \ > +sin(beta*(length1 - h))*(-Si(u0) +Si(v0) +Si(u1) -Si(v1)) \ > +cos(beta*(length1 + h))*(Ci(u0prime) +Ci(v0prime) -Ci(u2) > -Ci(v2)) \ > +sin(beta*(length1 +h))*(-Si(u0prime) +Si(v0prime) +Si(u2) > -Si(v2)) \ > +cos(beta*(length1 -2*length2 -h))*(-Ci(u1) -Ci(v1) +Ci(u3) > +Ci(v3)) \ > +sin(beta*(length1 -2*length2 -h))*(Si(u1) -Si(v1) -Si(u3) > +Si(v3)) \ > +cos(beta*(length1 +2*length2 +h))*(-Ci(u2) -Ci(v2) +Ci(u4) > +Ci(v4)) \ > +sin(beta*(length1 +2*length2 +h))*(Si(u2) -Si(v2) -Si(u4) > +Si(v4)) \ > +2*cos(beta*length1)*cos(beta*h)*(-Ci(w1) -Ci(y1) +Ci(w2) > +Ci(y2)) \ > +2*cos(beta*length1)*sin(beta*h)*(Si(w1) -Si(y1) -Si(w2) > +Si(y2)) \ > +2*cos(beta*length1)*cos(beta*(2*length2 +h))*(Ci(w2) > +Ci(y2) -Ci(w3) -Ci(y3)) \ > +2*cos(beta*length1)*sin(beta*h*(2*length2 +h))*(-Si(w2) > +Si(y2) -Si(w3) +Si(y3))) > > X12 = 15*(cos(beta*(length1 - h))*(-Si(u0) -Si(v0) +Si(u1) +Si(v1)) \ > +sin(beta*(length1 - h))*(-Ci(u0) +Ci(v0) +Ci(u1) -Ci(v1)) \ > +cos(beta*(length1 + h))*(-Si(u0prime) -Si(v0prime) +Si(u2) > +Si(v2)) \ > +sin(beta*(length1 +h))*(-Ci(u0prime) +Ci(v0prime) +Ci(u2) > -Ci(v2)) \ > +cos(beta*(length1 -2*length2 -h))*(Si(u1) +Si(v1) -Si(u3) > -Si(v3)) \ > +sin(beta*(length1 -2*length2 -h))*(Ci(u1) -Ci(v1) -Ci(u3) > +Ci(v3)) \ > +cos(beta*(length1 +2*length2 +h))*(Si(u2) +Si(v2) -Si(u4) > -Si(v4)) \ > +sin(beta*(length1 +2*length2 +h))*(Ci(u2) -Ci(v2) -Ci(u4) > +Ci(v4)) \ > +2*cos(beta*length1)*cos(beta*h)*(Si(w1) +Si(y1) -Si(w2) > -Si(y2)) \ > +2*cos(beta*length1)*sin(beta*h)*(Ci(w1) -Ci(y1) -Ci(w2) > +Ci(y2)) \ > +2*cos(beta*length1)*cos(beta*(2*length2 +h))*(-Si(w2) > -Si(y2) +Si(w3) +Si(y3)) \ > +2*cos(beta*length1)*sin(beta*h*(2*length2 +h))*(-Ci(w2) > +Ci(y2) -Ci(w3) +Ci(y3))) > > mut_imp = complex(R12, X12) > return mut_imp > > from math import * > length1 = 0.45 > length2 = 0.65 > stagger = 0.1 > d = 0.2 > > impedance = Mutual_impedance(length1, length2, stagger, d) > print impedance > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061007/c94bb8bd/attachment.htm From mc_anjo at tamu.edu Sun Oct 8 00:01:25 2006 From: mc_anjo at tamu.edu (Chris Smith) Date: Sat, 07 Oct 2006 17:01:25 -0500 Subject: [Tutor] error help In-Reply-To: <5d8e35a70610071453i365e03dh89e27be90ba991a7@mail.gmail.com> References: <5d8e35a70610071453i365e03dh89e27be90ba991a7@mail.gmail.com> Message-ID: Thanks for the help. That was the problem. I guess I'd been looking at it so long I missed that. The error message wasn't helping me either. Chris Smith Geoframer wrote: > The main problem from what i can tell is that the number of '(' and ')' > you use in declarations (and maybe even functions) are not correct. > > Take for instance : > > u0prime = beta*(sqrt(d**2 +(h +length1)**2) - h +length1)) > > You open 3 '(' and close 4 ')' . > > The problem is not the little test code at the end (as you illustrated > yourself by moving it up and getting a different error). > The "Token Error: EOF in multi-line statement" usually means you made an > error using too many or too little ()'s. > > I suggest carefully re-examining your code and check if everything is > entered correctly using the right amount of ()'s ;-) > > Hope this helps some. > > Ciao - Geofram > > On 10/7/06, *Chris Smith* > > wrote: > > I'm writing a numerical program for an assignment at school. So the code > of my program isn't too long I've coded the formulas, which are rather > long, as funcions. However when I try to run my program I keep getting > one of two errors. The first happens when I do a test run of my code > with the test portion of the code at the bottom. It keeps popping up an > error message that says that my import statement is spaced incorrectly. > It's not supposed to be indented at all and I can't figure out why it's > popping up at all. If I try moving the test portion of the code up to > the top it gives me "Token Error: EOF in multi-line statement". I don't > understand this one because I try to have the last line be the one with > the return statement of my last function and when the error happens it > adds a line to my code and the error pops up. > > Can anyone tell me why I'm having these error or what I can do to get > around them? > > Chris Smith > > > #Functions for Numerical Program > #---------------------------------- > ### The sine and cosine integrals are taken from Abramowitz and Stegun. > ### Only use the first 6 terms of the summation in the sine and cosine > ### integrals. > > > def Si(x): > sine_integral = x - x**3/18. + x**5/600. - x**7/35280. \ > + x**9/3265920. + x**11/439084800. > return sine_integral > > def Ci(x): > # Euler's constant > Euler_const = 0.5772156649 > > cosine_integral = Euler_const + log(x) - x**2/4. + x**4/96. \ > - x**6/4320. + x**8/322560. + x**10/36288000 > return cosine_integral > > > def Mutual_impedance(length1, length2, stagger, d): > """ > Mutual impedance formulas for Parallel in Echelon Configuration > The formulas are taken from a paper by Howard King, "Mutual > Impedance > of Unequal Length Antennas in Echelon" > > NOTE: all measurements should be entered in wavelengths > """ > > # stagger (this is the vertical separation between antenna centers) > # d (this is the horizontal separation between the antennas) > # length1 and length2 (this is the half length of the antennas) > > # vertical separation between center of antenna 1 and bottom of > antenna 2 > h = stagger - length2 > > # wave propagation constant and eta > beta = 2*pi > > # formulas to put into mutual impedance equation > u0 = beta*(sqrt(d**2 +(h -length1)**2) +(h -length1)) > v0 = beta*(sqrt(d**2 +(h -length1)**2) -(h -length1)) > u0prime = beta*(sqrt(d**2 +(h +length1)**2) - h +length1)) > v0prime = beta*(sqrt(d**2 +(h +length1)**2) +(h +length1)) > u1 = beta*(sqrt(d**2 +(h -length1 +length2)**2) +(h > -length1 +length2)) > v1 = beta*(sqrt(d**2 +(h -length1 +length2)**2) - h > -length1 +length2)) > u2 = beta*(sqrt(d**2 +(h +length1 +length2)**2) -(h > +length1 +length2)) > v2 = beta*(sqrt(d**2 +(h +length1 +length2)**2) +(h > +length1 +length2)) > u3 = beta*(sqrt(d**2 +(h -length1 +2*length2)**2) +(h > -length1 +2*length2)) > v3 = beta*(sqrt(d**2 +(h -length1 +2*length2)**2) -(h > -length1 +2*length2)) > u4 = beta*(sqrt(d**2 +(h +length1 +2*length2)**2) -(h > +length1 +2*length2)) > v4 = beta*(sqrt(d**2 +(h +length1 +2*length2)**2) +(h > +length1 +2*length2)) > w1 = beta*(sqrt(d**2 +h**2) -h) > y1 = beta*(sqrt(d**2 +h**2) +h) > w2 = beta*(sqrt(d**2 +(h +length2)**2) -(h +length2)) > y2 = beta*(sqrt(d**2 +(h +length2)**2) +(h +length2)) > w3 = beta*(sqrt(d**2 +(h +2*length2)**2) -(h +2*length2)) > y3 = beta*(sqrt(d**2 +(h +2*length2)**2) +(h +2*length2)) > > R12 = 15*(cos(beta*(length1 - h))*(Ci(u0) +Ci(v0) -Ci(u1) > -Ci(v1)) \ > +sin(beta*(length1 - h))*(-Si(u0) +Si(v0) +Si(u1) > -Si(v1)) \ > +cos(beta*(length1 + h))*(Ci(u0prime) +Ci(v0prime) > -Ci(u2) -Ci(v2)) \ > +sin(beta*(length1 +h))*(-Si(u0prime) +Si(v0prime) > +Si(u2) -Si(v2)) \ > +cos(beta*(length1 -2*length2 -h))*(-Ci(u1) -Ci(v1) > +Ci(u3) +Ci(v3)) \ > +sin(beta*(length1 -2*length2 -h))*(Si(u1) -Si(v1) > -Si(u3) +Si(v3)) \ > +cos(beta*(length1 +2*length2 +h))*(-Ci(u2) -Ci(v2) > +Ci(u4) +Ci(v4)) \ > +sin(beta*(length1 +2*length2 +h))*(Si(u2) -Si(v2) > -Si(u4) +Si(v4)) \ > +2*cos(beta*length1)*cos(beta*h)*(-Ci(w1) -Ci(y1) > +Ci(w2) +Ci(y2)) \ > +2*cos(beta*length1)*sin(beta*h)*(Si(w1) -Si(y1) > -Si(w2) +Si(y2)) \ > +2*cos(beta*length1)*cos(beta*(2*length2 +h))*(Ci(w2) > +Ci(y2) -Ci(w3) -Ci(y3)) \ > +2*cos(beta*length1)*sin(beta*h*(2*length2 > +h))*(-Si(w2) +Si(y2) -Si(w3) +Si(y3))) > > X12 = 15*(cos(beta*(length1 - h))*(-Si(u0) -Si(v0) +Si(u1) > +Si(v1)) \ > +sin(beta*(length1 - h))*(-Ci(u0) +Ci(v0) +Ci(u1) > -Ci(v1)) \ > +cos(beta*(length1 + h))*(-Si(u0prime) -Si(v0prime) > +Si(u2) +Si(v2)) \ > +sin(beta*(length1 +h))*(-Ci(u0prime) +Ci(v0prime) > +Ci(u2) -Ci(v2)) \ > +cos(beta*(length1 -2*length2 -h))*(Si(u1) +Si(v1) > -Si(u3) -Si(v3)) \ > +sin(beta*(length1 -2*length2 -h))*(Ci(u1) -Ci(v1) > -Ci(u3) +Ci(v3)) \ > +cos(beta*(length1 +2*length2 +h))*(Si(u2) +Si(v2) > -Si(u4) -Si(v4)) \ > +sin(beta*(length1 +2*length2 +h))*(Ci(u2) -Ci(v2) > -Ci(u4) +Ci(v4)) \ > +2*cos(beta*length1)*cos(beta*h)*(Si(w1) +Si(y1) > -Si(w2) -Si(y2)) \ > +2*cos(beta*length1)*sin(beta*h)*(Ci(w1) -Ci(y1) > -Ci(w2) +Ci(y2)) \ > +2*cos(beta*length1)*cos(beta*(2*length2 +h))*(-Si(w2) > -Si(y2) +Si(w3) +Si(y3)) \ > +2*cos(beta*length1)*sin(beta*h*(2*length2 > +h))*(-Ci(w2) +Ci(y2) -Ci(w3) +Ci(y3))) > > mut_imp = complex(R12, X12) > return mut_imp > > from math import * > length1 = 0.45 > length2 = 0.65 > stagger = 0.1 > d = 0.2 > > impedance = Mutual_impedance(length1, length2, stagger, d) > print impedance > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Sun Oct 8 01:33:35 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 8 Oct 2006 00:33:35 +0100 Subject: [Tutor] Can my code be optimized any further (speed-wise)? References: <5d8e35a70610071435t6b768925t35e00fb74b11d42d@mail.gmail.com> Message-ID: Hi, Maybe its just me but I didn't understand what you are trying to do... > The problem is to compute the number of trailing zero's in > factorials (n! = > 1*2*3*4*.......*n). with n <= 1000000000 > > My solution is as follows (a = times to read a number (b) to > process) : > > --------------------------------------------------------------------------- > > a = input() what does a represent? Its usually worth putting a prompt string into input() - and raw_input() - just as documentation if nothing else! And maybe a descriptive variable name if appropriate. > for i in range(a): > lst = (5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125, > 9765625, > 48828125, 244140625) None of these have any trailing zeros so far as I can tell? What answer are you expecting from this function? > ans = 0 > b = input() similarly, what is b supposed to be? > for i in lst: And here you are throwing away the i from the outer loop > if i <= b: > ans += b//i And now you divide some arbitrary input value by each factorial in turn and sum the results? > print ans > Please, if you have suggestions to improve the speed of this > algorithm give > an argumentation as to why a certain something is faster. I nbeed to understand what you are tryying to do first, its not making much sense at the moment. (But it is after midnight! :-) > P.s. I know python is probably not the best language for these kinds > of > problems (I can code it in C or C++), it just bugs me that it's > possible > and my solution is failing... ;-) Actually it looks like exactly what I would use Python for rarther than C/C++. The speed issue can be solved in numerous ways but as always lets be sure we get the functionality clear before starting to optimise things. Alan G. From geoframer at gmail.com Sun Oct 8 08:41:50 2006 From: geoframer at gmail.com (Geoframer) Date: Sun, 8 Oct 2006 08:41:50 +0200 Subject: [Tutor] Can my code be optimized any further (speed-wise)? In-Reply-To: References: <5d8e35a70610071435t6b768925t35e00fb74b11d42d@mail.gmail.com> Message-ID: <5d8e35a70610072341x671f5a0we9ab88e40a7f0bb7@mail.gmail.com> The problem is that these assignments are evaluated automatically. So i can not use description strings to clearify output or input etc. Basically it's like this: a = the number of times i'm going to read input to evaluate lst = the factors of 5. I.e. (5, 5^2, 5^3, 5^4.... etc) until the last one wich is smaller then 1000000000 For those that didn't know the number of trailing zero's in a factorial is decided by the numer of factors of 5, because only a 5 can create a 0. Remember a factorial (n) = n*....*4*3*2*1. The list does not represent factorials. Example input of this program: 5 #number of times i'm going to read in a number 3 # 3! = 6, no trailing 0's zo the output would be 0 5 # 5! = 120, 1 trailing 0's so the output would be 1 50! #50!= , 12 trailing 0's (50/5 + 50/25=12) 100! #100!= , 24 trailing 0's (100/5 + 100/25 = 24) 125! #125!= , 31 trailing 0's (125/5 + 125/25 +125/125 = 31) Output would be: 0 1 12 24 31 Hope this clarifies what i'm trying to achieve here... Ciao - Geofram On 10/8/06, Alan Gauld wrote: > > Hi, > > Maybe its just me but I didn't understand what you are > trying to do... > > > The problem is to compute the number of trailing zero's in > > factorials (n! = > > 1*2*3*4*.......*n). with n <= 1000000000 > > > > My solution is as follows (a = times to read a number (b) to > > process) : > > > > > --------------------------------------------------------------------------- > > > > a = input() > > what does a represent? Its usually worth putting a prompt string into > input() - and raw_input() - just as documentation if nothing else! > And maybe a descriptive variable name if appropriate. > > > for i in range(a): > > lst = (5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125, > > 9765625, > > 48828125, 244140625) > > None of these have any trailing zeros so far as I can tell? > What answer are you expecting from this function? > > > ans = 0 > > b = input() > > similarly, what is b supposed to be? > > > for i in lst: > > And here you are throwing away the i from the outer loop > > > if i <= b: > > ans += b//i > > And now you divide some arbitrary input value by each factorial > in turn and sum the results? > > > print ans > > > Please, if you have suggestions to improve the speed of this > > algorithm give > > an argumentation as to why a certain something is faster. > > I nbeed to understand what you are tryying to do first, its > not making much sense at the moment. (But it is after midnight! :-) > > > P.s. I know python is probably not the best language for these kinds > > of > > problems (I can code it in C or C++), it just bugs me that it's > > possible > > and my solution is failing... ;-) > > Actually it looks like exactly what I would use Python for rarther > than C/C++. The speed issue can be solved in numerous ways but > as always lets be sure we get the functionality clear before starting > to optimise things. > > Alan G. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061008/fc7552c3/attachment.html From geoframer at gmail.com Sun Oct 8 08:43:38 2006 From: geoframer at gmail.com (Geoframer) Date: Sun, 8 Oct 2006 08:43:38 +0200 Subject: [Tutor] Can my code be optimized any further (speed-wise)? In-Reply-To: <5d8e35a70610072341x671f5a0we9ab88e40a7f0bb7@mail.gmail.com> References: <5d8e35a70610071435t6b768925t35e00fb74b11d42d@mail.gmail.com> <5d8e35a70610072341x671f5a0we9ab88e40a7f0bb7@mail.gmail.com> Message-ID: <5d8e35a70610072343qb7c1ceco75039c3b5e3b5983@mail.gmail.com> Erm i made a typo Sample input should ofcourse be without the '!''s So input = 5 3 5 50 100 125 Sorry - Geoframer On 10/8/06, Geoframer wrote: > > The problem is that these assignments are evaluated automatically. So i > can not use description strings to clearify output or input etc. > > Basically it's like this: > > a = the number of times i'm going to read input to evaluate > lst = the factors of 5. I.e. (5, 5^2, 5^3, 5^4.... etc) until the last one > wich is smaller then 1000000000 > > For those that didn't know the number of trailing zero's in a factorial is > decided by the numer of factors of 5, because only a 5 can create a 0. > Remember a factorial (n) = n*....*4*3*2*1. The list does not represent > factorials. > > Example input of this program: > 5 #number of times i'm going to read in a > number > 3 # 3! = 6, no trailing 0's zo the output > would be 0 > 5 # 5! = 120, 1 trailing 0's so the output > would be 1 > 50! #50!= , 12 trailing 0's > (50/5 + 50/25=12) > 100! #100!= , 24 trailing 0's > (100/5 + 100/25 = 24) > 125! #125!= , 31 trailing 0's > (125/5 + 125/25 +125/125 = 31) > > Output would be: > 0 > 1 > 12 > 24 > 31 > > Hope this clarifies what i'm trying to achieve here... > > Ciao - Geofram > > > On 10/8/06, Alan Gauld wrote: > > > > Hi, > > > > Maybe its just me but I didn't understand what you are > > trying to do... > > > > > The problem is to compute the number of trailing zero's in > > > factorials (n! = > > > 1*2*3*4*.......*n). with n <= 1000000000 > > > > > > My solution is as follows (a = times to read a number (b) to > > > process) : > > > > > > > > --------------------------------------------------------------------------- > > > > > > a = input() > > > > what does a represent? Its usually worth putting a prompt string into > > input() - and raw_input() - just as documentation if nothing else! > > And maybe a descriptive variable name if appropriate. > > > > > for i in range(a): > > > lst = (5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125, > > > 9765625, > > > 48828125, 244140625) > > > > None of these have any trailing zeros so far as I can tell? > > What answer are you expecting from this function? > > > > > ans = 0 > > > b = input() > > > > similarly, what is b supposed to be? > > > > > for i in lst: > > > > And here you are throwing away the i from the outer loop > > > > > if i <= b: > > > ans += b//i > > > > And now you divide some arbitrary input value by each factorial > > in turn and sum the results? > > > > > print ans > > > > > Please, if you have suggestions to improve the speed of this > > > algorithm give > > > an argumentation as to why a certain something is faster. > > > > I nbeed to understand what you are tryying to do first, its > > not making much sense at the moment. (But it is after midnight! :-) > > > > > P.s. I know python is probably not the best language for these kinds > > > of > > > problems (I can code it in C or C++), it just bugs me that it's > > > possible > > > and my solution is failing... ;-) > > > > Actually it looks like exactly what I would use Python for rarther > > than C/C++. The speed issue can be solved in numerous ways but > > as always lets be sure we get the functionality clear before starting > > to optimise things. > > > > Alan G. > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061008/f399702b/attachment.htm From noufal at nibrahim.net.in Sun Oct 8 09:06:32 2006 From: noufal at nibrahim.net.in (Noufal Ibrahim) Date: Sun, 8 Oct 2006 12:36:32 +0530 (IST) Subject: [Tutor] Isolation of code Message-ID: <36663.59.144.39.164.1160291192.squirrel@members.hcoop.net> Greetings everyone, I'm working on a little project that's similar to tcltutor for python. I have a string which has some python code. I "compile" and "eval" this to get the output. So far so good. However, when this happens, the evaluation is happening in the current namespace so I'm afraid of symbols being redefined and messed up. What I want to do is to create a separate namespace for all the code so that I can execute it without worrying about symbol mangling. Something like if the code I have is code = """ x=5 if x==5: print "Yes" else: print "No" """ I'd like to be able to create a separate module called (say) "tester" with contents def __start_exec__(): then say something like import tester tester.__start_exec__() to actually run the code. This way, the namespace would be separate. Any idea how I can go about this? I'm guessing I should use the parser module to actually create the construct and then compile it but that looks little hairy. Is there something I'm missing? Any suggestions? Peace, -- -NI From noufal at nibrahim.net.in Sun Oct 8 09:06:09 2006 From: noufal at nibrahim.net.in (Noufal Ibrahim) Date: Sun, 8 Oct 2006 12:36:09 +0530 (IST) Subject: [Tutor] Isolation of code Message-ID: <36654.59.144.39.164.1160291169.squirrel@members.hcoop.net> Greetings everyone, I'm working on a little project that's similar to tcltutor for python. I have a string which has some python code. I "compile" and "eval" this to get the output. So far so good. However, when this happens, the evaluation is happening in the current namespace so I'm afraid of symbols being redefined and messed up. What I want to do is to create a separate namespace for all the code so that I can execute it without worrying about symbol mangling. Something like if the code I have is code = """ x=5 if x==5: print "Yes" else: print "No" """ I'd like to be able to create a separate module called (say) "tester" with contents def __start_exec__(): then say something like import tester tester.__start_exec__() to actually run the code. This way, the namespace would be separate. Any idea how I can go about this? I'm guessing I should use the parser module to actually create the construct and then compile it but that looks little hairy. Is there something I'm missing? Any suggestions? Peace, -- -NI From alan.gauld at btinternet.com Sun Oct 8 10:13:18 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 8 Oct 2006 09:13:18 +0100 Subject: [Tutor] Can my code be optimized any further (speed-wise)? References: <5d8e35a70610071435t6b768925t35e00fb74b11d42d@mail.gmail.com> <5d8e35a70610072341x671f5a0we9ab88e40a7f0bb7@mail.gmail.com> Message-ID: Thanks, thats a lot clearer. > a = the number of times i'm going to read input to evaluate > lst = the factors of 5. I.e. (5, 5^2, 5^3, 5^4.... etc) until the > last one > wich is smaller then 1000000000 OK, I had assumed it was a list of sample factorial results. Not reading it carefully enough. But a comment would have been good since its not self evident. > Example input of this program: > 5 #number of times i'm going to read > in a So a could be called iterations maybe? > number > 3 # 3! = 6, no trailing 0's zo the > output and b could be called factorial_number or similar? > would be 0 > 5 # 5! = 120, 1 trailing 0's so the > output > would be 1 > 50! #50!= , 12 > trailing 0's > (50/5 + 50/25=12) > 100! #100!= , 24 > trailing 0's > (100/5 + 100/25 = 24) > 125! #125!= , 31 > trailing 0's > (125/5 + 125/25 +125/125 = 31) > > Output would be: > 0 > 1 > 12 > 24 > 31 > > Hope this clarifies what i'm trying to achieve here... Yes, thats very clear now. I'll go back to the original post and reread the code. Alan G. From sillyhed2000 at hotmail.com Sun Oct 8 12:47:35 2006 From: sillyhed2000 at hotmail.com (Tom R.) Date: Sun, 08 Oct 2006 10:47:35 +0000 Subject: [Tutor] Variable help Message-ID: I have a number of arrays: player1 = [data, data, data] player2 = [data, data, data] player3 = [data, data, data] player4 = [data, data, data] I want to be able to do something like: count = 2 if player + count[3] == 5: do this do that count += 1 And that would do this and that to the array 'player2' in slot 3. It adds 1 to 'count', so next time through it will access the array 'player3'. Basically I want to be able to integrate the value of one variable into another variables name. It's hard explain, hopefully the code above will give you an idea of what I'm trying to achieve. Alternately, how can I use the return of a function as a variables name? eg: def choose_player(player): if player == 1: return player1[3 if player == 2: return player2[3] if player == 3: return player3[3] if player == 4: return player4[3] choose_player(2) = 5 This was another way I thought of doing it - one that might actually work - but it comes back with "Can't assign to function call." I'm not trying to assign it to the function itself, but the outcome of the function. I can use it to read the value of the player2 variable (ie. if choose_player(2) == 5), but not set it. Once again, I hope I've given an idea of what I'm trying to do. Any way I can achieve this? From andreengels at gmail.com Sun Oct 8 12:53:35 2006 From: andreengels at gmail.com (Andre Engels) Date: Sun, 8 Oct 2006 12:53:35 +0200 Subject: [Tutor] Can my code be optimized any further (speed-wise)? In-Reply-To: <5d8e35a70610071435t6b768925t35e00fb74b11d42d@mail.gmail.com> References: <5d8e35a70610071435t6b768925t35e00fb74b11d42d@mail.gmail.com> Message-ID: <6faf39c90610080353h1a050a65n468758c9b3f13896@mail.gmail.com> 2006/10/7, Geoframer : > Hi everyone, > > The last few days i've been learning python and have been doing this by > trying to solve problems for a programming competition. > One particular problem is bugging me. I have already solved it but my > solution does not compute in the set time-condition. I know > for a fact that this particular problem is solvable in the time-limit using > Python, so i was wondering if my solution is maybe inefficitient code-wise. > If my code can't be optimized for speed any more i must be missing something > and should labor hard to find a new algorithm ;-). > > The problem is to compute the number of trailing zero's in factorials (n! = > 1*2*3*4*.......*n). with n <= 1000000000 > > My solution is as follows (a = times to read a number (b) to process) : > > --------------------------------------------------------------------------- > > a = input() > for i in range(a): > lst = (5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125, 9765625, > 48828125, 244140625) > ans = 0 > b = input() > for i in lst: > if i <= b: > ans += b//i > print ans > > ---------------------------------------------------------------------------- > > Please, if you have suggestions to improve the speed of this algorithm give > an argumentation as to why a certain something is faster. > That would allow me to learn to program faster algorithms in Python al > together instead of just in this problem. The program as you have shown it, skims to incorrectness. Please don't use the same variable (i) for two nested loops! Regarding speed, I see some small improvements: * lst is created each time you go through the loop; creating it once would suffice as well * If we have found that some i is larger than b, then definitely the next one will be a = input() lst = (5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125, 9765625, 48828125, 244140625) for i in range(a): ans = 0 b = input() for j in lst: if j <= b: ans += b//i else: break print ans The first thing (moving the lst= out of the loop) will definitely make a (tiny) improvement on speed; it also improves the logic of your code. The second (the else: break) I am not sure whether it will improve things (because often you will go into the else at the last time or not at all). Your program goes wrong for large values of b. This should be avoided - the program should have as little chance as possible for the user to give 'wrong' input, either by forbidding it or by dealing with it. Here the latter is easily done: The way I would do this (although it would make the program slower rather than faster because it would make the check each time that b is set: replace lst = (5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125, 9765625, 48828125, 244140625) by lst = [5] and after b=input() add: while lst[-1]*5 < b: lst.append(lst[-1]*5) And finally I wonder why on Earth you would worry about the speed of this program, given that the running time over 1 number is just a fraction of the time it costs you to type in that number. -- Andre Engels, andreengels at gmail.com ICQ: 6260644 -- Skype: a_engels From ismaelgf at adinet.com.uy Sun Oct 8 15:40:26 2006 From: ismaelgf at adinet.com.uy (Ismael Garrido) Date: Sun, 08 Oct 2006 10:40:26 -0300 Subject: [Tutor] Variable help In-Reply-To: References: Message-ID: <4528FFCA.7040006@adinet.com.uy> Tom R. escribi?: > I have a number of arrays: > > player1 = [data, data, data] > player2 = [data, data, data] > player3 = [data, data, data] > player4 = [data, data, data] > > I want to be able to do something like: > > count = 2 > if player + count[3] == 5: > do this > do that > count += 1 > > And that would do this and that to the array 'player2' in slot 3. It adds 1 > to 'count', so next time through it will access the array 'player3'. > Basically I want to be able to integrate the value of one variable into > another variables name. It's hard explain, hopefully the code above will > give you an idea of what I'm trying to achieve. > Put the players in a list. player_list = [player1, player2, player3... ] So if you want to get to player1 data, you use player_list[0][0...2], which would be the same as player1[0...2]. If you then want to do something to every player, you could do: for player in player_list: do something > Alternately, how can I use the return of a function as a variables name? eg: > > def choose_player(player): > if player == 1: > return player1[3 > if player == 2: > return player2[3] > if player == 3: > return player3[3] > if player == 4: > return player4[3] > > choose_player(2) = 5 > > Functions return values. To keep the return value, you simply have to assign it to a variable: result = choose_player(3) And then you can do whatever you want with result. Bear in mind that result and player3[3] are *not* the same thing, they only have the same value. HTH! Ismael From kent37 at tds.net Sun Oct 8 15:23:26 2006 From: kent37 at tds.net (Kent Johnson) Date: Sun, 08 Oct 2006 09:23:26 -0400 Subject: [Tutor] Can my code be optimized any further (speed-wise)? In-Reply-To: <5d8e35a70610071435t6b768925t35e00fb74b11d42d@mail.gmail.com> References: <5d8e35a70610071435t6b768925t35e00fb74b11d42d@mail.gmail.com> Message-ID: <4528FBCE.5050608@tds.net> Geoframer wrote: > Hi everyone, > > The problem is to compute the number of trailing zero's in factorials > (n! = 1*2*3*4*.......*n). with n <= 1000000000 > > My solution is as follows (a = times to read a number (b) to process) : > > --------------------------------------------------------------------------- > > a = input() > for i in range(a): > lst = (5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125, > 9765625, 48828125, 244140625) > ans = 0 > b = input() > for i in lst: > if i <= b: > ans += b//i > print ans > > ---------------------------------------------------------------------------- > > Please, if you have suggestions to improve the speed of this algorithm > give an argumentation as to why a certain something is faster. > That would allow me to learn to program faster algorithms in Python al > together instead of just in this problem. Try putting the actual computation into a function. Make any variable that is used more than once a local variable of the function (ans, b,i). Accessing local variables is faster than accessing global variables. This gives about 40% speedup in my tests. Use psyco if it is available in your contest, for me that shaved off another 30-50%; you will get more benefit from psyco the more iterations you have, because psyco introduces some compilation overhead that has to be made up by the faster code. http://psyco.sourceforge.net/ You really aren't doing much so there's not a lot to optimize that I can see. You could try asking on comp.lang.python, lots of people there are good at optimization. Kent From geon at post.cz Sun Oct 8 16:09:07 2006 From: geon at post.cz (Pavel Kosina) Date: Sun, 08 Oct 2006 16:09:07 +0200 Subject: [Tutor] =?utf-8?q?Python=2C_wxPython_a_datab=C3=A1zov=C3=A1_aplik?= =?utf-8?q?ace?= Message-ID: <45290683.9010300@post.cz> Sorry for this mail, was sent by error. Pavel Kosina superman napsal(a): > Dobr? den, > > mohli byste m? n?jak nakopnout v tom, jak se d?l? datab?zov? aplikace v > Pythonu s pou?it?m wxPython? Respektive jestli wxPython m? n?jak? prvky, > kter? slou?? p??mo pro pr?ci s datab?zemi, a nebo jestli je pot?eba to > ud?lat ru?n? a v?echno si o?et?it s?m. > > nev?m > U? jsem se do toho pustil, nakreslil jsem si i voli? z?znam? jako je v > MS Accessu, cht?l jsem pou??t n?jak? grid a s?zet so n?j data, ale do?lo > mi, ?e zat?m ka?d? prost?ed? m?lo n?co, ??m to uleh?it. Prost? n?jak? > grafick? prvky stylu "grid napojen? na datab?zi", nebo "textedit > napojen? na datab?zi", apod.. Pak by bylo ?koda to d?lat ru?n?. > nezn?m > P??padn? zda takov? prvky n?kdo u? nenaprogramoval jako nadstavbu nad > n?co existuj?c?ho. Pak pros?m a? to proboha nen? GPL, nechci tuto > licenci. T?m vyly?uji p?edem i cokoli s PyQt. > hehe, to m? pobavilo. A jakou bys r?d? N?jakou komer?n?? LGPL by ?la? Mysl?m ?e vylou?en?m GPL vy?azuje? v?t?inu ?hav?ch kandid?t?, pokud tedy n?jac? jsou :-) P???t? pls vytvo? s nov?m t?matem nov? mail, at se to ne?ad? n?kam do nepat?i?n?ho m?sta stromu p??sp?vk?, jako te?. -- geon Pavel Kosina From geon at post.cz Sun Oct 8 15:58:59 2006 From: geon at post.cz (Pavel Kosina) Date: Sun, 08 Oct 2006 15:58:59 +0200 Subject: [Tutor] =?utf-8?q?Python=2C_wxPython_a_datab=C3=A1zov=C3=A1_aplik?= =?utf-8?q?ace?= Message-ID: <45290423.1000603@post.cz> superman napsal(a): > Dobr? den, > > mohli byste m? n?jak nakopnout v tom, jak se d?l? datab?zov? aplikace v > Pythonu s pou?it?m wxPython? Respektive jestli wxPython m? n?jak? prvky, > kter? slou?? p??mo pro pr?ci s datab?zemi, a nebo jestli je pot?eba to > ud?lat ru?n? a v?echno si o?et?it s?m. > > nev?m > U? jsem se do toho pustil, nakreslil jsem si i voli? z?znam? jako je v > MS Accessu, cht?l jsem pou??t n?jak? grid a s?zet so n?j data, ale do?lo > mi, ?e zat?m ka?d? prost?ed? m?lo n?co, ??m to uleh?it. Prost? n?jak? > grafick? prvky stylu "grid napojen? na datab?zi", nebo "textedit > napojen? na datab?zi", apod.. Pak by bylo ?koda to d?lat ru?n?. > nezn?m > P??padn? zda takov? prvky n?kdo u? nenaprogramoval jako nadstavbu nad > n?co existuj?c?ho. Pak pros?m a? to proboha nen? GPL, nechci tuto > licenci. T?m vyly?uji p?edem i cokoli s PyQt. > hehe, to m? pobavilo. A jakou bys r?d? N?jakou komer?n?? LGPL by ?la? Mysl?m ?e vylou?en?m GPL vy?azuje? v?t?inu ?hav?ch kandid?t?, pokud tedy n?jac? jsou :-) P???t? pls vytvo? s nov?m t?matem nov? mail, at se to ne?ad? n?kam do nepat?i?n?ho m?sta stromu p??sp?vk?, jako te?. -- geon Pavel Kosina From ph34r_th3_d4rkn3s at hotmail.com Sun Oct 8 16:52:41 2006 From: ph34r_th3_d4rkn3s at hotmail.com (max .) Date: Sun, 08 Oct 2006 08:52:41 -0600 Subject: [Tutor] Tkinter and python Message-ID: first off i just started looking for Tkinter tutorials but havent found much and what i have found was not very good if anyone knows og any Tkinter tutorials pleas let me know second is thair anyway to change the path that python looks for a program in ex: if i enter python hello into the command line then i get this error /Library/Frameworks/Python.framework/Versions/2.4/Resources/Python.app/Contents/MacOS/Python: can't open file 'hello1': [Errno 2] No such file or directory can i chage that search path? if so how? thx ^_^" s33 y4 _________________________________________________________________ Search?Your way, your world, right now! http://imagine-windowslive.com/minisites/searchlaunch/?locale=en-us&FORM=WLMTAG From arunkumarpg at gmail.com Sun Oct 8 17:06:31 2006 From: arunkumarpg at gmail.com (Arun Kumar PG) Date: Sun, 8 Oct 2006 20:36:31 +0530 Subject: [Tutor] Tkinter and python In-Reply-To: References: Message-ID: <3cffff920610080806y6901922ar9fe027e6bda4eea3@mail.gmail.com> Hi, You can try: >> import sys >> sys.path.append('') >> import Or else you can append the path to global PYTHONPATH environment variable and whenever you will type: python on the command prompt/bash shell the script gets executed. Hope that helps. Thanks, - Arun On 10/8/06, max . wrote: > > first off i just started looking for Tkinter tutorials but havent found > much > and what i have found was not very good if anyone knows og any Tkinter > tutorials pleas let me know > > second is thair anyway to change the path that python looks for a program > in > ex: if i enter python hello into the command line then i get this error > > > /Library/Frameworks/Python.framework/Versions/2.4/Resources/Python.app/Contents/MacOS/Python: > can't open file 'hello1': [Errno 2] No such file or directory > > can i chage that search path? > if so how? > > thx > > > > ^_^" s33 y4 > > _________________________________________________________________ > Search?Your way, your world, right now! > > http://imagine-windowslive.com/minisites/searchlaunch/?locale=en-us&FORM=WLMTAG > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061008/3d218f47/attachment-0001.html From noufal at airtelbroadband.in Sun Oct 8 17:03:03 2006 From: noufal at airtelbroadband.in (Noufal Ibrahim) Date: Sun, 08 Oct 2006 20:33:03 +0530 Subject: [Tutor] Tkinter and python In-Reply-To: References: Message-ID: <45291327.1000909@airtelbroadband.in> max . wrote: > first off i just started looking for Tkinter tutorials but havent found > much and what i have found was not very good if anyone knows og any > Tkinter tutorials pleas let me know Try this for a good tutorial http://www.pythonware.com/library/tkinter/introduction/ Peace. From dkuhlman at rexx.com Sun Oct 8 17:59:20 2006 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Sun, 8 Oct 2006 08:59:20 -0700 Subject: [Tutor] Isolation of code In-Reply-To: <36663.59.144.39.164.1160291192.squirrel@members.hcoop.net> References: <36663.59.144.39.164.1160291192.squirrel@members.hcoop.net> Message-ID: <20061008155920.GA49387@cutter.rexx.com> On Sun, Oct 08, 2006 at 12:36:32PM +0530, Noufal Ibrahim wrote: > Greetings everyone, > I'm working on a little project that's similar to tcltutor for python. > I have a string which has some python code. I "compile" and "eval" this > to get the output. So far so good. However, when this happens, the > evaluation is happening in the current namespace so I'm afraid of > symbols being redefined and messed up. > What I want to do is to create a separate namespace for all the code so > that I can execute it without worrying about symbol mangling. > > Something like if the code I have is > code = """ > x=5 > if x==5: > print "Yes" > else: > print "No" > """ > > I'd like to be able to create a separate module called (say) "tester" > with contents > > def __start_exec__(): > > > then say something like > import tester > tester.__start_exec__() > > to actually run the code. This way, the namespace would be separate. > Two points: 1. (Stating something obvious) Code in a module, when called, does run in a separate namespace. For example, if I run: import modB modB.f() then any variables set in modB are local to modB. 2. If that separation of namespaces is not "strong" enough for you, try something like the following: exec somecode in globalDict where globalDict is a dictionary. globalDict will be the namespace used by somecode, and, for example, variables created (perhaps using assignment) in somecode will be created in globalDict rather than in the current namespace. See: http://docs.python.org/ref/exec.html. Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From dkuhlman at rexx.com Sun Oct 8 18:20:10 2006 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Sun, 8 Oct 2006 09:20:10 -0700 Subject: [Tutor] Tkinter and python In-Reply-To: <3cffff920610080806y6901922ar9fe027e6bda4eea3@mail.gmail.com> References: <3cffff920610080806y6901922ar9fe027e6bda4eea3@mail.gmail.com> Message-ID: <20061008162010.GB49387@cutter.rexx.com> On Sun, Oct 08, 2006 at 08:36:31PM +0530, Arun Kumar PG wrote: > Hi, > > You can try: > > >>import sys > >>sys.path.append('') > >>import > > Or else you can append the path to global PYTHONPATH environment variable > and whenever you will type: > > python on the command prompt/bash shell the script gets > executed. > Not true, if I understand you correctly. PYTHONPATH affects where Python looks for modules to be imported. But if I type the following at the command line: $ python mymodule.py it is the shell (in my case bash) that looks for mymodule.py, not Python. It analogous to my typing: $ vi mymodule.py or (trying to avoid a fight between vi and emacs fanatics): $ emacs mymodule.py Neither vi nor emacs try to find mymodule.py; the (bash or other) shell does. So perhaps a solution to the problem is to make mymodule.py executable and put it somewhere on your path. Then execute it by typing at the command line: $ mymodule.py Now the shell will run it just like any other executable script and it will use Python as the interpreter for that script. How you make the script executable probably depends on which shell you are using. For bash, you could do the following: 1. Insert the following line as the first line of your script: #!/usr/bin/env python 2. Change the priveleges of the script to make it executable. Example: $ chmod u+x mymodule.py 3. Put mymodule.py on your path, that is, in a directory that is in your PATH environment variable. Alternatively, add the path to the directory containing mymodule.py to your PATH environment variable. Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From dyoo at hkn.eecs.berkeley.edu Sun Oct 8 18:23:17 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 8 Oct 2006 09:23:17 -0700 (PDT) Subject: [Tutor] Can my code be optimized any further (speed-wise)? In-Reply-To: <4528FBCE.5050608@tds.net> References: <5d8e35a70610071435t6b768925t35e00fb74b11d42d@mail.gmail.com> <4528FBCE.5050608@tds.net> Message-ID: > You really aren't doing much so there's not a lot to optimize that I can > see. You could try asking on comp.lang.python, lots of people there are > good at optimization. ** spoiler space: don't read ahead here unless you've attempted this problem already, or if you don't want to be spoiled ** ******************************************************************** You may be able to treat this as a combinatorial problem: how many ways can you get a factor of 10 from the product of all those numbers? Every factor of ten contributes to a trailing zero, so if we can count those, we're done. Concretely: if we're computing 10! factorial, imgaine we have the numbers 1-10 in front of us. 1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 Next, we'll do something a little funny: we break up everything into its prime factors: 1 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 3 * 3 * 3 * 3 * 5 * 5 * 7 Chop chop. Then we know that we're going to get a trailing zero when we multiply with the first five: 2 * 5 and we also get a trailing zero when we multiply with the other five: 2 * 5 Even without computing the factorial, we know there's going to be two trailing zeros in 10!, because there's only two ways of making tens. The key is to see that factors of five can be combined with the overabundance of twos that we have: that's how we can get tens. And those tens are going to contribute to trailing zeros in the final product. There are some complications, because some numbers produce more than one factor of five (like 25, for example...), but they can be handled with a little thought. As a reference point: because you're explicitely given the upper bounds on this assignment, this problem should be solvable in constant time, with a single math formula. Good luck. From ilias at lazaridis.com Sun Oct 8 19:18:50 2006 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Sun, 08 Oct 2006 20:18:50 +0300 Subject: [Tutor] Shell Output Format - [was: Is there Python code for accessing an object's reference count?] In-Reply-To: <45224D23.9040303@tds.net> References: <7.0.1.0.2.20061003030543.03f0fc90@rcblue.com> <7528bcdd0610030325w79666951w7456748aa145840@mail.gmail.com> <7.0.1.0.2.20061003035702.06a8a390@rcblue.com> <45224D23.9040303@tds.net> Message-ID: Kent Johnson wrote: ... > In [2]: sys.getrefcount(100) > Out[2]: 43 > > In [3]: def foo(): > ...: return 100 > ...: > > In [4]: sys.getrefcount(100) > Out[4]: 44 off-topic: how to you get this output format of the shell? In [2]: Out[2]: I've tried to alter IDLE: IDLE - Customizing output format http://groups.google.com/group/comp.lang.python/browse_frm/thread/b81ef0c0b134def2 . -- http://lazaridis.com From alan.gauld at btinternet.com Sun Oct 8 19:32:22 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 8 Oct 2006 18:32:22 +0100 Subject: [Tutor] Can my code be optimized any further (speed-wise)? References: <5d8e35a70610071435t6b768925t35e00fb74b11d42d@mail.gmail.com> Message-ID: I've had a look at the other comments, particularly Kents, but I'll add a few more comments: > One particular problem is bugging me. I have already solved it but > my > solution does not compute in the set time-condition. How can you tell since you pause for user input in the middle of the loop? The time to enter the data will be more than the time doing the calculation in most cases. You will need to move the extraneous stuff outsidethe loop to have any h0pe of timing sensibly. Something like this: iterations = input('How many factorials? ') facs = [input('Type a required factorial: ') for n in range(iterations)] factors = (5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125, 9765625, 48828125, 244140625) # start timing here for i in range(iterations): num = facs[i] print sum([num//f for f in factors if f<= num]) # end timing Now you have something you can time. I'm assuming that the sum/list comprehension will be faster than the explicit loop/add/break combination that Kent suggested for the low number of factors involved, but I haven't tried it... Its based on the theory that it maximises the time in C code as opposed to native Python... Alan G. PS. In looking at this I wondered whether an extension to list comprehension syntax would be a good idea. Namely to add a while condition at the end to limit the number of iterations: In this case the LC would become: [num//f for f in factors while f <= num]) It could even be combined with the conditional form I think: [num//f for f in factors if f == 7 while f <= num]) Just a thought... > My solution is as follows (a = times to read a number (b) to > process) : > > --------------------------------------------------------------------------- > > a = input() > for i in range(a): > lst = (5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125, > 9765625, > 48828125, 244140625) > ans = 0 > b = input() > for i in lst: > if i <= b: > ans += b//i > print ans > > ---------------------------------------------------------------------------- > From kent37 at tds.net Sun Oct 8 19:34:13 2006 From: kent37 at tds.net (Kent Johnson) Date: Sun, 08 Oct 2006 13:34:13 -0400 Subject: [Tutor] Shell Output Format - [was: Is there Python code for accessing an object's reference count?] In-Reply-To: References: <7.0.1.0.2.20061003030543.03f0fc90@rcblue.com> <7528bcdd0610030325w79666951w7456748aa145840@mail.gmail.com> <7.0.1.0.2.20061003035702.06a8a390@rcblue.com> <45224D23.9040303@tds.net> Message-ID: <45293695.8010506@tds.net> Ilias Lazaridis wrote: > how to you get this output format of the shell? > > In [2]: > Out[2]: IPython http://ipython.scipy.org/ Kent From python at venix.com Sun Oct 8 19:40:53 2006 From: python at venix.com (Python) Date: Sun, 08 Oct 2006 13:40:53 -0400 Subject: [Tutor] Variable help In-Reply-To: <4528FFCA.7040006@adinet.com.uy> References: <4528FFCA.7040006@adinet.com.uy> Message-ID: <1160329253.8103.154.camel@www.venix.com> On Sun, 2006-10-08 at 10:40 -0300, Ismael Garrido wrote: > Tom R. escribi?: > > I have a number of arrays: > > > > player1 = [data, data, data] > > player2 = [data, data, data] > > player3 = [data, data, data] > > player4 = [data, data, data] > > > > I want to be able to do something like: > > > > count = 2 > > if player + count[3] == 5: > > do this > > do that > > count += 1 > > > > And that would do this and that to the array 'player2' in slot 3. It adds 1 > > to 'count', so next time through it will access the array 'player3'. > > Basically I want to be able to integrate the value of one variable into > > another variables name. It's hard explain, hopefully the code above will > > give you an idea of what I'm trying to achieve. > > > Put the players in a list. > player_list = [player1, player2, player3... ] > So if you want to get to player1 data, you use player_list[0][0...2], > which would be the same as player1[0...2]. > > If you then want to do something to every player, you could do: > > for player in player_list: > do something > > > > Alternately, how can I use the return of a function as a variables name? eg: > > > > def choose_player(player): > > if player == 1: > > return player1[3 > > if player == 2: > > return player2[3] > > if player == 3: > > return player3[3] > > if player == 4: > > return player4[3] > > > > choose_player(2) = 5 > > > > > Functions return values. To keep the return value, you simply have to > assign it to a variable: > > result = choose_player(3) > > And then you can do whatever you want with result. Bear in mind that > result and player3[3] are *not* the same thing, they only have the same > value. (let me offer a correction to that last sentence.) result = player3[3] # player3 must contain at least 4 values result and player3[3] *do* reference the same thing. My preferred analogy is that names in Python are written on sticky notes and stuck on the objects they refer to. The name and the object are separate and distinct. So we take a sticky note labeled result and stick it on the *same* object that player3[3] refers to. If that object is immutable, then it can't be changed and you can only bind result or that position in the player3 list to different things. Both bindings are independent. HOWEVER, both start off referring (bound) to the same thing. If we have a succeeding line that says: result = 4 The "result sticky note" is peeled off the original object and stuck onto the the "4 object". player3[3] is not affected. This distinction between value and object reference becomes important when the object is mutable. Then lines like: result.sort() result.append('new stuff') affect player3[3] because both are actually bound to the same object. > > > HTH! > Ismael > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From tim.peters at gmail.com Sun Oct 8 19:55:18 2006 From: tim.peters at gmail.com (Tim Peters) Date: Sun, 8 Oct 2006 13:55:18 -0400 Subject: [Tutor] Can my code be optimized any further (speed-wise)? In-Reply-To: <5d8e35a70610071435t6b768925t35e00fb74b11d42d@mail.gmail.com> References: <5d8e35a70610071435t6b768925t35e00fb74b11d42d@mail.gmail.com> Message-ID: <1f7befae0610081055p692ebc4cof868a70a9c5442c@mail.gmail.com> [Geoframer] > The last few days i've been learning python and have been doing this by > trying to solve problems for a programming competition. I assume you're talking about: http://www.spoj.pl/problems/FCTRL/ If so, you'll note that I'm tied for the fastest Python solution there ;-) The /guts/ of my method is just: # count <- number of trailing zeroes in n! count = 0 base = 5 while n >= base: count += n // base base *= 5 There are several reasons for why that's faster than what you tried, which have been explained by others (doesn't create a list of divisors each time; gets out of the loop as soon as there's no point to continuing). It's /possible/ that it would be faster if you did keep a canned list of powers of 5. But for some of the SPOJ problems (like this one ;-)), that's not the real thing to worry about! Some have very large input sets, and the time spent doing I/O, and converting between strings and integers, swamps the time needed to do calculations. So, for example, in this problem I didn't read one line at a time. Instead I did: def main(): import sys ncases = int(sys.stdin.readline()) all = map(int, sys.stdin.read().split()) assert ncases == len(all) for n in z(all): print n The important part there is sucking in all of the test cases "in one gulp", and converting to them /all/ to integers with a /single/ fast map() call. The z() function is basically what I wrote above, containing a loop to march over all the inputs. It's also important for peak speed to use functions so that faster local-variable lookups can be used instead of slower global-variable lookups. But those aren't the most important parts either ;-) When it comes to speed, it's rarely what you think it is. Using the input() function was almost certainly your primary problem, because input() endures the relatively enormous expense of /compiling/ the input string as a fully general Python expression, generating a code object for that expression, interpreting that dynamically generated Python code, and then tearing down the code object again. For every input. It's not the slowest possible way to convert a string to an integer, but you'd have to work hard to find a slower way ;-) Just for fun, you might want to try /just/ changing: b = input() in your program to b = int(raw_input()) I don't know whether you'll meet the time limit then, but it will run much faster. Finally, if you look at the 20 accepted Python solutions: http://www.spoj.pl/ranks/FCTRL/lang=PYTH you'll see that the top 5 all used enormously more memory than the other 15. That's an almost-certain sign that they used psyco (which the SPOJ folks have installed), like so: # the rest of the code goes here import psyco psyco.full() if __name__ == "__main__": main() Note that psyco doesn't always help -- sometimes it makes a program slower. As the 15 other accepted Python solutions show, it's not necessary to use psyco to meet the time limit for this problem. If I could, I'd retract my run using psyco and settle for a non-psyco run -- I couldn't care less about being "the fastest" on these, and just /tried/ psyco here out of professional curiousity. Alas, SPOJ only remembers the fastest correct run you submit. From kent37 at tds.net Sun Oct 8 20:25:31 2006 From: kent37 at tds.net (Kent Johnson) Date: Sun, 08 Oct 2006 14:25:31 -0400 Subject: [Tutor] Variable help In-Reply-To: References: Message-ID: <4529429B.4020309@tds.net> Tom R. wrote: > Alternately, how can I use the return of a function as a variables name? eg: > > def choose_player(player): > if player == 1: > return player1[3 > if player == 2: > return player2[3] > if player == 3: > return player3[3] > if player == 4: > return player4[3] > > choose_player(2) = 5 You actually can do this very easily by returning the correct playerx list: def choose_player(player): if player == 1: return player1 if player == 2: return player2 if player == 3: return player3 if player == 4: return player4 then the result of choose_player() is a list that you can index normally: choose_player(2)[3] = 5 This actually looks a lot like the solution with a list of player lists, where you would write players[2][3] = 5 I recommend the list-of-lists solution, but I thought it was worth noting that the function version is easy to write. Kent From geoframer at gmail.com Sun Oct 8 23:38:13 2006 From: geoframer at gmail.com (Geoframer) Date: Sun, 8 Oct 2006 23:38:13 +0200 Subject: [Tutor] Can my code be optimized any further (speed-wise)? In-Reply-To: <1f7befae0610081055p692ebc4cof868a70a9c5442c@mail.gmail.com> References: <5d8e35a70610071435t6b768925t35e00fb74b11d42d@mail.gmail.com> <1f7befae0610081055p692ebc4cof868a70a9c5442c@mail.gmail.com> Message-ID: <5d8e35a70610081438w73e9e076ye5072044ed97ca5d@mail.gmail.com> Thanks everyone for the valuable suggestions. Lots of suggestions which i'm sure will improve the speed and performance of my solution. It is indeed the problem Tim said, and it helps a lot to get some help from one of the fastest people on there ;-). I just find it's more fun (and probably more productive) to learn by trying as well as reading. I'm sure i'll be able to solve some other problems with the suggestions here as i've run into the timelimit more often already. Next time i'll try to be more clear on what my problem is and how it is supposed to achieved! (The input was all streamed into the program automatically there was no manual input. I just used the input() function because i didn't have a clue yet how else to read in an integer ;-) ) Besides doing these little excersises i'm reading : O'reilly's - 'Learning Python' and 'Dive into python' (www.diveintopython.org). So i'm hoping i can soon help people the way you guys helped me ;-) Once again thanks everyone for their suggestions and time!!! Regards - Geoframer On 10/8/06, Tim Peters wrote: > > [Geoframer] > > The last few days i've been learning python and have been doing this by > > trying to solve problems for a programming competition. > > I assume you're talking about: > > http://www.spoj.pl/problems/FCTRL/ > > If so, you'll note that I'm tied for the fastest Python solution there ;-) > > The /guts/ of my method is just: > > # count <- number of trailing zeroes in n! > count = 0 > base = 5 > while n >= base: > count += n // base > base *= 5 > > There are several reasons for why that's faster than what you tried, > which have been explained by others (doesn't create a list of divisors > each time; gets out of the loop as soon as there's no point to > continuing). It's /possible/ that it would be faster if you did keep > a canned list of powers of 5. > > But for some of the SPOJ problems (like this one ;-)), that's not the > real thing to worry about! Some have very large input sets, and the > time spent doing I/O, and converting between strings and integers, > swamps the time needed to do calculations. > > So, for example, in this problem I didn't read one line at a time. > Instead I did: > > def main(): > import sys > ncases = int(sys.stdin.readline()) > all = map(int, sys.stdin.read().split()) > assert ncases == len(all) > for n in z(all): > print n > > The important part there is sucking in all of the test cases "in one > gulp", and converting to them /all/ to integers with a /single/ fast > map() call. The z() function is basically what I wrote above, > containing a loop to march over all the inputs. It's also important > for peak speed to use functions so that faster local-variable lookups > can be used instead of slower global-variable lookups. > > But those aren't the most important parts either ;-) When it comes to > speed, it's rarely what you think it is. > > Using the input() function was almost certainly your primary problem, > because input() endures the relatively enormous expense of /compiling/ > the input string as a fully general Python expression, generating a > code object for that expression, interpreting that dynamically > generated Python code, and then tearing down the code object again. > For every input. It's not the slowest possible way to convert a > string to an integer, but you'd have to work hard to find a slower way > ;-) > > Just for fun, you might want to try /just/ changing: > > b = input() > > in your program to > > b = int(raw_input()) > > I don't know whether you'll meet the time limit then, but it will run > much faster. > > Finally, if you look at the 20 accepted Python solutions: > > http://www.spoj.pl/ranks/FCTRL/lang=PYTH > > you'll see that the top 5 all used enormously more memory than the > other 15. That's an almost-certain sign that they used psyco (which > the SPOJ folks have installed), like so: > > # the rest of the code goes here > > import psyco > psyco.full() > > if __name__ == "__main__": > main() > > Note that psyco doesn't always help -- sometimes it makes a program > slower. > > As the 15 other accepted Python solutions show, it's not necessary to > use psyco to meet the time limit for this problem. If I could, I'd > retract my run using psyco and settle for a non-psyco run -- I > couldn't care less about being "the fastest" on these, and just > /tried/ psyco here out of professional curiousity. Alas, SPOJ only > remembers the fastest correct run you submit. > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061008/4adfe5aa/attachment.html From alan.gauld at freenet.co.uk Mon Oct 9 01:34:15 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 9 Oct 2006 00:34:15 +0100 Subject: [Tutor] Fw: pretty_printing Message-ID: <000301c6eb32$44f8b540$0201a8c0@XPpro> Forwarding to the list for interests sake, mainly for vim users. ----- Original Message ----- From: "LandSurveyor" Sent: Monday, October 09, 2006 12:00 AM Subject: Re: pretty_printing > This issue has been solved! in a big way!! > (I hope I'm doing this right, replying to your email this way...I'm > new to this. Hope this makes its' way to the 'big screen') > > The entire issue [that I raised] regarding printing scripts with the > same syntax highlighting with which they were displayed in the Vim > editor turn out to be a Vim issue, and Vim solves it in an elegant, > rich way. By using the command, > > ":hardcopy" > > (from within the Vim editor) a printout of the current file [being > edited] is produced, with very rich colors, faithful to the > displayed syntax colors. Two companion :help 'modules' provide a > smorgasbord of options to apply to the desired hardcopy. They are: > > ":printoptions", and > ":printfont" > > Ask for ":help" with either of the two options listed above, and a > very clear and detailed file is offered in each case, from which to > draw examples and/or specific coding types. > > -----Original Message----- >>From: Alan Gauld >>Sent: Sep 3, 2006 7:03 PM >>To: "Lowell H. Tackett" >>Subject: Re: pretty_printing >> >>> It had occured to me that the root of my lack of success is simply >>> that file >>> XYZ.py sits on my HD as a simple string of X's and O's, not as a >>> pretty, >>> colorful text repository. Only thru the magic of say, Vim, is the >>> display >>> converted to meaningful hues. Therefor, Vim somehow knows how to >>> detect each >>> of the discrete syntax types: comments, quotes, reserved words, >>> etc., and to >>> apply an appropriate color into its' display. >> >>No magic, the patterns are defined in the xxxx.vim files in the >>syntax >>folder. >>Each one defines a keyword/style and the regex that defines the >>terms. >> >>> It occured to me that it ought to be very simple to gain access to >>> those >>> syntax discrimnators, write a code script that creates a 'dye' for >>> each >>> syntax type, and pipe a print request thru such a file. >> >>Yes, not impossible, but not trivial either. >>The simplest way to generate the printed output is probably to >>create an intermediate html file and print that via a browser >>- possibly using the python browser module... >> >>Alan Gauld >>Author of the Learn to Program web site >>http://www.freenetpages.co.uk/hp/alan.gauld >> > From ph34r_th3_d4rkn3s at hotmail.com Mon Oct 9 03:47:43 2006 From: ph34r_th3_d4rkn3s at hotmail.com (max .) Date: Sun, 08 Oct 2006 19:47:43 -0600 Subject: [Tutor] embedding python Message-ID: hello i have a myspace and a blog both of wich allow me to input html and i know a little html not much i can make a page with backround coler a title words and pictures as well as links but i cant find any tutorials on embedding python useing html i found some that use c++ and i think one that used asp if anyone knows how or knows of a tutorial that would be great ^_^" s33 y4 _________________________________________________________________ Share your special moments by uploading 500 photos per month to Windows Live Spaces http://clk.atdmt.com/MSN/go/msnnkwsp0070000001msn/direct/01/?href=http://www.get.live.com/spaces/features From rabidpoobear at gmail.com Mon Oct 9 03:49:36 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sun, 08 Oct 2006 20:49:36 -0500 Subject: [Tutor] embedding python In-Reply-To: References: Message-ID: <4529AAB0.1000702@gmail.com> max . wrote: > hello i have a myspace and a blog both of wich allow me to input html and i > know a little html not much i can make a page with backround coler a title > words and pictures as well as links > > but i cant find any tutorials on embedding python useing html i found some > that use c++ and i think one that used asp > > if anyone knows how or knows of a tutorial that would be great > > > your http server has to be capable of running python code.... examples of hosts that aren't: myspace other blog sites :) > ^_^" s33 y4 > > _________________________________________________________________ > Share your special moments by uploading 500 photos per month to Windows Live > Spaces > http://clk.atdmt.com/MSN/go/msnnkwsp0070000001msn/direct/01/?href=http://www.get.live.com/spaces/features > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From arunkumarpg at gmail.com Mon Oct 9 06:01:03 2006 From: arunkumarpg at gmail.com (Arun Kumar PG) Date: Mon, 9 Oct 2006 09:31:03 +0530 Subject: [Tutor] Tkinter and python In-Reply-To: <20061008162010.GB49387@cutter.rexx.com> References: <3cffff920610080806y6901922ar9fe027e6bda4eea3@mail.gmail.com> <20061008162010.GB49387@cutter.rexx.com> Message-ID: <3cffff920610082101w4ca43e8ew900b916ce89d2b34@mail.gmail.com> > python on the command prompt/bash shell the script gets > executed. Hey Dave, Thanks for correcting me. I should read what I am writing before I hit the send button :). It was a stupid mistake.. Appending path to PYTHONPATH will allow us to import the module in some other Python script without requiring us to do sys.path.apend(). To execute the script from bash what Dave suggests is correct. Also, if you don't want to append path to PYTHONPATH you can also place the module under site-packages directory under Python home directory. Thanks, - A On 10/8/06, Dave Kuhlman wrote: > > On Sun, Oct 08, 2006 at 08:36:31PM +0530, Arun Kumar PG wrote: > > Hi, > > > > You can try: > > > > >>import sys > > >>sys.path.append('') > > >>import > > > > Or else you can append the path to global PYTHONPATH environment > variable > > and whenever you will type: > > > > python on the command prompt/bash shell the script gets > > executed. > > > > Not true, if I understand you correctly. PYTHONPATH affects where > Python looks for modules to be imported. But if I type the > following at the command line: > > $ python mymodule.py > > it is the shell (in my case bash) that looks for mymodule.py, not > Python. It analogous to my typing: > > $ vi mymodule.py > > or (trying to avoid a fight between vi and emacs fanatics): > > $ emacs mymodule.py > > Neither vi nor emacs try to find mymodule.py; the (bash or other) > shell does. > > So perhaps a solution to the problem is to make mymodule.py > executable and put it somewhere on your path. Then execute it by > typing at the command line: > > $ mymodule.py > > Now the shell will run it just like any other executable script and > it will use Python as the interpreter for that script. > > How you make the script executable probably depends on which shell > you are using. For bash, you could do the following: > > 1. Insert the following line as the first line of your script: > > #!/usr/bin/env python > > 2. Change the priveleges of the script to make it executable. > Example: > > $ chmod u+x mymodule.py > > 3. Put mymodule.py on your path, that is, in a directory that is in > your PATH environment variable. Alternatively, add the path to > the directory containing mymodule.py to your PATH environment > variable. > > Dave > > -- > Dave Kuhlman > http://www.rexx.com/~dkuhlman > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061009/930b1553/attachment.html From hugonz-lists at h-lab.net Sun Oct 8 19:11:56 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Sun, 08 Oct 2006 11:11:56 -0600 Subject: [Tutor] question about looping. In-Reply-To: <452621DE.7070200@nc.rr.com> References: <452621DE.7070200@nc.rr.com> Message-ID: <4529315C.3090000@h-lab.net> Doug Potter wrote: > for i in routers: > os.system('/bin/touch' %s) % i > > of course this dosn't work. > > Is there a simple way to get this done? Yep, someone already answered that you can create the file in write mode and then close it, but I wanted to add a little more in why your solution doesn't work. You're not interpolating the filename INTO the os.system string The following would work for i in routers: os.system('/bin/touch %s'%1) Granted, you should also provide a filename with a full path for simplicity. HTH Hugo From hugonz-lists at h-lab.net Sun Oct 8 20:01:12 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Sun, 08 Oct 2006 12:01:12 -0600 Subject: [Tutor] byte[] array In-Reply-To: <4522e66a.43b22ef0.07ad.ffffa559@mx.gmail.com> References: <4522e66a.43b22ef0.07ad.ffffa559@mx.gmail.com> Message-ID: <45293CE8.9030600@h-lab.net> gert wohlgemuth wrote: > As anybody an idea how I can do this in python? I can think of three ways: Strings in Python can contain arbitrary binary values, so they can be used. If they're going to be modified often, you may use a list, or you may use the array module for performance. Are you sure you cannot use any already written module? Are you getting data from the http protocol? are you using XML-RPC or something like this? Hugo From alan.gauld at btinternet.com Mon Oct 9 09:20:52 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 9 Oct 2006 08:20:52 +0100 Subject: [Tutor] embedding python References: Message-ID: > know a little html not much i can make a page with backround coler a > title > words and pictures as well as links > > but i cant find any tutorials on embedding python useing html i > found some > that use c++ and i think one that used asp Can you give an example of what you mean by *embedding* Python using html? You can represent python code inside HTML easily enough. You can insert Python code into your HTML as script, but it will only work if the readers browser supports it - only IE at present. Or you can do server side python code if the server supports it. What exactly do you have in mind? What were you aiming to achieve? Alan G From janos.juhasz at VELUX.com Mon Oct 9 10:06:59 2006 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Mon, 9 Oct 2006 10:06:59 +0200 Subject: [Tutor] Help me with two dimensional arrays in Python In-Reply-To: Message-ID: Dear Asrarahmed, I have found the next recipe in the cookbook. It should be interesting for you :) http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/392153 > Message: 1 > Date: Thu, 05 Oct 2006 10:26:19 -0400 > From: Kent Johnson > Subject: Re: [Tutor] Help me with two dimensional arrays in Python > Cc: tutor at python.org > Message-ID: <4525160B.3040709 at tds.net> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > Asrarahmed Kadri wrote: > > Its something very close. > > What I want is: > > > > 1 > > 1 1 > > 1 2 1 > > 1 3 3 1 > > 1 4 6 4 1 Yours sincerely, ______________________________ J?nos Juh?sz From picioslug at gmail.com Mon Oct 9 10:10:30 2006 From: picioslug at gmail.com (Picio) Date: Mon, 9 Oct 2006 10:10:30 +0200 Subject: [Tutor] python RMI In-Reply-To: <6122a57a0610071423w36d0cb28l4f86146dbd157065@mail.gmail.com> References: <825bef0c0610070607w5310f46ahceb9d8c277c7333d@mail.gmail.com> <6122a57a0610071423w36d0cb28l4f86146dbd157065@mail.gmail.com> Message-ID: <825bef0c0610090110y34fe25c4t86eb1d79123990db@mail.gmail.com> Hello, I was out for the week-end, sorry If I'm so late answering, and sorry because I wrote my message In italian. Since I have a subscription to another python mailing-list in italian, I've confused the tutor list with that. Thanks, I'm impressed, you were so kind triyng to help me!! I read the all articles at http://www.daimi.au.dk/~mailund/scripting2005/lecture-notes/rmi.html thanks, now I got a very good Idea about RMI and also, web services. Ps.: Ivan grazie di cuore dell'intervento! Daniele 2006/10/7, Ivan Furone : > > > Il 07/10/06, Alan Gauld ha scritto: > > > > PS. Any Italian speakers on the list who can cover this? > > > I think I can as far it's possible,Alan! :-) > > > > "Picio" wrote in message > > > news:825bef0c0610070607w5310f46ahceb9d8c277c7333d at mail.gmail.com... > > Salve, > > dovrei usare python per due progettini universitari, su RMI e l'altro > > sui Web Services. > > Ho notato che esiste PyRO, preferirei per? sentire voi sull'argomento: > > > > cosa uso per l'RMI (esiste qualche libreria,modulo....) > > cosa uso per i Web Services > > > Ciao, > Per quanto riguarda l'RMI vale la pena di dare un'occhiata a > quest'esempio,anche se in inglese in quanto il codice e'di per se abbastanza > comprensibile: > > http://www.daimi.au.dk/~mailund/scripting2005/lecture-notes/rmi.html > > Per quanto riguarda i web services,e'impossibile darti una risposta precisa > senza poter conoscere i servizi che devi (o dovresti) utilizzare; prova a > girare nella standard library,magari a guardare XML-RPC come altri ti hanno > gia'detto;comunque,se cerchi qualcosa di piu'dedicato usa Twisted che > e'sicuramente l'eccellenza nel campo della programmazione di rete in Python > per completezza e maturita'del codice. > Mentre per eventuali ritocchi e implementazione di particolari > funzionalita'di basso livello esiste dpkt.. > > Fai la tua scelta,spero di essere stato esaustivo. > > ______________________________ > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From picioslug at gmail.com Mon Oct 9 10:19:59 2006 From: picioslug at gmail.com (Picio) Date: Mon, 9 Oct 2006 10:19:59 +0200 Subject: [Tutor] a Apache-python-postgres kit Message-ID: <825bef0c0610090119i2a38d0c5ob22d17a669f66c41@mail.gmail.com> Hello, last week I configured three home made servers to host a little python web app (django based). Searching on the web about a kit/script to have Apache+PostgreSQL+Python, I found only Apache2triad. That is a littlel "overweight" for me because I got also: PHP Perl Mysql Slimftpd Xmail OpenSSL and some other staff I really don't need. Do you know a kit like WAMP or LAMP, that install one of the following configurations? 1-Apache+Posgtres+Python 2-Lighttpd+Posgtgres+Python Do you know some docs to help me create myself the kit? (Something like "How to make your own 'wamp' server") Thanks for any answer Daniele From janos.juhasz at VELUX.com Mon Oct 9 10:54:41 2006 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Mon, 9 Oct 2006 10:54:41 +0200 Subject: [Tutor] Point in polygon intro please~! In-Reply-To: Message-ID: Hi Michael, > Subject: Re: [Tutor] Point in polygon intro please~! > To: Michael Shulman > Cc: tutor at python.org > Message-ID: <4527AA35.4030000 at tds.net> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > Michael Shulman wrote: > > Hello, I'm very new to both python and OpenGL, but I'm catching on > > pretty quick, > > and trying to make a little game. I'm stuck on being able to do this > > point-in-polygon test though. > > Everyone seems to say that I should create a ray and see how many sides > > of a polygon it intersects, (even vs odd) > > but I have no idea how to go about setting this up. If you would like to get the 3D object, that belongs to the given pixel, OpenGL gives a simpler way for it with glRenderMode(GL_SELECT); Converting the 3D objects to poligons, seems to be too difficult, and not needed. Take a look after the GL_SELECT mode http://www.google.hu/search?hl=hu&q=glRenderMode%28GL_SELECT%29&meta= Yours sincerely, ______________________________ J?nos Juh?sz From duncan at thermal.esa.int Mon Oct 9 12:58:47 2006 From: duncan at thermal.esa.int (Duncan Gibson) Date: Mon, 09 Oct 2006 12:58:47 +0200 Subject: [Tutor] Handling large arrays/lists Message-ID: <20061009105847.4867922B6@zeeman.thermal.esa.int> One part of the application I'm dealing with handles a conceptual 'cube' of data, but is in fact implemented as a single python list. Items are stored and retrieved - no manipulation at the moment - by the classical approach of multiplying the appropriate x, y and z indices with the x, y and z extents to give the unique index into the single list. However, now that requirements have moved to include much larger cubes of data than originally envisaged, this single list has just become far too slow. Unfortunately the single list concept is currently a requirement in the tool, but how it is implemented is open to discussion. I've been mulling over the documentation for Numeric/numpy to see whether it makes sense to replace the single standard Python list with an array or multiarray. The first thing to strike me is that, in Numeric, the size of an array is fixed. To grow the 'cube' as each x,y slice is added, I can create a new array in one of three ways, but as far as I can see, each will require copying all of the data from the old to the new array, so I'm concerned that any speed benefit gained from replacing a standard list will be lost to repeated copying. Have I correctly understood the Numeric array handling? Does anyone have any suggestions for a more efficient way of handling a large list of data? Other modules perhaps? And yes, I know that Numeric has been replaced by numpy, but I understand that they are very similar, and it's been easier to find tutorial documentation for Numeric than for numpy. Cheers Duncan From abdullah.anar at gmail.com Mon Oct 9 13:23:32 2006 From: abdullah.anar at gmail.com (Abdullah Anar) Date: Mon, 9 Oct 2006 14:23:32 +0300 Subject: [Tutor] tkinter Message-ID: <71e07f040610090423i116a093fpff0a97a2c9bce28e@mail.gmail.com> hello, We try to build new software using python and tkinter. We would like to enter some fields using grid style. I mean we want to use rows to see old entries and to enter new one. I hope I could explain, because it also is not easy. I know there is grid to locate buttons, labels and something like these. I hope I could explain I did not mean this grid which is using instead of pack. we wonder if there is already some classes or widgets to do this. thanks for help from now Abdullah Anar -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061009/41a5ee23/attachment.html From tiagosaboga at terra.com.br Mon Oct 9 14:21:42 2006 From: tiagosaboga at terra.com.br (Tiago Saboga) Date: Mon, 9 Oct 2006 09:21:42 -0300 Subject: [Tutor] re-reading file-like objects Message-ID: <200610090921.43214.tiagosaboga@terra.com.br> Hi! I have a problem with file-like objects for months now, and I hoped I could cope with it, but I keep using what seems to me like a newbie workaround... The question is: how can I read a file (more precisely, a file-like object) more than one single time? In the following example, I want to generate a file in memory and save it with ten different names. But I can't do it with shutil.copyfileobj, AFAICS because it reads the file with read() method, which can only be used once. If it's a real file, on disk, I agree it would not be a clever strategy, reading it once for each copy, and I would be happy keeping its content in a variable. But if the file is in memory, why can't I simply read it again (or better, how can I...)? ====================successful================== import subprocess FILESIZE = 200000 NUMBER = 10 DIR = '/tmp/pytest' FILENAME = 'treco.x' basefilecontents = subprocess.Popen(['dd', 'if=/dev/zero', 'count=1', 'bs=%s' % FILESIZE], stdout=subprocess.PIPE, bufsize=FILESIZE).stdout.read() for i in range(NUMBER): print "File number %s" % i newfile = open('%s/%s%s' % (DIR, FILENAME, i), 'w') newfile.write(basefilecontents) newfile.close() =====================unsuccessful================== import subprocess, shutil FILESIZE = 200000 NUMBER = 10 DIR = '/tmp/pytest' FILENAME = 'treco.x' basefile = subprocess.Popen(['dd', 'if=/dev/zero', 'count=1', 'bs=%s' % FILESIZE], stdout=subprocess.PIPE, bufsize=FILESIZE).stdout for i in range(NUMBER): print "File number %s" % i newfile = open('%s/%s%s' % (DIR, FILENAME, i), 'w') shutil.copyfileobj(basefile, newfile) newfile.close() ========================================================= The program runs fine, but only the first file has the appropriate content. From tiagosaboga at terra.com.br Mon Oct 9 14:44:54 2006 From: tiagosaboga at terra.com.br (Tiago Saboga) Date: Mon, 9 Oct 2006 09:44:54 -0300 Subject: [Tutor] re-reading file-like objects (SOLVED?) In-Reply-To: <200610090921.43214.tiagosaboga@terra.com.br> References: <200610090921.43214.tiagosaboga@terra.com.br> Message-ID: <200610090944.57375.tiagosaboga@terra.com.br> I keep the original question: Em Segunda 09 Outubro 2006 09:21, Tiago Saboga escreveu: > Hi! > > I have a problem with file-like objects for months now, and I hoped I could > cope with it, but I keep using what seems to me like a newbie workaround... > > The question is: how can I read a file (more precisely, a file-like object) > more than one single time? > > In the following example, I want to generate a file in memory and save it > with ten different names. But I can't do it with shutil.copyfileobj, AFAICS > because it reads the file with read() method, which can only be used once. > If it's a real file, on disk, I agree it would not be a clever strategy, > reading it once for each copy, and I would be happy keeping its content in > a variable. But if the file is in memory, why can't I simply read it again > (or better, how can I...) But I strip the code, and post a new one. The solution I found is in the seek() method of the file object. And the problem I had is that not all the file-like objects have a functional seek() method. It's not the case for the object referenced by the stdout attribute of the subprocess.Popen class. So I have to copy it in a (seekable) temporary file. As I have already bothered you with my question, let's try to make it still useful: is it the "right" (or pythonic) way to do this? Thanks, Tiago. ============solution================ import subprocess, shutil, tempfile FILESIZE = 200000 NUMBER = 10 DIR = '/tmp/pytest' FILENAME = 'treco.x' cmd = ['dd', 'if=/dev/zero', 'count=1', 'bs=%s' % FILESIZE] tempbasefile = tempfile.TemporaryFile() basefile = subprocess.Popen( cmd, stdout=subprocess.PIPE, bufsize=FILESIZE ).stdout shutil.copyfileobj(basefile, tempbasefile) for i in range(NUMBER): tempbasefile.seek(0) print "File number %s" % i newfile = open('%s/%s%s' % (DIR, FILENAME, i), 'w') shutil.copyfileobj(tempbasefile, newfile) newfile.close() From alan.gauld at btinternet.com Mon Oct 9 15:00:26 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 9 Oct 2006 14:00:26 +0100 Subject: [Tutor] tkinter References: <71e07f040610090423i116a093fpff0a97a2c9bce28e@mail.gmail.com> Message-ID: > We try to build new software using python and tkinter. We would like > to > enter some fields using grid style. Based on the fact that you say: > these. I hope I could explain I did not mean this grid which is > using > instead of pack. I assume you mean like a spreadsheet grid of cells? > we wonder if there is already some classes or widgets to do this. I'm not aware of such a control but its quite likely someone has built one. Try asking on the Tkinter mailing list, they are more likely to know. Sorry I can't help further, Alan G. From hugonz at h-lab.net Sun Oct 8 19:47:18 2006 From: hugonz at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Sun, 08 Oct 2006 11:47:18 -0600 Subject: [Tutor] revisiting struct and bytes again. In-Reply-To: <384c93600610041035r18f8f9f7ubfeb91c468886faa@mail.gmail.com> References: <384c93600610041035r18f8f9f7ubfeb91c468886faa@mail.gmail.com> Message-ID: <452939A6.9020701@h-lab.net> > i can make a byte a string or number or whatever now. Up to the number 255. > I now have a problem with something that comes in as a 4 byte > representation of > the number of seconds since 1970. Hi Shawn, That's an epoch time as used in UNIX. Are you sure that what you're trying to do cannot be done with the Python time module? What is it exactly that you're trying to do? Hugo From kent37 at tds.net Mon Oct 9 15:41:21 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 09 Oct 2006 09:41:21 -0400 Subject: [Tutor] re-reading file-like objects In-Reply-To: <200610090921.43214.tiagosaboga@terra.com.br> References: <200610090921.43214.tiagosaboga@terra.com.br> Message-ID: <452A5181.6090702@tds.net> Tiago Saboga wrote: > Hi! > > I have a problem with file-like objects for months now, and I hoped I could > cope with it, but I keep using what seems to me like a newbie workaround... > > The question is: how can I read a file (more precisely, a file-like object) > more than one single time? > > In the following example, I want to generate a file in memory and save it with > ten different names. But I can't do it with shutil.copyfileobj, AFAICS > because it reads the file with read() method, which can only be used once. If > it's a real file, on disk, I agree it would not be a clever strategy, reading > it once for each copy, and I would be happy keeping its content in a > variable. But if the file is in memory, why can't I simply read it again (or > better, how can I...)? > > ====================successful================== > import subprocess > > FILESIZE = 200000 > NUMBER = 10 > DIR = '/tmp/pytest' > FILENAME = 'treco.x' > > basefilecontents = > subprocess.Popen(['dd', 'if=/dev/zero', 'count=1', 'bs=%s' % FILESIZE], > stdout=subprocess.PIPE, bufsize=FILESIZE).stdout.read() > > for i in range(NUMBER): > print "File number %s" % i > newfile = open('%s/%s%s' % (DIR, FILENAME, i), 'w') > newfile.write(basefilecontents) > newfile.close() Your input file isn't 'in memory', it is the output of a subprocess. To read the input again, the subprocess would have to create the output again. This solution seems fine to me - you read the input file *contents* into memory, then write it to multiple files. Why don't you like this approach? Kent From kent37 at tds.net Mon Oct 9 15:43:39 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 09 Oct 2006 09:43:39 -0400 Subject: [Tutor] re-reading file-like objects (SOLVED?) In-Reply-To: <200610090944.57375.tiagosaboga@terra.com.br> References: <200610090921.43214.tiagosaboga@terra.com.br> <200610090944.57375.tiagosaboga@terra.com.br> Message-ID: <452A520B.20804@tds.net> Tiago Saboga wrote: > But I strip the code, and post a new one. The solution I found is in the > seek() method of the file object. And the problem I had is that not all the > file-like objects have a functional seek() method. It's not the case for the > object referenced by the stdout attribute of the subprocess.Popen class. So I > have to copy it in a (seekable) temporary file. As I have already bothered > you with my question, let's try to make it still useful: is it the "right" > (or pythonic) way to do this? > > Thanks, > > Tiago. > > ============solution================ > import subprocess, shutil, tempfile > > FILESIZE = 200000 > NUMBER = 10 > DIR = '/tmp/pytest' > FILENAME = 'treco.x' > > cmd = ['dd', 'if=/dev/zero', 'count=1', 'bs=%s' % FILESIZE] > tempbasefile = tempfile.TemporaryFile() > > basefile = subprocess.Popen( > cmd, > stdout=subprocess.PIPE, > bufsize=FILESIZE > ).stdout > > shutil.copyfileobj(basefile, tempbasefile) > > for i in range(NUMBER): > tempbasefile.seek(0) > print "File number %s" % i > newfile = open('%s/%s%s' % (DIR, FILENAME, i), 'w') > shutil.copyfileobj(tempbasefile, newfile) > newfile.close() This is similar to your first successful solution in a way - you are reading the contents of the input file and storing them in a temporary location. In the first version you stored the contents in memory; in this one you store the contents in a temp file. Unless the data is too large to fit in memory I think the first program is preferable, it is simpler and will likely be faster. Kent From alan.gauld at btinternet.com Mon Oct 9 19:00:11 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 9 Oct 2006 18:00:11 +0100 Subject: [Tutor] re-reading file-like objects References: <200610090921.43214.tiagosaboga@terra.com.br> Message-ID: > because it reads the file with read() method, which can only be used > once. If > it's a real file, on disk, I agree it would not be a clever > strategy, reading > it once for each copy, and I would be happy keeping its content in a > variable. But if the file is in memory, why can't I simply read it > again (or > better, how can I...)? Not all file like objects support the seek() call, often for good reasons - they are streams for example. However it sounds like you could use a StringIO buffer object for what you want and you can reuse that as often as you like. Look here for more info: http://docs.python.org/lib/module-StringIO.html HTH -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld > > ====================successful================== > import subprocess > > FILESIZE = 200000 > NUMBER = 10 > DIR = '/tmp/pytest' > FILENAME = 'treco.x' > > basefilecontents = > subprocess.Popen(['dd', 'if=/dev/zero', 'count=1', 'bs=%s' % > FILESIZE], > stdout=subprocess.PIPE, bufsize=FILESIZE).stdout.read() > > for i in range(NUMBER): > print "File number %s" % i > newfile = open('%s/%s%s' % (DIR, FILENAME, i), 'w') > newfile.write(basefilecontents) > newfile.close() > > =====================unsuccessful================== > > import subprocess, shutil > > FILESIZE = 200000 > NUMBER = 10 > DIR = '/tmp/pytest' > FILENAME = 'treco.x' > > basefile = subprocess.Popen(['dd', 'if=/dev/zero', 'count=1', > 'bs=%s' % > FILESIZE], stdout=subprocess.PIPE, bufsize=FILESIZE).stdout > > for i in range(NUMBER): > print "File number %s" % i > newfile = open('%s/%s%s' % (DIR, FILENAME, i), 'w') > shutil.copyfileobj(basefile, newfile) > newfile.close() > > ========================================================= > The program runs fine, but only the first file has the appropriate > content. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From josipl2000 at yahoo.com Mon Oct 9 19:51:26 2006 From: josipl2000 at yahoo.com (josip) Date: Mon, 9 Oct 2006 10:51:26 -0700 (PDT) Subject: [Tutor] What after Learning Python 2nd Message-ID: <20061009175126.36497.qmail@web60817.mail.yahoo.com> Hi. Hi I have finished Learning Python 2nd ed. What to do next? Should I go with Programming Python book or Python Cookbook or? Or maybe something else? Thanks people! --------------------------------- Do you Yahoo!? Get on board. You're invited to try the new Yahoo! Mail. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061009/542aad1b/attachment.html From tiagosaboga at terra.com.br Mon Oct 9 19:54:42 2006 From: tiagosaboga at terra.com.br (Tiago Saboga) Date: Mon, 9 Oct 2006 14:54:42 -0300 Subject: [Tutor] re-reading file-like objects In-Reply-To: <452A5181.6090702@tds.net> References: <200610090921.43214.tiagosaboga@terra.com.br> <452A5181.6090702@tds.net> Message-ID: <200610091454.42934.tiagosaboga@terra.com.br> Em Segunda 09 Outubro 2006 10:41, Kent Johnson escreveu: > Tiago Saboga wrote: > > Hi! > > > > I have a problem with file-like objects for months now, and I hoped I > > could cope with it, but I keep using what seems to me like a newbie > > workaround... > > > > The question is: how can I read a file (more precisely, a file-like > > object) more than one single time? > > > > In the following example, I want to generate a file in memory and save it > > with ten different names. But I can't do it with shutil.copyfileobj, > > AFAICS because it reads the file with read() method, which can only be > > used once. If it's a real file, on disk, I agree it would not be a clever > > strategy, reading it once for each copy, and I would be happy keeping its > > content in a variable. But if the file is in memory, why can't I simply > > read it again (or better, how can I...)? > > > > ====================successful================== > > import subprocess > > > > FILESIZE = 200000 > > NUMBER = 10 > > DIR = '/tmp/pytest' > > FILENAME = 'treco.x' > > > > basefilecontents = > > subprocess.Popen(['dd', 'if=/dev/zero', 'count=1', 'bs=%s' % FILESIZE], > > stdout=subprocess.PIPE, bufsize=FILESIZE).stdout.read() > > > > for i in range(NUMBER): > > print "File number %s" % i > > newfile = open('%s/%s%s' % (DIR, FILENAME, i), 'w') > > newfile.write(basefilecontents) > > newfile.close() > > Your input file isn't 'in memory', it is the output of a subprocess. To > read the input again, the subprocess would have to create the output again. > > This solution seems fine to me - you read the input file *contents* into > memory, then write it to multiple files. Why don't you like this approach? I'm afraid I don't fully understand file objects. I thought I could use it just as a file: if I have one, and I want several copies, I just save it with several names. So, if Popen.stdout already is a file object, I thought the easier way would be to save it with another name. I see that it is more complicated. For this simple example, this solution is fine, and I think the solution proposed by Alan (StringIO) is not going to add anything. Would it be faster? Thanks, Tiago. > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From rob.andrews at gmail.com Mon Oct 9 19:55:33 2006 From: rob.andrews at gmail.com (Rob Andrews) Date: Mon, 9 Oct 2006 12:55:33 -0500 Subject: [Tutor] What after Learning Python 2nd In-Reply-To: <20061009175126.36497.qmail@web60817.mail.yahoo.com> References: <20061009175126.36497.qmail@web60817.mail.yahoo.com> Message-ID: <8d757d2e0610091055u6dd3f841od041c6219ad2c0c1@mail.gmail.com> Those are both fine "next book" choices, and neither should prove a disapointment. However, LP should've left you with just enough knowledge to be dangerous, so I'd encourage you to work on several small projects in python using what you already know. In the process of taking a crack at those, you'll surely want to do some things that will give you a good idea of what resources you need to tackle next. -Rob A. On 10/9/06, josip wrote: > Hi. > > Hi I have finished Learning Python 2nd ed. > What to do next? > Should I go with Programming Python book or Python Cookbook or? > Or maybe something else? From tiagosaboga at terra.com.br Mon Oct 9 20:24:50 2006 From: tiagosaboga at terra.com.br (Tiago Saboga) Date: Mon, 9 Oct 2006 15:24:50 -0300 Subject: [Tutor] Variable help In-Reply-To: References: Message-ID: <200610091524.50777.tiagosaboga@terra.com.br> Hi! I think your problem was solved, and that the list of lists is the better approach indeed. But I'd like to add an answer to a direct question you asked: Em Domingo 08 Outubro 2006 07:47, Tom R. escreveu: > Basically I want to be able to integrate the value of one variable into > another variables name. I think you would like to do something like: ================================= #!/usr/bin/env python # use of __get_attribute__() function class players(object): player1 = [2,4,8] player2 = [3,9,27] player3 = [4,16,64] count = 2 pl = players() actual_player_string = "player%s" % count if pl.__getattribute__(actual_player_string)[2]==9: print 'It worked.' =================================== I don't know how to do that if player{1,2,3} are not in a class, or if the class is not instanciated. But somebody else can possibly show a way. Anyway, as I said, I think you don't need it right now. Tiago. From kent37 at tds.net Mon Oct 9 20:51:30 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 09 Oct 2006 14:51:30 -0400 Subject: [Tutor] Variable help In-Reply-To: <200610091524.50777.tiagosaboga@terra.com.br> References: <200610091524.50777.tiagosaboga@terra.com.br> Message-ID: <452A9A32.8010209@tds.net> Tiago Saboga wrote: > Hi! > > I think your problem was solved, and that the list of lists is the better > approach indeed. But I'd like to add an answer to a direct question you > asked: > > Em Domingo 08 Outubro 2006 07:47, Tom R. escreveu: >> Basically I want to be able to integrate the value of one variable into >> another variables name. > > I think you would like to do something like: > > ================================= > #!/usr/bin/env python > # use of __get_attribute__() function > class players(object): > player1 = [2,4,8] > player2 = [3,9,27] > player3 = [4,16,64] > > count = 2 > pl = players() > actual_player_string = "player%s" % count > > if pl.__getattribute__(actual_player_string)[2]==9: > print 'It worked.' Better to use the built-in getattr() function: geattr(pl, actual_player_string) > =================================== > > I don't know how to do that if player{1,2,3} are not in a class, or if the > class is not instanciated. But somebody else can possibly show a way. There are ways to do it but really it's better not to. Kent From wescpy at gmail.com Mon Oct 9 21:01:20 2006 From: wescpy at gmail.com (wesley chun) Date: Mon, 9 Oct 2006 12:01:20 -0700 Subject: [Tutor] What after Learning Python 2nd In-Reply-To: <8d757d2e0610091055u6dd3f841od041c6219ad2c0c1@mail.gmail.com> References: <20061009175126.36497.qmail@web60817.mail.yahoo.com> <8d757d2e0610091055u6dd3f841od041c6219ad2c0c1@mail.gmail.com> Message-ID: <78b3a9580610091201o2ce6ea7dr88a9e2e7270561d7@mail.gmail.com> > > Hi I have finished Learning Python 2nd ed. > > What to do next? > > Should I go with Programming Python book or Python Cookbook or? > > Or maybe something else? > > However, LP should've left you with just enough knowledge to be > dangerous, so I'd encourage you to work on several small projects in > python using what you already know. In the process of taking a crack > at those, you'll surely want to do some things that will give you a > good idea of what resources you need to tackle next. hi josip, rob is right. you should really start cranking out some code. from the book perspective, LP is similar to Beginning Python (Hetland) or Dive into Python (Pilgrim), all of which are great intros to get your feet wet with Python. the two books you suggested point you in different directions: Programming Python should be used if you want to see many different case studies using Python in all kinds of ways, most with large bodies of application code. The Cookbook is used to see code snippets to perform specific tasks. the code is usually much shorter are typically not complete applications. another (unbiased?) suggestion would be my book, Core Python, which just came out a few weeks ago. it takes the 3 books i mentioned above and dives much deeper into how Python works under the covers, with the goal of making you more of an effective Python programmer in as short of a time as possible. plus there are many interesting exercises at the end of every chapter, a great place to start really getting some coding under your belt. hope this helps and good luck! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From gsf at panix.com Mon Oct 9 21:20:56 2006 From: gsf at panix.com (Gabriel Farrell) Date: Mon, 9 Oct 2006 15:20:56 -0400 Subject: [Tutor] What after Learning Python 2nd In-Reply-To: <20061009175126.36497.qmail@web60817.mail.yahoo.com> References: <20061009175126.36497.qmail@web60817.mail.yahoo.com> Message-ID: <20061009192056.GT12260@panix.com> On Mon, Oct 09, 2006 at 10:51:26AM -0700, josip wrote: > Hi. > > Hi I have finished Learning Python 2nd ed. > What to do next? > Should I go with Programming Python book or Python Cookbook or? > Or maybe something else? > > Thanks people! > I went from Learning Python to the Python Cookbook and have been very happy. The Cookbook is loaded with great tips in pretty much every area of programming, and it's great to get so many insights. I've also been pleasantly surprised by the usefulness of the intros to each section, written by some of the superstars of the Python community. gabe > > > --------------------------------- > Do you Yahoo!? > Get on board. You're invited to try the new Yahoo! Mail. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From Joel.Levine at Dartmouth.EDU Mon Oct 9 21:43:01 2006 From: Joel.Levine at Dartmouth.EDU (Joel Levine) Date: 09 Oct 2006 15:43:01 -0400 Subject: [Tutor] Menus / Mac Message-ID: <69354003@newdancer.Dartmouth.EDU> I'm trying to learn menus, starting with a textbook example. The textbook example (pasted below) doesn't work, but doesn't die either: It opens a window that has no menu. I'm guessing it is a Mac problem. I've tried it on 3 different Macs, with slightly different dates and configurations of Python and its libraries. Same story each time. But, mailing the same program to someone who pasted it into a PC program -- it was fine. On the Mac, I'm running straight from Terminal/Unix, that is, I'm not using IDLE. Hard to believe that something this basic would not be running & not be noticed -- but I'm at a loss. The program is below. Thanks, Joel Levine from Tkinter import * def callback(): print "called the callback!" root = Tk() # create a menu menu = Menu(root) root.config(menu=menu) filemenu = Menu(menu) menu.add_cascade(label="File", menu=filemenu) filemenu.add_command(label="New", command=callback) filemenu.add_command(label="Open...", command=callback) filemenu.add_separator() filemenu.add_command(label="Exit", command=callback) helpmenu = Menu(menu) menu.add_cascade(label="Help", menu=helpmenu) helpmenu.add_command(label="About...", command=callback) mainloop() From ajkadri at googlemail.com Mon Oct 9 23:04:17 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Mon, 9 Oct 2006 22:04:17 +0100 Subject: [Tutor] Seeking good resources for Tkinter Message-ID: Hi folks, I want to learn the GUI programming in Python. Can you suggest some nice web resources as well as books to start. Thanks in anticipation. Regards, Asrar -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061009/b780a9d7/attachment.html From john at fouhy.net Mon Oct 9 23:08:57 2006 From: john at fouhy.net (John Fouhy) Date: Tue, 10 Oct 2006 10:08:57 +1300 Subject: [Tutor] Menus / Mac In-Reply-To: <69354003@newdancer.Dartmouth.EDU> References: <69354003@newdancer.Dartmouth.EDU> Message-ID: <5e58f2e40610091408i3fb73ecdj400a3ae75d5f41bf@mail.gmail.com> On 09 Oct 2006 15:43:01 -0400, Joel Levine wrote: > I'm guessing it is a Mac problem. I've tried it on 3 different Macs, with slightly different dates and configurations of Python and its libraries. Same story each time. It works for me :-) (MBPro, Tiger) Remember that macs have a universal menu bar. If you click on the window it created, the menubar at the top should change appropriately. -- John. From alan.gauld at btinternet.com Tue Oct 10 00:46:05 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 9 Oct 2006 23:46:05 +0100 Subject: [Tutor] re-reading file-like objects References: <200610090921.43214.tiagosaboga@terra.com.br><452A5181.6090702@tds.net> <200610091454.42934.tiagosaboga@terra.com.br> Message-ID: > For this simple example, this solution is fine, and I think the > solution > proposed by Alan (StringIO) is not going to add anything. Would it > be faster? Probably not, the StringIO solution is just closer to how you described the problem, but also provides a fuller set of file-like methods, including seek(): >>> import StringIO >>> s = StringIO.StringIO() >>> s.write(''' ... here is some text ... that you can see''') >>> s.read() # at eof '' >>> s.seek(0) >>> s.read() # at start of file '\nhere is some text\nthat you can see' >>> HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From klappnase at freenet.de Tue Oct 10 00:43:25 2006 From: klappnase at freenet.de (Michael Lange) Date: Tue, 10 Oct 2006 00:43:25 +0200 Subject: [Tutor] tkinter In-Reply-To: References: <71e07f040610090423i116a093fpff0a97a2c9bce28e@mail.gmail.com> Message-ID: <20061010004325.4954cf9c.klappnase@freenet.de> On Mon, 9 Oct 2006 14:00:26 +0100 "Alan Gauld" wrote: > > We try to build new software using python and tkinter. We would like > > to > > enter some fields using grid style. > > Based on the fact that you say: > > > these. I hope I could explain I did not mean this grid which is > > using > > instead of pack. > > I assume you mean like a spreadsheet grid of cells? > > > we wonder if there is already some classes or widgets to do this. > > I'm not aware of such a control but its quite likely someone has > built one. Try asking on the Tkinter mailing list, they are more > likely to know. > As far as I know the tktable widget (http://tktable.sourceforge.net) is a quite advanced spreadsheet widget, and there is a Python wrapper module in the demos directory, I never used it though. Another option is the Tix.Grid, unfortunately there is only a partially implememted (and partially broken) python interface included in the Python-2.5 Tix module. For more functionality you can try the Tix.Grid wrapper I wrote a while ago (http://www.8ung.at/klappnase/TixGrid/TixGrid.html), however it is not much tested and the tixGrid itself seems to be alpha or beta quality, some methods do not seem to have any effect. I hope this helps Michael From klappnase at freenet.de Tue Oct 10 00:55:38 2006 From: klappnase at freenet.de (Michael Lange) Date: Tue, 10 Oct 2006 00:55:38 +0200 Subject: [Tutor] Seeking good resources for Tkinter In-Reply-To: References: Message-ID: <20061010005538.532ebc4a.klappnase@freenet.de> On Mon, 9 Oct 2006 22:04:17 +0100 "Asrarahmed Kadri" wrote: > Hi folks, > > I want to learn the GUI programming in Python. Can you suggest some nice web > resources as well as books to start. > > Thanks in anticipation. > Hi Asrar, for Tkinter a good place to start is the wiki: http://tkinter.unpy.net/wiki/ Several Tkinter books are mentioned here: http://tkinter.unpy.net/wiki/books where John Grayson's "Python and Tkinter programming" is (although it is a little outdated) still the ultimate resource. For a start the Tkinter reference from New Mexico Tech (http://infohost.nmt.edu/tcc/help/lang/python/tkinter.html) and Frederik Lundh's book (http://www.pythonware.com/library/tkinter/introduction/) are good, too (and they are free). I hope this helps Michael From alan.gauld at btinternet.com Tue Oct 10 01:07:09 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 10 Oct 2006 00:07:09 +0100 Subject: [Tutor] What after Learning Python 2nd References: <20061009175126.36497.qmail@web60817.mail.yahoo.com> Message-ID: > Hi I have finished Learning Python 2nd ed. > What to do next? Write code. Lots of code. Think of a project that will need more than a single file so you get practice with modules. Think of a project that can use OOP to practice with objects. Do some text processing, or write a web client to try out regular expressions or HTML parsing. In other words get some experience under your belt before worrying about advanced coding features etc. > Should I go with Programming Python book or > Python Cookbook Two very different books! Personally I would go for Programming Python because I've never been a fan of cookbook type books. They tend to encourage cut n' paste style reuse where you don't necessarily understand the why. I prefer the wider coverage of PP with lots of "real code". But its a very personal choice, one of my colleaguers loves cookbooks and has one for each of the different languages we use. I do recommend a reference book too, like the Beasley or Martelli books -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Tue Oct 10 01:24:32 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 10 Oct 2006 00:24:32 +0100 Subject: [Tutor] Seeking good resources for Tkinter References: Message-ID: > I want to learn the GUI programming in Python. Can you suggest some > nice web > resources as well as books to start. It never fails to amaze me how often we get near identical questions being asked within a few days of each other and then never mentioned again for weeks! There are many different GUI toolkits for Python but the two most commonly used are: wxPython and Tkinter. Tkinter is based ob Tcl/Tk and comes as standard in Python but has slightly less sophisticated widgets and some folks don't like its looks.Try the Tkinter Topic Guide in the Documentation section of the Python web site for links to references and tutorials. There are some books too. wxPython has its own web site and is based on a C++ framework called wxWidgets which also has a web site full of references which are very good if you can read C++. HTH, Alan G. From billburns at pennswoods.net Tue Oct 10 01:32:11 2006 From: billburns at pennswoods.net (Bill Burns) Date: Mon, 09 Oct 2006 19:32:11 -0400 Subject: [Tutor] Threaded FTP class Message-ID: <452ADBFB.1080309@pennswoods.net> Hi all, I'm trying to make a small, threaded FTP app and I'm running into a problem. My program has a GUI (I use PythonCard) and I want the GUI to be responsive while network operations are going on. I assumed that if I made a class (shown below) which was sub-classed from threading.Thread - I wouldn't have any problems. My GUI class (not shown) has a 'connect' button with a method that looks like this: def on_connect_command(self, event): """Connect to the remote server.""" # getConnectData() -> returns a tuple with # all of the data we need to connect. server, username, password = self.getConnectData() # Instantiate my threaded FTP class. self.host = FTP(server, username, password) self.host.setDaemon(True) self.host.start() time.sleep(1) When I hit this button, the GUI is completely responsive while trying to connect to the remote server. I have no problems and everything works as expected. Here's where I get the problem... The GUI class has another method which looks like this: def on_getData_command(self, event): # getDirectoryData(...) is a method in the # FTP() class. It walks a remote directory. self.host.getDirectoryData(someDirectory) When I fire this method - it blocks until getDirectoryData() returns, which makes the GUI non-responsive. It's *not* hanging due to a network problem (it will only fire if you're connected to the remote server.) Why does this one method block? I assumed it would run in the FTP class thread and I'd have no problems!? What should I do different? Thanks, Bill A simplified version of my FTP class: class FTP(threading.Thread): """This class requires ftputil which you can download from here -> http://ftputil.sschwarzer.net/download """ def __init__(self, server, username, password): threading.Thread.__init__(self) self.server = server self.username = username self.password = password self.host = None self.connected = False def run(self): """Connects to the remote server and prints a list containing files and directories from the current directory. This does not block the GUI! """ try: self.host = ftputil.FTPHost( self.server, self.username, self.password) data = self.getDirData() self.connected = True print data except ftputil.ftp_error.FTPOSError: self.connected = False print 'Could not connect to remote server!' def getDirData(self): """Returns a list containing remote 'listdir' output.""" return [d for d in self.host.listdir(self.host.curdir)] def getDirectoryData(self, directory): """Walks the remote directory and then prints a list containing the files which were found. This blocks the GUI! """ if self.connected: fileList = [] self.host.chdir(directory) for root, dirs, files in self.host.walk(self.host.curdir): for f in files: fileList.append(self.host.path.abspath( self.host.path.join(root, f))) self.host.chdir('..') print fileList def disconnect(self): """Disconnect from the remote server.""" self.host.close() self.connected = False From kent37 at tds.net Tue Oct 10 02:57:29 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 09 Oct 2006 20:57:29 -0400 Subject: [Tutor] re-reading file-like objects In-Reply-To: <200610091454.42934.tiagosaboga@terra.com.br> References: <200610090921.43214.tiagosaboga@terra.com.br> <452A5181.6090702@tds.net> <200610091454.42934.tiagosaboga@terra.com.br> Message-ID: <452AEFF9.9020309@tds.net> Tiago Saboga wrote: > I'm afraid I don't fully understand file objects. I thought I could use it > just as a file: if I have one, and I want several copies, I just save it with > several names. So, if Popen.stdout already is a file object, I thought the > easier way would be to save it with another name. I see that it is more > complicated. A file-like object doesn't represent a file on disk so much as a data stream. It is a place you can read data from or write data to. When you call subprocess.Popen(), you get back a data stream representing the output of the process you started. You can read through this stream once, when you get to the end it's done. Just like when you run the process from the console, it just outputs once. If you want to use the output more than once you can copy it or save it or run the process again. Some file-like objects do let you seek to a specific location, but not all. Kent From paulino1 at sapo.pt Mon Oct 9 23:44:03 2006 From: paulino1 at sapo.pt (Paulino) Date: Mon, 09 Oct 2006 22:44:03 +0100 Subject: [Tutor] tkinter In-Reply-To: References: Message-ID: <452AC2A3.9000709@sapo.pt> Hi Abdullah! There is a kind of grid for tkinter that you can find online in the python cookbook, search for MultiListbox. But if you really want a spreadsheet like grid, you'd rather use wx.grid from wxPython. wxPython is much more powerfull than tkinter and is as easy to learn. You can find lots od doc's in www.wxpython.org. > Date: Mon, 9 Oct 2006 14:23:32 +0300 > From: "Abdullah Anar" > Subject: [Tutor] tkinter > To: tutor at python.org > Message-ID: > <71e07f040610090423i116a093fpff0a97a2c9bce28e at mail.gmail.com> > Content-Type: text/plain; charset="iso-8859-1" > > hello, > > We try to build new software using python and tkinter. We would like to > enter some fields using grid style. I mean we want to use rows to see old > entries and to enter new one. I hope I could explain, because it also is > not easy. I know there is grid to locate buttons, labels and something like > these. I hope I could explain I did not mean this grid which is using > instead of pack. > > we wonder if there is already some classes or widgets to do this. > > thanks for help from now > > Abdullah Anar > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: http://mail.python.org/pipermail/tutor/attachments/20061009/41a5ee23/attachment-0001.html > > From kent37 at tds.net Tue Oct 10 03:10:10 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 09 Oct 2006 21:10:10 -0400 Subject: [Tutor] Threaded FTP class In-Reply-To: <452ADBFB.1080309@pennswoods.net> References: <452ADBFB.1080309@pennswoods.net> Message-ID: <452AF2F2.2010903@tds.net> Bill Burns wrote: > I'm trying to make a small, threaded FTP app and I'm running into > a problem. > > My program has a GUI (I use PythonCard) and I want the GUI to be > responsive while network operations are going on. > > I assumed that if I made a class (shown below) which was sub-classed > from threading.Thread - I wouldn't have any problems. > > My GUI class (not shown) has a 'connect' button with a method that > looks like this: > > def on_connect_command(self, event): > """Connect to the remote server.""" > # getConnectData() -> returns a tuple with > # all of the data we need to connect. > server, username, password = self.getConnectData() > # Instantiate my threaded FTP class. > self.host = FTP(server, username, password) > self.host.setDaemon(True) > self.host.start() > time.sleep(1) > > When I hit this button, the GUI is completely responsive while trying to > connect to the remote server. I have no problems and everything works as > expected. In this method you create a new thread and start it. The thread's run() method is called. It connects to the remote server, fetches and prints a directory and returns. At that point (when the run() method returns) the FTP thread is dead. > > Here's where I get the problem... The GUI class has another method which > looks like this: > > def on_getData_command(self, event): > # getDirectoryData(...) is a method in the > # FTP() class. It walks a remote directory. > self.host.getDirectoryData(someDirectory) > > When I fire this method - it blocks until getDirectoryData() returns, > which makes the GUI non-responsive. It's *not* hanging due to a network > problem (it will only fire if you're connected to the remote server.) > > Why does this one method block? I assumed it would run in the FTP class > thread and I'd have no problems!? What should I do different? No, you don't do anything here to make the getDirectoryData() method run in a separate thread. Just because the FTP class has (or had) one thread at one time doesn't automatically make all of the FTP class methods run in a different thread. There are a few different ways you could handle this. You could have each command in the FTP class be smart enough to start a new thread to run the command. You don't actually have to subclass threading.Thread, you can just create a thread and tell it what method to execute. (Side note - this might be a good use for a @run_in_thread decorator.) You could make a separate class for each command. This would be pretty similar to the above solution. You would probably want a base class or utility class to hold the common details of connecting and sending a command. You could make a thread that really does keep running, that listens to for commands from a Queue. Your GUI thread would put a command in the Queue, the daemon thread would pull a command out and execute it. You could figure out how to do this with Twisted... HTH, Kent From billburns at pennswoods.net Tue Oct 10 03:28:05 2006 From: billburns at pennswoods.net (Bill Burns) Date: Mon, 09 Oct 2006 21:28:05 -0400 Subject: [Tutor] Threaded FTP class In-Reply-To: <452AF2F2.2010903@tds.net> References: <452ADBFB.1080309@pennswoods.net> <452AF2F2.2010903@tds.net> Message-ID: <452AF725.9060400@pennswoods.net> >> I'm trying to make a small, threaded FTP app and I'm running into >> a problem. >> >> My program has a GUI (I use PythonCard) and I want the GUI to be >> responsive while network operations are going on. >> >> I assumed that if I made a class (shown below) which was sub-classed >> from threading.Thread - I wouldn't have any problems. >> >> My GUI class (not shown) has a 'connect' button with a method that >> looks like this: >> >> def on_connect_command(self, event): >> """Connect to the remote server.""" >> # getConnectData() -> returns a tuple with >> # all of the data we need to connect. >> server, username, password = self.getConnectData() >> # Instantiate my threaded FTP class. >> self.host = FTP(server, username, password) >> self.host.setDaemon(True) >> self.host.start() >> time.sleep(1) >> >> When I hit this button, the GUI is completely responsive while trying to >> connect to the remote server. I have no problems and everything works as >> expected. > > > In this method you create a new thread and start it. The thread's run() > method is called. It connects to the remote server, fetches and prints a > directory and returns. At that point (when the run() method returns) the > FTP thread is dead. > >> >> Here's where I get the problem... The GUI class has another method which >> looks like this: >> >> def on_getData_command(self, event): >> # getDirectoryData(...) is a method in the >> # FTP() class. It walks a remote directory. >> self.host.getDirectoryData(someDirectory) >> >> When I fire this method - it blocks until getDirectoryData() returns, >> which makes the GUI non-responsive. It's *not* hanging due to a network >> problem (it will only fire if you're connected to the remote server.) >> >> Why does this one method block? I assumed it would run in the FTP class >> thread and I'd have no problems!? What should I do different? > > > No, you don't do anything here to make the getDirectoryData() method run > in a separate thread. Just because the FTP class has (or had) one thread > at one time doesn't automatically make all of the FTP class methods run > in a different thread. > > There are a few different ways you could handle this. You could have > each command in the FTP class be smart enough to start a new thread to > run the command. You don't actually have to subclass threading.Thread, > you can just create a thread and tell it what method to execute. (Side > note - this might be a good use for a @run_in_thread decorator.) > > You could make a separate class for each command. This would be pretty > similar to the above solution. You would probably want a base class or > utility class to hold the common details of connecting and sending a > command. > > You could make a thread that really does keep running, that listens to > for commands from a Queue. Your GUI thread would put a command in the > Queue, the daemon thread would pull a command out and execute it. > > You could figure out how to do this with Twisted... > Kent, Thank you for the explanation and ideas!! I wasn't exactly sure how the threading was working but you've enlightened me! Bill From rdm at rcblue.com Tue Oct 10 06:23:34 2006 From: rdm at rcblue.com (Dick Moores) Date: Mon, 09 Oct 2006 21:23:34 -0700 Subject: [Tutor] multithreading random() Message-ID: <7.0.1.0.2.20061009211036.03cfedf0@rcblue.com> Please refer to , from which I quote: "The functions supplied by this module are actually bound methods of a hidden instance of the random.Random class. You can instantiate your own instances of Random to get generators that don't share state. This is especially useful for multi-threaded programs, creating a different instance of Random for each thread, and using the jumpahead() method to make it likely that the generated sequences seen by each thread don't overlap." Could someone point me to an example script where this was done? I'd very much like to learn how to do that. And another question. That page also says, "Almost all module functions depend on the basic function random(), which generates a random float uniformly in the semi-open range [0.0, 1.0). Python uses the Mersenne Twister as the core generator. It produces 53-bit precision floats and has a period of 2**19937-1." What is a 53-bit precision float? Would that be something like a float accurate to 8 or 9 figures (dividing 53 by 8). Or what? Thanks, Dick Moores From john at fouhy.net Tue Oct 10 06:51:09 2006 From: john at fouhy.net (John Fouhy) Date: Tue, 10 Oct 2006 17:51:09 +1300 Subject: [Tutor] multithreading random() In-Reply-To: <7.0.1.0.2.20061009211036.03cfedf0@rcblue.com> References: <7.0.1.0.2.20061009211036.03cfedf0@rcblue.com> Message-ID: <5e58f2e40610092151r286f4672q7ad16f5c8a9fadf6@mail.gmail.com> On 10/10/06, Dick Moores wrote: > And another question. That page also says, "Almost all module > functions depend on the basic function random(), which generates a > random float uniformly in the semi-open range [0.0, 1.0). Python uses > the Mersenne Twister as the core generator. It produces 53-bit > precision floats and has a period of 2**19937-1." What is a 53-bit > precision float? Would that be something like a float accurate to 8 > or 9 figures (dividing 53 by 8). Or what? Hi Dick, Have a look here: http://en.wikipedia.org/wiki/Double_precision and here: http://en.wikipedia.org/wiki/IEEE_floating-point_standard Basically, floating point numbers are of the form "x times 2**y", where x is a binary number between 1 and 10 (that's binary 10, decimal 2). 53 bits means 53 binary digits of precision (including the initial 1). Does that help? -- John. From john at fouhy.net Tue Oct 10 06:57:00 2006 From: john at fouhy.net (John Fouhy) Date: Tue, 10 Oct 2006 17:57:00 +1300 Subject: [Tutor] multithreading random() In-Reply-To: <7.0.1.0.2.20061009211036.03cfedf0@rcblue.com> References: <7.0.1.0.2.20061009211036.03cfedf0@rcblue.com> Message-ID: <5e58f2e40610092157k176c64cxbb6acf5b1151f834@mail.gmail.com> On 10/10/06, Dick Moores wrote: > Please refer to > , from which I quote: > > "The functions supplied by this module are actually bound methods of > a hidden instance of the random.Random class. You can instantiate > your own instances of Random to get generators that don't share > state. This is especially useful for multi-threaded programs, > creating a different instance of Random for each thread, and using > the jumpahead() method to make it likely that the generated sequences > seen by each thread don't overlap." > > Could someone point me to an example script where this was done? I'd > very much like to learn how to do that. Using google's code search, I found this: def _create_random_generators(self, num, delta, firstseed=None): """Return list of 'num' distinct generators. Each generator has its own unique segment of delta elements from Random.random()'s full period. Seed the first generator with optional arg firstseed (default is None, to seed from current time). """ g = Random(firstseed) result = [g] for i in range(num - 1): laststate = g.getstate() g = Random() g.setstate(laststate) g.jumpahead(delta) result.append(g) return result Although, from looking at the docs you quoted, this may not be correct for python2.3+. -- John. From rdm at rcblue.com Tue Oct 10 10:00:15 2006 From: rdm at rcblue.com (Dick Moores) Date: Tue, 10 Oct 2006 01:00:15 -0700 Subject: [Tutor] What are these things urandom() returns? Message-ID: <7.0.1.0.2.20061010005631.077e9e08@rcblue.com> "urandom(n) Return a string of n random bytes suitable for cryptographic use. This function returns random bytes from an OS-specific randomness source. The returned data should be unpredictable enough for cryptographic applications, though its exact quality depends on the OS implementation. On a UNIX-like system this will query /dev/urandom, and on Windows it will use CryptGenRandom. If a randomness source is not found, NotImplementedError will be raised. New in version 2.4." >>> from os import urandom >>> urandom(10) '\xc0\xf0\xea\x0c\xdd\x95u at Z\x89' >>> ??? Thanks, Dick Moores Win XP, Python 2.5 From rdm at rcblue.com Tue Oct 10 10:02:49 2006 From: rdm at rcblue.com (Dick Moores) Date: Tue, 10 Oct 2006 01:02:49 -0700 Subject: [Tutor] multithreading random() Message-ID: <7.0.1.0.2.20061010010231.078326a0@rcblue.com> At 09:51 PM 10/9/2006, you wrote: >On 10/10/06, Dick Moores wrote: > > And another question. That page also says, "Almost all module > > functions depend on the basic function random(), which generates a > > random float uniformly in the semi-open range [0.0, 1.0). Python uses > > the Mersenne Twister as the core generator. It produces 53-bit > > precision floats and has a period of 2**19937-1." What is a 53-bit > > precision float? Would that be something like a float accurate to 8 > > or 9 figures (dividing 53 by 8). Or what? > >Hi Dick, > >Have a look here: http://en.wikipedia.org/wiki/Double_precision >and here: http://en.wikipedia.org/wiki/IEEE_floating-point_standard > >Basically, floating point numbers are of the form "x times 2**y", >where x is a binary number between 1 and 10 (that's binary 10, decimal >2). 53 bits means 53 binary digits of precision (including the >initial 1). > >Does that help? Well, before I dig into those references that I know are going to be difficult to understand, could you give me the bottom line about random()? >>> from random import random >>> print "%.17f" % random() 0.54188753195519013 >>> I can get what appears to be a random number precise(?) to 17 digits. How many base-10 digits would a "53-bit precision float" have, if converted to base 10? >>> 2 ** 52 4503599627370496L >>> 2**53 9007199254740992L >>> >>> len(str(2**53))-1 15 So is the answer to my question something like len(str(2**53)) -1? (minus 1 because of the L in the long integer) Thanks, Dick From rdm at rcblue.com Tue Oct 10 10:03:30 2006 From: rdm at rcblue.com (Dick Moores) Date: Tue, 10 Oct 2006 01:03:30 -0700 Subject: [Tutor] multithreading random() Message-ID: <7.0.1.0.2.20061010010303.078777c8@rcblue.com> At 09:57 PM 10/9/2006, you wrote: >On 10/10/06, Dick Moores wrote: > > Please refer to > > , from > which I quote: > > > > "The functions supplied by this module are actually bound methods of > > a hidden instance of the random.Random class. You can instantiate > > your own instances of Random to get generators that don't share > > state. This is especially useful for multi-threaded programs, > > creating a different instance of Random for each thread, and using > > the jumpahead() method to make it likely that the generated sequences > > seen by each thread don't overlap." > > > > Could someone point me to an example script where this was done? I'd > > very much like to learn how to do that. > >Using google's code search, I found this: > > def _create_random_generators(self, num, delta, firstseed=None): > """Return list of 'num' distinct generators. > Each generator has its own unique segment of delta elements > from Random.random()'s full period. > Seed the first generator with optional arg firstseed (default > is None, to seed from current time). > """ > g = Random(firstseed) > result = [g] > for i in range(num - 1): > laststate = g.getstate() > g = Random() > g.setstate(laststate) > g.jumpahead(delta) > result.append(g) > return result > >Although, from looking at the docs you quoted, this may not be correct >for python2.3+. Thanks, John, That's a start. Didn't know about Google's code search, . What was your search string? Dick From kent37 at tds.net Tue Oct 10 12:04:25 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 10 Oct 2006 06:04:25 -0400 Subject: [Tutor] What are these things urandom() returns? In-Reply-To: <7.0.1.0.2.20061010005631.077e9e08@rcblue.com> References: <7.0.1.0.2.20061010005631.077e9e08@rcblue.com> Message-ID: <452B7029.9020109@tds.net> Dick Moores wrote: > "urandom(n) > > Return a string of n random bytes suitable for cryptographic use. > This function returns random bytes from an OS-specific randomness > source. The returned data should be unpredictable enough for > cryptographic applications, though its exact quality depends on the > OS implementation. On a UNIX-like system this will query > /dev/urandom, and on Windows it will use CryptGenRandom. If a > randomness source is not found, NotImplementedError will be raised. > New in version 2.4." > > >>> from os import urandom > >>> urandom(10) > '\xc0\xf0\xea\x0c\xdd\x95u at Z\x89' It's a string where each character (byte) is selected randomly from the range 0-255. In Python a string can be used as a container for arbitrary byte values that are not text and maybe don't fit your notion of what a string is. When the Python interpreter prints a value automatically (not as the result of an explicit print) as above, it prints repr(value). For a string s, repr(s) uses \x escapes to display any non-printable characters. So what you see above is the repr() of a string whose first bytes contain the values (in hexadecimal) c0 f0 ea 0c dd 95 75 == ord('u') so it prints as 'u' rather than \x75 40 == ord('@') 5a == ord('Z') 89 HTH, Kent From alan.gauld at btinternet.com Tue Oct 10 12:22:30 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 10 Oct 2006 11:22:30 +0100 Subject: [Tutor] What are these things urandom() returns? References: <7.0.1.0.2.20061010005631.077e9e08@rcblue.com> Message-ID: > source. The returned data should be unpredictable enough for > cryptographic applications, though its exact quality depends on the > OS implementation. > >>> from os import urandom > >>> urandom(10) > '\xc0\xf0\xea\x0c\xdd\x95u at Z\x89' > >>> > > ??? Its a string of bytes which you can use to encrypt data. The simplest form of reversible encryption is the xor operation. You simply xor the crypto string with the data to get an encrypted string. To return to the data xor the data with the original cryptioo string and you get the original data back. Look at a 4 bit pattern to see this in action: Data = 1010 Crypto = 0010 Data xor Crypto result = 1000 Now apply xor to result: 1000 xor 0010 = 1010, the original data... Of course much more sophiisticated algorithms are used in modern cryptography but the general principle applies, you apply some random stream of crypto key to a set of data and get an encrypted result. You then apply the same set of crypto data (or a set that can reliable be derived from it) to the encrypted stream to retrieve the original data. Examples are DES and RSA. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From ajkadri at googlemail.com Tue Oct 10 13:25:19 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Tue, 10 Oct 2006 12:25:19 +0100 Subject: [Tutor] Seeking good resources for Tkinter In-Reply-To: References: Message-ID: Thanks for the reply. The rule is: "when in doubt, always ask". Sorry if a similar question was answered previously. Regards, Asrar On 10/10/06, Alan Gauld wrote: > > > I want to learn the GUI programming in Python. Can you suggest some > > nice web > > resources as well as books to start. > > It never fails to amaze me how often we get near identical > questions being asked within a few days of each other and then > never mentioned again for weeks! > > There are many different GUI toolkits for Python but the two most > commonly used are: > > wxPython and > Tkinter. > > Tkinter is based ob Tcl/Tk and comes as standard in Python > but has slightly less sophisticated widgets and some folks > don't like its looks.Try the Tkinter Topic Guide in the Documentation > section of the Python web site for links to references and tutorials. > There are some books too. > > wxPython has its own web site and is based on a C++ > framework called wxWidgets which also has a web site > full of references which are very good if you can read C++. > > HTH, > > Alan G. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061010/85d2e531/attachment.html From ajkadri at googlemail.com Tue Oct 10 14:18:50 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Tue, 10 Oct 2006 13:18:50 +0100 Subject: [Tutor] Need problems to enhance programming skills Message-ID: Folks, Have you got set of programming problems in python to reinforce the core language concepts and also build logic. thanks. Regards, Asrar -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061010/62cb6b48/attachment.html From geoframer at gmail.com Tue Oct 10 14:31:39 2006 From: geoframer at gmail.com (Geoframer) Date: Tue, 10 Oct 2006 14:31:39 +0200 Subject: [Tutor] Need problems to enhance programming skills In-Reply-To: References: Message-ID: <5d8e35a70610100531m201198b2n708edd47cd9e5792@mail.gmail.com> Hi Asrarahmed, I recently started learning python. To reinforce the core language concepts I used the following website : http://www.spoj.pl/ This site features a large number of programming problems which you can solve in any number of programming language (including Python) and you can have the programs checked online to see if they are valid. The programming exercises are not specific to python but more of the kind you find in programming contests. You can still get valuable lessons from them though. Have fun - Geoframer On 10/10/06, Asrarahmed Kadri wrote: > > > > Folks, > > Have you got set of programming problems in python to reinforce the core > language concepts and also build logic. > > thanks. > > Regards, > Asrar > > -- > To HIM you shall return. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061010/a72a672e/attachment.htm From rdm at rcblue.com Tue Oct 10 17:20:06 2006 From: rdm at rcblue.com (Dick Moores) Date: Tue, 10 Oct 2006 08:20:06 -0700 Subject: [Tutor] Workaround for limitation in xrange()? Message-ID: <7.0.1.0.2.20061010081254.022073e0@rcblue.com> >>> for x in xrange(2**31): pass Traceback (most recent call last): File "", line 1, in for x in xrange(2**31): OverflowError: long int too large to convert to int >>> I can think of 2 workarounds for this 2**31 limitation in xrange(). Use a while loop instead. Or use 2 or more for loops, keeping the number of cycles in each under 2**31. Are there others? Thanks, Dick Moores From kent37 at tds.net Tue Oct 10 17:34:34 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 10 Oct 2006 11:34:34 -0400 Subject: [Tutor] Workaround for limitation in xrange()? In-Reply-To: <7.0.1.0.2.20061010081254.022073e0@rcblue.com> References: <7.0.1.0.2.20061010081254.022073e0@rcblue.com> Message-ID: <452BBD8A.9010807@tds.net> Dick Moores wrote: > >>> for x in xrange(2**31): > pass > > Traceback (most recent call last): > File "", line 1, in > for x in xrange(2**31): > OverflowError: long int too large to convert to int > >>> > > I can think of 2 workarounds for this 2**31 limitation in xrange(). > Use a while loop instead. Or use 2 or more for loops, keeping the > number of cycles in each under 2**31. > > Are there others? Encapsulate the while loop in a generator: def count(limit): n=0 while n Message-ID: Dick Moores rcblue.com> writes: > I can think of 2 workarounds for this 2**31 limitation in xrange(). > Use a while loop instead. Or use 2 or more for loops, keeping the > number of cycles in each under 2**31. > > Are there others? Write your own iterator: >>> def hugerange(minval, maxval): ... val = minval ... while val < maxval: ... yield val ... val += 1 ... >>> for i in hugerange(2**31, 2**31 + 2): ... print i ... 2147483648 2147483649 It might be slower than Python's xrange implementation (haven't tested), but it will take anything you throw at it as long as Python itself can handle it. Yours, Andrei From dyoo at hkn.eecs.berkeley.edu Tue Oct 10 17:46:25 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 10 Oct 2006 08:46:25 -0700 (PDT) Subject: [Tutor] Workaround for limitation in xrange()? In-Reply-To: <7.0.1.0.2.20061010081254.022073e0@rcblue.com> References: <7.0.1.0.2.20061010081254.022073e0@rcblue.com> Message-ID: > >>> for x in xrange(2**31): > pass > > Traceback (most recent call last): > File "", line 1, in > for x in xrange(2**31): > OverflowError: long int too large to convert to int Hi Dick, Hmmm... I'd consider this a misfeature in the implementation. Apparently xrange (and range) must be built with regular ints, not long ints. This limitation is documented, although I think this is inconsistent and a bad thing. http://www.python.org/doc/2.3.5/lib/built-in-funcs.html#l2h-73 http://www.python.org/doc/2.3.5/lib/built-in-funcs.html#l2h-55 In the meantime, you can build your own version of xrange that should work on long ints. Here is an example: ################# def myxrange(m, n=None, skip=1): """An xrange-like function that can deal with long ints. Note: doesn't deal with negative ranges particularly well.""" if n is None: m, n = 0, m i = m while i < n: yield i i = i + skip ################# This is a "generator" that does pretty much what you'll want. ################################################################## >>> list(myxrange(1, 5)) [1, 2, 3, 4] >>> list(myxrange(2**32, 2**32 + 5)) [4294967296L, 4294967297L, 4294967298L, 4294967299L, 4294967300L] ################################################################## Note: this is a quick-and-dirty function; I wouldn't use it in production yet. It needs some more work to reject bad input. If you want, we can talk about exhaustively testing the function using robust equivalence class testing. *grin* Best of wishes! From rdm at rcblue.com Tue Oct 10 20:10:21 2006 From: rdm at rcblue.com (Dick Moores) Date: Tue, 10 Oct 2006 11:10:21 -0700 Subject: [Tutor] Workaround for limitation in xrange()? In-Reply-To: References: <7.0.1.0.2.20061010081254.022073e0@rcblue.com> Message-ID: <7.0.1.0.2.20061010102836.06be3ae0@rcblue.com> > >> >>> for x in xrange(2**31): >> pass >> >>Traceback (most recent call last): >> File "", line 1, in >> for x in xrange(2**31): >>OverflowError: long int too large to convert to int > Here are the suggestions I've received: Danny's >################# >def myxrange(m, n=None, skip=1): > """An xrange-like function that can deal with long ints. > Note: doesn't deal with negative ranges particularly well.""" > if n is None: > m, n = 0, m > i = m > while i < n: > yield i > i = i + skip >################# Kent's Encapsulate the while loop in a generator: def count(limit): n=0 while n>> def hugerange(minval, maxval): ... val = minval ... while val < maxval: ... yield val ... val += 1 All 3 are essentially the same, aren't they. Which makes me feel even dumber, because I don't understand any of them. I've consulted 3 books, and still don't understand the use of yield. Let me show you what I was doing when I ran into the 2**31-1 limitation: This is one of my attempts to test the degree of uniformity of random(). The others are seeing how close the average random() return comes to 0.5, and using random() in an approximation of pi. I've realized now that all 3 scripts require an immense number of calls to random(), so many that I wouldn't be able to use my computer for anything else for weeks, maybe months. But be that as it may, I'd still like to know how to use yield in my 1histogram-5a. For your convenience, here's the list h, and the while loop I used: h = 100*[0] c = 0 while c < k: r = random() i = int(math.floor(100*r)) h[i] += 1 c += 1 So, for a random() return of 0.27862506717494118, i would be 27, and h[27] would be incremented by 1. Thanks, Dick From asdlinux at yahoo.se Tue Oct 10 20:15:22 2006 From: asdlinux at yahoo.se (=?ISO-8859-1?Q?Magnus_Wirstr=F6m?=) Date: Tue, 10 Oct 2006 20:15:22 +0200 Subject: [Tutor] How to read content in a tar file with tarfile module Message-ID: <452BE339.2070100@yahoo.se> Hi everyone I have written a app that makes a tar file and all works well... Now i want to expand that app so it can read read the tar and give me the contents of the tar file. How is the best way to do this ? I can't find a "listdir" like function in tarfile. Can anyone point me in the right direction? Thanks Magnus From kent37 at tds.net Tue Oct 10 20:34:46 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 10 Oct 2006 14:34:46 -0400 Subject: [Tutor] Workaround for limitation in xrange()? In-Reply-To: <7.0.1.0.2.20061010102836.06be3ae0@rcblue.com> References: <7.0.1.0.2.20061010081254.022073e0@rcblue.com> <7.0.1.0.2.20061010102836.06be3ae0@rcblue.com> Message-ID: <452BE7C6.2080607@tds.net> Dick Moores wrote: > Here are the suggestions I've received: > > All 3 are essentially the same, aren't they. Which makes me feel even > dumber, because I don't understand any of them. I've consulted 3 > books, and still don't understand the use of yield. Yes, they are pretty much the same. Mine is bare-bones, just doing what you specifically asked for. Danny's is a full replacement for xrange(); Andrei's is in between. Here is a good introduction to generators: http://www.python.org/doc/2.2.3/whatsnew/node5.html > I've realized now that all 3 scripts require an immense number of > calls to random() Um, yeah, more than 2**31-1, right? :-) By the way your approach to testing the 'goodness' of random() is pretty naive. For example a random() that just repeats 0...99 over and over would score very well. For large repeat counts it could even repeat the same number for a while and score well: 1111111112222222233333333 etc. You might be interested in this article and the links at the bottom: http://en.wikipedia.org/wiki/Pseudo-random_number_generator Kent From hugonz-lists at h-lab.net Tue Oct 10 21:19:20 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Tue, 10 Oct 2006 13:19:20 -0600 Subject: [Tutor] How to read content in a tar file with tarfile module In-Reply-To: <452BE339.2070100@yahoo.se> References: <452BE339.2070100@yahoo.se> Message-ID: <452BF238.4090105@h-lab.net> Magnus Wirstr?m wrote: > I have written a app that makes a tar file and all works well... Now i > want to expand that app so it can read read the tar and give me the > contents of the tar file. How is the best way to do this ? I can't find > a "listdir" like function in tarfile. Can anyone point me in the right > direction? Hi, is this what you're looking for?? (tarfile Object docs) getmembers( ) Return the members of the archive as a list of TarInfo objects. The list has the same order as the members in the archive. getnames( ) Return the members as a list of their names. It has the same order as the list returned by getmembers(). Hugo From rdm at rcblue.com Tue Oct 10 21:29:26 2006 From: rdm at rcblue.com (Dick Moores) Date: Tue, 10 Oct 2006 12:29:26 -0700 Subject: [Tutor] What are these things urandom() returns? In-Reply-To: <452B7029.9020109@tds.net> References: <7.0.1.0.2.20061010005631.077e9e08@rcblue.com> <452B7029.9020109@tds.net> Message-ID: <7.0.1.0.2.20061010121310.06beff90@rcblue.com> Thanks very much, Kent and Alan. I'm thinking that just for the hell of it I could use urandom() as a source of random decimal digits. Or in a coin tossing program. Here's a list of 7817 '1's and 0's generated by urandom(): >>> from os import urandom >>> lst = list(urandom(1000000)) >>> tosses = [y for y in lst if y in '01'] >>> len(tosses) 7817 >>> Would this be a better random source than choice([0,1]), which uses random()? Dick From marc_a_poulin at yahoo.com Tue Oct 10 21:31:06 2006 From: marc_a_poulin at yahoo.com (Marc Poulin) Date: Tue, 10 Oct 2006 12:31:06 -0700 (PDT) Subject: [Tutor] Workaround for limitation in xrange()? In-Reply-To: <7.0.1.0.2.20061010102836.06be3ae0@rcblue.com> Message-ID: <20061010193106.51025.qmail@web34106.mail.mud.yahoo.com> --- Dick Moores wrote: > > Andrei's > Write your own iterator: > >>> def hugerange(minval, maxval): > ... val = minval > ... while val < maxval: > ... yield val > ... val += 1 > > All 3 are essentially the same, aren't they. Which > makes me feel even > dumber, because I don't understand any of them. I've > consulted 3 > books, and still don't understand the use of yield. > This is an example of a "coroutine". See http://en.wikipedia.org/wiki/Coroutine def hugerange(minval, maxval): val = minval while val < maxval: yield val ### return value of "val" to calling routine ### at this point and place ### hugerange() function temporarily ### on hold ... ### ### next call to hugerange() ### resumes at this point with ### all previous variable values ### still intact ... val += 1 __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From tim.peters at gmail.com Tue Oct 10 21:51:21 2006 From: tim.peters at gmail.com (Tim Peters) Date: Tue, 10 Oct 2006 15:51:21 -0400 Subject: [Tutor] What are these things urandom() returns? In-Reply-To: <7.0.1.0.2.20061010121310.06beff90@rcblue.com> References: <7.0.1.0.2.20061010005631.077e9e08@rcblue.com> <452B7029.9020109@tds.net> <7.0.1.0.2.20061010121310.06beff90@rcblue.com> Message-ID: <1f7befae0610101251n463eac02oe4095711cb44eecb@mail.gmail.com> [Dick Moores] ... > I'm thinking that just for the hell of it I could use urandom() as a > source of random decimal digits. You could, yes. > Or in a coin tossing program. Here's a list of 7817 '1's and 0's > generated by urandom(): Note that the length of the list will vary from run to run. Since you grab a million bytes, and there's a 1 in 128 chance of gettiing a 0 or 1 byte, if you run this code many times the /average/ length of the final list will be about 1000000./128 = 7812.5. > >>> from os import urandom > >>> lst = list(urandom(1000000)) > >>> tosses = [y for y in lst if y in '01'] > >>> len(tosses) > 7817 > >>> > Would this be a better random source than choice([0,1]), which uses random()? "Better" as measured against what criteria? It's very much slower than using choice([0, 1]) (or choice("01"), or randrange(2), or ...), and can't (even in theory) be reproduced by setting a seed. The only reason to use urandom() is if you /need/ cryptographic-strength randomness. For any meaning of "better" other than "cryptographically strong", no, urandom() isn't better. If cryptographic strength is what you need, then urandom is not only better, there's no choice about it -- as the docs for random() say, the Mersenne Twister "completely unsuitable for cryptographic purposes". Note that the random.SystemRandom class (see the docs) supplies the full range of convenience methods (like choice() and randrange()), but using urandom() as the base generator instead of the Mersenne Twister. From chanson at ttsd.k12.or.us Tue Oct 10 20:36:57 2006 From: chanson at ttsd.k12.or.us (Carlos Hanson) Date: Tue, 10 Oct 2006 11:36:57 -0700 (PDT) Subject: [Tutor] How to read content in a tar file with tarfile module In-Reply-To: <452BE339.2070100@yahoo.se> References: <452BE339.2070100@yahoo.se> Message-ID: <54947.10.1.1.110.1160505417.squirrel@webmail.ttsd.k12.or.us> On Tue, October 10, 2006 11:15 am, Magnus Wirstr?m wrote: > Hi everyone > > I have written a app that makes a tar file and all works well... Now > i want to expand that app so it can read read the tar and give me the > contents of the tar file. How is the best way to do this ? I can't > find a "listdir" like function in tarfile. Can anyone point me in the > right direction? Thanks Magnus There are two choices depending on your needs. First is the list() method of a TarFile object: >>> from tarfile import TarFile >>> tar = TarFile('files.tar') >>> tar.list() -rw-r--r-- chanson/chanson 0 2006-10-10 11:31:08 file.1 -rw-r--r-- chanson/chanson 0 2006-10-10 11:31:11 file.2 -rw-r--r-- chanson/chanson 0 2006-10-10 11:31:15 file.3 The second option is the getmembers() method which returns TarInfo objects: >>> members = tar.getmembers() >>> for member in members: ... print member.name ... file.1 file.2 file.3 >>> for member in members: ... print "%s %s/%s\t%s %s %s" % ( ... member.mode, member.uname, member.gname, ... member.size, member.mtime, member.name) ... 420 chanson/chanson 0 1160505068 file.1 420 chanson/chanson 0 1160505071 file.2 420 chanson/chanson 0 1160505075 file.3 -- Carlos Hanson Web and System Administrator Tigard-Tualatin School District 503.431.4053 From rdm at rcblue.com Tue Oct 10 22:01:24 2006 From: rdm at rcblue.com (Dick Moores) Date: Tue, 10 Oct 2006 13:01:24 -0700 Subject: [Tutor] Workaround for limitation in xrange()? In-Reply-To: <452BE7C6.2080607@tds.net> References: <7.0.1.0.2.20061010081254.022073e0@rcblue.com> <7.0.1.0.2.20061010102836.06be3ae0@rcblue.com> <452BE7C6.2080607@tds.net> Message-ID: <7.0.1.0.2.20061010123303.07641598@rcblue.com> At 11:34 AM 10/10/2006, Kent Johnson wrote: >Dick Moores wrote: >>Here are the suggestions I've received: > > >>All 3 are essentially the same, aren't they. >>Which makes me feel even dumber, because I >>don't understand any of them. I've consulted 3 >>books, and still don't understand the use of yield. > >Yes, they are pretty much the same. Mine is >bare-bones, just doing what you specifically >asked for. Danny's is a full replacement for xrange(); Andrei's is in between. > >Here is a good introduction to generators: >http://www.python.org/doc/2.2.3/whatsnew/node5.html While I'm studying that, could you modify my while loop so that it incorporates your suggestion in a way that improves it? That would be a big help to me in understanding generators and the use of yield, I believe. I don't want to give up on generators, even though your referenced article grants me permission to do so: "Generators are considered a new part of the core Python language, but learning or using them isn't compulsory; if they don't solve any problems that you have, feel free to ignore them." >>I've realized now that all 3 scripts require an >>immense number of calls to random() > >Um, yeah, more than 2**31-1, right? :-) At least several trillions, I'm thinking now, naively. >By the way your approach to testing the >'goodness' of random() is pretty naive. For >example a random() that just repeats 0...99 over >and over would score very well. For large repeat >counts it could even repeat the same number for >a while and score well: 1111111112222222233333333 etc. Sure, but passing the 3 tests I had in mind would be necessary if not sufficient conditions. Obviously random() would not be of the sorts you mention. Functions like those wouldn't be chosen for use in Python, right? > You might be interested in this article and the links at the bottom: >http://en.wikipedia.org/wiki/Pseudo-random_number_generator I'll be sure to check this out. And a friend tells me he has the Knuth vol. 2 (with that "Chapter 3, pp.1?193. Extensive coverage of statistical tests for non-randomness). Dick From rdm at rcblue.com Tue Oct 10 22:15:38 2006 From: rdm at rcblue.com (Dick Moores) Date: Tue, 10 Oct 2006 13:15:38 -0700 Subject: [Tutor] What are these things urandom() returns? In-Reply-To: <1f7befae0610101251n463eac02oe4095711cb44eecb@mail.gmail.co m> References: <7.0.1.0.2.20061010005631.077e9e08@rcblue.com> <452B7029.9020109@tds.net> <7.0.1.0.2.20061010121310.06beff90@rcblue.com> <1f7befae0610101251n463eac02oe4095711cb44eecb@mail.gmail.com> Message-ID: <7.0.1.0.2.20061010130630.07652850@rcblue.com> At 12:51 PM 10/10/2006, Tim Peters wrote: >[Dick Moores] >... >>I'm thinking that just for the hell of it I could use urandom() as a >>source of random decimal digits. > >You could, yes. > >>Or in a coin tossing program. Here's a list of 7817 '1's and 0's >>generated by urandom(): > >Note that the length of the list will vary from run to run. Since you >grab a million bytes, and there's a 1 in 128 chance of gettiing a 0 or >1 byte, if you run this code many times the /average/ length of the >final list will be about 1000000./128 = 7812.5. Yes, I saw that, thanks to Kent's earlier explanation. >> >>> from os import urandom >> >>> lst = list(urandom(1000000)) >> >>> tosses = [y for y in lst if y in '01'] >> >>> len(tosses) >>7817 >> >>> > >>Would this be a better random source than choice([0,1]), which uses random()? > >"Better" as measured against what criteria? I meant would it be closer to true randomness than random(), even if much slower? > It's very much slower >than using choice([0, 1]) (or choice("01"), or randrange(2), or ...), >and can't (even in theory) be reproduced by setting a seed. That's fine. Why would one want to? >The only reason to use urandom() is if you /need/ >cryptographic-strength randomness. For any meaning of "better" other >than "cryptographically strong", no, urandom() isn't better. If >cryptographic strength is what you need, then urandom is not only >better, there's no choice about it -- as the docs for random() say, >the Mersenne Twister "completely unsuitable for cryptographic >purposes". No /need/, here. Just curiosity. I had enough of crypto in the Navy. >Note that the random.SystemRandom class (see the docs) supplies the >full range of convenience methods (like choice() and randrange()), but >using urandom() as the base generator instead of the Mersenne Twister. Great! I'll check them out. Thanks very much, Tim. Dick From kent37 at tds.net Tue Oct 10 22:27:09 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 10 Oct 2006 16:27:09 -0400 Subject: [Tutor] Workaround for limitation in xrange()? In-Reply-To: <7.0.1.0.2.20061010123303.07641598@rcblue.com> References: <7.0.1.0.2.20061010081254.022073e0@rcblue.com> <7.0.1.0.2.20061010102836.06be3ae0@rcblue.com> <452BE7C6.2080607@tds.net> <7.0.1.0.2.20061010123303.07641598@rcblue.com> Message-ID: <452C021D.4060005@tds.net> Dick Moores wrote: > At 11:34 AM 10/10/2006, Kent Johnson wrote: >> Dick Moores wrote: >>> Here are the suggestions I've received: >> >> >>> All 3 are essentially the same, aren't they. >>> Which makes me feel even dumber, because I >>> don't understand any of them. I've consulted 3 >>> books, and still don't understand the use of yield. >> Yes, they are pretty much the same. Mine is >> bare-bones, just doing what you specifically >> asked for. Danny's is a full replacement for xrange(); Andrei's is in between. >> >> Here is a good introduction to generators: >> http://www.python.org/doc/2.2.3/whatsnew/node5.html > > While I'm studying that, could you modify my > while loop so that it incorporates your > suggestion in a way that improves it? That would > be a big help to me in understanding generators > and the use of yield, I believe. I'm not certain I would call it an improvement, but it would look just like your loop with xrange(). If the generator function is called count(), your loop would be for i in count(2**100): # ;) # process i The big advantage of generators is they let you encapsulate the logic that generates a sequence. This makes it easy to reuse a sequence without having to duplicate the sequence generation logic in multiple loops. Sometimes this can make your loop clearer because it can focus on processing the sequence rather than generating it. Sometimes it can greatly simplify your logic. This happens when both the generation of a sequence and the processing of it involve maintaining state. Here's a very artificial and possibly helpful example. Consider the sequence 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, ... Imagine you want to do something with every third element of that sequence, for example sum them. Maybe it's not so hard to do this in a simple loop but my head starts to hurt thinking about it. OK, so let's encapsulate the sequence into a generator: In [13]: def multicount(limit): ....: for i in range(1, limit+1): ....: for j in range(1, i+1): ....: yield j ....: ....: In [14]: list(multicount(5)) Out[14]: [1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5] Now summing every third element is easy: In [16]: sum(list(multicount(5))[::3]) Out[16]: 10 Does that help? Kent From rdm at rcblue.com Tue Oct 10 22:30:42 2006 From: rdm at rcblue.com (Dick Moores) Date: Tue, 10 Oct 2006 13:30:42 -0700 Subject: [Tutor] Workaround for limitation in xrange()? In-Reply-To: <20061010193106.51025.qmail@web34106.mail.mud.yahoo.com> References: <7.0.1.0.2.20061010102836.06be3ae0@rcblue.com> <20061010193106.51025.qmail@web34106.mail.mud.yahoo.com> Message-ID: <7.0.1.0.2.20061010131923.075bf578@rcblue.com> At 12:31 PM 10/10/2006, Marc Poulin wrote: >--- Dick Moores wrote: > > > > Andrei's > > Write your own iterator: > > >>> def hugerange(minval, maxval): > > ... val = minval > > ... while val < maxval: > > ... yield val > > ... val += 1 > > > > All 3 are essentially the same, aren't they. Which > > makes me feel even > > dumber, because I don't understand any of them. I've > > consulted 3 > > books, and still don't understand the use of yield. > > > >This is an example of a "coroutine". >See http://en.wikipedia.org/wiki/Coroutine > >def hugerange(minval, maxval): > val = minval > while val < maxval: > yield val > ### return value of "val" to calling routine > ### at this point and place > ### hugerange() function temporarily > ### on hold ... > ### > ### next call to hugerange() > ### resumes at this point with > ### all previous variable values > ### still intact ... > val += 1 Ah, it's beginning to make sense. However, it seems there's a need to do this because the while loop is inside a function (made generator). The while loop of mine in is not in a function, so it seems I don't need a generator. Am I correct? I have a real interest in speed, however, and being forced to use the while loop for k larger than 2**31-1 really slows things down. It seems a while loop is about 20% slower than an equivalent for loop. Would using a generator be a help speedwise? I suspect it wouldn't. How about it? Thanks very much, Marc. Dick From john at fouhy.net Tue Oct 10 22:39:37 2006 From: john at fouhy.net (John Fouhy) Date: Wed, 11 Oct 2006 09:39:37 +1300 Subject: [Tutor] multithreading random() In-Reply-To: <7.0.1.0.2.20061010010303.078777c8@rcblue.com> References: <7.0.1.0.2.20061010010303.078777c8@rcblue.com> Message-ID: <5e58f2e40610101339k9af4842s7bac219fab27b5e3@mail.gmail.com> On 10/10/06, Dick Moores wrote: > Didn't know about Google's code search, > . What was your search string? Search string was just "jumpahead lang:python". Had to scroll past a bunch of results for python/random.py before I found those, though. -- John. From alan.gauld at btinternet.com Tue Oct 10 22:45:47 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 10 Oct 2006 21:45:47 +0100 Subject: [Tutor] Workaround for limitation in xrange()? References: <7.0.1.0.2.20061010081254.022073e0@rcblue.com> <7.0.1.0.2.20061010102836.06be3ae0@rcblue.com> Message-ID: "Dick Moores" wrote in message news:7.0.1.0.2.20061010102836.06be3ae0 at rcblue.com... > Encapsulate the while loop in a generator: > def count(limit): > n=0 > while n yield n > n += 1 > > All 3 are essentially the same, aren't they. Which makes me feel > even > dumber, because I don't understand any of them. I've consulted 3 > books, and still don't understand the use of yield. Think of yield as being the same as return except that next time you "call the function" all the state is preserved and it picks up processing after the yield. So first time you call count above it returns 0 next time you call it it executes the n+= 1 and goes round the loop again until it hits yield when it returns 1. next time you call it executes y+=1 again, but because the state has been remembered n goes to 2 and yield returns that and so on until you reach n = limit at which point it just exits with StopIteration. Here is a short example: >>> def y(n): ... j = 0 ... while j < n: ... yield j ... j += 1 ... >>> try: ... x = y(7) ... for n in range(20): ... print x.next() ... except StopIteration: ... print 'Reached the end' ... 0 1 2 3 4 5 6 Reached the end >>> Does that help? -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From john at fouhy.net Tue Oct 10 22:48:11 2006 From: john at fouhy.net (John Fouhy) Date: Wed, 11 Oct 2006 09:48:11 +1300 Subject: [Tutor] multithreading random() In-Reply-To: <7.0.1.0.2.20061010010231.078326a0@rcblue.com> References: <7.0.1.0.2.20061010010231.078326a0@rcblue.com> Message-ID: <5e58f2e40610101348o2ab149bem82371ce7a2aa123a@mail.gmail.com> On 10/10/06, Dick Moores wrote: > I can get what appears to be a random number precise(?) to 17 digits. > How many base-10 digits would a "53-bit > precision float" have, if converted to base 10? > > >>> 2 ** 52 > 4503599627370496L > >>> 2**53 > 9007199254740992L > >>> > > >>> len(str(2**53))-1 > 15 > > So is the answer to my question something like len(str(2**53)) -1? > (minus 1 because of the L in the long integer) The string representation of longs doesn't include the 'L': >>> str(9999999999999999999L) '9999999999999999999' >>> repr(9999999999999999999L) '9999999999999999999L' I think the answer is "approximately, yes". But you have to be a bit careful with talking about floating point numbers in terms of decimals. eg: >>> 1.1 1.1000000000000001 -- John. From dkuhlman at rexx.com Tue Oct 10 22:52:46 2006 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Tue, 10 Oct 2006 13:52:46 -0700 Subject: [Tutor] How to read content in a tar file with tarfile module In-Reply-To: <452BF238.4090105@h-lab.net> References: <452BE339.2070100@yahoo.se> <452BF238.4090105@h-lab.net> Message-ID: <20061010205246.GA85281@cutter.rexx.com> On Tue, Oct 10, 2006 at 01:19:20PM -0600, Hugo Gonz?lez Monteverde wrote: > Magnus Wirstr?m wrote: > > I have written a app that makes a tar file and all works well... Now i > > want to expand that app so it can read read the tar and give me the > > contents of the tar file. How is the best way to do this ? I can't find > > a "listdir" like function in tarfile. Can anyone point me in the right > > direction? > > Hi, is this what you're looking for?? (tarfile Object docs) > > getmembers( ) > > Return the members of the archive as a list of TarInfo objects. The list > has the same order as the members in the archive. > > getnames( ) > > Return the members as a list of their names. It has the same order as > the list returned by getmembers(). > Note also the presence of a "next()" method in TarFile objects. That (along with an "__iter__" method: see Lib/tarfile.py in the source) is your clue that each TarFile instance is an iterator. It iterates over its TarInfo members. So, you can do the following: In [11]: f = tf.open('tmp.tar.gz', 'r:gz') In [12]: for x in f: ....: print x.name See: http://docs.python.org/lib/module-tarfile.html http://docs.python.org/lib/tarfile-objects.html http://docs.python.org/lib/tar-examples.html Note that the TarFile object implementation of the iterator protocol is slightly non-standard. next() returns None when exhausted, whereas the iterator protocol specifies that it should throw a StopIteration exception. See: http://docs.python.org/lib/typeiter.html Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From ajkadri at googlemail.com Tue Oct 10 23:50:46 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Tue, 10 Oct 2006 22:50:46 +0100 Subject: [Tutor] Help me with this Tkinter code Message-ID: Folks, Just started to get my feet wet with basics of Tkinter Programming. Here is a code which is giving me some problem; when I run it, it displays me the button widget, but when I click it, the window doesn't goes away. the program gets stuck up. Can anyone help me to resolve this issue?? *import sys from Tkinter import ** *root = Tk() widget = Button(root, text='Hello widget world', command=root.quit) widget.pack( ) widget.mainloop( )* Thanks. Regards, Asrar -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061010/4d693d0e/attachment.html From rabidpoobear at gmail.com Tue Oct 10 23:53:58 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 10 Oct 2006 16:53:58 -0500 Subject: [Tutor] Help me with this Tkinter code In-Reply-To: References: Message-ID: <452C1676.60304@gmail.com> Asrarahmed Kadri wrote: > > > Folks, > > Just started to get my feet wet with basics of Tkinter Programming. > Here is a code which is giving me some problem; when I run it, it > displays me the button widget, but when I click it, the window doesn't > goes away. the program gets stuck up. Can anyone help me to resolve > this issue?? > > *import sys > from Tkinter import ** > > *root = Tk() > widget = Button(root, text='Hello widget world', command=root.quit) > widget.pack( ) > widget.mainloop( )* > shouldn't you mainloop your root? also, are you using IDLE? > Thanks. > > Regards, > Asrar > > > -- > To HIM you shall return. > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From ajkadri at googlemail.com Wed Oct 11 00:09:16 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Tue, 10 Oct 2006 23:09:16 +0100 Subject: [Tutor] Help me with this Tkinter code In-Reply-To: <452C1676.60304@gmail.com> References: <452C1676.60304@gmail.com> Message-ID: yeh, I am using IDLE. why, is it a problem?? On 10/10/06, Luke Paireepinart wrote: > > Asrarahmed Kadri wrote: > > > > > > Folks, > > > > Just started to get my feet wet with basics of Tkinter Programming. > > Here is a code which is giving me some problem; when I run it, it > > displays me the button widget, but when I click it, the window doesn't > > goes away. the program gets stuck up. Can anyone help me to resolve > > this issue?? > > > > *import sys > > from Tkinter import ** > > > > *root = Tk() > > widget = Button(root, text='Hello widget world', command=root.quit) > > widget.pack( ) > > widget.mainloop( )* > > > shouldn't you mainloop your root? > also, are you using IDLE? > > Thanks. > > > > Regards, > > Asrar > > > > > > -- > > To HIM you shall return. > > ------------------------------------------------------------------------ > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061010/e9899539/attachment.htm From ajkadri at googlemail.com Wed Oct 11 00:11:43 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Tue, 10 Oct 2006 23:11:43 +0100 Subject: [Tutor] Help me with this Tkinter code In-Reply-To: References: <452C1676.60304@gmail.com> Message-ID: i changed the code from widget.mainloop() to root.mainloop(); but still its not working On 10/10/06, Asrarahmed Kadri wrote: > > yeh, I am using IDLE. > why, is it a problem?? > > > On 10/10/06, Luke Paireepinart wrote: > > > > Asrarahmed Kadri wrote: > > > > > > > > > Folks, > > > > > > Just started to get my feet wet with basics of Tkinter Programming. > > > Here is a code which is giving me some problem; when I run it, it > > > displays me the button widget, but when I click it, the window doesn't > > > goes away. the program gets stuck up. Can anyone help me to resolve > > > this issue?? > > > > > > *import sys > > > from Tkinter import ** > > > > > > *root = Tk() > > > widget = Button(root, text='Hello widget world', command=root.quit) > > > widget.pack( ) > > > widget.mainloop ( )* > > > > > shouldn't you mainloop your root? > > also, are you using IDLE? > > > Thanks. > > > > > > Regards, > > > Asrar > > > > > > > > > -- > > > To HIM you shall return. > > > > > ------------------------------------------------------------------------ > > > > > > _______________________________________________ > > > Tutor maillist - Tutor at python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > > -- > To HIM you shall return. > -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061010/35a73e2f/attachment.html From alan.gauld at btinternet.com Wed Oct 11 00:13:19 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 10 Oct 2006 23:13:19 +0100 Subject: [Tutor] What are these things urandom() returns? References: <7.0.1.0.2.20061010005631.077e9e08@rcblue.com><452B7029.9020109@tds.net> <7.0.1.0.2.20061010121310.06beff90@rcblue.com> Message-ID: > I'm thinking that just for the hell of it I could use urandom() as a > source of random decimal digits. Or in a coin tossing program. > Here's > a list of 7817 '1's and 0's generated by urandom(): > > >>> from os import urandom > >>> lst = list(urandom(1000000)) > >>> tosses = [y for y in lst if y in '01'] > >>> len(tosses) > 7817 > >>> > > Would this be a better random source than choice([0,1]), which uses > random()? It depends on what you mean by better. Its not really any more random if thats what you mean, it might be faster but I doubt if by much. I assume that choice simply divides random by the number of options and selects by index. In pseudo code: def choice(seq): ran = random() # number between 0,1 num = 1/len(seq) # 4 numbers means quarter interval? for n in range(1,len(seq)+1): if ran < num * n: break return seq[n-1] That probably has some boundary errors but I'd guess its how it works, and if written in C is probably faster than generating a big list then extracting the 1s and zeros into another list. But in matters of timing its better to test than guess... :-) Alan G. From john at fouhy.net Wed Oct 11 00:15:03 2006 From: john at fouhy.net (John Fouhy) Date: Wed, 11 Oct 2006 11:15:03 +1300 Subject: [Tutor] Help me with this Tkinter code In-Reply-To: <452C1676.60304@gmail.com> References: <452C1676.60304@gmail.com> Message-ID: <5e58f2e40610101515s4f19248ch531909941d25a5f9@mail.gmail.com> On 11/10/06, Luke Paireepinart wrote: > shouldn't you mainloop your root? By convention, you should, but you don't have to. mainloop is mainloop; calling it on root just makes it easy to find. -- John. From ajkadri at googlemail.com Wed Oct 11 00:32:57 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Tue, 10 Oct 2006 23:32:57 +0100 Subject: [Tutor] Help me with this Tkinter code In-Reply-To: <5e58f2e40610101515s4f19248ch531909941d25a5f9@mail.gmail.com> References: <452C1676.60304@gmail.com> <5e58f2e40610101515s4f19248ch531909941d25a5f9@mail.gmail.com> Message-ID: The error message is as under: *Microsoft Visual C++ Runtime Library* * Runtime Error! Program: C:\python\Lib\site-packages\pythonwin\Pythonwin.exe* * This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more inforamtion.* Any idea??? what is this and how can it be fixed??? On 10/10/06, John Fouhy wrote: > > On 11/10/06, Luke Paireepinart wrote: > > shouldn't you mainloop your root? > > By convention, you should, but you don't have to. mainloop is > mainloop; calling it on root just makes it easy to find. > > -- > John. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061010/6ddab63d/attachment.html From john at fouhy.net Wed Oct 11 03:18:21 2006 From: john at fouhy.net (John Fouhy) Date: Wed, 11 Oct 2006 14:18:21 +1300 Subject: [Tutor] Tip: Firefox quicksearch for module docs Message-ID: <5e58f2e40610101818o2298b7e8j6aaa5797f85a42a0@mail.gmail.com> For all you firefox users out there, create a bookmark in your "Quick searches" bookmark folder with the keyword 'python' and the location 'http://www.python.org/doc/current/lib/module-%s.html'. Then, you can just type (for example): "python random" into the search bar, and go straight to http://www.python.org/doc/current/lib/module-random.html. Nifty :-) (more quick searches here: http://wormus.com/leakytap/Internet/CustomKeywordspython ) -- John. From alan.gauld at btinternet.com Wed Oct 11 06:08:17 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 11 Oct 2006 05:08:17 +0100 Subject: [Tutor] Help me with this Tkinter code References: <452C1676.60304@gmail.com> Message-ID: > yeh, I am using IDLE. > why, is it a problem?? IDLE is a Tkinter program. So you are trying to run a Tkinter program inside a Tkinter program which can confuse things. The latest versions of IDLE are a lot better but I stilll strongly recommend running any Tkinter , indeed any GUI) programme, from the OS prompt - or by double clicking in Windows exploder Alan G. > On 10/10/06, Luke Paireepinart wrote: >> >> Asrarahmed Kadri wrote: >> > >> > >> > Folks, >> > >> > Just started to get my feet wet with basics of Tkinter >> > Programming. >> > Here is a code which is giving me some problem; when I run it, it >> > displays me the button widget, but when I click it, the window >> > doesn't >> > goes away. the program gets stuck up. Can anyone help me to >> > resolve >> > this issue?? >> > >> > *import sys >> > from Tkinter import ** >> > >> > *root = Tk() >> > widget = Button(root, text='Hello widget world', >> > command=root.quit) >> > widget.pack( ) >> > widget.mainloop( )* >> > >> shouldn't you mainloop your root? >> also, are you using IDLE? >> > Thanks. >> > >> > Regards, >> > Asrar >> > >> > >> > -- >> > To HIM you shall return. >> > ------------------------------------------------------------------------ >> > >> > _______________________________________________ >> > Tutor maillist - Tutor at python.org >> > http://mail.python.org/mailman/listinfo/tutor >> > >> >> > > > -- > To HIM you shall return. > -------------------------------------------------------------------------------- > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From tim.peters at gmail.com Wed Oct 11 07:01:50 2006 From: tim.peters at gmail.com (Tim Peters) Date: Wed, 11 Oct 2006 01:01:50 -0400 Subject: [Tutor] What are these things urandom() returns? In-Reply-To: <7.0.1.0.2.20061010130630.07652850@rcblue.com> References: <7.0.1.0.2.20061010005631.077e9e08@rcblue.com> <452B7029.9020109@tds.net> <7.0.1.0.2.20061010121310.06beff90@rcblue.com> <1f7befae0610101251n463eac02oe4095711cb44eecb@mail.gmail.com> <7.0.1.0.2.20061010130630.07652850@rcblue.com> Message-ID: <1f7befae0610102201g22dfbedag70e64e8e870eeadc@mail.gmail.com> [Dick Moores] >>> Would this be a better random source than choice([0,1]), which uses >>> random()? [Tim Peters] >> "Better" as measured against what criteria? [Dick] > I meant would it be closer to true randomness than random(), even if > much slower? Define "closer to true randomness" ;-) I don't mean to be difficult, but if the phrase "cryptographically strong" doesn't mean something vital to you already, there's little for you to worry about here. If you want /true/ randomness, you can buy a certified hardware random number generator, based on non-deterministic physical processes (like timing radioactive decay, or measuring thermal noise). Anything short of that is more-or-less a hack designed to pass various tests for randomness. The Mersenne Twister is one of the best-tested generators in existence, producing a sequence indistinguishable from "truly random" via all tests in common use. Nevertheless, if an intelligent /adversary/ knows you're using the Mersenne Twister, they can exploit that under some conditions to predict the sequence you're using. OTOH, if you use a "cryptographically strong" generator, or a hardware source of true randomness, and your adversary knows that, current theory says that even if have they have enormous computer resources to throw at it, and you don't make "stupid mistakes" in the /way/ you use it, they won't be able to predict the sequence you're seeing at significantly better than chance rate. The /pragmatic/ answer to "would it be closer to true randomness?" thus depends on what you're trying to achieve. The theoretical answer is "yes", but that may be of no relevance to what you're trying to achieve. >> It's very much slower than using choice([0, 1]) (or choice("01"), or >> randrange(2), or ...), and can't (even in theory) be reproduced by setting >> a seed. > That's fine. Why would one want to? For example, any non-trivial program eventually grows a test suite to verify that the program continues to run correctly as time goes on. Testing a program that makes random decisions is, in general, very much easier if you have a way to force it to make the same decisions each time the test is run. For example, here's a tiny piece of Python's Lib/test/test_random.py: def test_genrandbits(self): # Verify cross-platform repeatability self.gen.seed(1234567) self.assertEqual(self.gen.getrandbits(100), 97904845777343510404718956115L) Without the ability to force the seed, that test wouldn't be possible. As is, it tests that given the specific seed 1234567, the next call to getrandbits(100) will return exactly 97904845777343510404718956115 regardless of platform. Even if there is no test, non-trivial programs do "surprising" things at times. In a program that makes random decisions, if something /very/ surprising is seen, and you have no way to reproduce the decisions made before the surprising occurrence, you may be completely stuck in debugging it. OTOH, if there's a way to force the same decisions to be made, you can, e.g., run the program under a debugger to see everything that happens before disaster strikes. From pyro9219 at gmail.com Wed Oct 11 08:12:33 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Tue, 10 Oct 2006 23:12:33 -0700 Subject: [Tutor] Way to search this mailing list? Message-ID: <1160547153.12689.1.camel@localhost> Just a simple question... Am I missing some great feature? or is there no way to search rather then going through the archives by hand? Thanks. From hokkakada at khmeros.info Wed Oct 11 10:44:02 2006 From: hokkakada at khmeros.info (hok kakada) Date: Wed, 11 Oct 2006 15:44:02 +0700 Subject: [Tutor] save configuration of one application. In-Reply-To: <5e58f2e40610032154m436d1e6fo17417d686f0dcbf5@mail.gmail.com> References: <200610041115.01688.hokkakada@khmeros.info> <45233BE5.9060301@gmail.com> <5e58f2e40610032154m436d1e6fo17417d686f0dcbf5@mail.gmail.com> Message-ID: <200610111544.02406.hokkakada@khmeros.info> On Wednesday 04 October 2006 11:54, John Fouhy wrote: > On 04/10/06, Luke Paireepinart wrote: > > you can make a config.ini file and use that one module that parses ini > > files. > > I can't remember what it's called. > > configparser I think, but I wouldn't bet my life on it :) > > Yes, ConfigParser. > > The docs for ConfigParser are a bit confusing in places (IMO), but > there are people here who can help if you get stuck. > > > Or you could just write the settings out to a file. > > Using ConfigParser means your configuratino files will be > human-readable and human-editable. If you don't care about that, you > could stick them in a dictionary and use pickle to write it to a file. > Or use the shelve module. > > > If you choose to go the latter route, keep in mind that modules are > > compiled to .pyc files upon importation, > > so you'll have to remove those anytime you modify config.py or the old > > code will be used instead. > > The python interpreter should check the timestamps on foo.py vs > foo.pyc, and recompile if it thinks things have changed. Thank both of you. I'd have added some points about it. I used PyQt for designing GUI. Hence, in this case, I want to open a Font Dialog box in order to choose fontname, size and so on. Then set all these values to the textEdit. For the secode time we open the font dialog, the previous selected font will be set to the font family and font size of the font dialog. Is there any way to do it? Thanks again, da From thomas.schmitz at uni-bonn.de Wed Oct 11 10:48:32 2006 From: thomas.schmitz at uni-bonn.de (Thomas A. Schmitz) Date: Wed, 11 Oct 2006 10:48:32 +0200 Subject: [Tutor] extracting matches by paragraph Message-ID: Please excuse this long mail. I have read several tutorials and googled for three days, but haven't made any real progress on this question, probably because I'm an absolute novice at python. I'd be very grateful for some help. 1. My problem: I have several files in a structured database format. They contain entries like this: Type de notice : monographie Auteur(s) : John Doe Titre(s) : Argl bargl Publication : Denver, University of Colorado Press, 1776 Type de notice : article Auteur(s) : Richard Doe Titre(s) : wurgl burgl Type de notice : recueil Titre(s) : orgl gorgl I want to translate this into a BibTeX format. My approach was to read the file in by paragraphs, then extract the values of the fields that interest me and write these values to another file. I cannot go line by line since I want to reuse, e.g., the value of the "Auteur(s)" and "Titre(s)" fields to generate a key for every item, in the form of "doeargl" or "doewurgl" (via the split and join functions) The problem is that not every entry contains every field (in my example, #3 doesn't have an author), so I guess I need to test for the existence of these fields before I can use their values. 2. The approach: There is code here http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/408996/ which allows to read a file by paragraphs. I copied this to my script: class FileIterator(object): """ A general purpose file object iterator cum file object proxy """ def __init__(self, fw): self._fw = fw def readparagraphs(self): """ Paragraph iterator """ # This re-uses Alex Martelli's # paragraph reading recipe. # Python Cookbook 2nd edition 19.10, Page 713 paragraph = [] for line in self._fw: if line.isspace(): if paragraph: yield "".join(paragraph) paragraph = [] else: paragraph.append(line) if paragraph: yield "".join(paragraph) When I now run a very basic test: for item in iter.readparagraphs(): print item The entire file is reprinted paragraph by paragraph, so this code appears to work. I can also match the first line of every paragraph like so: reBook = re.compile('^Type de notice : monographie') for item in iter.readparagraphs(): m1 = reBook.match(item) if m1: print "@Book{," this will print a line @Book{, for every "monographie" in the database -- a good start, I thought! 3. The problem that's driving me insane But as soon as I try to match anything inside of the paragraph: reAuthor = re.compile('^Auteur\(s\) : (?P.+)$') m2 = reAuthor.match(item) if m2: author = m2.group('author') print "author = {%s}," % author I get no matches at all. I have tried to remove the ^ and the $ from the regex, or to add the "re.DOTALL" flag, but to no avail. 4. My aim I would like to have dictionary with fixed keys (the BibTeX field) and values extracted from my file for every paragraph and then write this, in a proper format, to a bibtex file. If a paragraph does not provide a value for a particular key, I could then, in a second pass over the bibtex file, delete these lines. But that means I first have to match and extract the values from my parapgraphs. What am I doing wrong? Or is the entire approach flawed? What alternative method would you suggest? Thanks for any help on this Thomas From mhansen at cso.atmel.com Tue Oct 10 22:44:04 2006 From: mhansen at cso.atmel.com (Mike Hansen) Date: Tue, 10 Oct 2006 14:44:04 -0600 Subject: [Tutor] VIM & Python Message-ID: <000301c6ecac$d2ef3560$28645f0a@1430A0316> This is slightly off topic... I use VIM to write my Python programs. I usually have a shell open to run pyflakes on the file I just edited. Is there a way to run pyflakes from within VIM and have it display the errors in another buffer? The :make stuff is confusing me. Mike From ajkadri at googlemail.com Wed Oct 11 11:51:40 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Wed, 11 Oct 2006 10:51:40 +0100 Subject: [Tutor] I am using PythonwinRe: Help me with this Tkinter code Message-ID: I am using Pythonwin. Please help me resolve the issue. I have the following error message (in blue text): *Microsoft Visual C++ Runtime Library* * Runtime Error! Program: C:\python\Lib\site-packages\pythonwin\Pythonwin.exe* * This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more inforamtion.* Help me out...... Regards, Asrar On 10/11/06, Alan Gauld wrote: > > > yeh, I am using IDLE. > > why, is it a problem?? > > IDLE is a Tkinter program. > So you are trying to run a Tkinter program inside a Tkinter program > which can confuse things. The latest versions of IDLE are a lot better > but I stilll strongly recommend running any Tkinter , indeed any > GUI) programme, from the OS prompt - or by double clicking in > Windows exploder > > Alan G. > > > On 10/10/06, Luke Paireepinart wrote: > >> > >> Asrarahmed Kadri wrote: > >> > > >> > > >> > Folks, > >> > > >> > Just started to get my feet wet with basics of Tkinter > >> > Programming. > >> > Here is a code which is giving me some problem; when I run it, it > >> > displays me the button widget, but when I click it, the window > >> > doesn't > >> > goes away. the program gets stuck up. Can anyone help me to > >> > resolve > >> > this issue?? > >> > > >> > *import sys > >> > from Tkinter import ** > >> > > >> > *root = Tk() > >> > widget = Button(root, text='Hello widget world', > >> > command=root.quit) > >> > widget.pack( ) > >> > widget.mainloop( )* > >> > > >> shouldn't you mainloop your root? > >> also, are you using IDLE? > >> > Thanks. > >> > > >> > Regards, > >> > Asrar > >> > > >> > > >> > -- > >> > To HIM you shall return. > >> > > ------------------------------------------------------------------------ > >> > > >> > _______________________________________________ > >> > Tutor maillist - Tutor at python.org > >> > http://mail.python.org/mailman/listinfo/tutor > >> > > >> > >> > > > > > > -- > > To HIM you shall return. > > > > > > -------------------------------------------------------------------------------- > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061011/a5fad68f/attachment.html From kent37 at tds.net Wed Oct 11 11:55:03 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 11 Oct 2006 05:55:03 -0400 Subject: [Tutor] Way to search this mailing list? In-Reply-To: <1160547153.12689.1.camel@localhost> References: <1160547153.12689.1.camel@localhost> Message-ID: <452CBF77.1010003@tds.net> Chris Hengge wrote: > Just a simple question... Am I missing some great feature? or is there > no way to search rather then going through the archives by hand? You can search the ActiveState archives at http://aspn.activestate.com/ASPN/Mail/Browse/Threaded/python-Tutor or the Gmane archives here: http://dir.gmane.org/gmane.comp.python.tutor Kent From klappnase at freenet.de Wed Oct 11 11:57:00 2006 From: klappnase at freenet.de (Michael Lange) Date: Wed, 11 Oct 2006 11:57:00 +0200 Subject: [Tutor] Help me with this Tkinter code In-Reply-To: References: <452C1676.60304@gmail.com> <5e58f2e40610101515s4f19248ch531909941d25a5f9@mail.gmail.com> Message-ID: <20061011115700.123fbabf.klappnase@freenet.de> On Tue, 10 Oct 2006 23:32:57 +0100 "Asrarahmed Kadri" wrote: > The error message is as under: > > > *Microsoft Visual C++ Runtime Library* > > * Runtime Error! > Program: C:\python\Lib\site-packages\pythonwin\Pythonwin.exe* > > * This application has requested the Runtime to terminate it in an unusual > way. Please contact the application's support team for more inforamtion.* > Any idea??? what is this and how can it be fixed??? > If you run a Tkinter program from IDLE you should not call mainloop(), as Alan pointed out before, you try to run a new mainloop inside the already existing one which confuses Tk (at least this was true for the version of IDLE i had used). I hope this helps Michael From kent37 at tds.net Wed Oct 11 12:06:46 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 11 Oct 2006 06:06:46 -0400 Subject: [Tutor] extracting matches by paragraph In-Reply-To: References: Message-ID: <452CC236.8090308@tds.net> Thomas A. Schmitz wrote: > Please excuse this long mail. I have read several tutorials and > googled for > three days, but haven't made any real progress on this question, > probably > because I'm an absolute novice at python. I'd be very grateful for > some help. > > 1. My problem: > > I have several files in a structured database format. They > contain entries like this: > > Type de notice : monographie > Auteur(s) : John Doe > Titre(s) : Argl bargl > Publication : Denver, University of Colorado Press, 1776 > > Type de notice : article > Auteur(s) : Richard Doe > Titre(s) : wurgl burgl > > Type de notice : recueil > Titre(s) : orgl gorgl > > I want to translate this into a BibTeX format. My approach was to > read the file > in by paragraphs, then extract the values of the fields that interest > me and > write these values to another file. I cannot go line by line since I > want to > reuse, e.g., the value of the "Auteur(s)" and "Titre(s)" fields to > generate a > key for every item, in the form of "doeargl" or "doewurgl" (via the > split and > join functions) The problem is that not every entry contains every > field (in my > example, #3 doesn't have an author), so I guess I need to test for the > existence of these fields before I can use their values. > > 2. The approach: > > There is code here > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/408996/ > which allows to read a file by paragraphs. I copied this to my script: > > class FileIterator(object): > """ A general purpose file object iterator cum > file object proxy """ > > def __init__(self, fw): > self._fw = fw > > def readparagraphs(self): > """ Paragraph iterator """ > > # This re-uses Alex Martelli's > # paragraph reading recipe. > # Python Cookbook 2nd edition 19.10, Page 713 > paragraph = [] > for line in self._fw: > if line.isspace(): > if paragraph: > yield "".join(paragraph) > paragraph = [] > else: > paragraph.append(line) > if paragraph: > yield "".join(paragraph) > > When I now run a very basic test: > > for item in iter.readparagraphs(): > print item > > The entire file is reprinted paragraph by paragraph, so this code > appears to work. I would take out the join in this, at least, and return a list of lines. You don't really have a paragraph, you have structured data. There is not need to throw away the structure. It might be even more useful to return a dictionary that maps field names to values. Also there doesn't seem to be any reason to make FileIterator a class, you can use just a generator function (Dick Moores take notice!): def readparagraphs(fw): self._fw = fw data = {} for line in fw: if line.isspace(): if data: yield data data = {} else: key, value = line.split(' : ') data[key] = value if data: yield data Now you don't need a regexp, you have usable data directly from the iterator. > I can also match the first line of every paragraph like so: > > reBook = re.compile('^Type de notice : monographie') > for item in iter.readparagraphs(): > m1 = reBook.match(item) > if m1: > print "@Book{," > > this will print a line @Book{, for every "monographie" in the > database -- a > good start, I thought! > > 3. The problem that's driving me insane > > But as soon as I try to match anything inside of the paragraph: > > reAuthor = re.compile('^Auteur\(s\) : (?P.+)$') > m2 = reAuthor.match(item) > if m2: > author = m2.group('author') > print "author = {%s}," % author > > I get no matches at all. I have tried to remove the ^ and the $ from > the regex, > or to add the "re.DOTALL" flag, but to no avail. You need re.MULTILINE to modify the meaning of ^ and $. re.DOTALL affects whether . matches newlines. > > 4. My aim > > I would like to have dictionary with fixed keys (the BibTeX field) > and values > extracted from my file for every paragraph and then write this, in a > proper > format, to a bibtex file. If a paragraph does not provide a value for a > particular key, I could then, in a second pass over the bibtex file, > delete > these lines. I would write the code to exclude those lines in the first place. If the dict returned from readparagraphs() is missing a key, then don't write the corresponding line. Kent From ajkadri at googlemail.com Wed Oct 11 12:40:09 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Wed, 11 Oct 2006 11:40:09 +0100 Subject: [Tutor] its working... from command lineRe: Help me with this Tkinter code Message-ID: The program is working okay, when I run in from the command prompt. Thanks for all the support. Regards, Asrar On 10/11/06, Michael Lange wrote: > > On Tue, 10 Oct 2006 23:32:57 +0100 > "Asrarahmed Kadri" wrote: > > > The error message is as under: > > > > > > *Microsoft Visual C++ Runtime Library* > > > > * Runtime Error! > > Program: C:\python\Lib\site-packages\pythonwin\Pythonwin.exe* > > > > * This application has requested the Runtime to terminate it in an > unusual > > way. Please contact the application's support team for more > inforamtion.* > > Any idea??? what is this and how can it be fixed??? > > > > If you run a Tkinter program from IDLE you should not call mainloop(), as > Alan pointed > out before, you try to run a new mainloop inside the already existing one > which > confuses Tk (at least this was true for the version of IDLE i had used). > > I hope this helps > > Michael > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061011/5ada55bf/attachment.htm From kent37 at tds.net Wed Oct 11 14:48:56 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 11 Oct 2006 08:48:56 -0400 Subject: [Tutor] extracting matches by paragraph In-Reply-To: <8A74841A-D2F3-4B43-AB86-6DBF47EF6EDF@uni-bonn.de> References: <452CC236.8090308@tds.net> <8A74841A-D2F3-4B43-AB86-6DBF47EF6EDF@uni-bonn.de> Message-ID: <452CE838.9020909@tds.net> Thomas A. Schmitz wrote: > On Oct 11, 2006, at 12:06 PM, Kent Johnson wrote: > >> I would take out the join in this, at least, and return a list of >> lines. You don't really have a paragraph, you have structured data. >> There is not need to throw away the structure. >> >> It might be even more useful to return a dictionary that maps field >> names to values. Also there doesn't seem to be any reason to make >> FileIterator a class, you can use just a generator function (Dick >> Moores take notice!): >> >> def readparagraphs(fw): >> self._fw = fw >> >> data = {} >> for line in fw: >> if line.isspace(): >> if data: >> yield data >> data = {} >> else: >> key, value = line.split(' : ') >> data[key] = value >> if data: >> yield data >> >> Now you don't need a regexp, you have usable data directly from the >> iterator. >> > > Thank you for your help, Kent! But I'm not sure if this is > practicable. As I said, a line-by-line approach does not work, What I have outlined is not a line-by-line approach, it is still returning data for a paragraph at a time, but in a more usable format than your original iterator. Try printing out the values you get from the iterator, the same way you did with your original paragraph iterator. > for > two reasons: > 1. I want to combine and translate the results from two lines; You can do that with this approach. > 2. in the file, there are lines of the form > Publication : Denver, University of Colorado Press, 1776 > from which I need to extract three values (address, publisher, date), > and I may need to discard some other stuff from other lines. So I do > need a regex, I think. Unfortunately, the structure is not strong > enough to make a one on one translation viable, so I do need to > extract the values... Ok, so the dict from the iterator is still raw data that needs some processing. Something like for para in readparagraphs(open('mydata.txt')): # Your previous example if para.get('Type de notice') == 'monographie': print "@Book{," # publication data pubData = para.get('Publication') if pubData: address, publisher, date = pubData.split(', ') # do something with address, etc. Kent PS Please reply on-list. From thomas.schmitz at uni-bonn.de Wed Oct 11 15:18:19 2006 From: thomas.schmitz at uni-bonn.de (Thomas A. Schmitz) Date: Wed, 11 Oct 2006 15:18:19 +0200 Subject: [Tutor] extracting matches by paragraph In-Reply-To: <452CE838.9020909@tds.net> References: <452CC236.8090308@tds.net> <8A74841A-D2F3-4B43-AB86-6DBF47EF6EDF@uni-bonn.de> <452CE838.9020909@tds.net> Message-ID: <7E0976F7-BCB2-42A3-B0C6-7997F809C2DB@uni-bonn.de> On Oct 11, 2006, at 2:48 PM, Kent Johnson wrote: > Thomas A. Schmitz wrote: >> On Oct 11, 2006, at 12:06 PM, Kent Johnson wrote: >> >>> I would take out the join in this, at least, and return a list of >>> lines. You don't really have a paragraph, you have structured data. >>> There is not need to throw away the structure. >>> >>> It might be even more useful to return a dictionary that maps field >>> names to values. Also there doesn't seem to be any reason to make >>> FileIterator a class, you can use just a generator function (Dick >>> Moores take notice!): >>> >>> def readparagraphs(fw): >>> self._fw = fw >>> >>> data = {} >>> for line in fw: >>> if line.isspace(): >>> if data: >>> yield data >>> data = {} >>> else: >>> key, value = line.split(' : ') >>> data[key] = value >>> if data: >>> yield data >>> >>> Now you don't need a regexp, you have usable data directly from the >>> iterator. >>> >> >> Thank you for your help, Kent! But I'm not sure if this is >> practicable. As I said, a line-by-line approach does not work, > > What I have outlined is not a line-by-line approach, it is still > returning data for a paragraph at a time, but in a more usable format > than your original iterator. > > Try printing out the values you get from the iterator, the same way > you > did with your original paragraph iterator. > >> for >> two reasons: >> 1. I want to combine and translate the results from two lines; > > You can do that with this approach. > >> 2. in the file, there are lines of the form >> Publication : Denver, University of Colorado Press, 1776 >> from which I need to extract three values (address, publisher, date), >> and I may need to discard some other stuff from other lines. So I do >> need a regex, I think. Unfortunately, the structure is not strong >> enough to make a one on one translation viable, so I do need to >> extract the values... > > Ok, so the dict from the iterator is still raw data that needs some > processing. Something like > > for para in readparagraphs(open('mydata.txt')): > # Your previous example > if para.get('Type de notice') == 'monographie': > print "@Book{," > > # publication data > pubData = para.get('Publication') > if pubData: > address, publisher, date = pubData.split(', ') > # do something with address, etc. > > Kent > > PS Please reply on-list. > Kent, thanks again, I begin to see some light and will try to make sense of it. I had developed the bad habit of just treating such data as strings, but of course it makes much more sense to keep the original format and then convert it to another format. Sorry for mindlessly hitting the reply button, didn't mean to intrude on you. Thanks a lot Thomas From AJeffrey at ntu.edu.sg Wed Oct 11 15:19:37 2006 From: AJeffrey at ntu.edu.sg (Jeffrey Kennedy) Date: Wed, 11 Oct 2006 21:19:37 +0800 Subject: [Tutor] Responding to a request for input from a MS-DOS program Message-ID: <54BE2FC5ADFC254B832681E9622AACFEC6F3C5@EXCHANGE23.staff.main.ntu.edu.sg> Hi, I want to use Python to run an old MS-DOS program that doesn't accept arguments when launched. I have to open the program first, then it will ask me for the name of another program (which it will subsequently do some analysis on). It asks two more questions (each requiring me to type '1' followed by 'enter') before it does the analysis; I don't need to capture any output (it will save the analysis in files which I can access later). I'm new to Python. I have run some simple DOS commands (copy, delete), using os.system, but need some pointers on how to do this task. I want to bypass the human input, because I have over 100 files I want processed, and I can use Python to iterate through each file in turn (the files are named 1.sav, 2.sav, ... 100.sav). I run Python 2.4 on Windows XP and (needless to say) I'm new to Python. >From web searches, it seems that a variation on popen might do what I want, but I'd like a pointer to some examples I can play around with. Thanks for any help you can give. Jeff -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061011/d73eb89d/attachment.htm From Mike.Hansen at atmel.com Wed Oct 11 18:59:04 2006 From: Mike.Hansen at atmel.com (Mike Hansen) Date: Wed, 11 Oct 2006 10:59:04 -0600 Subject: [Tutor] VIM & Python Message-ID: <57B026980605A64F9B23484C5659E32E358796@poccso.US.ad.atmel.com> > -----Original Message----- > From: Carlos Hanson [mailto:chanson at ttsd.k12.or.us] > Sent: Wednesday, October 11, 2006 10:50 AM > To: Mike Hansen > Cc: tutor at python.org > Subject: Re: [Tutor] VIM & Python > > > On Tue, October 10, 2006 1:44 pm, Mike Hansen wrote: > > This is slightly off topic... > > > > I use VIM to write my Python programs. I usually have a > shell open to > > run pyflakes on the file I just edited. Is there a way to run > > pyflakes from within VIM and have it display the errors in another > > buffer? > > > > The :make stuff is confusing me. > > > > Mike > > Because I also use vim, I looked into this. I found the answer on the > following site: > > http://www.rayninfo.co.uk/vimtips.html > > Try the following: > > :new | r!pyflakes # > > -- > Carlos Hanson > Web and System Administrator > Tigard-Tualatin School District > 503.431.4053 > Interesting page. Works great! Thanks! Mike From rdm at rcblue.com Wed Oct 11 20:34:33 2006 From: rdm at rcblue.com (Dick Moores) Date: Wed, 11 Oct 2006 11:34:33 -0700 Subject: [Tutor] What are these things urandom() returns? In-Reply-To: <1f7befae0610102201g22dfbedag70e64e8e870eeadc@mail.gmail.co m> References: <7.0.1.0.2.20061010005631.077e9e08@rcblue.com> <452B7029.9020109@tds.net> <7.0.1.0.2.20061010121310.06beff90@rcblue.com> <1f7befae0610101251n463eac02oe4095711cb44eecb@mail.gmail.com> <7.0.1.0.2.20061010130630.07652850@rcblue.com> <1f7befae0610102201g22dfbedag70e64e8e870eeadc@mail.gmail.com> Message-ID: <7.0.1.0.2.20061011113030.036b1db8@rcblue.com> At 10:01 PM 10/10/2006, Tim Peters wrote: >[Dick Moores] > >>> Would this be a better random source than choice([0,1]), which uses > >>> random()? > >[Tim Peters] > >> "Better" as measured against what criteria? > >[Dick] > > I meant would it be closer to true randomness than random(), even if > > much slower? > >Define "closer to true randomness" ;-) > >I don't mean to be difficult, but if the phrase "cryptographically >strong" doesn't mean something vital to you already, there's little >for you to worry about here. If you want /true/ randomness, you can >buy a certified hardware random number generator, based on >non-deterministic physical processes (like timing radioactive decay, >or measuring thermal noise). > >Anything short of that is more-or-less a hack designed to pass various >tests for randomness. The Mersenne Twister is one of the best-tested >generators in existence, producing a sequence indistinguishable from >"truly random" via all tests in common use. Nevertheless, if an >intelligent /adversary/ knows you're using the Mersenne Twister, they >can exploit that under some conditions to predict the sequence you're >using. OTOH, if you use a "cryptographically strong" generator, or a >hardware source of true randomness, and your adversary knows that, >current theory says that even if have they have enormous computer >resources to throw at it, and you don't make "stupid mistakes" in the >/way/ you use it, they won't be able to predict the sequence you're >seeing at significantly better than chance rate. > >The /pragmatic/ answer to "would it be closer to true randomness?" >thus depends on what you're trying to achieve. The theoretical answer >is "yes", but that may be of no relevance to what you're trying to >achieve. > > >> It's very much slower than using choice([0, 1]) (or choice("01"), or > >> randrange(2), or ...), and can't (even in theory) be reproduced by setting > >> a seed. > > > That's fine. Why would one want to? > >For example, any non-trivial program eventually grows a test suite to >verify that the program continues to run correctly as time goes on. >Testing a program that makes random decisions is, in general, very >much easier if you have a way to force it to make the same decisions >each time the test is run. For example, here's a tiny piece of >Python's Lib/test/test_random.py: > > def test_genrandbits(self): > # Verify cross-platform repeatability > self.gen.seed(1234567) > self.assertEqual(self.gen.getrandbits(100), > 97904845777343510404718956115L) > >Without the ability to force the seed, that test wouldn't be possible. > As is, it tests that given the specific seed 1234567, the next call >to getrandbits(100) will return exactly 97904845777343510404718956115 >regardless of platform. > >Even if there is no test, non-trivial programs do "surprising" things >at times. In a program that makes random decisions, if something >/very/ surprising is seen, and you have no way to reproduce the >decisions made before the surprising occurrence, you may be completely >stuck in debugging it. OTOH, if there's a way to force the same >decisions to be made, you can, e.g., run the program under a debugger >to see everything that happens before disaster strikes. OK, Tim, got it. Thanks for the education. My thanks also to the others on this thread: Kent Johnson and Alan Gauld. Dick Moores From pyro9219 at gmail.com Wed Oct 11 21:00:07 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Wed, 11 Oct 2006 12:00:07 -0700 Subject: [Tutor] Way to search this mailing list? In-Reply-To: <452CBF77.1010003@tds.net> References: <1160547153.12689.1.camel@localhost> <452CBF77.1010003@tds.net> Message-ID: Thanks to you both for the answer... Even if the data isn't the current emails traveling back and forth, its a step in the right direction... Beats asking the same questions over again when someone asked months prior.. On 10/11/06, Kent Johnson wrote: > > Chris Hengge wrote: > > Just a simple question... Am I missing some great feature? or is there > > no way to search rather then going through the archives by hand? > > You can search the ActiveState archives at > http://aspn.activestate.com/ASPN/Mail/Browse/Threaded/python-Tutor > > or the Gmane archives here: > http://dir.gmane.org/gmane.comp.python.tutor > > Kent > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061011/733925b4/attachment.html From euoar at yahoo.es Wed Oct 11 21:42:18 2006 From: euoar at yahoo.es (Alfonso) Date: Wed, 11 Oct 2006 21:42:18 +0200 Subject: [Tutor] executing with double click on linux Message-ID: <452D491A.5000609@yahoo.es> Sorry for the too obvious question. I'm new to python and have no idea how can I make execute a compiled .pyc with a double click in linux, with gnome. Trying to double click in a .py gives allways the question wether I want to execute the text file, or read it. (This behaviour can be changed with gconf-editor, but as it is for security matters, I would prefer to execute the .pyc with a double click). I have tried to associate python to the .pyc (first time I executed it there was no programm associated), but it doesn't work. Thank you for your answer. ______________________________________________ LLama Gratis a cualquier PC del Mundo. Llamadas a fijos y m?viles desde 1 c?ntimo por minuto. http://es.voice.yahoo.com From alan.gauld at btinternet.com Wed Oct 11 22:39:24 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 11 Oct 2006 21:39:24 +0100 Subject: [Tutor] Responding to a request for input from a MS-DOS program References: <54BE2FC5ADFC254B832681E9622AACFEC6F3C5@EXCHANGE23.staff.main.ntu.edu.sg> Message-ID: Hi Jeff, > I want to use Python to run an old MS-DOS program that doesn't > accept arguments when launched. I have to open the program first, > then it will ask me for the name of another program .... > I want to bypass the human input, because I have over > 100 files I want processed, and I can use Python to iterate through > each file in turn You need to look at the subprocess module and the examples that replace the older popen functions. You will find more info including examples of both popen and subporocess in my tutorial under the OS topic in the Applications Section Since you are new to this you might want to read the whole topic, or for more directed help scroll down to the Manipulating Processes heading. Unfortunately I just noticed I don't give any excample of writing to a process(in response to a prompt) which is something I should fix... Finally, for more sophisticated scenarios there is a module implementing the expect program in Python, but I suspect that will be overkill here. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Wed Oct 11 22:40:56 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 11 Oct 2006 21:40:56 +0100 Subject: [Tutor] VIM & Python References: <000301c6ecac$d2ef3560$28645f0a@1430A0316> Message-ID: > I use VIM to write my Python programs. I usually have a shell open > to run > pyflakes on the file I just edited. Is there a way to run pyflakes > from > within VIM and have it display the errors in another buffer? I'm being lazy and not doing a search, but what is pyflakes? Alan G Another vim user... From Mike.Hansen at atmel.com Wed Oct 11 23:01:25 2006 From: Mike.Hansen at atmel.com (Mike Hansen) Date: Wed, 11 Oct 2006 15:01:25 -0600 Subject: [Tutor] VIM & Python Message-ID: <57B026980605A64F9B23484C5659E32E3587C1@poccso.US.ad.atmel.com> > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of Alan Gauld > Sent: Wednesday, October 11, 2006 2:41 PM > To: tutor at python.org > Subject: Re: [Tutor] VIM & Python > > > I use VIM to write my Python programs. I usually have a shell open > > to run > > pyflakes on the file I just edited. Is there a way to run pyflakes > > from > > within VIM and have it display the errors in another buffer? > > I'm being lazy and not doing a search, but what is pyflakes? > > Alan G > Another vim user... > No problem. http://www.divmod.org/projects/pyflakes "Pyflakes is a simple program which checks Python source files for errors. It is similar to PyChecker in scope, but differs in that it does not execute the modules to check them. This is both safer and faster, although it does not perform as many checks. Unlike PyLint, Pyflakes checks only for logical errors in programs; it does not perform any checks on style." - From the pyflakes web site. Mike From alan.gauld at btinternet.com Wed Oct 11 23:22:52 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 11 Oct 2006 22:22:52 +0100 Subject: [Tutor] VIM & Python References: <57B026980605A64F9B23484C5659E32E3587C1@poccso.US.ad.atmel.com> Message-ID: "Mike Hansen" wrote in message news:57B026980605A64F9B23484C5659E32E3587C1 at poccso.US.ad.atmel.com... >> I'm being lazy and not doing a search, but what is pyflakes? >> > No problem. > > http://www.divmod.org/projects/pyflakes > > "Pyflakes is a simple program which checks Python source files for Thanks, I'll take a peek. Alan G. From pyro9219 at gmail.com Thu Oct 12 00:00:07 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Wed, 11 Oct 2006 15:00:07 -0700 Subject: [Tutor] Creating folders in windows... Message-ID: I found this from a 2004 mailing on this list.. os.path.mkdir('folder') Doesn't work... there is no mkdir in os.path (old style maybe?) >>> os.path.mkdir('folder') Traceback (most recent call last): File "", line 1, in ? AttributeError: 'module' object has no attribute 'mkdir' >>> dir(os.path) ['__all__', '__builtins__', '__doc__', '__file__', '__name__', 'abspath', 'altsep', 'basename', 'commonprefix', 'curdir', 'defpath', 'devnull', 'dirname', 'exists', 'expanduser', 'expandvars', 'extsep', 'getatime', 'getctime', 'getmtime', 'getsize', 'isabs', 'isdir', 'isfile', 'islink', 'ismount', 'join', 'lexists', 'normcase', 'normpath', 'os', 'pardir', 'pathsep', 'realpath', 'sep', 'split', 'splitdrive', 'splitext', 'splitunc', 'stat', 'supports_unicode_filenames', 'sys', 'walk'] Anyways... could someone please point me in the right direction? I can use os.system('md test'), but that isn't cross platform... Hopefully nothing is wrong with my python installation. Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061011/9b0bf72a/attachment.htm From Mike.Hansen at atmel.com Thu Oct 12 00:06:38 2006 From: Mike.Hansen at atmel.com (Mike Hansen) Date: Wed, 11 Oct 2006 16:06:38 -0600 Subject: [Tutor] Creating folders in windows... Message-ID: <57B026980605A64F9B23484C5659E32E3587CD@poccso.US.ad.atmel.com> ________________________________ From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Chris Hengge Sent: Wednesday, October 11, 2006 4:00 PM To: Python Tutor Subject: [Tutor] Creating folders in windows... I found this from a 2004 mailing on this list.. os.path.mkdir('folder') Doesn't work... there is no mkdir in os.path (old style maybe?) >>> os.path.mkdir('folder') Traceback (most recent call last): File "", line 1, in ? AttributeError: 'module' object has no attribute 'mkdir' >>> dir(os.path) ['__all__', '__builtins__', '__doc__', '__file__', '__name__', 'abspath', 'altsep', 'basename', 'commonprefix', 'curdir', 'defpath', 'devnull', 'dirname', 'exists', 'expanduser', 'expandvars', 'extsep', 'getatime', 'getctime', 'getmtime', 'getsize', 'isabs', 'isdir', 'isfile', 'islink', 'ismount', 'join', 'lexists', 'normcase', 'normpath', 'os', 'pardir', 'pathsep', 'realpath', 'sep', 'split', 'splitdrive', 'splitext', 'splitunc', 'stat', 'supports_unicode_filenames', 'sys', 'walk'] Anyways... could someone please point me in the right direction? I can use os.system('md test'), but that isn't cross platform... Hopefully nothing is wrong with my python installation. Thanks! ------------ You might try os.mkdir instead of os.path.mkdir Mike From euoar at yahoo.es Thu Oct 12 00:26:28 2006 From: euoar at yahoo.es (Alfonso) Date: Thu, 12 Oct 2006 00:26:28 +0200 Subject: [Tutor] not such file or directory exception Message-ID: <452D6F94.4010402@yahoo.es> Trying to copy or move files -I do it with move or copyfile- between directories, with characters of the spanish language gives me this error: not such file or directory. I suppose this is related with unicode, any idea how can I handle it? Thank you very much, in advance. (My system is in spanish, I use linux). ______________________________________________ LLama Gratis a cualquier PC del Mundo. Llamadas a fijos y m?viles desde 1 c?ntimo por minuto. http://es.voice.yahoo.com From rabidpoobear at gmail.com Thu Oct 12 00:29:57 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 11 Oct 2006 17:29:57 -0500 Subject: [Tutor] not such file or directory exception In-Reply-To: <452D6F94.4010402@yahoo.es> References: <452D6F94.4010402@yahoo.es> Message-ID: <452D7065.3030803@gmail.com> Alfonso wrote: > Trying to copy or move files -I do it with move or copyfile- between > directories, with characters of the spanish language gives me this > error: not such file or directory. I suppose this is related with > unicode, any idea how can I handle it? > Can you give us the code you're using? > > Thank you very much, in advance. > (My system is in spanish, I use linux). > > > ______________________________________________ > LLama Gratis a cualquier PC del Mundo. > Llamadas a fijos y m?viles desde 1 c?ntimo por minuto. > http://es.voice.yahoo.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From Barry.Carroll at psc.com Thu Oct 12 00:45:05 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Wed, 11 Oct 2006 15:45:05 -0700 Subject: [Tutor] VIM & Python Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C376C@eugsrv400.psc.pscnet.com> I'm a Vim user, too. I usually have three windows open: IPython to try out snippets of code, ViM to edit the target program, and a command shell to execute the module/run the self tests. A while back I asked the ViM mailing list (vim at vim.org) if there was a way to open a shell window from within ViM. Here is the response I got: ** Vim can be compiled with Python support; the output of the ":version" ** command will then show either +python or +python/dyn ** With such a version of Vim, you can execute individual Python commands, ** inline Python documents in Vim scripts, or full-fledged Python scripts. ** Also, Python commands called from Vim may access Vim buffers, windows, ** variables, etc., giving you access to the power of both Vim and Python ** in a single script. Of course, 'T Aint No Such Thing As A Free Lunch: ** such a script is more powerful but less portable, since it can only be ** run on a machine where both Vim and Python are installed. ** See ":help python" for details of how to use the Python interface. I read the suggested help pages, but I haven't had the nerve to try out the interface yet. When I do, I'll post my findings here. Regards, Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed > -----Original Message----- > Date: Wed, 11 Oct 2006 21:40:56 +0100 > Subject: [Tutor] VIM & Python > To: tutor at python.org > > > I use VIM to write my Python programs. I usually have a shell open > > to run > > pyflakes on the file I just edited. Is there a way to run pyflakes > > from > > within VIM and have it display the errors in another buffer? From pyro9219 at gmail.com Thu Oct 12 01:15:50 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Wed, 11 Oct 2006 16:15:50 -0700 Subject: [Tutor] Creating folders in windows... In-Reply-To: References: Message-ID: Now, how would I enter this folder? lets say, to make a subfolder or create files inside it? I see os.chdir() but that either can't see newly created folders, or I must use the complete path... I'm not sure which. just created folder 'test' in current scripts directory... os.chdir('test') no such file or directory Thanks again... On 10/11/06, Chris Hengge wrote: > > I found this from a 2004 mailing on this list.. > os.path.mkdir('folder') > Doesn't work... there is no mkdir in os.path (old style maybe?) > > >>> os.path.mkdir('folder') > Traceback (most recent call last): > > File "", line 1, in ? > AttributeError: 'module' object has no attribute 'mkdir' > > > >>> dir(os.path) > ['__all__', '__builtins__', '__doc__', '__file__', '__name__', 'abspath', 'altsep', > > 'basename', 'commonprefix', 'curdir', 'defpath', 'devnull', 'dirname', 'exists', > 'expanduser', 'expandvars', 'extsep', 'getatime', 'getctime', 'getmtime', 'getsize', > 'isabs', 'isdir', 'isfile', 'islink', 'ismount', 'join', 'lexists', 'normcase', > > 'normpath', 'os', 'pardir', 'pathsep', 'realpath', 'sep', 'split', 'splitdrive', > 'splitext', 'splitunc', 'stat', 'supports_unicode_filenames', 'sys', 'walk'] > > Anyways... could someone please point me in the right direction? > > I can use os.system('md test'), but that isn't cross platform... > Hopefully nothing is wrong with my python installation. > > Thanks! > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061011/5ad7ec74/attachment.html From kent37 at tds.net Thu Oct 12 01:45:05 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 11 Oct 2006 19:45:05 -0400 Subject: [Tutor] Responding to a request for input from a MS-DOS program In-Reply-To: References: <54BE2FC5ADFC254B832681E9622AACFEC6F3C5@EXCHANGE23.staff.main.ntu.edu.sg> Message-ID: <452D8201.5060608@tds.net> Alan Gauld wrote: > Finally, for more sophisticated scenarios there is a module > implementing the expect program in Python, but I suspect that will > be overkill here. pyexpect requires the pty module which is not supported on Windows. Kent From kent37 at tds.net Thu Oct 12 02:49:31 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 11 Oct 2006 20:49:31 -0400 Subject: [Tutor] Workaround for limitation in xrange()? In-Reply-To: References: <7.0.1.0.2.20061010081254.022073e0@rcblue.com> <7.0.1.0.2.20061010102836.06be3ae0@rcblue.com> Message-ID: <452D911B.9030300@tds.net> Alan Gauld wrote: > "Dick Moores" wrote in message > news:7.0.1.0.2.20061010102836.06be3ae0 at rcblue.com... >> Encapsulate the while loop in a generator: >> def count(limit): >> n=0 >> while n> yield n >> n += 1 >> >> All 3 are essentially the same, aren't they. Which makes me feel >> even >> dumber, because I don't understand any of them. I've consulted 3 >> books, and still don't understand the use of yield. > > Think of yield as being the same as return except that next time > you "call the function" all the state is preserved and it picks up > processing > after the yield. A small correction - in normal use you only call the generator function once. The value it returns is a generator, an object with a next() method. It is the next() method that is called repeatedly to re-enter the function and return the next value. When there are no more values to return, the next() method raises StopIteration. For example: In [1]: def f(): yield 1 ...: In [2]: f Out[2]: f is a generator function. The result of calling it is a generator: In [3]: p=f() In [4]: p Out[4]: The generator p is not callable: In [5]: p() --------------------------------------------------------------------------- Traceback (most recent call last) D:\Projects\e3po\ in () : 'generator' object is not callable p.next() yields values, then raises StopIteration: In [6]: p.next() Out[6]: 1 In [7]: p.next() --------------------------------------------------------------------------- Traceback (most recent call last) D:\Projects\e3po\ in () : The generator also has an __iter__() method that returns the generator itself: In [9]: p.__iter__() is p Out[9]: True In other words, a generator satisfies the iterator protocol http://docs.python.org/lib/typeiter.html and it can be used any where an iterator can be used, such as in a for statement. Kent > > So first time you call count above it returns 0 > next time you call it it executes the n+= 1 and goes round the loop > again until it hits yield when it returns 1. > next time you call it executes y+=1 again, but because the state has > been remembered n goes to 2 and yield returns that > and so on until you reach n = limit at which point it just > exits with StopIteration. Here is a short example: > >>>> def y(n): > ... j = 0 > ... while j < n: > ... yield j > ... j += 1 > ... >>>> try: > ... x = y(7) > ... for n in range(20): > ... print x.next() > ... except StopIteration: > ... print 'Reached the end' > ... > 0 > 1 > 2 > 3 > 4 > 5 > 6 > Reached the end > > Does that help? > > From carroll at tjc.com Thu Oct 12 02:54:39 2006 From: carroll at tjc.com (Terry Carroll) Date: Wed, 11 Oct 2006 17:54:39 -0700 (PDT) Subject: [Tutor] What are these things urandom() returns? In-Reply-To: <1f7befae0610102201g22dfbedag70e64e8e870eeadc@mail.gmail.com> Message-ID: On Wed, 11 Oct 2006, Tim Peters wrote: > If you want /true/ randomness, you can buy a certified hardware random > number generator, based on non-deterministic physical processes (like > timing radioactive decay, or measuring thermal noise). Why buy when you can borrow?: def truerandom(n): """ truerandom(n) --> str Return a string of n truly random bytes. see: http://www.fourmilab.ch/hotbits/ http://www.fourmilab.ch/hotbits/generate.html """ import urllib _url = "http://www.fourmilab.ch/cgi-bin/Hotbits?nbytes=%s&fmt=bin" % n return urllib.urlopen(_url).read() From tim.peters at gmail.com Thu Oct 12 03:39:30 2006 From: tim.peters at gmail.com (Tim Peters) Date: Wed, 11 Oct 2006 21:39:30 -0400 Subject: [Tutor] What are these things urandom() returns? In-Reply-To: References: <1f7befae0610102201g22dfbedag70e64e8e870eeadc@mail.gmail.com> Message-ID: <1f7befae0610111839t6fe7f60es3a564b85bd55eea0@mail.gmail.com> [Tim Peters] >> If you want /true/ randomness, you can buy a certified hardware random >> number generator, based on non-deterministic physical processes (like >> timing radioactive decay, or measuring thermal noise). [Terry Carroll] > Why buy when you can borrow?: Speed and capacity, for two things ;-) As the HotBits page says, their method can't create more than about 100 bytes per second. So even if they were willing (which they aren't) to satisfy a request for 1000000 random bytes (as Dick used in one of his programs), it would take close to 3 hours to get them. Worse, many applications consume 1000s of times more than a measly million random bytes. > def truerandom(n): > """ > truerandom(n) --> str > > Return a string of n truly random bytes. > > see: > http://www.fourmilab.ch/hotbits/ > http://www.fourmilab.ch/hotbits/generate.html > > """ > > import urllib > _url = "http://www.fourmilab.ch/cgi-bin/Hotbits?nbytes=%s&fmt=bin" % n > return urllib.urlopen(_url).read() Note that a reasonable use for this service is to request a "small" number of random bytes to /seed/ a fast deterministic generator. From sisson.j at gmail.com Wed Oct 11 21:48:46 2006 From: sisson.j at gmail.com (Jonathon Sisson) Date: Wed, 11 Oct 2006 14:48:46 -0500 Subject: [Tutor] executing with double click on linux In-Reply-To: <452D491A.5000609@yahoo.es> References: <452D491A.5000609@yahoo.es> Message-ID: <452D4A9E.7020206@gmail.com> Alfonso wrote: > Sorry for the too obvious question. I'm new to python and have no idea > how can I make execute a compiled .pyc with a double click in linux, > with gnome. Trying to double click in a .py gives allways the question > wether I want to execute the text file, or read it. (This behaviour can > be changed with gconf-editor, but as it is for security matters, I would > prefer to execute the .pyc with a double click). I have tried to > associate python to the .pyc (first time I executed it there was no > programm associated), but it doesn't work. > I don't know how much Linux experience you have (judging by the "double-click" concept, I'm assuming you're coming from a Windows background or are perhaps catering to users with only a Windows background) (correct me if I'm wrong)...so I'm going to break this down as much as I can. .pyc files are considered binary files by Linux. As such, bash attempts to execute them as binary (ELF, etc...), which obviously won't work. If you really need to have double-click/execute functionality, consider writing a small shell script to execute the .pyc file for you. For instance, let's say you have a python script "foo.py" and a compiled python script "foo.pyc". If you attempt to run foo.py from the shell and you have a proper header (i.e. #!/usr/bin/python), then bash can execute the script. I'm assuming that GNOME has similar functionality (I prefer Fluxbox to either GNOME or KDE), which allows your .py files to execute directly. .pyc, however, even with a file association, fails to launch...on my system, I get this error: $ ./foo.pyc bash: ./foo.pyc: cannot execute binary file bash recognizes the file as binary, but it fails to launch as an ELF binary (or whatever you're set up to run). To fix it, simply write a shell script as such: #!/bin/sh python /home/me/scripts/foo.pyc Name the script whatever you want (i.e. foo.sh) then run from the commandline: $ chmod 700 foo.sh This gives the script read/write/execute permissions for the owner of the script...if you require read/write/execute/etc...for group or all, change 700 to whatever you need. (i.e. 755 for rwxr-xr-x permissions) (Alternatively you can right click on the shell script and set permissions graphically...whichever you prefer) Now, you should be able to double-click the script (or preferably a shortcut to the script on your desktop), which will launch the compiled python module for you. If this seems like a lot of work, then perhaps you could write a shell script to automate the task of creating the shell script and setting permissions each time you create a new .pyc...doh? Hope this is a satisfactory answer...and if anyone knows something I have overlooked, please let Alfonso and I know. Jonathon > Thank you for your answer. > > > ______________________________________________ > LLama Gratis a cualquier PC del Mundo. > Llamadas a fijos y m?viles desde 1 c?ntimo por minuto. > http://es.voice.yahoo.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From faranuddin at gmail.com Thu Oct 12 06:08:26 2006 From: faranuddin at gmail.com (Faran Uddin) Date: Wed, 11 Oct 2006 21:08:26 -0700 Subject: [Tutor] SQL Queries For MySQL Message-ID: <907cc7070610112108t134b1952k13a3b22aafa9b7ca@mail.gmail.com> i m running a mysql database, i create the connections and such using MySQLdb. someone told me that queries like query = "SELECT * FROM DB WHERE NAME = %s" % (name) cursor.execute(query) thats the syntax that i use, but someone told me not to use it, i m new to the db accessing thing, so if anyone can plz explain this and also send me an example of how to do this properly, it'll help me quite a lot. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061011/65901824/attachment.htm From carroll at tjc.com Thu Oct 12 06:42:32 2006 From: carroll at tjc.com (Terry Carroll) Date: Wed, 11 Oct 2006 21:42:32 -0700 (PDT) Subject: [Tutor] What are these things urandom() returns? In-Reply-To: <1f7befae0610111839t6fe7f60es3a564b85bd55eea0@mail.gmail.com> Message-ID: On Wed, 11 Oct 2006, Tim Peters wrote: > Speed and capacity, for two things ;-) As the HotBits page says, > their method can't create more than about 100 bytes per second. Yeah, I just couldn't resist. > So even if they were willing (which they aren't) to satisfy a request > for 1000000 random bytes (as Dick used in one of his programs), it would > take close to 3 hours to get them. Actually, there's a limited number of requests you can make in a 24-hour period; so this really isn't practical, except maybe... > Note that a reasonable use for this service is to request a "small" > number of random bytes to /seed/ a fast deterministic generator. Yup. From contact at endarion.com Thu Oct 12 09:01:35 2006 From: contact at endarion.com (Michael Shulman) Date: Thu, 12 Oct 2006 03:01:35 -0400 Subject: [Tutor] cylinder texture map? Message-ID: <452DE84F.6090607@endarion.com> Hello, You guys gave fantastic advice for my last question about point in polygon testing, thanks. New question; I'd like to make a scrolling background for a game I'm working on. I was thinking, since it's all in orthographic view, that a horizontal cylinder which rotates with a texture would simulate this very well. I've never used textures before, and in all the sample code I see, they have polygons with defined points, so it's very straightforward to see what goes with what... but I don't see how to make the switch over to the glut primitives. Any samples/ insights would be awesome. Thanks a bunch, -Mike From alan.gauld at btinternet.com Thu Oct 12 09:31:04 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 12 Oct 2006 08:31:04 +0100 Subject: [Tutor] SQL Queries For MySQL References: <907cc7070610112108t134b1952k13a3b22aafa9b7ca@mail.gmail.com> Message-ID: > query = "SELECT * FROM DB WHERE NAME = %s" % (name) > cursor.execute(query) There can be security issues with this style, especially if the parameters can be modified by users - for example you read the values from a web page. The cursor.execute() call has the ability to pass the parameters in directly, ie combining the two statements above into one. The details of how ypou do that varies between database drivers so you need to check the documents but I think for MySQL its almost an exact translation: query = "SELECT * FROM DB WHERE NAME = %s" cursor.execute(query, name) If you search the ist archives you'll find a fairly long thread describing the whys/wherefores in much more depth. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From rdm at rcblue.com Thu Oct 12 11:15:29 2006 From: rdm at rcblue.com (Dick Moores) Date: Thu, 12 Oct 2006 02:15:29 -0700 Subject: [Tutor] Why is random.choice so much slower than random.random()? Message-ID: <7.0.1.0.2.20061012011635.06535408@rcblue.com> Why is random.choice so much slower than random.random()? In fact, by a factor of 12! And randint(). Some 25 times slower than random(). Why? (I know that random() is the basis for most of the other functions in the random module, and a look at random.py, though I don't complete understand it, gives me an idea what's going on with randint(), etc., still...) C:\>python -m timeit -s"from random import choice" "for x in range(10000): " " choice([0, 1])" 10 loops, best of 3: 22.8 msec per loop C:\>python -m timeit -s"from random import random" "for x in range(10000): " " random()" 1000 loops, best of 3: 1.84 msec per loop C:\>python -m timeit -s"from random import uniform" "for x in range(10000) :" " uniform(0, 1)" 100 loops, best of 3: 12.2 msec per loop C:\>python -m timeit -s"from random import randrange" "for x in range(1000 0):" " randrange(2)" 10 loops, best of 3: 25.3 msec per loop C:\>python -m timeit -s"from random import randint" "for x in range(10000) :" " randint(0, 1)" 10 loops, best of 3: 45.9 msec per loop Anyway, if you are making a coin flipping program, with a great many flips and speed is important, it seems a good idea to avoid the otherwise obvious choice of choice(). coin = choice(["heads", "tails"]). instead, use value = random() if value >= .5: coin = "heads" else: coin = "tails" I tested these in order, using the template in random.py (a copy of it of course): Evaluating timeitRandom-1.py 100 loops, best of 3: 4.24 msec per loop SystemExit: >>> Evaluating timeitRandom-2.py 10 loops, best of 3: 27.9 msec per loop SystemExit: >>> (Thanks, Kent) Even with all the extra baggage attached to it, random() is 6.6 times faster than choice with no baggage! Dick Moores From rabidpoobear at gmail.com Thu Oct 12 11:24:55 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 12 Oct 2006 04:24:55 -0500 Subject: [Tutor] Why is random.choice so much slower than random.random()? In-Reply-To: <7.0.1.0.2.20061012011635.06535408@rcblue.com> References: <7.0.1.0.2.20061012011635.06535408@rcblue.com> Message-ID: <452E09E7.80107@gmail.com> Dick Moores wrote: > Why is random.choice so much slower than random.random()? In fact, by > a factor of 12! And randint(). Some 25 times slower than random(). Why? > (I know that random() is the basis for most of the other functions in > the random module, and a look at random.py, though I don't complete > understand it, gives me an idea what's going on with randint(), etc., still...) > I haven't looked at the random code, but what I expect is happening is that for random.choice(a) you need to 1) get a random number 2) convert that random number into an index into your list. eg. [0,1] any random number < .5 would be index 0. recall that random goes from 0 to 1. 3) grab that item from the list and return it. I'm guessing that step 2 and step 3 are why it takes a while, since these are probably implemented in Python. for random.randint(a,b): It might do random.choice(range(a,b+1)) so there's the overhead of generating the range. Course this is completely speculation and may be not true at all, but I thought I'd give it a shot :) From kent37 at tds.net Thu Oct 12 13:33:30 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 12 Oct 2006 07:33:30 -0400 Subject: [Tutor] Why is random.choice so much slower than random.random()? In-Reply-To: <7.0.1.0.2.20061012011635.06535408@rcblue.com> References: <7.0.1.0.2.20061012011635.06535408@rcblue.com> Message-ID: <452E280A.6030102@tds.net> Dick Moores wrote: > Why is random.choice so much slower than random.random()? In fact, by > a factor of 12! And randint(). Some 25 times slower than random(). Why? > (I know that random() is the basis for most of the other functions in > the random module, and a look at random.py, though I don't complete > understand it, gives me an idea what's going on with randint(), etc., still...) > > C:\>python -m timeit -s"from random import choice" "for x in range(10000): > " " choice([0, 1])" > 10 loops, best of 3: 22.8 msec per loop > > C:\>python -m timeit -s"from random import random" "for x in range(10000): > " " random()" > 1000 loops, best of 3: 1.84 msec per loop > > C:\>python -m timeit -s"from random import uniform" "for x in range(10000) > :" " uniform(0, 1)" > 100 loops, best of 3: 12.2 msec per loop > > C:\>python -m timeit -s"from random import randrange" "for x in range(1000 > 0):" " randrange(2)" > 10 loops, best of 3: 25.3 msec per loop > > C:\>python -m timeit -s"from random import randint" "for x in range(10000) > :" " randint(0, 1)" > 10 loops, best of 3: 45.9 msec per loop Looking at the code and your numbers, my guess is that the time to make a Python function call on your computer is about 2 microseconds (20 msec / 10000). (I mean the entire overhead - looking up the function and actually calling it.) random.randint() just calls random.randrange() after incrementing the upper limit. So the difference in times between these two is one addition and a function call. randrange() does a little checking, then calls random(). The time difference is a little more than 20 msec, probably due to the argument checking. > Anyway, if you are making a coin flipping program, with a great many > flips and speed is important, it seems a good idea to avoid the > otherwise obvious choice of choice(). And more generally, in a highly optimized loop, avoid function calls if possible, they are relatively expensive in Python. Kent From deandermo at hotmail.com Thu Oct 12 13:21:15 2006 From: deandermo at hotmail.com (deandermo) Date: Thu, 12 Oct 2006 12:21:15 +0100 Subject: [Tutor] tutor required Message-ID: please can you help me ? i need a private tutor to learn me python , i know this may seem strange but im finding it really difficult to learn , ive very website there is 'and im just not learning , i would feel better iff i had someone teaching it me ,. do you know of anyone who could help me out ? please get in touch. many thanks dean dermody -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061012/54cab570/attachment.htm From deandermo at hotmail.com Thu Oct 12 13:29:59 2006 From: deandermo at hotmail.com (deandermo) Date: Thu, 12 Oct 2006 12:29:59 +0100 Subject: [Tutor] python tutor Message-ID: can any one please help im looking for a personal tutor that can help me with learning python . im finding it alien to me as i am a beginer ive tried numerous websites and i am still finding it stranfe to . can anyone help me ?????? many thanks dean dermody -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061012/46d10564/attachment.html From deandermo at hotmail.com Thu Oct 12 14:14:25 2006 From: deandermo at hotmail.com (dean dermody) Date: Thu, 12 Oct 2006 12:14:25 +0000 Subject: [Tutor] (no subject) Message-ID: An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061012/23f7279d/attachment.html From alan.gauld at btinternet.com Thu Oct 12 14:36:14 2006 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Thu, 12 Oct 2006 13:36:14 +0100 (BST) Subject: [Tutor] Fwd: do you know how to do this Message-ID: <20061012123614.58313.qmail@web86103.mail.ird.yahoo.com> Forwarding to the group... --- anil maran wrote: > Date: Thu, 12 Oct 2006 01:46:44 -0700 (PDT) > From: anil maran > Subject: do you know how to do this > To: Alan Gauld > > The user, password and group are stored in a session on disk > using > flup.middleware.session. You can change this to fit your needs > like in > a database. I think someone have already extended the flup > session with > a database store? > > Use the decorator function on your GET and POST method to set > authentication and provide which group are allowed. > > If auth is set to True and user/password/access did not match, > a > redirect is made to /login. > > > > Anil > > > > ----- Original Message ---- > From: Alan Gauld > To: tutor at python.org > Sent: Thursday, October 12, 2006 12:31:04 AM > Subject: Re: [Tutor] SQL Queries For MySQL > > > > query = "SELECT * FROM DB WHERE NAME = %s" % (name) > > cursor.execute(query) > > There can be security issues with this style, especially > if the parameters can be modified by users - for example > you read the values from a web page. > > The cursor.execute() call has the ability to pass the > parameters > in directly, ie combining the two statements above into one. > The details of how ypou do that varies between database > drivers so you need to check the documents but I think for > MySQL its almost an exact translation: > > query = "SELECT * FROM DB WHERE NAME = %s" > cursor.execute(query, name) > > If you search the ist archives you'll find a fairly long > thread > describing the whys/wherefores in much more depth. > > HTH, > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > Send instant messages to your online friends http://uk.messenger.yahoo.com From alan.gauld at btinternet.com Thu Oct 12 14:46:15 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 12 Oct 2006 13:46:15 +0100 Subject: [Tutor] python tutor References: Message-ID: This list does not provide private tutors as such. But you can ask questions about topics that you don't understand on the web sites (preferrably with a link to the page in question) and people will try to clarify what is meant. The advantages of the list approach are: 1) More tutors so more chance of one finding an explanation you understand 2) The are other beginners on the list who may understand your perspective better than an expert who may take for granted certain assumptions that are not valid for a beginner. 3) Your learning experience gets shared to otherbgefginners who may be struggling with the same issues. The downside is that you have to be brave enough to publicly ask questions thatyou think are probably too basic, however any question is valid on this list. It is designed for beginners after all! If you are really lucky some individuial suibscriber may offer one on one coaching, or recommend a training course local to you. Finally, I recommend that you tackle one web tutor/book at a time, certainy not more than 2 in parallel to avoid getting confused over terminology etc. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld "deandermo" wrote in message news:BAY104-DAV15A6995D7606329F5E792BB0150 at phx.gbl... can any one please help im looking for a personal tutor that can help me with learning python . im finding it alien to me as i am a beginer ive tried numerous websites and i am still finding it stranfe to . can anyone help me ?????? many thanks dean dermody -------------------------------------------------------------------------------- From rdm at rcblue.com Thu Oct 12 14:56:55 2006 From: rdm at rcblue.com (Dick Moores) Date: Thu, 12 Oct 2006 05:56:55 -0700 Subject: [Tutor] Why is random.choice so much slower than random.random()? In-Reply-To: <452E280A.6030102@tds.net> References: <7.0.1.0.2.20061012011635.06535408@rcblue.com> <452E280A.6030102@tds.net> Message-ID: <7.0.1.0.2.20061012055337.06903568@rcblue.com> At 04:33 AM 10/12/2006, Kent Johnson wrote: >Looking at the code and your numbers, my guess is that the time to make >a Python function call on your computer is about 2 microseconds (20 msec >/ 10000). (I mean the entire overhead - looking up the function and >actually calling it.) Hm. Does this test include the entire overhead? C:\>python -m timeit -r 3 -s"from random import random" "random()" 10000000 loops, best of 3: 0.157 usec per loop Dick From ajkadri at googlemail.com Thu Oct 12 15:06:00 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Thu, 12 Oct 2006 14:06:00 +0100 Subject: [Tutor] Help with basic user-data file Message-ID: Folks, I am trying to modify the userManagement program given in Core Python Programming. It uses a dictionary to store user-password information. The usernames are the keys and the passwords are the values. Now I want is to add a third element; last login time. I want to store this information in a file so that the data is not lost once the program stops execution. I am not sure of using time function in python.. Can anyone help with this issue?? REgards. Asrar -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061012/22a95821/attachment.html From kent37 at tds.net Thu Oct 12 15:15:17 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 12 Oct 2006 09:15:17 -0400 Subject: [Tutor] Why is random.choice so much slower than random.random()? In-Reply-To: <7.0.1.0.2.20061012055337.06903568@rcblue.com> References: <7.0.1.0.2.20061012011635.06535408@rcblue.com> <452E280A.6030102@tds.net> <7.0.1.0.2.20061012055337.06903568@rcblue.com> Message-ID: <452E3FE5.4060701@tds.net> Dick Moores wrote: > At 04:33 AM 10/12/2006, Kent Johnson wrote: >> Looking at the code and your numbers, my guess is that the time to make >> a Python function call on your computer is about 2 microseconds (20 msec >> / 10000). (I mean the entire overhead - looking up the function and >> actually calling it.) > > Hm. Does this test include the entire overhead? > > C:\>python -m timeit -r 3 -s"from random import random" "random()" > 10000000 loops, best of 3: 0.157 usec per loop I don't know why that one is faster. Maybe because it is calling a function in C, or because there are no arguments? Someone else will have to answer that. Kent From jfabiani at yolo.com Thu Oct 12 15:19:30 2006 From: jfabiani at yolo.com (johnf) Date: Thu, 12 Oct 2006 06:19:30 -0700 Subject: [Tutor] SQL Queries For MySQL In-Reply-To: References: <907cc7070610112108t134b1952k13a3b22aafa9b7ca@mail.gmail.com> Message-ID: <200610120619.30379.jfabiani@yolo.com> On Thursday 12 October 2006 00:31, Alan Gauld wrote: > > query = "SELECT * FROM DB WHERE NAME = %s" % (name) > > cursor.execute(query) > > There can be security issues with this style, especially > if the parameters can be modified by users - for example > you read the values from a web page. > > The cursor.execute() call has the ability to pass the parameters > in directly, ie combining the two statements above into one. > The details of how ypou do that varies between database > drivers so you need to check the documents but I think for > MySQL its almost an exact translation: > > query = "SELECT * FROM DB WHERE NAME = %s" > cursor.execute(query, name) > > If you search the ist archives you'll find a fairly long thread > describing the whys/wherefores in much more depth. > > HTH, Since the archive is large - could you provide the subject title. Thanks John From rob.andrews at gmail.com Thu Oct 12 15:25:19 2006 From: rob.andrews at gmail.com (Rob Andrews) Date: Thu, 12 Oct 2006 08:25:19 -0500 Subject: [Tutor] Help with basic user-data file In-Reply-To: References: Message-ID: <8d757d2e0610120625wb121336yfcf58f91cf13980c@mail.gmail.com> To keep the information, the simplest solution is simply to save it in a text file that the program can load into memory when it starts up again. For sensitive information like passwords, a little extra fuss is generally merited. When someone logs in, you can save a value like time.strftime(time.ctime()) for a nice, human-readable time stamp. Don't forget to "import time" first. -Rob A. On 10/12/06, Asrarahmed Kadri wrote: > Folks, > > I am trying to modify the userManagement program given in Core Python > Programming. It uses a dictionary to store user-password information. The > usernames are the keys and the passwords are the values. > Now I want is to add a third element; last login time. > I want to store this information in a file so that the data is not lost once > the program stops execution. > > I am not sure of using time function in python.. > Can anyone help with this issue?? From ajkadri at googlemail.com Thu Oct 12 15:41:39 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Thu, 12 Oct 2006 14:41:39 +0100 Subject: [Tutor] Help with basic user-data file In-Reply-To: <8d757d2e0610120625wb121336yfcf58f91cf13980c@mail.gmail.com> References: <8d757d2e0610120625wb121336yfcf58f91cf13980c@mail.gmail.com> Message-ID: It means there is no need of entering the data in the dictionary,?? How will I then implement the uniqueness of loginnames??? Thanks for the support. regards, Asrar On 10/12/06, Rob Andrews wrote: > > To keep the information, the simplest solution is simply to save it in > a text file that the program can load into memory when it starts up > again. For sensitive information like passwords, a little extra fuss > is generally merited. > > When someone logs in, you can save a value like > time.strftime(time.ctime()) for a nice, human-readable time stamp. > Don't forget to "import time" first. > > -Rob A. > > On 10/12/06, Asrarahmed Kadri wrote: > > Folks, > > > > I am trying to modify the userManagement program given in Core Python > > Programming. It uses a dictionary to store user-password information. > The > > usernames are the keys and the passwords are the values. > > Now I want is to add a third element; last login time. > > I want to store this information in a file so that the data is not lost > once > > the program stops execution. > > > > I am not sure of using time function in python.. > > Can anyone help with this issue?? > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061012/7605682f/attachment.htm From nephish at gmail.com Thu Oct 12 15:44:44 2006 From: nephish at gmail.com (shawn bright) Date: Thu, 12 Oct 2006 08:44:44 -0500 Subject: [Tutor] question about number of threads Message-ID: <384c93600610120644h6d775e9ciafaf8745eb273349@mail.gmail.com> Hey there, i have an app that runs several processes as threads. using the threading.Thread() now, i have another app that does the same thing. Now, pretty soon, we will be combining all the features of the two packages together into one app. My question is, is there a limit on how many threads one GUI application can have running in the background ? Most of them are sleeping most of the time. They wake up and do something every 10 seconds, 20 minutes, etc... Any pitfalls out there i shoud know about ? thanks shawn -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061012/359447ef/attachment.html From rob.andrews at gmail.com Thu Oct 12 15:53:56 2006 From: rob.andrews at gmail.com (Rob Andrews) Date: Thu, 12 Oct 2006 08:53:56 -0500 Subject: [Tutor] Help with basic user-data file In-Reply-To: References: <8d757d2e0610120625wb121336yfcf58f91cf13980c@mail.gmail.com> Message-ID: <8d757d2e0610120653h6845f97p5ed9e0131474b52@mail.gmail.com> When a login name is being created, you can pull a list of existing login names from file, and run a check to see if it is in the list. If the new name is in the list, have it kick back a message telling the user to try another name. Also, your program could suggest a new user name in such a case, or even assign new users names of its choosing. The dictionary data structure is handy for the program to use in very efficiently matching user names with passwords. But you don't have to store the dictionary in a file as a dictionary. It's possible to do so, but often easier to use a delimited text file. On 10/12/06, Asrarahmed Kadri wrote: > It means there is no need of entering the data in the dictionary,?? > > How will I then implement the uniqueness of loginnames??? > > Thanks for the support. > regards, > Asrar > > > On 10/12/06, Rob Andrews wrote: > > > > To keep the information, the simplest solution is simply to save it in > > a text file that the program can load into memory when it starts up > > again. For sensitive information like passwords, a little extra fuss > > is generally merited. > > > > When someone logs in, you can save a value like > > time.strftime(time.ctime()) for a nice, human-readable time stamp. > > Don't forget to "import time" first. > > > > -Rob A. > > > > On 10/12/06, Asrarahmed Kadri wrote: > > > Folks, > > > > > > I am trying to modify the userManagement program given in Core Python > > > Programming. It uses a dictionary to store user-password information. > The > > > usernames are the keys and the passwords are the values. > > > Now I want is to add a third element; last login time. > > > I want to store this information in a file so that the data is not lost > once > > > the program stops execution. > > > > > > I am not sure of using time function in python.. > > > Can anyone help with this issue?? > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > -- > To HIM you shall return. -- Blogging my outdoors obsession: http://trekkingbob.blogspot.com/ From kent37 at tds.net Thu Oct 12 16:03:05 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 12 Oct 2006 10:03:05 -0400 Subject: [Tutor] question about number of threads In-Reply-To: <384c93600610120644h6d775e9ciafaf8745eb273349@mail.gmail.com> References: <384c93600610120644h6d775e9ciafaf8745eb273349@mail.gmail.com> Message-ID: <452E4B19.4040604@tds.net> shawn bright wrote: > Hey there, > i have an app that runs several processes as threads. > using the threading.Thread() > > now, i have another app that does the same thing. Now, pretty soon, we > will be combining all the features of the two packages together into one > app. > > My question is, is there a limit on how many threads one GUI application > can have running in the background ? > Most of them are sleeping most of the time. They wake up and do > something every 10 seconds, 20 minutes, etc... IIRC the number of threads is limited by memory - each thread requires some heap space for its stack, etc. I don't think you will have trouble until you have hundreds or thousands of threads. For example on my computer this program prints 1031 before it exits with thread.error: can't start new thread: import time from threading import Thread, activeCount def run(): while 1: time.sleep(1) while 1: print activeCount() t=Thread(target=run) t.setDaemon(1) t.start() (The setDaemon() call lets the application exit normally when it gets an exception; otherwise it hangs with all the threads running.) Kent From jason.massey at gmail.com Thu Oct 12 16:14:59 2006 From: jason.massey at gmail.com (Jason Massey) Date: Thu, 12 Oct 2006 09:14:59 -0500 Subject: [Tutor] SQL Queries For MySQL In-Reply-To: <200610120619.30379.jfabiani@yolo.com> References: <907cc7070610112108t134b1952k13a3b22aafa9b7ca@mail.gmail.com> <200610120619.30379.jfabiani@yolo.com> Message-ID: <7e3eab2c0610120714i1e6d45a3p90f561a4f921ae32@mail.gmail.com> On 10/12/06, johnf wrote: > > > On Thursday 12 October 2006 00:31, Alan Gauld wrote: > > > query = "SELECT * FROM DB WHERE NAME = %s" % (name) > > > cursor.execute(query) > > > > There can be security issues with this style, especially > > if the parameters can be modified by users - for example > > you read the values from a web page. > > > > The cursor.execute() call has the ability to pass the parameters > > in directly, ie combining the two statements above into one. > > The details of how ypou do that varies between database > > drivers so you need to check the documents but I think for > > MySQL its almost an exact translation: > > > > query = "SELECT * FROM DB WHERE NAME = %s" > > cursor.execute(query, name) > > > > If you search the ist archives you'll find a fairly long thread > > describing the whys/wherefores in much more depth. > > > > HTH, > Since the archive is large - could you provide the subject title. > > Thanks > John > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Forgot to forward to the list... Check out this posting from Danny: http://mail.python.org/pipermail/tutor/2003-April/022010.html -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061012/1b2f7b7a/attachment.htm From nephish at gmail.com Thu Oct 12 16:16:10 2006 From: nephish at gmail.com (shawn bright) Date: Thu, 12 Oct 2006 09:16:10 -0500 Subject: [Tutor] Fwd: question about number of threads In-Reply-To: <384c93600610120715i8a486b1ndeac5ee781dd9ff5@mail.gmail.com> References: <384c93600610120644h6d775e9ciafaf8745eb273349@mail.gmail.com> <452E4B19.4040604@tds.net> <384c93600610120715i8a486b1ndeac5ee781dd9ff5@mail.gmail.com> Message-ID: <384c93600610120716g4d073772l8c9e48dc47de4025@mail.gmail.com> ---------- Forwarded message ---------- From: shawn bright Date: Oct 12, 2006 9:15 AM Subject: Re: [Tutor] question about number of threads To: Kent Johnson oh, well then i do not have anything to worry about. I was talking about a move from 6 threads to 10. he he. Thanks for the advice ! shawn On 10/12/06, Kent Johnson wrote: > > shawn bright wrote: > > Hey there, > > i have an app that runs several processes as threads. > > using the threading.Thread() > > > > now, i have another app that does the same thing. Now, pretty soon, we > > will be combining all the features of the two packages together into one > > app. > > > > My question is, is there a limit on how many threads one GUI application > > can have running in the background ? > > Most of them are sleeping most of the time. They wake up and do > > something every 10 seconds, 20 minutes, etc... > > IIRC the number of threads is limited by memory - each thread requires > some heap space for its stack, etc. I don't think you will have trouble > until you have hundreds or thousands of threads. > > For example on my computer this program prints 1031 before it exits with > thread.error: can't start new thread: > > import time > from threading import Thread, activeCount > > def run(): > while 1: > time.sleep(1) > > while 1: > print activeCount() > t=Thread(target=run) > t.setDaemon(1) > t.start() > > (The setDaemon() call lets the application exit normally when it gets an > exception; otherwise it hangs with all the threads running.) > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061012/db3d07cb/attachment.html From python at venix.com Thu Oct 12 16:19:13 2006 From: python at venix.com (Python) Date: Thu, 12 Oct 2006 10:19:13 -0400 Subject: [Tutor] SQL Queries For MySQL In-Reply-To: <200610120619.30379.jfabiani@yolo.com> References: <907cc7070610112108t134b1952k13a3b22aafa9b7ca@mail.gmail.com> <200610120619.30379.jfabiani@yolo.com> Message-ID: <1160662753.8103.365.camel@www.venix.com> On Thu, 2006-10-12 at 06:19 -0700, johnf wrote: > On Thursday 12 October 2006 00:31, Alan Gauld wrote: > > > query = "SELECT * FROM DB WHERE NAME = %s" % (name) > > > cursor.execute(query) > > > > There can be security issues with this style, especially > > if the parameters can be modified by users - for example > > you read the values from a web page. > > > > The cursor.execute() call has the ability to pass the parameters > > in directly, ie combining the two statements above into one. > > The details of how ypou do that varies between database > > drivers so you need to check the documents but I think for > > MySQL its almost an exact translation: > > > > query = "SELECT * FROM DB WHERE NAME = %s" > > cursor.execute(query, name) > > > > If you search the ist archives you'll find a fairly long thread > > describing the whys/wherefores in much more depth. > > > > HTH, > Since the archive is large - could you provide the subject title. http://www.google.com/search?hl=en&q=cursor.execute+tutor+python&btnG=Google+Search The above google search should get you pretty close. It is looking for: cursor.execute tutor python In particular, this link (from the first page) http://www.mail-archive.com/tutor at python.org/msg15716.html is probably part of the thread you want. > > Thanks > John > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From ajkadri at googlemail.com Thu Oct 12 16:48:58 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Thu, 12 Oct 2006 15:48:58 +0100 Subject: [Tutor] how to check whether a file exists or not?? Message-ID: Hello, Sorry, but this is a very basic questions... Can you tell me how to check the existence of a file.. Also if a file exists, and we open it in a write mode, it would be truncated to zero length. So what is the way out of this??# Regards, Asrar -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061012/20e13203/attachment.html From ziad.rahhal at gmail.com Thu Oct 12 17:00:53 2006 From: ziad.rahhal at gmail.com (Ziad Rahhal) Date: Thu, 12 Oct 2006 17:00:53 +0200 Subject: [Tutor] how to check whether a file exists or not?? In-Reply-To: References: Message-ID: On 10/12/06, Asrarahmed Kadri wrote: > > > Hello, > > Sorry, but this is a very basic questions... > Can you tell me how to check the existence of a file.. > to check if a file exists, you can use os.path.exists(path) or look at http://python.org/doc/current/lib/module-os.path.html for more info Also if a file exists, and we open it in a write mode, it would be truncated > to zero length. So what is the way out of this??# > > Regards, > > Asrar > -- > To HIM you shall return. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061012/8412d7de/attachment.htm From dyoo at hkn.eecs.berkeley.edu Thu Oct 12 19:05:43 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 12 Oct 2006 10:05:43 -0700 (PDT) Subject: [Tutor] python tutor In-Reply-To: References: Message-ID: > 1) More tutors so more chance of one finding an explanation you > understand Another advantage that can't be overstated is that of checks-and-balances: if any one of the tutors here gives erroneous advice, the other tutors here will provide error-correction. (I've had this happen for myself several times, and I'm grateful!) Contrast this situation with depending on a single authority who might not necessarily know what he or she is talking about. So there's a strength and reliability in a public forum like this that you won't easily find from private tutoring. From dyoo at hkn.eecs.berkeley.edu Thu Oct 12 19:17:14 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 12 Oct 2006 10:17:14 -0700 (PDT) Subject: [Tutor] do you know how to do this In-Reply-To: <20061012123614.58313.qmail@web86103.mail.ird.yahoo.com> References: <20061012123614.58313.qmail@web86103.mail.ird.yahoo.com> Message-ID: >> Date: Thu, 12 Oct 2006 01:46:44 -0700 (PDT) >> From: anil maran >> Subject: do you know how to do this >> To: Alan Gauld >> >> The user, password and group are stored in a session on disk using >> flup.middleware.session. You can change this to fit your needs like in >> a database. I think someone have already extended the flup session with >> a database store? >> >> Use the decorator function on your GET and POST method to set >> authentication and provide which group are allowed. >> >> If auth is set to True and user/password/access did not match, a >> redirect is made to /login. Anil, can you try to refocus your question? You have to be more specific than "Do you know how to do this?" because that can invite really flippant answers like "Yes" or "No". That's not going to be useful for you. Instead, try focusing us on what problems you're having. >From your message with Alan, I see a general problem statement with several requirements necessary for a solution. It really looks like a homework assignment. We are not allowed to go into a particular solution; we're going to have to limit ourselves to reduce the confusion you have with the problem, but that's it: you're going to have to do your own work on the problem. Is there any part in your assignment that you don't understand? Is there any part in there that you do understand? Do you understand all the terms used in the problem? At what point are you getting stuck? Have you worked on any other problem that's similar to the one you're looking at now? Good luck. From dyoo at hkn.eecs.berkeley.edu Thu Oct 12 19:34:38 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 12 Oct 2006 10:34:38 -0700 (PDT) Subject: [Tutor] cylinder texture map? In-Reply-To: <452DE84F.6090607@endarion.com> References: <452DE84F.6090607@endarion.com> Message-ID: On Thu, 12 Oct 2006, Michael Shulman wrote: > I'd like to make a scrolling background for a game I'm working on. I > was thinking, since it's all in orthographic view, that a horizontal > cylinder which rotates with a texture would simulate this very well. I have to admit I'm clueless about programming games. You might want to ask a game developer forum for better advice. There's also a few links on: http://pyopengl.sourceforge.net/documentation/ to several OpenGL tutorials, including: http://nehe.gamedev.net/ From adam.jtm30 at gmail.com Thu Oct 12 19:57:32 2006 From: adam.jtm30 at gmail.com (Adam Bark) Date: Thu, 12 Oct 2006 18:57:32 +0100 Subject: [Tutor] cylinder texture map? In-Reply-To: References: <452DE84F.6090607@endarion.com> Message-ID: On 12/10/06, Danny Yoo wrote: > > > > On Thu, 12 Oct 2006, Michael Shulman wrote: > > > I'd like to make a scrolling background for a game I'm working on. I > > was thinking, since it's all in orthographic view, that a horizontal > > cylinder which rotates with a texture would simulate this very well. > > > I have to admit I'm clueless about programming games. You might want to > ask a game developer forum for better advice. There's also a few links > on: > > http://pyopengl.sourceforge.net/documentation/ > > to several OpenGL tutorials, including: > > http://nehe.gamedev.net/ pygame.org and there mailing list might be helpful as well. The only thing I can think of for this is to use something like blender with an exact replica of the 3d object you plan to map to, unwrap it and make a uv mapping, ie you cut the 3d object up so it's flat draw the texture on then it fits perfectly when you apply it to the original object. HTH -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061012/6a2522b5/attachment.htm From rob.andrews at gmail.com Thu Oct 12 19:54:54 2006 From: rob.andrews at gmail.com (Rob Andrews) Date: Thu, 12 Oct 2006 12:54:54 -0500 Subject: [Tutor] Fwd: Help with basic user-data file In-Reply-To: References: <8d757d2e0610120625wb121336yfcf58f91cf13980c@mail.gmail.com> <8d757d2e0610120653h6845f97p5ed9e0131474b52@mail.gmail.com> Message-ID: <8d757d2e0610121054q55cb22e1ta67936cee6534065@mail.gmail.com> I'm forwarding this to the tutor list, as I'm swamped at work. ---------- Forwarded message ---------- From: Asrarahmed Kadri Date: Oct 12, 2006 9:17 AM Subject: Re: [Tutor] Help with basic user-data file To: Rob Andrews Thanks. Can you please also tell me how to check the existence of a file using python builtin functions. Regards, Asrar On 10/12/06, Rob Andrews wrote: > When a login name is being created, you can pull a list of existing > login names from file, and run a check to see if it is in the list. If > the new name is in the list, have it kick back a message telling the > user to try another name. > > Also, your program could suggest a new user name in such a case, or > even assign new users names of its choosing. > > The dictionary data structure is handy for the program to use in very > efficiently matching user names with passwords. But you don't have to > store the dictionary in a file as a dictionary. It's possible to do > so, but often easier to use a delimited text file. > > On 10/12/06, Asrarahmed Kadri wrote: > > It means there is no need of entering the data in the dictionary,?? > > > > How will I then implement the uniqueness of loginnames??? > > > > Thanks for the support. > > regards, > > Asrar > > > > > > On 10/12/06, Rob Andrews < rob.andrews at gmail.com> wrote: > > > > > > To keep the information, the simplest solution is simply to save it in > > > a text file that the program can load into memory when it starts up > > > again. For sensitive information like passwords, a little extra fuss > > > is generally merited. > > > > > > When someone logs in, you can save a value like > > > time.strftime(time.ctime()) for a nice, human-readable time stamp. > > > Don't forget to "import time" first. > > > > > > -Rob A. > > > > > > On 10/12/06, Asrarahmed Kadri wrote: > > > > Folks, > > > > > > > > I am trying to modify the userManagement program given in Core Python > > > > Programming. It uses a dictionary to store user-password information. > > The > > > > usernames are the keys and the passwords are the values. > > > > Now I want is to add a third element; last login time. > > > > I want to store this information in a file so that the data is not lost > > once > > > > the program stops execution. > > > > > > > > I am not sure of using time function in python.. > > > > Can anyone help with this issue?? > > > _______________________________________________ > > > Tutor maillist - Tutor at python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > > > -- > > To HIM you shall return. > > > -- > Blogging my outdoors obsession: http://trekkingbob.blogspot.com/ > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- To HIM you shall return. -- Blogging my outdoors obsession: http://trekkingbob.blogspot.com/ From kdidriksson at gmail.com Thu Oct 12 20:05:41 2006 From: kdidriksson at gmail.com (Kristinn Didriksson) Date: Thu, 12 Oct 2006 14:05:41 -0400 Subject: [Tutor] float object not callable error Message-ID: <3052CA7C-B695-48E8-808C-DABB12119718@gmail.com> Hello, I an completely new to programming and am trying to teach myself Python using Python Programming by John Zelle. Essentially I am an ex- tech writer trying to learn how to program. My system: Mac OS X 10.4, Python 2.5, TextMate editor Here is the problem: I get 'float' object not callable error. I thought this was a conversion error, but it seems to me that it may be something else. It will not print x and I don't understand why it will not do that. Any help is greatly appreciated. This is the code below. When I got the error message initially, I tried to break it down into smaller bites so I could see the problem more clearly. I tried to figure this out myself, but not having any luck. Regards, Kristinn # Calculate the area of a triangle. Input the lengths of the sides: a, b, c. # Formulas: (s = a + b + c) / 2 # A = sqrt(s(s - a)(s -b)(s - c)) def main(): import math a, b, c = input("Please enter the sides of the triangle separated by commas: ") s = (float(a + b + c)/2) print s #This is to test the first part of the algorithm--and it fails x = (s(s -a)(s -b)(s -c)) print x y = math.sqrt(x) print y #area = math.sqrt((s)(s - a)(s -b)(s-c)) --this is the formula that will not work print "This is the area of the traingle: " + area main() # This algorithm has type conversion problems. # Error message: 'float' object is not callable From hmm at woolgathering.cx Thu Oct 12 20:07:03 2006 From: hmm at woolgathering.cx (William O'Higgins Witteman) Date: Thu, 12 Oct 2006 14:07:03 -0400 Subject: [Tutor] embedding lists in configuration files Message-ID: <20061012180703.GA22265@sillyrabbi.dyndns.org> I am looking for a way to use a plain text configuration file in a Python program instead of hard-coded values. The configuration data currently is in the form of a couple of lists and some triple-quoted strings. I was looking at the ConfigParser module, but I cannot see how to use this format to represent lists or triple-quoted strings. Are there any other suggestions? Thanks. -- yours, William From dyoo at hkn.eecs.berkeley.edu Thu Oct 12 20:46:24 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 12 Oct 2006 11:46:24 -0700 (PDT) Subject: [Tutor] float object not callable error In-Reply-To: <3052CA7C-B695-48E8-808C-DABB12119718@gmail.com> References: <3052CA7C-B695-48E8-808C-DABB12119718@gmail.com> Message-ID: > Here is the problem: > > I get 'float' object not callable error. Hi Kristinn, Ah. Ok. The problem is a notational one. You're reusing notation that you've learned from your math classes, that is, that: a b informally represents the multiplication of numbers 'a' and 'b'. Furthermore, math notation allows the use of parens, so: (a) (b) a (b) (a) b all designate expressions that multiply two variables together in math. However, Python does NOT support this particular math notation! The reason is because it conflicts with the notation used for applying functions to arguments: f(x) Computers are "stupid" and computer programming languages avoid using notations that can be ambiguously interpreted. Math notation is pretty ambiguous sometimes, but that's usually not a problem because it's primarily used to communicate between humans who can tease out the meaning of the ambiguities. But, again, computers are stupid, so the notation we use in programming is often a bit more fixed and inflexible. In that context, take a look at the way you're notating multiplication. Good luck! From bgailer at alum.rpi.edu Thu Oct 12 21:24:38 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu, 12 Oct 2006 12:24:38 -0700 Subject: [Tutor] float object not callable error In-Reply-To: <3052CA7C-B695-48E8-808C-DABB12119718@gmail.com> References: <3052CA7C-B695-48E8-808C-DABB12119718@gmail.com> Message-ID: <452E9676.9090209@alum.rpi.edu> Kristinn Didriksson wrote: > Hello, > I an completely new to programming and am trying to teach myself > Python using Python Programming by John Zelle. Essentially I am an ex- > tech writer trying to learn how to program. > My system: Mac OS X 10.4, Python 2.5, TextMate editor > Here is the problem: > > I get 'float' object not callable error. > Please in future posts include the exception message (traceback). It pinpoints the line of code raising the exception. You did help us here by commenting the problem lines. > I thought this was a conversion error, but it seems to me that it may > be something else. It will not print x and I don't understand why it > will not do that. Any help is greatly appreciated. > > This is the code below. When I got the error message initially, I > tried to break it down into smaller bites so I could see the problem > more clearly. I tried to figure this out myself, but not having any > luck. > > Regards, > Kristinn > > # Calculate the area of a triangle. Input the lengths of the sides: > a, b, c. > # Formulas: (s = a + b + c) / 2 > # A = sqrt(s(s - a)(s -b)(s - c)) > > def main(): > import math > a, b, c = input("Please enter the sides of the triangle separated by > commas: ") > s = (float(a + b + c)/2) > print s #This is to test the first part of the algorithm--and it fails > x = (s(s -a)(s -b)(s -c)) > In algebra multiplication is assumed when 2 items are adjacent. In most programming languages multiplication is expressed by some symbol. Python (as many languages) uses * for multiplication. Parentheses following a name assumes the name is a callable object (e.g. function). So change the above to: x = s*(s -a)*(s -b)*(s -c) Note I've also dropped the outside parentheses as (1) not necessary and (2) potentially confusing considering that outside parentheses are used to construct tuples and generators. > print x > y = math.sqrt(x) > print y > #area = math.sqrt((s)(s - a)(s -b)(s-c)) --this is the formula that > will not work > print "This is the area of the traingle: " + area > > main() > > # This algorithm has type conversion problems. > # Error message: 'float' object is not callable FWIW the simplest example of the callable issue is: >>> 2(3) Traceback (most recent call last): File "", line 1, in ? TypeError: 'int' object is not callable >>> 2*3 6 > > -- Bob Gailer 510-978-4454 From anilmrn at yahoo.com Thu Oct 12 22:13:47 2006 From: anilmrn at yahoo.com (anil maran) Date: Thu, 12 Oct 2006 13:13:47 -0700 (PDT) Subject: [Tutor] do you know how to do this Message-ID: <20061012201347.22311.qmail@web55206.mail.re4.yahoo.com> Dear Danny THanks for your prompt response. THis is not a homework problem, I m trying to learn how to do sessions logins I m trying to do the following 1) have logins/passwords stored in postgresql, currently this is my code, python+psycopg2 talking to postgresql running in backend. if i.email != "" and i.password != "": algo = 'sha1' salt = sha.new(str(random.random())).hexdigest()[:5] hsh = sha.new(salt+i.password).hexdigest() password_algo_salt_hash = '%s$%s$%s' % (algo, salt, hsh) web.insert('users', email = i.email, password = password_algo_salt_hash, ip=web.ctx.ip, rawpassword=i.password) web.setcookie('username', i.email,2629743)#expires in a month 2) As you can see I m not setting the cookie properly , I m just setting email as cookie, So I want to set a proper hash of email time and cookie HOW DO I set a proper hash based cookie. a login page that takes a username and password, checks it against a database, and then sets a cookie of (hash(secret,user, time),user,time). Then there's a function that checks the cookie and returns the user object if the hashes match. I m unable to figure out how to do this yet Anil ----- Original Message ---- From: Danny Yoo To: anilmrn at yahoo.com Cc: Tutor Sent: Thursday, October 12, 2006 10:17:14 AM Subject: do you know how to do this >> Date: Thu, 12 Oct 2006 01:46:44 -0700 (PDT) >> From: anil maran >> Subject: do you know how to do this >> To: Alan Gauld >> >> The user, password and group are stored in a session on disk using >> flup.middleware.session. You can change this to fit your needs like in >> a database. I think someone have already extended the flup session with >> a database store? >> >> Use the decorator function on your GET and POST method to set >> authentication and provide which group are allowed. >> >> If auth is set to True and user/password/access did not match, a >> redirect is made to /login. Anil, can you try to refocus your question? You have to be more specific than "Do you know how to do this?" because that can invite really flippant answers like "Yes" or "No". That's not going to be useful for you. Instead, try focusing us on what problems you're having. From your message with Alan, I see a general problem statement with several requirements necessary for a solution. It really looks like a homework assignment. We are not allowed to go into a particular solution; we're going to have to limit ourselves to reduce the confusion you have with the problem, but that's it: you're going to have to do your own work on the problem. Is there any part in your assignment that you don't understand? Is there any part in there that you do understand? Do you understand all the terms used in the problem? At what point are you getting stuck? Have you worked on any other problem that's similar to the one you're looking at now? Good luck. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061012/ca795d99/attachment.html From anilmrn at yahoo.com Thu Oct 12 22:16:31 2006 From: anilmrn at yahoo.com (anil maran) Date: Thu, 12 Oct 2006 13:16:31 -0700 (PDT) Subject: [Tutor] Help with generating session id Message-ID: <20061012201632.79287.qmail@web55211.mail.re4.yahoo.com> Hi guys I m trying to maintain Sessions for each user, and a session-id that needs to be stored in cookie. I m unable to figure out how to generate session-id that can be stored in a cookie and sync with a session. The problem is this everytime someone logs in check and see if they have session info that can be resumed or create a new session and store the session id in a cookie. Atleast this is my understanding, how do we sync up sessions + logins. Should I store the session id in a db. Thanks Anil Here is code I have worked on so far, does login with sessions no cookies yet;) #!/usr/bin/env python # -*- coding: utf-8 -*- import os import web from flup.middleware.session import DiskSessionStore, SessionMiddleware web.internalerror = web.debugerror # ## URL MAPPING # urls = ( '/','index', '/login','login', '/logout','logout' ) # ## AUTHORIZATION STUFF # def dologin(user): session = web.ctx.environ['com.saddi.service.session'].session session['id'] = user.id session['username'] = user.username session['groups'] = user.groups session['loggedin'] = 1 def dologout(): session = web.ctx.environ['com.saddi.service.session'].session session.invalidate() def initsession(session): session['id'] = 0 session['username'] = '' session['groups'] = '' session['loggedin'] = 0 def checkauth(session): if session['loggedin'] == 1: return True return False def checkaccess(auth=False, access=''): def decorator(func): def proxyfunc(self, *args, **kw): service = web.ctx.environ['com.saddi.service.session'] session = service.session if service.isSessionNew: initsession(session) if auth == True: if not checkauth(session): return web.redirect('/login') if access != '': groups = session['groups'].split(',') if access not in groups: return web.redirect('/login') return func(self, *args, **kw) return proxyfunc return decorator # ## PAGES # class index: @checkaccess(auth=True, access='admin') def GET(self): print web.ctx.environ service = web.ctx.environ['com.saddi.service.session'] print '
' print service session = web.ctx.environ['com.saddi.service.session'].session print '

Session' print session web.render('index.html') class login: @checkaccess() def GET(self): web.render('login.html') @checkaccess() def POST(self): user = web.storify({ 'id':1, 'username':'mark', 'password':'userss', 'groups':'admin' }) inp = web.input() if inp.username == user.username and inp.password == user.password: dologin(user) web.redirect('/') else: web.render('login.html') class logout: @checkaccess() def GET(self): dologout() web.redirect('/') # ## MIDDLEWARE FACTORIES # def session_mw(app): sessionStore = DiskSessionStore(storeDir="%s/sessions/" % os.getcwd(), timeout=5) return SessionMiddleware(sessionStore, app) Anil -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061012/841b47b2/attachment-0001.htm From rabidpoobear at gmail.com Thu Oct 12 22:44:56 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 12 Oct 2006 15:44:56 -0500 Subject: [Tutor] Help with generating session id In-Reply-To: <20061012201632.79287.qmail@web55211.mail.re4.yahoo.com> References: <20061012201632.79287.qmail@web55211.mail.re4.yahoo.com> Message-ID: <452EA948.4080506@gmail.com> anil maran wrote: > Hi guys > I m trying to maintain Sessions for each user, and a session-id that > needs to be stored in cookie. I m unable to figure out how to generate > session-id that can be stored in a cookie and sync with a session. > The problem is this > everytime someone logs in check and see if they have session info that > can be resumed or create a new session and store the session id in a > cookie. Atleast this is my understanding, how do we sync up sessions + > logins. Should I store the session id in a db. > Thanks > Anil > Here is code I have worked on so far, does login with sessions no > cookies yet;) You need to think through the logic of what you're trying to do. Often, the logistics of how a specific algo will be implemented take more thought and planning than the actual programming of it. We here are essentially a programming help forum, for people who don't have a problem coming up with an algorithm (the hard part) but just in implementing it (the easy part). So asking us 'how do I do x' is almost definitely not going to get the kind of answer you want. Consider what you're seeking. It's not up to us to design an implementation for you. There are many different ways you can sync up logins, there are multiple ways to store the session-id on the server. It's up to you to come up with which way you want to do it, and start implementing it, and then we assist you if you have basic programming problems. If you want to know about session-ids, what they're supposed to do, how to generate them, how to use cookies... all of these questions are questions you would get better help by asking on a Webmaster forum. What problem are you having specifically? can you generate the session-id? can you make a cookie with the session-id on the user's computer? can you check their cookie when they login with whatever method you're using to keep track of sessions on your server? Also, what does @checkaccess() do? is this a placeholder? what is flup? what is flup.middleware? what is flup.middleware.session? Your code doesn't do anything, does it? it's just a definition of a bunch of methods. Is this a library you wrote? What kind of advice are you looking to get from showing us this? HTH, -Luke From rabidpoobear at gmail.com Thu Oct 12 22:59:08 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 12 Oct 2006 15:59:08 -0500 Subject: [Tutor] embedding lists in configuration files In-Reply-To: <20061012180703.GA22265@sillyrabbi.dyndns.org> References: <20061012180703.GA22265@sillyrabbi.dyndns.org> Message-ID: <452EAC9C.1010707@gmail.com> William O'Higgins Witteman wrote: > I am looking for a way to use a plain text configuration file in a > Python program instead of hard-coded values. The configuration data > currently is in the form of a couple of lists and some triple-quoted > strings. > > I was looking at the ConfigParser module, but I cannot see how to use > this format to represent lists or triple-quoted strings. Are there any > other suggestions? Thanks. > I've never used configparser, but from what I read just now about it, it seems like this should work for lists: #--- start INI file [category] list: element1,element2,element3,element4,element5 #end INI file #your file from ConfigParser import ConfigParser config = ConfigParser() config.read('sample.ini') print "The COW says: " #the following line should generate a list from the comma-separated values. print config.get("category","list").split(',') #--- end your file I can't install ConfigParser at the moment to test this, but I hope it works :) Tell me if it does. As for triple-quoted strings... I'm not sure about that. a little bit of googling seems to agree that you can't have multi-line strings. I don't know that for a fact, though. HTH, -Luke From kent37 at tds.net Thu Oct 12 23:04:59 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 12 Oct 2006 17:04:59 -0400 Subject: [Tutor] Fwd: Help with basic user-data file In-Reply-To: <8d757d2e0610121054q55cb22e1ta67936cee6534065@mail.gmail.com> References: <8d757d2e0610120625wb121336yfcf58f91cf13980c@mail.gmail.com> <8d757d2e0610120653h6845f97p5ed9e0131474b52@mail.gmail.com> <8d757d2e0610121054q55cb22e1ta67936cee6534065@mail.gmail.com> Message-ID: <452EADFB.5090600@tds.net> > From: Asrarahmed Kadri > Date: Oct 12, 2006 9:17 AM > Subject: Re: [Tutor] Help with basic user-data file > To: Rob Andrews > > > Thanks. > Can you please also tell me how to check the existence of a file using > python builtin functions. If path is a string containing the full path to the file (absolute path or relative to the working dir) then use import os os.path.exists(path) # To see if the path represents *something* real os.path.isfile(path) # check for a file specifically os.path.isdir(path) # check for a directory Kent From kent37 at tds.net Thu Oct 12 23:09:40 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 12 Oct 2006 17:09:40 -0400 Subject: [Tutor] embedding lists in configuration files In-Reply-To: <20061012180703.GA22265@sillyrabbi.dyndns.org> References: <20061012180703.GA22265@sillyrabbi.dyndns.org> Message-ID: <452EAF14.90501@tds.net> William O'Higgins Witteman wrote: > I am looking for a way to use a plain text configuration file in a > Python program instead of hard-coded values. The configuration data > currently is in the form of a couple of lists and some triple-quoted > strings. > > I was looking at the ConfigParser module, but I cannot see how to use > this format to represent lists or triple-quoted strings. Are there any > other suggestions? Thanks. ConfigObj supports lists and triple-quoted strings directly: http://www.voidspace.org.uk/python/configobj.html Kent From john at fouhy.net Thu Oct 12 23:13:22 2006 From: john at fouhy.net (John Fouhy) Date: Fri, 13 Oct 2006 10:13:22 +1300 Subject: [Tutor] how to check whether a file exists or not?? In-Reply-To: References: Message-ID: <5e58f2e40610121413i3863f9ebj5a54be9488cbb9db@mail.gmail.com> On 13/10/06, Asrarahmed Kadri wrote: > Also if a file exists, and we open it in a write mode, it would be truncated > to zero length. So what is the way out of this??# You can open in append mode.. >>> f = open('foo', 'w') >>> f.write('Hello ') >>> f.close() >>> f = open('foo', 'a') >>> f.write('world!') >>> f.close() >>> f = open('foo', 'r') >>> f.read() 'Hello world!' -- John. From alan.gauld at freenet.co.uk Thu Oct 12 23:18:03 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 12 Oct 2006 22:18:03 +0100 Subject: [Tutor] wxPython book Message-ID: <000301c6ee43$e79307b0$0201a8c0@XPpro> I just noticed WxPython in Action (Paperback) by Noel Rappin, Robin Dunn on Amazon.co.uk. I wondered if anyone has got the book and would like to comment on it? One of the main reasions I stick with Tkinter is that I have Grayson's book as a reference. If this is as useful for wxPython I might move my allegiance... Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From jfabiani at yolo.com Thu Oct 12 23:46:07 2006 From: jfabiani at yolo.com (johnf) Date: Thu, 12 Oct 2006 14:46:07 -0700 Subject: [Tutor] SQL Queries For MySQL In-Reply-To: <7e3eab2c0610120714i1e6d45a3p90f561a4f921ae32@mail.gmail.com> References: <907cc7070610112108t134b1952k13a3b22aafa9b7ca@mail.gmail.com> <200610120619.30379.jfabiani@yolo.com> <7e3eab2c0610120714i1e6d45a3p90f561a4f921ae32@mail.gmail.com> Message-ID: <200610121446.07193.jfabiani@yolo.com> On Thursday 12 October 2006 07:14, Jason Massey wrote: > On 10/12/06, johnf wrote: > > On Thursday 12 October 2006 00:31, Alan Gauld wrote: > > > > query = "SELECT * FROM DB WHERE NAME = %s" % (name) > > > > cursor.execute(query) > > > > > > There can be security issues with this style, especially > > > if the parameters can be modified by users - for example > > > you read the values from a web page. > > > > > > The cursor.execute() call has the ability to pass the parameters > > > in directly, ie combining the two statements above into one. > > > The details of how ypou do that varies between database > > > drivers so you need to check the documents but I think for > > > MySQL its almost an exact translation: > > > > > > query = "SELECT * FROM DB WHERE NAME = %s" > > > cursor.execute(query, name) > > > > > > If you search the ist archives you'll find a fairly long thread > > > describing the whys/wherefores in much more depth. > > > > > > HTH, > > > > Since the archive is large - could you provide the subject title. > > > > Thanks > > John > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > Forgot to forward to the list... > > Check out this posting from Danny: > > http://mail.python.org/pipermail/tutor/2003-April/022010.html OK from what I understand you are concerned with "SQL injection". But I don't see the difference between the two statements preventing "SQL injection". Can someone explain. John From alan.gauld at btinternet.com Thu Oct 12 23:01:06 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 12 Oct 2006 22:01:06 +0100 Subject: [Tutor] embedding lists in configuration files References: <20061012180703.GA22265@sillyrabbi.dyndns.org> Message-ID: > Python program instead of hard-coded values. The configuration data > currently is in the form of a couple of lists and some triple-quoted > strings. > > I was looking at the ConfigParser module, but I cannot see how to > use > this format to represent lists or triple-quoted strings. Are there > any > other suggestions? Thanks. There are several possibilities:- 1) the simplest is simply a lsingle line with the values separated by some character - commas, colons, hyphens, whatever doesn't appear in the data. Then read the line as a string, split(char) it into its parts and convert the parts to the appropriate types. Using commas may allow you to leverage the CSV module. 2) Use a richer format, like XML which provides for very complex structures and allows you to use a standard parser like ElementTree to extract the data. 3) Write all values onm their own lines and add a marker to separate lists. Then use a while loop to read in the lines until you reach the marker. Thee are other options too, but those should be enough to get you going. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From wescpy at gmail.com Fri Oct 13 00:38:21 2006 From: wescpy at gmail.com (wesley chun) Date: Thu, 12 Oct 2006 15:38:21 -0700 Subject: [Tutor] wxPython book In-Reply-To: <000301c6ee43$e79307b0$0201a8c0@XPpro> References: <000301c6ee43$e79307b0$0201a8c0@XPpro> Message-ID: <78b3a9580610121538p48cfee20qfb1ae7f27688faac@mail.gmail.com> > WxPython in Action (Paperback) > by Noel Rappin, Robin Dunn i'll probably be picking up a copy of it myself. i've seen positive comments about the book. more reviews available at Amazon US: http://www.amazon.com/exec/obidos/ASIN/1932394621 there's also a wxWidgets book if you need to know the details. hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From cappy2112 at gmail.com Fri Oct 13 00:48:25 2006 From: cappy2112 at gmail.com (Tony Cappellini) Date: Thu, 12 Oct 2006 15:48:25 -0700 Subject: [Tutor] Trying to understand sys.getrefcount() Message-ID: <8249c4ac0610121548n152a0ce3y9359622dbf2bf614@mail.gmail.com> I'm using Python 2.3.4 After reading this in the docs *getrefcount*( object) Return the reference count of the object. The count returned is generally one higher than you might expect, because it includes the (temporary) reference as an argument to getrefcount().I decided to try some experiments class junk(object): ... pass ... >>> sys.getrefcount(junk) 5 >>> j1=junk() >>> sys.getrefcount(junk) 6 sys.getrefcount(j1) 2 I understand why j1 is 1 higher than I expect, based on the docs, but why does getrefcount(junk) return 5 before any instances of class junk are made? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061012/58a078c1/attachment-0001.htm From alan.gauld at freenet.co.uk Fri Oct 13 00:50:11 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 12 Oct 2006 23:50:11 +0100 Subject: [Tutor] wxPython book References: <000301c6ee43$e79307b0$0201a8c0@XPpro> <78b3a9580610121538p48cfee20qfb1ae7f27688faac@mail.gmail.com> Message-ID: <000301c6ee50$c6579220$0201a8c0@XPpro> Thanks Wes, After posting it dawned on me that the US site might have more (any!) reviews, and sure enough there is one mega review and several shorter ones, none negative. I think I'll be buying... The wxWidgets book I'll pass on, I have an old one from about 10 years ago (from when I was actively programming in C++) which explains the logic behind the toolkit and the wxWidgets reference web pages do all I need now, its really the Python aspects I want a book on. Thanks again, Alan G. ----- Original Message ----- From: "wesley chun" To: "Alan Gauld" Cc: Sent: Thursday, October 12, 2006 11:38 PM Subject: Re: [Tutor] wxPython book >> WxPython in Action (Paperback) >> by Noel Rappin, Robin Dunn > > i'll probably be picking up a copy of it myself. i've seen positive > comments about the book. more reviews available at Amazon US: > http://www.amazon.com/exec/obidos/ASIN/1932394621 > > there's also a wxWidgets book if you need to know the details. > > hope this helps! > -- wesley > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > "Core Python Programming", Prentice Hall, (c)2007,2001 > http://corepython.com > > wesley.j.chun :: wescpy-at-gmail.com > python training and technical consulting > cyberweb.consulting : silicon valley, ca > http://cyberwebconsulting.com From ajkadri at googlemail.com Fri Oct 13 01:38:42 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Fri, 13 Oct 2006 00:38:42 +0100 Subject: [Tutor] Help me : Why this code is not working?? Message-ID: I have created two buttons. The code for button2 is not working as I want it to be. When I click button2, the application should exit, but it isnt. Can someone fix it?? from Tkinter import * from tkMessageBox import * def callback(): showinfo('message','I am here...') def QUIT(): ans = askyesno('Confirm','Do you really want to quit?') if ans: root.exit else: showinfo('Selection','You have decided to stay on') root = Tk() win = Frame(root) win.pack() button1 = Button(win,text='Hello',command=callback) button1.pack(side=LEFT) button2 = Button(win,text='Quit',command=QUIT) button2.pack(side=RIGHT) root.mainloop() -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061013/c1179984/attachment.htm From python at venix.com Fri Oct 13 01:51:06 2006 From: python at venix.com (Python) Date: Thu, 12 Oct 2006 19:51:06 -0400 Subject: [Tutor] SQL Queries For MySQL In-Reply-To: <200610121446.07193.jfabiani@yolo.com> References: <907cc7070610112108t134b1952k13a3b22aafa9b7ca@mail.gmail.com> <200610120619.30379.jfabiani@yolo.com> <7e3eab2c0610120714i1e6d45a3p90f561a4f921ae32@mail.gmail.com> <200610121446.07193.jfabiani@yolo.com> Message-ID: <1160697066.8103.401.camel@www.venix.com> On Thu, 2006-10-12 at 14:46 -0700, johnf wrote: > On Thursday 12 October 2006 07:14, Jason Massey wrote: > > On 10/12/06, johnf wrote: > > > On Thursday 12 October 2006 00:31, Alan Gauld wrote: > > > > > query = "SELECT * FROM DB WHERE NAME = %s" % (name) > > > > > cursor.execute(query) (snipped) > > > > query = "SELECT * FROM DB WHERE NAME = %s" > > > > cursor.execute(query, name) (snipped) > OK from what I understand you are concerned with "SQL injection". But I don't > see the difference between the two statements preventing "SQL injection". Suppose name = 'x"; DELETE FROM DB; SELECT COUNT(*) FROM DB; SELECT FROM DB WHERE NAME = "x' The first version will simply build a string with the SQL command interpolating name. The where quote (") gets closed and semicolons separate SQL commands. The sequence of commands gets executed. The second version will escape the quotes and semicolons in the name string. You will simply try to match a rather odd looking name. You could do the escaping yourself before doing the string interpolation, but the DB module is already set up to do the work for you. > Can someone explain. > > John > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From rabidpoobear at gmail.com Fri Oct 13 01:53:51 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 12 Oct 2006 18:53:51 -0500 Subject: [Tutor] Help me : Why this code is not working?? In-Reply-To: References: Message-ID: <452ED58F.5050306@gmail.com> Asrarahmed Kadri wrote: > > > I have created two buttons. The code for button2 is not working as I > want it to be. When I click button2, the application should exit, but > it isnt. > Can someone fix it?? > > from Tkinter import * > from tkMessageBox import * > > def callback(): > showinfo('message','I am here...') > > def QUIT(): > ans = askyesno('Confirm','Do you really want to quit?') > if ans: > root.exit > SEND US THE TRACEBACK!!!! :) Don't just tell us that something doesn't work. The traceback contains valuable information that tells you (or us) how to debug it. In this case,the traceback was #////// Exception in Tkinter callback Traceback (most recent call last): File "C:\Python24\lib\lib-tk\Tkinter.py", line 1345, in __call__ return self.func(*args) File "C:/Python24/temp.py", line 10, in QUIT root.exit File "C:\Python24\lib\lib-tk\Tkinter.py", line 1654, in __getattr__ return getattr(self.tk, attr) AttributeError: exit #\\\\ Okay, so what do we see here? Start reading from the bottom. AttributeError: exit. okay, so that means that we tried to access a method or a variable of a class, and it wasn't there. It lacked that attribute. Which class was it? looking further up the stack, we see where we access 'exit.' line 10, in QUIT: root.exit This means that whatever class root is an instance of doesn't have a method named exit. Remember, the computer is stupid. To the computer, 'exit' and 'quit' mean something as different as 'root beer' and 'trash can' would to us. The method you're trying to access is called 'quit', not 'exit' That's your first problem. The second problem you have, is that you're not calling this method, you're just accessing it, which doesn't really do anything. What you'll want to do is root.quit() and not root.quit HTH, -Luke From ajkadri at googlemail.com Fri Oct 13 01:58:43 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Fri, 13 Oct 2006 00:58:43 +0100 Subject: [Tutor] Help me : Why this code is not working?? In-Reply-To: <452ED58F.5050306@gmail.com> References: <452ED58F.5050306@gmail.com> Message-ID: Thanks a lot. It was quick. I will send the traceback from now on. -Asrar On 10/13/06, Luke Paireepinart wrote: > > Asrarahmed Kadri wrote: > > > > > > I have created two buttons. The code for button2 is not working as I > > want it to be. When I click button2, the application should exit, but > > it isnt. > > Can someone fix it?? > > > > from Tkinter import * > > from tkMessageBox import * > > > > def callback(): > > showinfo('message','I am here...') > > > > def QUIT(): > > ans = askyesno('Confirm','Do you really want to quit?') > > if ans: > > root.exit > > > SEND US THE TRACEBACK!!!! :) > Don't just tell us that something doesn't work. > The traceback contains valuable information that tells you (or us) how > to debug it. > In this case,the traceback was > #////// > Exception in Tkinter callback > Traceback (most recent call last): > File "C:\Python24\lib\lib-tk\Tkinter.py", line 1345, in __call__ > return self.func(*args) > File "C:/Python24/temp.py", line 10, in QUIT > root.exit > File "C:\Python24\lib\lib-tk\Tkinter.py", line 1654, in __getattr__ > return getattr(self.tk, attr) > AttributeError: exit > #\\\\ > Okay, so what do we see here? > Start reading from the bottom. > AttributeError: exit. > okay, so that means that we tried to access a method or a variable of a > class, and it wasn't there. > It lacked that attribute. > > Which class was it? > looking further up the stack, we see where we access 'exit.' > line 10, in QUIT: > root.exit > > This means that whatever class root is an instance of doesn't have a > method named exit. > > Remember, the computer is stupid. To the computer, 'exit' and 'quit' > mean something as different > as 'root beer' and 'trash can' would to us. The method you're trying to > access is called 'quit', not 'exit' > That's your first problem. > > The second problem you have, is that you're not calling this method, > you're just accessing it, which doesn't really do anything. > What you'll want to do is > root.quit() > > and not > root.quit > > HTH, > -Luke > -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061013/d420697b/attachment.html From amadeo.bellotti at gmail.com Fri Oct 13 02:04:21 2006 From: amadeo.bellotti at gmail.com (Amadeo Bellotti) Date: Thu, 12 Oct 2006 20:04:21 -0400 Subject: [Tutor] tkinter tutorials Message-ID: I am currently interseted in learning tkinter and what beeter way then with a project so im making a python IDE and i was wondering if there were any good tutorials that are out there for tkinter and a book or 2 would be nice thank you -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061012/ad88fdc3/attachment.htm From dyoo at hkn.eecs.berkeley.edu Fri Oct 13 02:45:46 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 12 Oct 2006 17:45:46 -0700 (PDT) Subject: [Tutor] tkinter tutorials In-Reply-To: References: Message-ID: On Thu, 12 Oct 2006, Amadeo Bellotti wrote: > I am currently interseted in learning tkinter and what beeter way then > with a project so im making a python IDE and i was wondering if there > were any good tutorials that are out there for tkinter and a book or 2 > would be nice thank you John Grayson's "Python and Tkinter Programming" is an excellent book on learning the Tkinter toolkit: http://www.manning.com/grayson/ You might also find the tutorial material on: http://wiki.python.org/moin/TkInter to be helpful. From ajkadri at googlemail.com Fri Oct 13 03:03:49 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Fri, 13 Oct 2006 02:03:49 +0100 Subject: [Tutor] How to write strings with new line character in a file Message-ID: Folks, I am trying to enter names in a file; each on a new line with this code, but not working: done = 0 *while not done: str = raw_input("Enter login name:\t to quit type 'q': ") if str == 'q': done = 1 else: * * str = str + '\n'* * fd.write(str) * The traceback is as under: Traceback (most recent call last): File "scrap.py", line 38, in ? fd.write(str) IOError: (0, 'Error') Please help to rectify this error... -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061013/c61223aa/attachment.html From dyoo at hkn.eecs.berkeley.edu Fri Oct 13 03:24:36 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 12 Oct 2006 18:24:36 -0700 (PDT) Subject: [Tutor] do you know how to do this In-Reply-To: <20061012201347.22311.qmail@web55206.mail.re4.yahoo.com> References: <20061012201347.22311.qmail@web55206.mail.re4.yahoo.com> Message-ID: > a login page that takes a username and password, checks it against a > database, and then sets a cookie of (hash(secret,user, time),user,time). Hi Anil, Ok, separate the concerns about where the inputs are coming from. It will seem weird, but just for the moment, forget completely about the web, and just concentrate on the inputs and outputs of this subproblem. It sounds like you're trying to generate a string value, given a user name and value. Conceptually, you can treat this as a simple function: def generate_login_cookie(username, password): """generate_login_cookie: string string -> string Creates a new login cookie that can be used to log in again.""" ## fill me in. This might not quite be right yet, but we're still looking at this from a high level. > Then there's a function that checks the cookie and returns the user > object if the hashes match. Ok, furthermore, it sounds like you want a function that takes a cookie string value and returns a User object if the hashes match. Just for discussion's sake, let's call this login_with_cookie(). def login_with_cookie(cookie_value): """login_with_cookie: string -> User, or None Given a string value generated with generate_login_cookie(), returns the associated user. Otherwise, returns None.""" ## fill me in I have no idea what a User object is supposed to be, but I'll assume for the moment that this function is going to satisfy the following pseudocode requirement: if sometime in the past: c = generate_login_cookie(username, password): then: u = login_with_cookie(c) assert (u.username == username) should hold. Furthermore, on any other arbitrary string s that hasn't been generated with generate_login_cookie(), we'd like to know that: assert (login_with_cookie(s) == None) because otherwise the login system would suck. *grin* We also know that generate_login_cookie() and login_with_cookie() must cooperate in some way that is persistent across time. That's where your database is going to come into play: a database is going to be your persistent state. I would recommend concentrating on getting those two functions working, because they have the nice property that you can actually code these out without having to go doing web-ish things. More importantly, you should be able to unit-test something like this with ease. (And you'd better test, considering how important login and authentication are!) The part dealing with the web itself can be considered orthogonal. If you get generate_login_cookie() and login_with_cookie() working ok, then your problem reduces down to: "How do I set a cookie in my web application?", and "How do I read a cookie from the user's request?" because you can use the above functions as helpers. Then you have a much simpler problem on your hands. The main difficulty that I think you're hitting is that you seem to try to juggle all your requirements at the same time. So the main recommendation I can give is: decompose your problem. Try not to solve it in one gulp: most problems are too big to handle all at once. From dyoo at hkn.eecs.berkeley.edu Fri Oct 13 03:32:10 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 12 Oct 2006 18:32:10 -0700 (PDT) Subject: [Tutor] How to write strings with new line character in a file In-Reply-To: References: Message-ID: > > while not done: > str = raw_input("Enter login name:\t to quit type 'q': ") > if str == 'q': > done = 1 > else: > str = str + '\n' > fd.write(str) Hi Asrarahmed, What's 'fd'? Where is it defined? (I have a guess, but I'd rather that you show where fd is being defined explicitely.) If you're still trying to drive DOS applications with popen(), I'd strongly encourage you to take a closer look at PExpect: you should be able to get it to work with a Cygwin-based environment. http://pexpect.sourceforge.net/ Good luck! From DOBrien at LeapFrog.com Fri Oct 13 03:40:03 2006 From: DOBrien at LeapFrog.com (Dennis O'Brien) Date: Thu, 12 Oct 2006 18:40:03 -0700 Subject: [Tutor] wxPython book In-Reply-To: Message-ID: There is a good interview on Python 411 last week with the authors of the book. http://www.awaretek.com/python/index.html You can also find a few other shows about gui toolkits in Python. This is a great resource if you want to learn about Python while you commute. --Dennis ----- Original Message -----Date: Thu, 12 Oct 2006 23:50:11 +0100 From: "Alan Gauld" Subject: Re: [Tutor] wxPython book To: "wesley chun" Cc: tutor at python.org Message-ID: <000301c6ee50$c6579220$0201a8c0 at XPpro> Content-Type: text/plain; format=flowed; charset="iso-8859-1"; reply-type=response Thanks Wes, After posting it dawned on me that the US site might have more (any!) reviews, and sure enough there is one mega review and several shorter ones, none negative. I think I'll be buying... The wxWidgets book I'll pass on, I have an old one from about 10 years ago (from when I was actively programming in C++) which explains the logic behind the toolkit and the wxWidgets reference web pages do all I need now, its really the Python aspects I want a book on. Thanks again, Alan G. ----- Original Message ----- From: "wesley chun" To: "Alan Gauld" Cc: Sent: Thursday, October 12, 2006 11:38 PM Subject: Re: [Tutor] wxPython book >> WxPython in Action (Paperback) >> by Noel Rappin, Robin Dunn > > i'll probably be picking up a copy of it myself. i've seen positive > comments about the book. more reviews available at Amazon US: > http://www.amazon.com/exec/obidos/ASIN/1932394621 > > there's also a wxWidgets book if you need to know the details. > > hope this helps! > -- wesley > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > "Core Python Programming", Prentice Hall, (c)2007,2001 > http://corepython.com > > wesley.j.chun :: wescpy-at-gmail.com > python training and technical consulting > cyberweb.consulting : silicon valley, ca > http://cyberwebconsulting.com From AJeffrey at ntu.edu.sg Fri Oct 13 05:19:31 2006 From: AJeffrey at ntu.edu.sg (Jeffrey Kennedy) Date: Fri, 13 Oct 2006 11:19:31 +0800 Subject: [Tutor] Responding to a request for input from a MS-DOS program Message-ID: <54BE2FC5ADFC254B832681E9622AACFE01E598D7@EXCHANGE23.staff.main.ntu.edu.sg> Hi Alan, I think I might be trying to walk before I can crawl; for benefits of other newbies, I'll summarise lessons learned so far. Firstly, I spent ages trying to find out why the Python documentation syntax for Popen, using stdin=PIPE, didn't work: Traceback (most recent call last): File "", line 1, in -toplevel- p1=subprocess.Popen("c:/temp/enter.bat", stdin = PIPE) NameError: name 'PIPE' is not defined Turns out it needs to be specified as stdin=subprocess.PIPE. Then spent even longer trying to figure out why this command: >>> p=subprocess.Popen("c:/temp/enter.bat", stdin=subprocess.PIPE) gave this error: Traceback (most recent call last): File "", line 1, in -toplevel- p=subprocess.Popen("c:/temp/enter.bat", stdin=subprocess.PIPE) File "C:\Python24\lib\subprocess.py", line 533, in __init__ (p2cread, p2cwrite, File "C:\Python24\lib\subprocess.py", line 607, in _get_handles c2pwrite = self._make_inheritable(c2pwrite) File "C:\Python24\lib\subprocess.py", line 634, in _make_inheritable DUPLICATE_SAME_ACCESS) WindowsError: [Errno 6] The handle is invalid (and stdout gives TypeError: an integer is required). Google eventually helped me find out that it's a problem with the way the IDLE Python GUI treats stdin and stdout rather than a problem in the code (which is based on an example in your excellent tutorial). I created a two-line DOS batch file to emulate what I'm trying to do. The file (saved as 'enter.bat') is: SET /P = Type '1' then press 'Enter' SET /P = Type '2' then press 'Enter' After typing the following lines into the Python command line editor, enter.bat runs and takes over the command prompt (waiting for the first input): import subprocess cmd='C:/temp/enter.bat' p1=subprocess.Popen(cmd, stdin = subprocess.PIPE) OUTPUT: >>> p1=subprocess.Popen(cmd, stdin = subprocess.PIPE) >>> C:\Python24>SET /P = Type '1' then press 'Enter' Type '1' then press 'Enter' I then tried the following: subprocess.Popen(cmd, stdin = subprocess.PIPE).stdin.write('1\n') This seems to work - the entry seems to be accepted, but the second prompt from enter.bat now takes over the command prompt: OUTPUT: >>> subprocess.Popen(cmd, stdin = subprocess.PIPE).stdin.write('1\n') >>> C:\Python24>SET /P = Type '1' then press 'Enter' Type '1' then press 'Enter' C:\Python24>SET /P = Type '2' then press 'Enter' Type '2' then press 'Enter' Am I on the right track? I suspect I need to use checks to make sure the enter.bat program has responded before sending the input, but I'm trying to get the basic commands right first. Thanks again, Jeff Hi Jeff, > I want to use Python to run an old MS-DOS program that doesn't > accept arguments when launched. I have to open the program first, > then it will ask me for the name of another program .... > I want to bypass the human input, because I have over > 100 files I want processed, and I can use Python to iterate through > each file in turn You need to look at the subprocess module and the examples that replace the older popen functions. You will find more info including examples of both popen and subporocess in my tutorial under the OS topic in the Applications Section Since you are new to this you might want to read the whole topic, or for more directed help scroll down to the Manipulating Processes heading. Unfortunately I just noticed I don't give any excample of writing to a process(in response to a prompt) which is something I should fix... From bgailer at alum.rpi.edu Fri Oct 13 05:35:08 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu, 12 Oct 2006 20:35:08 -0700 Subject: [Tutor] How to write strings with new line character in a file In-Reply-To: References: Message-ID: <452F096C.1030201@alum.rpi.edu> Asrarahmed Kadri wrote: > Folks, > > I am trying to enter names in a file; each on a new line with this > code, but not working: > > done = 0 > *while not done: > str = raw_input("Enter login name:\t to quit type 'q': ") > if str == 'q': > done = 1 > else: * > * str = str + '\n'* > * fd.write(str) > * No can help without seeing the code that creates fd. Please post that. > The traceback is as under: > > Traceback (most recent call last): > File "scrap.py", line 38, in ? > fd.write(str) > IOError: (0, 'Error') > > Please help to rectify this error... > -- > To HIM you shall return. > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Bob Gailer 510-978-4454 From ml.cyresse at gmail.com Fri Oct 13 08:46:33 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Fri, 13 Oct 2006 19:46:33 +1300 Subject: [Tutor] Help with basic user-data file In-Reply-To: References: Message-ID: <452F3649.60608@gmail.com> Hi Asrarahmed, There's a few questions in there, and unfortunately I don't have a copy of your book. But I'll try to answer them, and I'll change the order so that they build on each other. >I am not sure of using time function in python.. Depending on what you're trying to do, the simplest way is to just use the datetime module. http://docs.python.org/lib/module-datetime.html >>> import datetime >>> the_time_right_now = datetime.datetime.now() This creates a datetime object. You can do all sorts of useful stuff with them, but for now, you probably just want to display the time. You can just >>> print the_time_right_now 2006-10-13 19:26:45.671000 But that may not be the most useful format. Datetime objects have a method called strftime(), and you can give it format strings as per the time module - http://docs.python.org/lib/module-time.html to change the output. For instance. >>> print the_time_right_now 2006-10-13 19:26:45.671000 >>> print the_time_now.strftime("%I:%M%p, %A %d %B %Y") 07:26PM, Friday 13 October 2006 In that case in the format string %I means hours in 1-12 format, %M is minutes, %p is AM/PM, %A is the full name of the day, %d is the day number, %B is the full month name and %Y is the full year.' Have a play with it. > I am trying to modify the userManagement program given in Core Python > Programming. It uses a dictionary to store user-password information. > The usernames are the keys and the passwords are the values. > Now I want is to add a third element; last login time. Okay. So what could do here is instead of having the password as a value, have a list or a dictionary as the value and store the password and login time in that. For example: >>> userInfo = {} >>> userInfo['Liam'] = { 'password' : 'snooze', 'last_login_time': datetime.datetime.now()} If you print userInfo, you'll see that it's saved a datetime object in there. >>> print userInfo {'Liam': {'password': 'snooze', 'last_login_time': datetime.datetime(2006, 10, 13, 19, 34, 58, 437000)}} You could then retrieve my password by >>> print userInfo['Liam']['password'] snooze Or the datetime object you created with >>> print userInfo['Liam']['last_login_time'] 2006-10-13 19:34:58.437000 > I want to store this information in a file so that the data is not > lost once the program stops execution. You'd need to use the pickle module. (Or cPickle, which is marginally faster. They work the same, more or less) >>> import pickle Pickle will turn objects into a stream of bytes, which you can save to a file. You can then reopen the file, and reload the objects. So, once you've imported pickle, you need to open a file to write to. Make sure you open it in binary mode (So file mode will be "wb") >>> save_file = open("userInfo.pck", "wb") You then use the pickle.dump() method to serialize the object - >>> pickle.dump(userInfo, save_file) Make sure you close the file afterwards. >>> save_file.close() Now, next time you start up - >>> import pickle You use the pickle.load() method to get your object back. First thing is to open the file you saved it to, (open it in binary mode). >>> load_file = open("userInfo.pck", "rb") >>> userInfo = pickle.load(load_file) >>> load_file.close() >>> print userInfo {'Liam': {'password': 'snooze', 'last_login_time': datetime.datetime(2006, 10, 13, 19, 34, 58, 437000)}} Hope that helps. Regards, Liam Clarke From alan.gauld at btinternet.com Fri Oct 13 09:55:49 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 13 Oct 2006 08:55:49 +0100 Subject: [Tutor] Trying to understand sys.getrefcount() References: <8249c4ac0610121548n152a0ce3y9359622dbf2bf614@mail.gmail.com> Message-ID: > class junk(object): > ... pass > ... >>>> sys.getrefcount(junk) > 5 > I understand why j1 is 1 higher than I expect, based on the docs, > but why > does getrefcount(junk) return 5 before any instances of class junk > are made? Because Python s holding 4 references to the class object internally. For example the namespace dictionary will have one. I've no idea what all the others will be but presumably thats whats happening. Remember classes are objects too. Alan G. From meherkp at gmail.com Fri Oct 13 10:55:41 2006 From: meherkp at gmail.com (Meher Kolli) Date: Fri, 13 Oct 2006 01:55:41 -0700 Subject: [Tutor] Tutor Digest, Vol 32, Issue 49 In-Reply-To: References: Message-ID: <3f61ac130610130155k6b1146a9uec9516279e1d9da9@mail.gmail.com> > > Message: 8 > Date: Fri, 13 Oct 2006 02:03:49 +0100 > From: "Asrarahmed Kadri" > Subject: [Tutor] How to write strings with new line character in a > file > To: pythontutor > Message-ID: > > Content-Type: text/plain; charset="iso-8859-1" > > Folks, > > I am trying to enter names in a file; each on a new line with this code, > but > not working: > > done = 0 > *while not done: > str = raw_input("Enter login name:\t to quit type 'q': ") > if str == 'q': > done = 1 > else: * > * str = str + '\n'* > * fd.write(str) > * > The traceback is as under: > > Traceback (most recent call last): > File "scrap.py", line 38, in ? > fd.write(str) > IOError: (0, 'Error') > > Please help to rectify this error... You can't add \n to a string ..up have use something like this if str == 'q': done = 1 fd.close() else: fd.write("%s \n" %(str)) -- Meher Kolli Sunnyvale,CA-94085 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061013/a3021be6/attachment.html From alan.gauld at btinternet.com Fri Oct 13 11:09:04 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 13 Oct 2006 10:09:04 +0100 Subject: [Tutor] Tutor Digest, Vol 32, Issue 49 References: <3f61ac130610130155k6b1146a9uec9516279e1d9da9@mail.gmail.com> Message-ID: "Meher Kolli" wrote in message > You can't add \n to a string ..up have use something like this > > if str == 'q': > done = 1 > fd.close() > else: > fd.write("%s \n" %(str)) What makes you think so? >>> s = 'l' >>> s += '\n' >>> s 'l\n' >>> Seems to work.... '\n' is just a character like any other. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From ajkadri at googlemail.com Fri Oct 13 12:23:19 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Fri, 13 Oct 2006 11:23:19 +0100 Subject: [Tutor] How to write strings with new line character in a file In-Reply-To: <452F096C.1030201@alum.rpi.edu> References: <452F096C.1030201@alum.rpi.edu> Message-ID: Here is the complete code: fd is the file handle. import sys def check_dup(fd1): print fd1 fd1.seek(0,0) done = 0 list1 = [] while not done: x = fd1.readline() if x == "": done = 1 else: list1.append(x) return list1 fname = raw_input("Enter the file name to write data to:\t") fd = open(fname,'a+') print fd done = 0 while not done: str = raw_input("Enter login name:\t to quit type 'q'") if str == 'q': done = 1 else: flag = check_dup(fd) print flag if str in flag: print "Login already exists.!!" else: fd.seek(0,2) fd.write(str + '\n') On 10/13/06, Bob Gailer wrote: > > Asrarahmed Kadri wrote: > > Folks, > > > > I am trying to enter names in a file; each on a new line with this > > code, but not working: > > > > done = 0 > > *while not done: > > str = raw_input("Enter login name:\t to quit type 'q': ") > > if str == 'q': > > done = 1 > > else: * > > * str = str + '\n'* > > * fd.write(str) > > * > No can help without seeing the code that creates fd. Please post that. > > The traceback is as under: > > > > Traceback (most recent call last): > > File "scrap.py", line 38, in ? > > fd.write(str) > > IOError: (0, 'Error') > > > > Please help to rectify this error... > > -- > > To HIM you shall return. > > ------------------------------------------------------------------------ > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > -- > Bob Gailer > 510-978-4454 > > -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061013/11ec78cb/attachment.htm From ajkadri at googlemail.com Fri Oct 13 12:44:36 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Fri, 13 Oct 2006 11:44:36 +0100 Subject: [Tutor] How to write string in a file, each one on new line??? Message-ID: Folks, I dont like to swamp your mailboxes with my trivial questions. But please tell me why this isnt working?? str = str + '\n' fd.write(str) # fd is teh file handle the traceback is as under: Traceback (most recent call last): File "scrap.py", line 39, in ? fd.write(str + '\n') IOError: (0, 'Error') -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061013/7f9a87ae/attachment.html From kent37 at tds.net Fri Oct 13 13:37:05 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 13 Oct 2006 07:37:05 -0400 Subject: [Tutor] How to write strings with new line character in a file In-Reply-To: References: <452F096C.1030201@alum.rpi.edu> Message-ID: <452F7A61.7080909@tds.net> Asrarahmed Kadri wrote: > Here is the complete code: > fd is the file handle. > > import sys > > def check_dup(fd1): > print fd1 > fd1.seek(0,0) > done = 0 > list1 = [] > while not done: > x = fd1.readline() > if x == "": > done = 1 > else: > list1.append(x) > return list1 > > > fname = raw_input("Enter the file name to write data to:\t") > > fd = open(fname,'a+') > print fd > done = 0 > > while not done: > str = raw_input("Enter login name:\t to quit type 'q'") > > if str == 'q': > done = 1 > else: > flag = check_dup(fd) > print flag > if str in flag: > print "Login already exists.!!" > else: > fd.seek(0,2) > fd.write(str + '\n') I don't know why this isn't working, but I do know a better way to write it that will work. Keep the list of login names in a list in memory until you have all the names, then write them to a file. Your program will look something like this: ask the file name open the file for reading and read all the names into a list close the file while not done: ask the user for a name if the name is not in the list: add the name to the list open the file for writing write the list to the file close the file Kent From kent37 at tds.net Fri Oct 13 13:39:52 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 13 Oct 2006 07:39:52 -0400 Subject: [Tutor] How to write string in a file, each one on new line??? In-Reply-To: References: Message-ID: <452F7B08.6020300@tds.net> Asrarahmed Kadri wrote: > Folks, > > I dont like to swamp your mailboxes with my trivial questions. We don't mind trivial questions, this is a list for beginners. But there is no need to swamp our mailboxes by asking the same question more than once, and if you include complete code and complete error tracebacks you have a much better chance of getting a good answer. Kent From ajkadri at googlemail.com Fri Oct 13 14:03:15 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Fri, 13 Oct 2006 13:03:15 +0100 Subject: [Tutor] Code for checking whether an input string is a palindrome or not. Message-ID: Hi, Here is a code that reports whether the string is a palindrome or not. I have posted it to help people new to programming ( i am also a newbie) to understand the logic and comment on it. Share and expand your knowledge as well as understanding... Happy scripting.... Regards, Asrar Code: string1 = raw_input("enter a string\n") str_len = len(string1) flag = 0 j = str_len-1 for i in range(0,(str_len-1)/2): if string1[i] == string1[j]: j = j-1 else: flag = 1 break if flag ==0: print "The entered string is a PALINDROME" else: print "The entered string is not a PALINDROME" -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061013/c5162c3e/attachment.htm From alan.gauld at btinternet.com Fri Oct 13 15:08:48 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 13 Oct 2006 14:08:48 +0100 Subject: [Tutor] Code for checking whether an input string is a palindromeor not. References: Message-ID: "Asrarahmed Kadri" wrote in message > Here is a code that reports whether the string is a palindrome or > not. I'd suggest a simpler approach is to use the string/list methods in Python: string1 = list(raw_input("enter a string\n")) #using a list is easier string2 = string1[:] # make a copy string2.reverse() if string1 == string2: print "The entered string is a PALINDROME" else: print "The entered string is not a PALINDROME" HTH, Alan G > string1 = raw_input("enter a string\n") > str_len = len(string1) > flag = 0 > j = str_len-1 > > for i in range(0,(str_len-1)/2): > if string1[i] == string1[j]: > j = j-1 > > else: > flag = 1 > break > if flag ==0: > print "The entered string is a PALINDROME" > else: > print "The entered string is not a PALINDROME" -------------------------------------------------------------------------------- > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From simon at brunningonline.net Fri Oct 13 16:46:21 2006 From: simon at brunningonline.net (Simon Brunning) Date: Fri, 13 Oct 2006 15:46:21 +0100 Subject: [Tutor] Code for checking whether an input string is a palindrome or not. In-Reply-To: References: Message-ID: <8c7f10c60610130746t4c3cf2acia0b2629f818bc3ef@mail.gmail.com> def pal(spam): return spam == spam[::-1] ;-) -- Cheers, Simon B simon at brunningonline.net http://www.brunningonline.net/simon/blog/ From kent37 at tds.net Fri Oct 13 17:12:59 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 13 Oct 2006 11:12:59 -0400 Subject: [Tutor] Code for checking whether an input string is a palindrome or not. In-Reply-To: References: Message-ID: <452FACFB.4090209@tds.net> Asrarahmed Kadri wrote: > > Hi, > > Here is a code that reports whether the string is a palindrome or not. I > have posted it to help people new to programming ( i am also a newbie) > to understand the logic and comment on it. > > Share and expand your knowledge as well as understanding... > > Happy scripting.... > > Regards, > Asrar > Others have pointed out that there are easier ways to do this. I'll comment on your code. > Code: > > > > string1 = raw_input("enter a string\n") > > str_len = len(string1) > > > > flag = 0 > j = str_len-1 > > for i in range(0,(str_len-1)/2): I think there is an off-by-one error here; try 'abcdba' as a test. > if string1[i] == string1[j]: Negative indices would work well here, you don't need j at all: if string1[i] == string1[-i]: This would also be a good place to use for: / else: but that is a bit more advanced. Kent > j = j-1 > > else: > flag = 1 > break > if flag ==0: > print "The entered string is a PALINDROME" > else: > print "The entered string is not a PALINDROME" > > > -- > To HIM you shall return. > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From meherkp at gmail.com Fri Oct 13 18:12:31 2006 From: meherkp at gmail.com (Meher Kolli) Date: Fri, 13 Oct 2006 09:12:31 -0700 Subject: [Tutor] Tutor Digest, Vol 32, Issue 51 In-Reply-To: References: Message-ID: <3f61ac130610130912m7142b182pe76709fd62ac1829@mail.gmail.com> On 10/13/06, tutor-request at python.org wrote: > > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request at python.org > > You can reach the person managing the list at > tutor-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. Re: Tutor Digest, Vol 32, Issue 49 (Alan Gauld) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Fri, 13 Oct 2006 10:09:04 +0100 > From: "Alan Gauld" > Subject: Re: [Tutor] Tutor Digest, Vol 32, Issue 49 > To: tutor at python.org > Message-ID: > Content-Type: text/plain; format=flowed; charset="iso-8859-1"; > reply-type=original > > > "Meher Kolli" wrote in message > > > You can't add \n to a string ..up have use something like this > > > > if str == 'q': > > done = 1 > > fd.close() > > else: > > fd.write("%s \n" %(str)) > > What makes you think so? > > >>> s = 'l' > >>> s += '\n' > >>> s > 'l\n' > >>> > > Seems to work.... '\n' is just a character like any other. The issue was to have a newline or return character after every string, Here it is just iterpreted as \n alphabet., but not as a return character. -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > End of Tutor Digest, Vol 32, Issue 51 > ************************************* > -- Meher Kolli Sunnyvale,CA-94085 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061013/0f750b22/attachment.html From dyoo at hkn.eecs.berkeley.edu Fri Oct 13 18:33:35 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 13 Oct 2006 09:33:35 -0700 (PDT) Subject: [Tutor] Tutor Digest, Vol 32, Issue 51 In-Reply-To: <3f61ac130610130912m7142b182pe76709fd62ac1829@mail.gmail.com> References: <3f61ac130610130912m7142b182pe76709fd62ac1829@mail.gmail.com> Message-ID: >> What makes you think so? >> >> >>> s = 'l' >> >>> s += '\n' >> >>> s >> 'l\n' >> >>> >> >> Seems to work.... '\n' is just a character like any other. > > The issue was to have a newline or return character after every string, > Here it is just iterpreted as \n alphabet., but not as a return > character. Hi Meher, Are you familiar with Python's rules for escaped character literals? http://docs.python.org/ref/strings.html In regular character literals, '\n' is treated as the single newline character, and not as the literal sequence of a backslash and 'n'. We can see this concretely: ############# >>> len('\n') 1 ############# The backslashing notation is necessary in Python because we often need to talk about characters that are hard to type literally. The escape characters provide us a coded way to talk about those characters. If we did want to talk about the string that contains the "backslash" and "n" sequence, we have to be a little subtle: ############## >>> len('\\n') 2 ############## Alan and I want to clarify that the way the newlines are being handled in the original program looks perfectly fine at the moment; I don't think that's the source of the problem. From kent37 at tds.net Fri Oct 13 18:37:06 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 13 Oct 2006 12:37:06 -0400 Subject: [Tutor] Code for checking whether an input string is a palindrome or not. In-Reply-To: References: <452FACFB.4090209@tds.net> Message-ID: <452FC0B2.9010108@tds.net> Asrarahmed Kadri wrote: > Yes, you are right; the code isnt working for 'abcdba'; > So what should I do to rectify it. Try walking through the code by hand so you understand why it is failing. Then maybe you can figure out how to fix it. It's important to learn to find and fix errors yourself. Kent PS Please reply on the list. > > Thanks, > Asrar > > > On 10/13/06, *Kent Johnson* > wrote: > > Asrarahmed Kadri wrote: > > > > Hi, > > > > Here is a code that reports whether the string is a palindrome or > not. I > > have posted it to help people new to programming ( i am also a > newbie) > > to understand the logic and comment on it. > > > > Share and expand your knowledge as well as understanding... > > > > Happy scripting.... > > > > Regards, > > Asrar > > > > Others have pointed out that there are easier ways to do this. I'll > comment on your code. > > > Code: > > > > > > > > string1 = raw_input("enter a string\n") > > > > str_len = len(string1) > > > > > > > > flag = 0 > > j = str_len-1 > > > > for i in range(0,(str_len-1)/2): > > I think there is an off-by-one error here; try 'abcdba' as a test. > > > if string1[i] == string1[j]: > > Negative indices would work well here, you don't need j at all: > if string1[i] == string1[-i]: > > This would also be a good place to use for: / else: but that is a bit > more advanced. > > Kent > > > j = j-1 > > > > else: > > flag = 1 > > break > > if flag ==0: > > print "The entered string is a PALINDROME" > > else: > > print "The entered string is not a PALINDROME" > > > > > > -- > > To HIM you shall return. > > > > > > > ------------------------------------------------------------------------ > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > -- > To HIM you shall return. From dyoo at hkn.eecs.berkeley.edu Fri Oct 13 18:53:32 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 13 Oct 2006 09:53:32 -0700 (PDT) Subject: [Tutor] How to write strings with new line character in a file In-Reply-To: References: <452F096C.1030201@alum.rpi.edu> Message-ID: > fname = raw_input("Enter the file name to write data to:\t") > > fd = open(fname,'a+') > print fd > done = 0 Ok, good, that helps a lot: that's exactly what we need to diagnose the problem. There appears to be something funky that happens with append-plus mode. This problem has come up before on the list: http://aspn.activestate.com/ASPN/Mail/Message/python-tutor/2961494 In general, any of the '+' modes on a Windows platform is slightly broken. See: http://mail.python.org/pipermail/tutor/2006-September/049511.html for approaches that people suggest to avoid "plus" mode issues. From dyoo at hkn.eecs.berkeley.edu Fri Oct 13 19:04:35 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 13 Oct 2006 10:04:35 -0700 (PDT) Subject: [Tutor] Code for checking whether an input string is a palindrome or not. In-Reply-To: <452FC0B2.9010108@tds.net> References: <452FACFB.4090209@tds.net> <452FC0B2.9010108@tds.net> Message-ID: >> Yes, you are right; the code isnt working for 'abcdba'; >> So what should I do to rectify it. > > Try walking through the code by hand so you understand why it is > failing. Then maybe you can figure out how to fix it. It's important to > learn to find and fix errors yourself. Hi Asrar, On a slight tangent: you have a bunch of code that takes input from the user, and then checks it for palindromeness. If you have a palindrome-checking function that eats strings, then you can do tests without pestering the user. So my suggestion is to try to take your existing code and make a function called 'is_palindrome' (or if you want, something shorter like pali()). The key is that once you have a function, you should be able to write small tests like: def pali(word): """Returns True if word is palindromic.""" ## ... fill me in ## Test cases: assert (pali("aa") == True) assert (pali("abcdba") == False) Once you have something like this, then you can run all tests together every time you change the palindrome function. As you've experienced, the problem is subtle enough that there's going to be a few edge cases. You want to make it easy to make sure all the things that worked before continue to work. From euoar at yahoo.es Fri Oct 13 21:33:49 2006 From: euoar at yahoo.es (Alfonso) Date: Fri, 13 Oct 2006 21:33:49 +0200 Subject: [Tutor] executing with double click on linux In-Reply-To: <452D4A9E.7020206@gmail.com> References: <452D491A.5000609@yahoo.es> <452D4A9E.7020206@gmail.com> Message-ID: <452FEA1D.8050608@yahoo.es> Jonathon Sisson escribi?: > Alfonso wrote: > >> Sorry for the too obvious question. I'm new to python and have no idea >> how can I make execute a compiled .pyc with a double click in linux, >> with gnome. Trying to double click in a .py gives allways the question >> wether I want to execute the text file, or read it. (This behaviour can >> be changed with gconf-editor, but as it is for security matters, I would >> prefer to execute the .pyc with a double click). I have tried to >> associate python to the .pyc (first time I executed it there was no >> programm associated), but it doesn't work. >> >> > > I don't know how much Linux experience you have (judging by the > "double-click" concept, I'm assuming you're coming from a Windows > background or are perhaps catering to users with only a Windows > background) (correct me if I'm wrong)...so I'm going to break this down > as much as I can. > > .pyc files are considered binary files by Linux. As such, bash attempts > to execute them as binary (ELF, etc...), which obviously won't work. If > you really need to have double-click/execute functionality, consider > writing a small shell script to execute the .pyc file for you. > > For instance, let's say you have a python script "foo.py" and a compiled > python script "foo.pyc". If you attempt to run foo.py from the shell > and you have a proper header (i.e. #!/usr/bin/python), then bash can > execute the script. I'm assuming that GNOME has similar functionality > (I prefer Fluxbox to either GNOME or KDE), which allows your .py files > to execute directly. .pyc, however, even with a file association, fails > to launch...on my system, I get this error: > > $ ./foo.pyc > bash: ./foo.pyc: cannot execute binary file > > bash recognizes the file as binary, but it fails to launch as an ELF > binary (or whatever you're set up to run). To fix it, simply write a > shell script as such: > > > #!/bin/sh > > python /home/me/scripts/foo.pyc > > > > Name the script whatever you want (i.e. foo.sh) then run from the > commandline: > > $ chmod 700 foo.sh > > This gives the script read/write/execute permissions for the owner of > the script...if you require read/write/execute/etc...for group or all, > change 700 to whatever you need. (i.e. 755 for rwxr-xr-x permissions) > > (Alternatively you can right click on the shell script and set > permissions graphically...whichever you prefer) Now, you should be able > to double-click the script (or preferably a shortcut to the script on > your desktop), which will launch the compiled python module for you. If > this seems like a lot of work, then perhaps you could write a shell > script to automate the task of creating the shell script and setting > permissions each time you create a new .pyc...doh? > > Hope this is a satisfactory answer...and if anyone knows something I > have overlooked, please let Alfonso and I know. > > Jonathon > > > >> Thank you for your answer. >> >> >> ______________________________________________ >> LLama Gratis a cualquier PC del Mundo. >> Llamadas a fijos y m?viles desde 1 c?ntimo por minuto. >> http://es.voice.yahoo.com >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> > > Thank you very much for your answer. Both true, coming from windows, three years with linux. I don't have any fear to executing from the shell, but It's not the same thing with some of my friends, totally new to linux, and not very much friends of the console. I would like to distribute to them my python programms (when I have the knolowdge to writte something decent with python :) ). If I use a bash script I have the same "problem" that with executing the .py. Gnome asks wether you want to execute or read it, etc. This is due to security reasons, and can be disabled using the tool gconf-editor, you can change that behaviour so that the files are allways executed or opened with a text editor. But I didn't want to change that, and I thought this could be easily avoided just executing the .pyc files, because I have programmed with mono (.net) in linux and that works so. I mean, if I'm not mistaked .pyc are compiled in intermediate language files, just like .exe in .net/mono. With mono all I have to do was chmod at the .exe, then changing the programm with which the .exe is opened (to mono) and that works fine for me, it can be opened with a double click. But it's not an elf binary, I think... I think there must be a way to execute with a launcher the programm without being asked each time. As it is for example with bittornado or bittorrent, both written in python and both are executed from the applications menu or from a launcher at the desktop with no intermediate question about if you want to show or execute the file, or just to cancel the action. In fact, when I execute bittornado it's a file called btdownoladgui.bittornado which is executed. But it's python code. If I try to do something similar (executing a file with a not .py extension, but written in python), gnome will complain, that the file is python script with a different extension, and that as it could be a security risk it won't be executed. Could it be that those applications, bittornado, bittorrent, etc., modify some gnome configuration files when they are installed, to avoid that default behaviour? Don't know if I'm explaining right (sorry for my bad english). Resume: anyone that has programmed a python app and created a launcher, in gnome, how do you make it so that the file is executed directly after clicking on it without showing all this anoying messages each time? Again, thank you for your answers. ______________________________________________ LLama Gratis a cualquier PC del Mundo. Llamadas a fijos y m?viles desde 1 c?ntimo por minuto. http://es.voice.yahoo.com From jfabiani at yolo.com Fri Oct 13 23:20:34 2006 From: jfabiani at yolo.com (johnf) Date: Fri, 13 Oct 2006 14:20:34 -0700 Subject: [Tutor] executing with double click on linux In-Reply-To: <452FEA1D.8050608@yahoo.es> References: <452D491A.5000609@yahoo.es> <452D4A9E.7020206@gmail.com> <452FEA1D.8050608@yahoo.es> Message-ID: <200610131420.34998.jfabiani@yolo.com> On Friday 13 October 2006 12:33, Alfonso wrote: Could be wrong but can't you use file associations? I do on my SUSE system. John From bgailer at alum.rpi.edu Sat Oct 14 01:35:36 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri, 13 Oct 2006 16:35:36 -0700 Subject: [Tutor] How to write strings with new line character in a file In-Reply-To: References: <452F096C.1030201@alum.rpi.edu> Message-ID: <453022C8.1050907@alum.rpi.edu> Asrarahmed Kadri wrote: > Here is the complete code: > fd is the file handle. > > import sys > > def check_dup(fd1): > print fd1 > fd1.seek(0,0) > done = 0 > list1 = [] > while not done: > x = fd1.readline() > if x == "": > done = 1 > else: > list1.append(x) > return list1 > > > fname = raw_input("Enter the file name to write data to:\t") > > fd = open(fname,'a+') > print fd > done = 0 > > while not done: > str = raw_input("Enter login name:\t to quit type 'q'") > > if str == 'q': > done = 1 > else: > flag = check_dup(fd) > print flag > if str in flag: > print "Login already exists.!!" > else: > fd.seek(0,2) > fd.write(str + '\n') > Thank you. I can't get this to fail, so I wonder whether it has to do with permissions? What OS are you running on? Also note when you open a file for output (append or write) it is inadvisable to change the file position or to read it ( as you are doing). As Kent points out there are better ways to do what you are doing. My (minimalist?) version is: fname = raw_input("Enter the file name to write data to:\t") fd = open(fname,'a+') names = set() while 1: name = raw_input("Enter login name:\t to quit type 'q'") if name == 'q': break if name in names: print "Login already exists.!!" names.add(name) fname.write('\n'.join(names)) -- Bob Gailer 510-978-4454 From bgailer at alum.rpi.edu Sat Oct 14 01:55:54 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri, 13 Oct 2006 16:55:54 -0700 Subject: [Tutor] How to write strings with new line character in a file OOPS CORRECTION In-Reply-To: <453022C8.1050907@alum.rpi.edu> References: <452F096C.1030201@alum.rpi.edu> <453022C8.1050907@alum.rpi.edu> Message-ID: <4530278A.90009@alum.rpi.edu> Bob Gailer wrote: > Asrarahmed Kadri wrote: > >> Here is the complete code: >> fd is the file handle. >> >> import sys >> >> def check_dup(fd1): >> print fd1 >> fd1.seek(0,0) >> done = 0 >> list1 = [] >> while not done: >> x = fd1.readline() >> if x == "": >> done = 1 >> else: >> list1.append(x) >> return list1 >> >> >> fname = raw_input("Enter the file name to write data to:\t") >> >> fd = open(fname,'a+') >> print fd >> done = 0 >> >> while not done: >> str = raw_input("Enter login name:\t to quit type 'q'") >> >> if str == 'q': >> done = 1 >> else: >> flag = check_dup(fd) >> print flag >> if str in flag: >> print "Login already exists.!!" >> else: >> fd.seek(0,2) >> fd.write(str + '\n') >> >> > Thank you. I can't get this to fail, so I wonder whether it has to do > with permissions? What OS are you running on? > > Also note when you open a file for output (append or write) it is > inadvisable to change the file position or to read it ( as you are doing). > > As Kent points out there are better ways to do what you are doing. My > (minimalist?) version is: > > fname = raw_input("Enter the file name to write data to:\t") > fd = open(fname,'a+') > names = set() > while 1: > name = raw_input("Enter login name:\t to quit type 'q'") > if name == 'q': break > if name in names: print "Login already exists.!!" > names.add(name) > fname.write('\n'.join(names)) <<<< OOPS > Should be fd.write('\n'.join(names)) > > -- Bob Gailer 510-978-4454 From pyro9219 at gmail.com Sat Oct 14 03:50:18 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Fri, 13 Oct 2006 18:50:18 -0700 Subject: [Tutor] Zipfile and File manipulation questions. Message-ID: First question.. This is the code that I have: for filename in zfile.namelist(): outfile = open(filename, 'w') outfile.write(zfile.read(filename)) outfile.close() Is there a way to say : for filename in zfile.namelist() contains '.txt, .exe': outfile = open(filename, 'w') outfile.write(zfile.read(filename)) outfile.close() second question is along the same lines.. I'm looking for a way to say: os.remove('All by .py') or- os.remove('*.txt, *.exe') Thank you all again for your time and effort. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061013/558c479a/attachment.html From dyoo at hkn.eecs.berkeley.edu Sat Oct 14 07:23:46 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 13 Oct 2006 22:23:46 -0700 (PDT) Subject: [Tutor] Zipfile and File manipulation questions. In-Reply-To: References: Message-ID: > Is there a way to say : > for filename in zfile.namelist() contains '.txt, .exe': Hi Chris, Yes. It sounds like you want to filter zfile.namelist() and restrict the entries to those with particular extensions. Try a "list comprehension" to filter for those interesting filenames: for filename in [f for f in zfile.namelist() if os.path.splitext(f)[1] in ('.txt', '.exe')]: This may be a little dense and hard to read. So you can always break this out into a function: ######################################################### def keep_txt_exe_filenames(file_list): """keep_txt_exe_filenames: list of strings -> list of strings Returns a list of all filenames that end in .txt or .exe.""" return [f for f in file_list if os.path.splitext(f)[1] in ('.txt', '.exe')] ######################################################### At least that tight expression is documented and can be treated as a black box. But after you have this function, you can use that helper function: for filename in keep_txt_exe_filenames(zfile.namelist()): ... which is usually fairly easy for a person to understand. > os.remove('*.txt, *.exe') One way to approach this is with loops. You might find the glob module useful here: http://docs.python.org/lib/module-glob.html It'll help to match the file names for each glob pattern. Again, if you find yourself doing this a bit, make a helper function to make it easier to say next time. *grin* Good luck! From rdm at rcblue.com Sat Oct 14 08:24:53 2006 From: rdm at rcblue.com (Dick Moores) Date: Fri, 13 Oct 2006 23:24:53 -0700 Subject: [Tutor] tkinter tutorials In-Reply-To: References: Message-ID: <7.0.1.0.2.20061013232029.075c6298@rcblue.com> At 05:45 PM 10/12/2006, Danny Yoo wrote: >John Grayson's "Python and Tkinter Programming" is an excellent book on >learning the Tkinter toolkit: > > http://www.manning.com/grayson/ Danny, "Python and Tkinter Programming" is still in its first edition, which came out in 2000. Python has changed a lot since then. Hasn't Tkinter? Is the book still usable by a Tkinter beginner? Dick Moores From john at fouhy.net Sat Oct 14 08:48:28 2006 From: john at fouhy.net (John Fouhy) Date: Sat, 14 Oct 2006 19:48:28 +1300 Subject: [Tutor] A puzzle for you Message-ID: <5e58f2e40610132348j3b06d5e9vba45f2ce6c74747d@mail.gmail.com> >From the python_dev LiveJournal community --- Predict the outcome of the following code: ## from random import * seed() [choice(dict((x+1,0) for x in range(1000))) for x in range(693)][0] ## -- John. From asdlinux at yahoo.se Sat Oct 14 08:59:10 2006 From: asdlinux at yahoo.se (=?ISO-8859-1?Q?Magnus_Wirstr=F6m?=) Date: Sat, 14 Oct 2006 08:59:10 +0200 Subject: [Tutor] How to read content in a tar file with tarfile module In-Reply-To: <452BE339.2070100@yahoo.se> References: <452BE339.2070100@yahoo.se> Message-ID: <45308ABE.5090204@yahoo.se> Thank you for all the answers. Sorry for not replying but i have been very busy this week I will try all the suggested ways. //Magnus Magnus Wirstr?m skrev: > Hi everyone > > I have written a app that makes a tar file and all works well... Now i > want to expand that app so it can read read the tar and give me the > contents of the tar file. How is the best way to do this ? I can't find > a "listdir" like function in tarfile. Can anyone point me in the right > direction? > Thanks > Magnus > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From alan.gauld at btinternet.com Sat Oct 14 09:54:16 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 14 Oct 2006 08:54:16 +0100 Subject: [Tutor] tkinter tutorials References: <7.0.1.0.2.20061013232029.075c6298@rcblue.com> Message-ID: > Danny, "Python and Tkinter Programming" is still in its first > edition, which came out in 2000. Python has changed a lot since > then. > Hasn't Tkinter? Is the book still usable by a Tkinter beginner? Tkinter has not changed hardly at all. The only shame about the book is that it strongly features the Python MegaWidgets add-on library whereas it was Tix that was adoptted in the standard library, and there is no coverage of Tix at all. (Time for a second edition Manning?) However the book is not really a beginners book in Tkinter, you should do Fred Lundh's intro tutorial first, but it is good on more advanced topics and as a reference book. Alan G. From billburns at pennswoods.net Sat Oct 14 14:12:14 2006 From: billburns at pennswoods.net (Bill Burns) Date: Sat, 14 Oct 2006 08:12:14 -0400 Subject: [Tutor] Zipfile and File manipulation questions. In-Reply-To: References: Message-ID: <4530D41E.7070606@pennswoods.net> Chris Hengge wrote: > First question.. > > This is the code that I have: > for filename in zfile.namelist(): > outfile = open(filename, 'w') > outfile.write(zfile.read(filename)) > outfile.close() > > Is there a way to say : > for filename in zfile.namelist() contains '.txt, .exe': > outfile = open(filename, 'w') > outfile.write(zfile.read(filename)) > outfile.close() Maybe take a look at 'endswith': Example: for filename in zfile.namelist(): if filename.endswith('.exe') or filename.endswith('.txt'): # do something with filename > second question is along the same lines.. > > I'm looking for a way to say: > os.remove('All by .py') > > or- > > os.remove('*.txt, *.exe') > > Thank you all again for your time and effort. > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Sat Oct 14 14:14:45 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 14 Oct 2006 13:14:45 +0100 Subject: [Tutor] tkinter tutorials References: <7.0.1.0.2.20061013232029.075c6298@rcblue.com> Message-ID: "Alan Gauld" wrote > Tkinter has not changed hardly at all. Yuk, a double negative, sorry. That should of course say: Tkinter has hardly changed at all. Hopefully that was obvious from my subsequent comments! Alan G. From gtnorton at earthlink.net Sat Oct 14 14:47:52 2006 From: gtnorton at earthlink.net (Glenn T Norton) Date: Sat, 14 Oct 2006 07:47:52 -0500 Subject: [Tutor] A puzzle for you In-Reply-To: <5e58f2e40610132348j3b06d5e9vba45f2ce6c74747d@mail.gmail.com> References: <5e58f2e40610132348j3b06d5e9vba45f2ce6c74747d@mail.gmail.com> Message-ID: <4530DC78.5080804@earthlink.net> John Fouhy wrote: >>From the python_dev LiveJournal community --- > >Predict the outcome of the following code: > >## >from random import * >seed() >[choice(dict((x+1,0) for x in range(1000))) for x in range(693)][0] >## > > > random.choice( [ SyntaxError: invalid syntax, 42 the answer is young skywalker. always the answer is 42. ] ) -- "Ketchup. For the good times... " - Ketchup Advisory Board Glenn Norton Application Developer Nebraska.gov 1-402-471-2777 glenn at nebraska.gov From amadeo.bellotti at gmail.com Sat Oct 14 15:11:38 2006 From: amadeo.bellotti at gmail.com (Amadeo Bellotti) Date: Sat, 14 Oct 2006 09:11:38 -0400 Subject: [Tutor] Python Magazine Message-ID: I no im probally not the best pereson to go about this but maybe people in this community are. I was wondering if there was or maybe someone can start a Python maganize kinda like 3dCreative or 2d Artist. that is an PDF magazine with tutorials interviews, python news, and maybe a programming challenge or two. and free would be nice i might start this but does anyone want to help maybe? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061014/cc3656a1/attachment.htm From gtnorton at earthlink.net Sat Oct 14 15:39:23 2006 From: gtnorton at earthlink.net (Glenn T Norton) Date: Sat, 14 Oct 2006 08:39:23 -0500 Subject: [Tutor] Python Magazine In-Reply-To: References: Message-ID: <4530E88B.1080604@earthlink.net> Amadeo Bellotti wrote: > I no im probally not the best pereson to go about this but maybe > people in this community are. I was wondering if there was or maybe > someone can start a Python maganize kinda like 3dCreative or 2d > Artist. that is an PDF magazine with tutorials interviews, python > news, and maybe a programming challenge or two. and free would be nice > i might start this but does anyone want to help maybe? > >------------------------------------------------------------------------ > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > "#1, make it so..." http://www.pyzine.com/ -- "Ketchup. For the good times... " - Ketchup Advisory Board Glenn Norton Application Developer Nebraska.gov 1-402-471-2777 glenn at nebraska.gov From amadeo.bellotti at gmail.com Sat Oct 14 15:43:15 2006 From: amadeo.bellotti at gmail.com (Amadeo Bellotti) Date: Sat, 14 Oct 2006 09:43:15 -0400 Subject: [Tutor] Python Magazine In-Reply-To: <4530E88B.1080604@earthlink.net> References: <4530E88B.1080604@earthlink.net> Message-ID: i saw it but it didnt quite meet what i wanted :\ On 10/14/06, Glenn T Norton wrote: > > Amadeo Bellotti wrote: > > > I no im probally not the best pereson to go about this but maybe > > people in this community are. I was wondering if there was or maybe > > someone can start a Python maganize kinda like 3dCreative or 2d > > Artist. that is an PDF magazine with tutorials interviews, python > > news, and maybe a programming challenge or two. and free would be nice > > i might start this but does anyone want to help maybe? > > > >------------------------------------------------------------------------ > > > >_______________________________________________ > >Tutor maillist - Tutor at python.org > >http://mail.python.org/mailman/listinfo/tutor > > > > > "#1, make it so..." > http://www.pyzine.com/ > > -- > "Ketchup. For the good times... " - Ketchup Advisory Board > Glenn Norton > Application Developer > Nebraska.gov > 1-402-471-2777 > glenn at nebraska.gov > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061014/69d06a19/attachment.html From ajkadri at googlemail.com Sat Oct 14 16:35:13 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Sat, 14 Oct 2006 15:35:13 +0100 Subject: [Tutor] Building a simple text editor Message-ID: Folks, I am trying to build a simple text editor which has a couple of options of editing, displaying and saving the file. Now what I want to do is to allow teh user to keep entering the text unless he pressed ':q'. How can I add this functionality?? Thanks. REgards, Asrar -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061014/f8fa6e6d/attachment.htm From alan.gauld at btinternet.com Sat Oct 14 16:52:37 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 14 Oct 2006 15:52:37 +0100 Subject: [Tutor] Building a simple text editor References: Message-ID: > I am trying to build a simple text editor which has a couple of > options of > editing, displaying and saving the file. Are you using a GUI or console? The solution is potentially quite different depending on the choice. > Now what I want to do is to allow teh user to keep entering the text > unless > he pressed ':q'. How are you reading the characters in the first place? if you can find a way to read characters from the keyboard one at a time then while True ch = getchar() if ch ==':' ch = getchar() if ch == 'q': break Will work. So the question becomers do you know how to write getchar()? Alan G. From ajkadri at googlemail.com Sat Oct 14 17:04:02 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Sat, 14 Oct 2006 16:04:02 +0100 Subject: [Tutor] Building a simple text editor In-Reply-To: References: Message-ID: Is it possible to make the utility like in vi, where the user keeps on entering the data and when he hits ':wq', the work is saved and the application exists. I guess the use of standard input file would be applicable??? Thanks. Regrds, Asrar On 10/14/06, Alan Gauld wrote: > > > I am trying to build a simple text editor which has a couple of > > options of > > editing, displaying and saving the file. > > Are you using a GUI or console? > The solution is potentially quite different depending on the choice. > > > Now what I want to do is to allow teh user to keep entering the text > > unless > > he pressed ':q'. > > How are you reading the characters in the first place? > > if you can find a way to read characters from the keyboard > one at a time then > > while True > ch = getchar() > if ch ==':' > ch = getchar() > if ch == 'q': break > > Will work. > > So the question becomers do you know how to write getchar()? > > Alan G. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061014/d827feb4/attachment.html From David.Heiser at intelliden.com Sat Oct 14 17:50:02 2006 From: David.Heiser at intelliden.com (David Heiser) Date: Sat, 14 Oct 2006 09:50:02 -0600 Subject: [Tutor] Reading escaped characters from a file Message-ID: I have code that uses variables to hold escaped characters like "\n" or "\03". As long as the assignment is done within the code, like self.crChar = "\n", there is no problem. But When I try to read the same character string from a text file and assign it, the string is seen as just a string of characters instead of an escape sequence, and the program fails. I read the "parameter = value" pairs, like "crChar = \n", from an ASCII file and store them in a dictionary; "parameterDict[parameter] = value". Then I assign the value to the variable using "self.crChar = parameterDict["crChar"]. When I print "self.crChar", it displays "\\n" and it doesn't behave like a carriage return. Can anyone guide me toward a resolution? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061014/decc8cb2/attachment.htm From rabidpoobear at gmail.com Sat Oct 14 18:04:22 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sat, 14 Oct 2006 11:04:22 -0500 Subject: [Tutor] Reading escaped characters from a file In-Reply-To: References: Message-ID: <45310A86.4020308@gmail.com> David Heiser wrote: > > I have code that uses variables to hold escaped characters like "\n" > or "\03". As long as the assignment is done within the code, like > self.crChar = "\n", there is no problem. But When I try to read the > same character string from a text file and assign it, the string is > seen as just a string of characters instead of an escape sequence, and > the program fails. > > I read the "parameter = value" pairs, like "crChar = \n", from an > ASCII file and store them in a dictionary; "parameterDict[parameter] = > value". Then I assign the value to the variable using "self.crChar = > parameterDict["crChar"]. When I print "self.crChar", it displays "\\n > " and it doesn't behave like a carriage return. Please include the code that is causing you trouble instead of trying to sum up what you think the problem is. Quite often the problem is just a simple syntax or other error that the beginner may overlook that we can help by pointing out to you. In this situation, I believe what's happening is that you expect this: #ascii text file hello, world!\n #----- end to be read into python as >>> f.readlines()[0] == 'hello, world!\n' True but no, that's not what the file says. The file says 'hello, world \\n' because you can see an actual \ in the file text, right? So in python it'll be represented by a double-backslash. The actual \n is an escape code, you can't ever see it in files. In the file #start a b c d e #end >>> print f.readlines() ['a\n','b\n','c\n','d\n','e\n'] You don't explicitly put \n in a text file to have a string with \n at the end. You hit enter at the end of the line. > > Can anyone guide me toward a resolution? > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From wescpy at gmail.com Sat Oct 14 18:07:43 2006 From: wescpy at gmail.com (wesley chun) Date: Sat, 14 Oct 2006 09:07:43 -0700 Subject: [Tutor] Reading escaped characters from a file In-Reply-To: References: Message-ID: <78b3a9580610140907r6e468a1dqed294bc22eca7737@mail.gmail.com> > I have code that uses variables to hold escaped characters like "\n" or > "\03". As long as the assignment is done within the code, like self.crChar = > "\n", there is no problem. But When I try to read the same character string > from a text file and assign it, the string is seen as just a string of > characters instead of an escape sequence, and the program fails. > : > When I print "self.crChar", it displays "\\n" and > it doesn't behave like a carriage return. david, the problem is that when you're doing it "live", Python translates the \n as a single character, NEWLINE. when you are reading those same characters from disk, what it reads is '\' followed by 'n' because that's what stored in the file and the reason why you get '\\n', which is the same as r'\n', a raw string. in "\n" the backslash is used to "escape the n," meaning to realize the special symbol \n. in "\\n", the (frontmost) backslash is used to escape the 2nd backslash, telling Python to take the backslash verbatim and to take the following 'n' as-is. in order to read in a NEWLINE, you have to just store a blank line to the disk file. off the top of my head, i can't think of a way to "eval" a '/' and 'n' to convert it into a \n... perhaps someone else here can help with that. regards, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From wescpy at gmail.com Sat Oct 14 18:16:58 2006 From: wescpy at gmail.com (wesley chun) Date: Sat, 14 Oct 2006 09:16:58 -0700 Subject: [Tutor] Building a simple text editor In-Reply-To: References: Message-ID: <78b3a9580610140916o6f8d3496xff8972337dbbcf51@mail.gmail.com> > I am trying to build a simple text editor which has a couple of options of > editing, displaying and saving the file. > Now what I want to do is to allow teh user to keep entering the text unless > he pressed ':q'. reading of and writing of a text file is one of the examples i added to "Core Python Programming". in fact, these are the 1st two applications that are presented to the reader to introduce them to their first pieces of Python code to study. in the application that writes text files, the user types '.' to terminate the input and save the file. that can easily be changed to 'q'. you don't need to buy the book if you don't wish... you can just get to the source code. it's available at the book's website (see below)... just go to chapter 3. (the server is down at the moment, but should be back up soon.) furthermore, in order to do what you suggest, e.g., make it work like vim where it has two modes, edit and input, you will have to build that into your application, plus have special keys to get you into that mode as well as a key (e.g., ESC) to get you out. good luck! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From bgailer at alum.rpi.edu Sat Oct 14 19:28:27 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sat, 14 Oct 2006 10:28:27 -0700 Subject: [Tutor] A puzzle for you In-Reply-To: <5e58f2e40610132348j3b06d5e9vba45f2ce6c74747d@mail.gmail.com> References: <5e58f2e40610132348j3b06d5e9vba45f2ce6c74747d@mail.gmail.com> Message-ID: <45311E3B.5040904@alum.rpi.edu> John Fouhy wrote: > >From the python_dev LiveJournal community --- > > Predict the outcome of the following code: > > ## > from random import * > seed() > [choice(dict((x+1,0) for x in range(1000))) for x in range(693)][0] > ## > Hmm - interesting. Given that the argument of random.choice is supposed to be a sequence (according to the docs str, unicode, list, tuple, buffer, xrange), I'd expect an exception. I also predicted the the result if no exception was raised, and that was correct. I will withhold further observation until others (who wish) may reply. -- Bob Gailer 510-978-4454 From kent37 at tds.net Sat Oct 14 20:21:42 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 14 Oct 2006 14:21:42 -0400 Subject: [Tutor] Reading escaped characters from a file In-Reply-To: References: Message-ID: <45312AB6.8010401@tds.net> David Heiser wrote: > > I have code that uses variables to hold escaped characters like "\n" or > "\03". As long as the assignment is done within the code, like > self.crChar = "\n", there is no problem. But When I try to read the > same character string from a text file and assign it, the string is seen > as just a string of characters instead of an escape sequence, and the > program fails. > > I read the "parameter = value" pairs, like "crChar = \n", from an ASCII > file and store them in a dictionary; "parameterDict[parameter] = value". > Then I assign the value to the variable using "self.crChar = > parameterDict["crChar"]. When I print "self.crChar", it displays "\\n > " and it doesn't behave like a carriage return. You can use the 'string_escape' codec to translate literal backslash escapes to the special characters the escapes represent: In [5]: s='this is not a newline\\n' In [6]: s.decode('string_escape') Out[6]: 'this is not a newline\n' In [7]: s Out[7]: 'this is not a newline\\n' See the difference? Kent From pyro9219 at gmail.com Sat Oct 14 23:52:04 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Sat, 14 Oct 2006 14:52:04 -0700 Subject: [Tutor] Zipfile and File manipulation questions. In-Reply-To: <4530D41E.7070606@pennswoods.net> References: <4530D41E.7070606@pennswoods.net> Message-ID: Excellent suggestion! Thanks! I have a question... is endswith() case sensitive? On 10/14/06, Bill Burns wrote: > > Chris Hengge wrote: > > First question.. > > > > This is the code that I have: > > for filename in zfile.namelist(): > > outfile = open(filename, 'w') > > outfile.write(zfile.read(filename)) > > outfile.close() > > > > Is there a way to say : > > for filename in zfile.namelist() contains '.txt, .exe': > > outfile = open(filename, 'w') > > outfile.write(zfile.read(filename)) > > outfile.close() > > > Maybe take a look at 'endswith': > > Example: > for filename in zfile.namelist(): > if filename.endswith('.exe') or filename.endswith('.txt'): > # do something with filename > > > > second question is along the same lines.. > > > > I'm looking for a way to say: > > os.remove('All by .py') > > > > or- > > > > os.remove('*.txt, *.exe') > > > > Thank you all again for your time and effort. > > > > > > ------------------------------------------------------------------------ > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061014/3daabda4/attachment.html From kent37 at tds.net Sat Oct 14 23:59:53 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 14 Oct 2006 17:59:53 -0400 Subject: [Tutor] Zipfile and File manipulation questions. In-Reply-To: <4530D41E.7070606@pennswoods.net> References: <4530D41E.7070606@pennswoods.net> Message-ID: <45315DD9.6010300@tds.net> Bill Burns wrote: > Maybe take a look at 'endswith': > > Example: > for filename in zfile.namelist(): > if filename.endswith('.exe') or filename.endswith('.txt'): > # do something with filename In Python 2.5 endswith() can take a tuple of strings to try: if filename.endswith(('.exe', '.txt')): (The double parentheses create a single, tuple argument instead of passing two string arguments.) And yes, endswith() is case-sensitive; use e.g. if filename.lower().endswith(('.exe', '.txt')): Kent From pyro9219 at gmail.com Sun Oct 15 00:18:28 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Sat, 14 Oct 2006 15:18:28 -0700 Subject: [Tutor] Zipfile and File manipulation questions. In-Reply-To: <4530D41E.7070606@pennswoods.net> References: <4530D41E.7070606@pennswoods.net> Message-ID: Oops.... I get an error using that code.. if filename.endswith('.cap','.fru','.hex') or filename.endswith('.sdr', '.cfg'): TypeError: slice indices must be integers or None On 10/14/06, Bill Burns wrote: > > Chris Hengge wrote: > > First question.. > > > > This is the code that I have: > > for filename in zfile.namelist(): > > outfile = open(filename, 'w') > > outfile.write(zfile.read(filename)) > > outfile.close() > > > > Is there a way to say : > > for filename in zfile.namelist() contains '.txt, .exe': > > outfile = open(filename, 'w') > > outfile.write(zfile.read(filename)) > > outfile.close() > > > Maybe take a look at 'endswith': > > Example: > for filename in zfile.namelist(): > if filename.endswith('.exe') or filename.endswith('.txt'): > # do something with filename > > > > second question is along the same lines.. > > > > I'm looking for a way to say: > > os.remove('All by .py') > > > > or- > > > > os.remove('*.txt, *.exe') > > > > Thank you all again for your time and effort. > > > > > > ------------------------------------------------------------------------ > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061014/483e973e/attachment.htm From kent37 at tds.net Sun Oct 15 00:33:05 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 14 Oct 2006 18:33:05 -0400 Subject: [Tutor] Zipfile and File manipulation questions. In-Reply-To: References: <4530D41E.7070606@pennswoods.net> Message-ID: <453165A1.1090902@tds.net> Chris Hengge wrote: > Oops.... I get an error using that code.. > > if filename.endswith('.cap','.fru','.hex') or > filename.endswith('.sdr', '.cfg'): > TypeError: slice indices must be integers or None With Python 2.5 you can do this with a tuple argument. You need an extra set of parentheses to create the tuple: if filename.endswith(('.cap','.fru','.hex', '.sdr', '.cfg')): In Python 2.4 or less you need a separate endswith() for each ending. Kent From alan.gauld at btinternet.com Sun Oct 15 00:52:04 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 14 Oct 2006 23:52:04 +0100 Subject: [Tutor] Building a simple text editor References: Message-ID: "Asrarahmed Kadri" wrote > Is it possible to make the utility like in vi, where the user keeps > on > entering the data and when he hits ':wq', the work is saved and the > application exists. YES BUT THE ACTUAL CODE TO READ KEYSTROKES AS THEY ARE TYPED WILL BE VERY DIFFERENT DEPENDING ON WHEHER YOU USE A gii OR A TEXT CONSOLE. SEE MY EVENT HANDLING TOPIC FOR EXAMPLES OF BOTH STYLE TO COMPARE AND CONTRAST. Oops!! Sorry for the upper case, not meaning to shout but this mail tool has no case inversion, and its late... -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld > I guess the use of standard input file would be applicable??? > > Thanks. > Regrds, > Asrar > > On 10/14/06, Alan Gauld wrote: >> >> > I am trying to build a simple text editor which has a couple of >> > options of >> > editing, displaying and saving the file. >> >> Are you using a GUI or console? >> The solution is potentially quite different depending on the >> choice. >> >> > Now what I want to do is to allow teh user to keep entering the >> > text >> > unless >> > he pressed ':q'. >> >> How are you reading the characters in the first place? >> >> if you can find a way to read characters from the keyboard >> one at a time then >> >> while True >> ch = getchar() >> if ch ==':' >> ch = getchar() >> if ch == 'q': break >> >> Will work. >> >> So the question becomers do you know how to write getchar()? >> >> Alan G. >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> > > > > -- > To HIM you shall return. > -------------------------------------------------------------------------------- > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From pyro9219 at gmail.com Sun Oct 15 01:05:34 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Sat, 14 Oct 2006 16:05:34 -0700 Subject: [Tutor] Zipfile and File manipulation questions. In-Reply-To: <453165A1.1090902@tds.net> References: <4530D41E.7070606@pennswoods.net> <453165A1.1090902@tds.net> Message-ID: Got that working now, thanks. I've been using activepythons release, and they dont have 2.5 prepared yet. Guess I should just upgrade without them? On 10/14/06, Kent Johnson wrote: > > Chris Hengge wrote: > > Oops.... I get an error using that code.. > > > > if filename.endswith('.cap','.fru','.hex') or > > filename.endswith('.sdr', '.cfg'): > > TypeError: slice indices must be integers or None > > With Python 2.5 you can do this with a tuple argument. You need an extra > set of parentheses to create the tuple: > if filename.endswith(('.cap','.fru','.hex', '.sdr', '.cfg')): > > In Python 2.4 or less you need a separate endswith() for each ending. > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061014/71056432/attachment.html From pyro9219 at gmail.com Sun Oct 15 02:39:57 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Sat, 14 Oct 2006 17:39:57 -0700 Subject: [Tutor] Zipfile and File manipulation questions. In-Reply-To: References: <4530D41E.7070606@pennswoods.net> <453165A1.1090902@tds.net> Message-ID: Ok, last problem with this whole shebang... When I write the file from the zip, if it is in a subfolder, it will error.. The code below will detect if the file in contained inside a directory in the zip, but I just want it to write it like it wasn't. Another words Zipfile.zip looks like this file.ext file2.ext folder/ anotherfile.ext file.ext extracts fine, file2.ext extracts file.. but it see's the last file as folder/anotherfile.ext and it can't write it.. I tried to figure out how to use .split to get it working right.. but I'm not having any luck.. Thanks. for afile in zfile.namelist(): # For every file in the zip. # If the file ends with a needed extension, extract it. if afile.lower().endswith('.cap') \ or afile.lower().endswith('.hex') \ or afile.lower().endswith('.fru') \ or afile.lower().endswith('.cfg'): if afile.__contains__("/"): outfile = open(afile, 'w') # Open output buffer for writing. outfile.write(zfile.read(afile)) # Write the file. outfile.close() # Close the output file buffer. else: outfile = open(afile, 'w') # Open output buffer for writing. outfile.write(zfile.read(afile)) # Write the file. outfile.close() # Close the output file buffer. On 10/14/06, Chris Hengge wrote: > > Got that working now, thanks. > > I've been using activepythons release, and they dont have 2.5 prepared > yet. Guess I should just upgrade without them? > > On 10/14/06, Kent Johnson wrote: > > > > Chris Hengge wrote: > > > Oops.... I get an error using that code.. > > > > > > if filename.endswith('.cap','.fru','.hex') or > > > filename.endswith('.sdr', '.cfg'): > > > TypeError: slice indices must be integers or None > > > > With Python 2.5 you can do this with a tuple argument. You need an extra > > set of parentheses to create the tuple: > > if filename.endswith(('.cap','.fru','.hex', '.sdr', '.cfg')): > > > > In Python 2.4 or less you need a separate endswith() for each ending. > > > > Kent > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061014/02b05e8b/attachment.htm From kent37 at tds.net Sun Oct 15 03:28:54 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 14 Oct 2006 21:28:54 -0400 Subject: [Tutor] Zipfile and File manipulation questions. In-Reply-To: References: <4530D41E.7070606@pennswoods.net> <453165A1.1090902@tds.net> Message-ID: <45318ED6.5010305@tds.net> Chris Hengge wrote: > Ok, last problem with this whole shebang... > > When I write the file from the zip, if it is in a subfolder, it will > error.. > The code below will detect if the file in contained inside a directory > in the zip, but I just want it to write it like it wasn't. > Another words > > Zipfile.zip looks like this > file.ext > file2.ext > folder/ > anotherfile.ext > > file.ext extracts fine, file2.ext extracts file.. but it see's the last > file as folder/anotherfile.ext and it can't write it.. I tried to figure > out how to use .split to get it working right.. but I'm not having any > luck.. Thanks. > > for afile in zfile.namelist(): # For every file in the zip. > # If the file ends with a needed extension, extract it. > if afile.lower().endswith('.cap') \ > or afile.lower().endswith('.hex') \ > or afile.lower().endswith('.fru') \ > or afile.lower().endswith('.cfg'): > if afile.__contains__("/"): This should be spelled if "/" in afile: __contains__() is the method used by the python runtime to implement 'in', generally you don't call double-underscore methods yourself. I think you want afile = afile.rsplit('/', 1)[-1] that splits afile on the rightmost '/', if any, and keeps the rightmost piece. You don't need the test for '/' in afile, the split will work correctly whether the '/' is present or not. If you are on Windows you should be prepared for paths containing \ as well as /. You can use re.split() to split on either one. Kent > outfile = open(afile, 'w') # Open output buffer for > writing. > outfile.write(zfile.read(afile)) # Write the file. > outfile.close() # Close the output file buffer. > else: > outfile = open(afile, 'w') # Open output buffer for > writing. > outfile.write(zfile.read(afile)) # Write the file. > outfile.close() # Close the output file buffer. From pyro9219 at gmail.com Sun Oct 15 03:34:55 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Sat, 14 Oct 2006 18:34:55 -0700 Subject: [Tutor] Zipfile and File manipulation questions. In-Reply-To: <45318ED6.5010305@tds.net> References: <4530D41E.7070606@pennswoods.net> <453165A1.1090902@tds.net> <45318ED6.5010305@tds.net> Message-ID: I was using afile.split("/"), but I'm not sure how to impliment it... if "/" in afile: (for some reason I can't add 'or "\" in afile' on this line) outfile = open(afile, 'w') # Open output buffer for writing. (to open the file, I can't split here) outfile.write(zfile.read(afile)) # Write the file. ( zfile.read(afile)) wont work if I split here...) outfile.close() # Close the output file buffer. On 10/14/06, Kent Johnson wrote: > > Chris Hengge wrote: > > Ok, last problem with this whole shebang... > > > > When I write the file from the zip, if it is in a subfolder, it will > > error.. > > The code below will detect if the file in contained inside a directory > > in the zip, but I just want it to write it like it wasn't. > > Another words > > > > Zipfile.zip looks like this > > file.ext > > file2.ext > > folder/ > > anotherfile.ext > > > > file.ext extracts fine, file2.ext extracts file.. but it see's the last > > file as folder/anotherfile.ext and it can't write it.. I tried to figure > > out how to use .split to get it working right.. but I'm not having any > > luck.. Thanks. > > > > for afile in zfile.namelist(): # For every file in the zip. > > # If the file ends with a needed extension, extract it. > > if afile.lower().endswith('.cap') \ > > or afile.lower().endswith('.hex') \ > > or afile.lower().endswith('.fru') \ > > or afile.lower().endswith('.cfg'): > > if afile.__contains__("/"): > > This should be spelled > if "/" in afile: > > __contains__() is the method used by the python runtime to implement > 'in', generally you don't call double-underscore methods yourself. > > I think you want > afile = afile.rsplit('/', 1)[-1] > > that splits afile on the rightmost '/', if any, and keeps the rightmost > piece. You don't need the test for '/' in afile, the split will work > correctly whether the '/' is present or not. > > If you are on Windows you should be prepared for paths containing \ as > well as /. You can use re.split() to split on either one. > > Kent > > outfile = open(afile, 'w') # Open output buffer for > > writing. > > outfile.write(zfile.read(afile)) # Write the file. > > outfile.close() # Close the output file buffer. > > else: > > outfile = open(afile, 'w') # Open output buffer for > > writing. > > outfile.write(zfile.read(afile)) # Write the file. > > outfile.close() # Close the output file buffer. > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061014/e198a93e/attachment.html From pyro9219 at gmail.com Sun Oct 15 03:36:13 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Sat, 14 Oct 2006 18:36:13 -0700 Subject: [Tutor] Zipfile and File manipulation questions. In-Reply-To: References: <4530D41E.7070606@pennswoods.net> <453165A1.1090902@tds.net> <45318ED6.5010305@tds.net> Message-ID: Correction... The first comment I just realised I needed "\\" to make it work.. so that issue is gone.. On 10/14/06, Chris Hengge wrote: > > I was using afile.split("/"), but I'm not sure how to impliment it... > > if "/" in afile: (for some reason I can't add 'or "\" in afile' on this > line) > outfile = open(afile, 'w') # Open output buffer for > writing. (to open the file, I can't split here) > outfile.write(zfile.read(afile)) # Write the file. ( > zfile.read(afile)) wont work if I split here...) > outfile.close() # Close the output file buffer. > > On 10/14/06, Kent Johnson wrote: > > > > Chris Hengge wrote: > > > Ok, last problem with this whole shebang... > > > > > > When I write the file from the zip, if it is in a subfolder, it will > > > error.. > > > The code below will detect if the file in contained inside a directory > > > > > in the zip, but I just want it to write it like it wasn't. > > > Another words > > > > > > Zipfile.zip looks like this > > > file.ext > > > file2.ext > > > folder/ > > > anotherfile.ext > > > > > > file.ext extracts fine, file2.ext extracts file.. but it see's the > > last > > > file as folder/anotherfile.ext and it can't write it.. I tried to > > figure > > > out how to use .split to get it working right.. but I'm not having any > > > > > luck.. Thanks. > > > > > > for afile in zfile.namelist(): # For every file in the zip. > > > # If the file ends with a needed extension, extract it. > > > if afile.lower().endswith('.cap') \ > > > or afile.lower().endswith('.hex') \ > > > or afile.lower().endswith('.fru') \ > > > or afile.lower().endswith('.cfg'): > > > if afile.__contains__("/"): > > > > This should be spelled > > if "/" in afile: > > > > __contains__() is the method used by the python runtime to implement > > 'in', generally you don't call double-underscore methods yourself. > > > > I think you want > > afile = afile.rsplit('/', 1)[-1] > > > > that splits afile on the rightmost '/', if any, and keeps the rightmost > > piece. You don't need the test for '/' in afile, the split will work > > correctly whether the '/' is present or not. > > > > If you are on Windows you should be prepared for paths containing \ as > > well as /. You can use re.split() to split on either one. > > > > Kent > > > outfile = open(afile, 'w') # Open output buffer for > > > writing. > > > outfile.write(zfile.read(afile)) # Write the file. > > > outfile.close() # Close the output file buffer. > > > else: > > > outfile = open(afile, 'w') # Open output buffer for > > > writing. > > > outfile.write(zfile.read(afile)) # Write the file. > > > outfile.close() # Close the output file buffer. > > > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061014/793a940c/attachment.htm From pyro9219 at gmail.com Sun Oct 15 06:31:37 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Sat, 14 Oct 2006 21:31:37 -0700 Subject: [Tutor] Zipfile and File manipulation questions. In-Reply-To: References: <4530D41E.7070606@pennswoods.net> <453165A1.1090902@tds.net> <45318ED6.5010305@tds.net> Message-ID: Guess nobody has had a chance to point me in the write direction on this problem yet? Thats ok, I've gotten a ton of other code written, and I'll come back to this tricky part later. This particular project I've been working on to automate some of my job at work has been an excellent learning experience. :D On 10/14/06, Chris Hengge wrote: > > I was using afile.split("/"), but I'm not sure how to impliment it... > > if "/" in afile: (for some reason I can't add 'or "\" in afile' on this > line) > outfile = open(afile, 'w') # Open output buffer for > writing. (to open the file, I can't split here) > outfile.write(zfile.read(afile)) # Write the file. ( > zfile.read(afile)) wont work if I split here...) > outfile.close() # Close the output file buffer. > > On 10/14/06, Kent Johnson wrote: > > > > Chris Hengge wrote: > > > Ok, last problem with this whole shebang... > > > > > > When I write the file from the zip, if it is in a subfolder, it will > > > error.. > > > The code below will detect if the file in contained inside a directory > > > > > in the zip, but I just want it to write it like it wasn't. > > > Another words > > > > > > Zipfile.zip looks like this > > > file.ext > > > file2.ext > > > folder/ > > > anotherfile.ext > > > > > > file.ext extracts fine, file2.ext extracts file.. but it see's the > > last > > > file as folder/anotherfile.ext and it can't write it.. I tried to > > figure > > > out how to use .split to get it working right.. but I'm not having any > > > > > luck.. Thanks. > > > > > > for afile in zfile.namelist(): # For every file in the zip. > > > # If the file ends with a needed extension, extract it. > > > if afile.lower().endswith('.cap') \ > > > or afile.lower().endswith('.hex') \ > > > or afile.lower().endswith('.fru') \ > > > or afile.lower().endswith('.cfg'): > > > if afile.__contains__("/"): > > > > This should be spelled > > if "/" in afile: > > > > __contains__() is the method used by the python runtime to implement > > 'in', generally you don't call double-underscore methods yourself. > > > > I think you want > > afile = afile.rsplit('/', 1)[-1] > > > > that splits afile on the rightmost '/', if any, and keeps the rightmost > > piece. You don't need the test for '/' in afile, the split will work > > correctly whether the '/' is present or not. > > > > If you are on Windows you should be prepared for paths containing \ as > > well as /. You can use re.split() to split on either one. > > > > Kent > > > outfile = open(afile, 'w') # Open output buffer for > > > writing. > > > outfile.write(zfile.read(afile)) # Write the file. > > > outfile.close() # Close the output file buffer. > > > else: > > > outfile = open(afile, 'w') # Open output buffer for > > > writing. > > > outfile.write(zfile.read(afile)) # Write the file. > > > outfile.close() # Close the output file buffer. > > > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061014/57d25f0f/attachment.html From sisson.j at gmail.com Sun Oct 15 01:28:57 2006 From: sisson.j at gmail.com (Jonathon Sisson) Date: Sat, 14 Oct 2006 18:28:57 -0500 Subject: [Tutor] executing with double click on linux In-Reply-To: <452FEA1D.8050608@yahoo.es> References: <452D491A.5000609@yahoo.es> <452D4A9E.7020206@gmail.com> <452FEA1D.8050608@yahoo.es> Message-ID: <453172B9.8090702@gmail.com> I'm afraid I don't have enough experience with Gnome to answer your questions, Alfonso. I will share what I know, though. If you could, run this: $ gnomevfs-info .pyc | grep MIME and see what it says? (If it gives you nothing back, then you need to register a MIME type for .pyc files. http://www.gnome.org/learn/admin-guide/2.14/mimetypes-modifying.html is the official Gnome documentation on how to accomplish that task) You should get a MIME type of "application/x-python-bytecode". If that checks out good, then my suggestion would be to place all of your python code in a good place (/home/user/scripts or the like) then create a desktop shortcut pointing to: "python /home/user/scripts/targetScript.pyc". If my memory serves me well, when you create a desktop shortcut you can tell it what command to run as well as what commandline arguements to pass to the program. Split it up accordingly. I've tested that out in idesk running on fluxbox, so I can't guarantee how well it will work under Gnome, but it's worth a try. Also, if your script doesn't have a GUI, you'll need to point the desktop shortcut to: "xterm -e 'python /home/user/scripts/targetScript.pyc'" (use your favorite terminal, of course...) instead of simply "python /home/user/scripts/targetScript.pyc", or you'll lose the output. (I checked against idesk/fluxbox while monitoring with Conky...my CPU shoots to 100% on a py script that I wrote that builds Markov models from the words in a given dictionary file...(yes, I was quite bored the day I wrote that...), so I know the script is indeed running even without a terminal to output to). If you create the shortcut in that fashion, you *should* be able to run whatever python bytecode you want... Hope this helps, and let me know how that works out for you... Jonathon Alfonso wrote: > Jonathon Sisson escribi?: >> Alfonso wrote: >> >>> Sorry for the too obvious question. I'm new to python and have no idea >>> how can I make execute a compiled .pyc with a double click in linux, >>> with gnome. Trying to double click in a .py gives allways the question >>> wether I want to execute the text file, or read it. (This behaviour can >>> be changed with gconf-editor, but as it is for security matters, I would >>> prefer to execute the .pyc with a double click). I have tried to >>> associate python to the .pyc (first time I executed it there was no >>> programm associated), but it doesn't work. >>> >>> >> I don't know how much Linux experience you have (judging by the >> "double-click" concept, I'm assuming you're coming from a Windows >> background or are perhaps catering to users with only a Windows >> background) (correct me if I'm wrong)...so I'm going to break this down >> as much as I can. >> >> .pyc files are considered binary files by Linux. As such, bash attempts >> to execute them as binary (ELF, etc...), which obviously won't work. If >> you really need to have double-click/execute functionality, consider >> writing a small shell script to execute the .pyc file for you. >> >> For instance, let's say you have a python script "foo.py" and a compiled >> python script "foo.pyc". If you attempt to run foo.py from the shell >> and you have a proper header (i.e. #!/usr/bin/python), then bash can >> execute the script. I'm assuming that GNOME has similar functionality >> (I prefer Fluxbox to either GNOME or KDE), which allows your .py files >> to execute directly. .pyc, however, even with a file association, fails >> to launch...on my system, I get this error: >> >> $ ./foo.pyc >> bash: ./foo.pyc: cannot execute binary file >> >> bash recognizes the file as binary, but it fails to launch as an ELF >> binary (or whatever you're set up to run). To fix it, simply write a >> shell script as such: >> >> >> #!/bin/sh >> >> python /home/me/scripts/foo.pyc >> >> >> >> Name the script whatever you want (i.e. foo.sh) then run from the >> commandline: >> >> $ chmod 700 foo.sh >> >> This gives the script read/write/execute permissions for the owner of >> the script...if you require read/write/execute/etc...for group or all, >> change 700 to whatever you need. (i.e. 755 for rwxr-xr-x permissions) >> >> (Alternatively you can right click on the shell script and set >> permissions graphically...whichever you prefer) Now, you should be able >> to double-click the script (or preferably a shortcut to the script on >> your desktop), which will launch the compiled python module for you. If >> this seems like a lot of work, then perhaps you could write a shell >> script to automate the task of creating the shell script and setting >> permissions each time you create a new .pyc...doh? >> >> Hope this is a satisfactory answer...and if anyone knows something I >> have overlooked, please let Alfonso and I know. >> >> Jonathon >> >> >> >>> Thank you for your answer. >>> >>> >>> ______________________________________________ >>> LLama Gratis a cualquier PC del Mundo. >>> Llamadas a fijos y m?viles desde 1 c?ntimo por minuto. >>> http://es.voice.yahoo.com >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> http://mail.python.org/mailman/listinfo/tutor >>> >>> >> > Thank you very much for your answer. > > Both true, coming from windows, three years with linux. I don't have any > fear to executing from the shell, but It's not the same thing with some > of my friends, totally new to linux, and not very much friends of the > console. I would like to distribute to them my python programms (when I > have the knolowdge to writte something decent with python :) ). > > If I use a bash script I have the same "problem" that with executing > the .py. Gnome asks wether you want to execute or read it, etc. This is > due to security reasons, and can be disabled using the tool > gconf-editor, you can change that behaviour so that the files are > allways executed or opened with a text editor. But I didn't want to > change that, and I thought this could be easily avoided just executing > the .pyc files, because I have programmed with mono (.net) in linux and > that works so. I mean, if I'm not mistaked .pyc are compiled in > intermediate language files, just like .exe in .net/mono. With mono all > I have to do was chmod at the .exe, then changing the programm with > which the .exe is opened (to mono) and that works fine for me, it can be > opened with a double click. But it's not an elf binary, I think... > > I think there must be a way to execute with a launcher the programm > without being asked each time. As it is for example with bittornado or > bittorrent, both written in python and both are executed from the > applications menu or from a launcher at the desktop with no intermediate > question about if you want to show or execute the file, or just to > cancel the action. In fact, when I execute bittornado it's a file called > btdownoladgui.bittornado which is executed. But it's python code. If I > try to do something similar (executing a file with a not .py extension, > but written in python), gnome will complain, that the file is python > script with a different extension, and that as it could be a security > risk it won't be executed. Could it be that those applications, > bittornado, bittorrent, etc., modify some gnome configuration files when > they are installed, to avoid that default behaviour? > > Don't know if I'm explaining right (sorry for my bad english). Resume: > anyone that has programmed a python app and created a launcher, in > gnome, how do you make it so that the file is executed directly after > clicking on it without showing all this anoying messages each time? > > Again, thank you for your answers. > > > > ______________________________________________ > LLama Gratis a cualquier PC del Mundo. > Llamadas a fijos y m?viles desde 1 c?ntimo por minuto. > http://es.voice.yahoo.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From bill at celestial.net Sun Oct 15 07:51:42 2006 From: bill at celestial.net (Bill Campbell) Date: Sat, 14 Oct 2006 22:51:42 -0700 Subject: [Tutor] python equivalent of perl readlink()? Message-ID: <20061015055142.GA17416@ayn.mi.celestial.com> Is there a python equivalent of the perl readlink() function (e.g. one that returns the relative path in cases where a command such as ``ln -s ls /usr/local/bin/gls'' created the link? Reading the documentation on the various os.path functions, the only thing I see returns the fully resolved path rather than the relative one (/usr/local/bin/ls in the case above). Bill -- INTERNET: bill at Celestial.COM Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 ``It's time to feed the hogs'' -- Unintended Consequences From rabidpoobear at gmail.com Sun Oct 15 09:57:21 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sun, 15 Oct 2006 02:57:21 -0500 Subject: [Tutor] Zipfile and File manipulation questions. In-Reply-To: References: <4530D41E.7070606@pennswoods.net> <453165A1.1090902@tds.net> <45318ED6.5010305@tds.net> Message-ID: On 10/14/06, Chris Hengge wrote: > > Guess nobody has had a chance to point me in the write direction on this > problem yet? > > Thats ok, I've gotten a ton of other code written, and I'll come back to > this tricky part later. > > This particular project I've been working on to automate some of my job at > work has been an excellent learning experience. :D > > On 10/14/06, Chris Hengge wrote: > > > > I was using afile.split("/"), but I'm not sure how to impliment it... > > I think kent johnson gave you a solution to this... was it not acceptable? Another alternate route you can take is os.path.split(path)[-1] this will give you the filename no matter what system you're on. it should work for '\\' and '/'. Are you making a script to automatically unzip something? ( I confess, I didn't read the other e-mails before this one.) If you are, and the problem you're having is with writing files to subdirectories, you'd want to do something like this: check if directory you want exists if it does, change into it. if it doesn't, create it and then change into it. recursively do this until you get to where you want to create the file... then create the file you want. in python, this would look like: import os path = 'directory/subdir/filename.txt' #this is the path you use from your zipfile or w/e path = os.path.split(path) #this will make a list ['directory','subdir',' filename.txt'] for item in path[:-1]: #everything but the last item (which is the filename) if item not in os.listdir(): #directory doesn't exist os.mkdir(item)#so we'll create it os.chdir(item)#it doesn't matter to us if the directory exists before, we change into it either way. f = file(path[-1])#create the file you wanted f.write("Hello, this is the file!!!!")#change this to write the file info from out of the zip. f.close()#close file :) #now let's go back to the parent directory so we don't get lost later on :) for x in path[:-1]:#for every directory that we've changed into, os.chdir('..') #go back to parent directory. I don't have a python interp installed on this computer, so there may be errors, and if so, I apologize in advance, but I can't see any reason why this wouldn't work. I just realized os.path doesn't do what I thought it does. It only splits the end. so I guess my solution above would work, but you'd have to split it a different way :) I hope that helps, -Luke -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061015/80f418d5/attachment.html From pyro9219 at gmail.com Sun Oct 15 10:38:04 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Sun, 15 Oct 2006 01:38:04 -0700 Subject: [Tutor] Zipfile and File manipulation questions. In-Reply-To: References: <4530D41E.7070606@pennswoods.net> <453165A1.1090902@tds.net> <45318ED6.5010305@tds.net> Message-ID: I must have not been clear.. I have a zip file with folders inside.. When I extract it.. I dont want the folder structure, just the files.. using split doesn't seem to help in this situation.. unless I'm not putting the results in the right spot.. Thanks again though. On 10/15/06, Luke Paireepinart wrote: > > > > On 10/14/06, Chris Hengge wrote: > > > > Guess nobody has had a chance to point me in the write direction on this > > problem yet? > > > > Thats ok, I've gotten a ton of other code written, and I'll come back to > > this tricky part later. > > > > This particular project I've been working on to automate some of my job > > at work has been an excellent learning experience. :D > > > > On 10/14/06, Chris Hengge < pyro9219 at gmail.com> wrote: > > > > > > I was using afile.split("/"), but I'm not sure how to impliment it... > > > > > I think kent johnson gave you a solution to this... > was it not acceptable? > > Another alternate route you can take is os.path.split(path)[-1] > this will give you the filename no matter what system you're on. > it should work for '\\' and '/'. > > Are you making a script to automatically unzip something? > ( I confess, I didn't read the other e-mails before this one.) > If you are, and the problem you're having is with writing files to > subdirectories, > you'd want to do something like this: > > check if directory you want exists > if it does, change into it. > if it doesn't, create it and then change into it. > recursively do this until you get to where you want to create the file... > then create the file you want. > > in python, this would look like: > > import os > path = 'directory/subdir/filename.txt' #this is the path you use from your > zipfile or w/e > path = os.path.split(path) #this will make a list ['directory','subdir',' > filename.txt'] > > for item in path[:-1]: #everything but the last item (which is the > filename) > if item not in os.listdir(): #directory doesn't exist > os.mkdir(item)#so we'll create it > os.chdir(item)#it doesn't matter to us if the directory exists before, > we change into it either way. > > f = file(path[-1])#create the file you wanted > f.write("Hello, this is the file!!!!")#change this to write the file info > from out of the zip. > f.close()#close file :) > > #now let's go back to the parent directory so we don't get lost later on > :) > for x in path[:-1]:#for every directory that we've changed into, > os.chdir('..') #go back to parent directory. > > > > I don't have a python interp installed on this computer, so there may be > errors, > and if so, I apologize in advance, but I can't see any reason why this > wouldn't work. > > I just realized os.path doesn't do what I thought it does. It only splits > the end. > so I guess my solution above would work, but you'd have to split it a > different way :) > > > I hope that helps, > -Luke > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061015/d080a04c/attachment.htm From bashu at yandex.ru Sun Oct 15 12:19:25 2006 From: bashu at yandex.ru (Basil Shubin) Date: Sun, 15 Oct 2006 17:19:25 +0700 Subject: [Tutor] [OT] Python and Excel/OOCalc Message-ID: <45320B2D.9090703@yandex.ru> Hi, friends! Is there exist python extension or library for writing or exporting data into the Excel and/or OO Calc file? Excuse me for crossposting. Thanks in advance! From bashu at yandex.ru Sun Oct 15 12:23:38 2006 From: bashu at yandex.ru (Basil Shubin) Date: Sun, 15 Oct 2006 17:23:38 +0700 Subject: [Tutor] How to open file in Excel/Calc spreadsheet? Message-ID: <45320C2A.7090700@yandex.ru> Hi ,friends! How I can open Excel or OOCalc spreadsheet file 'remotely' from python programm? I mean how to execute Excel or Calc with appropriate spreadsheet file? Thanks in advance! From kent37 at tds.net Sun Oct 15 13:34:58 2006 From: kent37 at tds.net (Kent Johnson) Date: Sun, 15 Oct 2006 07:34:58 -0400 Subject: [Tutor] Zipfile and File manipulation questions. In-Reply-To: References: <4530D41E.7070606@pennswoods.net> <453165A1.1090902@tds.net> <45318ED6.5010305@tds.net> Message-ID: <45321CE2.9080000@tds.net> Chris Hengge wrote: > I was using afile.split("/"), but I'm not sure how to impliment it... Did you see my hint below? Is there something you don't understand about it? Kent > > if "/" in afile: (for some reason I can't add 'or "\" in afile' on this > line) > outfile = open(afile, 'w') # Open output buffer for > writing. (to open the file, I can't split here) > outfile.write(zfile.read(afile)) # Write the file. > (zfile.read(afile)) wont work if I split here...) > outfile.close() # Close the output file buffer. > > On 10/14/06, *Kent Johnson* > wrote: > > Chris Hengge wrote: > > Ok, last problem with this whole shebang... > > > > When I write the file from the zip, if it is in a subfolder, it will > > error.. > > The code below will detect if the file in contained inside a > directory > > in the zip, but I just want it to write it like it wasn't. > > Another words > > > > Zipfile.zip looks like this > > file.ext > > file2.ext > > folder/ > > anotherfile.ext > > > > file.ext extracts fine, file2.ext extracts file.. but it see's > the last > > file as folder/anotherfile.ext and it can't write it.. I tried to > figure > > out how to use .split to get it working right.. but I'm not > having any > > luck.. Thanks. > > > > for afile in zfile.namelist(): # For every file in the zip. > > # If the file ends with a needed extension, extract it. > > if afile.lower().endswith('.cap') \ > > or afile.lower().endswith('.hex') \ > > or afile.lower().endswith('.fru') \ > > or afile.lower().endswith('.cfg'): > > if afile.__contains__("/"): > > This should be spelled > if "/" in afile: > > __contains__() is the method used by the python runtime to implement > 'in', generally you don't call double-underscore methods yourself. > > I think you want > afile = afile.rsplit('/', 1)[-1] > > that splits afile on the rightmost '/', if any, and keeps the rightmost > piece. You don't need the test for '/' in afile, the split will work > correctly whether the '/' is present or not. > > If you are on Windows you should be prepared for paths containing \ as > well as /. You can use re.split() to split on either one. > > Kent > > outfile = open(afile, 'w') # Open output buffer for > > writing. > > outfile.write(zfile.read(afile)) # Write the file. > > outfile.close() # Close the output file buffer. > > else: > > outfile = open(afile, 'w') # Open output buffer for > > writing. > > outfile.write(zfile.read(afile)) # Write the file. > > outfile.close() # Close the output file buffer. > > > From kent37 at tds.net Sun Oct 15 13:36:20 2006 From: kent37 at tds.net (Kent Johnson) Date: Sun, 15 Oct 2006 07:36:20 -0400 Subject: [Tutor] Zipfile and File manipulation questions. In-Reply-To: References: <4530D41E.7070606@pennswoods.net> <453165A1.1090902@tds.net> <45318ED6.5010305@tds.net> Message-ID: <45321D34.60307@tds.net> Chris Hengge wrote: > I must have not been clear.. I have a zip file with folders inside.. > When I extract it.. I dont want the folder structure, just the files.. > > using split doesn't seem to help in this situation.. unless I'm not > putting the results in the right spot.. Can you show us what you tried? split() can definitely help here. Kent From kent37 at tds.net Sun Oct 15 13:53:53 2006 From: kent37 at tds.net (Kent Johnson) Date: Sun, 15 Oct 2006 07:53:53 -0400 Subject: [Tutor] How to open file in Excel/Calc spreadsheet? In-Reply-To: <45320C2A.7090700@yandex.ru> References: <45320C2A.7090700@yandex.ru> Message-ID: <45322151.3050506@tds.net> Basil Shubin wrote: > Hi ,friends! > > How I can open Excel or OOCalc spreadsheet file 'remotely' from python > programm? I mean how to execute Excel or Calc with appropriate > spreadsheet file? You can use win32com to drive Excel using its COM interface. The sample chapter from the O'Reilly book "Python Programming on Win32" shows how to open a spreadsheet in Excel; http://www.oreilly.com/catalog/pythonwin32/chapter/ch12.html Google 'python excel com' for more examples. Kent From paulino1 at sapo.pt Sun Oct 15 18:09:34 2006 From: paulino1 at sapo.pt (Paulino) Date: Sun, 15 Oct 2006 17:09:34 +0100 Subject: [Tutor] Exception and sys.exit() in a cgi script In-Reply-To: References: Message-ID: <45325D3E.7000605@sapo.pt> This is a peace of a CGI script i have. 1 import cgi 2 form=cgi.FieldStorage() 3 try : 4 ano=form["ano"].value 5 conta=form["conta"].value 6 except KeyError : 7 print '

Please enter values in the fields

' 8 sys.exit(0) When the excption occurs, no message is shown on the browser. If I run the script with IDLE, the message is printed and then the script exits. What's wrong here? From paulino1 at sapo.pt Sun Oct 15 18:44:01 2006 From: paulino1 at sapo.pt (Paulino) Date: Sun, 15 Oct 2006 17:44:01 +0100 Subject: [Tutor] How to open file in Excel/Calc spreadsheet? In-Reply-To: <45208761.1010207@gmail.com> References: <4520533C.9090500@sapo.pt> <45208761.1010207@gmail.com> Message-ID: <45326551.1050101@sapo.pt> Very simple: os.startfile([file]) ex: >>> import os >>> os.startfile("d:\\documentos\\eleicoes2005-dn.xls") It works with any file tipe in windows, the file is opened with it's associated application. Basil Shubin wrote: >/ Hi ,friends! />/ />/ How I can open Excel or OOCalc spreadsheet file 'remotely' from python />/ programm? I mean how to execute Excel or Calc with appropriate />/ spreadsheet file?/ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061015/a013fe0d/attachment.html From alan.gauld at btinternet.com Sun Oct 15 19:27:51 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 15 Oct 2006 18:27:51 +0100 Subject: [Tutor] Exception and sys.exit() in a cgi script References: <45325D3E.7000605@sapo.pt> Message-ID: Hi Paulino, > This is a peace of a CGI script i have. > > 1 import cgi > 2 form=cgi.FieldStorage() > 3 try : > 4 ano=form["ano"].value > 5 conta=form["conta"].value > 6 except KeyError : > 7 print '

Please enter values in the > fields

' > 8 sys.exit(0) > > > When the excption occurs, no message is shown on the browser. Can you tell us a bit more about the set up? What OS? What web server? Can you get any other python CGI scripts running correctly? > If I run the script with IDLE, the message is printed and then the > script exits. The IDE environment is very different to a web server environment. You should only treat IDLE as a first approximation when developing Web scripts. You can use the OS prompt for a slightly better approximation provided you set some environment variables first, but ultimately you need to test on the web server you will be using. Alan G. From paulino1 at sapo.pt Sun Oct 15 19:44:09 2006 From: paulino1 at sapo.pt (Paulino) Date: Sun, 15 Oct 2006 18:44:09 +0100 Subject: [Tutor] Exception and sys.exit() in a cgi script In-Reply-To: <45325D3E.7000605@sapo.pt> References: <45325D3E.7000605@sapo.pt> Message-ID: <45327369.7080209@sapo.pt> Thank you, Yes I have other scripts working fine. The OS is WXP and the server is the python's CGIHTTPserver (for an intranet use only) --------- Hi Paulino, >/ This is a peace of a CGI script i have. />/ />/ 1 import cgi />/ 2 form=cgi.FieldStorage() />/ 3 try : />/ 4 ano=form["ano"].value />/ 5 conta=form["conta"].value />/ 6 except KeyError : />/ 7 print '

Please enter values in the />/ fields

' />/ 8 sys.exit(0) />/ />/ />/ When the excption occurs, no message is shown on the browser. / Can you tell us a bit more about the set up? What OS? What web server? Can you get any other python CGI scripts running correctly? >/ If I run the script with IDLE, the message is printed and then the />/ script exits. / The IDE environment is very different to a web server environment. You should only treat IDLE as a first approximation when developing Web scripts. You can use the OS prompt for a slightly better approximation provided you set some environment variables first, but ultimately you need to test on the web server you will be using. Alan G. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061015/c8196e68/attachment.htm From paulino1 at sapo.pt Sun Oct 15 19:55:38 2006 From: paulino1 at sapo.pt (Paulino) Date: Sun, 15 Oct 2006 18:55:38 +0100 Subject: [Tutor] CGIHTTPServer - redirect output to a log file Message-ID: <4532761A.1070802@sapo.pt> How can I redirect the output of an CGIHTTPServer from the console to a logfile? From wescpy at gmail.com Sun Oct 15 20:04:19 2006 From: wescpy at gmail.com (wesley chun) Date: Sun, 15 Oct 2006 11:04:19 -0700 Subject: [Tutor] How to open file in Excel/Calc spreadsheet? In-Reply-To: <45320C2A.7090700@yandex.ru> References: <45320C2A.7090700@yandex.ru> Message-ID: <78b3a9580610151104p41c071bdlbec2adab77ea7366@mail.gmail.com> > How I can open Excel or OOCalc spreadsheet file 'remotely' from python > programm? I mean how to execute Excel or Calc with appropriate > spreadsheet file? there was a similar question on the main newsgroup a few days ago, slightly related to this post, but the answers will be helpful here. http://groups.google.com/group/comp.lang.python/browse_thread/thread/a7ed60067ca5a8d4/# if you're interested, i added a section (in chapter 23) to my book, Core Python Programming, on programming Microsoft Office applications, with examples for Word, Excel, PowerPoint, and Outlook. good luck! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From gtnorton at earthlink.net Sun Oct 15 20:23:32 2006 From: gtnorton at earthlink.net (Glenn T Norton) Date: Sun, 15 Oct 2006 13:23:32 -0500 Subject: [Tutor] CGIHTTPServer - redirect output to a log file In-Reply-To: <4532761A.1070802@sapo.pt> References: <4532761A.1070802@sapo.pt> Message-ID: <45327CA4.8050801@earthlink.net> Paulino wrote: >How can I redirect the output of an CGIHTTPServer from the console to a >logfile? >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > > You can start it from a shell script #!/bin/sh ./MyWebServer.py 2>>/path/to/output.log Good Luck, Glenn -- "Ketchup. For the good times... " - Ketchup Advisory Board Glenn Norton Application Developer Nebraska.gov 1-402-471-2777 glenn at nebraska.gov From paulino1 at sapo.pt Sun Oct 15 21:15:50 2006 From: paulino1 at sapo.pt (Paulino) Date: Sun, 15 Oct 2006 20:15:50 +0100 Subject: [Tutor] CGIHTTPServer - redirect output to a log file In-Reply-To: <45327CA4.8050801@earthlink.net> References: <4532761A.1070802@sapo.pt> <45327CA4.8050801@earthlink.net> Message-ID: <453288E6.7000509@sapo.pt> well, I'm running this CGIserver on windows... Glenn T Norton escreveu: > Paulino wrote: > >> How can I redirect the output of an CGIHTTPServer from the console to >> a logfile? >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> >> > You can start it from a shell script > #!/bin/sh > ./MyWebServer.py 2>>/path/to/output.log > > Good Luck, > Glenn > From alan.gauld at btinternet.com Mon Oct 16 00:18:18 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 15 Oct 2006 23:18:18 +0100 Subject: [Tutor] CGIHTTPServer - redirect output to a log file References: <4532761A.1070802@sapo.pt> <45327CA4.8050801@earthlink.net> <453288E6.7000509@sapo.pt> Message-ID: >> You can start it from a shell script >> #!/bin/sh >> ./MyWebServer.py 2>>/path/to/output.log >> "Paulino" wrote in message news:453288E6.7000509 at sapo.pt... > well, I'm running this CGIserver on windows... You can still use redirection although its not as powerful as unix. Just try C:\PATH> python \path\mywebserver.py > logfile.txt You can get full details by entering the search string "output redirection" at the XP Help screen and viewing the "Using command redirection operators" topic. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From euoar at yahoo.es Mon Oct 16 01:06:05 2006 From: euoar at yahoo.es (Alfonso) Date: Mon, 16 Oct 2006 01:06:05 +0200 Subject: [Tutor] executing with double click on linux Message-ID: <4532BEDD.3020602@yahoo.es> Thank you for your answer, Jonathon. I have found that the problem ocurs only with programs that make use of glade files for the interface. With pure pygtk programs without using glade files, making a launcher with a simple double click works perfectly. But if the program builds his interface basing in a glade file, that doesn't work. The mime type is ok, and I have tried your proposal, but it doesn't work with those programs. I'll keep trying to find the reason. I'll tell you if I find it. I have wroten to gnome-devel about this, and they have recommended me to have a look at the source from "orca", a gnome application that makes use of glade files, so I'll have a look at it... ______________________________________________ LLama Gratis a cualquier PC del Mundo. Llamadas a fijos y m?viles desde 1 c?ntimo por minuto. http://es.voice.yahoo.com From euoar at yahoo.es Mon Oct 16 01:16:19 2006 From: euoar at yahoo.es (Alfonso) Date: Mon, 16 Oct 2006 01:16:19 +0200 Subject: [Tutor] an alternative to shutil.move()? Message-ID: <4532C143.7070208@yahoo.es> Is there an alternative in python to use shutil.move()? It copies the files and then removes the source file insted of just moving directly the file (don't know much about file systems, but I suppose that when you move using the shell, if both source and destination are in the same partition, it's just a matter of changing the entries in the file allocation table). Copying the entire file, specially with big files is very slow, and I think that it makes an unnecesary use of the hard drive and system resources, when both source file and destination are on the same partition... ______________________________________________ LLama Gratis a cualquier PC del Mundo. Llamadas a fijos y m?viles desde 1 c?ntimo por minuto. http://es.voice.yahoo.com From pyro9219 at gmail.com Mon Oct 16 02:30:56 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Sun, 15 Oct 2006 17:30:56 -0700 Subject: [Tutor] Zipfile and File manipulation questions. In-Reply-To: <45321D34.60307@tds.net> References: <453165A1.1090902@tds.net> <45318ED6.5010305@tds.net> <45321D34.60307@tds.net> Message-ID: After getting some sleep and looking at my code, I think I was just to tired to work through that problem =P Here is my fully working and tested code.. Thanks to you all for your assistance! if "/" in afile: aZipFile = afile.rsplit('/', 1)[-1] # Split file based on criteria. outfile = open(aZipFile, 'w') # Open output buffer for writing. outfile.write(zfile.read(afile)) # Write the file. outfile.close() # Close the output file buffer. elif "\\" in afile: aZipFile = afile.rsplit('\\', 1)[-1] # Split file based on criteria. outfile = open(aZipFile, 'w') # Open output buffer for writing. outfile.write(zfile.read(afile)) # Write the file. outfile.close() # Close the output file buffer. else: outfile = open(afile, 'w') # Open output buffer for writing. outfile.write(zfile.read(afile)) # Write the file. outfile.close() # Close the output file buffer. On 10/15/06, Kent Johnson wrote: > > Chris Hengge wrote: > > I must have not been clear.. I have a zip file with folders inside.. > > When I extract it.. I dont want the folder structure, just the files.. > > > > using split doesn't seem to help in this situation.. unless I'm not > > putting the results in the right spot.. > > Can you show us what you tried? split() can definitely help here. > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061015/9ac0e0fa/attachment.html From chris.lasher at gmail.com Mon Oct 16 02:44:11 2006 From: chris.lasher at gmail.com (Chris Lasher) Date: Sun, 15 Oct 2006 20:44:11 -0400 Subject: [Tutor] Equivalent to perl -e Message-ID: <128a885f0610151744n34527af5l51bd3e227940422c@mail.gmail.com> My professor and advisor has been "inspired" by me to give Python a try. He's an avid Perl user, and challenged me with the following: What is the Python equivalent to perl -e ''? Embarassingly, I had no answer, but I figure, someone on the list will know. His use of Python is at stake; he threatened that, since he's dependant enough on using perl -e within Emacs enough, if it can't be done in Python, he won't take the language seriously. Help me, Python Tutor, you're his only hope! Thanks in advance, Chris From kent37 at tds.net Mon Oct 16 03:31:11 2006 From: kent37 at tds.net (Kent Johnson) Date: Sun, 15 Oct 2006 21:31:11 -0400 Subject: [Tutor] Equivalent to perl -e In-Reply-To: <128a885f0610151744n34527af5l51bd3e227940422c@mail.gmail.com> References: <128a885f0610151744n34527af5l51bd3e227940422c@mail.gmail.com> Message-ID: <4532E0DF.1040404@tds.net> Chris Lasher wrote: > My professor and advisor has been "inspired" by me to give Python a > try. He's an avid Perl user, and challenged me with the following: > > What is the Python equivalent to perl -e ''? python -c More details here: http://linuxcommand.org/man_pages/python1.html Kent From gtnorton at earthlink.net Mon Oct 16 03:32:47 2006 From: gtnorton at earthlink.net (Glenn T Norton) Date: Sun, 15 Oct 2006 20:32:47 -0500 Subject: [Tutor] Equivalent to perl -e In-Reply-To: <128a885f0610151744n34527af5l51bd3e227940422c@mail.gmail.com> References: <128a885f0610151744n34527af5l51bd3e227940422c@mail.gmail.com> Message-ID: <4532E13F.3060402@earthlink.net> Chris Lasher wrote: >My professor and advisor has been "inspired" by me to give Python a >try. He's an avid Perl user, and challenged me with the following: > >What is the Python equivalent to perl -e ''? > >Embarassingly, I had no answer, but I figure, someone on the list will >know. His use of Python is at stake; he threatened that, since he's >dependant enough on using perl -e within Emacs enough, if it can't be >done in Python, he won't take the language seriously. Help me, Python >Tutor, you're his only hope! > >Thanks in advance, >Chris >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > > How about... python -c "for x in 'Tell them to jump on board and take the blue pill': print x" Glenn -- "Ketchup. For the good times... " - Ketchup Advisory Board Glenn Norton Application Developer Nebraska.gov 1-402-471-2777 glenn at nebraska.gov From arcege at gmail.com Mon Oct 16 03:39:02 2006 From: arcege at gmail.com (Michael P. Reilly) Date: Sun, 15 Oct 2006 21:39:02 -0400 Subject: [Tutor] python equivalent of perl readlink()? In-Reply-To: <20061015055142.GA17416@ayn.mi.celestial.com> References: <20061015055142.GA17416@ayn.mi.celestial.com> Message-ID: <7e5ba9220610151839u3d978826n3cad4ae93fbaecc7@mail.gmail.com> On 10/15/06, Bill Campbell wrote: > > Is there a python equivalent of the perl readlink() function > (e.g. one that returns the relative path in cases where a command > such as ``ln -s ls /usr/local/bin/gls'' created the link? > > Reading the documentation on the various os.path functions, the > only thing I see returns the fully resolved path rather than the > relative one (/usr/local/bin/ls in the case above). > > Bill > The function is in the os module ( http://docs.python.org/lib/os-file-dir.html). -Arcege -- There's so many different worlds, So many different suns. And we have just one world, But we live in different ones. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061015/3c77f5fc/attachment-0001.htm From chris.lasher at gmail.com Mon Oct 16 04:07:25 2006 From: chris.lasher at gmail.com (Chris Lasher) Date: Sun, 15 Oct 2006 22:07:25 -0400 Subject: [Tutor] Equivalent to perl -e In-Reply-To: <4532E13F.3060402@earthlink.net> References: <128a885f0610151744n34527af5l51bd3e227940422c@mail.gmail.com> <4532E13F.3060402@earthlink.net> Message-ID: <128a885f0610151907h220934dbncb96e6ff52f16c67@mail.gmail.com> Haha! I'll relay that message! Thanks Kent and Glenn! Chris On 10/15/06, Glenn T Norton wrote: > Chris Lasher wrote: > > >My professor and advisor has been "inspired" by me to give Python a > >try. He's an avid Perl user, and challenged me with the following: > > > >What is the Python equivalent to perl -e ''? > > > >Embarassingly, I had no answer, but I figure, someone on the list will > >know. His use of Python is at stake; he threatened that, since he's > >dependant enough on using perl -e within Emacs enough, if it can't be > >done in Python, he won't take the language seriously. Help me, Python > >Tutor, you're his only hope! > > > >Thanks in advance, > >Chris > >_______________________________________________ > >Tutor maillist - Tutor at python.org > >http://mail.python.org/mailman/listinfo/tutor > > > > > > > How about... > python -c "for x in 'Tell them to jump on board and take the blue pill': > print x" > > Glenn > > -- > "Ketchup. For the good times... " - Ketchup Advisory Board > Glenn Norton > Application Developer > Nebraska.gov > 1-402-471-2777 > glenn at nebraska.gov > > From billburns at pennswoods.net Mon Oct 16 04:30:51 2006 From: billburns at pennswoods.net (Bill Burns) Date: Sun, 15 Oct 2006 22:30:51 -0400 Subject: [Tutor] Zipfile and File manipulation questions. In-Reply-To: References: <453165A1.1090902@tds.net> <45318ED6.5010305@tds.net> <45321D34.60307@tds.net> Message-ID: <4532EEDB.9000509@pennswoods.net> Chris Hengge wrote: > After getting some sleep and looking at my code, I think I was just to > tired to work through that problem =P > > Here is my fully working and tested code.. > Thanks to you all for your assistance! > > if "/" in afile: > aZipFile = afile.rsplit('/', 1)[-1] # Split file based on criteria. > outfile = open(aZipFile, 'w') # Open output buffer for writing. > outfile.write(zfile.read(afile)) # Write the file. > outfile.close () # Close the output file buffer. > elif "\\" in afile: > aZipFile = afile.rsplit('\\', 1)[-1] # Split file based on criteria. > outfile = open(aZipFile, 'w') # Open output buffer for writing. > outfile.write(zfile.read(afile)) # Write the file. > outfile.close() # Close the output file buffer. > else: > outfile = open(afile, 'w') # Open output buffer for writing. > outfile.write(zfile.read(afile)) # Write the file. > outfile.close() # Close the output file buffer. Somewhere along the way, I got lost ;-) Why are you messing with the slashes ("/" & "\\")? If you're trying to split a path and filename, then your best bet is 'os.path.split()'. For Example: >>> import os >>> s = '/some/path/to/file.txt' >>> path, filename = os.path.split(s) >>> path '/some/path/to' >>> filename 'file.txt' 'os.path.split()' works equally as well for paths containing "\\". I have some code below which I *think* does what you want..... read a zip file and 'write out' only those files with a certain file extension. The directory structure is *not* preserved (it just writes all files to the current working directory). It has a little helper function 'myFileTest()' which I think makes things easier ;-) The function tests a file to see if meets our extension criteria. HTH, Bill import zipfile import os # This is what I did for testing. Change it to point # to your zip file... zip = zipfile.ZipFile('test.zip', 'r') def myFileTest(aFile): """myFileTest(aFile) -> returns True if input file endswith one of the extensions specified below. """ for ext in ['.cap', '.hex', '.fru', '.cfg']: if aFile.lower().endswith(ext): return True for aFile in zip.namelist(): # See if the file meets our criteria. if myFileTest(aFile): # Split the path and filename. path, filename = os.path.split(aFile) # Don't overwrite an existing file. if not os.path.exists(filename): # Write out the file. outfile = open(filename, 'w') outfile.write(zip.read(aFile)) outfile.close() From tim.peters at gmail.com Mon Oct 16 04:40:30 2006 From: tim.peters at gmail.com (Tim Peters) Date: Sun, 15 Oct 2006 22:40:30 -0400 Subject: [Tutor] Equivalent to perl -e In-Reply-To: <128a885f0610151744n34527af5l51bd3e227940422c@mail.gmail.com> References: <128a885f0610151744n34527af5l51bd3e227940422c@mail.gmail.com> Message-ID: <1f7befae0610151940y4bda39d6k9175b889efeaa16a@mail.gmail.com> [Chris Lasher] > My professor and advisor has been "inspired" by me to give Python a > try. He's an avid Perl user, and challenged me with the following: > > What is the Python equivalent to perl -e ''? The initally attractive but unsatisfying answer is: python -c '' The reason it's "unsatisfying" is that Python isn't concerned with making: pleasant, or even sanely possible, for many tasks. Perl excels at one-liners; Python doesn't much care about them. > Embarassingly, I had no answer, but I figure, someone on the list will > know. His use of Python is at stake; he threatened that, since he's > dependant enough on using perl -e within Emacs enough, if it can't be > done in Python, he won't take the language seriously. Help me, Python > Tutor, you're his only hope! Like many Python (very) old-timers, I used Perl heavily at the time Python came out. As was also true for many of them, as time went on the size of a new program I was willing to write in Perl instead of in Python got smaller and smaller, eventually reaching "almost 0". I still use Perl some 15 years later, but now /only/ for "perl -e"-style 1-liners at an interactive shell. If it takes more than a line, I stick it in a module (and maybe a class) for reuse later. Python's strengths are more in readability, helpful uniformity, easy use of classes and rich data structures, and maintainability. Cryptic one-liners are in general (but not always) opposed to all of those. So, ya, "python -c" exists, but your professor won't be happy with it. That's fine! If one-liners are all he cares about, Perl is usually the best tool for the job. From pyro9219 at gmail.com Mon Oct 16 05:33:05 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Sun, 15 Oct 2006 20:33:05 -0700 Subject: [Tutor] Zipfile and File manipulation questions. In-Reply-To: <4532EEDB.9000509@pennswoods.net> References: <45318ED6.5010305@tds.net> <45321D34.60307@tds.net> <4532EEDB.9000509@pennswoods.net> Message-ID: The code in my last email that I stated worked, is doing exactly what I want (perhaps there is a better method, but this is working) The slash detection is for the subdirectories located inside of a zip file. The name list for a file located inside a zipped folder shows up as folder/file.ext in windows, and folder\file.ext in linux.. so I was accounting for both. I dont think your method os.path.split() would work since there isn't a fully qualified path coming from the namelist. I like this little snip of code from your suggestion, and I may incorporate it... for ext in ['.cap', '.hex', '.fru', '.cfg']: if aFile.lower().endswith(ext): return True Just for sake of sharing.. here is my entire method.. def extractZip(filePathName): """ This method recieves the zip file name for decompression, placing the contents of the zip file appropriately. """ if filePathName == "": print "No file provided...\n" else: if filePathName[0] == '"': # If the path includes quotes, remove them. zfile = zipfile.ZipFile(filePathName[1:-1], "r") else: # If the path doesn't include quotes, dont change. zfile = zipfile.ZipFile(filePathName, "r") for afile in zfile.namelist(): # For every file in the zip. # If the file ends with a needed extension, extract it. if afile.lower().endswith('.cap') \ or afile.lower().endswith('.hex') \ or afile.lower().endswith('.fru') \ or afile.lower().endswith('.sdr') \ or afile.lower().endswith('.cfg'): if "/" in afile: aZipFile = afile.rsplit('/', 1)[-1] # Split file based on criteria. outfile = open(aZipFile, 'w') # Open output buffer for writing. outfile.write(zfile.read(afile)) # Write the file. outfile.close() # Close the output file buffer. elif "\\" in afile: aZipFile = afile.rsplit('\\', 1)[-1] # Split file based on criteria. outfile = open(aZipFile, 'w') # Open output buffer for writing. outfile.write(zfile.read(afile)) # Write the file. outfile.close() # Close the output file buffer. else: outfile = open(afile, 'w') # Open output buffer for writing. outfile.write(zfile.read(afile)) # Write the file. outfile.close() # Close the output file buffer. print "Resource extraction completed successfully!\n" Not to go on and bore people with my project, the goal of this application (which is nearly done) is to take several zip files that I've prompted the user to drag and drop into the console, extract the necessary peices, add a few more files, change some lines within a couple of the files extracted, then pack it all back into one single zip... At this point, my little script is doing everything other then the file i/o for changing the lines inside the couple files needed (which I'll probably have done tomorrow if I have time at work). The script does a little more then that, like sets up a file structure and some menu's for the user, but essentially I've explained it... and it takes about a 20-45minute job and chops it into less then 30 seconds.. And considering I run through this process sometimes dozens of times a day, that time adds up fast.. Hopefully I can work on getting better at coding python with my newly earned time =D The flow of the script is a little odd because I had to make it extensible by basically copying a method for a specific package I'm trying to build and modifying to suite.. but.. once I'm fully done, this script should let me add an entire new type of zip package within minutes. Again, thanks to all of you for your input and suggestions. On 10/15/06, Bill Burns wrote: > > Chris Hengge wrote: > > After getting some sleep and looking at my code, I think I was just to > > tired to work through that problem =P > > > > Here is my fully working and tested code.. > > Thanks to you all for your assistance! > > > > if "/" in afile: > > aZipFile = afile.rsplit('/', 1)[-1] # Split file based on criteria. > > outfile = open(aZipFile, 'w') # Open output buffer for writing. > > outfile.write(zfile.read(afile)) # Write the file. > > outfile.close () # Close the output file buffer. > > elif "\\" in afile: > > aZipFile = afile.rsplit('\\', 1)[-1] # Split file based on criteria. > > outfile = open(aZipFile, 'w') # Open output buffer for writing. > > outfile.write(zfile.read(afile)) # Write the file. > > outfile.close() # Close the output file buffer. > > else: > > outfile = open(afile, 'w') # Open output buffer for writing. > > outfile.write(zfile.read(afile)) # Write the file. > > outfile.close() # Close the output file buffer. > > Somewhere along the way, I got lost ;-) Why are you messing with the > slashes ("/" & "\\")? > > If you're trying to split a path and filename, then your best bet is > 'os.path.split()'. > > For Example: > > >>> import os > >>> s = '/some/path/to/file.txt' > >>> path, filename = os.path.split(s) > >>> path > '/some/path/to' > >>> filename > 'file.txt' > > 'os.path.split()' works equally as well for paths containing "\\". > > I have some code below which I *think* does what you want..... read a > zip file and 'write out' only those files with a certain file extension. > The directory structure is *not* preserved (it just writes all files to > the current working directory). > > It has a little helper function 'myFileTest()' which I think makes > things easier ;-) The function tests a file to see if meets our > extension criteria. > > HTH, > > Bill > > > import zipfile > import os > > # This is what I did for testing. Change it to point > # to your zip file... > zip = zipfile.ZipFile('test.zip', 'r') > > def myFileTest(aFile): > """myFileTest(aFile) -> returns True if input file > endswith one of the extensions specified below. > """ > for ext in ['.cap', '.hex', '.fru', '.cfg']: > if aFile.lower().endswith(ext): > return True > > for aFile in zip.namelist(): > # See if the file meets our criteria. > if myFileTest(aFile): > # Split the path and filename. > path, filename = os.path.split(aFile) > # Don't overwrite an existing file. > if not os.path.exists(filename): > # Write out the file. > outfile = open(filename, 'w') > outfile.write(zip.read(aFile)) > outfile.close() > > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061015/39836c5d/attachment-0001.html From anilmrn at yahoo.com Mon Oct 16 05:47:34 2006 From: anilmrn at yahoo.com (anil maran) Date: Sun, 15 Oct 2006 20:47:34 -0700 (PDT) Subject: [Tutor] Help with sessions Message-ID: <20061016034734.7954.qmail@web55203.mail.re4.yahoo.com> I tried creating sessions for each app and then did htis code def session_mw(app): sessionStore = DiskSessionStore(storeDir="%s/sessions/" % os.getcwd(), timeout=5) sessionStore= sessionStore.createSession() return SessionMiddleware(sessionStore, app) def initsession(session): session['id'] = 0 session['username'] = '' session['groups'] = '' session['loggedin'] = 0 in 2 diff webapps, I run them in 2 different ports 9109 and 9911 But the problem is both are now sharing the same session how do i ensure that they dont share browser session and create a new one from themselves Anil -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061015/e74d785f/attachment.html From chris.lasher at gmail.com Mon Oct 16 06:01:33 2006 From: chris.lasher at gmail.com (Chris Lasher) Date: Mon, 16 Oct 2006 00:01:33 -0400 Subject: [Tutor] Equivalent to perl -e In-Reply-To: <1f7befae0610151940y4bda39d6k9175b889efeaa16a@mail.gmail.com> References: <128a885f0610151744n34527af5l51bd3e227940422c@mail.gmail.com> <1f7befae0610151940y4bda39d6k9175b889efeaa16a@mail.gmail.com> Message-ID: <128a885f0610152101w7ea4bd7dq23afb72a3cc14151@mail.gmail.com> Points well taken. In fact, the example he demonstrated to me as a one-liner was a regular expression as a line filter in Emacs--essentially just a grep. There's no Pythonic equivalent to this. Right tool for the right job, as you said. He was half-joking about not learning Python if it lacked the option to execute snippets. His lab maintains a significant amount of Perl code; he was intrigued by my zealous enthusiasm for Python and my assertion that, personally, I experienced greater long-term readability with my scripts written in Python over those written in Perl. I think once he begins to experience Python he will come to understand why it's not suited for one-liners, and why that's a Good Thing. Excellent reply! Chris On 10/15/06, Tim Peters wrote: > [Chris Lasher] > > My professor and advisor has been "inspired" by me to give Python a > > try. He's an avid Perl user, and challenged me with the following: > > > > What is the Python equivalent to perl -e ''? > > The initally attractive but unsatisfying answer is: > > python -c '' > > The reason it's "unsatisfying" is that Python isn't concerned with making: > > > > pleasant, or even sanely possible, for many tasks. Perl excels at > one-liners; Python doesn't much care about them. > > > Embarassingly, I had no answer, but I figure, someone on the list will > > know. His use of Python is at stake; he threatened that, since he's > > dependant enough on using perl -e within Emacs enough, if it can't be > > done in Python, he won't take the language seriously. Help me, Python > > Tutor, you're his only hope! > > Like many Python (very) old-timers, I used Perl heavily at the time > Python came out. As was also true for many of them, as time went on > the size of a new program I was willing to write in Perl instead of in > Python got smaller and smaller, eventually reaching "almost 0". I > still use Perl some 15 years later, but now /only/ for "perl -e"-style > 1-liners at an interactive shell. If it takes more than a line, I > stick it in a module (and maybe a class) for reuse later. > > Python's strengths are more in readability, helpful uniformity, easy > use of classes and rich data structures, and maintainability. Cryptic > one-liners are in general (but not always) opposed to all of those. > > So, ya, "python -c" exists, but your professor won't be happy with it. > That's fine! If one-liners are all he cares about, Perl is usually > the best tool for the job. > From bill at celestial.net Mon Oct 16 07:06:47 2006 From: bill at celestial.net (Bill Campbell) Date: Sun, 15 Oct 2006 22:06:47 -0700 Subject: [Tutor] python equivalent of perl readlink()? In-Reply-To: <7e5ba9220610151839u3d978826n3cad4ae93fbaecc7@mail.gmail.com> References: <20061015055142.GA17416@ayn.mi.celestial.com> <7e5ba9220610151839u3d978826n3cad4ae93fbaecc7@mail.gmail.com> Message-ID: <20061016050647.GB5249@ayn.mi.celestial.com> On Sun, Oct 15, 2006, Michael P. Reilly wrote: > > On 10/15/06, Bill Campbell <[1]bill at celestial.net> wrote: > > Is there a python equivalent of the perl readlink() function > (e.g. one that returns the relative path in cases where a command > such as ``ln -s ls /usr/local/bin/gls'' created the link? > Reading the documentation on the various os.path functions, the > only thing I see returns the fully resolved path rather than the > relative one (/usr/local/bin/ls in the case above). > Bill > > The function is in the os module ([2] > http://docs.python.org/lib/os-file-dir.html). Silly me. I was looking in the os.path module :-). Thanks. Bill -- INTERNET: bill at Celestial.COM Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 ``Unix is simple. It just takes a genius to understand its simplicity'' -- Dennis Ritchie From euoar at yahoo.es Mon Oct 16 08:22:35 2006 From: euoar at yahoo.es (Alfonso) Date: Mon, 16 Oct 2006 08:22:35 +0200 Subject: [Tutor] an alternative to shutil.move()? In-Reply-To: <128a885f0610151718g289610a4o4478c3c151f4e88c@mail.gmail.com> References: <4532C143.7070208@yahoo.es> <128a885f0610151718g289610a4o4478c3c151f4e88c@mail.gmail.com> Message-ID: <4533252B.1040108@yahoo.es> Chris Lasher escribi?: > How about os.rename > > http://docs.python.org/lib/os-file-dir.html > > On 10/15/06, Alfonso wrote: >> Is there an alternative in python to use shutil.move()? > That's exactly what I was looking for. Thank you very much. Don't know how I didn't find it before. I suppose that I was thinking that the name of the module would be other... ______________________________________________ LLama Gratis a cualquier PC del Mundo. Llamadas a fijos y m?viles desde 1 c?ntimo por minuto. http://es.voice.yahoo.com From wescpy at gmail.com Mon Oct 16 08:51:21 2006 From: wescpy at gmail.com (wesley chun) Date: Sun, 15 Oct 2006 23:51:21 -0700 Subject: [Tutor] Equivalent to perl -e In-Reply-To: <128a885f0610152101w7ea4bd7dq23afb72a3cc14151@mail.gmail.com> References: <128a885f0610151744n34527af5l51bd3e227940422c@mail.gmail.com> <1f7befae0610151940y4bda39d6k9175b889efeaa16a@mail.gmail.com> <128a885f0610152101w7ea4bd7dq23afb72a3cc14151@mail.gmail.com> Message-ID: <78b3a9580610152351j47e24f81td40b83500152d9a7@mail.gmail.com> > His lab maintains a significant amount of Perl code this sounds like a full-time job on its own. everyone brings up a good point... use the right tool for the job. if it's one-liners, that's what perl -e is made for. for everything else that you mentioned above, Python is the the one, preferably the only one --obvious way to do it. :-) one perl'y thing that i *do* use is perl -c, for checking your syntax. i don't believe there's an equivalent way to do that from the Python cmd-line (correct me if i'm wrong!), but i wrote up a short script I called (pydashc.py) which just uses compile() to get the same effect... very useful for when i don't want to *run* something to see if i made any typos. regards, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From alan.gauld at btinternet.com Mon Oct 16 10:33:09 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 16 Oct 2006 09:33:09 +0100 Subject: [Tutor] python equivalent of perl readlink()? References: <20061015055142.GA17416@ayn.mi.celestial.com><7e5ba9220610151839u3d978826n3cad4ae93fbaecc7@mail.gmail.com> <20061016050647.GB5249@ayn.mi.celestial.com> Message-ID: "Bill Campbell" wrote in message >> The function is in the os module ([2] >> http://docs.python.org/lib/os-file-dir.html). > > Silly me. I was looking in the os.path module :-). Yes, its confusing/. One thing that should be rationalised IMHO is the various os modules.There are os, os.path, shutil, and now subprocess too. Alll doing things vaguely related to os type things. A re-org to make them more consistent would be good, but unfortunately would probably break lots of code! Alan G. From kent37 at tds.net Mon Oct 16 12:07:37 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 16 Oct 2006 06:07:37 -0400 Subject: [Tutor] Zipfile and File manipulation questions. In-Reply-To: References: <45318ED6.5010305@tds.net> <45321D34.60307@tds.net> <4532EEDB.9000509@pennswoods.net> Message-ID: <453359E9.7020708@tds.net> Chris Hengge wrote: > I like this little snip of code from your suggestion, and I may > incorporate it... > > for ext in ['.cap', '.hex', '.fru', '.cfg']: > if aFile.lower().endswith(ext): > return True > > Just for sake of sharing.. here is my entire method.. Hopefully for the sake of feedback also... You have a lot of duplicated code that is pretty easy to remove, and a few places where there are easier ways to do it. In general duplicated code is a bad thing - it makes your program larger and harder maintain. Copy and paste is the enemy of readable, maintainable code. > > def extractZip(filePathName): > """ > This method recieves the zip file name for decompression, placing the > contents of the zip file appropriately. > """ > if filePathName == "": > print "No file provided...\n" > else: > if filePathName[0] == '"': # If the path includes quotes, remove > them. > zfile = zipfile.ZipFile(filePathName[1:-1], "r") > else: # If the path doesn't include quotes, dont change. > zfile = zipfile.ZipFile(filePathName, "r") I would write: filePathName = filePathName.strip('"') zfile = zipfile.ZipFile(filePathName, "r") > for afile in zfile.namelist(): # For every file in the zip. > # If the file ends with a needed extension, extract it. > if afile.lower().endswith('.cap') \ > or afile.lower().endswith('.hex') \ > or afile.lower().endswith('.fru') \ > or afile.lower().endswith('.sdr') \ > or afile.lower().endswith('.cfg'): The suggestion to use a loop here is excellent. If you are using Python 2.5 it's even easier: if afile.lower().endswith( ('.cap', '.hex', '.fru', '.cfg') ): > if "/" in afile: > aZipFile = afile.rsplit('/', 1)[-1] # Split file > based on criteria. > outfile = open(aZipFile, 'w') # Open output buffer > for writing. > outfile.write(zfile.read(afile)) # Write the file. > outfile.close() # Close the output file buffer. > elif "\\" in afile: > aZipFile = afile.rsplit('\\', 1)[-1] # Split file > based on criteria. > outfile = open(aZipFile, 'w') # Open output buffer > for writing. > outfile.write(zfile.read(afile)) # Write the file. > outfile.close() # Close the output file > buffer. > else: > outfile = open(afile, 'w') # Open output buffer for > writing. > outfile.write(zfile.read(afile)) # Write the file. > outfile.close() # Close the output file buffer. Here you have three copies of the code to process the file. One way to avoid duplication is to factor duplicated code into a separate function but in this case I would preprocess afile, then do the work: if "/" in afile: afile = afile.rsplit('/', 1)[-1] elif "\\" in afile: afile = afile.rsplit('\\', 1)[-1] You could do both of the above in one split using re.split() but I'm not sure you are ready for that... Now you can just use afile, it is the filename you want and you need only one copy of the following code: outfile = open(afile, 'w') # Open output buffer for writing. outfile.write(zfile.read(afile)) # Write the file. outfile.close() # Close the output file buffer. Kent > print "Resource extraction completed successfully!\n" > From klappnase at freenet.de Mon Oct 16 13:00:47 2006 From: klappnase at freenet.de (Michael Lange) Date: Mon, 16 Oct 2006 13:00:47 +0200 Subject: [Tutor] an alternative to shutil.move()? In-Reply-To: <4532C143.7070208@yahoo.es> References: <4532C143.7070208@yahoo.es> Message-ID: <20061016130047.16b7f78c.klappnase@freenet.de> On Mon, 16 Oct 2006 01:16:19 +0200 Alfonso wrote: > Is there an alternative in python to use shutil.move()? > > It copies the files and then removes the source file insted of just > moving directly the file (don't know much about file systems, but I > suppose that when you move using the shell, if both source and > destination are in the same partition, it's just a matter of changing > the entries in the file allocation table). Copying the entire file, > specially with big files is very slow, and I think that it makes an > unnecesary use of the hard drive and system resources, when both source > file and destination are on the same partition... > Try os.rename(old, new) I hope this helps Michael From tim.golden at viacom-outdoor.co.uk Mon Oct 16 14:05:34 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Mon, 16 Oct 2006 13:05:34 +0100 Subject: [Tutor] an alternative to shutil.move()? In-Reply-To: <20061016130047.16b7f78c.klappnase@freenet.de> Message-ID: | Alfonso wrote: | | > Is there an alternative in python to use shutil.move()? | > | > It copies the files and then removes the source file insted of just | > moving directly the file (don't know much about file systems, but I | > suppose that when you move using the shell, if both source and | > destination are in the same partition, it's just a matter | of changing | > the entries in the file allocation table). Copying the entire file, | > specially with big files is very slow, and I think that it makes an | > unnecesary use of the hard drive and system resources, when | both source | > file and destination are on the same partition... I'm assuming that you're on Win32 because of the "shell" and "file allocation table" references. If so, try the stuff in the pywin32 package: http://timgolden.me.uk/python/win32_how_do_i/copy-a-file.html#shell (Obviously, substitute move for copy as appropriate) TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From aguffabuff at hotmail.com Mon Oct 16 15:06:52 2006 From: aguffabuff at hotmail.com (Jack) Date: Mon, 16 Oct 2006 06:06:52 -0700 Subject: [Tutor] simulate a long key press Message-ID: I know about using sendkeys to simulate typing on the keyboard, but how can I simulate holding down a key for several seconds? thanks Jack -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061016/3b669188/attachment.htm From aguffabuff at hotmail.com Mon Oct 16 15:10:36 2006 From: aguffabuff at hotmail.com (Jack) Date: Mon, 16 Oct 2006 06:10:36 -0700 Subject: [Tutor] Get keyboard input while other program is in focus? Message-ID: What commands can I use to have the program know a certain key has been pressed while another program is in focus? thanks, Jack -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061016/f3400ed1/attachment.html From rabidpoobear at gmail.com Mon Oct 16 16:56:42 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 16 Oct 2006 09:56:42 -0500 Subject: [Tutor] Get keyboard input while other program is in focus? In-Reply-To: References: Message-ID: <45339DAA.3010502@gmail.com> Jack wrote: > What commands can I use to have the program know a certain key has > been pressed while another program is in focus? > I think Pygame and TKInter have a capture-all-keys function, but this might also prevent the keypresses from actually going to the target application. > thanks, > Jack > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From bill at celestial.net Mon Oct 16 17:32:14 2006 From: bill at celestial.net (Bill Campbell) Date: Mon, 16 Oct 2006 08:32:14 -0700 Subject: [Tutor] python equivalent of perl readlink()? In-Reply-To: References: <20061016050647.GB5249@ayn.mi.celestial.com> Message-ID: <20061016153214.GA14178@ayn.mi.celestial.com> On Mon, Oct 16, 2006, Alan Gauld wrote: > >"Bill Campbell" wrote in message >> The >function is in the os module ([2] >>> http://docs.python.org/lib/os-file-dir.html). >> >> Silly me. I was looking in the os.path module :-). > >Yes, its confusing/. One thing that should be rationalised IMHO >is the various os modules.There are os, os.path, shutil, and now >subprocess too. > >Alll doing things vaguely related to os type things. A re-org to >make them more consistent would be good, but unfortunately >would probably break lots of code! It would probably be possible to do much, if not all, to make these consistent by judicious programming for backwards compatibility (e.g. having the old call work while creating the new, rational call for use by newer programs). I certainly wouldn't like to see python breaking backwards compatibility, which is probably my primary gripe about open source software (although Bell Labs was equally guilty when they did things like change the ``grep -y'' option to ``grep -i''). Bill -- INTERNET: bill at Celestial.COM Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 Instead of giving money to found colleges to promote learning, why don't they pass a constitutional amendment prohibiting anybody from learning anything? If it works as good as the Prohibition one did, why, in five years we would have the smartest race of people on earth. -- The Best of Will Rogers From kent37 at tds.net Mon Oct 16 17:45:17 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 16 Oct 2006 11:45:17 -0400 Subject: [Tutor] python equivalent of perl readlink()? In-Reply-To: References: <20061015055142.GA17416@ayn.mi.celestial.com><7e5ba9220610151839u3d978826n3cad4ae93fbaecc7@mail.gmail.com> <20061016050647.GB5249@ayn.mi.celestial.com> Message-ID: <4533A90D.7080308@tds.net> Alan Gauld wrote: > "Bill Campbell" wrote in message >> The > function is in the os module ([2] >>> http://docs.python.org/lib/os-file-dir.html). >> Silly me. I was looking in the os.path module :-). > > Yes, its confusing/. One thing that should be rationalised IMHO > is the various os modules.There are os, os.path, shutil, and now > subprocess too. The portions of these modules that have to do with files and file paths are collected in the path module which many people find very handy: http://www.jorendorff.com/articles/python/path/index.html A version of this has been proposed for the standard library: http://www.python.org/dev/peps/pep-0355/ Unfortunately not everyone loves this module and there has been a fair amount of wrangling about the details and for now PEP 355 is rejected. Kent From david at graniteweb.com Mon Oct 16 17:49:04 2006 From: david at graniteweb.com (David Rock) Date: Mon, 16 Oct 2006 10:49:04 -0500 Subject: [Tutor] Equivalent to perl -e In-Reply-To: <128a885f0610151907h220934dbncb96e6ff52f16c67@mail.gmail.com> References: <128a885f0610151744n34527af5l51bd3e227940422c@mail.gmail.com> <4532E13F.3060402@earthlink.net> <128a885f0610151907h220934dbncb96e6ff52f16c67@mail.gmail.com> Message-ID: <20061016154904.GA12882@wdfs.graniteweb.com> * Chris Lasher [2006-10-15 22:07]: > Haha! I'll relay that message! Thanks Kent and Glenn! > Here is one I actually use in real life. I needed something to figure out what the previous year, month, etc for rolling up old log files. The best thing I could think of for date calculation was datetime. This is embedded inside a shell script. python -c ' import time import datetime dtup_now = time.localtime() y,m,d = dtup_now[:3] d_today = datetime.datetime(y,m,d) d_delta = datetime.timedelta(d_today.day) last_month = d_today - d_delta d_delta = datetime.timedelta(last_month.day) two_month = last_month - datetime.timedelta(last_month.day) d_delta = datetime.timedelta(two_month.day) del_month = two_month - datetime.timedelta(two_month.day) print "%d %02d %d%02d" % (last_month.year, last_month.month, del_month.year, del_month.month)' What you will notice is it gets complicated in a hurry if you try to do loops or anything fancy because of formatting constraints. Not that it can't be done, but it would hurt to try. :-) -- David Rock david at graniteweb.com From pyro9219 at gmail.com Mon Oct 16 18:21:46 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Mon, 16 Oct 2006 09:21:46 -0700 Subject: [Tutor] Zipfile and File manipulation questions. In-Reply-To: <453359E9.7020708@tds.net> References: <45321D34.60307@tds.net> <4532EEDB.9000509@pennswoods.net> <453359E9.7020708@tds.net> Message-ID: Excellent suggestions! I'll see how many of them I can impliment. Part of my project 'criteria' is that someone that doesn't know python (or possibly programming) should be able to follow my work to add a new system to the list. Right now I've got it setup so it only takes 3 steps. The reason for this is that I've inherited perl scripts that supposedly can do parts of what my project can do, except I dont know perl, and I dont want to either.. The language (atleast in these scripts) is VERY cryptic... no commenting, no implimentation for adding new output(which I have). This position is short term that high school interns tend to have, so I'm not going to be doing this very long, but it provided a great chance to work with a real world project for python, so I took it. As for python 2.5, I've not made the jump yet... I was waiting for active python to make their release... Not sure why, but this(active python) is what I'm used to =D. That, and I'm not sure how SPE will handle python 2.5and from the feedback I've gotten from the author, he's not able to maintin his project at the moment, which is a shame. If I make changes based on your suggestions, I'll re-share the updated code incase anyone out there wants to see. On 10/16/06, Kent Johnson wrote: > > Chris Hengge wrote: > > I like this little snip of code from your suggestion, and I may > > incorporate it... > > > > for ext in ['.cap', '.hex', '.fru', '.cfg']: > > if aFile.lower().endswith(ext): > > return True > > > > Just for sake of sharing.. here is my entire method.. > > Hopefully for the sake of feedback also... > > You have a lot of duplicated code that is pretty easy to remove, and a > few places where there are easier ways to do it. In general duplicated > code is a bad thing - it makes your program larger and harder maintain. > > Copy and paste is the enemy of readable, maintainable code. > > > > > def extractZip(filePathName): > > """ > > This method recieves the zip file name for decompression, placing > the > > contents of the zip file appropriately. > > """ > > if filePathName == "": > > print "No file provided...\n" > > else: > > if filePathName[0] == '"': # If the path includes quotes, remove > > them. > > zfile = zipfile.ZipFile(filePathName[1:-1], "r") > > else: # If the path doesn't include quotes, dont change. > > zfile = zipfile.ZipFile(filePathName, "r") > > I would write: > filePathName = filePathName.strip('"') > zfile = zipfile.ZipFile(filePathName, "r") > > > for afile in zfile.namelist(): # For every file in the zip. > > # If the file ends with a needed extension, extract it. > > if afile.lower().endswith('.cap') \ > > or afile.lower().endswith('.hex') \ > > or afile.lower().endswith('.fru') \ > > or afile.lower().endswith('.sdr') \ > > or afile.lower().endswith('.cfg'): > > The suggestion to use a loop here is excellent. If you are using Python > 2.5 it's even easier: > if afile.lower().endswith( ('.cap', '.hex', '.fru', '.cfg') ): > > > if "/" in afile: > > aZipFile = afile.rsplit('/', 1)[-1] # Split file > > based on criteria. > > outfile = open(aZipFile, 'w') # Open output buffer > > for writing. > > outfile.write(zfile.read(afile)) # Write the file. > > outfile.close() # Close the output file buffer. > > elif "\\" in afile: > > aZipFile = afile.rsplit('\\', 1)[-1] # Split file > > based on criteria. > > outfile = open(aZipFile, 'w') # Open output buffer > > for writing. > > outfile.write(zfile.read(afile)) # Write the file. > > outfile.close() # Close the output file > > buffer. > > else: > > outfile = open(afile, 'w') # Open output buffer for > > writing. > > outfile.write(zfile.read(afile)) # Write the file. > > outfile.close() # Close the output file buffer. > > Here you have three copies of the code to process the file. One way to > avoid duplication is to factor duplicated code into a separate function > but in this case I would preprocess afile, then do the work: > > if "/" in afile: > afile = afile.rsplit('/', 1)[-1] > elif "\\" in afile: > afile = afile.rsplit('\\', 1)[-1] > > You could do both of the above in one split using re.split() but I'm not > sure you are ready for that... > > Now you can just use afile, it is the filename you want and you need > only one copy of the following code: > > outfile = open(afile, 'w') # Open output buffer for writing. > outfile.write(zfile.read(afile)) # Write the file. > outfile.close() # Close the output file buffer. > > Kent > > > > print "Resource extraction completed successfully!\n" > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061016/a0be9b83/attachment.html From alan.gauld at btinternet.com Mon Oct 16 18:32:34 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 16 Oct 2006 17:32:34 +0100 Subject: [Tutor] Equivalent to perl -e References: <128a885f0610151744n34527af5l51bd3e227940422c@mail.gmail.com><4532E13F.3060402@earthlink.net><128a885f0610151907h220934dbncb96e6ff52f16c67@mail.gmail.com> <20061016154904.GA12882@wdfs.graniteweb.com> Message-ID: "David Rock" wrote in message > This is embedded inside a shell script. > > python -c ' > import time > import datetime > dtup_now = time.localtime() > y,m,d = dtup_now[:3] > d_today = datetime.datetime(y,m,d) > d_delta = datetime.timedelta(d_today.day) > last_month = d_today - d_delta > d_delta = datetime.timedelta(last_month.day) > two_month = last_month - datetime.timedelta(last_month.day) > d_delta = datetime.timedelta(two_month.day) > del_month = two_month - datetime.timedelta(two_month.day) > print "%d %02d %d%02d" % (last_month.year, last_month.month, > del_month.year, del_month.month)' Why? Why not just put it in a Python script? I'm missing something I think. Alan G. > > What you will notice is it gets complicated in a hurry if you try to > do > loops or anything fancy because of formatting constraints. Not that > it > can't be done, but it would hurt to try. :-) > > -- > David Rock > david at graniteweb.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Mon Oct 16 18:40:24 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 16 Oct 2006 17:40:24 +0100 Subject: [Tutor] simulate a long key press References: Message-ID: "Jack" wrote in message > I know about using sendkeys to simulate typing on the keyboard, > but how can I simulate holding down a key for several seconds? I think you need to use ctypes or pythonwin to send a key_down/key_up sequence using the Windows Post/SendMessage API function. I don't know of any other way. The help info below might be useful. Alan G ############ From the Win32 help file ############# The SendMessage function sends the specified message to a window or windows. The function calls the window procedure for the specified window and does not return until the window procedure has processed the message. The PostMessage function, in contrast, posts a message to a thread's message queue and returns immediately. LRESULT SendMessage( HWND hwnd, // handle of destination window UINT uMsg, // message to send WPARAM wParam, // first message parameter LPARAM lParam // second message parameter ); Parameters hwnd Identifies the window whose window procedure will receive the message. If this parameter is HWND_BROADCAST, the message is sent to all top-level windows in the system, including disabled or invisible unowned windows, overlapped windows, and pop-up windows; but the message is not sent to child windows. uMsg Specifies the message to be sent. wParam Specifies additional message-specific information. lParam Specifies additional message-specific information. Return Value The return value specifies the result of the message processing and depends on the message sent. ######################## WM_KEYDOWN nVirtKey = (int) wParam; // virtual-key code lKeyData = lParam; // key data The WM_KEYDOWN message is posted to the window with the keyboard focus when a nonsystem key is pressed. A nonsystem key is a key that is pressed when the ALT key is not pressed. Parameters nVirtKey Value of wParam. Specifies the virtual-key code of the nonsystem key. lKeyData Value of lParam. Specifies the repeat count, scan code, extended-key flag, context code, previous key-state flag, and transition-state flag, as shown in the following table: Value Description 0-15 Specifies the repeat count. The value is the number of times the keystroke is repeated as a result of the user holding down the key. 16-23 Specifies the scan code. The value depends on the original equipment manufacturer (OEM). 24 Specifies whether the key is an extended key, such as the right-hand ALT and CTRL keys that appear on an enhanced 101- or 102-key keyboard. The value is 1 if it is an extended key; otherwise, it is 0. 25-28 Reserved; do not use. 29 Specifies the context code. The value is always 0 for a WM_KEYDOWN message. 30 Specifies the previous key state. The value is 1 if the key is down before the message is sent, or it is 0 if the key is up. 31 Specifies the transition state. The value is always 0 for a WM_KEYDOWN message. Return Value An application should return zero if it processes this message. ################################### WM_KEYUP nVirtKey = (int) wParam; // virtual-key code lKeyData = lParam; // key data The WM_KEYUP message is posted to the window with the keyboard focus when a nonsystem key is released. A nonsystem key is a key that is pressed when the ALT key is not pressed, or a keyboard key that is pressed when a window has the keyboard focus. Parameters nVirtKey Value of wParam. Specifies the virtual-key code of the nonsystem key. lKeyData Value of lParam. Specifies the repeat count, scan code, extended-key flag, context code, previous key-state flag, and transition-state flag, as shown in the following table: Value Description 0-15 Specifies the repeat count. The value is the number of times the keystroke is repeated as a result of the user holding down the key. The repeat count is always one for a WM_KEYUP message. 16-23 Specifies the scan code. The value depends on the original equipment manufacturer (OEM). 24 Specifies whether the key is an extended key, such as the right-hand ALT and CTRL keys that appear on an enhanced 101- or 102-key keyboard. The value is 1 if it is an extended key; otherwise, it is 0. 25-28 Reserved; do not use. 29 Specifies the context code. The value is always 0 for a WM_KEYUP message. 30 Specifies the previous key state. The value is always 1 for a WM_KEYUP message. 31 Specifies the transition state. The value is always 1 for a WM_KEYUP message. Return Value An application should return zero if it processes this message. From Mike.Hansen at atmel.com Mon Oct 16 18:43:29 2006 From: Mike.Hansen at atmel.com (Mike Hansen) Date: Mon, 16 Oct 2006 10:43:29 -0600 Subject: [Tutor] Exception and sys.exit() in a cgi script Message-ID: <57B026980605A64F9B23484C5659E32E35897D@poccso.US.ad.atmel.com> > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of Paulino > Sent: Sunday, October 15, 2006 10:10 AM > To: tutor at python.org > Subject: [Tutor] Exception and sys.exit() in a cgi script > > This is a peace of a CGI script i have. > > 1 import cgi > 2 form=cgi.FieldStorage() > 3 try : > 4 ano=form["ano"].value > 5 conta=form["conta"].value > 6 except KeyError : > 7 print '

Please enter values in the > fields

' > 8 sys.exit(0) > > > When the excption occurs, no message is shown on the browser. > > If I run the script with IDLE, the message is printed and then the > script exits. > > What's wrong here? > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > I'm catching up on the weekend's tutor messages. import cgitb; cgitb.enable() That spits errors to the web page which is great for debugging cgi scripts. I think you need print "Content-Type: text/html\n\n" Before your print html statement. http://docs.python.org/lib/cgi-intro.html http://docs.python.org/lib/node560.html Mike From alan.gauld at btinternet.com Mon Oct 16 18:41:46 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 16 Oct 2006 17:41:46 +0100 Subject: [Tutor] Get keyboard input while other program is in focus? References: Message-ID: "Jack" wrote in message > What commands can I use to have the program know a certain key has > been pressed while another program is in focus? In windows the Key_Down message will tell you if you know the other (focused) window handle. Alan G. From Mike.Hansen at atmel.com Mon Oct 16 18:45:59 2006 From: Mike.Hansen at atmel.com (Mike Hansen) Date: Mon, 16 Oct 2006 10:45:59 -0600 Subject: [Tutor] Equivalent to perl -e Message-ID: <57B026980605A64F9B23484C5659E32E35897E@poccso.US.ad.atmel.com> > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of wesley chun > Sent: Monday, October 16, 2006 12:51 AM > To: Chris Lasher > Cc: Python Tutor > Subject: Re: [Tutor] Equivalent to perl -e > > > His lab maintains a significant amount of Perl code > > this sounds like a full-time job on its own. everyone brings up a > good point... use the right tool for the job. if it's one-liners, > that's what perl -e is made for. for everything else that you > mentioned above, Python is the the one, preferably the only one > --obvious way to do it. :-) > > one perl'y thing that i *do* use is perl -c, for checking your syntax. > i don't believe there's an equivalent way to do that from the Python > cmd-line (correct me if i'm wrong!), but i wrote up a short script I > called (pydashc.py) which just uses compile() to get the same > effect... very useful for when i don't want to *run* something to see > if i made any typos. > > regards, > -- wesley I had this same issue when I moved from Perl to Python. You might take a look at pyflakes, pychecker, or pylint. Mike From alan.gauld at btinternet.com Mon Oct 16 18:44:55 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 16 Oct 2006 17:44:55 +0100 Subject: [Tutor] python equivalent of perl readlink()? References: <20061015055142.GA17416@ayn.mi.celestial.com><7e5ba9220610151839u3d978826n3cad4ae93fbaecc7@mail.gmail.com> <20061016050647.GB5249@ayn.mi.celestial.com> <4533A90D.7080308@tds.net> Message-ID: >> Yes, its confusing/. One thing that should be rationalised IMHO >> is the various os modules.There are os, os.path, shutil, and now >> subprocess too. > > The portions of these modules that have to do with files and file > paths > are collected in the path module which many people find very handy: > http://www.jorendorff.com/articles/python/path/index.html Unfortunately introducing yet another module adds to the confusion. But at least it provides a compatible pathway to rationalisation in the long term. Which is 'A Good Thing' IMHO... Alan G. From Mike.Hansen at atmel.com Mon Oct 16 18:49:50 2006 From: Mike.Hansen at atmel.com (Mike Hansen) Date: Mon, 16 Oct 2006 10:49:50 -0600 Subject: [Tutor] python equivalent of perl readlink()? Message-ID: <57B026980605A64F9B23484C5659E32E35897F@poccso.US.ad.atmel.com> [...] > > I certainly wouldn't like to see python breaking backwards > compatibility, which is probably my primary gripe about open > source software (although Bell Labs was equally guilty when they > did things like change the ``grep -y'' option to ``grep -i''). > > Bill >From what I understand, Python 3000 is going to break backwards compatibility. However, I think I read that someone is writing a utility that will translate your pre-Python 3000 code to Python 3000 code. Mike From billburns at pennswoods.net Mon Oct 16 19:03:38 2006 From: billburns at pennswoods.net (billburns at pennswoods.net) Date: Mon, 16 Oct 2006 13:03:38 -0400 Subject: [Tutor] Get keyboard input while other program is in focus? In-Reply-To: <45339DAA.3010502@gmail.com> References: <45339DAA.3010502@gmail.com> Message-ID: <1161018218.4533bb6aa89e3@webmail.pennswoods.net> [Jack] > > What commands can I use to have the program know a certain key has > > been pressed while another program is in focus? [Luke] > I think Pygame and TKInter have a capture-all-keys function, but this > might also prevent the keypresses from actually going to the target > application. If you need this to work on Windows - take a look at pyHook: http://www.cs.unc.edu/Research/assist/developer.shtml As Luke has stated... it's possible to stop the key presses from reaching their target application. If you do use pyHook, make sure your functions always return True (this allows the key press to hit it's destination). HTH, Bill From dpotter at nc.rr.com Mon Oct 16 19:43:32 2006 From: dpotter at nc.rr.com (dpotter at nc.rr.com) Date: Mon, 16 Oct 2006 13:43:32 -0400 Subject: [Tutor] Capture telnet output to a file? Message-ID: Hello, I am trying to capture telnet output to a file. For example I want to telnet into a router and run the command ?show arp? and be able to capture all the arp information that normally would show up on the screen to a file on my system. I am using python and pexpect to backup my router configurations on a daily basis, but for this the router has the option to send the configuration via tftp to a server, there is no option to send normal screen data to a file. Any ideas? Thank you. From bill at celestial.net Mon Oct 16 19:53:31 2006 From: bill at celestial.net (Bill Campbell) Date: Mon, 16 Oct 2006 10:53:31 -0700 Subject: [Tutor] Capture telnet output to a file? In-Reply-To: References: Message-ID: <20061016175331.GA31925@ayn.mi.celestial.com> On Mon, Oct 16, 2006, dpotter at nc.rr.com wrote: >Hello, > >I am trying to capture telnet output to a file. For example I want to >telnet into a router and run the command ?show arp? and be able to >capture all the arp information that normally would show up on the >screen to a file on my system. I am using python and pexpect to >backup my router configurations on a daily basis, but for this the >router has the option to send the configuration via tftp to a server, >there is no option to send normal screen data to a file. Any ideas? One could use the ``script'' program in *NIX systems which captures your entire session. I haven't used pexpect with python yet, but the perl expect module can also be used to capture things like this, and I would expect that one could do this with pexpect as well. Bill -- INTERNET: bill at Celestial.COM Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 ``If the personal freedoms guaranteed by the Constitution inhibit the government's ability to govern the people, we should look to limit those guarantees.'' -President Bill Clinton, August 12, 1993 From wescpy at gmail.com Mon Oct 16 19:58:12 2006 From: wescpy at gmail.com (wesley chun) Date: Mon, 16 Oct 2006 10:58:12 -0700 Subject: [Tutor] python equivalent of perl readlink()? In-Reply-To: <57B026980605A64F9B23484C5659E32E35897F@poccso.US.ad.atmel.com> References: <57B026980605A64F9B23484C5659E32E35897F@poccso.US.ad.atmel.com> Message-ID: <78b3a9580610161058i61e25d9fy7d3157e265545c50@mail.gmail.com> >From what I understand, Python 3000 is going to break backwards > compatibility. However, I think I read that someone is writing a utility > that will translate your pre-Python 3000 code to Python 3000 code. this will mainly be side effects or for features that are deprecated (sufficient notice is being given for those on the hit list). as with most Python releases, they will try as best they can to keep old programs running. in other words, they're not "starting from scratch." your simple Python scripts that don't involve exotic constructs and calls should still work for the most part. regards, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From david at graniteweb.com Mon Oct 16 20:01:35 2006 From: david at graniteweb.com (David Rock) Date: Mon, 16 Oct 2006 13:01:35 -0500 Subject: [Tutor] Equivalent to perl -e In-Reply-To: References: <20061016154904.GA12882@wdfs.graniteweb.com> Message-ID: <20061016180135.GA13658@wdfs.graniteweb.com> * Alan Gauld [2006-10-16 17:32]: > > Why? > Why not just put it in a Python script? > I'm missing something I think. I don't think you are missing anything. It was something that just sort of happened one day. I was trying to do something fairly simple in a shell script and didn't have a good way to get the date info I wanted, so I started playing around with python -e. It really SHOULD just be a python script that calls shell stuff, not the other way 'round :-) Still, in the spirit of the OP, I thought it would be appropriate to share. -- David Rock david at graniteweb.com From kent37 at tds.net Mon Oct 16 20:00:55 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 16 Oct 2006 14:00:55 -0400 Subject: [Tutor] Capture telnet output to a file? In-Reply-To: References: Message-ID: <4533C8D7.2040308@tds.net> dpotter at nc.rr.com wrote: > Hello, > > I am trying to capture telnet output to a file. For example I want to > telnet into a router and run the command ?show arp? and be able to > capture all the arp information that normally would show up on the > screen to a file on my system. I am using python and pexpect to > backup my router configurations on a daily basis, but for this the > router has the option to send the configuration via tftp to a server, > there is no option to send normal screen data to a file. Any ideas? You might be able to do this using telnetlib instead of pexpect. Kent From dpotter at nc.rr.com Mon Oct 16 20:18:35 2006 From: dpotter at nc.rr.com (dpotter at nc.rr.com) Date: Mon, 16 Oct 2006 14:18:35 -0400 Subject: [Tutor] Capture telnet output to a file? In-Reply-To: <4533C8D7.2040308@tds.net> References: <4533C8D7.2040308@tds.net> Message-ID: That looks like it will do what I want. Thank You! ----- Original Message ----- From: Kent Johnson Date: Monday, October 16, 2006 2:06 pm Subject: Re: [Tutor] Capture telnet output to a file? To: dpotter at nc.rr.com Cc: tutor at python.org > dpotter at nc.rr.com wrote: > > Hello, > > > > I am trying to capture telnet output to a file. For example I > want to > > telnet into a router and run the command ?show arp? and be able to > > capture all the arp information that normally would show up on the > > screen to a file on my system. I am using python and pexpect to > > backup my router configurations on a daily basis, but for this the > > router has the option to send the configuration via tftp to a > server,> there is no option to send normal screen data to a file. > Any ideas? > > You might be able to do this using telnetlib instead of pexpect. > > Kent > From learner404 at gmail.com Mon Oct 16 20:18:32 2006 From: learner404 at gmail.com (learner404) Date: Mon, 16 Oct 2006 20:18:32 +0200 Subject: [Tutor] Get keyboard input while other program is in focus? In-Reply-To: References: Message-ID: <13a83ca10610161118p7ff7589cqbb94aee5e362a7ed@mail.gmail.com> On 16/10/06, Jack wrote: > > What commands can I use to have the program know a certain key has been > pressed while another program is in focus? > Hello, On windows I use the pyHook module (simple to use and works fine) : http://www.cs.unc.edu/~parente/tech/tr08.shtml On Linux its more tricky but you can find some informations here: http://groups.google.com/group/comp.lang.python/browse_thread/thread/2d7e3791381bdeb5/a03d438f64ec5ac8#a03d438f64ec5ac8 cheers thanks, > Jack > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061016/5dfaa090/attachment.htm From dpotter at nc.rr.com Mon Oct 16 20:19:26 2006 From: dpotter at nc.rr.com (dpotter at nc.rr.com) Date: Mon, 16 Oct 2006 14:19:26 -0400 Subject: [Tutor] Capture telnet output to a file? In-Reply-To: <20061016175331.GA31925@ayn.mi.celestial.com> References: <20061016175331.GA31925@ayn.mi.celestial.com> Message-ID: I was not aware of script. Thanks! ----- Original Message ----- From: Bill Campbell Date: Monday, October 16, 2006 1:55 pm Subject: Re: [Tutor] Capture telnet output to a file? To: tutor at python.org > On Mon, Oct 16, 2006, dpotter at nc.rr.com wrote: > >Hello, > > > >I am trying to capture telnet output to a file. For example I > want to > >telnet into a router and run the command ?show arp? and be able to > >capture all the arp information that normally would show up on the > >screen to a file on my system. I am using python and pexpect to > >backup my router configurations on a daily basis, but for this the > >router has the option to send the configuration via tftp to a server, > >there is no option to send normal screen data to a file. Any ideas? > > One could use the ``script'' program in *NIX systems which > captures your entire session. > > I haven't used pexpect with python yet, but the perl expect > module can also be used to capture things like this, and I would > expect that one could do this with pexpect as well. > > Bill > -- > INTERNET: bill at Celestial.COM Bill Campbell; Celestial Software LLC > URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way > FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) > 236-1676 > > ``If the personal freedoms guaranteed by the Constitution inhibit the > government's ability to govern the people, we should look to limit > thoseguarantees.'' > -President Bill Clinton, August 12, 1993 > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Mon Oct 16 20:22:56 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 16 Oct 2006 14:22:56 -0400 Subject: [Tutor] python equivalent of perl readlink()? In-Reply-To: <78b3a9580610161058i61e25d9fy7d3157e265545c50@mail.gmail.com> References: <57B026980605A64F9B23484C5659E32E35897F@poccso.US.ad.atmel.com> <78b3a9580610161058i61e25d9fy7d3157e265545c50@mail.gmail.com> Message-ID: <4533CE00.4080807@tds.net> wesley chun wrote: >>From what I understand, Python 3000 is going to break backwards >> compatibility. However, I think I read that someone is writing a utility >> that will translate your pre-Python 3000 code to Python 3000 code. > > > this will mainly be side effects or for features that are deprecated > (sufficient notice is being given for those on the hit list). as with > most Python releases, they will try as best they can to keep old > programs running. in other words, they're not "starting from > scratch." your simple Python scripts that don't involve exotic > constructs and calls should still work for the most part. Although it is true that Python 3000 is not starting from scratch, I think you are overstating the degree of backward compatibility that is striven for. For example PEP 3000 says, "Python 3000 will break backwards compatibility. There is no requirement that Python 2.9 code will run unmodified on Python 3.0. "I'm not sure whether it is reasonable to require that Python 2.x code can be mechanically translated to equivalent Python 3.0 code; Python's dynamic typing combined with the plans to change the semantics of certain methods of dictionaries, for example, would make this task really hard." Some changes contemplated or already in place that affect code that I wouldn't call exotic - they certainly will break much of my code: - Remove dict.setdefault(), dict.has_key(), input(), raw_input() - Replace print by a function See the list for yourself in PEP 3100: http://www.python.org/dev/peps/pep-3100/ There is also a PEP for things that definitely will not change: http://www.python.org/dev/peps/pep-3099/ From bill at celestial.net Mon Oct 16 20:27:21 2006 From: bill at celestial.net (Bill Campbell) Date: Mon, 16 Oct 2006 11:27:21 -0700 Subject: [Tutor] Capture telnet output to a file? In-Reply-To: References: <20061016175331.GA31925@ayn.mi.celestial.com> Message-ID: <20061016182721.GB3387@ayn.mi.celestial.com> On Mon, Oct 16, 2006, dpotter at nc.rr.com wrote: >I was not aware of script. Thanks! Don't feel bad. I've been using *NIX systems since 1982, and still find new commands from time to time (and we won't talk of the continual ``stupid vi tricks'' I find :-). Bill -- INTERNET: bill at Celestial.COM Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 To say that UNIX is doomed is pretty rabid, OS/2 will certainly play a role, but you don't build a hundred million instructions per second multiprocessor micro and then try to run it on OS/2. I mean, get serious. -- William Zachmann, International Data Corp From pyro9219 at gmail.com Mon Oct 16 20:32:30 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Mon, 16 Oct 2006 11:32:30 -0700 Subject: [Tutor] Zipfile and File manipulation questions. In-Reply-To: <453359E9.7020708@tds.net> References: <45321D34.60307@tds.net> <4532EEDB.9000509@pennswoods.net> <453359E9.7020708@tds.net> Message-ID: Using one of the things you suggested... > if "/" in afile: > aZipFile = afile.rsplit('/', 1)[-1] # Split file > based on criteria. > outfile = open(aZipFile, 'w') # Open output buffer > for writing. > outfile.write(zfile.read(afile)) # Write the file. > outfile.close() # Close the output file buffer. > elif "\\" in afile: > aZipFile = afile.rsplit('\\', 1)[-1] # Split file > based on criteria. > outfile = open(aZipFile, 'w') # Open output buffer > for writing. > outfile.write(zfile.read(afile)) # Write the file. > outfile.close() # Close the output file > buffer. > else: > outfile = open(afile, 'w') # Open output buffer for > writing. > outfile.write(zfile.read(afile)) # Write the file. > outfile.close() # Close the output file buffer. Here you have three copies of the code to process the file. One way to avoid duplication is to factor duplicated code into a separate function but in this case I would preprocess afile, then do the work: if "/" in afile: afile = afile.rsplit('/', 1)[-1] elif "\\" in afile: afile = afile.rsplit('\\', 1)[-1] ############################################################## How do I account for the seperation I had? If you look closely... > outfile = open(afile, 'w') # Open output buffer for > writing. > outfile.write(zfile.read(afile)) # Write the file. > outfile.close() # Close the output file buffer. is not the same as: > aZipFile = afile.rsplit('\\', 1)[-1] # Split file > based on criteria. > outfile = open(aZipFile, 'w') # Open output buffer > for writing. > outfile.write(zfile.read(afile)) # Write the file. > outfile.close() # Close the output file > buffer. The problem is, outfile.write(zfile.read(whatever)) 'whatever' must have the slashes in order to find the file I want inside the zip to extract.. Here is my solution, completed with (I think) all your suggestions... ######################################################################### def extractZip(filePathName): """ This method recieves the zip file name for decompression, placing the contents of the zip file appropriately. """ if filePathName == "": print "No file provided...\n" else: try: # Attempt to unzip file. zFile = zipfile.ZipFile(filePathName.strip('"'), "r") for aFile in zFile.namelist(): # For every file in the zip. # If the file ends with a needed extension, extract it. for ext in ['.cap', '.hex', '.fru', '.cfg', '.sdr']: if aFile.lower().endswith(ext): insideZip = aFile # Copy of Filename. if "/" in aFile: # Split the filename if '/'. aFile = aFile.rsplit('/', 1)[-1] elif "\\" in aFile: # Split the filename if '\'. aFile = aFile.rsplit('\\', 1)[-1] outfile = open(aFile.lower(), 'w') # Open output buffer for writing. outfile.write(zFile.read(insideZip)) # Write the file. outfile.close() # Close the output file buffer. print "Resource extraction completed successfully!\n" except IOerror, message: # If file creation fails, let the user know. print "File could not be written: \n" print message ######################################################################### Definatly an improvement! Thanks Kent. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061016/78b1f876/attachment.html From wescpy at gmail.com Mon Oct 16 20:35:30 2006 From: wescpy at gmail.com (wesley chun) Date: Mon, 16 Oct 2006 11:35:30 -0700 Subject: [Tutor] python equivalent of perl readlink()? In-Reply-To: <4533CE00.4080807@tds.net> References: <57B026980605A64F9B23484C5659E32E35897F@poccso.US.ad.atmel.com> <78b3a9580610161058i61e25d9fy7d3157e265545c50@mail.gmail.com> <4533CE00.4080807@tds.net> Message-ID: <78b3a9580610161135u259bcaefv5a4ab9857973044f@mail.gmail.com> On 10/16/06, Kent Johnson wrote: > wesley chun wrote: > >>From what I understand, Python 3000 is going to break backwards > >> compatibility. However, I think I read that someone is writing a utility > >> that will translate your pre-Python 3000 code to Python 3000 code. > > > > > > this will mainly be side effects or for features that are deprecated > > (sufficient notice is being given for those on the hit list). as with > > most Python releases, they will try as best they can to keep old > > programs running. in other words, they're not "starting from > > scratch." your simple Python scripts that don't involve exotic > > constructs and calls should still work for the most part. > > Although it is true that Python 3000 is not starting from scratch, I > think you are overstating the degree of backward compatibility that is > striven for. For example PEP 3000 says, > > "Python 3000 will break backwards compatibility. There is no requirement > that Python 2.9 code will run unmodified on Python 3.0. yeah, i understand that. this is just the vibe i got from Guido's Python 3000 talk at OSCON several months ago. there is no requirement thus no guarantee for any script to work, but he did say that there will be no *radical* changes. loops and conditionals will be the same, dict.keys still needs (), etc. still, for any medium or moderate script, it probably won't run without some tweaks. From kent37 at tds.net Mon Oct 16 20:41:25 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 16 Oct 2006 14:41:25 -0400 Subject: [Tutor] Zipfile and File manipulation questions. In-Reply-To: References: <45321D34.60307@tds.net> <4532EEDB.9000509@pennswoods.net> <453359E9.7020708@tds.net> Message-ID: <4533D255.2020308@tds.net> Chris Hengge wrote: > Here is my solution, completed with (I think) all your suggestions... > > ######################################################################### > def extractZip(filePathName): > """ > This method recieves the zip file name for decompression, placing the > contents of the zip file appropriately. > """ > if filePathName == "": > print "No file provided...\n" > else: > try: # Attempt to unzip file. > zFile = zipfile.ZipFile(filePathName.strip('"'), "r") > for aFile in zFile.namelist(): # For every file in the zip. > # If the file ends with a needed extension, extract it. > for ext in ['.cap', '.hex', '.fru', '.cfg', '.sdr']: > if aFile.lower().endswith(ext): > insideZip = aFile # Copy of Filename. > if "/" in aFile: # Split the filename if '/'. > aFile = aFile.rsplit('/', 1)[-1] > elif "\\" in aFile: # Split the filename if '\'. > aFile = aFile.rsplit('\\', > 1)[-1] > outfile = open( aFile.lower(), 'w') # Open > output buffer for writing. > outfile.write(zFile.read(insideZip)) # Write the > file. > outfile.close() # Close the output file buffer. > print "Resource extraction completed successfully!\n" > except IOerror, message: # If file creation fails, let the user > know. > print "File could not be written: \n" > print message > > ######################################################################### > Definatly an improvement! Thanks Kent. Yes, that is what I meant. One minor quibble, I think I would keep aFile as the name in the zip, since that is what it starts as, and use a new name for the external file name. Maybe you could use better names, for example zipPath and fileName. I think that would make the code a little clearer but it is a very minor point. Kent From pyro9219 at gmail.com Mon Oct 16 21:26:12 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Mon, 16 Oct 2006 12:26:12 -0700 Subject: [Tutor] Zipfile and File manipulation questions. In-Reply-To: <4533D255.2020308@tds.net> References: <45321D34.60307@tds.net> <4532EEDB.9000509@pennswoods.net> <453359E9.7020708@tds.net> <4533D255.2020308@tds.net> Message-ID: I chose the way I used the names because to me... outFile = open(aFile.lower(), 'w') # Open output buffer for writing. = open a file with lowercase name for writing. it is implied that aFile is from the zip, since it is created in the loop to read the zip.. outFile.write(zFile.read(insideZip)) # Write the file. = write what is read from inside the zip file. I guess for declaration it isn't very clear, but thats what comments are for? My naming was purely for my ease of mind.. I personally care less about what I call it when I declare, as to how it logically flows when I go to use it. I'm sure this is considered poor method, but once I declare a method I tend to never need to change the declaration, just how I use the info... I hope that makes sense. On 10/16/06, Kent Johnson wrote: > > Chris Hengge wrote: > > Here is my solution, completed with (I think) all your suggestions... > > > > > ######################################################################### > > def extractZip(filePathName): > > """ > > This method recieves the zip file name for decompression, placing > the > > contents of the zip file appropriately. > > """ > > if filePathName == "": > > print "No file provided...\n" > > else: > > try: # Attempt to unzip file. > > zFile = zipfile.ZipFile(filePathName.strip('"'), "r") > > for aFile in zFile.namelist(): # For every file in the zip. > > # If the file ends with a needed extension, extract it. > > for ext in ['.cap', '.hex', '.fru', '.cfg', '.sdr']: > > if aFile.lower().endswith(ext): > > insideZip = aFile # Copy of Filename. > > if "/" in aFile: # Split the filename if '/'. > > aFile = aFile.rsplit('/', 1)[-1] > > elif "\\" in aFile: # Split the filename if > '\'. > > aFile = aFile.rsplit('\\', > > 1)[-1] > > outfile = open( aFile.lower(), 'w') # Open > > output buffer for writing. > > outfile.write(zFile.read(insideZip)) # Write the > > file. > > outfile.close() # Close the output file buffer. > > print "Resource extraction completed successfully!\n" > > except IOerror, message: # If file creation fails, let the user > > know. > > print "File could not be written: \n" > > print message > > > > > ######################################################################### > > Definatly an improvement! Thanks Kent. > > Yes, that is what I meant. One minor quibble, I think I would keep aFile > as the name in the zip, since that is what it starts as, and use a new > name for the external file name. Maybe you could use better names, for > example zipPath and fileName. I think that would make the code a little > clearer but it is a very minor point. > > Kent > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061016/123b5222/attachment.html From David.Heiser at intelliden.com Mon Oct 16 22:22:53 2006 From: David.Heiser at intelliden.com (David Heiser) Date: Mon, 16 Oct 2006 14:22:53 -0600 Subject: [Tutor] Capture telnet output to a file? Message-ID: Here is a snippet of code that may work for you: #----------------------------------- import telnetlib HOST = "myServer" Username = "bob" Password = "fido" LoginList = ['=login:', '%s=password:' % (Username), '%s=$' % (Password)] ## Like an Expect script Terminator = "$" print "CONNECTING:" Telnet = telnetlib.Telnet(HOST) i = 0 for LoginPair in LoginList: LoginPair = LoginPair.split("=") if i > 0: Telnet.write(LoginPair[0] + "\n") x = Telnet.read_until(LoginPair[1]) print x i = i + 1 print "CONNECTED:" CommandLine = "ls -l\n" Telnet.write(CommandLine) Blob = Telnet.read_until(Terminator) print Blob #----------------------------------- -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of dpotter at nc.rr.com Sent: Monday, October 16, 2006 12:19 PM To: Kent Johnson Cc: tutor at python.org Subject: Re: [Tutor] Capture telnet output to a file? That looks like it will do what I want. Thank You! ----- Original Message ----- From: Kent Johnson Date: Monday, October 16, 2006 2:06 pm Subject: Re: [Tutor] Capture telnet output to a file? To: dpotter at nc.rr.com Cc: tutor at python.org > dpotter at nc.rr.com wrote: > > Hello, > > > > I am trying to capture telnet output to a file. For example I > want to > > telnet into a router and run the command "show arp" and be able to > > capture all the arp information that normally would show up on the > > screen to a file on my system. I am using python and pexpect to > > backup my router configurations on a daily basis, but for this the > > router has the option to send the configuration via tftp to a > server,> there is no option to send normal screen data to a file. > Any ideas? > > You might be able to do this using telnetlib instead of pexpect. > > Kent > _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From ps_python at yahoo.com Mon Oct 16 23:18:35 2006 From: ps_python at yahoo.com (kumar s) Date: Mon, 16 Oct 2006 14:18:35 -0700 (PDT) Subject: [Tutor] extracting numbers from a list Message-ID: <20061016211835.76058.qmail@web35815.mail.mud.yahoo.com> hi : I have a simple question to ask tutors: list A : a = [10,15,18,20,25,30,40] I want to print 10 15 (first two elements) 16 18 (16 is last number +1) 19 20 21 25 26 30 31 40 >>> fx = a[0] >>> fy = a[1] >>> b = a[2:] >>> ai = iter(b) >>> last = ai.next() >>> for j in ai: ... print fy+1,last ... last = j ... 16 18 16 20 16 25 16 30 can any one help please. thank you __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From wescpy at gmail.com Mon Oct 16 23:37:51 2006 From: wescpy at gmail.com (wesley chun) Date: Mon, 16 Oct 2006 14:37:51 -0700 Subject: [Tutor] extracting numbers from a list In-Reply-To: <20061016211835.76058.qmail@web35815.mail.mud.yahoo.com> References: <20061016211835.76058.qmail@web35815.mail.mud.yahoo.com> Message-ID: <78b3a9580610161437i30c935e7wbc5d701c53a9a33e@mail.gmail.com> > I want to print > 10 15 (first two elements) > 16 18 (16 is last number +1) > : > >>> fx = a[0] > >>> fy = a[1] > >>> b = a[2:] > >>> ai = iter(b) > >>> last = ai.next() > >>> for j in ai: > ... print fy+1,last > ... last = j > ... > 16 18 > 16 20 > 16 25 > 16 30 look very carefully at variables 'fy' vs. 'last', what you do with them, and when, and you should be able to figure out your homework assignment problem. hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From ziad.rahhal at gmail.com Mon Oct 16 23:41:43 2006 From: ziad.rahhal at gmail.com (Ziad Rahhal) Date: Mon, 16 Oct 2006 23:41:43 +0200 Subject: [Tutor] extracting numbers from a list In-Reply-To: <20061016211835.76058.qmail@web35815.mail.mud.yahoo.com> References: <20061016211835.76058.qmail@web35815.mail.mud.yahoo.com> Message-ID: On 10/16/06, kumar s wrote: > > hi : > > I have a simple question to ask tutors: > > list A : > > a = [10,15,18,20,25,30,40] > > I want to print > 10 15 (first two elements) > 16 18 (16 is last number +1) > 19 20 > 21 25 > 26 30 > 31 40 > > >>> fx = a[0] > >>> fy = a[1] > >>> b = a[2:] > >>> ai = iter(b) > >>> last = ai.next() > >>> for j in ai: > ... print fy+1,last > ... last = j > ... > 16 18 > 16 20 > 16 25 > 16 30 > > > can any one help please. > > thank you a = [10,15,18,20,25,30, 40] print a[0], a[1] for i in xrange(2, len(a)): print a[i-1] + 1, a[i] __________________________________________________ > Do You Yahoo!? > Tired of spam? Yahoo! Mail has the best spam protection around > http://mail.yahoo.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061016/564616b7/attachment.htm From alan.gauld at btinternet.com Tue Oct 17 00:13:51 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 16 Oct 2006 23:13:51 +0100 Subject: [Tutor] extracting numbers from a list References: <20061016211835.76058.qmail@web35815.mail.mud.yahoo.com> Message-ID: "kumar s" wrote > a = [10,15,18,20,25,30,40] > > I want to print > 10 15 (first two elements) > 16 18 (16 is last number +1) > 19 20 The simplest solution would seem to be a while loop: print a[0], a[1] # special case index = 1 while index < len(a): print a[index-1]+1, a[index] index += 1 But that seems too straightforward to be the solution, so I assume I'm missing something? -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From rabidpoobear at gmail.com Tue Oct 17 00:47:01 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 16 Oct 2006 17:47:01 -0500 Subject: [Tutor] Zipfile and File manipulation questions. In-Reply-To: References: <45321D34.60307@tds.net> <4532EEDB.9000509@pennswoods.net> <453359E9.7020708@tds.net> <4533D255.2020308@tds.net> Message-ID: <45340BE5.4010103@gmail.com> Chris Hengge wrote: > I chose the way I used the names because to me... > > outFile = open(aFile.lower(), 'w') # Open output buffer for writing. > = open a file with lowercase name for writing. > it is implied that aFile is from the zip, since it is created in the > loop to read the zip.. > > outFile.write(zFile.read(insideZip)) # Write the file. > = write what is read from inside the zip file. > > I guess for declaration it isn't very clear, but thats what comments > are for? No!!!! Consider the following 2 examples: #temp.py def aa(a): for b in range(2,a): if a % b == 0: return False return True a = int(raw_input('Please enter a prime number: ')) if not aa(a): print "That's not a prime." raise SystemExit a = (2**a)-1 if aa(a): print "It's a mersenne prime." else: print "It's not a mersenne prime." #---- #Check_Mersenne_Numbers.py def isprime(candidate): for number in range(2,candidate): if number % candidate == 0: return False return True power = int(raw_input('Please enter a prime number: ')) if not isprime(power): print "That's not a prime." raise SystemExit mersenne_number = (2**power) - 1 if not isprime(mersenne_number): print "It's not a mersenne prime." else: print "It is a mersenne prime." # ---- Obviously, the whole aa(a) thing was designed to look ridiculous, but you have to remember that other people looking at your code don't know anything about it, like you do. You can comment the example #1 to the point where people can figure out what's going on, but example #2 is more or less completely clear as to what is happening at every step without any need for documentation. If you find yourself commenting "Remember here that file is no longer the input file but is now the output file" chances are you'd be better off having 2 variables, infile and outfile. If you fall into this pattern of willy-nilly naming variables you might someday have a script that looks like this: import os, sys print sys.argv sys = "Intel Core 2 Duo" os = "Windows XP Professional" print "This computer is running %s on a(n) %s" % (os,sys) #remember os and sys are strings and not modules #we need to use the os and sys modules again so we need to reimport them, #but we'll go ahead and import them as something else so we don't overwrite our string vars. import os as Os import sys as Sys if sys in Sys.argv: print "They passed ",sys," as an argument!" #we need an alternate configuration now SYs = "AMD ATHLON 64" OS = "Ubuntu" #let's get the name of this script SYs = Os.path.split(Sys.argv[0])[-1] sys = "Error creating directory." print "this script is called %s" % SYs #subdirectories for our oses try: Os.mkdir(OS) Os.mkdir(os) except: print sys #------ Haha. Just be forewarned! Coming up with good variable names is extremely important! > My naming was purely for my ease of mind.. I personally care less > about what I call it when I declare, as to how it logically flows when > I go to use it. I'm sure this is considered poor method, but once I > declare a method I tend to never need to change the declaration, just > how I use the info... I hope that makes sense. No, I don't know what you mean here. > > On 10/16/06, *Kent Johnson* > > wrote: > > Chris Hengge wrote: > > Here is my solution, completed with (I think) all your > suggestions... > > > > > ######################################################################### > > def extractZip(filePathName): > > """ > > This method recieves the zip file name for decompression, > placing the > > contents of the zip file appropriately. > > """ > > if filePathName == "": > > print "No file provided...\n" > > else: > > try: # Attempt to unzip file. > > zFile = zipfile.ZipFile(filePathName.strip('"'), "r") > > for aFile in zFile.namelist(): # For every file in > the zip. > > # If the file ends with a needed extension, > extract it. > > for ext in ['.cap', '.hex', '.fru', '.cfg', '.sdr']: > > if aFile.lower().endswith(ext): > > insideZip = aFile # Copy of Filename. > > if "/" in aFile: # Split the filename if > '/'. > > aFile = aFile.rsplit('/', 1)[-1] > > elif "\\" in aFile: # Split the > filename if '\'. > > aFile = aFile.rsplit('\\', > > 1)[-1] > > outfile = open( aFile.lower(), 'w') # Open > > output buffer for writing. > > outfile.write(zFile.read(insideZip)) # > Write the > > file. > > outfile.close() # Close the output file > buffer. > > print "Resource extraction completed successfully!\n" > > except IOerror, message: # If file creation fails, let > the user > > know. > > print "File could not be written: \n" > > print message > > > > > ######################################################################### > > Definatly an improvement! Thanks Kent. > > Yes, that is what I meant. One minor quibble, I think I would keep > aFile > as the name in the zip, since that is what it starts as, and use > a new > name for the external file name. Maybe you could use better names, for > example zipPath and fileName. I think that would make the code a > little > clearer but it is a very minor point. > > Kent > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Tue Oct 17 01:13:16 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 17 Oct 2006 00:13:16 +0100 Subject: [Tutor] extracting numbers from a list References: <20061016211835.76058.qmail@web35815.mail.mud.yahoo.com> <78b3a9580610161437i30c935e7wbc5d701c53a9a33e@mail.gmail.com> Message-ID: "wesley chun" wrote in message > look very carefully at variables 'fy' vs. 'last', what you do with > them, and when, and you should be able to figure out your homework > assignment problem. Hmmm, "homework assignment" was probably what I was missing.... Alan G. From pine508 at hotmail.com Tue Oct 17 02:27:22 2006 From: pine508 at hotmail.com (Pine Marten) Date: Mon, 16 Oct 2006 20:27:22 -0400 Subject: [Tutor] How to save and later open text from a wxTextCtrl widget to a text file? Message-ID: I want to make a GUI in which user can write text in a text box and then click a button to save it to a text file. I'm using wxPython's TextCtrl widget. Then later I would want the user to be able to open it back into that window. Any help appreciated, thank you. _________________________________________________________________ Stay in touch with old friends and meet new ones with Windows Live Spaces http://clk.atdmt.com/MSN/go/msnnkwsp0070000001msn/direct/01/?href=http://spaces.live.com/spacesapi.aspx?wx_action=create&wx_url=/friends.aspx&mkt=en-us From ajkadri at googlemail.com Tue Oct 17 02:42:07 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Tue, 17 Oct 2006 01:42:07 +0100 Subject: [Tutor] extracting numbers from a list In-Reply-To: <20061016211835.76058.qmail@web35815.mail.mud.yahoo.com> References: <20061016211835.76058.qmail@web35815.mail.mud.yahoo.com> Message-ID: My solution : (i have tested it) list1 = [10,15,18,20,25,30,40] for i in range(len(list1)-1): print list1[i],list1[i+1] list1[i+1] += 1 Note: # print the consecutive elements; for the first pass of the loop the elements are unchanged, for the remaining we add one. On 10/16/06, kumar s wrote: > > hi : > > I have a simple question to ask tutors: > > list A : > > a = [10,15,18,20,25,30,40] > > I want to print > 10 15 (first two elements) > 16 18 (16 is last number +1) > 19 20 > 21 25 > 26 30 > 31 40 > > >>> fx = a[0] > >>> fy = a[1] > >>> b = a[2:] > >>> ai = iter(b) > >>> last = ai.next() > >>> for j in ai: > ... print fy+1,last > ... last = j > ... > 16 18 > 16 20 > 16 25 > 16 30 > > > can any one help please. > > thank you > > __________________________________________________ > Do You Yahoo!? > Tired of spam? Yahoo! Mail has the best spam protection around > http://mail.yahoo.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061017/d059a958/attachment.htm From john at fouhy.net Tue Oct 17 02:56:43 2006 From: john at fouhy.net (John Fouhy) Date: Tue, 17 Oct 2006 13:56:43 +1300 Subject: [Tutor] How to save and later open text from a wxTextCtrl widget to a text file? In-Reply-To: References: Message-ID: <5e58f2e40610161756u62742222s22cdfb6dc76b86f4@mail.gmail.com> On 17/10/06, Pine Marten wrote: > I want to make a GUI in which user can write text in a text box and then > click a button to save it to a text file. I'm using wxPython's TextCtrl > widget. > > Then later I would want the user to be able to open it back into that > window. > > Any help appreciated, thank you. Suppose you've got a TextCtrl: myTextBox = wx.TextCtrl(parent, style=wx.TE_MULTILINE) You can save it simply like this: def save(event): savefile = open(self.filename, 'w') savefile.write(myTextBox.GetValue()) savefile.close() saveButton = wx.Button(parent, id=wx.ID_SAVE) saveButton.Bind(wx.EVT_BUTTON, save) Of course, you'll need some way of setting self.filename. The usual way would be to have a Save button and a Save as.. button, and have Save as.. invoke a wx.FileDialog. Something like: def saveas(event): dialog = wx.FileDialog(parent, message='Choose a file', style=wx.SAVE|wx.OVERWRITE_PROMPT) if dialog.ShowModal() == wx.ID_OK: self.savefile = dialog.GetFilename() save(event) saveAsButton = wx.Button(parent, id=wx.ID_SAVEAS) saveAsButton.Bind(wx.EVT_BUTTON, saveas) You could also modify save() to automatically call saveas() if self.filename is not set. (just be careful of recursion if the user clicks cancel!) Loading is the same except in the opposite direction. Look at wx.TextCtrl.SetValue and the style options for wx.FileDialog. HTH! -- John. From kent37 at tds.net Tue Oct 17 03:00:47 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 16 Oct 2006 21:00:47 -0400 Subject: [Tutor] extracting numbers from a list In-Reply-To: References: <20061016211835.76058.qmail@web35815.mail.mud.yahoo.com> Message-ID: <45342B3F.2060002@tds.net> Asrarahmed Kadri wrote: > My solution : (i have tested it) > > > list1 = [10,15,18,20,25,30,40] > > for i in range(len(list1)-1): > print list1[i],list1[i+1] > list1[i+1] += 1 Note that this changes the original list, which may or may not be acceptable. Normally you would expect a printing function not to change the value being printed. Kent From ajkadri at googlemail.com Tue Oct 17 03:08:59 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Tue, 17 Oct 2006 02:08:59 +0100 Subject: [Tutor] extracting numbers from a list In-Reply-To: <45342B3F.2060002@tds.net> References: <20061016211835.76058.qmail@web35815.mail.mud.yahoo.com> <45342B3F.2060002@tds.net> Message-ID: I agree. Regards, Asrar On 10/17/06, Kent Johnson wrote: > > Asrarahmed Kadri wrote: > > My solution : (i have tested it) > > > > > > list1 = [10,15,18,20,25,30,40] > > > > for i in range(len(list1)-1): > > print list1[i],list1[i+1] > > list1[i+1] += 1 > > Note that this changes the original list, which may or may not be > acceptable. Normally you would expect a printing function not to change > the value being printed. > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061017/23936edf/attachment.htm From john at fouhy.net Tue Oct 17 03:20:23 2006 From: john at fouhy.net (John Fouhy) Date: Tue, 17 Oct 2006 14:20:23 +1300 Subject: [Tutor] extracting numbers from a list In-Reply-To: References: <20061016211835.76058.qmail@web35815.mail.mud.yahoo.com> Message-ID: <5e58f2e40610161820g52af72c5m7acc780428245d9e@mail.gmail.com> On 17/10/06, Asrarahmed Kadri wrote: > My solution : (i have tested it) As long as we're all taking turns, what about a functional approach: >>> a = [10, 15, 18, 20, 25, 30, 40] >>> def pairs(lst): ... return list.__add__([(lst[0], lst[1])], zip(map((1).__add__, lst[1:]), lst[2:])) ... >>> pairs(a) [(10, 15), (16, 18), (19, 20), (21, 25), (26, 30), (31, 40)] -- John. From amonroe at columbus.rr.com Tue Oct 17 03:39:06 2006 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Mon, 16 Oct 2006 21:39:06 -0400 Subject: [Tutor] How to save and later open text from a wxTextCtrl widget to a text file? In-Reply-To: References: Message-ID: <102-1680782648.20061016213906@columbus.rr.com> > I want to make a GUI in which user can write text in a text box and then > click a button to save it to a text file. I'm using wxPython's TextCtrl > widget. > Then later I would want the user to be able to open it back into that > window. > Any help appreciated, thank you. Have you learnt how to open, write, and close files yet? If you can get that working in a non-gui program, that's a good first step. Check out: http://docs.python.org/tut/node9.html#SECTION00920000000000000000 Alan From pyro9219 at gmail.com Tue Oct 17 03:54:17 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Mon, 16 Oct 2006 18:54:17 -0700 Subject: [Tutor] Zipfile and File manipulation questions. In-Reply-To: <45340BE5.4010103@gmail.com> References: <45321D34.60307@tds.net> <4532EEDB.9000509@pennswoods.net> <453359E9.7020708@tds.net> <4533D255.2020308@tds.net> <45340BE5.4010103@gmail.com> Message-ID: I didn't come up with those variable names willy nilly... I chose them because they reflect their functionality.. Which to me, is much more important then anything else... if I go back and look at code months later.. I have an easier time remember names based on functionality, and less of an easy time naming "because that word best describes it" real world example... I drive to work, I own a car... While car is the actual object description, when I go to tell someone what I'm attempting to do with the car, 'drive' is much more clear then car. On 10/16/06, Luke Paireepinart wrote: > > Chris Hengge wrote: > > I chose the way I used the names because to me... > > > > outFile = open(aFile.lower(), 'w') # Open output buffer for writing. > > = open a file with lowercase name for writing. > > it is implied that aFile is from the zip, since it is created in the > > loop to read the zip.. > > > > outFile.write(zFile.read(insideZip)) # Write the file. > > = write what is read from inside the zip file. > > > > I guess for declaration it isn't very clear, but thats what comments > > are for? > No!!!! > Consider the following 2 examples: > > #temp.py > def aa(a): > for b in range(2,a): > if a % b == 0: > return False > return True > > a = int(raw_input('Please enter a prime number: ')) > if not aa(a): > print "That's not a prime." > raise SystemExit > a = (2**a)-1 > if aa(a): > print "It's a mersenne prime." > else: > print "It's not a mersenne prime." > #---- > > > > > #Check_Mersenne_Numbers.py > def isprime(candidate): > for number in range(2,candidate): > if number % candidate == 0: > return False > return True > > power = int(raw_input('Please enter a prime number: ')) > if not isprime(power): > print "That's not a prime." > raise SystemExit > > mersenne_number = (2**power) - 1 > > if not isprime(mersenne_number): > print "It's not a mersenne prime." > else: > print "It is a mersenne prime." > # ---- > > Obviously, the whole aa(a) thing was designed to look ridiculous, > but you have to remember that other people looking at your code don't > know anything about it, like you do. > You can comment the example #1 to the point where people can figure out > what's going on, > but example #2 is more or less completely clear as to what is happening > at every step without any need for documentation. > If you find yourself commenting "Remember here that file is no longer > the input file but is now the output file" > chances are you'd be better off having 2 variables, infile and outfile. > If you fall into this pattern of willy-nilly naming variables you might > someday have a script that looks like this: > > import os, sys > print sys.argv > sys = "Intel Core 2 Duo" > os = "Windows XP Professional" > print "This computer is running %s on a(n) %s" % (os,sys) #remember os > and sys are strings and not modules > > #we need to use the os and sys modules again so we need to reimport them, > #but we'll go ahead and import them as something else so we don't > overwrite our string vars. > import os as Os > import sys as Sys > if sys in Sys.argv: print "They passed ",sys," as an argument!" > #we need an alternate configuration now > SYs = "AMD ATHLON 64" > OS = "Ubuntu" > #let's get the name of this script > SYs = Os.path.split(Sys.argv[0])[-1] > sys = "Error creating directory." > print "this script is called %s" % SYs > #subdirectories for our oses > try: > Os.mkdir(OS) > Os.mkdir(os) > except: > print sys > > #------ > Haha. > Just be forewarned! Coming up with good variable names is extremely > important! > > > My naming was purely for my ease of mind.. I personally care less > > about what I call it when I declare, as to how it logically flows when > > I go to use it. I'm sure this is considered poor method, but once I > > declare a method I tend to never need to change the declaration, just > > how I use the info... I hope that makes sense. > No, I don't know what you mean here. > > > > On 10/16/06, *Kent Johnson* > > > wrote: > > > > Chris Hengge wrote: > > > Here is my solution, completed with (I think) all your > > suggestions... > > > > > > > > > ######################################################################### > > > def extractZip(filePathName): > > > """ > > > This method recieves the zip file name for decompression, > > placing the > > > contents of the zip file appropriately. > > > """ > > > if filePathName == "": > > > print "No file provided...\n" > > > else: > > > try: # Attempt to unzip file. > > > zFile = zipfile.ZipFile(filePathName.strip('"'), "r") > > > for aFile in zFile.namelist(): # For every file in > > the zip. > > > # If the file ends with a needed extension, > > extract it. > > > for ext in ['.cap', '.hex', '.fru', '.cfg', > '.sdr']: > > > if aFile.lower().endswith(ext): > > > insideZip = aFile # Copy of Filename. > > > if "/" in aFile: # Split the filename if > > '/'. > > > aFile = aFile.rsplit('/', 1)[-1] > > > elif "\\" in aFile: # Split the > > filename if '\'. > > > aFile = aFile.rsplit('\\', > > > 1)[-1] > > > outfile = open( aFile.lower(), 'w') # Open > > > output buffer for writing. > > > outfile.write(zFile.read(insideZip)) # > > Write the > > > file. > > > outfile.close() # Close the output file > > buffer. > > > print "Resource extraction completed successfully!\n" > > > except IOerror, message: # If file creation fails, let > > the user > > > know. > > > print "File could not be written: \n" > > > print message > > > > > > > > > ######################################################################### > > > Definatly an improvement! Thanks Kent. > > > > Yes, that is what I meant. One minor quibble, I think I would keep > > aFile > > as the name in the zip, since that is what it starts as, and use > > a new > > name for the external file name. Maybe you could use better names, > for > > example zipPath and fileName. I think that would make the code a > > little > > clearer but it is a very minor point. > > > > Kent > > > > > > > > ------------------------------------------------------------------------ > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061016/8663cc10/attachment-0001.html From rabidpoobear at gmail.com Tue Oct 17 04:12:05 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 16 Oct 2006 21:12:05 -0500 Subject: [Tutor] Zipfile and File manipulation questions. In-Reply-To: References: <45321D34.60307@tds.net> <4532EEDB.9000509@pennswoods.net> <453359E9.7020708@tds.net> <4533D255.2020308@tds.net> <45340BE5.4010103@gmail.com> Message-ID: <45343BF5.6030804@gmail.com> Chris Hengge wrote: > I didn't come up with those variable names willy nilly... I know :) I just wanted to make it clear that your statement 'that's what comments are for' wasn't really a good way to look at it. If you have to write a comment because your usage of variables, or something else you're doing, contradicts what someone would logically think you're trying to accomplish, then it's bad. If you're writing a comment to explain an algorithm or something you're doing, it's good. > I chose them because they reflect their functionality.. Which to me, > is much more important then anything else... if I go back and look at > code months later.. I have an easier time remember names based on > functionality, and less of an easy time naming "because that word best > describes it" That's perfectly fine... but also, if you're using a single variable for multiple things, you might get confused about what it is at a certain point... and if you have to trace back up through your code and figure out where you modified the variable, it's less convenient. You know what I mean? I actually read kent's comment " Yes, that is what I meant. One minor quibble, I think I would keep aFile as the name in the zip, since that is what it starts as, and use a new name for the external file name. Maybe you could use better names, for example zipPath and fileName. I think that would make the code a little clearer but it is a very minor point." and I didn't read your code, and I think I misunderstood what Kent meant. So you probably have no idea what I'm talking about. Oh well, sorry! > > real world example... > I drive to work, I own a car... While car is the actual object > description, when I go to tell someone what I'm attempting to do with > the car, 'drive' is much more clear then car. Yeah, that makes sense, but I'm not really sure how it applies in this case. -Luke From pyro9219 at gmail.com Tue Oct 17 05:40:30 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Mon, 16 Oct 2006 20:40:30 -0700 Subject: [Tutor] Zipfile and File manipulation questions. In-Reply-To: <45343BF5.6030804@gmail.com> References: <4532EEDB.9000509@pennswoods.net> <453359E9.7020708@tds.net> <4533D255.2020308@tds.net> <45340BE5.4010103@gmail.com> <45343BF5.6030804@gmail.com> Message-ID: [quote] and I didn't read your code [/quote] How's that supposed to help? =D -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061016/87906450/attachment.html From pine508 at hotmail.com Tue Oct 17 06:03:04 2006 From: pine508 at hotmail.com (Pine Marten) Date: Tue, 17 Oct 2006 00:03:04 -0400 Subject: [Tutor] Tutor Digest, Vol 32, Issue 69 In-Reply-To: Message-ID: Thank you John for the code but I still can't get it to work and to simply save the contents of the text box to a file. Here is the code I have which just makes a panel with a text control and two buttons, "Save" and "Save As..." My hope is this can easily incorporate the changes you suggest, but I can't figure out how to do it: #Boa:Frame:Frame1 import wx def create(parent): return Frame1(parent) [wxID_FRAME1, wxID_FRAME1PANEL1, wxID_FRAME1SAVE, wxID_FRAME1SAVEAS, wxID_FRAME1TEXTCTRL1, ] = [wx.NewId() for _init_ctrls in range(5)] class Frame1(wx.Frame): def _init_ctrls(self, prnt): # generated method, don't edit wx.Frame.__init__(self, id=wxID_FRAME1, name='', parent=prnt, pos=wx.Point(367, 109), size=wx.Size(402, 489), style=wx.DEFAULT_FRAME_STYLE, title='Frame1') self.SetClientSize(wx.Size(394, 455)) self.panel1 = wx.Panel(id=wxID_FRAME1PANEL1, name='panel1', parent=self, pos=wx.Point(0, 0), size=wx.Size(394, 455), style=wx.TAB_TRAVERSAL) self.textCtrl1 = wx.TextCtrl(id=wxID_FRAME1TEXTCTRL1, name='textCtrl1', parent=self.panel1, pos=wx.Point(40, 56), size=wx.Size(264, 248), style=wx.TE_MULTILINE, value='textCtrl1') self.Save = wx.Button(id=wxID_FRAME1SAVE, label='Save', name='Save', parent=self.panel1, pos=wx.Point(152, 32), size=wx.Size(75, 23), style=0) self.Save.Bind(wx.EVT_BUTTON, self.OnSaveButton, id=wxID_FRAME1SAVE) self.saveas = wx.Button(id=wxID_FRAME1SAVEAS, label='Save as...', name='saveas', parent=self.panel1, pos=wx.Point(232, 32), size=wx.Size(75, 23), style=0) self.saveas.Bind(wx.EVT_BUTTON, self.OnSaveasButton, id=wxID_FRAME1SAVEAS) def __init__(self, parent): self._init_ctrls(parent) def OnSaveButton(self, event): event.Skip() def OnSaveasButton(self, event): event.Skip() If you or someone could show me how to insert the save function into this properly so I can get it to work in this simple case, I think I'll understand it better. In the meantime I will continue trying, and I will read up on Alan's suggestion about learning to open, write, and close files generally. Thank you, PM _________________________________________________________________ Try Search Survival Kits: Fix up your home and better handle your cash with Live Search! http://imagine-windowslive.com/search/kits/default.aspx?kit=improve&locale=en-US&source=hmtagline From john at fouhy.net Tue Oct 17 06:15:41 2006 From: john at fouhy.net (John Fouhy) Date: Tue, 17 Oct 2006 17:15:41 +1300 Subject: [Tutor] How to save and later open text from a wxTextCtrl widget to a text file? Message-ID: <5e58f2e40610162115g37ba6ccei4300c5018fa6e8cf@mail.gmail.com> On 17/10/06, Pine Marten wrote: > > Thank you John for the code but I still can't get it to work and to simply > save the contents of the text box to a file. Here is the code I have which > just makes a panel with a text control and two buttons, "Save" and "Save > As..." My hope is this can easily incorporate the changes you suggest, but > I can't figure out how to do it: > > #Boa:Frame:Frame1 > > import wx [...] Did you create this code, or did someone give it to you? It looks like it's been made with BoaConstructor. If you're using Boa for development, you'd probably be better off using it to add your save functionality, rather than writing the code by hand. Unfortunately, I can't help you with that, but maybe someone else can. In fact, I see you've already got Save and SaveAs buttons, so maybe you just need to edit OnSaveButton() and OnSaveAsButton(). -- John. From sisson.j at gmail.com Tue Oct 17 00:27:06 2006 From: sisson.j at gmail.com (Jonathon Sisson) Date: Mon, 16 Oct 2006 17:27:06 -0500 Subject: [Tutor] Zipfile and File manipulation questions. In-Reply-To: References: <45321D34.60307@tds.net> <4532EEDB.9000509@pennswoods.net> <453359E9.7020708@tds.net> <4533D255.2020308@tds.net> Message-ID: <4534073A.3090102@gmail.com> Chris Hengge wrote: > I chose the way I used the names because to me... > > outFile = open(aFile.lower(), 'w') # Open output buffer for writing. > = open a file with lowercase name for writing. > it is implied that aFile is from the zip, since it is created in the > loop to read the zip.. > > outFile.write(zFile.read(insideZip)) # Write the file. > = write what is read from inside the zip file. > > I guess for declaration it isn't very clear, but thats what comments are > for? > My naming was purely for my ease of mind.. I personally care less about > what I call it when I declare, as to how it logically flows when I go to > use it. I'm sure this is considered poor method, but once I declare a > method I tend to never need to change the declaration, just how I use > the info... I hope that makes sense. > Even if you're the only person that EVER lays eyes on that code (and you inherited Perl code, so I assume someone will eventually take this code over) it's vital to use names that are clear and concise. If you disagree, put your code away in a locked box, then re-read it after six months and see if it makes perfect sense. As Kent said, this is quite a minor issue that shouldn't be paraded, but I have been on the receiving end of code such as: int a; if (a == 0) { /* do something interesting */ } else { /* do something less interesting */ } (Sorry for the Java-ish flair...Java happens to be on my mind at the moment...) Even if I was there when the code was written, how could I know what "a" means a month later without digging back through to see how it's used? (and worse, "a" was used for conditional testing in this specific example (i.e. on/off conditions), so a boolean would have done MUCH better). Commenting can only help so much...the code must speak for itself at some point. (Yes, I know this is an extreme example, but it happens all the time). Something like this is much more readable: boolean fileExists; if (fileExists) { /* do something interesting */ } else { /* do something less interesting */ } I'm not complaining, because afterall it's up to you to write the code you're comfortable with (because you're not working on a team, that is), but a friendly suggestion on naming conventions (especially when you can refactor in most IDE's today) could go a long ways to helping you build readable code that is easier to maintain. Jonathon > On 10/16/06, *Kent Johnson* > wrote: > > Chris Hengge wrote: > > Here is my solution, completed with (I think) all your suggestions... > > > > > ######################################################################### > > def extractZip(filePathName): > > """ > > This method recieves the zip file name for decompression, > placing the > > contents of the zip file appropriately. > > """ > > if filePathName == "": > > print "No file provided...\n" > > else: > > try: # Attempt to unzip file. > > zFile = zipfile.ZipFile(filePathName.strip('"'), "r") > > for aFile in zFile.namelist(): # For every file in > the zip. > > # If the file ends with a needed extension, > extract it. > > for ext in ['.cap', '.hex', '.fru', '.cfg', '.sdr']: > > if aFile.lower().endswith(ext): > > insideZip = aFile # Copy of Filename. > > if "/" in aFile: # Split the filename if '/'. > > aFile = aFile.rsplit('/', 1)[-1] > > elif "\\" in aFile: # Split the filename > if '\'. > > aFile = aFile.rsplit('\\', > > 1)[-1] > > outfile = open( aFile.lower(), 'w') # Open > > output buffer for writing. > > outfile.write(zFile.read(insideZip)) # > Write the > > file. > > outfile.close() # Close the output file > buffer. > > print "Resource extraction completed successfully!\n" > > except IOerror, message: # If file creation fails, let > the user > > know. > > print "File could not be written: \n" > > print message > > > > > ######################################################################### > > Definatly an improvement! Thanks Kent. > > Yes, that is what I meant. One minor quibble, I think I would keep > aFile > as the name in the zip, since that is what it starts as, and use a new > name for the external file name. Maybe you could use better names, for > example zipPath and fileName. I think that would make the code a little > clearer but it is a very minor point. > > Kent > > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From rabidpoobear at gmail.com Tue Oct 17 06:20:44 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 16 Oct 2006 23:20:44 -0500 Subject: [Tutor] [Fwd: Re: Tutor Digest, Vol 32, Issue 69] Message-ID: <45345A1C.20901@gmail.com> Oops, I replied off-list. Forwarding copy to list. -------------- next part -------------- An embedded message was scrubbed... From: Luke Paireepinart Subject: Re: [Tutor] Tutor Digest, Vol 32, Issue 69 Date: Mon, 16 Oct 2006 23:20:15 -0500 Size: 3759 Url: http://mail.python.org/pipermail/tutor/attachments/20061016/0ccef013/attachment.mht From pyro9219 at gmail.com Tue Oct 17 06:36:22 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Mon, 16 Oct 2006 21:36:22 -0700 Subject: [Tutor] Zipfile and File manipulation questions. In-Reply-To: <4534073A.3090102@gmail.com> References: <45321D34.60307@tds.net> <4532EEDB.9000509@pennswoods.net> <453359E9.7020708@tds.net> <4533D255.2020308@tds.net> <4534073A.3090102@gmail.com> Message-ID: Have you even read my code to see if you find it cryptic? I'm starting to beleive people just read the one comment on possibly using better naming conventions and assumed I had picked completely irrelivent names. On 10/16/06, Jonathon Sisson wrote: > > Chris Hengge wrote: > > I chose the way I used the names because to me... > > > > outFile = open(aFile.lower(), 'w') # Open output buffer for writing. > > = open a file with lowercase name for writing. > > it is implied that aFile is from the zip, since it is created in the > > loop to read the zip.. > > > > outFile.write(zFile.read(insideZip)) # Write the file. > > = write what is read from inside the zip file. > > > > I guess for declaration it isn't very clear, but thats what comments are > > for? > > My naming was purely for my ease of mind.. I personally care less about > > what I call it when I declare, as to how it logically flows when I go to > > use it. I'm sure this is considered poor method, but once I declare a > > method I tend to never need to change the declaration, just how I use > > the info... I hope that makes sense. > > > > Even if you're the only person that EVER lays eyes on that code (and you > inherited Perl code, so I assume someone will eventually take this code > over) it's vital to use names that are clear and concise. If you > disagree, put your code away in a locked box, then re-read it after six > months and see if it makes perfect sense. > > As Kent said, this is quite a minor issue that shouldn't be paraded, but > I have been on the receiving end of code such as: > > > int a; > > if (a == 0) > { > /* do something interesting */ > } > else > { > /* do something less interesting */ > } > > (Sorry for the Java-ish flair...Java happens to be on my mind at the > moment...) > > Even if I was there when the code was written, how could I know what "a" > means a month later without digging back through to see how it's used? > (and worse, "a" was used for conditional testing in this specific > example (i.e. on/off conditions), so a boolean would have done MUCH > better). Commenting can only help so much...the code must speak for > itself at some point. (Yes, I know this is an extreme example, but it > happens all the time). > > Something like this is much more readable: > > > boolean fileExists; > > if (fileExists) > { > /* do something interesting */ > } > else > { > /* do something less interesting */ > } > > > I'm not complaining, because afterall it's up to you to write the code > you're comfortable with (because you're not working on a team, that is), > but a friendly suggestion on naming conventions (especially when you can > refactor in most IDE's today) could go a long ways to helping you build > readable code that is easier to maintain. > > Jonathon > > > > On 10/16/06, *Kent Johnson* > > wrote: > > > > Chris Hengge wrote: > > > Here is my solution, completed with (I think) all your > suggestions... > > > > > > > > > ######################################################################### > > > def extractZip(filePathName): > > > """ > > > This method recieves the zip file name for decompression, > > placing the > > > contents of the zip file appropriately. > > > """ > > > if filePathName == "": > > > print "No file provided...\n" > > > else: > > > try: # Attempt to unzip file. > > > zFile = zipfile.ZipFile(filePathName.strip('"'), "r") > > > for aFile in zFile.namelist(): # For every file in > > the zip. > > > # If the file ends with a needed extension, > > extract it. > > > for ext in ['.cap', '.hex', '.fru', '.cfg', > '.sdr']: > > > if aFile.lower().endswith(ext): > > > insideZip = aFile # Copy of Filename. > > > if "/" in aFile: # Split the filename if > '/'. > > > aFile = aFile.rsplit('/', 1)[-1] > > > elif "\\" in aFile: # Split the filename > > if '\'. > > > aFile = aFile.rsplit('\\', > > > 1)[-1] > > > outfile = open( aFile.lower(), 'w') # > Open > > > output buffer for writing. > > > outfile.write(zFile.read(insideZip)) # > > Write the > > > file. > > > outfile.close() # Close the output file > > buffer. > > > print "Resource extraction completed successfully!\n" > > > except IOerror, message: # If file creation fails, let > > the user > > > know. > > > print "File could not be written: \n" > > > print message > > > > > > > > > ######################################################################### > > > Definatly an improvement! Thanks Kent. > > > > Yes, that is what I meant. One minor quibble, I think I would keep > > aFile > > as the name in the zip, since that is what it starts as, and use a > new > > name for the external file name. Maybe you could use better names, > for > > example zipPath and fileName. I think that would make the code a > little > > clearer but it is a very minor point. > > > > Kent > > > > > > > > > > ------------------------------------------------------------------------ > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061016/7790fb0b/attachment.html From rabidpoobear at gmail.com Tue Oct 17 06:39:15 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 16 Oct 2006 23:39:15 -0500 Subject: [Tutor] Zipfile and File manipulation questions. In-Reply-To: References: <45321D34.60307@tds.net> <4532EEDB.9000509@pennswoods.net> <453359E9.7020708@tds.net> <4533D255.2020308@tds.net> <4534073A.3090102@gmail.com> Message-ID: <45345E73.5070103@gmail.com> Chris Hengge wrote: > Have you even read my code to see if you find it cryptic? I'm starting > to beleive people just read the one comment on possibly using better > naming conventions and assumed I had picked completely irrelivent names. Well, Chris, what can I say? We're busy people and we generally assume that Kent knows what he's talking about ;) I'll read your code sometime but I have to take care of some Calculus homework right now! From pine508 at hotmail.com Tue Oct 17 06:56:46 2006 From: pine508 at hotmail.com (Pine Marten) Date: Tue, 17 Oct 2006 00:56:46 -0400 Subject: [Tutor] Tutor Digest, Vol 32, Issue 70 In-Reply-To: Message-ID: >Did you create this code, or did someone give it to you? It looks >like it's been made with BoaConstructor. If you're using Boa for >development, you'd probably be better off using it to add your save >functionality, rather than writing the code by hand. > >Unfortunately, I can't help you with that, but maybe someone else can. > >In fact, I see you've already got Save and SaveAs buttons, so maybe >you just need to edit OnSaveButton() and OnSaveAsButton(). I used Boa Constructor to make it. As far as I understand it, Boa sets things up for you but then you have to add code to complete things, it does not have an option to add save functionality on its own. In this case I did in fact try to add the code you originally suggested under the OnSaveButton() and OnSaveAsButton() but was unable to get it to work. Teetering on the brink of just bagging trying to learn Python, but thanks for your suggestions. _________________________________________________________________ Stay in touch with old friends and meet new ones with Windows Live Spaces http://clk.atdmt.com/MSN/go/msnnkwsp0070000001msn/direct/01/?href=http://spaces.live.com/spacesapi.aspx?wx_action=create&wx_url=/friends.aspx&mkt=en-us From sisson.j at gmail.com Tue Oct 17 01:14:55 2006 From: sisson.j at gmail.com (Jonathon Sisson) Date: Mon, 16 Oct 2006 18:14:55 -0500 Subject: [Tutor] Zipfile and File manipulation questions. In-Reply-To: References: <45321D34.60307@tds.net> <4532EEDB.9000509@pennswoods.net> <453359E9.7020708@tds.net> <4533D255.2020308@tds.net> <4534073A.3090102@gmail.com> Message-ID: <4534126F.3020903@gmail.com> Yes, I read your code, as well as this entire thread. All I'm saying is that: #1) I'm not complaining about your naming conventions. #2) It would be easier *on you* in the long run if you use more concise names. #3) Code how you are comfortable coding...just don't expect "aFile" to fly in a team setting. I'm not trying to run you down or "bare my fangs" for bad naming conventions, seriously, I'm not. This list's intent is to help, and Kent, Luke, myself, and a whole slew of other programmers have made suggestions that you simply cast aside. (Again, it is *your* decision, but don't expect any of us to be much help if we can't read your code and go "oh, that's what he's trying to do there" without serious effort). None of us are getting paid to figure out what your code does, then formulate an answer and post it to this list. We do that because we're trying to help. I apologise if the tone of my last post was misunderstood, Chris. I'm not trying to be "Mr. Enforcer" here or nothing (I'd rather think I'm far from capable), but don't take constructive criticism wrong. I'm glad you got the code working. Congrats. Jonathon Chris Hengge wrote: > Have you even read my code to see if you find it cryptic? I'm starting > to beleive people just read the one comment on possibly using better > naming conventions and assumed I had picked completely irrelivent names. > > On 10/16/06, *Jonathon Sisson* > wrote: > > Chris Hengge wrote: > > I chose the way I used the names because to me... > > > > outFile = open(aFile.lower(), 'w') # Open output buffer for writing. > > = open a file with lowercase name for writing. > > it is implied that aFile is from the zip, since it is created in the > > loop to read the zip.. > > > > outFile.write(zFile.read(insideZip)) # Write the file. > > = write what is read from inside the zip file. > > > > I guess for declaration it isn't very clear, but thats what > comments are > > for? > > My naming was purely for my ease of mind.. I personally care less > about > > what I call it when I declare, as to how it logically flows when > I go to > > use it. I'm sure this is considered poor method, but once I declare a > > method I tend to never need to change the declaration, just how I use > > the info... I hope that makes sense. > > > > Even if you're the only person that EVER lays eyes on that code (and > you > inherited Perl code, so I assume someone will eventually take this code > over) it's vital to use names that are clear and concise. If you > disagree, put your code away in a locked box, then re-read it after six > months and see if it makes perfect sense. > > As Kent said, this is quite a minor issue that shouldn't be paraded, but > I have been on the receiving end of code such as: > > > int a; > > if (a == 0) > { > /* do something interesting */ > } > else > { > /* do something less interesting */ > } > > (Sorry for the Java-ish flair...Java happens to be on my mind at the > moment...) > > Even if I was there when the code was written, how could I know what > "a" > means a month later without digging back through to see how it's used? > (and worse, "a" was used for conditional testing in this specific > example (i.e. on/off conditions), so a boolean would have done MUCH > better). Commenting can only help so much...the code must speak for > itself at some point. (Yes, I know this is an extreme example, but it > happens all the time). > > Something like this is much more readable: > > > boolean fileExists; > > if (fileExists) > { > /* do something interesting */ > } > else > { > /* do something less interesting */ > } > > > I'm not complaining, because afterall it's up to you to write the code > you're comfortable with (because you're not working on a team, that is), > but a friendly suggestion on naming conventions (especially when you can > refactor in most IDE's today) could go a long ways to helping you build > readable code that is easier to maintain. > > Jonathon > > > > On 10/16/06, *Kent Johnson* >> wrote: > > > > Chris Hengge wrote: > > > Here is my solution, completed with (I think) all your > suggestions... > > > > > > > > > ######################################################################### > > > > def extractZip(filePathName): > > > """ > > > This method recieves the zip file name for decompression, > > placing the > > > contents of the zip file appropriately. > > > """ > > > if filePathName == "": > > > print "No file provided...\n" > > > else: > > > try: # Attempt to unzip file. > > > zFile = > zipfile.ZipFile(filePathName.strip('"'), "r") > > > for aFile in zFile.namelist(): # For every file in > > the zip. > > > # If the file ends with a needed extension, > > extract it. > > > for ext in ['.cap', '.hex', '.fru', > '.cfg', '.sdr']: > > > if aFile.lower().endswith(ext): > > > insideZip = aFile # Copy of Filename. > > > if "/" in aFile: # Split the > filename if '/'. > > > aFile = aFile.rsplit('/', 1)[-1] > > > elif "\\" in aFile: # Split the > filename > > if '\'. > > > aFile = aFile.rsplit('\\', > > > 1)[-1] > > > outfile = open( aFile.lower(), > 'w') # Open > > > output buffer for writing. > > > outfile.write(zFile.read(insideZip)) # > > Write the > > > file. > > > outfile.close() # Close the output > file > > buffer. > > > print "Resource extraction completed > successfully!\n" > > > except IOerror, message: # If file creation fails, let > > the user > > > know. > > > print "File could not be written: \n" > > > print message > > > > > > > > > ######################################################################### > > > > Definatly an improvement! Thanks Kent. > > > > Yes, that is what I meant. One minor quibble, I think I would > keep > > aFile > > as the name in the zip, since that is what it starts as, > and use a new > > name for the external file name. Maybe you could use better > names, for > > example zipPath and fileName. I think that would make the > code a little > > clearer but it is a very minor point. > > > > Kent > > > > > > > > > > > ------------------------------------------------------------------------ > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > From dyoo at hkn.eecs.berkeley.edu Tue Oct 17 07:09:24 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 16 Oct 2006 22:09:24 -0700 (PDT) Subject: [Tutor] Zipfile and File manipulation questions. In-Reply-To: References: <45321D34.60307@tds.net> <4532EEDB.9000509@pennswoods.net> <453359E9.7020708@tds.net> <4533D255.2020308@tds.net> <4534073A.3090102@gmail.com> Message-ID: On Mon, 16 Oct 2006, Chris Hengge wrote: > Have you even read my code to see if you find it cryptic? I'm starting > to beleive people just read the one comment on possibly using better > naming conventions and assumed I had picked completely irrelivent names. Hi Chris, Sometimes one of us (or a few of us) might rush out our answers a bit too quickly. I think we're just trying to make good on that "24 hours or your answer is free" thing. *wink* The last version I've seen of your code is: http://mail.python.org/pipermail/tutor/2006-October/050059.html The comment I'd make on extractZip is that it is a bit nested and long. You might want to apply a refactoring to flatten things out a bit. Concretely, if we look at extractZip(): ########################################################### def extractZip(filename): ... zFile = zipfile.ZipFile(filePathName.strip('"'), "r") for aFile in zFile.namelist(): for ext in ['.cap', '.hex', '.fru', '.cfg', '.sdr']: if aFile.lower().endswith(ext): ... ############################################################ we see that it has several levels of logic. But it can have its nesting reduced if we provide a helper function to recognize interesting filenames: ######################################################## def isInterestingFile(fileName): """Returns True if the fileName ends with a needed extension, and False otherwise.""" for ext in ['.cap', '.hex', '.fru', '.cfg', '.sdr']: if fileName.lower().endswith(ext): return True return False ######################################################## If we have this isInterestingFile() as a helper function, the main logic in extractZip is easier to see: ######################################################### def extractZip(filename): ... zFile = zipfile.ZipFile(filePathName.strip('"'), "r") for aFile in zFile.namelist(): if isInterestingFile(aFile): ... ######################################################### Since the helper function is standalone, it's just physically easier to see that what's distinguishing interesting files from non-interesting ones is its treatment of the extension, and I hope you agree that the structure of extractZip() improves a bit. You may want to consider restructuring your program like this, using things like helper functions, so that commenting every single line of code becomes less necessary to understand the program. As it stands, every line of code is commented --- this is usually overkill. If you find yourself needing to do it to understand the program, consider the possiblity that those comments might be acting as a crutch. The approach that most of us here recommend is to simplify the program structure so that it's easy to understand. Comments are necessary, but they should be used judiciously. See how far you can get by using helper functions to break out blocks of interesting and useful code. If you want another example of a possible refactoring, feel free to ask the group. Good luck! From nibudh at gmail.com Tue Oct 17 07:47:05 2006 From: nibudh at gmail.com (nibudh) Date: Tue, 17 Oct 2006 15:47:05 +1000 Subject: [Tutor] Equivalent to perl -e In-Reply-To: <20061016180135.GA13658@wdfs.graniteweb.com> References: <20061016154904.GA12882@wdfs.graniteweb.com> <20061016180135.GA13658@wdfs.graniteweb.com> Message-ID: <77f8f7c30610162247l551d4d5es45f4ddcfed7bff52@mail.gmail.com> On 10/17/06, David Rock wrote: > > * Alan Gauld [2006-10-16 17:32]: > > > > Why? > > Why not just put it in a Python script? > > I'm missing something I think. > > I don't think you are missing anything. It was something that just sort > of happened one day. I was trying to do something fairly simple in a > shell script and didn't have a good way to get the date info I wanted, > so I started playing around with python -e. It really SHOULD just be a > python script that calls shell stuff, not the other way 'round :-) > > Hi, list. This is my first post... What i've found is that my quick and dirty oneliners can go from host to host with me and having them "all in one file" makes it easier to move around or share... Recently i wrote a shell script called "hostingdata" that returns a report on a given domain name. It mostly stays on my monitoring server and i have broken out some of the functions into a seperate file so i can reuse them in other scripts. However one of the helpdesk guys saw the script and he wanted to be able to run it from his computer, I bundled up the functions back into the main script and copied it into his ~/bin. It just seemed easier that way. One needs to gauge whether doing this is likely to cause more problems than it's worth... but for small scripts with a small user base this would seem to work fine. Cheers, nibudh. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061017/3036eb89/attachment.html From pyro9219 at gmail.com Tue Oct 17 07:51:57 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Mon, 16 Oct 2006 22:51:57 -0700 Subject: [Tutor] Zipfile and File manipulation questions. In-Reply-To: <4534126F.3020903@gmail.com> References: <4532EEDB.9000509@pennswoods.net> <453359E9.7020708@tds.net> <4533D255.2020308@tds.net> <4534073A.3090102@gmail.com> <4534126F.3020903@gmail.com> Message-ID: Comment on #2.... I am hearing that from basically everyone here... But as I just wrote in another reply, descriptional names dont work for me.. I like functional names... So, using 'more concise' (meaning descriptional) do not help me, and haven't helped me in the last few years I've written code in various languages out of hobby. I personally can look back at every project I've made and understand what I meant when I wrote it... In my head.. I figure out what something does by looking at how it works, not by naming all the parts.. (engine reference) I do this because it implicitly uses the "term" in it's intented context. As stated in the other email, this could be because english wasn't my first language.. or the fact that while in lower education I took 9 combined years of various foriegn languages and thats how we were taught to identify vocabulary that doesn't have direct meaning. On 10/16/06, Jonathon Sisson wrote: > > Yes, I read your code, as well as this entire thread. All I'm saying is > that: > > #1) I'm not complaining about your naming conventions. > > #2) It would be easier *on you* in the long run if you use more concise > names. > > #3) Code how you are comfortable coding...just don't expect "aFile" to > fly in a team setting. > > I'm not trying to run you down or "bare my fangs" for bad naming > conventions, seriously, I'm not. This list's intent is to help, and > Kent, Luke, myself, and a whole slew of other programmers have made > suggestions that you simply cast aside. (Again, it is *your* decision, > but don't expect any of us to be much help if we can't read your code > and go "oh, that's what he's trying to do there" without serious > effort). None of us are getting paid to figure out what your code does, > then formulate an answer and post it to this list. We do that because > we're trying to help. > > I apologise if the tone of my last post was misunderstood, Chris. I'm > not trying to be "Mr. Enforcer" here or nothing (I'd rather think I'm > far from capable), but don't take constructive criticism wrong. > > I'm glad you got the code working. Congrats. > > Jonathon > > > Chris Hengge wrote: > > Have you even read my code to see if you find it cryptic? I'm starting > > to beleive people just read the one comment on possibly using better > > naming conventions and assumed I had picked completely irrelivent names. > > > > On 10/16/06, *Jonathon Sisson* > > wrote: > > > > Chris Hengge wrote: > > > I chose the way I used the names because to me... > > > > > > outFile = open(aFile.lower(), 'w') # Open output buffer for > writing. > > > = open a file with lowercase name for writing. > > > it is implied that aFile is from the zip, since it is created in > the > > > loop to read the zip.. > > > > > > outFile.write(zFile.read(insideZip)) # Write the file. > > > = write what is read from inside the zip file. > > > > > > I guess for declaration it isn't very clear, but thats what > > comments are > > > for? > > > My naming was purely for my ease of mind.. I personally care less > > about > > > what I call it when I declare, as to how it logically flows when > > I go to > > > use it. I'm sure this is considered poor method, but once I > declare a > > > method I tend to never need to change the declaration, just how I > use > > > the info... I hope that makes sense. > > > > > > > Even if you're the only person that EVER lays eyes on that code (and > > you > > inherited Perl code, so I assume someone will eventually take this > code > > over) it's vital to use names that are clear and concise. If you > > disagree, put your code away in a locked box, then re-read it after > six > > months and see if it makes perfect sense. > > > > As Kent said, this is quite a minor issue that shouldn't be paraded, > but > > I have been on the receiving end of code such as: > > > > > > int a; > > > > if (a == 0) > > { > > /* do something interesting */ > > } > > else > > { > > /* do something less interesting */ > > } > > > > (Sorry for the Java-ish flair...Java happens to be on my mind at the > > moment...) > > > > Even if I was there when the code was written, how could I know what > > "a" > > means a month later without digging back through to see how it's > used? > > (and worse, "a" was used for conditional testing in this specific > > example (i.e. on/off conditions), so a boolean would have done MUCH > > better). Commenting can only help so much...the code must speak for > > itself at some point. (Yes, I know this is an extreme example, but > it > > happens all the time). > > > > Something like this is much more readable: > > > > > > boolean fileExists; > > > > if (fileExists) > > { > > /* do something interesting */ > > } > > else > > { > > /* do something less interesting */ > > } > > > > > > I'm not complaining, because afterall it's up to you to write the > code > > you're comfortable with (because you're not working on a team, that > is), > > but a friendly suggestion on naming conventions (especially when you > can > > refactor in most IDE's today) could go a long ways to helping you > build > > readable code that is easier to maintain. > > > > Jonathon > > > > > > > On 10/16/06, *Kent Johnson* > > >> wrote: > > > > > > Chris Hengge wrote: > > > > Here is my solution, completed with (I think) all your > > suggestions... > > > > > > > > > > > > > > ######################################################################### > > > > > > def extractZip(filePathName): > > > > """ > > > > This method recieves the zip file name for > decompression, > > > placing the > > > > contents of the zip file appropriately. > > > > """ > > > > if filePathName == "": > > > > print "No file provided...\n" > > > > else: > > > > try: # Attempt to unzip file. > > > > zFile = > > zipfile.ZipFile(filePathName.strip('"'), "r") > > > > for aFile in zFile.namelist(): # For every > file in > > > the zip. > > > > # If the file ends with a needed > extension, > > > extract it. > > > > for ext in ['.cap', '.hex', '.fru', > > '.cfg', '.sdr']: > > > > if aFile.lower().endswith(ext): > > > > insideZip = aFile # Copy of > Filename. > > > > if "/" in aFile: # Split the > > filename if '/'. > > > > aFile = aFile.rsplit('/', 1)[-1] > > > > elif "\\" in aFile: # Split the > > filename > > > if '\'. > > > > aFile = aFile.rsplit('\\', > > > > 1)[-1] > > > > outfile = open( aFile.lower(), > > 'w') # Open > > > > output buffer for writing. > > > > outfile.write(zFile.read(insideZip)) > # > > > Write the > > > > file. > > > > outfile.close() # Close the output > > file > > > buffer. > > > > print "Resource extraction completed > > successfully!\n" > > > > except IOerror, message: # If file creation fails, > let > > > the user > > > > know. > > > > print "File could not be written: \n" > > > > print message > > > > > > > > > > > > > > ######################################################################### > > > > > > Definatly an improvement! Thanks Kent. > > > > > > Yes, that is what I meant. One minor quibble, I think I would > > keep > > > aFile > > > as the name in the zip, since that is what it starts as, > > and use a new > > > name for the external file name. Maybe you could use better > > names, for > > > example zipPath and fileName. I think that would make the > > code a little > > > clearer but it is a very minor point. > > > > > > Kent > > > > > > > > > > > > > > > > > > ------------------------------------------------------------------------ > > > > > > _______________________________________________ > > > Tutor maillist - Tutor at python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061016/a08dc3cb/attachment.htm From rabidpoobear at gmail.com Tue Oct 17 08:13:51 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 17 Oct 2006 01:13:51 -0500 Subject: [Tutor] How to save text from a wxTextCtrl widget [was: Tutor Digest, Vol 32, Issue 70] In-Reply-To: References: Message-ID: <4534749F.4080903@gmail.com> Pine Marten wrote: > >> Did you create this code, or did someone give it to you? It looks >> like it's been made with BoaConstructor. If you're using Boa for >> development, you'd probably be better off using it to add your save >> functionality, rather than writing the code by hand. >> >> Unfortunately, I can't help you with that, but maybe someone else can. >> >> In fact, I see you've already got Save and SaveAs buttons, so maybe >> you just need to edit OnSaveButton() and OnSaveAsButton(). >> > > I used Boa Constructor to make it. As far as I understand it, Boa sets > things up for you but then you have to add code to complete things, it does > not have an option to add save functionality on its own. > > In this case I did in fact try to add the code you originally suggested > under the OnSaveButton() and OnSaveAsButton() but was unable to get it to > work. > > Teetering on the brink of just bagging trying to learn Python, but thanks > for your suggestions. > I'd hate for you to give up learning Python just cause of one problem! Here, I'll take you through the example code that John wrote. Suppose you've got a TextCtrl: #here's our textctrl. myTextBox = wx.TextCtrl(parent, style=wx.TE_MULTILINE) You can save it simply like this: #a function that takes an event as an argument (note that it doesn't actually use this event) def save(event): savefile = open(self.filename, 'w')#open the file (self.filename) to store our saved data savefile.write(myTextBox.GetValue())#get our text from the textctrl, and write it out to the file we just opened. savefile.close()#and then close the file. saveButton = wx.Button(parent, id=wx.ID_SAVE)#we make a button saveButton.Bind(wx.EVT_BUTTON, save)#and we bind it to the 'save' function #so whenever someone clicks on the button it will call the 'save' function with an argument (event). #all this other stuff isn't necessary to the saving function, it's just #if you want to give the users some kind of dialog to enter #where to save the file. If you're going to save the text to a certain #file in all cases, then you wouldn't need to do any of this. #so for now, let's just skip this part. Of course, you'll need some way of setting self.filename. The usual way would be to have a Save button and a Save as.. button, and have Save as.. invoke a wx.FileDialog. Something like: def saveas(event): dialog = wx.FileDialog(parent, message='Choose a file', style=wx.SAVE|wx.OVERWRITE_PROMPT) if dialog.ShowModal() == wx.ID_OK: self.savefile = dialog.GetFilename() save(event) saveAsButton = wx.Button(parent, id=wx.ID_SAVEAS) saveAsButton.Bind(wx.EVT_BUTTON, saveas) You could also modify save() to automatically call saveas() if self.filename is not set. (just be careful of recursion if the user clicks cancel!) Loading is the same except in the opposite direction. Look at wx.TextCtrl.SetValue and the style options for wx.FileDialog. #-------------------- Okay, now that we know what we want to use, let's put it into your code! #Don't need to change any of this. # I'll leave any relevant code. import wx [snip code] class Frame1(wx.Frame): [snip code] self.textCtrl1 = wx.TextCtrl(id=wxID_FRAME1TEXTCTRL1, name='textCtrl1', parent=self.panel1, pos=wx.Point(40, 56), size=wx.Size(264, 248), style=wx.TE_MULTILINE, value='textCtrl1') self.Save = wx.Button(id=wxID_FRAME1SAVE, label='Save', name='Save', parent=self.panel1, pos=wx.Point(152, 32), size=wx.Size(75, 23), style=0) self.Save.Bind(wx.EVT_BUTTON, self.OnSaveButton, id=wxID_FRAME1SAVE) [snip code] # # # # # # #Okay, here is the function we need to change. def OnSaveButton(self, event): #from John's save(event) function: # #savefile = open(self.filename, 'w') #savefile.write(myTextBox.GetValue()) #savefile.close() savefile = open('test.txt','w') #if you don't want 'test.txt' try using a variable. savefile.write(self.textCtrl1.GetValue()) #textCtrl1 is an attribute of your Frame1 class. savefile.close() #then we just save it. #-------------------- Do you understand which parts of John's examples were changed and why? Hope That Helps, -Luke From kent37 at tds.net Tue Oct 17 12:04:41 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 17 Oct 2006 06:04:41 -0400 Subject: [Tutor] Zipfile and File manipulation questions. In-Reply-To: References: <45321D34.60307@tds.net> <4532EEDB.9000509@pennswoods.net> <453359E9.7020708@tds.net> <4533D255.2020308@tds.net> Message-ID: <4534AAB9.40200@tds.net> Chris Hengge wrote: > I chose the way I used the names because to me... > > outFile = open(aFile.lower(), 'w') # Open output buffer for writing. > = open a file with lowercase name for writing. > it is implied that aFile is from the zip, since it is created in the > loop to read the zip.. > > outFile.write(zFile.read(insideZip)) # Write the file. > = write what is read from inside the zip file. This sub-thread seems to have turned into "let's beat on Chris for the way he names things" which certainly isn't what I intended. Ultimately it is up to the program author to use the names that he thinks communicate most clearly. But I think the actual naming was secondary to the my main point which is that the value for 'insideZip' is read from the zip, if you assign to that name and keep it in that name the code is easier to follow because the value that doesn't change stays in a name that doesn't change. So using your names, it would read for insideZip in zFile.namelist(): for ext in ['.cap', '.hex', '.fru', '.cfg', '.sdr']: if insideZip .lower().endswith(ext): if "/" in insideZip : aFile = aFile.rsplit('/', 1)[-1] elif "\\" in insideZip : aFile = aFile.rsplit('\\', 1)[-1] else: aFile = insideZip This way inzideZip is always the name from inside the zip, and aFile is always the name of the file to write. > > I guess for declaration it isn't very clear, but thats what comments are > for? The comments about comments have been on the mark, I think. A helpful guideline I use is, when I think I need a comment, look at the names I am using and see if I can create a function whose name conveys what I wanted to say in the comment. Kent From 3dbernard at gmail.com Tue Oct 17 16:46:26 2006 From: 3dbernard at gmail.com (Bernard Lebel) Date: Tue, 17 Oct 2006 10:46:26 -0400 Subject: [Tutor] Importing module - file system requests Message-ID: <61d0e2b40610170746r5ffe9f61uf43983bad92d4ade@mail.gmail.com> Hello, When I import a module in Python, I see that 6 file system operation are being made. All requests are for opening. I know very well what are the .py and and .pyc files. But I'm not so sure what are .pyd and .pyw, and why it's looking for a dll. Anyone can shed some light on this? Also, if I have a .pyd version of modules, will it skip the other requests? Here are the requests, in order: file directory .pyd file .dll file .py file .pyw file .pyc file Thanks Bernard From picioslug at gmail.com Tue Oct 17 17:25:56 2006 From: picioslug at gmail.com (Picio) Date: Tue, 17 Oct 2006 17:25:56 +0200 Subject: [Tutor] python applets Message-ID: <825bef0c0610170825o5d6fd169k739d8ff058ac1ff2@mail.gmail.com> Hello, I'm evaluating a way to build applets in python. Actually google told me that I can use Grail Jython Can you add/suggest other ways? The more easy to learn wins !!! thanks a lot for any answer. Picio From rabidpoobear at gmail.com Tue Oct 17 17:27:13 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 17 Oct 2006 10:27:13 -0500 Subject: [Tutor] Zipfile and File manipulation questions. In-Reply-To: <4534AAB9.40200@tds.net> References: <45321D34.60307@tds.net> <4532EEDB.9000509@pennswoods.net> <453359E9.7020708@tds.net> <4533D255.2020308@tds.net> <4534AAB9.40200@tds.net> Message-ID: <4534F651.9030803@gmail.com> Kent Johnson wrote: > Chris Hengge wrote: > >> I chose the way I used the names because to me... >> >> outFile = open(aFile.lower(), 'w') # Open output buffer for writing. >> = open a file with lowercase name for writing. >> it is implied that aFile is from the zip, since it is created in the >> loop to read the zip.. >> >> outFile.write(zFile.read(insideZip)) # Write the file. >> = write what is read from inside the zip file. >> > > This sub-thread seems to have turned into "let's beat on Chris for the > way he names things" which certainly isn't what I intended. Ultimately > it is up to the program author to use the names that he thinks > communicate most clearly. > Well, yes, and it's up to the auto mechanic to use the parts he thinks are best when he fixes your car. However, one hopes that he has training in how to determine which parts are the most durable, safest, etc, etc. Similarly, while it's up to you to choose variable names, we still hope that you know why you're choosing certain names. > But I think the actual naming was secondary to the my main point which > is that the value for 'insideZip' is read from the zip, if you assign to > that name and keep it in that name the code is easier to follow because > the value that doesn't change stays in a name that doesn't change. > > So using your names, it would read > for insideZip in zFile.namelist(): > for ext in ['.cap', '.hex', '.fru', '.cfg', '.sdr']: > if insideZip .lower().endswith(ext): > if "/" in insideZip : > aFile = aFile.rsplit('/', 1)[-1] > elif "\\" in insideZip : > aFile = aFile.rsplit('\\', 1)[-1] > else: > aFile = insideZip > > This way inzideZip is always the name from inside the zip, and aFile is > always the name of the file to write. > I think it'd be most clear if you did something like: ext = ['.cap','.hex','.fru','.cfg','.sdr'] for zipFile in zFile.namelist(): if os.path.splitext(zipFile)[-1] in ext: outFile = os.path.split(zipFile)[-1] but that's just me :) I've gone back and read your code. The problem Kent was pointing out was that your for loop was iterating over a variable called aFile, and you were changing this variable during the loop. This is generally considered Bad Practice. That's all he meant. I think. HTH, -Luke From kent37 at tds.net Tue Oct 17 17:50:51 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 17 Oct 2006 11:50:51 -0400 Subject: [Tutor] python applets In-Reply-To: <825bef0c0610170825o5d6fd169k739d8ff058ac1ff2@mail.gmail.com> References: <825bef0c0610170825o5d6fd169k739d8ff058ac1ff2@mail.gmail.com> Message-ID: <4534FBDB.5040907@tds.net> Picio wrote: > Hello, > I'm evaluating a way to build applets in python. > Actually google told me that I can use > Grail > Jython Grail is a very old, very dead project to write a web browser in Python. Your users would have to use Grail for this to work. You can write Java applets in Jython, see www.jython.org to get started. Kent From ajkadri at googlemail.com Tue Oct 17 17:58:16 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Tue, 17 Oct 2006 16:58:16 +0100 Subject: [Tutor] Help me abt this error Message-ID: I am trying to write to a file, but I am getting this errror. IOError: (0, 'Error') Can someone explain what is it and whats the solution?? Thanks. Regards, Asrar -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061017/d0f3c1c3/attachment.htm From Joel.Levine at Dartmouth.EDU Tue Oct 17 18:59:48 2006 From: Joel.Levine at Dartmouth.EDU (Joel Levine) Date: 17 Oct 2006 12:59:48 -0400 Subject: [Tutor] distribution Message-ID: <69933769@newdancer.Dartmouth.EDU> A non-text attachment was scrubbed... Name: not available Type: text/enriched Size: 474 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20061017/fdfa0801/attachment.bin From pyro9219 at gmail.com Tue Oct 17 19:03:20 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Tue, 17 Oct 2006 10:03:20 -0700 Subject: [Tutor] Zipfile and File manipulation questions. In-Reply-To: <4534F651.9030803@gmail.com> References: <4532EEDB.9000509@pennswoods.net> <453359E9.7020708@tds.net> <4533D255.2020308@tds.net> <4534AAB9.40200@tds.net> <4534F651.9030803@gmail.com> Message-ID: I find your example rather amusing, since it makes it sound like you want this fictional mechanic to pick his parts by the brand name, rather then by how well the part works (in description vs context)... Your analogy seems to push that the brand name would inherently give the descriptive name.... which is fine.. Personally.. I dont care if you call it a motor or anything else... a motor is a motor because of its functionality... not because "motor" itself has some great descriptive meaning. We only understand what motor means because its been the standard to describe the hunk of metal, rubber, and plastic under the hook of an automobile. now.. if I've never heard of a motor... I'd learn what it is be getting some basic understanding of its functionality... it wouldn't matter what you called it if I've never heard the word, I'd have to know what it does to understand what distiguishes it from a bicycle. The only exception is when new terminology isn't defined for an object, such as "motor-carriage"(still have that darn motor word that I dont understand without knowing atleast basic functionality) or "auto-mobile"...(so... is this a bike that peddles itself? and flying machine? a cellphone that beams me to work automagically at 9:00am? We call them cars? why? because its what people stuck with from "motor-'car'riage" after adapting to the new machine.. You want to add to the mess... A truck is defined as a tool to move items around... mentally, I think of something more like a wheel-barrel.. but wait.. wheel-barrels dont look like barrels... either way... poor naming =P Names are nothing more then a distinguishing mark to define something that hasn't already been defined.. Humans are great because they wrap huge functional and contextual definitions to names and dont even realise it.. Think of your own name.. if that is all I used to describe you I'd never understand what was different between you and anyone else with your name.. but when I think of "you"( aka you in context), I can list tons of stuff that makes you who you are.. Try and imagine your name if I took it completely out of context and functionality... You'd have some name more like "Brian, slacker of the eastside, teller of the great jokes, driver of the SUV, son of Marry and George, birth-father of little billy, owner of many pc's"... vs the guy that lives in another neighborhood who'd have to be named "Brian, civil servant of the eastside, impressor of women, driver of the sports car, Adopted,birth father to many across the town, owner of no pc's" if you wanted to describe someone. Rambling aside... I was just trying to take a light hearted spin because the poor mechanic we have subjected for abuse in this debate struck me funny. On 10/17/06, Luke Paireepinart wrote: > > Kent Johnson wrote: > > Chris Hengge wrote: > > > >> I chose the way I used the names because to me... > >> > >> outFile = open(aFile.lower(), 'w') # Open output buffer for writing. > >> = open a file with lowercase name for writing. > >> it is implied that aFile is from the zip, since it is created in the > >> loop to read the zip.. > >> > >> outFile.write(zFile.read(insideZip)) # Write the file. > >> = write what is read from inside the zip file. > >> > > > > This sub-thread seems to have turned into "let's beat on Chris for the > > way he names things" which certainly isn't what I intended. Ultimately > > it is up to the program author to use the names that he thinks > > communicate most clearly. > > > Well, yes, and it's up to the auto mechanic to use the parts he thinks > are best when he fixes your car. > However, one hopes that he has training in how to determine which parts > are the most durable, safest, etc, etc. > Similarly, while it's up to you to choose variable names, we still hope > that you know why you're choosing certain names. > > But I think the actual naming was secondary to the my main point which > > is that the value for 'insideZip' is read from the zip, if you assign to > > that name and keep it in that name the code is easier to follow because > > the value that doesn't change stays in a name that doesn't change. > > > > So using your names, it would read > > for insideZip in zFile.namelist(): > > for ext in ['.cap', '.hex', '.fru', '.cfg', '.sdr']: > > if insideZip .lower().endswith(ext): > > if "/" in insideZip : > > aFile = aFile.rsplit('/', 1)[-1] > > elif "\\" in insideZip : > > aFile = aFile.rsplit('\\', 1)[-1] > > else: > > aFile = insideZip > > > > This way inzideZip is always the name from inside the zip, and aFile is > > always the name of the file to write. > > > I think it'd be most clear if you did something like: > ext = ['.cap','.hex','.fru','.cfg','.sdr'] > for zipFile in zFile.namelist(): > if os.path.splitext(zipFile)[-1] in ext: > outFile = os.path.split(zipFile)[-1] > > but that's just me :) > > I've gone back and read your code. > The problem Kent was pointing out was that your for loop was iterating > over a variable called aFile, > and you were changing this variable during the loop. This is generally > considered Bad Practice. > That's all he meant. > I think. > > HTH, > -Luke > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061017/f1c04531/attachment-0001.html From pyro9219 at gmail.com Tue Oct 17 19:23:51 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Tue, 17 Oct 2006 10:23:51 -0700 Subject: [Tutor] Zipfile and File manipulation questions. In-Reply-To: <4534AAB9.40200@tds.net> References: <45321D34.60307@tds.net> <4532EEDB.9000509@pennswoods.net> <453359E9.7020708@tds.net> <4533D255.2020308@tds.net> <4534AAB9.40200@tds.net> Message-ID: I get what you are trying to say.. but I'm looking at the code after changing names, and I think it makes more sense in the code my way because of the following lines.. outFile = open(aFile.lower(), 'w') #open 'afile' named with lowercase to 'w'rite outFile.write(zFile.read(insideZip)) #write what you read 'insidezip' This is what I mean by functional names verses descriptive... Your way I'd have a better grasp of the data, my way I feel I have a better grasp of what is going on in my code. When I'm done writing my code and go back through the documentation I'll be adding all the variables used to the docstring, inputs, outputs.. all that jazz. Even if I didn't, and I'd never seen this code before, I'd try to figure out what it is doing before caring what data is being manipulated. Think about it... understanding the purpose in context will give me a better understanding of what the data going in, and coming out should appear to be, then hoping the author picked the right stuff. Perhaps I've adopted this habbit after years of trying to learn from snippets of code online where people use completely generic variable names as references, and kind of started ignoring variable names.. Seriously... its just how you look at things... I obviously read code and get my understanding very differently then many people on here. I take more of a top down approach, while it sounds many of you take a bottom up approach. On 10/17/06, Kent Johnson wrote: > > Chris Hengge wrote: > > I chose the way I used the names because to me... > > > > outFile = open(aFile.lower(), 'w') # Open output buffer for writing. > > = open a file with lowercase name for writing. > > it is implied that aFile is from the zip, since it is created in the > > loop to read the zip.. > > > > outFile.write(zFile.read(insideZip)) # Write the file. > > = write what is read from inside the zip file. > > This sub-thread seems to have turned into "let's beat on Chris for the > way he names things" which certainly isn't what I intended. Ultimately > it is up to the program author to use the names that he thinks > communicate most clearly. > > But I think the actual naming was secondary to the my main point which > is that the value for 'insideZip' is read from the zip, if you assign to > that name and keep it in that name the code is easier to follow because > the value that doesn't change stays in a name that doesn't change. > > So using your names, it would read > for insideZip in zFile.namelist(): > for ext in ['.cap', '.hex', '.fru', '.cfg', '.sdr']: > if insideZip .lower().endswith(ext): > if "/" in insideZip : > aFile = aFile.rsplit('/', 1)[-1] > elif "\\" in insideZip : > aFile = aFile.rsplit('\\', 1)[-1] > else: > aFile = insideZip > > This way inzideZip is always the name from inside the zip, and aFile is > always the name of the file to write. > > > > I guess for declaration it isn't very clear, but thats what comments are > > for? > > The comments about comments have been on the mark, I think. A helpful > guideline I use is, when I think I need a comment, look at the names I > am using and see if I can create a function whose name conveys what I > wanted to say in the comment. > > Kent > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061017/c06f9229/attachment.htm From rabidpoobear at gmail.com Tue Oct 17 19:49:48 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 17 Oct 2006 12:49:48 -0500 Subject: [Tutor] Help me abt this error In-Reply-To: References: Message-ID: <453517BC.2040208@gmail.com> Asrarahmed Kadri wrote: > I am trying to write to a file, but I am getting this errror. > > IOError: (0, 'Error') > > Can someone explain what is it and whats the solution?? No. Give us the actual source and the full traceback. Cheers, -Luke From rabidpoobear at gmail.com Tue Oct 17 19:51:44 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 17 Oct 2006 12:51:44 -0500 Subject: [Tutor] distribution In-Reply-To: <69933769@newdancer.Dartmouth.EDU> References: <69933769@newdancer.Dartmouth.EDU> Message-ID: <45351830.8030609@gmail.com> Joel Levine wrote: > I am writing code that people I work with want to pick up "instantly" > for their own machines. BUT they may be using different platforms and > different installations on those platforms. > > I'm writing on a Mac, using Python 2.4, numpy, and Tkinter. They are > using Macs and PC's, who-knows-what vintage Python, with or without > numpy, numeric, and Tkinter. > > Any suggestions for keeping my sanity? Is there something in > particular I should be reading? Use the os module a lot, and harrass them until they install numpy(or don't use it.) Feel free to use TKInter, it's part of the python distribution (Unless they have pre-1.5 or something, in which case they should upgrade anyway !) :) HTH, -Luke From dyoo at hkn.eecs.berkeley.edu Tue Oct 17 21:13:40 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 17 Oct 2006 12:13:40 -0700 (PDT) Subject: [Tutor] Help me abt this error In-Reply-To: References: Message-ID: > I am trying to write to a file, but I am getting this errror. > > IOError: (0, 'Error') > > Can someone explain what is it and whats the solution?? Hi Asrarahmed, Did you read my response from the last few days? http://mail.python.org/pipermail/tutor/2006-October/049958.html Did you find it helpful? I thought it directly addressed the question you had on: http://mail.python.org/pipermail/tutor/2006-October/049937.html If it doesn't apply, at least please mention that it didn't work for you; at least we'll be able to cross off that possibility. From rabidpoobear at gmail.com Tue Oct 17 22:43:15 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 17 Oct 2006 15:43:15 -0500 Subject: [Tutor] Help me abt this error Message-ID: <45354063.20307@gmail.com> Oops, I replied off-list. Forwarding to list. -------------- next part -------------- An embedded message was scrubbed... From: Luke Paireepinart Subject: Re: [Tutor] Help me abt this error Date: Tue, 17 Oct 2006 15:42:40 -0500 Size: 1982 Url: http://mail.python.org/pipermail/tutor/attachments/20061017/f79668a3/attachment.mht From carroll at tjc.com Tue Oct 17 23:15:44 2006 From: carroll at tjc.com (Terry Carroll) Date: Tue, 17 Oct 2006 14:15:44 -0700 (PDT) Subject: [Tutor] A puzzle for you In-Reply-To: <5e58f2e40610132348j3b06d5e9vba45f2ce6c74747d@mail.gmail.com> Message-ID: On Sat, 14 Oct 2006, John Fouhy wrote: > >From the python_dev LiveJournal community --- > > Predict the outcome of the following code: > > ## > from random import * > seed() > [choice(dict((x+1,0) for x in range(1000))) for x in range(693)][0] > ## On ActivePython 2.4.3: >>> from random import * >>> seed() >>> [choice(dict((x+1,0) for x in range(1000))) for x in range(693)][0] Traceback (most recent call last): File "", line 1, in ? File "C:\Python24\Lib\random.py", line 249, in choice return seq[int(self.random() * len(seq))] # raises IndexError if seq is empty KeyError: 0 >>> From john at fouhy.net Tue Oct 17 23:21:53 2006 From: john at fouhy.net (John Fouhy) Date: Wed, 18 Oct 2006 10:21:53 +1300 Subject: [Tutor] A puzzle for you In-Reply-To: References: <5e58f2e40610132348j3b06d5e9vba45f2ce6c74747d@mail.gmail.com> Message-ID: <5e58f2e40610171421va4eae88h54f8fc2c45ce23af@mail.gmail.com> On 18/10/06, Terry Carroll wrote: > On Sat, 14 Oct 2006, John Fouhy wrote: > > > >From the python_dev LiveJournal community --- > > > > Predict the outcome of the following code: > > > > ## > > from random import * > > seed() > > [choice(dict((x+1,0) for x in range(1000))) for x in range(693)][0] > > ## > > On ActivePython 2.4.3: > > >>> from random import * > >>> seed() > >>> [choice(dict((x+1,0) for x in range(1000))) for x in range(693)][0] > Traceback (most recent call last): > File "", line 1, in ? > File "C:\Python24\Lib\random.py", line 249, in choice > return seq[int(self.random() * len(seq))] # raises IndexError if seq is empty > KeyError: 0 > >>> Does that always happen? -- John. From ps_python at yahoo.com Tue Oct 17 23:42:28 2006 From: ps_python at yahoo.com (kumar s) Date: Tue, 17 Oct 2006 14:42:28 -0700 (PDT) Subject: [Tutor] extracting numbers from a list In-Reply-To: <5e58f2e40610161820g52af72c5m7acc780428245d9e@mail.gmail.com> Message-ID: <20061017214228.83168.qmail@web35802.mail.mud.yahoo.com> In continuation to : Re: [Tutor] extracting numbers from a list hello list I have coordinates for exons (chunks of sequence). For instance: 10 - 50 A 10 - 20 B 35 - 50 B 60 - 70 A 60 - 70 B 80 - 100 A 80 - 100 B (The above coordinates and names are easier than in dat) Here my aim is to creat chunks of exons specific to A or B. For instance: 10 - 20,35 - 50 are common to both A and B, whereas 21 - 34 is specific only to A. The desired output for me is : 10 \t 20 A,B 21 \t 34 A 35 \t 50 A,B 60 \t 70 A,B 80 \t 100 A,B I just learned python frm a friend and he is also a novice. What I could get is the break up of chunks. A problem here I am getting number different from what I need: [10, 20] [10, 50] [21, 35] [10, 50] [36, 50] [10, 50] [60, 70] [60, 70] [80, 100] [80, 100] The list next to chunks is the pairs( the longer ones). could any one help me how can I correct [21, 35],[36, 50] to 21 \t 34 , 35 \t 50. I tried chaning the indexs in function chunker, it is not working for me. Also, how can I point chunks to their names. This is the abstract example of the complex numbers and their sequence names. I want to change the simple code and then go to the complex one. Thank you very much for your valuable time. REsult: what I am getting now: [10, 20] [10, 50] [21, 35] [10, 50] [36, 50] [10, 50] [60, 70] [60, 70] [80, 100] [80, 100] My code: from sets import Set dat = ['10\t50\tA', '10\t20\tB', '35\t50\tB', '60\t70\tA', '60\t70\tB', '80\t100\tA', '80\t100\tB'] ############ # creating a dictionary with coordiates as key and NM_ as value ##### ekda = {} for j in dat: cols = j.split('\t') ekda.setdefault(cols[0]+'\t'+cols[1],[]).append(cols[2]) ###### #getting tab delim numbers only and not the A,B bat = [] for j in dat: cols = j.split('\t') bat.append(cols[0]+'\t'+cols[1]) pairs = [ map(int, x.split('\t')) for x in bat ] ##################################################################################### # this function takes pairs (from the above result)and longer blocks(exons). # For instance: # 10 - 20; 14 - 25; 19 - 30; 40 - 50; 45 - 60; 70 - 80 # a = [[10,20],[14,25],[19,30],[40,50],[45,60],[70,80]] # for j in exoner(a): # print j #The result would be: #10 - 30; 40 - 60; 70 - 80 ##################################################################################### def exoner(pairs): pairs.sort() i = iter(pairs) last = i.next() for current in i: if current[0] in xrange(last[0],last[1]): if current[1] > last[1]: last = [last[0], current[1]] else: last = [last[0],last[1]] else: yield last last = current yield last lon = exoner(pairs) ##################################################################################### ## Here I am getting all the unique numbers in dat nums = [] for j in pairs: for k in j: nums.append(k) unm = Set(nums) unums = [] for x in unm: unums.append(x) unums.sort() ##################################################################################### ### This function takes a list of numbers and breaks it in pieces ## For instance [10,15,20,25,30] #>>> i = [10,15,20,25,30] #>>> chunker(i) #[[10, 15], [16, 20], [21, 25], [26, 30]] #### def chunker(lis): res = [] res.append([lis[0],lis[1]]) for m in range(2,len(lis)): res.append([lis[m-1]+1,lis[m]]) return res #### # Here I take each pair (longer block) and roll over all the unique numbers ((unums) from dat) and check if that number is in#the range of pair, if so, I will break all those set of number in pair range into small blocks ###### gdic = {} unums.sort() for pair in exoner(pairs): x = pair[0] y = pair[1]+1 sml = [] for k in unums: if k in range(x,y): sml.append(k) else: pass for j in chunker(sml): print j,pair __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From pyro9219 at gmail.com Tue Oct 17 23:47:31 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Tue, 17 Oct 2006 14:47:31 -0700 Subject: [Tutor] Searching list items. Message-ID: contents = readlines(myfile, 'r') Ok, I'm under the impression this is a list of strings (array) How in the world do I cycle through them looking for words? for line in contents: if line.contains("something") print line Thats a mock up of what I'm looking for. I tried to figure out how to use re, but that spits out locations in memory or none it seems. Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061017/8dac5801/attachment.htm From rabidpoobear at gmail.com Tue Oct 17 23:51:11 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 17 Oct 2006 16:51:11 -0500 Subject: [Tutor] Searching list items. In-Reply-To: References: Message-ID: <4535504F.4010300@gmail.com> Chris Hengge wrote: > contents = readlines(myfile, 'r') > Ok, I'm under the impression this is a list of strings (array) Nope. No such thing as arrays in Python. It is a list of strings, that's it. :) > How in the world do I cycle through them looking for words? > > for line in contents: > if line.contains("something") > print line > > Thats a mock up of what I'm looking for. > I tried to figure out how to use re, but that spits out locations in > memory or none it seems. You'd use regular expressions or use if 'astring' in line: if your use case is simple enough for that. show us what RE you used that gave you trouble. It's hard to help when we don't know where you're getting stuck :) > > Thanks. Sure. -Luke From pyro9219 at gmail.com Tue Oct 17 23:54:14 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Tue, 17 Oct 2006 14:54:14 -0700 Subject: [Tutor] Searching list items. In-Reply-To: <4535504F.4010300@gmail.com> References: <4535504F.4010300@gmail.com> Message-ID: I remove those lines, but I was trying to use for line in contents: result = re.search("something", line) print result this printed out something like None None None hex memory address of goodness None None ... On 10/17/06, Luke Paireepinart wrote: > > Chris Hengge wrote: > > contents = readlines(myfile, 'r') > > Ok, I'm under the impression this is a list of strings (array) > Nope. No such thing as arrays in Python. > It is a list of strings, that's it. :) > > How in the world do I cycle through them looking for words? > > > > for line in contents: > > if line.contains("something") > > print line > > > > Thats a mock up of what I'm looking for. > > I tried to figure out how to use re, but that spits out locations in > > memory or none it seems. > You'd use regular expressions or use > if 'astring' in line: > > if your use case is simple enough for that. > show us what RE you used that gave you trouble. > It's hard to help when we don't know where you're getting stuck :) > > > > Thanks. > Sure. > > -Luke > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061017/a6f36bc7/attachment.html From rabidpoobear at gmail.com Tue Oct 17 23:55:33 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 17 Oct 2006 16:55:33 -0500 Subject: [Tutor] Searching list items. In-Reply-To: References: <4535504F.4010300@gmail.com> Message-ID: <45355155.6080807@gmail.com> Chris Hengge wrote: > I remove those lines, but I was trying to use > for line in contents: > result = re.search("something", line) > print result I'm pretty sure this isn't how you use regular expressions. I have to go to class right now but if no one else has replied when I get back I'll look into it. Sorry I can't help right now. -Luke > > this printed out something like > > None > None > None > hex memory address of goodness > None > None From pyro9219 at gmail.com Tue Oct 17 23:59:10 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Tue, 17 Oct 2006 14:59:10 -0700 Subject: [Tutor] Searching list items. In-Reply-To: <45355155.6080807@gmail.com> References: <4535504F.4010300@gmail.com> <45355155.6080807@gmail.com> Message-ID: An article at devshed was using it like that... but the output wasn't what I was looking for.. I was getting the hex address where the result was, but not printing the line.. I think the simple code you recommended in your first reply will do the trick, I'm not looking for anything magical, just need to see a line if it contains what I'm looking for. I'll do some more checking into regex later, looks very useful... Thanks. On 10/17/06, Luke Paireepinart wrote: > > Chris Hengge wrote: > > I remove those lines, but I was trying to use > > for line in contents: > > result = re.search("something", line) > > print result > I'm pretty sure this isn't how you use regular expressions. > I have to go to class right now but if no one else has replied when I > get back I'll look into it. > Sorry I can't help right now. > -Luke > > > > this printed out something like > > > > None > > None > > None > > hex memory address of goodness > > None > > None > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061017/417a3a3a/attachment.htm From john at fouhy.net Wed Oct 18 00:01:56 2006 From: john at fouhy.net (John Fouhy) Date: Wed, 18 Oct 2006 11:01:56 +1300 Subject: [Tutor] Searching list items. In-Reply-To: References: <4535504F.4010300@gmail.com> Message-ID: <5e58f2e40610171501l52fed2c5n84b71dab9408a71f@mail.gmail.com> On 18/10/06, Chris Hengge wrote: > I remove those lines, but I was trying to use > for line in contents: > result = re.search("something", line) > print result > > this printed out something like > > None > None > None > hex memory address of goodness > None > None If you don't need a regular expression, you are probably better off using 'in': for line in contents: if 'something' in line: print line Otherwise, re.search() and re.match() return either None or a match object. So, you can do this: for line in contents: m = re.search('something', line) if m: print line[m.start():m.end()] match objects become more powerful when you start using groups or named groups in your regular expressions. See the documentation for more :-) -- John. From dyoo at hkn.eecs.berkeley.edu Wed Oct 18 00:07:23 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 17 Oct 2006 15:07:23 -0700 (PDT) Subject: [Tutor] Searching list items. In-Reply-To: References: <4535504F.4010300@gmail.com> Message-ID: > I remove those lines, but I was trying to use > for line in contents: > result = re.search("something", line) > print result 'result' here is going to either be None, as you've seen, or a "match" object. We have several options available to use once we have a match. Take a look at a few of the methods in here: http://www.python.org/doc/lib/match-objects.html Printing a match object itself won't be too informative. What would you like to show up if there is some match? From ajkadri at googlemail.com Wed Oct 18 00:37:59 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Tue, 17 Oct 2006 23:37:59 +0100 Subject: [Tutor] Help me abt this error In-Reply-To: <453517BC.2040208@gmail.com> References: <453517BC.2040208@gmail.com> Message-ID: I changed to append mode and it is working. But the thing is that I have another problem. I am trying to insert usernames that are unique. Please look at the code and help me. import sys fd = open('usr.txt','a') def chk(str): global fd fd.seek(0,0) print fd done = 0 list1 = [] answer = True while not done: aline = fd.readline() if aline == "": done = 1 else: list1.append(aline) print list1 for i in list1: print i j = i.split(':') if str == j[0]: answer = False break return answer def make_entry(uname,passwd): global fd fd.seek(0,2) str1 = uname+':'+passwd fd.write(str1+'\n') enter_choice() def die(): sys.exit(0) def new_user(): uname = raw_input("Enter your desired username") ans = chk(uname) print ans if ans: passwd = raw_input("Enter your password") make_entry(uname,passwd) else: showerror('Login Error...','Id already taken') new_user() def display_menu(): print "-" * 30 print "Select 1 for new user:" print "Select 2 to exit" print "-" * 30 def enter_choice(): display_menu() print choice = raw_input("Enter your choice") if choice == '1': new_user() else: die() enter_choice() The problem is in the chk() function.. It is not reading the file ....The file is a txt file with colon (:) as the delimiter between username and password. I cannot understand why its not reading??? Please help... On 10/17/06, Luke Paireepinart wrote: > > Asrarahmed Kadri wrote: > > I am trying to write to a file, but I am getting this errror. > > > > IOError: (0, 'Error') > > > > Can someone explain what is it and whats the solution?? > No. > Give us the actual source and the full traceback. > Cheers, > -Luke > -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061017/14f8f1e5/attachment-0001.htm From ajkadri at googlemail.com Wed Oct 18 01:12:35 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Wed, 18 Oct 2006 00:12:35 +0100 Subject: [Tutor] My apologyRe: Help me abt this error Message-ID: I am so sorry...... if anyone felt offended.. I am a bit nervous about teh whole thing.. I am learning the language as well as i have a deadline to complete my project which is on Tkinter.. Dont mind.. I acknowledge the help from all the people out here.. Thanks. God Bless. Regards, Asrar On 10/17/06, Danny Yoo wrote: > > > I am trying to write to a file, but I am getting this errror. > > > > IOError: (0, 'Error') > > > > Can someone explain what is it and whats the solution?? > > Hi Asrarahmed, > > Did you read my response from the last few days? > > http://mail.python.org/pipermail/tutor/2006-October/049958.html > > Did you find it helpful? I thought it directly addressed the question you > had on: > > http://mail.python.org/pipermail/tutor/2006-October/049937.html > > If it doesn't apply, at least please mention that it didn't work for you; > at least we'll be able to cross off that possibility. > -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061018/d471edfb/attachment.htm From rabidpoobear at gmail.com Wed Oct 18 03:08:48 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 17 Oct 2006 20:08:48 -0500 Subject: [Tutor] Help me abt this error In-Reply-To: References: <453517BC.2040208@gmail.com> Message-ID: <45357EA0.4080108@gmail.com> Asrarahmed Kadri wrote: > > I changed to append mode and it is working. > But the thing is that I have another problem. > I am trying to insert usernames that are unique. Please look at the > code and help me. > > import sys > > fd = open('usr.txt','a') > append mode is write-only. more comments further down. > > > def chk(str): > global fd > fd.seek(0,0) > print fd > done = 0 > list1 = [] > answer = True > > while not done: > > aline = fd.readline () > > if aline == "": > done = 1 > else: > list1.append(aline) > print list1 > for i in list1: > print i > j = i.split(':') > if str == j[0]: > answer = False > break > return answer > Can I politely request that you don't add color to your functions? It makes it harder for me to read them. I know you're trying to place emphasis on which functions are giving you problems, but if you were to just comment them instead I'd be happy :) For your problem about reading the file, I would suggest that you keep the contents in memory, or read the file each time and close it, instead of trying to keep an open copy of it around and seeking and such. Since you're opening the file in append mode, you aren't able to do reads. you could use 'a+', but I don't recommend it. You'll probably run into weird behavior, and maybe only on certain inputs (I.E. scary bugs that you might not notice till your program is in use already.) HTH, -Luke From rabidpoobear at gmail.com Wed Oct 18 03:10:50 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 17 Oct 2006 20:10:50 -0500 Subject: [Tutor] My apologyRe: Help me abt this error In-Reply-To: References: Message-ID: <45357F1A.5040301@gmail.com> Asrarahmed Kadri wrote: > I am so sorry...... if anyone felt offended.. I don't think anyone was offended :) > > I am a bit nervous about teh whole thing.. I am learning the language > as well as i have a deadline to complete my project which is on Tkinter.. Why do you have a deadline? Is it a school project or a work project? They expected you to learn Python and TKInter while you had a project looming over you? That's not a good way to go about it! Well, in any case, good luck. -Luke From dyoo at hkn.eecs.berkeley.edu Wed Oct 18 03:38:16 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 17 Oct 2006 18:38:16 -0700 (PDT) Subject: [Tutor] followup on python cookies/sessions (fwd) Message-ID: ---------- Forwarded message ---------- Date: Mon, 16 Oct 2006 14:19:53 -0700 (PDT) From: anil maran To: Danny Yoo Subject: followup on python cookies/sessions Dear Danny My login code looks like this for session and cookie i dont know how to combine both and save session id in cookie, SESSION CODE class login: @checkaccess() def GET(self): web.render('login.html') @checkaccess() def POST(self): user = web.storify({ 'id':1, 'username':'mark', 'password':'userss', 'groups':'admin' }) inp = web.input() if inp.username == user.username and inp.password == user.password: dologin(user) web.redirect('/') else: web.render('login.html') class logout: @checkaccess() def GET(self): dologout() web.redirect('/') class login: @checkaccess() def GET(self): web.render('login.html') @checkaccess() def POST(self): user = web.storify({ 'id':1, 'username':'anil', 'password':'toper', 'groups':'admin' }) inp = web.input() if inp.username == user.username and inp.password == user.password: dologin(user) web.redirect('/') else: web.render('login.html') class logout: @checkaccess() def GET(self): dologout() web.redirect('/') COOKIE CODE def check_password(raw_password, enc_password): """ Returns a boolean of whether the raw_password was correct. Handles encryption formats behind the scenes. """ algo, salt, hsh = enc_password.split('$') if algo == 'sha1': return hsh == sha.new(salt+raw_password).hexdigest() elif algo == 'md5': import md5 return hsh == md5.new(salt+raw_password).hexdigest() raise ValueError, "Got unknown password algorithm type in password." class login: def POST(self): login = web.input() thisuser = web.query('select * from users where email = $login.email', vars=locals()) if thisuser: thisuser = thisuser[0] if login.email== thisuser.email and check_password(login.passwd, thisuser.password): web.setcookie('username', thisuser.email) else: web.setcookie('rss_flash_message', 'Please try again with correct email and password') web.redirect('/') class logout: def GET(self): web.setcookie('username', '') web.redirect('/') Please help me out thanks Anil Anil From pine508 at hotmail.com Wed Oct 18 04:17:50 2006 From: pine508 at hotmail.com (Pine Marten) Date: Tue, 17 Oct 2006 22:17:50 -0400 Subject: [Tutor] Tutor Digest, Vol 32, Issue 72 In-Reply-To: Message-ID: (in reference to a question I had about how to simply save the content of a textCtrl to a text file) >#Okay, here is the function we need to change. > > > def OnSaveButton(self, event): > #from John's save(event) function: > # > #savefile = open(self.filename, 'w') > #savefile.write(myTextBox.GetValue()) > #savefile.close() > > savefile = open('test.txt','w') > #if you don't want 'test.txt' try using a variable. > > > savefile.write(self.textCtrl1.GetValue()) > #textCtrl1 is an attribute of your Frame1 class. > > > > savefile.close() > #then we just save it. > >Do you understand which parts of John's examples were changed and why? >Hope That Helps, >-Luke I tried it and it did work this time, thanks so much. Your effort may keep me trying bit by bit to gain a little profiency. And yes, I believe I see how much of this ought to work now. I am just going to keep going over how one assigns a variable like savefile to a built in function like open() but then attaches a method to it such as when you write savefile.write. I think if I work with that enough I will come to see it as intuitive; for now it still is unintuitive. Thanks again. _________________________________________________________________ Stay in touch with old friends and meet new ones with Windows Live Spaces http://clk.atdmt.com/MSN/go/msnnkwsp0070000001msn/direct/01/?href=http://spaces.live.com/spacesapi.aspx?wx_action=create&wx_url=/friends.aspx&mkt=en-us From dyoo at hkn.eecs.berkeley.edu Wed Oct 18 04:23:25 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 17 Oct 2006 19:23:25 -0700 (PDT) Subject: [Tutor] extracting numbers from a list In-Reply-To: <20061016211835.76058.qmail@web35815.mail.mud.yahoo.com> References: <20061016211835.76058.qmail@web35815.mail.mud.yahoo.com> Message-ID: On Mon, 16 Oct 2006, kumar s wrote: > I have a simple question to ask tutors: > > list A : > > a = [10,15,18,20,25,30,40] Hi Kumar, If you're concerned about correctness, I'd recommend that you try thinking about the problem inductively. An inductive definition for what you're asking is straightforward to state in about three or four lines of code. I'll try to go through it slowly so you see what the reasoning behind it is. The code sketch above uses a technique that you should already know called "mathematical induction." http://en.wikipedia.org/wiki/Mathematical_induction Let's say we're designing a function called getSpans(). Here are some sample behavior we'd like from it: getSpans([10, 15]) = [(10, 15)] getSpans([10, 15, 18]) = [(10, 15), (16, 18)] getSpans([10, 15, 18, 20]) = [(10, 15), (16, 18), (19, 20)] Would you agree that this is reasonable output for a function like this? getSpans() takes a list of numbers, and returns a list of pairs of numbers. There is one "base" case to this problem. The smallest list we'd like to consider is a list of two elements. If we see that, then we're happy, because the answer is really simple: getSpans([a, b]) = [(a, b)] Otherwise, let's imagine a list that's a bit longer, with three elements. Concretely, we know that this is going to look like: getSpans([a, b, c]) = [(a, b), (b+1, c)] But another way to say this, though is that: getSpans([a, b, c]) = [(a, b)] + getSpans([b+1, c]) That is, we try to restate the problem in terms of smaller subproblems. Let's look at what the case for four elements might look like: getSpans([a, b, c, d]) = [(a, b), (b+1, c), (c+1, d)] Concretely, we know that that's the list of spans we'd like to see. But if we think about it, we might also restate this as: getSpans([a, b, c, d]) = [a, b] + getSpans([b+1, c, d]) because getSpans([b+1, c, d]) is going to give us: [(b+1, c), (c+1, d)] All we need to do is add on [(a, b)] to that to get the complete answer to getSpans([a, b, c, d]). Generally, for any particular list L that's longer than two elements: getExons(L) = [L[0:2]] + getExons([L[1] + 1] + L[2:]) When we work inductively, all we really need to think about is "base case" and "inductive case": the solution will often just fall through from stating those two cases. An inductively-designed function is going to look something like: def solve(input): if input looks like a base-case: handle that directly in a base-case way else: break up the problem into smaller pieces that we assume can be solve()d by induction The inductive definition above is slightly inefficient because we're doing physical list slicing. Rewriting it to use loops and list indicies instead of slicing is a little harder, but not much harder. Another example: how do we add up a list of numbers? If there's just one number, that must be the sum. Otherwise, we can add up the first number to the sum of the rest of the numbers. ################################# def mysum(L): if len(L) == 1: return L[0] else: return L[0] + mysum(L[1:]) ################################# It's a funky way of doing this, but this is a real definition that works (modulo limits in Python's recursion implementation). It's inefficient, but it's easy to state and reason about. I'm assuming you're more interested in correctness than efficiency at the moment. Get it correct first, then if you really need to, work to get it fast. From rabidpoobear at gmail.com Wed Oct 18 06:14:32 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 17 Oct 2006 23:14:32 -0500 Subject: [Tutor] Tutor Digest, Vol 32, Issue 72 In-Reply-To: References: Message-ID: <4535AA28.3050805@gmail.com> > I tried it and it did work this time, thanks so much. Your effort may keep > me trying bit by bit to gain a little profiency. > I'm glad that you're not going to give up just yet! Don't worry, I have much more effort in store for you :) > And yes, I believe I see how much of this ought to work now. I am just > going to keep going over how one assigns a variable like savefile to a built > in function like open() but then attaches a method to it such as when you > write savefile.write. I think if I work with that enough I will come to see > it as intuitive; for now it still is unintuitive. Thanks again. > Okay, I think I can explain this :) Starting from the beginning: a variable is a name that refers to an object. it's nothing more than this. It can refer to any type of object, a class, a class instance, a class method, a function, a class attribute, a list, a tuple, whatever. It's just a way that the programmer can tie a name to an object so it can be used later. A function is a collection of expressions. There are different types of functions. This is what they do: Takes zero to many inputs, and returns (outputs) one object. Takes zero to many inputs, and modifies something outside of the function. Takes zero to many inputs, and modifies something outside of the function, and returns (outputs) one object. The first kind is the most conventional function. The second kind is called a null or void function, because it doesn't return anything. The point of these functions are their side-effects. The third kind is something that you should avoid, which is a function that has side-effects as well as a return. Here are examples of these: #first type def add_five(aNumber): return aNumber + 5 #second type def append_five(aList): aList.append(5) #third type def append_and_add_five(aList): aList.append(5) return aList[0] + 5 #--------------- And testing them: >>> add_five(5) 10 >>> a_list = [1,2,3,4] >>> append_five(a_list) >>> print a_list [1,2,3,4,5] >>> a_list = [1,2,3,4] >>> append_and_add_five(a_list) 6 >>> print a_list [1,2,3,4,5] #------------- Some things to note: You have a list a_list in the global scope that has the value [1,2,3,4]. when you pass it to the append_five function as 'aList', and then print it out, a_list is [1,2,3,4,5]. This is because python doesn't pass _copies_ of variables to functions, it passes what that variable is referring to, UNLESS the variable is immutable (you can't change it.) For immutable variables, a new object will be created to contain the value. This only makes a difference with lists, because lists are mutable. A good way to rationalize this: #since integers are immutable, these actually refer to two separate copies of an int object containing a 5. >>> a = b = 5 >>> a += 5 >>> a 10 >>> b 5 #since lists are mutable, these refer to the same object. >>> a = b = ['hello,'] >>> a.append('world!') >>> a ['hello,','world!'] >>> b ['hello,','world!'] So think of it like this: aVariable = 1 def aFunction(anotherVariable): print anotherVariable #... other useful stuff.... When you make the call aFunction(aVariable) what's happening is this: anotherVariable = aVariable print anotherVariable # ---- other useful stuff ----- It's slightly more complicated than this, (namespaces and such), but that's the main idea. so this example: aList = [1,2,3,4] def aFunction(anotherList): print anotherList #... other useful stuff .... when you make the call aFunction(aList) it's doing anotherList = aList print anotherList # --- other useful stuff ---- and as we saw above, if you do a = b, and b = a list, then a is the SAME list, not a COPY of that list. Hope that makes sense. Also, note that 'print' is in itself a side-effect, because it's modifying things that are outside the function, so if you have a function printing things, you shouldn't have that function return anything. Or so I've been told after a year of Computer Science courses :) The reason I explained this is to hopefully make the next section I'll explain more clear. >going to keep going over how one assigns a variable like savefile to a built >in function like open() but then attaches a method to it such as when you >write savefile.write. I think if I work with that enough I will come to see >it as intuitive; for now it still is unintuitive. Thanks again. Okay, you're thinking of this in the wrong way. #given this definition, def aFunction(a): print a >>> myFunction = aFunction >>> myFunction >>> aFunction That is what assigning a variable to a function looks like. What I was doing was something completely different. >>> myFunction = aFunction('hello') #notice the parenthesis! hello Do you see what the difference is? Because functions are objects, you can assign variables to them if you want! You can do a = b= c= d= e= aFunction and call all of these the same way. However, they are just references to the function (remember, we talked about references earlier?) Generally, we don't care about the function itself, but what it _returns_ or what its side-effects are. So when I type myFunction = aFunction('hello') a temporary variable (we'll call it temp for easy explanation, but it's called something different) is created, containing the string 'hello.' temp = 'hello' then the aFunction is called, which results in a = temp print a (this isn't really what's happening, but it's close) so when I say something like this: >>> f = open('filename.txt') what's happening is that the function 'open' is doing all its stuff and creating an object that contains the information for the file, and returns it. Remember, whenever there are parenthesis, it's a function call, we're not assigning a variable to refer to a function itself. You can see this pretty clearly by outputting f. >>> f If we were assigning f to be the actual function 'open', you'd see something similar to what we saw before. >>> f = open >>> f The reason it doesn't say "function 'open' at 0x009....." is because it's a built-in, but the premise is the same. So I'll take you through my code again, this time explaining what's happening now that I know what you're struggling with. > def OnSaveButton(self, event): Just ignore this, we don't care about any of this stuff. > savefile = open('test.txt','w') What this is doing is (to explain in human terms) talking to the function named 'open' and saying "please go get all the information for this file for me, and give me a bunch of methods that deal with it, because I don't want to have to deal with the nitty-gritty of reading and writing files at the operating-system level." 'open' gladly obliges, and constructs some object. if we were to do 'print savefile' right now, we'd get this is an object that has many methods that 'open' has been nice enough to create for us that help us deal with files. we can figure out which methods it has by doing a directory listing, much like you'd do on an OS. >>> dir(savefile) and we get: ['__class__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__', '__iter__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'close', 'closed', 'encoding', 'fileno', 'flush', 'isatty', 'mode', 'name', 'newlines', 'next', 'read', 'readinto', 'readline', 'readlines', 'seek', 'softspace', 'tell', 'truncate', 'write', 'writelines', 'xreadlines'] as you can see, one of these methods that the class instance (object) has is the write method. So now that we know it's available to us, > savefile.write(self.textCtrl1.GetValue()) This line is a little complex. Let's break it up to make it easier to read. textBox = self.textCtrl1 even though self.textCtrl1 is a method of the current class instance (which is what self means) we can still assign a variable to it. text = textBox.GetValue() this will give us everything that's in the textBox (which is self.textCtrl1 also) and make a string object that contains the text. then it'll point the variable named 'text' to this object so we don't lose it and so we can use the data later. savefile.write(text) this will output the text that we just got into the file. > savefile.close() Another one of those methods that the file object has, if you go look, is 'close'. When you close a file, it flushes the buffer and such, and unlocks it can be deleted and stuff. You should always close your files, just in case, even if it's at the end of a program. Well, that was a bit of a long-winded response, and I hope I didn't confuse you further, but of course anywhere that I was just completely incoherent, just point it out and I'll try to explain it more proficiently. :D Also, have you tried working through Alan Gauld's tutorial? I'm sure he explains these concepts much better than I do ;) Good luck with the Python! -Luke From pyro9219 at gmail.com Wed Oct 18 06:29:42 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Tue, 17 Oct 2006 21:29:42 -0700 Subject: [Tutor] Searching list items. In-Reply-To: References: <4535504F.4010300@gmail.com> Message-ID: Not sure if you were challenging me to think, or asking me, but I was wanting to "line" to be printed... as in the string from the list. What I got with re was what I'm assuming was a memory address. On 10/17/06, Danny Yoo wrote: > > > > > I remove those lines, but I was trying to use > > for line in contents: > > result = re.search("something", line) > > print result > > 'result' here is going to either be None, as you've seen, or a "match" > object. We have several options available to use once we have a > match. Take a look at a few of the methods in here: > > http://www.python.org/doc/lib/match-objects.html > > Printing a match object itself won't be too informative. What would you > like to show up if there is some match? > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061017/6bb5929b/attachment.html From bgailer at alum.rpi.edu Wed Oct 18 07:19:03 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Tue, 17 Oct 2006 22:19:03 -0700 Subject: [Tutor] A puzzle for you In-Reply-To: <5e58f2e40610132348j3b06d5e9vba45f2ce6c74747d@mail.gmail.com> References: <5e58f2e40610132348j3b06d5e9vba45f2ce6c74747d@mail.gmail.com> Message-ID: <4535B947.6040504@alum.rpi.edu> John Fouhy wrote: > >From the python_dev LiveJournal community --- > > Predict the outcome of the following code: > > ## > from random import * > seed() > [choice(dict((x+1,0) for x in range(1000))) for x in range(693)][0] > ## > > Well the discussion did not go very far! You got my "prediction" and one execution. It appears that (despite the docs) a dict is OK as an argument. choice uses len() to get the # of elements, picks a number between 0 and len()-1, and uses [] to access the chosen element. len() and [] both work with dicts. So you have built a dict of 1000 items with keys between 1 and 1000, all values 0. Then you have give choice 693 tries to pick a key value other than 0. One 0 raises a key not found exception. No 0s raises no exception and the expression returns 0. -- Bob Gailer 510-978-4454 From rabidpoobear at gmail.com Wed Oct 18 07:50:06 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 18 Oct 2006 00:50:06 -0500 Subject: [Tutor] Searching list items. In-Reply-To: References: <4535504F.4010300@gmail.com> Message-ID: <4535C08E.7040501@gmail.com> Chris Hengge wrote: > Not sure if you were challenging me to think, or asking me, but I was > wanting to "line" to be printed... as in the string from the list. > What I got with re was what I'm assuming was a memory address. What you got was an object. If you try to print an object, all you get is the name of the object and the memory address of the object. def aFunction(): print 'hi' >>> x = aFunction >>> print x This is pretty useless, as Danny said. what you want to do is actually use the object. >>> x() hi or without the intermediate variable: >>> aFunction() hi When you do a re search, you get a match object, which has methods such as... well, Danny already gave you the site. > > match. Take a look at a few of the methods in here: > > http://www.python.org/doc/lib/match-objects.html > > Does this explanation help? so if you just want to print the line, all you would do is check whether the re.search() call returned None or a match object. As John Fouhy said: for line in contents: m = re.search('something', line) if m: print line[m.start():m.end()] This example prints the portion of the line that matched the string you're searching for. if you just want to print the line if it matches, simply change the last line in the example to 'print line'. note that the line 'if m' could be rewritten 'if m != None:' Or even (this may be Too Much Magic, so beware ;) ) 'if m is not None' For more advanced matching, you can actually use the match object that is returned. but if you're just searching for a substring, then this will work. Another good reason to use regular expressions is if you wanted to find, say, the substring 'substring' with a 2-digit number on the end, you'd have to do something like substrs = ['substring'+str(a).zfill(2) for a in range(0,100)] then for item in substrs: if item in line: print line Whereas with a regular expression, you'd just do regexp = re.compile('something\d\d') then if regexp.search(line): print line Computationally the last example should be much more efficient. clearly it's also more complicated if you don't know regular expressions very well. However, the substrs example is not too great either when it comes to readability. HTH, -Luke From janos.juhasz at VELUX.com Wed Oct 18 17:14:28 2006 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Wed, 18 Oct 2006 17:14:28 +0200 Subject: [Tutor] regexp help needed Message-ID: Dear All, I have a problem about the EDI invoices created by our erp system. I have to make a small correction on them, just before sending them by ftp. The problem is that, the big numbers are printed with thousand separator. U:\ediout\INVOIC\Backup>grep \...., *.doc File 063091.doc: MOALIN 203 79.524,480 DKK4 PRI YYY 1.095,130 1 PC MOATOT 79 594.629,400 DKK4 File 063092.doc: MOALIN 203 47.281,680 DKK4 MOATOT 86 56.738,016 DKK4 MOATOT 79 47.281,680 DKK4 I have to remove the thousand separator by moving the numbers before it to right. So the number and char groups has to be left in their original position. I have to make this kind of changes on the problematic lines: MOATOT 79 47.281,680 DKK4 MOATOT 79 47281,680 DKK4 I have no idea how to make it :( ______________________________ J?nos Juh?sz From pine508 at hotmail.com Wed Oct 18 18:09:32 2006 From: pine508 at hotmail.com (Pine Marten) Date: Wed, 18 Oct 2006 12:09:32 -0400 Subject: [Tutor] Tutor Digest, Vol 32, Issue 72 In-Reply-To: <4535AA28.3050805@gmail.com> Message-ID: >I'm glad that you're not going to give up just yet! Don't worry, I have >much more effort in store for you :) [long and useful description of some basics of Python deleted] Wow, thanks very much! That was extremely useful. I had some time late last night when it was quiet here and I could just read through it, and I wound up making a little more progress, making the filename a variable which was named based on the current date (had to figure out to import the datetime module and how to use that), and also made the save button clear the textbox using Clear(). I'll no doubt encounter more confusions and the train of understanding may still be in the station, but it lurched forward a bit due to your explanations! Thanks! -PM _________________________________________________________________ Add a Yahoo! contact to Windows Live Messenger for a chance to win a free trip! http://www.imagine-windowslive.com/minisites/yahoo/default.aspx?locale=en-us&hmtagline From sgilja at email.t-com.hr Wed Oct 18 19:49:08 2006 From: sgilja at email.t-com.hr (Stanko) Date: Wed, 18 Oct 2006 19:49:08 +0200 Subject: [Tutor] characters in python Message-ID: <45366914.1080405@email.t-com.hr> Can python handle this characters: ?, ?, ?, ?, ?? If can, How? And how to change tab spaceing in idle? I tried in idle properties. I have set it to 4 character but it's still 8. Thanks! From ps_python at yahoo.com Wed Oct 18 20:52:11 2006 From: ps_python at yahoo.com (kumar s) Date: Wed, 18 Oct 2006 11:52:11 -0700 (PDT) Subject: [Tutor] extracting numbers from a list In-Reply-To: Message-ID: <20061018185212.45133.qmail@web35810.mail.mud.yahoo.com> Thank you Danny. I am going over your email and trying to understand (i am a biologist with bioinformatics training). I am not sure if I got your opinion about the way I solved. do you mean that there is something wrong with the way i solved it. I am not sure If I explained the problem correctly in terms of exons, transcripts. If not I would be happy to send you a pdf file with a figure. Thanks again. --- Danny Yoo wrote: > > > On Mon, 16 Oct 2006, kumar s wrote: > > > I have a simple question to ask tutors: > > > > list A : > > > > a = [10,15,18,20,25,30,40] > > > Hi Kumar, > > If you're concerned about correctness, I'd recommend > that you try thinking > about the problem inductively. An inductive > definition for what you're > asking is straightforward to state in about three or > four lines of code. > I'll try to go through it slowly so you see what the > reasoning behind it > is. The code sketch above uses a technique that you > should already know > called "mathematical induction." > > > http://en.wikipedia.org/wiki/Mathematical_induction > > > Let's say we're designing a function called > getSpans(). Here are some > sample behavior we'd like from it: > > getSpans([10, 15]) = [(10, 15)] > getSpans([10, 15, 18]) = [(10, 15), (16, 18)] > getSpans([10, 15, 18, 20]) = [(10, 15), (16, > 18), (19, 20)] > > Would you agree that this is reasonable output for a > function like this? > getSpans() takes a list of numbers, and returns a > list of pairs of > numbers. > > > There is one "base" case to this problem. The > smallest list we'd like to > consider is a list of two elements. If we see that, > then we're happy, > because the answer is really simple: > > getSpans([a, b]) = [(a, b)] > > > Otherwise, let's imagine a list that's a bit longer, > with three elements. > Concretely, we know that this is going to look like: > > getSpans([a, b, c]) = [(a, b), (b+1, c)] > > But another way to say this, though is that: > > getSpans([a, b, c]) = [(a, b)] + getSpans([b+1, > c]) > > That is, we try to restate the problem in terms of > smaller subproblems. > > > > Let's look at what the case for four elements might > look like: > > getSpans([a, b, c, d]) = [(a, b), (b+1, c), > (c+1, d)] > > Concretely, we know that that's the list of spans > we'd like to see. But > if we think about it, we might also restate this as: > > getSpans([a, b, c, d]) = [a, b] + > getSpans([b+1, c, d]) > > because getSpans([b+1, c, d]) is going to give us: > > [(b+1, c), (c+1, d)] > > All we need to do is add on [(a, b)] to that to get > the complete answer to > getSpans([a, b, c, d]). > > > Generally, for any particular list L that's longer > than two elements: > > getExons(L) = [L[0:2]] + getExons([L[1] + 1] + > L[2:]) > > When we work inductively, all we really need to > think about is "base case" > and "inductive case": the solution will often just > fall through from > stating those two cases. An inductively-designed > function is going to > look something like: > > def solve(input): > if input looks like a base-case: > handle that directly in a base-case way > else: > break up the problem into smaller > pieces > that we assume can be solve()d by > induction > > The inductive definition above is slightly > inefficient because we're doing > physical list slicing. Rewriting it to use loops > and list indicies > instead of slicing is a little harder, but not much > harder. > > Another example: how do we add up a list of numbers? > If there's just one > number, that must be the sum. Otherwise, we can add > up the first number > to the sum of the rest of the numbers. > > ################################# > def mysum(L): > if len(L) == 1: > return L[0] > else: > return L[0] + mysum(L[1:]) > ################################# > > It's a funky way of doing this, but this is a real > definition that works > (modulo limits in Python's recursion > implementation). It's inefficient, > but it's easy to state and reason about. I'm > assuming you're more > interested in correctness than efficiency at the > moment. Get it correct > first, then if you really need to, work to get it > fast. > __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From kent37 at tds.net Wed Oct 18 20:55:05 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 18 Oct 2006 14:55:05 -0400 Subject: [Tutor] regexp help needed In-Reply-To: References: Message-ID: <45367889.5030607@tds.net> J?nos Juh?sz wrote: > Dear All, > > I have a problem about the EDI invoices created by our erp system. > I have to make a small correction on them, just before sending them by > ftp. > > The problem is that, the big numbers are printed with thousand separator. > > U:\ediout\INVOIC\Backup>grep \...., *.doc > File 063091.doc: > MOALIN 203 79.524,480 DKK4 > PRI YYY 1.095,130 1 PC > MOATOT 79 594.629,400 DKK4 > File 063092.doc: > MOALIN 203 47.281,680 DKK4 > MOATOT 86 56.738,016 DKK4 > MOATOT 79 47.281,680 DKK4 > > I have to remove the thousand separator by moving the numbers before it to > right. > So the number and char groups has to be left in their original position. > > I have to make this kind of changes on the problematic lines: > MOATOT 79 47.281,680 DKK4 > MOATOT 79 47281,680 DKK4 > > I have no idea how to make it :( Break it up into smaller problems: for each line in the data: break the line up into fields fix the field containing the amount rebuild the line You don't really have to make a regex for the whole line. re.split() is useful for splitting the line and preserving the whitespace so you can rebuild the line with the same format. Kent From rabidpoobear at gmail.com Wed Oct 18 21:04:06 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 18 Oct 2006 14:04:06 -0500 Subject: [Tutor] characters in python In-Reply-To: <45366914.1080405@email.t-com.hr> References: <45366914.1080405@email.t-com.hr> Message-ID: <45367AA6.1000407@gmail.com> Stanko wrote: > Can python handle this characters: ?, ?, ?, ?, ?? > If can, How? > Unicode strings. > And how to change tab spaceing in idle? I tried in idle properties. I > have set it to 4 character but it's still 8. > The default is 4. If it's 8, find out who changed it and ask them to change it back. It seems to me like the indentation configuration doesn't work in Configure IDLE... , so google it and you can probably find info on it, as other people probably have noticed this error before (if it is in fact an error in IDLE and not a human error :) > Thanks! > You're welcome! From rabidpoobear at gmail.com Wed Oct 18 21:15:04 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 18 Oct 2006 14:15:04 -0500 Subject: [Tutor] Tutor Digest, Vol 32, Issue 72 In-Reply-To: References: Message-ID: <45367D38.1030009@gmail.com> >> I'm glad that you're not going to give up just yet! Don't worry, I >> have much more effort in store for you :) > [long and useful description of some basics of Python deleted] > > Wow, thanks very much! That was extremely useful. I had some time > late last night when it was quiet here and I could just read through > it, and I wound up making a little more progress, making the filename > a variable which was named based on the current date (had to figure > out to import the datetime module and how to use that), and also made > the save button clear the textbox using Clear(). Yay! Glad it helped. sounds like you're getting along :) > > I'll no doubt encounter more confusions and the train of understanding > may still be in the station, but it lurched forward a bit due to your > explanations! Thanks! That's why we are here. We love to hear about your happiness when it "All Makes Sense" :D From sgilja at email.t-com.hr Wed Oct 18 21:35:39 2006 From: sgilja at email.t-com.hr (Stanko) Date: Wed, 18 Oct 2006 21:35:39 +0200 Subject: [Tutor] characters in python In-Reply-To: <45366914.1080405@email.t-com.hr> References: <45366914.1080405@email.t-com.hr> Message-ID: <4536820B.4040807@email.t-com.hr> I tried with unicode strings, but nothing. It says : unsoported characters From rabidpoobear at gmail.com Wed Oct 18 21:39:47 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 18 Oct 2006 14:39:47 -0500 Subject: [Tutor] characters in python In-Reply-To: <4536820B.4040807@email.t-com.hr> References: <45366914.1080405@email.t-com.hr> <4536820B.4040807@email.t-com.hr> Message-ID: <45368303.7010802@gmail.com> Stanko wrote: > I tried with unicode strings, but nothing. It says : unsoported characters > Perhaps you could give us the code you were using? > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From dyoo at hkn.eecs.berkeley.edu Wed Oct 18 22:18:14 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 18 Oct 2006 13:18:14 -0700 (PDT) Subject: [Tutor] extracting numbers from a list In-Reply-To: <20061018185212.45133.qmail@web35810.mail.mud.yahoo.com> References: <20061018185212.45133.qmail@web35810.mail.mud.yahoo.com> Message-ID: On Wed, 18 Oct 2006, kumar s wrote: > I am not sure if I got your opinion about the way I solved. Hi Kumar, I was replying to your question: http://mail.python.org/pipermail/tutor/2006-October/050064.html in which you showed a program that had problems. I'm assuming that you haven't figured out what's wrong with the code in your post. I've presented an approach that shows how one might try to approach the problem without being brilliant. Did you understand every step in the program in: http://mail.python.org/pipermail/tutor/2006-October/050121.html or was there something there that you didn't understand? If so, please ask for clarification, because everything there should have been approachable to you. > do you mean that there is something wrong with the way i solved it. Well... how do I put this gently? Your program doesn't work, so I can't really give a positive or negative opinion about its effectiveness until it does. I can sorta see what the code tries to do, but it's going about it in a complicated fashion. I can give my opinion that: ################### fx = a[0] fy = a[1] b = a[2:] ai = iter(b) last = ai.next() for j in ai: print fy+1,last last = j ################### seems to be juggling too many variables, too much state. I think the conceptual bug here is that the code fumbles around, trying to do something toward a goal, but it loses intentionality. I don't understand the intent of 'fx', since that variable is never used. I don't understand the expression 'fy+1' in the print statement, since 'fy' never changes. There's just a lot of little small things there that seem irrelevant to the problem at hand. I haven't tried to fix your program; rather, I've tried to show you an approach that can systematic attack these kinds of problems without much trouble. The problem I see that you've been having is that you're getting stuck as soon as the complexity of a problem reaches a threshold. I'm trying to show you techniques to compensate when problems get hard. I could just as easily have just fixed the above code, but how would this really help you? For you, it would be as if I just pulled that program out of thin air! But just to satisfy you, such a program would have looked like this: ################# x = a[0] for y in a[1:]: print x, y x = y + 1 ################# The relationship between this and your original program is somewhat there. But again, if I just showed this to you, how does that really help you to program better? The program here is written to conserve memory, but at the expense of being harder to develop, understand, and explain. And, if I were doing this as a computer scientist, I'd have to develop a loop invariant argument to feel satisfied that it was doing the right thing. In comparison, the inductive definition has the force of a proof behind it. > I am not sure If I explained the problem correctly in terms of exons, > transcripts. If not I would be happy to send you a pdf file with a > figure. That's ok. I don't think it is necessary as long as you clearly explain the problem you're trying to solve. You should be able to communicate what you're trying to do. (And just as background: I've worked in the past as a bioinformatician at arabidopsis.org. The terminology that you've been using has not been an issue.) From janos.juhasz at VELUX.com Wed Oct 18 22:48:33 2006 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Wed, 18 Oct 2006 22:48:33 +0200 Subject: [Tutor] regexp help needed In-Reply-To: Message-ID: Hi Kent, thanks your respond. > > I have to remove the thousand separator by moving the numbers before it to > > right. > > So the number and char groups has to be left in their original position. > > > > I have to make this kind of changes on the problematic lines: > > MOATOT 79 47.281,680 DKK4 > > MOATOT 79 47281,680 DKK4 > > > > I have no idea how to make it :( > Break it up into smaller problems: > for each line in the data: > break the line up into fields > fix the field containing the amount > rebuild the line > > You don't really have to make a regex for the whole line. re.split() is > useful for splitting the line and preserving the whitespace so you can > rebuild the line with the same format. > Kent I can't find the way to preserve the whitespace at split. But I found a way to use regexp. import re # this is a group of numbers, followed by a dot, followed by 3 numerics and a comma pat = re.compile(r'(\d+)\.(\d{3},)') def replace_thousand_separator(line): # when the '.' removed a space has to be prepended return re.sub(pat, r' \1\2', line) for file in glob.glob('*.doc'): lines = open(file, 'r').readlines() lines = [replace_thousand_separator(line) for line in lines] open(file, 'wt').writelines(lines) Yours sincerely, ______________________________ Janos Juhasz From gigs at hi.t-com.hr Wed Oct 18 23:11:41 2006 From: gigs at hi.t-com.hr (Gigs_) Date: Wed, 18 Oct 2006 23:11:41 +0200 Subject: [Tutor] characters in python In-Reply-To: <45366914.1080405@email.t-com.hr> References: <45366914.1080405@email.t-com.hr> Message-ID: <4536988D.2040604@hi.t-com.hr> here is the code: def changer(): """Changer from Serbian to Croatian for this letters: ?, ?, ? in ?, ?, ? """ whatfile = raw_input('Enter location of your file: ') # open and read file ofile = open(whatfile, 'r') S = ofile.read() ofile.close() # search file and replace ?, ? in ?, ? for i in S: S = S.replace('?', '?') S = S.replace('?', '?') S = S.replace('?', '?') # open and write to file infile = open(whatfile, 'w') infile.write(S) infile.close() I attached file too. -------------- next part -------------- A non-text attachment was scrubbed... Name: literalschanger.rar Type: application/octet-stream Size: 431 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20061018/d5d22dd8/attachment.obj From hugonz-lists at h-lab.net Wed Oct 18 23:43:49 2006 From: hugonz-lists at h-lab.net (Hugo Gonzalez M) Date: Wed, 18 Oct 2006 16:43:49 -0500 Subject: [Tutor] characters in python In-Reply-To: <45368303.7010802@gmail.com> References: <45366914.1080405@email.t-com.hr> <4536820B.4040807@email.t-com.hr> <45368303.7010802@gmail.com> Message-ID: <4536A015.1050403@h-lab.net> >> I tried with unicode strings, but nothing. It says : unsoported characters >> They are supported. Are you using them literally in your code? Anything other than ASCII or Latin-1 needs to be declared explicitly at the start of the source code file. Maybe you can use UTF-8 encoding. See: http://www.python.org/dev/peps/pep-0263/ Hugo Luke Paireepinart wrote: > Stanko wrote: > Perhaps you could give us the code you were using? >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From gigs at hi.t-com.hr Thu Oct 19 00:04:22 2006 From: gigs at hi.t-com.hr (Gigs_) Date: Thu, 19 Oct 2006 00:04:22 +0200 Subject: [Tutor] characters in python In-Reply-To: <4536A015.1050403@h-lab.net> References: <45366914.1080405@email.t-com.hr><4536820B.4040807@email.t-com.h r> <45368303.7010802@gmail.com> <4536A015.1050403@h-lab.net> Message-ID: <4536A4E6.3050205@hi.t-com.hr> Hugo Gonzalez M wrote: > >> I tried with unicode strings, but nothing. It says : unsoported > characters > >> > > They are supported. Are you using them literally in your code? Anything > other than ASCII or Latin-1 needs to be declared explicitly at the start > of the source code file. > > Maybe you can use UTF-8 encoding. > > See: > http://www.python.org/dev/peps/pep-0263/ > > Hugo > > Thanks man its working with UTF-8 encoding From alan.gauld at btinternet.com Thu Oct 19 00:16:35 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 18 Oct 2006 23:16:35 +0100 Subject: [Tutor] characters in python References: <45366914.1080405@email.t-com.hr> <4536988D.2040604@hi.t-com.hr> Message-ID: "Gigs_" wrote in message > here is the code: So where do you think you tell Python that you are using unicode strings? I'm no expert but I think, as a minimum you need: for i in S: S = S.replace(u'?', u'?') S = S.replace(u'?', u'?') S = S.replace(u'?', u'?') You might also need to specify a locale/encoding, but I'm not sure about that... BTW THere is a translate() somewhere function in Python that might enable you to do all the translations in one step. You specify a set of characters to translate and the corresponding translations. Sounds a lot like what you want - if it works with unicode... Regards, Alan G. From pyro9219 at gmail.com Thu Oct 19 01:15:07 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Wed, 18 Oct 2006 16:15:07 -0700 Subject: [Tutor] Location of found item in list. Message-ID: I'm looking for a way to do the following. for item in limitedLineList: if item in directoryList: print match.ljust(20) + limitedLineList[count].ljust(20) + directoryList[count].ljust(20) else: print fail.ljust(20) + limitedLineList[count].ljust(20) + directoryList[count].ljust(20) os.rename(pathName + directoryList[count], pathName + limitedLineList[count]) count = count + 1 Where I have underlined, needs to be the item from the directoryList, and I'm unable to find a way to return that. The code is actually doing what I want correctly, (cheated a test by hand changing variables), but I need to find the directory location. Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061018/d00f7f09/attachment.htm From pyro9219 at gmail.com Thu Oct 19 02:18:08 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Wed, 18 Oct 2006 17:18:08 -0700 Subject: [Tutor] Location of found item in list. In-Reply-To: References: Message-ID: Still no progress with this myself. For clarification if I didn't provide enough earlier, for item in list1: if item in list2: print item and list[object at location where matched item] <-- need this location. On 10/18/06, Chris Hengge wrote: > > I'm looking for a way to do the following. > > for item in limitedLineList: > if item in directoryList: > print match.ljust(20) + limitedLineList[count].ljust(20) + > directoryList[ count].ljust(20) > else: > print fail.ljust(20) + limitedLineList[count].ljust(20) + > directoryList[count].ljust(20) > os.rename(pathName + directoryList[ count], pathName + > limitedLineList[count]) > count = count + 1 > > Where I have underlined, needs to be the item from the directoryList, and > I'm unable to find a way to return that. > > The code is actually doing what I want correctly, (cheated a test by hand > changing variables), but I need to find the directory location. > > Thanks. > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061018/d68773ef/attachment.htm From pyro9219 at gmail.com Thu Oct 19 02:27:57 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Wed, 18 Oct 2006 17:27:57 -0700 Subject: [Tutor] Location of found item in list. In-Reply-To: References: Message-ID: What that should have said For clarification if I didn't provide enough earlier, for item in list1: if item in list2: print item and list2[object that matched item] <-- need this location. On 10/18/06, Chris Hengge wrote: > > Still no progress with this myself. > > For clarification if I didn't provide enough earlier, > for item in list1: > if item in list2: > print item and list[object at location where matched item] <-- > need this location. > > On 10/18/06, Chris Hengge wrote: > > > > I'm looking for a way to do the following. > > > > for item in limitedLineList: > > if item in directoryList: > > print match.ljust(20) + limitedLineList[count].ljust(20) + > > directoryList[ count].ljust(20) > > else: > > print fail.ljust(20) + limitedLineList[count].ljust(20) + > > directoryList[count].ljust(20) > > os.rename(pathName + directoryList[ count], pathName + > > limitedLineList[count]) > > count = count + 1 > > > > Where I have underlined, needs to be the item from the directoryList, > > and I'm unable to find a way to return that. > > > > The code is actually doing what I want correctly, (cheated a test by > > hand changing variables), but I need to find the directory location. > > > > Thanks. > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061018/ef7c13b6/attachment-0001.html From kent37 at tds.net Thu Oct 19 02:38:37 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 18 Oct 2006 20:38:37 -0400 Subject: [Tutor] Location of found item in list. In-Reply-To: References: Message-ID: <4536C90D.3040704@tds.net> Chris Hengge wrote: > Still no progress with this myself. > > For clarification if I didn't provide enough earlier, > for item in list1: > if item in list2: > print item and list[object at location where matched item] <-- > need this location. I still don't understand your question. If you want the index in list2 of the item that matches, use list2.find(item). If you want to enumerate over a list and have the list indices available as well as the list values, use enumerate() e.g. for i, item in enumerate(list1): # i is the index of item in list1 Kent > > On 10/18/06, *Chris Hengge* > wrote: > > I'm looking for a way to do the following. > > for item in limitedLineList: > if item in directoryList: > print match.ljust(20) + limitedLineList[count].ljust(20) > + directoryList[ count].ljust(20) > else: > print fail.ljust(20) + limitedLineList[count].ljust(20) > + directoryList[count].ljust(20) > os.rename(pathName + directoryList[ count], pathName + > limitedLineList[count]) > count = count + 1 > > Where I have underlined, needs to be the item from the > directoryList, and I'm unable to find a way to return that. > > The code is actually doing what I want correctly, (cheated a test by > hand changing variables), but I need to find the directory location. > > Thanks. > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From john at fouhy.net Thu Oct 19 02:37:33 2006 From: john at fouhy.net (John Fouhy) Date: Thu, 19 Oct 2006 13:37:33 +1300 Subject: [Tutor] Location of found item in list. In-Reply-To: References: Message-ID: <5e58f2e40610181737j322c7d4es8fc759f9c84f0447@mail.gmail.com> On 19/10/06, Chris Hengge wrote: > What that should have said > > For clarification if I didn't provide enough earlier, > for item in list1: > if item in list2: > print item and list2[object that matched item] <-- need this > location. Um, I'm still a bit confused. Suppose item == list2[10]. Does that mean you want to print item and list2[10]? Won't that just mean you print item twice? You can find the position of an element in a list by using the list.index() method, but I'm still not sure exactly what you're trying to do here. -- John. From pyro9219 at gmail.com Thu Oct 19 02:48:47 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Wed, 18 Oct 2006 17:48:47 -0700 Subject: [Tutor] Location of found item in list. In-Reply-To: <4536C90D.3040704@tds.net> References: <4536C90D.3040704@tds.net> Message-ID: Tried your first suggestion. AttributeError: 'list' object has no attribute 'find' Perhaps a better explanation... for word in paragraph: if word in sentence: print word + sentence Assume that the word is only used once per paragraph. I can't figure out how to tell it to print the right sentence (using this example) because python does the search internally and doesn't seem to have a way to return the list location where the match occurred. On 10/18/06, Kent Johnson wrote: > > Chris Hengge wrote: > > Still no progress with this myself. > > > > For clarification if I didn't provide enough earlier, > > for item in list1: > > if item in list2: > > print item and list[object at location where matched item] <-- > > need this location. > > I still don't understand your question. If you want the index in list2 > of the item that matches, use list2.find(item). > > If you want to enumerate over a list and have the list indices available > as well as the list values, use enumerate() e.g. > for i, item in enumerate(list1): > # i is the index of item in list1 > > Kent > > > > > On 10/18/06, *Chris Hengge* > > wrote: > > > > I'm looking for a way to do the following. > > > > for item in limitedLineList: > > if item in directoryList: > > print match.ljust(20) + limitedLineList[count].ljust(20) > > + directoryList[ count].ljust(20) > > else: > > print fail.ljust(20) + limitedLineList[count].ljust(20) > > + directoryList[count].ljust(20) > > os.rename(pathName + directoryList[ count], pathName + > > limitedLineList[count]) > > count = count + 1 > > > > Where I have underlined, needs to be the item from the > > directoryList, and I'm unable to find a way to return that. > > > > The code is actually doing what I want correctly, (cheated a test by > > hand changing variables), but I need to find the directory location. > > > > Thanks. > > > > > > > > ------------------------------------------------------------------------ > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061018/53714d26/attachment.html From pyro9219 at gmail.com Thu Oct 19 02:54:53 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Wed, 18 Oct 2006 17:54:53 -0700 Subject: [Tutor] Location of found item in list. In-Reply-To: References: <4536C90D.3040704@tds.net> Message-ID: The point of this script is to read a text file that has a bunch of code that calls external files. Then read the directory where all the files are.. I build a list from the text file (this works correct), and I build a list from the directory (this works correct). I want to print out the result of a match.. Here is sample output. Tested: Textname: DirectoryName: Match! a.exe a.exe Fail! A.exe a.exe My program works, it will find where they match and where they dont, but I can't get the darn thing to output the correct item to the 3rd column because: if item in list: does not return the list location, so I can't write it out to the screen. On 10/18/06, Chris Hengge wrote: > > Tried your first suggestion. > AttributeError: 'list' object has no attribute 'find' > > Perhaps a better explanation... > > > for word in paragraph: > if word in sentence: > print word + sentence > > Assume that the word is only used once per paragraph. > > I can't figure out how to tell it to print the right sentence (using this > example) because python does the search internally and doesn't seem to have > a way to return the list location where the match occurred. > > > On 10/18/06, Kent Johnson wrote: > > > > Chris Hengge wrote: > > > Still no progress with this myself. > > > > > > For clarification if I didn't provide enough earlier, > > > for item in list1: > > > if item in list2: > > > print item and list[object at location where matched item] > > <-- > > > need this location. > > > > I still don't understand your question. If you want the index in list2 > > of the item that matches, use list2.find(item). > > > > If you want to enumerate over a list and have the list indices available > > > > as well as the list values, use enumerate() e.g. > > for i, item in enumerate(list1): > > # i is the index of item in list1 > > > > Kent > > > > > > > > On 10/18/06, *Chris Hengge* < pyro9219 at gmail.com > > > > wrote: > > > > > > I'm looking for a way to do the following. > > > > > > for item in limitedLineList: > > > if item in directoryList: > > > print match.ljust(20) + > > limitedLineList[count].ljust(20) > > > + directoryList[ count].ljust(20) > > > else: > > > print fail.ljust(20) + > > limitedLineList[count].ljust(20) > > > + directoryList[count].ljust(20) > > > os.rename(pathName + directoryList[ count], pathName + > > > limitedLineList[count]) > > > count = count + 1 > > > > > > Where I have underlined, needs to be the item from the > > > directoryList, and I'm unable to find a way to return that. > > > > > > The code is actually doing what I want correctly, (cheated a test > > by > > > hand changing variables), but I need to find the directory > > location. > > > > > > Thanks. > > > > > > > > > > > > > > ------------------------------------------------------------------------ > > > > > > _______________________________________________ > > > Tutor maillist - Tutor at python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061018/4b576563/attachment.htm From kent37 at tds.net Thu Oct 19 02:58:07 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 18 Oct 2006 20:58:07 -0400 Subject: [Tutor] Location of found item in list. In-Reply-To: References: <4536C90D.3040704@tds.net> Message-ID: <4536CD9F.7050200@tds.net> Chris Hengge wrote: > Tried your first suggestion. > AttributeError: 'list' object has no attribute 'find' Sorry, it's index() not find(). Strings have both but lists only have index() > > Perhaps a better explanation... > > > for word in paragraph: > if word in sentence: > print word + sentence > > Assume that the word is only used once per paragraph. Still not clear - the above looks like it would actually run. > > I can't figure out how to tell it to print the right sentence (using > this example) because python does the search internally and doesn't seem > to have a way to return the list location where the match occurred. There is only one sentence in the above example. I think you want index(). If not, maybe you could show a small sample of the data and the result you want. > > > On 10/18/06, *Kent Johnson* > wrote: > > Chris Hengge wrote: > > Still no progress with this myself. > > > > For clarification if I didn't provide enough earlier, > > for item in list1: > > if item in list2: > > print item and list[object at location where matched > item] <-- > > need this location. > > I still don't understand your question. If you want the index in list2 > of the item that matches, use list2.find(item). > > If you want to enumerate over a list and have the list indices > available > as well as the list values, use enumerate() e.g. > for i, item in enumerate(list1): > # i is the index of item in list1 > > Kent > > > > > On 10/18/06, *Chris Hengge* < pyro9219 at gmail.com > > > >> wrote: > > > > I'm looking for a way to do the following. > > > > for item in limitedLineList: > > if item in directoryList: > > print match.ljust(20) + > limitedLineList[count].ljust(20) > > + directoryList[ count].ljust(20) > > else: > > print fail.ljust(20) + > limitedLineList[count].ljust(20) > > + directoryList[count].ljust(20) > > os.rename(pathName + directoryList[ count], > pathName + > > limitedLineList[count]) > > count = count + 1 > > > > Where I have underlined, needs to be the item from the > > directoryList, and I'm unable to find a way to return that. > > > > The code is actually doing what I want correctly, (cheated a > test by > > hand changing variables), but I need to find the directory > location. > > > > Thanks. > > > > > > > > > ------------------------------------------------------------------------ > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From rabidpoobear at gmail.com Thu Oct 19 02:59:22 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 18 Oct 2006 19:59:22 -0500 Subject: [Tutor] Location of found item in list. In-Reply-To: References: <4536C90D.3040704@tds.net> Message-ID: <4536CDEA.10909@gmail.com> Chris Hengge wrote: > The point of this script is to read a text file that has a bunch of > code that calls external files. Then read the directory where all the > files are.. I build a list from the text file (this works correct), > and I build a list from the directory (this works correct). I want to > print out the result of a match.. > > Here is sample output. > Tested: Textname: DirectoryName: > Match! a.exe a.exe > Fail! A.exe a.exe ok, so you have a text file of filenames. f = file('test.txt','r') textnames = f.readlines() f.close() and you have a directory listing import os dirnames = os.listdir('.') what you want to do is find matches. so, for item1 in textnames: for item2 in dirnames: if item1 == item2: print "Match! %s and %s" % (item1, item2) Why even try to use the 'in' syntax if it's not working correctly? Maybe I still don't understand. -Luke From john at fouhy.net Thu Oct 19 03:05:06 2006 From: john at fouhy.net (John Fouhy) Date: Thu, 19 Oct 2006 14:05:06 +1300 Subject: [Tutor] Location of found item in list. In-Reply-To: References: <4536C90D.3040704@tds.net> Message-ID: <5e58f2e40610181805g794a6d22le3f1d1d03c06608f@mail.gmail.com> On 19/10/06, Chris Hengge wrote: > The point of this script is to read a text file that has a bunch of code > that calls external files. Then read the directory where all the files are.. > I build a list from the text file (this works correct), and I build a list > from the directory (this works correct). I want to print out the result of a > match.. > > Here is sample output. > Tested: Textname: DirectoryName: > Match! a.exe a.exe > Fail! A.exe a.exe for filename in Textname: try: print '%s found in DirectoryName at position %d' % (filename, DirectoryName.index(filename)) except ValueError: print '%s not found in DirectoryName.' % filename ? From pyro9219 at gmail.com Thu Oct 19 03:07:14 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Wed, 18 Oct 2006 18:07:14 -0700 Subject: [Tutor] Location of found item in list. In-Reply-To: <4536CDEA.10909@gmail.com> References: <4536C90D.3040704@tds.net> <4536CDEA.10909@gmail.com> Message-ID: > > Why even try to use the 'in' syntax if it's not working correctly? > Maybe I still don't understand. > -Luke > Because I've been up for 40 hours... 5 days of the week I'm up at 8:45AM and I dont get home until 10PM, once I'm home, I do homework trying to finish my senior year, on the weekends I am either trying to catch up on lost work time from classes I have to go to across town, or I'm working on my senior project. =P That, and I'm running tests on 14 servers(at work), and only look at this code when I'm between tasks because they refuse to hire another intern to do this job, so I'm basically trying to balance two jobs, school.. and on occassion I try to find time for my spouce.. =P -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061018/264b7f5e/attachment.html From pyro9219 at gmail.com Thu Oct 19 03:25:29 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Wed, 18 Oct 2006 18:25:29 -0700 Subject: [Tutor] Location of found item in list. In-Reply-To: <4536CD9F.7050200@tds.net> References: <4536C90D.3040704@tds.net> <4536CD9F.7050200@tds.net> Message-ID: Ok the example I gave here wasn't written as I had it in my head.. you are right, the example only had 1 sentence. Inputs: List1 ['a.exe','b.exe',c.exe'] List2 ['A.exe',B.eXe',c.EXE'] for item in List1: if item in List2: print item + " " + list2thing that matched. I can't force to upper or lower, that would break the already working code.. Its just this darn output for list2 that isn't working. I tried the suggested list.index(item) but that wont work if there isn't a match. Right now my code works when there is a match, and if there isnt'... It also works for renaming the actual file to match the file call from the document. I'm about to take the display out, since I dont honestly care that it works, but now that I've been working with it I'm being stubborn and want the darn thing to show me =P On 10/18/06, Kent Johnson wrote: > > Chris Hengge wrote: > > Tried your first suggestion. > > AttributeError: 'list' object has no attribute 'find' > > Sorry, it's index() not find(). Strings have both but lists only have > index() > > > > Perhaps a better explanation... > > > > > > for word in paragraph: > > if word in sentence: > > print word + sentence > > > > Assume that the word is only used once per paragraph. > > Still not clear - the above looks like it would actually run. > > > > I can't figure out how to tell it to print the right sentence (using > > this example) because python does the search internally and doesn't seem > > to have a way to return the list location where the match occurred. > > There is only one sentence in the above example. > > I think you want index(). If not, maybe you could show a small sample of > the data and the result you want. > > > > > > On 10/18/06, *Kent Johnson* > > wrote: > > > > Chris Hengge wrote: > > > Still no progress with this myself. > > > > > > For clarification if I didn't provide enough earlier, > > > for item in list1: > > > if item in list2: > > > print item and list[object at location where matched > > item] <-- > > > need this location. > > > > I still don't understand your question. If you want the index in > list2 > > of the item that matches, use list2.find(item). > > > > If you want to enumerate over a list and have the list indices > > available > > as well as the list values, use enumerate() e.g. > > for i, item in enumerate(list1): > > # i is the index of item in list1 > > > > Kent > > > > > > > > On 10/18/06, *Chris Hengge* < pyro9219 at gmail.com > > > > > >> wrote: > > > > > > I'm looking for a way to do the following. > > > > > > for item in limitedLineList: > > > if item in directoryList: > > > print match.ljust(20) + > > limitedLineList[count].ljust(20) > > > + directoryList[ count].ljust(20) > > > else: > > > print fail.ljust(20) + > > limitedLineList[count].ljust(20) > > > + directoryList[count].ljust(20) > > > os.rename(pathName + directoryList[ count], > > pathName + > > > limitedLineList[count]) > > > count = count + 1 > > > > > > Where I have underlined, needs to be the item from the > > > directoryList, and I'm unable to find a way to return that. > > > > > > The code is actually doing what I want correctly, (cheated a > > test by > > > hand changing variables), but I need to find the directory > > location. > > > > > > Thanks. > > > > > > > > > > > > > > > ------------------------------------------------------------------------ > > > > > > _______________________________________________ > > > Tutor maillist - Tutor at python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061018/b2d7102f/attachment.htm From pyro9219 at gmail.com Thu Oct 19 03:34:54 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Wed, 18 Oct 2006 18:34:54 -0700 Subject: [Tutor] Location of found item in list. In-Reply-To: References: Message-ID: For all who dont get what I'm trying to do... I've bolded what needs to change... This is the code...wanted result of the comparisons works, but I am unable to display correctly.. count = 0 for item in limitedLineList: if item in directoryList: print match.ljust(20) + item.ljust(20) + item.ljust(20) else: print fail.ljust(20) + item.ljust(20) + item.ljust(20) #os.rename(pathName + item, pathName + limitedLineList[count]) count = count + 1 This is a pretty capture of the real output this script provides... (its formatted on the screen, but drops when I past here) Tested: File Name: Directory Name: Fail! SL_39.sdr SL_39.sdr Match! PSL_MBD5.FRU PSL_MBD5.FRU Match! XSL_MBD3.FRU XSL_MBD3.FRU Match! RA_MBD4.FRU RA_MBD4.FRU Match! XVN_MBD3.FRU XVN_MBD3.FRU Match! P_R24BP.FRU P_R24BP.FRU Match! P_R26BP.FRU P_R26BP.FRU Match! P_R24BPE.FRU P_R24BPE.FRU Match! P_R26BPE.FRU P_R26BPE.FRU Match! S_R24BP.FRU S_R24BP.FRU Match! S_R26BP.FRU S_R26BP.FRU Match! S_R24BPE.FRU S_R24BPE.FRU Match! S_R26BPE.FRU S_R26BPE.FRU Ok, I bolded the line that is my example. 3rd column should say SL_39.SDR (because I just changed it to that so it would flag as failed) if you look at my code for both match and fail, I printed item... (just to make the darn thing work for now) the 3rd column needs to be the value from the 2nd list (directoryList) This list item is what I can't get to print. If I uncomment the underlined line of my script, it will infact rename the lowercase extension to uppercase, as it should. On 10/18/06, Chris Hengge wrote: > > I'm looking for a way to do the following. > > for item in limitedLineList: > if item in directoryList: > print match.ljust(20) + limitedLineList[count].ljust(20) + > directoryList[ count].ljust(20) > else: > print fail.ljust(20) + limitedLineList[count].ljust(20) + > directoryList[count].ljust(20) > os.rename(pathName + directoryList[ count], pathName + > limitedLineList[count]) > count = count + 1 > > Where I have underlined, needs to be the item from the directoryList, and > I'm unable to find a way to return that. > > The code is actually doing what I want correctly, (cheated a test by hand > changing variables), but I need to find the directory location. > > Thanks. > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061018/213829da/attachment.html From rabidpoobear at gmail.com Thu Oct 19 03:34:52 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 18 Oct 2006 20:34:52 -0500 Subject: [Tutor] Location of found item in list. In-Reply-To: References: <4536C90D.3040704@tds.net> <4536CD9F.7050200@tds.net> Message-ID: <4536D63C.8070606@gmail.com> Chris Hengge wrote: > Ok the example I gave here wasn't written as I had it in my head.. you > are right, the example only had 1 sentence. > > Inputs: > List1 ['a.exe','b.exe',c.exe'] > List2 ['A.exe',B.eXe',c.EXE'] > > for item in List1: > if item in List2: > print item + " " + list2thing that matched. > > I can't force to upper or lower, that would break the already working > code.. > > Its just this darn output for list2 that isn't working. > > I tried the suggested list.index(item) but that wont work if there > isn't a match. Well, yeah, but it won't go into the if statement if there isn't a match so what does that matter? > Right now my code works when there is a match, and if there isnt'... > It also works for renaming the actual file to match the file call from > the document. > > I'm about to take the display out, since I dont honestly care that it > works, but now that I've been working with it I'm being stubborn and > want the darn thing to show me =P Did you try my example yet? It should work just fine. just iterate over both of the lists... for item1 in List1: for item2 in List2: if item1 == item2: #this is equivalent to 'if item1 in List2' except will match ALL occurrences of item1 in List2. if you want to only match the first, add a break. print item1+ ' ' + item2 From kent37 at tds.net Thu Oct 19 03:38:35 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 18 Oct 2006 21:38:35 -0400 Subject: [Tutor] Location of found item in list. In-Reply-To: References: <4536C90D.3040704@tds.net> <4536CD9F.7050200@tds.net> Message-ID: <4536D71B.7030107@tds.net> Chris Hengge wrote: > Ok the example I gave here wasn't written as I had it in my head.. you > are right, the example only had 1 sentence. > > Inputs: > List1 ['a.exe','b.exe',c.exe'] > List2 ['A.exe',B.eXe',c.EXE'] > > for item in List1: > if item in List2: > print item + " " + list2thing that matched. But the list2thing that matched is the same as item! In this example nothing will match because nothing in list1 is also in list2. I still don't have a clue what you want. > > I can't force to upper or lower, that would break the already working > code.. > > Its just this darn output for list2 that isn't working. > > I tried the suggested list.index(item) but that wont work if there isn't > a match. It raises an exception if there is no match, but you want to print only if there is a match. John Fouhy showed how to catch the exception. I'm done guessing what you want. If you can't state the problem so I can understand it I give up. Kent > Right now my code works when there is a match, and if there isnt'... > It also works for renaming the actual file to match the file call from > the document. > > I'm about to take the display out, since I dont honestly care that it > works, but now that I've been working with it I'm being stubborn and > want the darn thing to show me =P > > On 10/18/06, *Kent Johnson* > wrote: > > Chris Hengge wrote: > > Tried your first suggestion. > > AttributeError: 'list' object has no attribute 'find' > > Sorry, it's index() not find(). Strings have both but lists only have > index() > > > > Perhaps a better explanation... > > > > > > for word in paragraph: > > if word in sentence: > > print word + sentence > > > > Assume that the word is only used once per paragraph. > > Still not clear - the above looks like it would actually run. > > > > I can't figure out how to tell it to print the right sentence (using > > this example) because python does the search internally and > doesn't seem > > to have a way to return the list location where the match occurred. > > There is only one sentence in the above example. > > I think you want index(). If not, maybe you could show a small sample of > the data and the result you want. > > > > > > On 10/18/06, *Kent Johnson* < kent37 at tds.net > >> wrote: > > > > Chris Hengge wrote: > > > Still no progress with this myself. > > > > > > For clarification if I didn't provide enough earlier, > > > for item in list1: > > > if item in list2: > > > print item and list[object at location where matched > > item] <-- > > > need this location. > > > > I still don't understand your question. If you want the index > in list2 > > of the item that matches, use list2.find(item). > > > > If you want to enumerate over a list and have the list indices > > available > > as well as the list values, use enumerate() e.g. > > for i, item in enumerate(list1): > > # i is the index of item in list1 > > > > Kent > > > > > > > > On 10/18/06, *Chris Hengge* < pyro9219 at gmail.com > > > > > > > > >>> wrote: > > > > > > I'm looking for a way to do the following. > > > > > > for item in limitedLineList: > > > if item in directoryList: > > > print match.ljust(20) + > > limitedLineList[count].ljust(20) > > > + directoryList[ count].ljust(20) > > > else: > > > print fail.ljust(20) + > > limitedLineList[count].ljust(20) > > > + directoryList[count].ljust(20) > > > os.rename(pathName + directoryList[ count], > > pathName + > > > limitedLineList[count]) > > > count = count + 1 > > > > > > Where I have underlined, needs to be the item from the > > > directoryList, and I'm unable to find a way to return > that. > > > > > > The code is actually doing what I want correctly, > (cheated a > > test by > > > hand changing variables), but I need to find the directory > > location. > > > > > > Thanks. > > > > > > > > > > > > > > > ------------------------------------------------------------------------ > > > > > > _______________________________________________ > > > Tutor maillist - Tutor at python.org > > > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From pyro9219 at gmail.com Thu Oct 19 03:44:24 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Wed, 18 Oct 2006 18:44:24 -0700 Subject: [Tutor] Location of found item in list. In-Reply-To: <4536D71B.7030107@tds.net> References: <4536C90D.3040704@tds.net> <4536CD9F.7050200@tds.net> <4536D71B.7030107@tds.net> Message-ID: I just replied to my original thread with output and real working code and bolding and underlined items all over the place.. I dont see what is so hard to explain... Please refer to that post, so I dont end up just copying and pasting. On 10/18/06, Kent Johnson wrote: > > Chris Hengge wrote: > > Ok the example I gave here wasn't written as I had it in my head.. you > > are right, the example only had 1 sentence. > > > > Inputs: > > List1 ['a.exe','b.exe',c.exe'] > > List2 ['A.exe',B.eXe',c.EXE'] > > > > for item in List1: > > if item in List2: > > print item + " " + list2thing that matched. > > But the list2thing that matched is the same as item! In this example > nothing will match because nothing in list1 is also in list2. I still > don't have a clue what you want. > > > > I can't force to upper or lower, that would break the already working > > code.. > > > > Its just this darn output for list2 that isn't working. > > > > I tried the suggested list.index(item) but that wont work if there isn't > > a match. > > It raises an exception if there is no match, but you want to print only > if there is a match. John Fouhy showed how to catch the exception. > > I'm done guessing what you want. If you can't state the problem so I can > understand it I give up. > > Kent > > > Right now my code works when there is a match, and if there isnt'... > > It also works for renaming the actual file to match the file call from > > the document. > > > > I'm about to take the display out, since I dont honestly care that it > > works, but now that I've been working with it I'm being stubborn and > > want the darn thing to show me =P > > > > On 10/18/06, *Kent Johnson* > > wrote: > > > > Chris Hengge wrote: > > > Tried your first suggestion. > > > AttributeError: 'list' object has no attribute 'find' > > > > Sorry, it's index() not find(). Strings have both but lists only > have > > index() > > > > > > Perhaps a better explanation... > > > > > > > > > for word in paragraph: > > > if word in sentence: > > > print word + sentence > > > > > > Assume that the word is only used once per paragraph. > > > > Still not clear - the above looks like it would actually run. > > > > > > I can't figure out how to tell it to print the right sentence > (using > > > this example) because python does the search internally and > > doesn't seem > > > to have a way to return the list location where the match > occurred. > > > > There is only one sentence in the above example. > > > > I think you want index(). If not, maybe you could show a small > sample of > > the data and the result you want. > > > > > > > > > On 10/18/06, *Kent Johnson* < kent37 at tds.net > > > >> wrote: > > > > > > Chris Hengge wrote: > > > > Still no progress with this myself. > > > > > > > > For clarification if I didn't provide enough earlier, > > > > for item in list1: > > > > if item in list2: > > > > print item and list[object at location where > matched > > > item] <-- > > > > need this location. > > > > > > I still don't understand your question. If you want the index > > in list2 > > > of the item that matches, use list2.find(item). > > > > > > If you want to enumerate over a list and have the list > indices > > > available > > > as well as the list values, use enumerate() e.g. > > > for i, item in enumerate(list1): > > > # i is the index of item in list1 > > > > > > Kent > > > > > > > > > > > On 10/18/06, *Chris Hengge* < pyro9219 at gmail.com > > > > > > > > > > > > >>> wrote: > > > > > > > > I'm looking for a way to do the following. > > > > > > > > for item in limitedLineList: > > > > if item in directoryList: > > > > print match.ljust(20) + > > > limitedLineList[count].ljust(20) > > > > + directoryList[ count].ljust(20) > > > > else: > > > > print fail.ljust(20) + > > > limitedLineList[count].ljust(20) > > > > + directoryList[count].ljust(20) > > > > os.rename(pathName + directoryList[ > count], > > > pathName + > > > > limitedLineList[count]) > > > > count = count + 1 > > > > > > > > Where I have underlined, needs to be the item from the > > > > directoryList, and I'm unable to find a way to return > > that. > > > > > > > > The code is actually doing what I want correctly, > > (cheated a > > > test by > > > > hand changing variables), but I need to find the > directory > > > location. > > > > > > > > Thanks. > > > > > > > > > > > > > > > > > > > > > > ------------------------------------------------------------------------ > > > > > > > > _______________________________________________ > > > > Tutor maillist - Tutor at python.org > > > > > > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > > > > > > _______________________________________________ > > > Tutor maillist - Tutor at python.org > > > > > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > > > > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061018/cb8b03d5/attachment.htm From rabidpoobear at gmail.com Thu Oct 19 03:46:49 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 18 Oct 2006 20:46:49 -0500 Subject: [Tutor] Location of found item in list. In-Reply-To: References: <4536C90D.3040704@tds.net> <4536CD9F.7050200@tds.net> <4536D71B.7030107@tds.net> Message-ID: <4536D909.6060504@gmail.com> Chris Hengge wrote: > I just replied to my original thread with output and real working code > and bolding and underlined items all over the place.. I dont see what > is so hard to explain... > > Please refer to that post, so I dont end up just copying and pasting. Please refer to my post so I can at least get confirmation that you received it, whether or not you read it. KTHXBYE. :) -Luke From pyro9219 at gmail.com Thu Oct 19 03:47:21 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Wed, 18 Oct 2006 18:47:21 -0700 Subject: [Tutor] Location of found item in list. In-Reply-To: <4536D63C.8070606@gmail.com> References: <4536C90D.3040704@tds.net> <4536CD9F.7050200@tds.net> <4536D63C.8070606@gmail.com> Message-ID: Yes, I tried what you suggested, I've changed my looping structure to this: count = 0 for itemLine in lineList: for itemDirectory in directoryList: if itemLine == itemDirectory: print match.ljust(20) + itemLine.ljust(20) + itemDirectory.ljust(20) else: print fail.ljust(20) + itemLine.ljust(20) + itemDirectory.ljust(20) #os.rename(pathName + item, pathName + LineList[count]) count = count + 1 I'm just trying to figure out where to put the break(s), but I need to verify this is working since I'll be using it to rename files.. my old structure did EXACTLY what I wanted (I replied to my original post with more details and screen captures) as far as renaming the files.. but the display was screwed up. On 10/18/06, Luke Paireepinart wrote: > > Chris Hengge wrote: > > Ok the example I gave here wasn't written as I had it in my head.. you > > are right, the example only had 1 sentence. > > > > Inputs: > > List1 ['a.exe','b.exe',c.exe'] > > List2 ['A.exe',B.eXe',c.EXE'] > > > > for item in List1: > > if item in List2: > > print item + " " + list2thing that matched. > > > > I can't force to upper or lower, that would break the already working > > code.. > > > > Its just this darn output for list2 that isn't working. > > > > I tried the suggested list.index(item) but that wont work if there > > isn't a match. > Well, yeah, but it won't go into the if statement if there isn't a > match so what does that matter? > > Right now my code works when there is a match, and if there isnt'... > > It also works for renaming the actual file to match the file call from > > the document. > > > > I'm about to take the display out, since I dont honestly care that it > > works, but now that I've been working with it I'm being stubborn and > > want the darn thing to show me =P > Did you try my example yet? > It should work just fine. > just iterate over both of the lists... > for item1 in List1: > for item2 in List2: > if item1 == item2: #this is equivalent to 'if item1 in List2' > except will match ALL occurrences of item1 in List2. if you want to > only match the first, add a break. > print item1+ ' ' + item2 > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061018/68414210/attachment.html From Christopher.Hatherly at anu.edu.au Thu Oct 19 03:48:18 2006 From: Christopher.Hatherly at anu.edu.au (Christopher Hatherly) Date: Thu, 19 Oct 2006 11:48:18 +1000 Subject: [Tutor] Best GUI toolkit? Message-ID: Hi Pythonistas, I'm a newbie. I've worked through some introductory python books, and feel that I now understand the logic on the coding side enough to make the application I'm after. However I'm now trying to turn my code into a (fairly complex) graphical app, and have found both Tkinter and wxPython to be much more complex than perhaps they need to be (at least for the beginner. Or perhaps I just haven't yet found a good, easy to follow tutorial???) I read somewhere that BoaConstructor was a good alternative. I installed and had a look, and it seems promising. Just wondering if anyone could pass on any advice before I leap into it though. Specifically, my app needs full-screen display of lots of very simple bitmaps with precise control over display timing (synchronising with vertical refresh etc). Any advice much appreciated. Thanks Chris From rabidpoobear at gmail.com Thu Oct 19 03:48:37 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 18 Oct 2006 20:48:37 -0500 Subject: [Tutor] Location of found item in list. In-Reply-To: References: <4536C90D.3040704@tds.net> <4536CD9F.7050200@tds.net> <4536D63C.8070606@gmail.com> Message-ID: <4536D975.10502@gmail.com> Chris Hengge wrote: > Yes, I tried what you suggested, I've changed my looping structure to > this: > > count = 0 > for itemLine in lineList: > for itemDirectory in directoryList: > if itemLine == itemDirectory: > print match.ljust(20) + itemLine.ljust(20) + > itemDirectory.ljust(20) > else: > print fail.ljust(20) + itemLine.ljust(20) + > itemDirectory.ljust(20) > #os.rename(pathName + item, pathName + LineList[count]) > count = count + 1 > > I'm just trying to figure out where to put the break(s), but I need to > verify this is working since I'll be using it to rename files.. my old > structure did EXACTLY what I wanted (I replied to my original post > with more details and screen captures) as far as renaming the files.. > but the display was screwed up. under what conditions do you want to break? From rabidpoobear at gmail.com Thu Oct 19 03:51:45 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 18 Oct 2006 20:51:45 -0500 Subject: [Tutor] Best GUI toolkit? In-Reply-To: References: Message-ID: <4536DA31.2050606@gmail.com> Christopher Hatherly wrote: > Hi Pythonistas, > > I'm a newbie. I've worked through some introductory python books, and > feel that I now understand the logic on the coding side enough to make > the application I'm after. However I'm now trying to turn my code into a > (fairly complex) graphical app, and have found both Tkinter and wxPython > to be much more complex than perhaps they need to be (at least for the > beginner. Or perhaps I just haven't yet found a good, easy to follow > tutorial???) > > I read somewhere that BoaConstructor was a good alternative. I installed > and had a look, and it seems promising. Just wondering if anyone could > pass on any advice before I leap into it though. Specifically, my app > needs full-screen display of lots of very simple bitmaps with precise > control over display timing (synchronising with vertical refresh etc). > Any advice much appreciated. > I'd say that it sounds like a job for Pygame, if you don't need actual GUI controls. I think if you used PyOpenGL + Pygame you could have vsync. pygame itself might have an option for this. Displaying lots of bitmaps may be painful in a GUI toolkit. HTH, -Luke > Thanks > Chris > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From pyro9219 at gmail.com Thu Oct 19 03:52:17 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Wed, 18 Oct 2006 18:52:17 -0700 Subject: [Tutor] Location of found item in list. In-Reply-To: <4536D975.10502@gmail.com> References: <4536C90D.3040704@tds.net> <4536CD9F.7050200@tds.net> <4536D63C.8070606@gmail.com> <4536D975.10502@gmail.com> Message-ID: Well, if you refer to my thread where I mentioned that I had a screen capture of the output.. I want it to look like that.. now it yells at me for everything that doens't match and does match. =D I dont think this test is working though, because using your suggested method. Fail! SL_39.sdr flashupdt.cfg Fail! SL_39.sdr flashupdt_da.cfg Fail! SL_39.sdr MASTER.CFG Fail! SL_39.sdr MASTER_da.CFG Fail! SL_39.sdr PSL_MBD5.FRU Fail! SL_39.sdr P_R24BP.FRU Fail! SL_39.sdr P_R24BPE.FRU Fail! SL_39.sdr P_R26BP.FRU Fail! SL_39.sdr P_R26BPE.FRU Fail! SL_39.sdr R0066.Cap Fail! SL_39.sdr R24BP202.hex Fail! SL_39.sdr R26BP202.hex Fail! SL_39.sdr RA_MBD4.FRU Fail! SL_39.sdr SLBMC55.hex Fail! SL_39.sdr SL_39.SDR Fail! SL_39.sdr S_R24BP.FRU Fail! SL_39.sdr S_R24BPE.FRU Fail! SL_39.sdr S_R26BP.FRU Fail! SL_39.sdr S_R26BPE.FRU Fail! SL_39.sdr XSL_MBD3.FRU Fail! SL_39.sdr XVN_MBD3.FRU Ok, I dont want it to rename SL_39.sdr for each of those fails... just the one where I bolded.. this worked with my loop method, but the 3rd columns output wasn't correct. Loop = works Display = wrong On 10/18/06, Luke Paireepinart wrote: > > Chris Hengge wrote: > > Yes, I tried what you suggested, I've changed my looping structure to > > this: > > > > count = 0 > > for itemLine in lineList: > > for itemDirectory in directoryList: > > if itemLine == itemDirectory: > > print match.ljust(20) + itemLine.ljust(20) + > > itemDirectory.ljust(20) > > else: > > print fail.ljust(20) + itemLine.ljust(20) + > > itemDirectory.ljust(20) > > #os.rename(pathName + item, pathName + LineList[count]) > > count = count + 1 > > > > I'm just trying to figure out where to put the break(s), but I need to > > verify this is working since I'll be using it to rename files.. my old > > structure did EXACTLY what I wanted (I replied to my original post > > with more details and screen captures) as far as renaming the files.. > > but the display was screwed up. > > under what conditions do you want to break? > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061018/54d3fac7/attachment.htm From rabidpoobear at gmail.com Thu Oct 19 03:57:30 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 18 Oct 2006 20:57:30 -0500 Subject: [Tutor] Location of found item in list. In-Reply-To: References: <4536C90D.3040704@tds.net> <4536CD9F.7050200@tds.net> <4536D63C.8070606@gmail.com> <4536D975.10502@gmail.com> Message-ID: <4536DB8A.4070700@gmail.com> Chris Hengge wrote: > Well, if you refer to my thread where I mentioned that I had a screen > capture of the output.. I want it to look like that.. > > now it yells at me for everything that doens't match and does match. =D > > I dont think this test is working though, because using your suggested > method. > > [snip output] > > Ok, I dont want it to rename SL_39.sdr for each of those fails... just > the one where I bolded.. this worked with my loop method, but the 3rd > columns output wasn't correct. > > Loop = works > Display = wrong The reason it worked with your method was because you were outputting the same item. Are you really just checking for same item but different case? I have no idea what you're trying to do. I don't think anyone else does either. From pyro9219 at gmail.com Thu Oct 19 04:14:05 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Wed, 18 Oct 2006 19:14:05 -0700 Subject: [Tutor] Location of found item in list. In-Reply-To: <4536DB8A.4070700@gmail.com> References: <4536C90D.3040704@tds.net> <4536CD9F.7050200@tds.net> <4536D63C.8070606@gmail.com> <4536D975.10502@gmail.com> <4536DB8A.4070700@gmail.com> Message-ID: I've said in several of my emails that I understand that output is wrong... I just put it there until I had a fix... and so I could bold something to try and show people what I'm trying to do.. using this exact code: count = 0 for item in lineList: if item in directoryList: print match.ljust(20) + item.ljust(20) + "this should be the object from directoryList" else: print fail.ljust(20) + item.ljust(20) + "this should be the object from directoryList" #os.rename(pathName + item, pathName + item) count = count + 1 my program works without ANY flaw.. it finds the name from the first list, compares it to the second list, and then renames the file in the directory if it doesn't match the one from the first list. Here is output from the code above.. Tested: File Name: Directory Name: Fail! SL_39.sdr this should be the object from directoryList Match! PSL_MBD5.FRU this should be the object from directoryList Match! XSL_MBD3.FRU this should be the object from directoryList Match! RA_MBD4.FRU this should be the object from directoryList Match! XVN_MBD3.FRU this should be the object from directoryList Match! P_R24BP.FRU this should be the object from directoryList Match! P_R26BP.FRU this should be the object from directoryList Match! P_R24BPE.FRU this should be the object from directoryList Match! P_R26BPE.FRU this should be the object from directoryList Match! S_R24BP.FRU this should be the object from directoryList Match! S_R26BP.FRU this should be the object from directoryList Match! S_R24BPE.FRU this should be the object from directoryList Match! S_R26BPE.FRU this should be the object from directoryList I bolded the first line, just incase its lost in email land... the reason this line flagged fail! is because the filename for the real file located in the directory, is SL_39.SDR (I named it this so I could give an example).... now.. if I uncomment the os.rename() from my code (disabled while trying to figure out this problem), it will rename the file to the one located in the second column.. which is perfect.. what I want.. no questions asked.. I could remove the 'print' from this application, and it would do exactly what I want.. but I like the visual record for my own sanity.. What should be located in the 3rd column is the literal filename (which is located in directoryList). but, since I dont have a location to write directoryList[here] I can't print it out. I've tried using directoryList[directoryList.index(item)], but that seems to be a case-sensitive check and fails to work. On 10/18/06, Luke Paireepinart wrote: > > Chris Hengge wrote: > > Well, if you refer to my thread where I mentioned that I had a screen > > capture of the output.. I want it to look like that.. > > > > now it yells at me for everything that doens't match and does match. =D > > > > I dont think this test is working though, because using your suggested > > method. > > > > > [snip output] > > > > Ok, I dont want it to rename SL_39.sdr for each of those fails... just > > the one where I bolded.. this worked with my loop method, but the 3rd > > columns output wasn't correct. > > > > Loop = works > > Display = wrong > The reason it worked with your method was because you were outputting > the same item. > Are you really just checking for same item but different case? > I have no idea what you're trying to do. > I don't think anyone else does either. > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061018/2ae3d89a/attachment.html From john at fouhy.net Thu Oct 19 04:15:18 2006 From: john at fouhy.net (John Fouhy) Date: Thu, 19 Oct 2006 15:15:18 +1300 Subject: [Tutor] Location of found item in list. In-Reply-To: References: Message-ID: <5e58f2e40610181915i3446806cudd823c5642eef986@mail.gmail.com> Ok, so your question is: If nothing in directoryList matches item, how do I find the element of directoryList that should have matched? This is a bit tricky, because you need to define exactly what results you expect. (for example, suppose limitedLineList contained 'SL_39.sdr' and directoryList had 'SL39.sdr'. Is that something that should be a match?) Possibly you could do this: def match(item, lst): """ See if item is present in lst. output :: bool """ return item in lst def near_match(item, lst): """ See if item is similar to something in lst. Currently, we just match case-insensitive. output :: first matching element of lst, or None """ for item2 in lst: if item.upper() == item2.upper(): return item2 return None for item in limitedLineList: if match(item, directoryList): print '%20s%20s%20s' % ('Match!', item, item) else: item2 = near_match(item, directoryList) if item2: print '%20s%20s%20s' % ('Fail!', item, item2) else: print '%20s%20s%20s' % ('Fail!', item, '????') You can modify near_match if you have some other definition of what you want it to return. -- John. From pyro9219 at gmail.com Thu Oct 19 04:17:18 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Wed, 18 Oct 2006 19:17:18 -0700 Subject: [Tutor] Location of found item in list. In-Reply-To: <5e58f2e40610181915i3446806cudd823c5642eef986@mail.gmail.com> References: <5e58f2e40610181915i3446806cudd823c5642eef986@mail.gmail.com> Message-ID: I think this is overkill for what I'm trying to do, could you please refer to what I just wrote luke? That might make things simpler.. On 10/18/06, John Fouhy wrote: > > Ok, so your question is: > > If nothing in directoryList matches item, how do I find the > element of directoryList that should have matched? > > This is a bit tricky, because you need to define exactly what results > you expect. > > (for example, suppose limitedLineList contained 'SL_39.sdr' and > directoryList had 'SL39.sdr'. Is that something that should be a > match?) > > Possibly you could do this: > > def match(item, lst): > """ See if item is present in lst. > > output :: bool > """ > return item in lst > > def near_match(item, lst): > """ See if item is similar to something in lst. Currently, we just > match case-insensitive. > > output :: first matching element of lst, or None > """ > for item2 in lst: > if item.upper() == item2.upper(): > return item2 > return None > > for item in limitedLineList: > if match(item, directoryList): > print '%20s%20s%20s' % ('Match!', item, item) > else: > item2 = near_match(item, directoryList) > if item2: > print '%20s%20s%20s' % ('Fail!', item, item2) > else: > print '%20s%20s%20s' % ('Fail!', item, '????') > > You can modify near_match if you have some other definition of what > you want it to return. > > -- > John. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061018/77c7652a/attachment.htm From pyro9219 at gmail.com Thu Oct 19 04:28:52 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Wed, 18 Oct 2006 19:28:52 -0700 Subject: [Tutor] Location of found item in list. In-Reply-To: References: Message-ID: If that last post to Luke didn't clear anything up.. lets try this at a smaller level... I'm going to ignore the fact that my program already renames the file properly.. I have list1 of filenames I have list2 of filenames Item from list 1 needs to be found in list2, but I can't change cases, because thats what I'm looking for. I suppose, I could .sort each list after chopping the extra files names out of list2 that aren't in list1. then all I have to do is list1[count] = list2[count] What I'd like to know, is why my program works, if I can't get it to display the proper filename in the 3rd output column. I guess os.rename(notcasesensitive, iscasesensitive) ? On 10/18/06, Chris Hengge wrote: > > I'm looking for a way to do the following. > > for item in limitedLineList: > if item in directoryList: > print match.ljust(20) + limitedLineList[count].ljust(20) + > directoryList[ count].ljust(20) > else: > print fail.ljust(20) + limitedLineList[count].ljust(20) + > directoryList[count].ljust(20) > os.rename(pathName + directoryList[ count], pathName + > limitedLineList[count]) > count = count + 1 > > Where I have underlined, needs to be the item from the directoryList, and > I'm unable to find a way to return that. > > The code is actually doing what I want correctly, (cheated a test by hand > changing variables), but I need to find the directory location. > > Thanks. > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061018/705608ed/attachment.html From john at fouhy.net Thu Oct 19 04:36:01 2006 From: john at fouhy.net (John Fouhy) Date: Thu, 19 Oct 2006 15:36:01 +1300 Subject: [Tutor] Location of found item in list. In-Reply-To: References: <5e58f2e40610181915i3446806cudd823c5642eef986@mail.gmail.com> Message-ID: <5e58f2e40610181936n20757a94kcb390abd7a28c363@mail.gmail.com> On 19/10/06, Chris Hengge wrote: > I think this is overkill for what I'm trying to do, could you please refer > to what I just wrote luke? That might make things simpler.. Did you try my code? It doesn't seem like overkill to me. Remember, there are no prizes for writing the shortest code possible, or for using the fewest language features you can.. -- John. From alan.gauld at btinternet.com Thu Oct 19 06:12:58 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 19 Oct 2006 05:12:58 +0100 Subject: [Tutor] Best GUI toolkit? References: Message-ID: "Christopher Hatherly" wrote > the application I'm after. However I'm now trying to turn my code > into a > (fairly complex) graphical app, and have found both Tkinter and > wxPython > to be much more complex than perhaps they need to be Both are actually quite simple compared to most GUI toolkits. But there are certain complexities inherent in building GUIs and you can't get away from those I'm afraid. > I read somewhere that BoaConstructor was a good alternative. Boa is a GUI builder, similar tools exist for Tkinter too - SpecTix is an example... > pass on any advice before I leap into it though. Specifically, my > app > needs full-screen display of lots of very simple bitmaps with > precise > control over display timing (synchronising with vertical refresh > etc). Almost by definition full screen display is a non standard GUI activity. As soon as you move away from standard GUI style (a window displayed within a screen) you add complexity to the task because you are not working within the usual model. From a usability point of view applications that grab the full screen are considered bad news (the classic example is game programs which need fastest possible access to the graphics). If you need that kind of access a games framework might be more useful that a general GUI framework. But then if you really need that amount of graphics power, I'd question if Python is the right toool for your task! -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From rabidpoobear at gmail.com Thu Oct 19 08:41:45 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 19 Oct 2006 01:41:45 -0500 Subject: [Tutor] Location of found item in list. In-Reply-To: References: Message-ID: <45371E29.2070608@gmail.com> Chris Hengge wrote: > If that last post to Luke didn't clear anything up.. lets try this at > a smaller level... > I'm going to ignore the fact that my program already renames the file > properly.. > > I have list1 of filenames > I have list2 of filenames > > Item from list 1 needs to be found in list2, but I can't change cases, > because thats what I'm looking for. I suppose, I could .sort each list > after chopping the extra files names out of list2 that aren't in > list1. then all I have to do is list1[count] = list2[count] > > What I'd like to know, is why my program works, if I can't get it to > display the proper filename in the 3rd output column. I guess > os.rename(notcasesensitive, iscasesensitive) ? > I doubt os.rename is case insensitive for the first argument. Okay, here is what you're trying to do. Assuming I haven't seen your code before and I'm writing it from scratch. I have a list of filenames. list1 = ['a.exe', 'b.exe', 'c.exe', 'e.exe'] I could've read these in from a file, or anything. It doesn't matter where they came from. The important thing is that they have the case that I want. Say I also have another list. list2 = ['a.ExE',' B.exe', 'C.EXE', 'd.EXE','E.eXe'] we got this list maybe from a directory listing or something. It doesn't matter. What we're trying to do is: apply any case changes that are necessary to make all of list1's items' counterparts in list2 be the same. I.E., 'a.ExE' in list2 becomes 'a.exe' from list1. We'll assume that if there is an item in list2 that doesn't have a counterpart in list1, that we just don't care. So 'd.EXE' is going to be 'd.EXE' after the program is run, because there is no corresponding item in list1. In other words, if there are extra files in the directory that we don't need to fix the case for, we'll just ignore them. So, without thinking about the implementation, what is it we want to do? for every item in list1, check it against each item in list2. if the case-insensitive version of the list1 item is equal to the case-insensitive version of list2, and the case-sensitive versions aren't equal, we know we need to change the case. Otherwise, if the case-sensitive versions are equal, we don't need to change case, but we'll tell them so. if the case-insensitive version of list1 item is not equal to the case-insensitive version of the list2 item, we don't care. It's one of the things that we don't need to change. So what would this look like in python code? for item1 in list1: for item2 in list2: if item1.lower() == item2.lower(): #they're the same file if you ignore case if item1 != item2: #but there's some case error, os.rename(item1,item2) print "%s is not %s" % (item1, item2) else: print "%s is %s" % (item1,item1)# or (item1, item1), or (item2,item2), since they're equivalent. I think this is what you wanted. The way you were trying to explain it just confused everyone. Hope that helps, -Luke From etrade.griffiths at dsl.pipex.com Thu Oct 19 11:41:27 2006 From: etrade.griffiths at dsl.pipex.com (etrade.griffiths at dsl.pipex.com) Date: Thu, 19 Oct 2006 10:41:27 +0100 Subject: [Tutor] Sharing data between modules Message-ID: <1161250887.45374847bf409@netmail.pipex.net> Hi just starting to get to grips with writing GUIs in Python using wxPython and not being a computer scientist, have a philosophical question about the "best" way to pass data between various modules. For example, I anticipate having one module to look after the GUI stuff where users can input data (either from the keyboard or file), another to process the data and (probably) a third to display the calculation results. Just not sure what the most efficient way of passing data between the various modules. I can think of 4 ways to do this, of which 1 is not possible in Python (I think). (1) via temp files: modules read to and write from temporary files (2) via function arguments: data passed from one module to another via argument lists. This seems the most logical but I have an irrational dislike of long argument lists. Could pass data objects (eg. C type structs) or dictionaries via the argument list but I don't think this gets around the "problem" of long argument lists and we now need pack/unpack type functions. Maybe this isn't a problem anyway? (3) via globals: AFAIK this is not recommended so we will move swiftly on (4) indirectly: thinking here of something along the FORTRAN COMMON blocks which (I think) Python doesn't have So, looks like it's a choice between (1) and (2) - or have I missed something obvious? What is the most "pythonic" way of doing this? Thanks in advance for any suggestions From arunkumarpg at gmail.com Thu Oct 19 13:11:28 2006 From: arunkumarpg at gmail.com (Arun Kumar PG) Date: Thu, 19 Oct 2006 16:41:28 +0530 Subject: [Tutor] Writing serialized objects from BaseHTTPServer Message-ID: <3cffff920610190411l1b868314oad2ad5e53a5f052@mail.gmail.com> Hi Guys, I wrote a simple server using sockets ,the traditional whille True: scoket.accept() approach. This server reads some pickled parameters sent by the client using the cPickle module -> do some processing -> and finally writes a list of tuples, objects using cPickle back to the client output stream (cPickle.dump). Now I want to replace this server with an HTTP server. Python's BaseHTTPServer basically. I was wondering when using BaseHTTPServer if I want to read/write a serialized object to meet the above behavior how could I achive this using HTTP server ? We need a content-type to specify before writing back to the client -- whats the content-type for serialised objects which I want to write back to the client using cPickle ? Thanks. Arun -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061019/2af06d5c/attachment.html From dpotter at nc.rr.com Thu Oct 19 15:21:51 2006 From: dpotter at nc.rr.com (dpotter at nc.rr.com) Date: Thu, 19 Oct 2006 09:21:51 -0400 Subject: [Tutor] passing a variable ? Message-ID: I am stumped. I am trying to pass the variable 'savename' to a string and get errors. can someone tell me why? Thanks to all on this list. (The problem happens in the for loop 1st line) This is my error Traceback (most recent call last): File "./ArpAcl.py", line 39, in ? fout = file('/home/cable/sandbox/%s', 'a''w' % savename) TypeError: not all arguments converted during string formatting ---------------------------------------------------------------------------- import pexpect import getpass import sys #Go through all the routers and gather Access-list or ARP information, return the info into it's own file. print '\n' print 'Router scrub will take approx 60 Seconds.' print '\n' print "For the ARP list enter '1'" print "For the ACL list enter '2'" print '\n' choice = input('Enter 1 or 2: ') print '\n' telpass = getpass.getpass('Please enter the telnet password: ') enablepass = getpass.getpass('Please enter the enable password: ') if choice == 1: command = 'show arp' savename = 'arp.txt' else: command = 'sh ip access-l' savename = 'acl.txt' print '\n' print '-' * 48 print 'You will be notified when program is finished.' print '-' * 48 x = open('/home/cable/router.list','r') routers = x.readlines() for i in routers: fout = file('/home/cable/sandbox/%s', 'a''w' % savename) c = pexpect.spawn('/usr/bin/telnet %s' %i) c.expect('Please Enter Password:') c.sendline(telpass +'\r') c.sendline('enable\r') c.expect('Password:') c.sendline(enablepass + '\r') c.expect('#') c.logfile = fout c.sendline('skip\r') c.expect('#') c.sendline(command + '\r') c.expect('#') fout.close() c.close() x.close() print '\n' print 'Finished!' print '\n' print 'File has been save to /home/cable/sandbox/%s' % savename raw_input('Press any key to exit....') From jason.massey at gmail.com Thu Oct 19 15:32:11 2006 From: jason.massey at gmail.com (Jason Massey) Date: Thu, 19 Oct 2006 08:32:11 -0500 Subject: [Tutor] passing a variable ? In-Reply-To: References: Message-ID: <7e3eab2c0610190632q4d5692acwc1e180e33c2ec0f0@mail.gmail.com> It should look like this: fout = file('/home/cable/sandbox/%s' % savename, 'a''w') The variables come immediately after the string your formatting. On 10/19/06, dpotter at nc.rr.com wrote: > > I am stumped. I am trying to pass the variable 'savename' to a string > and get errors. > can someone tell me why? Thanks to all on this list. (The problem > happens in the for loop 1st line) > > This is my error > Traceback (most recent call last): > File "./ArpAcl.py", line 39, in ? > fout = file('/home/cable/sandbox/%s', 'a''w' % savename) > TypeError: not all arguments converted during string formatting > > > ---------------------------------------------------------------------------- > > import pexpect > import getpass > import sys > > #Go through all the routers and gather Access-list or ARP information, > return the info into it's own file. > print '\n' > print 'Router scrub will take approx 60 Seconds.' > print '\n' > print "For the ARP list enter '1'" > print "For the ACL list enter '2'" > print '\n' > > choice = input('Enter 1 or 2: ') > print '\n' > telpass = getpass.getpass('Please enter the telnet password: ') > enablepass = getpass.getpass('Please enter the enable password: ') > > if choice == 1: > command = 'show arp' > savename = 'arp.txt' > else: > command = 'sh ip access-l' > savename = 'acl.txt' > > print '\n' > print '-' * 48 > print 'You will be notified when program is finished.' > print '-' * 48 > > x = open('/home/cable/router.list','r') > routers = x.readlines() > > for i in routers: > fout = file('/home/cable/sandbox/%s', 'a''w' % savename) > c = pexpect.spawn('/usr/bin/telnet %s' %i) > c.expect('Please Enter Password:') > c.sendline(telpass +'\r') > c.sendline('enable\r') > c.expect('Password:') > c.sendline(enablepass + '\r') > c.expect('#') > c.logfile = fout > c.sendline('skip\r') > c.expect('#') > c.sendline(command + '\r') > c.expect('#') > fout.close() > c.close() > x.close() > print '\n' > print 'Finished!' > print '\n' > print 'File has been save to /home/cable/sandbox/%s' % savename > raw_input('Press any key to exit....') > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061019/f228d7c8/attachment.htm From kent37 at tds.net Thu Oct 19 15:37:57 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 19 Oct 2006 09:37:57 -0400 Subject: [Tutor] passing a variable ? In-Reply-To: References: Message-ID: <45377FB5.6020202@tds.net> dpotter at nc.rr.com wrote: > I am stumped. I am trying to pass the variable 'savename' to a string > and get errors. > can someone tell me why? Thanks to all on this list. (The problem > happens in the for loop 1st line) > > This is my error > Traceback (most recent call last): > File "./ArpAcl.py", line 39, in ? > fout = file('/home/cable/sandbox/%s', 'a''w' % savename) > TypeError: not all arguments converted during string formatting You are applying the formatting operator to the string 'aw' not to the path string. Try this: fout = file('/home/cable/sandbox/%s' % savename, 'a''w') Not sure why you have both 'a' and 'w' - which one do you want? Seems like you should pick one. Kent > > ---------------------------------------------------------------------------- > > import pexpect > import getpass > import sys > > #Go through all the routers and gather Access-list or ARP information, > return the info into it's own file. > print '\n' > print 'Router scrub will take approx 60 Seconds.' > print '\n' > print "For the ARP list enter '1'" > print "For the ACL list enter '2'" > print '\n' > > choice = input('Enter 1 or 2: ') > print '\n' > telpass = getpass.getpass('Please enter the telnet password: ') > enablepass = getpass.getpass('Please enter the enable password: ') > > if choice == 1: > command = 'show arp' > savename = 'arp.txt' > else: > command = 'sh ip access-l' > savename = 'acl.txt' > > print '\n' > print '-' * 48 > print 'You will be notified when program is finished.' > print '-' * 48 > > x = open('/home/cable/router.list','r') > routers = x.readlines() > > for i in routers: > fout = file('/home/cable/sandbox/%s', 'a''w' % savename) > c = pexpect.spawn('/usr/bin/telnet %s' %i) > c.expect('Please Enter Password:') > c.sendline(telpass +'\r') > c.sendline('enable\r') > c.expect('Password:') > c.sendline(enablepass + '\r') > c.expect('#') > c.logfile = fout > c.sendline('skip\r') > c.expect('#') > c.sendline(command + '\r') > c.expect('#') > fout.close() > c.close() > x.close() > print '\n' > print 'Finished!' > print '\n' > print 'File has been save to /home/cable/sandbox/%s' % savename > raw_input('Press any key to exit....') > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From jfabiani at yolo.com Thu Oct 19 17:42:55 2006 From: jfabiani at yolo.com (johnf) Date: Thu, 19 Oct 2006 08:42:55 -0700 Subject: [Tutor] Sharing data between modules In-Reply-To: <1161250887.45374847bf409@netmail.pipex.net> References: <1161250887.45374847bf409@netmail.pipex.net> Message-ID: <200610190842.55972.jfabiani@yolo.com> On Thursday 19 October 2006 02:41, etrade.griffiths at dsl.pipex.com wrote: > Hi > > just starting to get to grips with writing GUIs in Python using wxPython > and not being a computer scientist, have a philosophical question about the > "best" way to pass data between various modules. For example, I anticipate > having one module to look after the GUI stuff where users can input data > (either from the keyboard or file), another to process the data and > (probably) a third to display the calculation results. Just not sure what > the most efficient way of passing data between the various modules. I can > think of 4 ways to do this, of which 1 is not possible in Python (I think). > > (1) via temp files: modules read to and write from temporary files > (2) via function arguments: data passed from one module to another via > argument lists. This seems the most logical but I have an irrational > dislike of long argument lists. Could pass data objects (eg. C type > structs) or dictionaries via the argument list but I don't think this gets > around the "problem" of long argument lists and we now need pack/unpack > type functions. Maybe this isn't a problem anyway? > (3) via globals: AFAIK this is not recommended so we will move swiftly on > (4) indirectly: thinking here of something along the FORTRAN COMMON blocks > which (I think) Python doesn't have > > So, looks like it's a choice between (1) and (2) - or have I missed > something obvious? What is the most "pythonic" way of doing this? Thanks > in advance for any suggestions What you are describing is N-Tier programming. Normally that is 3-Tier - user interface, rules (business rules), and data access. There are several python frameworks that assist with the N-tier setup. You might want to try 'Dabo' or "PYTHONCARD". Using the frameworks you will not have to concern yourself with how the modules are passing data (although all the source code is available for review). Of course both frameworks assume the use of a data store. John From python at venix.com Thu Oct 19 17:48:13 2006 From: python at venix.com (Python) Date: Thu, 19 Oct 2006 11:48:13 -0400 Subject: [Tutor] Sharing data between modules In-Reply-To: <1161250887.45374847bf409@netmail.pipex.net> References: <1161250887.45374847bf409@netmail.pipex.net> Message-ID: <1161272893.8103.788.camel@www.venix.com> On Thu, 2006-10-19 at 10:41 +0100, etrade.griffiths at dsl.pipex.com wrote: > Hi > > just starting to get to grips with writing GUIs in Python using wxPython and > not being a computer scientist, have a philosophical question about the "best" > way to pass data between various modules. For example, I anticipate having > one module to look after the GUI stuff where users can input data (either from > the keyboard or file), another to process the data and (probably) a third to > display the calculation results. Just not sure what the most efficient way of > passing data between the various modules. I can think of 4 ways to do this, > of which 1 is not possible in Python (I think). > > (1) via temp files: modules read to and write from temporary files > (2) via function arguments: data passed from one module to another via > argument lists. This seems the most logical but I have an irrational dislike > of long argument lists. Could pass data objects (eg. C type structs) or > dictionaries via the argument list but I don't think this gets around > the "problem" of long argument lists and we now need pack/unpack type > functions. Maybe this isn't a problem anyway? dictionaries can work pretty well if you leverage the ** syntax in function arguments. If we imagine a dictionary named passdata where the keys are named k1 to k99: def func1(k1, k30, k47, **kwds): # the unused parameters are collected in the dictionary kwds # do stuff with the parameters return result result = func1( **passdata) The functions that depend on specific variables can identify the variables in the parameter definition. I've generally been happy with this kind of approach. > (3) via globals: AFAIK this is not recommended so we will move swiftly on > (4) indirectly: thinking here of something along the FORTRAN COMMON blocks > which (I think) Python doesn't have > > So, looks like it's a choice between (1) and (2) - or have I missed something > obvious? What is the most "pythonic" way of doing this? Thanks in advance > for any suggestions > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From kent37 at tds.net Thu Oct 19 17:58:48 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 19 Oct 2006 11:58:48 -0400 Subject: [Tutor] Sharing data between modules In-Reply-To: <1161250887.45374847bf409@netmail.pipex.net> References: <1161250887.45374847bf409@netmail.pipex.net> Message-ID: <4537A0B8.7020502@tds.net> etrade.griffiths at dsl.pipex.com wrote: > Hi > > just starting to get to grips with writing GUIs in Python using wxPython and > not being a computer scientist, have a philosophical question about the "best" > way to pass data between various modules. For example, I anticipate having > one module to look after the GUI stuff where users can input data (either from > the keyboard or file), another to process the data and (probably) a third to > display the calculation results. Just not sure what the most efficient way of > passing data between the various modules. I can think of 4 ways to do this, > of which 1 is not possible in Python (I think). > > (1) via temp files: modules read to and write from temporary files I can't think of any reason to do this for in-process communication. You still have to marshall and unmarshall the values, you might as well just pass around lists or some other structure. > (2) via function arguments: data passed from one module to another via > argument lists. This seems the most logical but I have an irrational dislike > of long argument lists. Could pass data objects (eg. C type structs) or > dictionaries via the argument list but I don't think this gets around > the "problem" of long argument lists and we now need pack/unpack type > functions. Maybe this isn't a problem anyway? This is the best way. Well designed objects can help a lot with avoiding long argument lists. The key is to make objects that have functionality, they are more than just data containers but include the operations on the data. For repeating data use lists. > (3) via globals: AFAIK this is not recommended so we will move swiftly on Only if there is no alternative. > (4) indirectly: thinking here of something along the FORTRAN COMMON blocks > which (I think) Python doesn't have You can use a module as a shared namespace. This sometimes makes sense for configuration data that is shared and doesn't change much. I wouldn't use it as a general argument passing mechanism, it has all the disadvantages of globals. > > So, looks like it's a choice between (1) and (2) - or have I missed something > obvious? What is the most "pythonic" way of doing this? Thanks in advance > for any suggestions (2) Kent From dkuhlman at rexx.com Thu Oct 19 18:07:21 2006 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Thu, 19 Oct 2006 09:07:21 -0700 Subject: [Tutor] Sharing data between modules In-Reply-To: <1161250887.45374847bf409@netmail.pipex.net> References: <1161250887.45374847bf409@netmail.pipex.net> Message-ID: <20061019160721.GA32317@cutter.rexx.com> On Thu, Oct 19, 2006 at 10:41:27AM +0100, etrade.griffiths at dsl.pipex.com wrote: > Hi > > just starting to get to grips with writing GUIs in Python using wxPython and > not being a computer scientist, have a philosophical question about the "best" > way to pass data between various modules. For example, I anticipate having > one module to look after the GUI stuff where users can input data (either from > the keyboard or file), another to process the data and (probably) a third to > display the calculation results. Just not sure what the most efficient way of > passing data between the various modules. I can think of 4 ways to do this, > of which 1 is not possible in Python (I think). > Ask yourself the following question: Does the data cohere or stick together in some way? For example, is a user entering information for a new member or a new account? If so, define a class that will serve as a container for this collection of related information, perhaps a class called AccountInfo. Now somewhere (in the GUI stuff, maybe), you will create an instance of the AccountInfo class and pass that instance between your modules. A slightly different need is where you want to share a *single* set of common values among several modules. An example might be a set of configuration values that are read from a config file at the application start-up. For this you could use a "config" module (config.py, say) containing variables that hold these values, and each module that needed access to these values could do "import config". Although, I suppose that a singleton class (a class intended to have only one instance) might be just as good, and would be more pleasing to the "object-orientated" among us. Dave [snip] -- Dave Kuhlman http://www.rexx.com/~dkuhlman From pyro9219 at gmail.com Thu Oct 19 18:26:20 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Thu, 19 Oct 2006 09:26:20 -0700 Subject: [Tutor] Generic Application Frameworks? Message-ID: I was curious if there are any frameworks around like carbon/razor implimented in razor? Here's a link with information about razor (.net 1.1 versin of carbon) http://www.codeproject.com/cs/design/razorpt1.asp If not, is there any reason why? (limitation of python?) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061019/42ba85d8/attachment.htm From thomas.coopman at gmail.com Thu Oct 19 19:03:03 2006 From: thomas.coopman at gmail.com (thomas) Date: Thu, 19 Oct 2006 19:03:03 +0200 Subject: [Tutor] property built-in Message-ID: <4537AFC7.80504@localhost> Hi, I was wondering some things about property. suppose I have a class like this: class A(object): def __init__(self, x, y): self.__x = x def x(): def get(self): return self.__x def set(self, x): self.__x = x #and some other code that is important x= property(**x()) questions: 1: why doesn't there have to be a self in x()? 2: how do I address the setter of x in the init? I think these are basic questions, but I can't seem to find out how to do it. Thanks From python at venix.com Thu Oct 19 19:37:10 2006 From: python at venix.com (Python) Date: Thu, 19 Oct 2006 13:37:10 -0400 Subject: [Tutor] property built-in In-Reply-To: <4537AFC7.80504@localhost> References: <4537AFC7.80504@localhost> Message-ID: <1161279430.8103.804.camel@www.venix.com> On Thu, 2006-10-19 at 19:03 +0200, thomas wrote: > Hi, > > > I was wondering some things about property. > > suppose I have a class like this: > > class A(object): > def __init__(self, x, y): > self.__x = x > > def x(): > def get(self): fget > return self.__x > > def set(self, x): fset > self.__x = x > #and some other code that is important return locals() > > x= property(**x()) > > questions: > 1: why doesn't there have to be a self in x()? x is not a "normal" class method. It is only used as a container to hold the "real" methods which are returned in the locals() dictionary. property supports keyword arguments fget, fset, fdel and doc. The definitions in your x method (Too many uses of x for different purposes) MUST match the property keywords because of the use of locals(). > 2: how do I address the setter of x in the init? Just use it. Change __init__ to have self.x = x By the time __init__ is usable, x = property( **x()) will have done its magic. x will be a property of the class. >>> class A(object): ... def __init__(self, x, y): ... self.x = x ... def x(): ... def fget(self): ... return self.__x ... def fset(self, x): ... self.__x = x ... #and some other code that is important ... return locals() ... x= property(**x()) ... >>> a = A(1,2) >>> a.x 1 >>> a.x=4 >>> a.x 4 > > I think these are basic questions, but I can't seem to find out how to > do it. > > > Thanks > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From ajkadri at googlemail.com Thu Oct 19 19:44:07 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Thu, 19 Oct 2006 18:44:07 +0100 Subject: [Tutor] Trying to extract the last line of a text file Message-ID: Hi Folks, I want to extract the last line of the text file. Any idea ??? Thanks, Regards, Asrarahmed -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061019/f2c13b65/attachment.html From dyoo at hkn.eecs.berkeley.edu Thu Oct 19 19:50:30 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 19 Oct 2006 10:50:30 -0700 (PDT) Subject: [Tutor] Trying to extract the last line of a text file In-Reply-To: References: Message-ID: On Thu, 19 Oct 2006, Asrarahmed Kadri wrote: > I want to extract the last line of the text file. Any idea ??? Hi Asrarahmed, Ok, so what part do you get stuck on when you try to do this? That is, what sort of things do you already know how to do with files? From ajkadri at googlemail.com Thu Oct 19 19:55:45 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Thu, 19 Oct 2006 18:55:45 +0100 Subject: [Tutor] Trying to extract the last line of a text file In-Reply-To: References: Message-ID: My algorithm is like this: first count the number of lines in the file by using a loop. Use a second loop and when teh counter reaches the num_of_lines values: take the line. Is there any other way to do it?? On 10/19/06, Danny Yoo wrote: > > > > On Thu, 19 Oct 2006, Asrarahmed Kadri wrote: > > > I want to extract the last line of the text file. Any idea ??? > > Hi Asrarahmed, > > Ok, so what part do you get stuck on when you try to do this? That is, > what sort of things do you already know how to do with files? > -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061019/45992f28/attachment.htm From pyro9219 at gmail.com Thu Oct 19 20:54:21 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Thu, 19 Oct 2006 11:54:21 -0700 Subject: [Tutor] Location of found item in list. In-Reply-To: <45371E29.2070608@gmail.com> References: <45371E29.2070608@gmail.com> Message-ID: This is the solution I came up with. for dirItem in directoryList: directoryListLower.append(dirItem.lower()) #---Loop for file name comparison. for item in lineList: # For every item in the 'lineList' if item in directoryList: # If the item is also in 'directoryList' # Print out so I know it is found. print match.ljust(20) + item.ljust(20) \ + directoryList[directoryList.index(item)] else: # If it isn't found, print what didn't match. # Use the lowercase form from each list to find what didn't match. if item.lower() in directoryListLower: # Print out so I can see why it failed. print fail.ljust(20) + item.ljust(20) + \ directoryList[directoryListLower.index(item.lower())] os.rename(pathName + \ directoryList[directoryListLower.index(item.lower())], \ pathName + item) On 10/18/06, Luke Paireepinart wrote: > > Chris Hengge wrote: > > If that last post to Luke didn't clear anything up.. lets try this at > > a smaller level... > > I'm going to ignore the fact that my program already renames the file > > properly.. > > > > I have list1 of filenames > > I have list2 of filenames > > > > Item from list 1 needs to be found in list2, but I can't change cases, > > because thats what I'm looking for. I suppose, I could .sort each list > > after chopping the extra files names out of list2 that aren't in > > list1. then all I have to do is list1[count] = list2[count] > > > > What I'd like to know, is why my program works, if I can't get it to > > display the proper filename in the 3rd output column. I guess > > os.rename(notcasesensitive, iscasesensitive) ? > > > I doubt os.rename is case insensitive for the first argument. > > Okay, here is what you're trying to do. > Assuming I haven't seen your code before and I'm writing it from scratch. > > I have a list of filenames. > list1 = ['a.exe', 'b.exe', 'c.exe', 'e.exe'] > I could've read these in from a file, or anything. > It doesn't matter where they came from. > The important thing is that they have the case that I want. > > Say I also have another list. > list2 = ['a.ExE',' B.exe', 'C.EXE', 'd.EXE','E.eXe'] > we got this list maybe from a directory listing or something. It > doesn't matter. > > What we're trying to do is: apply any case changes that are necessary to > make all of list1's items' counterparts > in list2 be the same. I.E., 'a.ExE' in list2 becomes 'a.exe' from list1. > > We'll assume that if there is an item in list2 that doesn't have a > counterpart in list1, > that we just don't care. So 'd.EXE' is going to be 'd.EXE' after the > program is run, > because there is no corresponding item in list1. In other words, > if there are extra files in the directory that we don't need to fix the > case for, we'll just ignore them. > > > So, without thinking about the implementation, what is it we want to do? > > for every item in list1, > check it against each item in list2. > if the case-insensitive version of the list1 item is equal to the > case-insensitive version of list2, > and the case-sensitive versions aren't equal, > we know we need to change the case. > > Otherwise, if the case-sensitive versions are equal, > we don't need to change case, but we'll tell them so. > > if the case-insensitive version of list1 item is not equal to the > case-insensitive version of the list2 item, > we don't care. It's one of the things that we don't need to change. > > > So what would this look like in python code? > > for item1 in list1: > for item2 in list2: > if item1.lower() == item2.lower(): #they're the same file if you > ignore case > if item1 != item2: #but there's some case error, > os.rename(item1,item2) > print "%s is not %s" % (item1, item2) > else: > print "%s is %s" % (item1,item1)# or (item1, item1), or > (item2,item2), since they're equivalent. > > I think this is what you wanted. > The way you were trying to explain it just confused everyone. > > Hope that helps, > -Luke > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061019/1db80a81/attachment.htm From broek at cc.umanitoba.ca Thu Oct 19 20:57:48 2006 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Thu, 19 Oct 2006 13:57:48 -0500 Subject: [Tutor] Trying to extract the last line of a text file In-Reply-To: References: Message-ID: <4537CAAC.3070701@cc.umanitoba.ca> Asrarahmed Kadri said unto the world upon 19/10/06 12:55 PM: > My algorithm is like this: > first count the number of lines in the file by using a loop. > Use a second loop and when teh counter reaches the num_of_lines values: > take > the line. > > Is there any other way to do it?? > > > > On 10/19/06, Danny Yoo wrote: >> >> >> >> On Thu, 19 Oct 2006, Asrarahmed Kadri wrote: >> >> > I want to extract the last line of the text file. Any idea ??? >> >> Hi Asrarahmed, >> >> Ok, so what part do you get stuck on when you try to do this? That is, >> what sort of things do you already know how to do with files? >> Hi Asrarahmed, one way would be to use the readlines method of the file object. That will get you a list of lines. From that, you could slice out the last line. Would you know how to do that? If not, ask again. Best, Brian vdB From pyro9219 at gmail.com Thu Oct 19 20:58:18 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Thu, 19 Oct 2006 11:58:18 -0700 Subject: [Tutor] Trying to extract the last line of a text file In-Reply-To: References: Message-ID: I'd personally do something like this. file = open(myfile, 'r') fileContents = file.readlines() # read the entire document into memory for speed. file.close() print fileContents[-1] # This is the last line. On 10/19/06, Asrarahmed Kadri wrote: > > My algorithm is like this: > first count the number of lines in the file by using a loop. > Use a second loop and when teh counter reaches the num_of_lines values: > take the line. > > Is there any other way to do it?? > > > > On 10/19/06, Danny Yoo wrote: > > > > > > > > On Thu, 19 Oct 2006, Asrarahmed Kadri wrote: > > > > > I want to extract the last line of the text file. Any idea ??? > > > > Hi Asrarahmed, > > > > Ok, so what part do you get stuck on when you try to do this? That is, > > what sort of things do you already know how to do with files? > > > > > > -- > To HIM you shall return. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061019/467a3193/attachment.html From flaxeater at gmail.com Thu Oct 19 21:11:38 2006 From: flaxeater at gmail.com (Chad Crabtree) Date: Thu, 19 Oct 2006 15:11:38 -0400 Subject: [Tutor] Trying to extract the last line of a text file In-Reply-To: References: Message-ID: <584940990610191211rf70b3a2ybed72788a36806d3@mail.gmail.com> On 10/19/06, Chris Hengge wrote: > > I'd personally do something like this. > > file = open(myfile, 'r') > fileContents = file.readlines() # read the entire document into memory for > speed. > file.close() > > print fileContents[-1] # This is the last line. This works as well file('filename.txt').readlines()[-1] Some will say that this is no good because the file is still open. However I've been told that when the object is cleaned the file is closed so it should be fine. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061019/9890c1c2/attachment.htm From pyro9219 at gmail.com Thu Oct 19 21:17:09 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Thu, 19 Oct 2006 12:17:09 -0700 Subject: [Tutor] Trying to extract the last line of a text file In-Reply-To: <584940990610191211rf70b3a2ybed72788a36806d3@mail.gmail.com> References: <584940990610191211rf70b3a2ybed72788a36806d3@mail.gmail.com> Message-ID: Not to hijack the thread, but what stops you from just putting a file.close() after your example line? On 10/19/06, Chad Crabtree wrote: > > file('filename.txt').readlines()[-1] > > Some will say that this is no good because the file is still open. > However I've been told that when the object is cleaned the file is closed so > it should be fine. > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061019/27428c89/attachment.html From pyro9219 at gmail.com Thu Oct 19 21:22:25 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Thu, 19 Oct 2006 12:22:25 -0700 Subject: [Tutor] Generic Application Frameworks? In-Reply-To: References: Message-ID: Just incase anyone doesn't want to see that document to know what I'm asking about... Razor/Carbon includes: Auto Update Plugin System with management Error reporting Its got a few other features, but these are my focus. On 10/19/06, Chris Hengge wrote: > > I was curious if there are any frameworks around like carbon/razor > implimented in razor? > > Here's a link with information about razor (.net 1.1 versin of carbon) > http://www.codeproject.com/cs/design/razorpt1.asp > > If not, is there any reason why? (limitation of python?) > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061019/9e44447b/attachment.htm From jordangreenberg at gmail.com Thu Oct 19 21:26:51 2006 From: jordangreenberg at gmail.com (Jordan Greenberg) Date: Thu, 19 Oct 2006 15:26:51 -0400 Subject: [Tutor] Trying to extract the last line of a text file In-Reply-To: References: <584940990610191211rf70b3a2ybed72788a36806d3@mail.gmail.com> Message-ID: <4537D17B.6000602@gmail.com> Chris Hengge wrote: > Not to hijack the thread, but what stops you from just putting a > file.close() > after your example line? Because file is a class. file(filename) creates a file object, but he's not saving the object to a variable, so its lost. file.close() takes a file object as a parameter, but theres no object left to pass it. HTH. -Jordan Greenberg From Mike.Hansen at atmel.com Thu Oct 19 21:40:44 2006 From: Mike.Hansen at atmel.com (Mike Hansen) Date: Thu, 19 Oct 2006 13:40:44 -0600 Subject: [Tutor] Generic Application Frameworks? Message-ID: <57B026980605A64F9B23484C5659E32E358C49@poccso.US.ad.atmel.com> From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Chris Hengge Sent: Thursday, October 19, 2006 1:22 PM To: PyTutor Subject: Re: [Tutor] Generic Application Frameworks? Just incase anyone doesn't want to see that document to know what I'm asking about... Razor/Carbon includes: Auto Update Plugin System with management Error reporting Its got a few other features, but these are my focus. On 10/19/06, Chris Hengge wrote: I was curious if there are any frameworks around like carbon/razor implimented in razor? Here's a link with information about razor (.net 1.1 versin of carbon) http://www.codeproject.com/cs/design/razorpt1.asp If not, is there any reason why? (limitation of python?) ----------- You might ask on comp.lang.python. You might also do a search at http://cheeseshop.python.org/pypi I did a search for 'application framework' and came up with http://cheeseshop.python.org/pypi/PlugBoard/0.2 Most of the other hits were for web application frameworks. Do you feel you need an application framework? I don't believe there's any limitation in python. I suspect it's mostly philosophical. Mike From pyro9219 at gmail.com Thu Oct 19 21:56:31 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Thu, 19 Oct 2006 12:56:31 -0700 Subject: [Tutor] Generic Application Frameworks? In-Reply-To: <57B026980605A64F9B23484C5659E32E358C49@poccso.US.ad.atmel.com> References: <57B026980605A64F9B23484C5659E32E358C49@poccso.US.ad.atmel.com> Message-ID: I ran a couple searches for one, and mostly got scientific or web based projects.. I was just looking for a basic desktop framework to handle common tasks that aren't so easy to impliment like the ones I mentioned. Thanks for that repository! I hadn't seen that before.. I'm looking at plugboard now, that might be atleast a step in the right direction. I don't believe there's any limitation in python. I suspect it's mostly philosophical. <-- What did you mean by this Mike? On 10/19/06, Mike Hansen wrote: > > > From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] > On Behalf Of Chris Hengge > Sent: Thursday, October 19, 2006 1:22 PM > To: PyTutor > Subject: Re: [Tutor] Generic Application Frameworks? > > > Just incase anyone doesn't want to see that document to know > what I'm asking about... > > Razor/Carbon includes: > Auto Update > Plugin System with management > Error reporting > > Its got a few other features, but these are my focus. > > > On 10/19/06, Chris Hengge wrote: > > I was curious if there are any frameworks around like > carbon/razor implimented in razor? > > Here's a link with information about razor (.net 1.1 > versin of carbon) > http://www.codeproject.com/cs/design/razorpt1.asp > > If not, is there any reason why? (limitation of python?) > > ----------- > > You might ask on comp.lang.python. > You might also do a search at http://cheeseshop.python.org/pypi > > I did a search for 'application framework' and came up with > http://cheeseshop.python.org/pypi/PlugBoard/0.2 > > Most of the other hits were for web application frameworks. > > Do you feel you need an application framework? > > I don't believe there's any limitation in python. I suspect it's mostly > philosophical. > > Mike > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061019/5c21c052/attachment-0001.htm From pyro9219 at gmail.com Thu Oct 19 21:59:43 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Thu, 19 Oct 2006 12:59:43 -0700 Subject: [Tutor] Generic Application Frameworks? In-Reply-To: References: <57B026980605A64F9B23484C5659E32E358C49@poccso.US.ad.atmel.com> Message-ID: http://dabodev.com/about Here we go... 3 tier application framework.. Thats almost perfect.. I suppose I could figure out the auto update thing myself... since that is all that it is missing for what I was wanting.. Thanks again! On 10/19/06, Chris Hengge wrote: > > I ran a couple searches for one, and mostly got scientific or web based > projects.. I was just looking for a basic desktop framework to handle common > tasks that aren't so easy to impliment like the ones I mentioned. > > Thanks for that repository! I hadn't seen that before.. > I'm looking at plugboard now, that might be atleast a step in the right > direction. > > I don't believe there's any limitation in python. I suspect it's mostly > philosophical. <-- What did you mean by this Mike? > > On 10/19/06, Mike Hansen wrote: > > > > > > From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] > > On Behalf Of Chris Hengge > > Sent: Thursday, October 19, 2006 1:22 PM > > To: PyTutor > > Subject: Re: [Tutor] Generic Application Frameworks? > > > > > > Just incase anyone doesn't want to see that document to know > > what I'm asking about... > > > > Razor/Carbon includes: > > Auto Update > > Plugin System with management > > Error reporting > > > > Its got a few other features, but these are my focus. > > > > > > On 10/19/06, Chris Hengge wrote: > > > > I was curious if there are any frameworks around like > > carbon/razor implimented in razor? > > > > Here's a link with information about razor (.net 1.1 > > versin of carbon) > > http://www.codeproject.com/cs/design/razorpt1.asp > > > > If not, is there any reason why? (limitation of python?) > > > > ----------- > > > > You might ask on comp.lang.python. > > You might also do a search at http://cheeseshop.python.org/pypi > > > > I did a search for 'application framework' and came up with > > http://cheeseshop.python.org/pypi/PlugBoard/0.2 > > > > Most of the other hits were for web application frameworks. > > > > Do you feel you need an application framework? > > > > I don't believe there's any limitation in python. I suspect it's mostly > > philosophical. > > > > Mike > > > > > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061019/e9952fb2/attachment.htm From Mike.Hansen at atmel.com Thu Oct 19 22:20:35 2006 From: Mike.Hansen at atmel.com (Mike Hansen) Date: Thu, 19 Oct 2006 14:20:35 -0600 Subject: [Tutor] Generic Application Frameworks? Message-ID: <57B026980605A64F9B23484C5659E32E358C51@poccso.US.ad.atmel.com> [...] I don't believe there's any limitation in python. I suspect it's mostly philosophical. <-- What did you mean by this Mike? ---------------- import this "Simple is better than complex." "Complex is better than complicated." I'm kind of torn on using frameworks. I'm but a simple caveman programmer(*), and some of these frameworks seem pretty complicated. On the other hand, they sound like they can speed up development. One of these days I'll probably take a good look at Django(**), and see if I can whip out a CRUD(***) web app. * - Phil Hartman SNL("I'm but a simple caveman lawyer") ** - A web application framework *** - CRUD...Create Update Delete Mike From wescpy at gmail.com Thu Oct 19 22:46:46 2006 From: wescpy at gmail.com (wesley chun) Date: Thu, 19 Oct 2006 13:46:46 -0700 Subject: [Tutor] property built-in In-Reply-To: <1161279430.8103.804.camel@www.venix.com> References: <4537AFC7.80504@localhost> <1161279430.8103.804.camel@www.venix.com> Message-ID: <78b3a9580610191346h3b870a5eiaad0a4daefe75064@mail.gmail.com> > > x= property(**x()) > > > > questions: > > 1: why doesn't there have to be a self in x()? > > x is not a "normal" class method. It is only used as a container to > hold the "real" methods which are returned in the locals() dictionary. on a related note, if you're using Python 2.4 and newer, you can simplfy your code a bit by replacing the call to property() with a decorator for x, as in: @property def x(): : cheers, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From dyoo at hkn.eecs.berkeley.edu Thu Oct 19 23:10:41 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 19 Oct 2006 14:10:41 -0700 (PDT) Subject: [Tutor] Trying to extract the last line of a text file In-Reply-To: References: <584940990610191211rf70b3a2ybed72788a36806d3@mail.gmail.com> Message-ID: >> file('filename.txt').readlines()[-1] > Not to hijack the thread, but what stops you from just putting a > file.close() after your example line? Which file should file.close() close? The problem is that we don't have a handle on the particular file we want to close off. From dyoo at hkn.eecs.berkeley.edu Thu Oct 19 23:12:13 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 19 Oct 2006 14:12:13 -0700 (PDT) Subject: [Tutor] Trying to extract the last line of a text file In-Reply-To: References: Message-ID: > first count the number of lines in the file by using a loop. Use a > second loop and when teh counter reaches the num_of_lines values: take > the line. > > Is there any other way to do it?? Yes, there's a way to do it in one pass: you can keep track of the very last line you've read from the file at any given time. As soon as you hit the end of the file, the auxiliary "last seen line" must be the last line. From pyro9219 at gmail.com Thu Oct 19 23:14:06 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Thu, 19 Oct 2006 14:14:06 -0700 Subject: [Tutor] Trying to extract the last line of a text file In-Reply-To: References: <584940990610191211rf70b3a2ybed72788a36806d3@mail.gmail.com> Message-ID: Oh wow.. I totally missed that... nevermind.. ignore that question =D On 10/19/06, Danny Yoo wrote: > > > >> file('filename.txt').readlines()[-1] > > > Not to hijack the thread, but what stops you from just putting a > > file.close() after your example line? > > > Which file should file.close() close? The problem is that we don't have a > handle on the particular file we want to close off. > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061019/3b776f4a/attachment.htm From dyoo at hkn.eecs.berkeley.edu Thu Oct 19 23:15:11 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 19 Oct 2006 14:15:11 -0700 (PDT) Subject: [Tutor] Trying to extract the last line of a text file In-Reply-To: <584940990610191211rf70b3a2ybed72788a36806d3@mail.gmail.com> References: <584940990610191211rf70b3a2ybed72788a36806d3@mail.gmail.com> Message-ID: > This works as well > > file('filename.txt').readlines()[-1] > > Some will say that this is no good because the file is still open. > However I've been told that when the object is cleaned the file is > closed so it should be fine. It matters in an implementation like Jython, which depends on the underlying Java runtime's garage collector to reap values. The issue there is that we don't control the frequency of the garbage collector, so we may exhaust all open files that the system provides before the collector kicks in. From pyro9219 at gmail.com Thu Oct 19 23:16:29 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Thu, 19 Oct 2006 14:16:29 -0700 Subject: [Tutor] Generic Application Frameworks? In-Reply-To: <57B026980605A64F9B23484C5659E32E358C51@poccso.US.ad.atmel.com> References: <57B026980605A64F9B23484C5659E32E358C51@poccso.US.ad.atmel.com> Message-ID: About frameworks being complicated... I'm sure there are exceptions to this, but my experience is that if you think of a framework as a tool, sure , you gotta learn how to use it first, which means it will slow you down upfront.. But.. once you know how to use the tool in theory it will make your job easier... again, there are always exceptions.. :] Thanks for your feedback. On 10/19/06, Mike Hansen wrote: > > [...] > > I don't believe there's any limitation in python. I suspect it's > mostly > philosophical. <-- What did you mean by this Mike? > > ---------------- > > import this > > "Simple is better than complex." > "Complex is better than complicated." > > I'm kind of torn on using frameworks. I'm but a simple caveman > programmer(*), and some of these frameworks seem pretty complicated. On > the other hand, they sound like they can speed up development. One of > these days I'll probably take a good look at Django(**), and see if I > can whip out a CRUD(***) web app. > > * - Phil Hartman SNL("I'm but a simple caveman lawyer") > ** - A web application framework > *** - CRUD...Create Update Delete > > Mike > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061019/12427279/attachment.html From dyoo at hkn.eecs.berkeley.edu Thu Oct 19 23:35:18 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 19 Oct 2006 14:35:18 -0700 (PDT) Subject: [Tutor] Trying to extract the last line of a text file In-Reply-To: References: <584940990610191211rf70b3a2ybed72788a36806d3@mail.gmail.com> Message-ID: >> >> file('filename.txt').readlines()[-1] >> >> > Not to hijack the thread, but what stops you from just putting a >> > file.close() after your example line? >> >> Which file should file.close() close? The problem is that we don't >> have a handle on the particular file we want to close off. >> > Oh wow.. I totally missed that... nevermind.. ignore that question =D Hi Chris, No, no, it's an interesting one. It turns out that there IS a way to sorta do what you're thinking: ############################################################ class FilePool: """A small demo class to show how we might keep track of files opened with us.""" def __init__(self): self.pool = [] def open(self, filename): f = open(filename) self.pool.append(f) return f def closeAll(self): for f in self.pool: f.close() self.pool = [] fp = FilePool() ############################################################ Once we have FilePool, we might say something like: ################################################################## print "the last line is:", fp.open('filename.txt').readlines()[-1] fp.closeAll() ################################################################## This is similar in spirit to the idea of "autorelease" memory pools used by the Objective C language. We use some resource "manager" that does keep a handle on resources. That manager then has the power and responsiblity to call close() at some point. So one might imagine doing something like: ############################################ create a manager try: ... # use resources that the manager doles out finally: use the manager to close everything down ############################################ So your question may have seemed like a dumb one, but it's actually a good one. *grin* Good luck! From pyro9219 at gmail.com Thu Oct 19 23:37:21 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Thu, 19 Oct 2006 14:37:21 -0700 Subject: [Tutor] Trying to extract the last line of a text file In-Reply-To: References: <584940990610191211rf70b3a2ybed72788a36806d3@mail.gmail.com> Message-ID: Very informative and creative reply! Thanks for sharing :] On 10/19/06, Danny Yoo wrote: > > > > >> >> file('filename.txt').readlines()[-1] > >> > >> > Not to hijack the thread, but what stops you from just putting a > >> > file.close() after your example line? > >> > >> Which file should file.close() close? The problem is that we don't > >> have a handle on the particular file we want to close off. > >> > > Oh wow.. I totally missed that... nevermind.. ignore that question =D > > > Hi Chris, > > No, no, it's an interesting one. It turns out that there IS a way to > sorta do what you're thinking: > > ############################################################ > class FilePool: > """A small demo class to show how we might keep track of > files opened with us.""" > def __init__(self): > self.pool = [] > > def open(self, filename): > f = open(filename) > self.pool.append(f) > return f > > def closeAll(self): > for f in self.pool: > f.close() > self.pool = [] > fp = FilePool() > ############################################################ > > > Once we have FilePool, we might say something like: > > ################################################################## > print "the last line is:", fp.open('filename.txt').readlines()[-1] > fp.closeAll() > ################################################################## > > > This is similar in spirit to the idea of "autorelease" memory pools used > by the Objective C language. We use some resource "manager" that does > keep a handle on resources. That manager then has the power and > responsiblity to call close() at some point. So one might imagine doing > something like: > > ############################################ > create a manager > try: > ... # use resources that the manager doles out > finally: > use the manager to close everything down > ############################################ > > > So your question may have seemed like a dumb one, but it's actually a good > one. *grin* > > > Good luck! > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061019/65739d51/attachment.htm From ajkadri at googlemail.com Thu Oct 19 23:48:57 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Thu, 19 Oct 2006 22:48:57 +0100 Subject: [Tutor] Trying to extract the last line of a text file In-Reply-To: References: Message-ID: Danny.... This is a very clean way to get the last line. Thanks. Regards, Asrarahmed On 10/19/06, Danny Yoo wrote: > > > first count the number of lines in the file by using a loop. Use a > > second loop and when teh counter reaches the num_of_lines values: take > > the line. > > > > Is there any other way to do it?? > > Yes, there's a way to do it in one pass: you can keep track of the very > last line you've read from the file at any given time. As soon as you hit > the end of the file, the auxiliary "last seen line" must be the last line. > -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061019/38a7f509/attachment.html From ajkadri at googlemail.com Thu Oct 19 23:51:44 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Thu, 19 Oct 2006 22:51:44 +0100 Subject: [Tutor] How to know which module the function belongs to...?? Message-ID: I tried to use getchar()... But I dont know which module it belongs (this I came to know when I encountered an error)..!! Is there a good documentation by which we can search both ways... Look at modules as well as search for a particular function and locate which module it belongs to... Thanks.. Regards, Asrar -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061019/1e7de642/attachment.htm From rabidpoobear at gmail.com Fri Oct 20 00:17:33 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 19 Oct 2006 17:17:33 -0500 Subject: [Tutor] Location of found item in list. In-Reply-To: References: <45371E29.2070608@gmail.com> Message-ID: <4537F97D.7040900@gmail.com> Chris Hengge wrote: > This is the solution I came up with. > > for dirItem in directoryList: > directoryListLower.append(dirItem.lower()) > > #---Loop for file name comparison. > for item in lineList: # For every item in the 'lineList' > if item in directoryList: # If the item is also in 'directoryList' > # Print out so I know it is found. > print match.ljust(20) + item.ljust(20) \ > + directoryList[directoryList.index (item)] > else: # If it isn't found, print what didn't match. > # Use the lowercase form from each list to find what > didn't match. > if item.lower() in directoryListLower: > # Print out so I can see why it failed. > print fail.ljust(20) + item.ljust(20) + \ > directoryList[directoryListLower.index(item.lower())] > os.rename(pathName + \ > directoryList[directoryListLower.index > (item.lower())], \ > pathName + item) It looks like it would do what you wanted. The lines are a little long, but sometimes that can't be helped. If you could come up with shorter variable names that were still descriptive, maybe that would help. also, you can use a list comprehension for the first two lines: directoryListLower = [item.lower() for item in directoryList] IF you're not familiar with list comprehensions this may look a tad scary, but once you learn them, you'll be pleased to see something in this form :) also, I assume you initialized directoryListLower at some other point in the code, since append() doesn't work unless the variable is tied to a list object, so in this syntax you could skip that line as well. I'm not really sure why you don't want to use an inner loop, so you don't have to use the index, but I guess 'to each his own'. I'd probably do it this way: for line in lineList: found = False for filename in directoryList: if line.lower() == filename.lower(): found = True if line == filename: #an exact match print "%s is already set to %s" % (line,filename) #add a break here if you want :) else:#we found the right directory entry, but we need to change the case. print "Changing %s to %s." % (filename,line) os.rename(filename,line) #add a break here if you want :) if not found: print "The item %s wasn't found in the directory listing." % line Then you don't need the intermediate list of lowered items, and you don't have those really long indexing lines. But your way is fine :) Good luck on your future Python endeavours. -Luke From kent37 at tds.net Fri Oct 20 00:20:51 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 19 Oct 2006 18:20:51 -0400 Subject: [Tutor] property built-in In-Reply-To: <78b3a9580610191346h3b870a5eiaad0a4daefe75064@mail.gmail.com> References: <4537AFC7.80504@localhost> <1161279430.8103.804.camel@www.venix.com> <78b3a9580610191346h3b870a5eiaad0a4daefe75064@mail.gmail.com> Message-ID: <4537FA43.2050905@tds.net> wesley chun wrote: >>> x= property(**x()) >>> >>> questions: >>> 1: why doesn't there have to be a self in x()? >> x is not a "normal" class method. It is only used as a container to >> hold the "real" methods which are returned in the locals() dictionary. > > > on a related note, if you're using Python 2.4 and newer, you can > simplfy your code a bit by replacing the call to property() with a > decorator for x, as in: > > @property > def x(): > : I don't think so. This will wrap x itself as a property, equivalent to x = property(x) which is not the same as Lloyd's code which turns the dict returned by x into a property: x = property(**x()) Kent From kent37 at tds.net Fri Oct 20 00:25:14 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 19 Oct 2006 18:25:14 -0400 Subject: [Tutor] Trying to extract the last line of a text file In-Reply-To: References: <584940990610191211rf70b3a2ybed72788a36806d3@mail.gmail.com> Message-ID: <4537FB4A.3060307@tds.net> Danny Yoo wrote: > >>>>> file('filename.txt').readlines()[-1] >>>> Not to hijack the thread, but what stops you from just putting a >>>> file.close() after your example line? >>> Which file should file.close() close? The problem is that we don't >>> have a handle on the particular file we want to close off. >>> >> Oh wow.. I totally missed that... nevermind.. ignore that question =D > > > Hi Chris, > > No, no, it's an interesting one. It turns out that there IS a way to > sorta do what you're thinking: > > ############################################################ > class FilePool: > """A small demo class to show how we might keep track of > files opened with us.""" > def __init__(self): > self.pool = [] > > def open(self, filename): > f = open(filename) > self.pool.append(f) > return f > > def closeAll(self): > for f in self.pool: > f.close() > self.pool = [] > fp = FilePool() > ############################################################ > > > Once we have FilePool, we might say something like: > > ################################################################## > print "the last line is:", fp.open('filename.txt').readlines()[-1] > fp.closeAll() > ################################################################## Wow, that seems like overkill when you can just write f = open('filename.txt') f.readlines() f.close() In CPython (the regular Python that we usually talk about here, implemented in C) a file will be closed automatically as soon as there are no references to the file because CPython garbage collects objects immediately. This behaviour is not guaranteed by the language though and it is different in Jython. > > > This is similar in spirit to the idea of "autorelease" memory pools used > by the Objective C language. We use some resource "manager" that does > keep a handle on resources. That manager then has the power and > responsiblity to call close() at some point. So one might imagine doing > something like: > > ############################################ > create a manager > try: > ... # use resources that the manager doles out > finally: > use the manager to close everything down > ############################################ In Python 2.5 you can use with: to do this: with open('filename.txt') as f: f.readlines() f is guaranteed to be closed when the block exits. Kent From kent37 at tds.net Fri Oct 20 00:27:20 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 19 Oct 2006 18:27:20 -0400 Subject: [Tutor] How to know which module the function belongs to...?? In-Reply-To: References: Message-ID: <4537FBC8.10105@tds.net> Asrarahmed Kadri wrote: > > I tried to use getchar()... But I dont know which module it belongs > (this I came to know when I encountered an error)..!! > > Is there a good documentation by which we can search both ways... Look > at modules as well as search for a particular function and locate which > module it belongs to... Try this index: http://docs.python.org/lib/genindex.html Kent From john at fouhy.net Fri Oct 20 00:42:47 2006 From: john at fouhy.net (John Fouhy) Date: Fri, 20 Oct 2006 11:42:47 +1300 Subject: [Tutor] property built-in In-Reply-To: <4537FA43.2050905@tds.net> References: <4537AFC7.80504@localhost> <1161279430.8103.804.camel@www.venix.com> <78b3a9580610191346h3b870a5eiaad0a4daefe75064@mail.gmail.com> <4537FA43.2050905@tds.net> Message-ID: <5e58f2e40610191542o1bc42e31o6b753d424db9fd96@mail.gmail.com> On 20/10/06, Kent Johnson wrote: > wesley chun wrote: > > on a related note, if you're using Python 2.4 and newer, you can > > simplfy your code a bit by replacing the call to property() with a > > decorator for x, as in: > > > > @property > > def x(): > > : > > I don't think so. This will wrap x itself as a property, equivalent to > x = property(x) > which is not the same as Lloyd's code which turns the dict returned by x > into a property: > x = property(**x()) There's some discussion in the cookbook about how to make a property decorator: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/410698 I'm not sure I'd use it, though --- seems a lot of effort to go to, when all it would do is trade "foo = property(**foo())" for "@Property".. There's also a good point made here: http://www.artima.com/forums/flat.jsp?forum=122&thread=119914 Basically, if you want a read-only attribute, you _can_ create it by using the built-in property as a decorator: @property def x(self): return self.__x equivalent to def x(self): return self.__x x = property(x) (which works because fget is the first keyword argument for property()) -- John. From ajkadri at googlemail.com Fri Oct 20 01:11:30 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Fri, 20 Oct 2006 00:11:30 +0100 Subject: [Tutor] Resources for Tkinter... Message-ID: Folks, I have the Tkinter book by Grayson (Python and Tkinter Programming).. *But I must say, its quite boring..* Do you have any suggestions for a nice book or web resource..?? Thanks, REgards, Asrarahmed -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061020/8db2bd6c/attachment.htm From bgailer at alum.rpi.edu Fri Oct 20 01:24:06 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu, 19 Oct 2006 16:24:06 -0700 Subject: [Tutor] Resources for Tkinter... In-Reply-To: References: Message-ID: <45380916.8080302@alum.rpi.edu> Asrarahmed Kadri wrote: > > Folks, > > I have the Tkinter book by Grayson (Python and Tkinter Programming).. > *But I must say, its quite boring..* Boring - what exactly do you mean? What would make a book "nice"? And please tell us the meaning or significance of "To HIM you shall return." > > Do you have any suggestions for a nice book or web resource..?? > -- Bob Gailer 510-978-4454 From DFeise at ea.com Fri Oct 20 01:22:55 2006 From: DFeise at ea.com (Feise, David) Date: Thu, 19 Oct 2006 16:22:55 -0700 Subject: [Tutor] Resources for Tkinter... In-Reply-To: Message-ID: <23EEDA6DFA85B14EA82718973A598AC909314747@EAHQ-CSMB7.rws.ad.ea.com> I really got a lot out of Thinking in Tkinter: http://www.ferg.org/thinking_in_tkinter/ It doesn't delve too deeply, but it's still a good resource. This New Mexico Tech website is a good reference once you've got some of the basics: http://infohost.nmt.edu/tcc/help/pubs/tkinter/ -Dave ________________________________ From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Asrarahmed Kadri Sent: Thursday, October 19, 2006 4:12 PM To: pythontutor Subject: [Tutor] Resources for Tkinter... Folks, I have the Tkinter book by Grayson (Python and Tkinter Programming).. But I must say, its quite boring.. Do you have any suggestions for a nice book or web resource..?? Thanks, REgards, Asrarahmed -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061019/38108b58/attachment.html From pyro9219 at gmail.com Fri Oct 20 01:30:58 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Thu, 19 Oct 2006 16:30:58 -0700 Subject: [Tutor] Trying to extract the last line of a text file In-Reply-To: <4537FB4A.3060307@tds.net> References: <584940990610191211rf70b3a2ybed72788a36806d3@mail.gmail.com> <4537FB4A.3060307@tds.net> Message-ID: I thought my solution was the easiest.. but I guess everyone skipped it =P On 10/19/06, Kent Johnson wrote: > > Danny Yoo wrote: > > > >>>>> file('filename.txt').readlines()[-1] > >>>> Not to hijack the thread, but what stops you from just putting a > >>>> file.close() after your example line? > >>> Which file should file.close() close? The problem is that we don't > >>> have a handle on the particular file we want to close off. > >>> > >> Oh wow.. I totally missed that... nevermind.. ignore that question =D > > > > > > Hi Chris, > > > > No, no, it's an interesting one. It turns out that there IS a way to > > sorta do what you're thinking: > > > > ############################################################ > > class FilePool: > > """A small demo class to show how we might keep track of > > files opened with us.""" > > def __init__(self): > > self.pool = [] > > > > def open(self, filename): > > f = open(filename) > > self.pool.append(f) > > return f > > > > def closeAll(self): > > for f in self.pool: > > f.close() > > self.pool = [] > > fp = FilePool() > > ############################################################ > > > > > > Once we have FilePool, we might say something like: > > > > ################################################################## > > print "the last line is:", fp.open('filename.txt').readlines()[-1] > > fp.closeAll() > > ################################################################## > > Wow, that seems like overkill when you can just write > f = open('filename.txt') > f.readlines() > f.close() > > In CPython (the regular Python that we usually talk about here, > implemented in C) a file will be closed automatically as soon as there > are no references to the file because CPython garbage collects objects > immediately. This behaviour is not guaranteed by the language though and > it is different in Jython. > > > > > > This is similar in spirit to the idea of "autorelease" memory pools used > > by the Objective C language. We use some resource "manager" that does > > keep a handle on resources. That manager then has the power and > > responsiblity to call close() at some point. So one might imagine doing > > something like: > > > > ############################################ > > create a manager > > try: > > ... # use resources that the manager doles out > > finally: > > use the manager to close everything down > > ############################################ > > In Python 2.5 you can use with: to do this: > > with open('filename.txt') as f: > f.readlines() > > f is guaranteed to be closed when the block exits. > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061019/68034a6b/attachment.htm From ajkadri at googlemail.com Fri Oct 20 01:49:30 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Fri, 20 Oct 2006 00:49:30 +0100 Subject: [Tutor] Resources for Tkinter... In-Reply-To: <23EEDA6DFA85B14EA82718973A598AC909314747@EAHQ-CSMB7.rws.ad.ea.com> References: <23EEDA6DFA85B14EA82718973A598AC909314747@EAHQ-CSMB7.rws.ad.ea.com> Message-ID: I came across Thinking in Tkinter a few days back., and I found it interesting but then I didnt get the print out ( dont know why)... Thanks for that. Regards, Asrarahmed PS: To Bob:: To HIM you shall return--->> It means that one day every person has to die and return to the Almighty to get the reward or punishment for the deeds. It helps me in remembering this ULTIMATE reality... On 10/20/06, Feise, David wrote: > > I really got a lot out of Thinking in Tkinter: > http://www.ferg.org/thinking_in_tkinter/ > > It doesn't delve too deeply, but it's still a good resource. > > > > This New Mexico Tech website is a good reference once you've got some of > the basics: http://infohost.nmt.edu/tcc/help/pubs/tkinter/ > > > > -Dave > > > ------------------------------ > > *From:* tutor-bounces at python.org [mailto:tutor-bounces at python.org] *On > Behalf Of *Asrarahmed Kadri > *Sent:* Thursday, October 19, 2006 4:12 PM > *To:* pythontutor > *Subject:* [Tutor] Resources for Tkinter... > > > > > > Folks, > > > > I have the Tkinter book by Grayson (Python and Tkinter Programming).. *But > I must say, its quite boring..* > > > > Do you have any suggestions for a nice book or web resource..?? > > > > Thanks, > > > > REgards, > > Asrarahmed > > > -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061020/33d50761/attachment-0001.html From rabidpoobear at gmail.com Fri Oct 20 02:25:02 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 19 Oct 2006 19:25:02 -0500 Subject: [Tutor] Trying to extract the last line of a text file In-Reply-To: References: <584940990610191211rf70b3a2ybed72788a36806d3@mail.gmail.com> <4537FB4A.3060307@tds.net> Message-ID: <4538175E.50008@gmail.com> Chris Hengge wrote: > I thought my solution was the easiest.. but I guess everyone skipped it =P No, we didn't skip it, but as we're all programmers here, we showed alternate ways that it could be done. Your post is the one that sparked the whole 'garbage collection' thing, you'll notice. Now, I don't want to be left out of the loop on this, and the first thing I thought of when I read his question about how to read the last line was: Well, what if he wants to read the last line of 100 20 mb files? Does he really want to read all of these into memory just to get the last line? I wouldn't think so! So I've made an alternate solution using seek. The last line can't be more than 1000 chars long, or whatever the Python maximum recursion depth happens to be at runtime, but you could easily change this into a non-recursive implementation if you so desired. I just wanted to be cool :) #read_last_line.py f = file('wii.txt','r') f.seek(-1,2)#start at end of file. if f.read(1) == '\n':#if file ends with a newline: f.seek(-3,1)#start at right before the newline. else: f.seek(-1,1)#just start at the end. def prevchar(fileobj): achar = fileobj.read(1) if achar == '\n': return '' else: fileobj.seek(-2,1) return prevchar(fileobj)+achar print prevchar(f) From pyro9219 at gmail.com Fri Oct 20 04:28:59 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Thu, 19 Oct 2006 19:28:59 -0700 Subject: [Tutor] Trying to extract the last line of a text file In-Reply-To: <4538175E.50008@gmail.com> References: <584940990610191211rf70b3a2ybed72788a36806d3@mail.gmail.com> <4537FB4A.3060307@tds.net> <4538175E.50008@gmail.com> Message-ID: I dont care for slow... I dont use computers with less then 1gb of ram.. (all my systems have 2gb), I hate to wait... =D If I've got memory to use, I intend to use it! As for reading 100 20mb files, I'd do one at a time, then dump the variable storing the data, or reset/re-use. Just my take though. On 10/19/06, Luke Paireepinart wrote: > > Chris Hengge wrote: > > I thought my solution was the easiest.. but I guess everyone skipped it > =P > No, we didn't skip it, > but as we're all programmers here, we showed alternate ways that it > could be done. > Your post is the one that sparked the whole 'garbage collection' thing, > you'll notice. > > Now, I don't want to be left out of the loop on this, > and the first thing I thought of when I read his question about how to > read the last line was: > Well, what if he wants to read the last line of 100 20 mb files? > Does he really want to read all of these into memory just to get the > last line? > I wouldn't think so! > So I've made an alternate solution using seek. > The last line can't be more than 1000 chars long, or whatever the Python > maximum recursion depth happens to be at runtime, > but you could easily change this into a non-recursive implementation if > you so desired. > I just wanted to be cool :) > > #read_last_line.py > f = file('wii.txt','r') > f.seek(-1,2)#start at end of file. > if f.read(1) == '\n':#if file ends with a newline: > f.seek(-3,1)#start at right before the newline. > else: > f.seek(-1,1)#just start at the end. > def prevchar(fileobj): > achar = fileobj.read(1) > if achar == '\n': return '' > else: > fileobj.seek(-2,1) > return prevchar(fileobj)+achar > print prevchar(f) > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061019/06a29028/attachment.html From pyro9219 at gmail.com Fri Oct 20 04:30:04 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Thu, 19 Oct 2006 19:30:04 -0700 Subject: [Tutor] Trying to extract the last line of a text file In-Reply-To: References: <584940990610191211rf70b3a2ybed72788a36806d3@mail.gmail.com> <4537FB4A.3060307@tds.net> <4538175E.50008@gmail.com> Message-ID: More on that.. some of the file I work with are thousands of lines long... one is even 10's of thousands.. so reading the entire thing into ram is MUCH faster then reading line by line with the filestream open. On 10/19/06, Chris Hengge wrote: > > I dont care for slow... I dont use computers with less then 1gb of ram.. > (all my systems have 2gb), I hate to wait... =D If I've got memory to use, I > intend to use it! > > As for reading 100 20mb files, I'd do one at a time, then dump the > variable storing the data, or reset/re-use. Just my take though. > > On 10/19/06, Luke Paireepinart wrote: > > > > Chris Hengge wrote: > > > I thought my solution was the easiest.. but I guess everyone skipped > > it =P > > No, we didn't skip it, > > but as we're all programmers here, we showed alternate ways that it > > could be done. > > Your post is the one that sparked the whole 'garbage collection' thing, > > you'll notice. > > > > Now, I don't want to be left out of the loop on this, > > and the first thing I thought of when I read his question about how to > > read the last line was: > > Well, what if he wants to read the last line of 100 20 mb files? > > Does he really want to read all of these into memory just to get the > > last line? > > I wouldn't think so! > > So I've made an alternate solution using seek. > > The last line can't be more than 1000 chars long, or whatever the Python > > maximum recursion depth happens to be at runtime, > > but you could easily change this into a non-recursive implementation if > > you so desired. > > I just wanted to be cool :) > > > > #read_last_line.py > > f = file('wii.txt','r') > > f.seek(-1,2)#start at end of file. > > if f.read(1) == '\n':#if file ends with a newline: > > f.seek(-3,1)#start at right before the newline. > > else: > > f.seek(-1,1)#just start at the end. > > def prevchar(fileobj): > > achar = fileobj.read(1) > > if achar == '\n': return '' > > else: > > fileobj.seek(-2,1) > > return prevchar(fileobj)+achar > > print prevchar(f) > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061019/5b695fe0/attachment.htm From rabidpoobear at gmail.com Fri Oct 20 04:42:22 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 19 Oct 2006 21:42:22 -0500 Subject: [Tutor] Trying to extract the last line of a text file In-Reply-To: References: <584940990610191211rf70b3a2ybed72788a36806d3@mail.gmail.com> <4537FB4A.3060307@tds.net> <4538175E.50008@gmail.com> Message-ID: <4538378E.8090703@gmail.com> Chris Hengge wrote: > More on that.. some of the file I work with are thousands of lines > long... one is even 10's of thousands.. so reading the entire thing > into ram is MUCH faster then reading line by line with the filestream > open. Did you look at my code? It doesn't read the whole thing into ram, nor does it read line by line. It seeks to the end of the file (should be extremely fast) and reads backwards until it gets to a newline char. In other words: Very fast, and no extra ram usage. HTH, -Luke From pyro9219 at gmail.com Fri Oct 20 07:27:32 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Thu, 19 Oct 2006 22:27:32 -0700 Subject: [Tutor] Trying to extract the last line of a text file In-Reply-To: <4538378E.8090703@gmail.com> References: <4537FB4A.3060307@tds.net> <4538175E.50008@gmail.com> <4538378E.8090703@gmail.com> Message-ID: Oops, my mistake, I did read your code, as well as all the others and I had your code mixed with another submission. In that case, excellent contribution =D On 10/19/06, Luke Paireepinart wrote: > > Chris Hengge wrote: > > More on that.. some of the file I work with are thousands of lines > > long... one is even 10's of thousands.. so reading the entire thing > > into ram is MUCH faster then reading line by line with the filestream > > open. > Did you look at my code? > It doesn't read the whole thing into ram, nor does it read line by line. > It seeks to the end of the file (should be extremely fast) > and reads backwards until it gets to a newline char. > In other words: Very fast, and no extra ram usage. > HTH, > -Luke > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061019/be88d539/attachment.html From Christopher.Hatherly at anu.edu.au Fri Oct 20 07:31:06 2006 From: Christopher.Hatherly at anu.edu.au (Christopher Hatherly) Date: Fri, 20 Oct 2006 15:31:06 +1000 Subject: [Tutor] Best GUI toolkit? Message-ID: Hi Luke, Thanks very much! I do need some GUI widgets as well, so reckon I might try PyGame with OpenGL as you suggest, and go for a basic GUI library for PyGame. After looking round, I'm now having a closer look at Phil's Pygame Utilities (PGU - www.imitationpickles.org/pgu/ which seems pretty good so far! Cheers Chris -----Original Message----- From: Luke Paireepinart [mailto:rabidpoobear at gmail.com] Sent: Thursday, 19 October 2006 11:52 AM To: Christopher Hatherly Cc: tutor at python.org Subject: Re: [Tutor] Best GUI toolkit? Christopher Hatherly wrote: > Hi Pythonistas, > > I'm a newbie. I've worked through some introductory python books, and > feel that I now understand the logic on the coding side enough to make > the application I'm after. However I'm now trying to turn my code into > a (fairly complex) graphical app, and have found both Tkinter and > wxPython to be much more complex than perhaps they need to be (at > least for the beginner. Or perhaps I just haven't yet found a good, > easy to follow > tutorial???) > > I read somewhere that BoaConstructor was a good alternative. I > installed and had a look, and it seems promising. Just wondering if > anyone could pass on any advice before I leap into it though. > Specifically, my app needs full-screen display of lots of very simple > bitmaps with precise control over display timing (synchronising with vertical refresh etc). > Any advice much appreciated. > I'd say that it sounds like a job for Pygame, if you don't need actual GUI controls. I think if you used PyOpenGL + Pygame you could have vsync. pygame itself might have an option for this. Displaying lots of bitmaps may be painful in a GUI toolkit. HTH, -Luke > Thanks > Chris > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From janos.juhasz at VELUX.com Fri Oct 20 09:01:27 2006 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Fri, 20 Oct 2006 09:01:27 +0200 Subject: [Tutor] Trying to extract the last line of a text file In-Reply-To: Message-ID: > Danny Yoo wrote: > > > >>>>> file('filename.txt').readlines()[-1] > >>>> Not to hijack the thread, but what stops you from just putting a > >>>> file.close() after your example line? > >>> Which file should file.close() close? The problem is that we don't > >>> have a handle on the particular file we want to close off. > >>> > >> Oh wow.. I totally missed that... nevermind.. ignore that question =D > > > > > > Hi Chris, > > > Wow, that seems like overkill when you can just write > f = open('filename.txt') > f.readlines() > f.close() > In CPython (the regular Python that we usually talk about here, > implemented in C) a file will be closed automatically as soon as there > are no references to the file because CPython garbage collects objects > immediately. This behaviour is not guaranteed by the language though and > it is different in Jython. > > > > > > This is similar in spirit to the idea of "autorelease" memory pools used > > by the Objective C language. We use some resource "manager" that does > > keep a handle on resources. That manager then has the power and > > responsiblity to call close() at some point. So one might imagine doing > > something like: > > > In Python 2.5 you can use with: to do this: > with open('filename.txt') as f: > f.readlines() > > f is guaranteed to be closed when the block exits. > Kent I made a small test about, what could happen with a file object, that was opened for read, but left without closing. # we need to put something into the test file >>> fw1 = open(r'test.txt', 'w') >>> fw1.write('written by fw1') >>> fw1.close() # so we have the test file # we can open and read from it >>> fr1 = open(r'test.txt', 'r') >>> fr1.readlines() ['written by fw1'] # I left it opened. # Another instance could be opened for read again >>> fr2 = open(r'test.txt', 'r') >>> fr2.readlines() ['written by fw1'] # I left the second instance opened eighter # Someone rewrite the content of the file >>> fw2 = open(r'test.txt', 'w') >>> fw2.write('written by fw2') >>> fw2.close() # I closed it correctly after writing # The instance opened for reading could be reread >>> fr1.seek(0) >>> fr1.readlines() ['written by fw2'] >>> fr2.readlines() [] # I have extended it a little >>> fw2 = open(r'test.txt', 'w') >>> fw2.write('written by fw2 but it is extended later') >>> fw2.close() >>> fr2.read() ' but it is extended later' >>> I feel that, we can left opened files with open(filename).readlines() in a number of times, but would be problematic to do it 100 000 times in the same script. Yours sincerely, ______________________________ Janos Juhasz From ajkadri at googlemail.com Fri Oct 20 12:55:10 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Fri, 20 Oct 2006 11:55:10 +0100 Subject: [Tutor] How to get the width of teh button widget..?? Message-ID: Folks, Sorry for asking you such a trivial question.!!! But i want to size up all the buttons with the same size as the largest one in the interface.. And thats why I am asking this question.. Regards, Asrarahmed -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061020/c99bd5ba/attachment.htm From rabidpoobear at gmail.com Fri Oct 20 15:47:20 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 20 Oct 2006 08:47:20 -0500 Subject: [Tutor] How to get the width of teh button widget..?? In-Reply-To: References: Message-ID: <4538D368.8030008@gmail.com> Asrarahmed Kadri wrote: > > > > Folks, > > Sorry for asking you such a trivial question.!!! But i want to size up > all the buttons with the same size as the largest one in the > interface.. And thats why I am asking this question.. Oops, in your hurry to send the e-mail you seem to have forgotten to tell us what GUI package you're using! HTH, -Luke From hmm at woolgathering.cx Fri Oct 20 17:55:39 2006 From: hmm at woolgathering.cx (William O'Higgins Witteman) Date: Fri, 20 Oct 2006 11:55:39 -0400 Subject: [Tutor] I need a time object from the future Message-ID: <20061020155539.GA14962@sillyrabbi.dyndns.org> I've been looking into this, and I am not understanding how to get this task done. I need to be able to look at a time object and know if it si between now and a set point 120 days in the future. I can get a value for now (currently I am using datetime.datetime.now()), but I haven't found a way to get now + 120 days, or figured out how to test if a given datetime falls between the two. Any pointers would be appreciated. Thanks. -- yours, William From nephish at gmail.com Fri Oct 20 18:21:31 2006 From: nephish at gmail.com (shawn bright) Date: Fri, 20 Oct 2006 11:21:31 -0500 Subject: [Tutor] need some class / module help Message-ID: <384c93600610200921p4a3d3b50vd18b84871ca52e9c@mail.gmail.com> Hey there, I am trying to create a module with one class the module name is group.py it looks like this so far import DbConnector class Group(object): def __init__(self, id): self.id = id con = DbConnector.DbConnector() query = con.getOne("select `name`, `position` from `groups` where `id` = '"+id+"' ") self.name = query[0] self.position = query[1] def set_position(position): self.position = position con.update("update `groups` set `position` = '"+self.position+"' where `id` = '"+self.id"' ") now lets say i wanted to do mygroup = Group.group(12) position = mygroup.position() # gives me position of group where id = 12 mygroup.set_position(13) # changes value of position to 13 is this right? i would test it here, but the database is not available. I am writing this to implement an easier way to code something very long later. Just wanted to know if i am on the right track. if you have read this far, thanks ! sk -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061020/3b86e3d6/attachment.html From carlos.hanson at gmail.com Fri Oct 20 18:19:52 2006 From: carlos.hanson at gmail.com (Carlos Hanson) Date: Fri, 20 Oct 2006 09:19:52 -0700 (PDT) Subject: [Tutor] I need a time object from the future In-Reply-To: <20061020155539.GA14962@sillyrabbi.dyndns.org> References: <20061020155539.GA14962@sillyrabbi.dyndns.org> Message-ID: <50247.10.1.0.47.1161361192.squirrel@webmail.ttsd.k12.or.us> On Fri, October 20, 2006 8:55 am, William O'Higgins Witteman wrote: > I've been looking into this, and I am not understanding how to get > this task done. I need to be able to look at a time object and know > if it si between now and a set point 120 days in the future. I can > get a value for now (currently I am using datetime.datetime.now()), > but I haven't found a way to get now + 120 days, or figured out how > to test if a given datetime falls between the two. Any pointers > would be appreciated. Thanks. -- The time() function returns the current time in seconds, so one idea is adding the number of seconds for 120 days: >>> from time import time, ctime >>> help(time) Help on built-in function time: time(...) time() -> floating point number Return the current time in seconds since the Epoch. Fractions of a second may be present if the system clock provides them. >>> t1 = time() >>> t2 = t1 + 120*24*60*60 >>> now = time() >>> now > t1 and now < t2 True >>> ctime(t1) 'Fri Oct 20 09:09:26 2006' >>> ctime(t2) 'Sat Feb 17 08:09:26 2007' >>> ctime(now) 'Fri Oct 20 09:10:14 2006' -- Carlos Hanson From dkuhlman at rexx.com Fri Oct 20 18:39:10 2006 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Fri, 20 Oct 2006 09:39:10 -0700 Subject: [Tutor] I need a time object from the future In-Reply-To: <20061020155539.GA14962@sillyrabbi.dyndns.org> References: <20061020155539.GA14962@sillyrabbi.dyndns.org> Message-ID: <20061020163910.GB51353@cutter.rexx.com> On Fri, Oct 20, 2006 at 11:55:39AM -0400, William O'Higgins Witteman wrote: > I've been looking into this, and I am not understanding how to get this > task done. I need to be able to look at a time object and know if it si > between now and a set point 120 days in the future. I can get a value > for now (currently I am using datetime.datetime.now()), but I haven't > found a way to get now + 120 days, or figured out how to test if a given > datetime falls between the two. Any pointers would be appreciated. > Thanks. Take a look at mxDateTime: http://www.egenix.com/files/python/mxDateTime.html It provides arithmetic and comparison operations. Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From bgailer at alum.rpi.edu Fri Oct 20 18:48:13 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri, 20 Oct 2006 09:48:13 -0700 Subject: [Tutor] need some class / module help In-Reply-To: <384c93600610200921p4a3d3b50vd18b84871ca52e9c@mail.gmail.com> References: <384c93600610200921p4a3d3b50vd18b84871ca52e9c@mail.gmail.com> Message-ID: <4538FDCD.4040907@alum.rpi.edu> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061020/5a799254/attachment.html From nephish at gmail.com Fri Oct 20 19:58:56 2006 From: nephish at gmail.com (shawn bright) Date: Fri, 20 Oct 2006 12:58:56 -0500 Subject: [Tutor] need some class / module help In-Reply-To: <4538FDCD.4040907@alum.rpi.edu> References: <384c93600610200921p4a3d3b50vd18b84871ca52e9c@mail.gmail.com> <4538FDCD.4040907@alum.rpi.edu> Message-ID: <384c93600610201058j39bd93dbh9590dbfb3744d5ec@mail.gmail.com> Hey thanks for the help, yes, the class in in another file called group. the class Group is the only class in the module. I am doing this because the script that will call it is not the only place in all our scripts where it can be used. I have been doing stuff with python for over a year now, thought i would take advantage of some stuff that might save me some time. thanks again shawn On 10/20/06, Bob Gailer wrote: > > shawn bright wrote: > > Hey there, > > I am trying to create a module with one class > the module name is group.py > > it looks like this so far > > import DbConnector > > class Group(object): > > def __init__(self, id): > self.id = id > con = DbConnector.DbConnector() > query = con.getOne("select `name`, `position` from `groups` where > `id` = '"+id+"' ") > self.name = query[0] > self.position = query[1] > > def set_position(position): > self.position = position > con.update("update `groups` set `position` = '"+self.position+"' > where `id` = '"+self.id"' ") > > now lets say i wanted to do > > mygroup = Group.group(12) > position = mygroup.position() # gives me position of group where id = 12 > mygroup.set_position(13) # changes value of position to 13 > > Is this code in another module? > If so you need: > import group > and > mygroup = Group.group(12) > should be (module name followed by class name) > mygroup = group.Group(12). > > mygroup.position() # this is a call, and position is not callable. > should be > mygroup.position > > "select `name`, `position` from `groups` where `id` = '"+id+"' " > is OK but an easier to read version is: > "select `name`, `position` from `groups` where `id` = '%s'" % (id,) > > > is this right? > i would test it here, but the database is not available. I am writing this > to implement an easier way to code something very long later. > > Just wanted to know if i am on the right track. > > if you have read this far, thanks ! > > sk > > > > > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.orghttp://mail.python.org/mailman/listinfo/tutor > > > > -- > Bob Gailer > 510-978-4454 > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061020/d4ca163e/attachment.htm From nephish at gmail.com Fri Oct 20 20:18:10 2006 From: nephish at gmail.com (shawn bright) Date: Fri, 20 Oct 2006 13:18:10 -0500 Subject: [Tutor] need some class / module help In-Reply-To: <384c93600610201058j39bd93dbh9590dbfb3744d5ec@mail.gmail.com> References: <384c93600610200921p4a3d3b50vd18b84871ca52e9c@mail.gmail.com> <4538FDCD.4040907@alum.rpi.edu> <384c93600610201058j39bd93dbh9590dbfb3744d5ec@mail.gmail.com> Message-ID: <384c93600610201118k59d13410i6213df3f6ac35ce3@mail.gmail.com> oh, one more thing. these objects are going to be created at the rate of about 20 / minute in a thread. at some point is this going to be a problem ? do they go away over time? Or do i need to write something that will kill them? thanks sk On 10/20/06, shawn bright wrote: > > Hey thanks for the help, > yes, the class in in another file called group. the class Group is the > only class in the module. I am doing this because the script that will call > it is not the only place in all our scripts where it can be used. I have > been doing stuff with python for over a year now, thought i would take > advantage of some stuff that might save me some time. > > thanks again > shawn > > On 10/20/06, Bob Gailer wrote: > > > > shawn bright wrote: > > > > Hey there, > > > > I am trying to create a module with one class > > the module name is group.py > > > > it looks like this so far > > > > import DbConnector > > > > class Group(object): > > > > def __init__(self, id): > > self.id = id > > con = DbConnector.DbConnector() > > query = con.getOne("select `name`, `position` from `groups` > > where `id` = '"+id+"' ") > > self.name = query[0] > > self.position = query[1] > > > > def set_position(position): > > self.position = position > > con.update("update `groups` set `position` = '"+self.position+"' > > where `id` = '"+self.id"' ") > > > > now lets say i wanted to do > > > > mygroup = Group.group(12) > > position = mygroup.position() # gives me position of group where id = 12 > > mygroup.set_position(13) # changes value of position to 13 > > > > Is this code in another module? > > If so you need: > > import group > > and > > mygroup = Group.group(12) > > should be (module name followed by class name) > > mygroup = group.Group(12). > > > > mygroup.position() # this is a call, and position is not callable. > > should be > > mygroup.position > > > > "select `name`, `position` from `groups` where `id` = '"+id+"' " > > is OK but an easier to read version is: > > "select `name`, `position` from `groups` where `id` = '%s'" % (id,) > > > > > > is this right? > > i would test it here, but the database is not available. I am writing > > this to implement an easier way to code something very long later. > > > > Just wanted to know if i am on the right track. > > > > if you have read this far, thanks ! > > > > sk > > > > > > > > > > > > ------------------------------ > > > > _______________________________________________ > > Tutor maillist - Tutor at python.orghttp://mail.python.org/mailman/listinfo/tutor > > > > > > > > -- > > Bob Gailer > > 510-978-4454 > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061020/5a9d0ec3/attachment.html From simon at brunningonline.net Fri Oct 20 20:26:01 2006 From: simon at brunningonline.net (Simon Brunning) Date: Fri, 20 Oct 2006 19:26:01 +0100 Subject: [Tutor] need some class / module help In-Reply-To: <384c93600610201118k59d13410i6213df3f6ac35ce3@mail.gmail.com> References: <384c93600610200921p4a3d3b50vd18b84871ca52e9c@mail.gmail.com> <4538FDCD.4040907@alum.rpi.edu> <384c93600610201058j39bd93dbh9590dbfb3744d5ec@mail.gmail.com> <384c93600610201118k59d13410i6213df3f6ac35ce3@mail.gmail.com> Message-ID: <8c7f10c60610201126j31a41744qec4e1a90f64f6d4b@mail.gmail.com> On 10/20/06, shawn bright wrote: > oh, one more thing. > these objects are going to be created at the rate of about 20 / minute in a > thread. > at some point is this going to be a problem ? do they go away over time? > Or do i need to write something that will kill them? If you don't keep references too them (i.e. by having names that are bound to them, or by keeping them in collections) then they'll go away - usually as soon as the last reference to them is gone. -- Cheers, Simon B simon at brunningonline.net http://www.brunningonline.net/simon/blog/ From kent37 at tds.net Fri Oct 20 20:37:49 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 20 Oct 2006 14:37:49 -0400 Subject: [Tutor] I need a time object from the future In-Reply-To: <20061020155539.GA14962@sillyrabbi.dyndns.org> References: <20061020155539.GA14962@sillyrabbi.dyndns.org> Message-ID: <4539177D.4080800@tds.net> William O'Higgins Witteman wrote: > I've been looking into this, and I am not understanding how to get this > task done. I need to be able to look at a time object and know if it si > between now and a set point 120 days in the future. I can get a value > for now (currently I am using datetime.datetime.now()), but I haven't > found a way to get now + 120 days, or figured out how to test if a given > datetime falls between the two. Any pointers would be appreciated. > Thanks. You can do this with datetime.timedelta: In [1]: from datetime import datetime, timedelta In [2]: n=datetime.now() In [3]: n Out[3]: datetime.datetime(2006, 10, 20, 14, 36, 44, 453000) In [4]: later = n + timedelta(days=120) In [5]: later Out[5]: datetime.datetime(2007, 2, 17, 14, 36, 44, 453000) In [6]: n < later Out[6]: True Kent From nephish at gmail.com Fri Oct 20 20:44:20 2006 From: nephish at gmail.com (shawn bright) Date: Fri, 20 Oct 2006 13:44:20 -0500 Subject: [Tutor] need some class / module help In-Reply-To: <8c7f10c60610201126j31a41744qec4e1a90f64f6d4b@mail.gmail.com> References: <384c93600610200921p4a3d3b50vd18b84871ca52e9c@mail.gmail.com> <4538FDCD.4040907@alum.rpi.edu> <384c93600610201058j39bd93dbh9590dbfb3744d5ec@mail.gmail.com> <384c93600610201118k59d13410i6213df3f6ac35ce3@mail.gmail.com> <8c7f10c60610201126j31a41744qec4e1a90f64f6d4b@mail.gmail.com> Message-ID: <384c93600610201144s59326287p3322b859b0fbe26b@mail.gmail.com> if i name them, like bob = group.Group(some_id) ? what is going to happen is that each time, the variable will create a different object like while 1: group = group.Group(some_id) do some stuff with group. so since it keeps getting replaced, it should be ok without some way to destroy it ? thanks On 10/20/06, Simon Brunning wrote: > > On 10/20/06, shawn bright wrote: > > oh, one more thing. > > these objects are going to be created at the rate of about 20 / minute > in a > > thread. > > at some point is this going to be a problem ? do they go away over time? > > Or do i need to write something that will kill them? > > If you don't keep references too them (i.e. by having names that are > bound to them, or by keeping them in collections) then they'll go away > - usually as soon as the last reference to them is gone. > > -- > Cheers, > Simon B > simon at brunningonline.net > http://www.brunningonline.net/simon/blog/ > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061020/d556523d/attachment.htm From python at venix.com Fri Oct 20 21:11:40 2006 From: python at venix.com (Python) Date: Fri, 20 Oct 2006 15:11:40 -0400 Subject: [Tutor] need some class / module help In-Reply-To: <384c93600610201144s59326287p3322b859b0fbe26b@mail.gmail.com> References: <384c93600610200921p4a3d3b50vd18b84871ca52e9c@mail.gmail.com> <4538FDCD.4040907@alum.rpi.edu> <384c93600610201058j39bd93dbh9590dbfb3744d5ec@mail.gmail.com> <384c93600610201118k59d13410i6213df3f6ac35ce3@mail.gmail.com> <8c7f10c60610201126j31a41744qec4e1a90f64f6d4b@mail.gmail.com> <384c93600610201144s59326287p3322b859b0fbe26b@mail.gmail.com> Message-ID: <1161371500.8103.845.camel@www.venix.com> On Fri, 2006-10-20 at 13:44 -0500, shawn bright wrote: > if i name them, like bob = group.Group(some_id) ? > > what is going to happen is that each time, the variable will create a > different object > > like > while 1: > group = group.Group(some_id) > do some stuff with group. > > so since it keeps getting replaced, it should be ok without some way > to destroy it ? You can verify this by putting some kind of signal in the __del__ method. For instance: >>> class A: ... def __del__(self): print "destroyed" ... >>> bob = A() >>> bob = A() destroyed >>> dir() ['A', '__builtins__', '__doc__', '__name__', 'bob'] So you can see that binding the name "bob" to a different instance resulted in destroying the first one. > > > thanks > > > On 10/20/06, Simon Brunning wrote: > On 10/20/06, shawn bright wrote: > > oh, one more thing. > > these objects are going to be created at the rate of about > 20 / minute in a > > thread. > > at some point is this going to be a problem ? do they go > away over time? > > Or do i need to write something that will kill them? > > If you don't keep references too them (i.e. by having names > that are > bound to them, or by keeping them in collections) then they'll > go away > - usually as soon as the last reference to them is gone. > > -- > Cheers, > Simon B > simon at brunningonline.net > http://www.brunningonline.net/simon/blog/ > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From nephish at gmail.com Fri Oct 20 21:22:24 2006 From: nephish at gmail.com (shawn bright) Date: Fri, 20 Oct 2006 14:22:24 -0500 Subject: [Tutor] need some class / module help In-Reply-To: <1161371500.8103.845.camel@www.venix.com> References: <384c93600610200921p4a3d3b50vd18b84871ca52e9c@mail.gmail.com> <4538FDCD.4040907@alum.rpi.edu> <384c93600610201058j39bd93dbh9590dbfb3744d5ec@mail.gmail.com> <384c93600610201118k59d13410i6213df3f6ac35ce3@mail.gmail.com> <8c7f10c60610201126j31a41744qec4e1a90f64f6d4b@mail.gmail.com> <384c93600610201144s59326287p3322b859b0fbe26b@mail.gmail.com> <1161371500.8103.845.camel@www.venix.com> Message-ID: <384c93600610201222p300c228id100951d7d22aa5d@mail.gmail.com> way cool, thanks much guys. sk On 10/20/06, Python wrote: > > On Fri, 2006-10-20 at 13:44 -0500, shawn bright wrote: > > if i name them, like bob = group.Group(some_id) ? > > > > what is going to happen is that each time, the variable will create a > > different object > > > > like > > while 1: > > group = group.Group(some_id) > > do some stuff with group. > > > > so since it keeps getting replaced, it should be ok without some way > > to destroy it ? > > You can verify this by putting some kind of signal in the __del__ > method. For instance: > > >>> class A: > ... def __del__(self): print "destroyed" > ... > >>> bob = A() > >>> bob = A() > destroyed > >>> dir() > ['A', '__builtins__', '__doc__', '__name__', 'bob'] > > > So you can see that binding the name "bob" to a different instance > resulted in destroying the first one. > > > > > > > thanks > > > > > > On 10/20/06, Simon Brunning wrote: > > On 10/20/06, shawn bright wrote: > > > oh, one more thing. > > > these objects are going to be created at the rate of about > > 20 / minute in a > > > thread. > > > at some point is this going to be a problem ? do they go > > away over time? > > > Or do i need to write something that will kill them? > > > > If you don't keep references too them (i.e. by having names > > that are > > bound to them, or by keeping them in collections) then they'll > > go away > > - usually as soon as the last reference to them is gone. > > > > -- > > Cheers, > > Simon B > > simon at brunningonline.net > > http://www.brunningonline.net/simon/blog/ > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > -- > Lloyd Kvam > Venix Corp > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061020/9e5c2ec2/attachment-0001.html From pyro9219 at gmail.com Fri Oct 20 22:00:03 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Fri, 20 Oct 2006 13:00:03 -0700 Subject: [Tutor] Best way to replace items in a list. Message-ID: I'm trying to build a little piece of code that replaces an item in a list. Here is a sample of what I'd like to do. str = "This was replaced" ff item in list: replace item with str I know I can do list.remove(item), but how do I place str back into that exact location? Is this how / best way? if item in list: loc = list.index(item) list.remove(item) list.insert(loc, str) Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061020/6afaa45e/attachment.htm From jason.massey at gmail.com Fri Oct 20 22:02:44 2006 From: jason.massey at gmail.com (Jason Massey) Date: Fri, 20 Oct 2006 15:02:44 -0500 Subject: [Tutor] Best way to replace items in a list. In-Reply-To: References: Message-ID: <7e3eab2c0610201302h724f9e38q25c1e2152c24f814@mail.gmail.com> Why not: if item in list: loc = list.index(item) list[loc] = str On 10/20/06, Chris Hengge wrote: > > I'm trying to build a little piece of code that replaces an item in a > list. > > Here is a sample of what I'd like to do. > > str = "This was replaced" > > ff item in list: > replace item with str > > I know I can do list.remove(item), but how do I place str back into that > exact location? > > Is this how / best way? > > if item in list: > loc = list.index(item) > list.remove(item) > list.insert(loc, str) > > Thanks. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061020/df2615b6/attachment.html From pyro9219 at gmail.com Fri Oct 20 22:17:48 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Fri, 20 Oct 2006 13:17:48 -0700 Subject: [Tutor] Best way to replace items in a list. In-Reply-To: <7e3eab2c0610201302h724f9e38q25c1e2152c24f814@mail.gmail.com> References: <7e3eab2c0610201302h724f9e38q25c1e2152c24f814@mail.gmail.com> Message-ID: Will that replace the location? or add to it? Thanks. On 10/20/06, Jason Massey wrote: > > Why not: > > if item in list: > loc = list.index(item) > list[loc] = str > > > > On 10/20/06, Chris Hengge < pyro9219 at gmail.com> wrote: > > > I'm trying to build a little piece of code that replaces an item in a > > list. > > > > Here is a sample of what I'd like to do. > > > > str = "This was replaced" > > > > ff item in list: > > replace item with str > > > > I know I can do list.remove(item), but how do I place str back into that > > exact location? > > > > Is this how / best way? > > > > if item in list: > > loc = list.index(item) > > list.remove(item) > > list.insert(loc, str) > > > > Thanks. > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061020/a6c31805/attachment.htm From jason.massey at gmail.com Fri Oct 20 22:27:55 2006 From: jason.massey at gmail.com (Jason Massey) Date: Fri, 20 Oct 2006 15:27:55 -0500 Subject: [Tutor] Best way to replace items in a list. In-Reply-To: References: <7e3eab2c0610201302h724f9e38q25c1e2152c24f814@mail.gmail.com> Message-ID: <7e3eab2c0610201327h7db40a5ds3baa4220b575cc4d@mail.gmail.com> You can access and change the elements in a list by directly referencing their position in the list. Something like: >>> foo = [1,2,3] >>> foo[0] 1 >>> foo[0] = 'a' >>> foo ['a', 2, 3] On 10/20/06, Chris Hengge wrote: > > Will that replace the location? or add to it? > > Thanks. > > On 10/20/06, Jason Massey wrote: > > > > Why not: > > > > if item in list: > > loc = list.index(item) > > list[loc] = str > > > > > > > > On 10/20/06, Chris Hengge < pyro9219 at gmail.com> wrote: > > > > > I'm trying to build a little piece of code that replaces an item in a > > > list. > > > > > > Here is a sample of what I'd like to do. > > > > > > str = "This was replaced" > > > > > > ff item in list: > > > replace item with str > > > > > > I know I can do list.remove(item), but how do I place str back into > > > that exact location? > > > > > > Is this how / best way? > > > > > > if item in list: > > > loc = list.index(item) > > > list.remove(item) > > > list.insert(loc, str) > > > > > > Thanks. > > > > > > _______________________________________________ > > > Tutor maillist - Tutor at python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061020/c4a4a6d5/attachment.html From klappnase at freenet.de Sat Oct 21 00:22:35 2006 From: klappnase at freenet.de (Michael Lange) Date: Sat, 21 Oct 2006 00:22:35 +0200 Subject: [Tutor] How to get the width of teh button widget..?? In-Reply-To: References: Message-ID: <20061021002235.7ae6865a@localhost> On Fri, 20 Oct 2006 11:55:10 +0100 "Asrarahmed Kadri" wrote: > Folks, > > Sorry for asking you such a trivial question.!!! But i want to size up all > the buttons with the same size as the largest one in the interface.. And > thats why I am asking this question.. > Hi Asrarahmed, in case you use Tkinter, something like this should do the trick (untested): b1 = Button(master, text='Hi') b1.grid(row=0, column=0, sticky='ew') b2 = Button(master, text='Good-bye') b2.grid(row=0, column=1, sticky='ew') maxwidth = 0 for button in (b1, b2): w = button.winfo_reqwidth() if w > maxwidth: maxwidth = w master.grid_columnconfigure(0, minsize=maxwidth) master.grid_columnconfigure(1, minsize=maxwidth) or, if this is an option for you, use a Pmw.ButtonBox and call its alignbuttons() method. I hope this helps Michael From rick__sterling at hotmail.com Sat Oct 21 00:13:04 2006 From: rick__sterling at hotmail.com (Rick Sterling) Date: Fri, 20 Oct 2006 18:13:04 -0400 Subject: [Tutor] PyAlsaAudio with Multiple Sound Cards? Message-ID: Hi. I am pretty new to Python, but am trying to get up to speed so I move over to Python from Perl. One progam I wrote in Perl I am trying to re-write in Python. It controls the mixer settings on my sound card. I managed to rewrite most of it by borrowing and stealing from the mixertest.py included with PyAlsaAudio. I haven't been able to figure out on thing however. I know that normally when you assign the mixer with: mixer = alsaaudio.Mixer("Master") It seems to use the first card in the system. My system has two sound cards, and I can't figure out how to access the second card. Digging around online I found the following syntax: mixdev = alsaaudio.Mixer(mixer, id, device) I don't know what values it expects for id and device. I have tried using 0 for the id and using "hw:1" for the device to no avail. I am sure it is something simple, but after trying many different things I still haven't been able to figure out how to access my second sound card. Any help is apprecaited. Rick. _________________________________________________________________ Experience Live Search from your PC or mobile device today. http://www.live.com/?mkt=en-ca From alan.gauld at btinternet.com Sat Oct 21 00:38:28 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 20 Oct 2006 23:38:28 +0100 Subject: [Tutor] Resources for Tkinter... References: Message-ID: "Asrarahmed Kadri" wrote > I have the Tkinter book by Grayson (Python and Tkinter > Programming).. *But > I must say, its quite boring..* It is a bit dense. And it jumps from basic to advanced pretty quickly. But it is thorough and so far I've found very few mistakes. That makes it a *nice* book for me, I only use it as a reference, I dont normally try reading whole chapters... > Do you have any suggestions for a nice book or web resource..?? My other Tk resources are nearly all based on Tcl/Tk. The Tcl/Tk in a Nutshell is very useful(covers Tix too), but you do need to be happy translating Tcl/Tk into Python/Tkinter... For beginner level Ivor Lanningham's book "Teach Yourself Python in 24 Hours" has 3 or 4 chapters on Tkinter and a Mandelbrot case study that pulls it all together. Alan G. From alan.gauld at btinternet.com Sat Oct 21 00:43:33 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 20 Oct 2006 23:43:33 +0100 Subject: [Tutor] How to get the width of teh button widget..?? References: Message-ID: "Asrarahmed Kadri" wrote > Sorry for asking you such a trivial question.!!! But i want to size > up all > the buttons with the same size as the largest one in the interface.. > And > thats why I am asking this question.. Assuming you mean in Tkinter(given yor other posts) it depends... You can specify the size when you create it, and if you use the placer layout manager it should keep that size. But if you use grid or packer managers then the size may change if the window is resized, depending on the options. However you should be able to read the size of the buttons back from the widget at runtime using dictionary syntax: def max(a,b): return (a>b) and a or b for button in mybuttons: max_size = max(max_size, button['width']) Or something very similar... Alan G. From alan.gauld at btinternet.com Sat Oct 21 00:49:51 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 20 Oct 2006 23:49:51 +0100 Subject: [Tutor] Best way to replace items in a list. References: <7e3eab2c0610201302h724f9e38q25c1e2152c24f814@mail.gmail.com> Message-ID: Chris, > Will that replace the location? or add to it? > >> if item in list: >> loc = list.index(item) >> list[loc] = str Jason already showed you the answer, but significantly he also showed you how to find out for yourself. Use the >>> prompt. Its what its there for. For some reason people use the >>> prompt wehen starting out in Python then seem to forget it exists. But the ability to try out little bits of code interactively as you develop code is one of Pythons most powerful features. One that it shares with Lisp Ruby and Smalltalk but surprisingly few other languages... For those kinds of quiestions its usually much faster to just try it than it is to post a question to the list! -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From rabidpoobear at gmail.com Sat Oct 21 06:00:02 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 20 Oct 2006 23:00:02 -0500 Subject: [Tutor] Best way to replace items in a list. In-Reply-To: References: Message-ID: <45399B42.6010001@gmail.com> Chris Hengge wrote: > I'm trying to build a little piece of code that replaces an item in a > list. > > Here is a sample of what I'd like to do. > > str = "This was replaced" > > ff item in list: > replace item with str > > I know I can do list.remove(item), but how do I place str back into > that exact location? > > Is this how / best way? This is almost definitely not the best way to do that, though it depends what results you're looking for. This way will only replace the first occurrence of the item. I don't know why you like the 'if item in ...' syntax so much ( ;) ), but you could do this with a loop pretty easily. #example for index,item in enumerate(lst): if item == 'Item To Replace': lst[index] = 'Replaced!' #-------- HTH, -Luke > > if item in list: > loc = list.index(item) > list.remove(item) > list.insert(loc, str) > > Thanks. > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From pyro9219 at gmail.com Sat Oct 21 08:09:36 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Fri, 20 Oct 2006 23:09:36 -0700 Subject: [Tutor] Best way to replace items in a list. In-Reply-To: <45399B42.6010001@gmail.com> References: <45399B42.6010001@gmail.com> Message-ID: I like it because it different.. and it reads cleanly... =P As far as the first occurance.. I'm not concerned about checking extra, because the first occurance is the only one I should ever need. On 10/20/06, Luke Paireepinart wrote: > > Chris Hengge wrote: > > I'm trying to build a little piece of code that replaces an item in a > > list. > > > > Here is a sample of what I'd like to do. > > > > str = "This was replaced" > > > > ff item in list: > > replace item with str > > > > I know I can do list.remove(item), but how do I place str back into > > that exact location? > > > > Is this how / best way? > This is almost definitely not the best way to do that, though it depends > what results you're looking for. > This way will only replace the first occurrence of the item. > I don't know why you like the 'if item in ...' syntax so much ( ;) ), > but you could do this with a loop pretty easily. > #example > for index,item in enumerate(lst): > if item == 'Item To Replace': > lst[index] = 'Replaced!' > #-------- > HTH, > -Luke > > > > if item in list: > > loc = list.index(item) > > list.remove(item) > > list.insert(loc, str) > > > > Thanks. > > ------------------------------------------------------------------------ > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061020/775ef3b9/attachment.htm From treed at ultraviolet.org Sat Oct 21 07:44:43 2006 From: treed at ultraviolet.org (Tracy R Reed) Date: Fri, 20 Oct 2006 22:44:43 -0700 Subject: [Tutor] My first real python project: LOLLERSKATES Message-ID: <4539B3CB.6060207@ultraviolet.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 I have been a sysadmin for quite a while now and used to do a lot of perl. I haven't done much programming at all in the last couple of years but have been meaning to dump perl for python anyhow (for the usual reasons) and have finally gotten around to doing it. The first itch that I wanted to scratch was something to help me find anomalies in our system logs. We have a lot of servers and need some automation for watching over them including logfiles. I have used logwatch and logcheck but they are both too complicated for what I really need not to mention practically unmaintained these days. So I decided to write my own. Features I wanted were: 1. A basic grep -v sort of functionality on the logfile where I have a file full of regexes/lines to be ignored that are applied to the logfiles to filter everything uninteresting out and whatever is left gets emailed to the admin. 2. A sort of macro system where I can substitute nasty long commonly used regexes in my filter/ignore file with something more easily read and typed. 3. Simplicity. Logcheck had several different levels of logfile events which it could report back on and if you wanted something ignored you had to put it in the right config file for whatever level it was popping up in. This drove me nuts because I often got the wrong one. Logwatch tries to analyze your logs and provide various summaries and statistics and other things I don't care about. I just want to see the interesting lines from the logfile. My code seems to have all of the above and a silly name as well: http://ultraviolet.org/Members/treed/lollerskates It has a list of logfiles to look at, a list of regexes to compare to each line to know what is uninteresting and to filter out/ignore, and emails anything left to the admin, and a simple macro facility. I would appreciate it if anyone interested would download and critique my code. Am I doing anything terribly un-pythonic? Questions/problems/TODO's: This is a fairly simple structured programming implementation. No OO. Should I be using some classes somewhere? The config file is just a module which I import which causes all of my configs to become globals. Globals are bad. Is there a better way or would just about anything else be overkill? A singleton config class or something? Overkill? I have several loops in this code for processing the logfiles. I once tried to convert these for loops to list comprehensions and totally confused myself and backed out the change (yeay svn!). Is there any benefit to list comprehensions in this case? I would kinda like to play with unit tests. Not sure how I would construct unit tests for this. And again, perhaps overkill. But some people tell me you should write the unit tests before you even begin coding and code until the tests are satisfied. So even on a small project you would have tests. I run into a couple nasty bugs I created which caused the script to never return anything from the logfile (so you don't immediately realize something is broken) where I thought "It sure would be nice to have a test to catch that if it ever happens again." Stuff tends to build up in the ignore file. If a line is typo'd and never gets used/matched you will never know. If a service is no longer running that we had lines in the ignore file for they will be there forever unused. I don't like this sort of clutter. I am really tempted to somehow make it keep track of when a rule is matched and if it doesn't match in a whole month email the admin because it doesn't need to be there. I am wondering if this is needless complexity or something useful. I think it could be useful. If so, how to save the info on when each line was last matched? I am thinking maybe of just having a dictionary keyed on the compiled regex object and the value being a tuple of the uncompiled regex string from the ignore file and a date string containing when it was last matched and pickling this data structure to disk to be read in each start of the program. Comments? I am currently pushing this code to around 20 systems with cfengine using just one ignore file for them all. If I use the scheme mentioned in the previous paragraph to alert me of unused rules in the ignore file I will get tons of such messages from machines not running a service that other machines of mine are. I guess that means perhaps I should split my ignore file out into ignore.hostname.conf or something like that so there is a separate one for each host. Anyhow, I appreciate any feedback on this potentially very handy sysadmin tool. Thanks in advance! - -- Tracy R Reed http://ultraviolet.org -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.5 (GNU/Linux) Comment: Using GnuPG with Fedora - http://enigmail.mozdev.org iD8DBQFFObPK9PIYKZYVAq0RAiflAJ9jprJgGnNRXkB+nKsljFUsAUGnFwCgiJg/ M3U24dNDtH+hAgSh7kZ40hQ= =nxQS -----END PGP SIGNATURE----- From pyro9219 at gmail.com Sat Oct 21 08:51:20 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Fri, 20 Oct 2006 23:51:20 -0700 Subject: [Tutor] My first real python project: LOLLERSKATES In-Reply-To: <4539B3CB.6060207@ultraviolet.org> References: <4539B3CB.6060207@ultraviolet.org> Message-ID: All I can say to this... LOLLERSKATES.... =D On 10/20/06, Tracy R Reed wrote: > > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > I have been a sysadmin for quite a while now and used to do a lot of > perl. I haven't done much programming at all in the last couple of years > but have been meaning to dump perl for python anyhow (for the usual > reasons) and have finally gotten around to doing it. > > The first itch that I wanted to scratch was something to help me find > anomalies in our system logs. We have a lot of servers and need some > automation for watching over them including logfiles. I have used > logwatch and logcheck but they are both too complicated for what I > really need not to mention practically unmaintained these days. So I > decided to write my own. > > Features I wanted were: > > 1. A basic grep -v sort of functionality on the logfile where I have a > file full of regexes/lines to be ignored that are applied to the > logfiles to filter everything uninteresting out and whatever is left > gets emailed to the admin. > > 2. A sort of macro system where I can substitute nasty long commonly > used regexes in my filter/ignore file with something more easily read > and typed. > > 3. Simplicity. Logcheck had several different levels of logfile events > which it could report back on and if you wanted something ignored you > had to put it in the right config file for whatever level it was popping > up in. This drove me nuts because I often got the wrong one. Logwatch > tries to analyze your logs and provide various summaries and statistics > and other things I don't care about. I just want to see the interesting > lines from the logfile. > > My code seems to have all of the above and a silly name as well: > > http://ultraviolet.org/Members/treed/lollerskates > > It has a list of logfiles to look at, a list of regexes to compare to > each line to know what is uninteresting and to filter out/ignore, and > emails anything left to the admin, and a simple macro facility. > > I would appreciate it if anyone interested would download and critique > my code. Am I doing anything terribly un-pythonic? > > Questions/problems/TODO's: > > This is a fairly simple structured programming implementation. No OO. > Should I be using some classes somewhere? > > The config file is just a module which I import which causes all of my > configs to become globals. Globals are bad. Is there a better way or > would just about anything else be overkill? A singleton config class or > something? Overkill? > > I have several loops in this code for processing the logfiles. I once > tried to convert these for loops to list comprehensions and totally > confused myself and backed out the change (yeay svn!). Is there any > benefit to list comprehensions in this case? > > I would kinda like to play with unit tests. Not sure how I would > construct unit tests for this. And again, perhaps overkill. But some > people tell me you should write the unit tests before you even begin > coding and code until the tests are satisfied. So even on a small > project you would have tests. I run into a couple nasty bugs I created > which caused the script to never return anything from the logfile (so > you don't immediately realize something is broken) where I thought "It > sure would be nice to have a test to catch that if it ever happens again." > > Stuff tends to build up in the ignore file. If a line is typo'd and > never gets used/matched you will never know. If a service is no longer > running that we had lines in the ignore file for they will be there > forever unused. I don't like this sort of clutter. I am really tempted > to somehow make it keep track of when a rule is matched and if it > doesn't match in a whole month email the admin because it doesn't need > to be there. I am wondering if this is needless complexity or something > useful. I think it could be useful. If so, how to save the info on when > each line was last matched? I am thinking maybe of just having a > dictionary keyed on the compiled regex object and the value being a > tuple of the uncompiled regex string from the ignore file and a date > string containing when it was last matched and pickling this data > structure to disk to be read in each start of the program. Comments? > > I am currently pushing this code to around 20 systems with cfengine > using just one ignore file for them all. If I use the scheme mentioned > in the previous paragraph to alert me of unused rules in the ignore file > I will get tons of such messages from machines not running a service > that other machines of mine are. I guess that means perhaps I should > split my ignore file out into ignore.hostname.conf or something like > that so there is a separate one for each host. > > Anyhow, I appreciate any feedback on this potentially very handy > sysadmin tool. Thanks in advance! > > - -- > Tracy R Reed > http://ultraviolet.org > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.4.5 (GNU/Linux) > Comment: Using GnuPG with Fedora - http://enigmail.mozdev.org > > iD8DBQFFObPK9PIYKZYVAq0RAiflAJ9jprJgGnNRXkB+nKsljFUsAUGnFwCgiJg/ > M3U24dNDtH+hAgSh7kZ40hQ= > =nxQS > -----END PGP SIGNATURE----- > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061020/83f632d6/attachment-0001.html From euoar at yahoo.es Sat Oct 21 12:45:47 2006 From: euoar at yahoo.es (euoar) Date: Sat, 21 Oct 2006 12:45:47 +0200 Subject: [Tutor] sending mails from python Message-ID: <4539FA5B.5020403@yahoo.es> I'm trying to learn how to send e-mails with python. But I always become this error: socket.error: (110, 'Connection timed out'). Is there something bad in the code? Does anyone knows what could be wrong? I'm using python from linux, and have no proxy... The code that I use is this (of course, filling with my persona data the " "): import smtplib smtpserver = 'my smtp server goes here' AUTHREQUIRED = 1 smtpuser = 'my user name' smtppass = 'my password' RECIPIENTS = ['the recipients'] SENDER = 'my mail' mssg = "una prueba desde python" session = smtplib.SMTP(smtpserver) if AUTHREQUIRED: session.login(smtpuser, smtppass) smtpresult = session.sendmail(SENDER, RECIPIENTS, mssg) if smtpresult: errstr = "" for recip in smtpresult.keys(): errstr = """Could not delivery mail to: %s Server said: %s %s %s""" % (recip, smtpresult[recip][0], smtpresult[recip][1], errstr) raise smtplib.SMTPException, errstr Thank you for your help ______________________________________________ LLama Gratis a cualquier PC del Mundo. Llamadas a fijos y m?viles desde 1 c?ntimo por minuto. http://es.voice.yahoo.com From tsila.hassine at gmail.com Sat Oct 21 12:55:22 2006 From: tsila.hassine at gmail.com (Tsila Hassine) Date: Sat, 21 Oct 2006 12:55:22 +0200 Subject: [Tutor] checking for robots on a python script based site Message-ID: Hello All! I have a site that takes some input from the user and then produces a dynamic page based on the input. In the last months bots (not only search engine ones) have been hitting the site pretty heavily, so my sys admin disabled it. As far as I know there are 2 options to fight this : 1: write a robots.txt file - but then I'd have to rely on the bots' good will. 2: implement a "captcha" mechanism, which I am not sure I want. Does Python provide anything to deal with such problems ? thanks, Tsila -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061021/dcf213e8/attachment.htm From kent37 at tds.net Sat Oct 21 13:28:25 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 21 Oct 2006 07:28:25 -0400 Subject: [Tutor] Best way to replace items in a list. In-Reply-To: <7e3eab2c0610201302h724f9e38q25c1e2152c24f814@mail.gmail.com> References: <7e3eab2c0610201302h724f9e38q25c1e2152c24f814@mail.gmail.com> Message-ID: <453A0459.9030805@tds.net> Jason Massey wrote: > Why not: > > if item in lst: > loc = lst.index(item) > lst[loc] = str You can also just try to do the replacement and catch the ValueError that is raised if the item is not there: try: loc = list.index(item) list[loc] = str except ValueError: pass If lst is long this will be faster because it only searches lst for item once. If lst is short maybe the first version is better because the code is shorter. This is an example of two different approaches to handling exceptional conditions: Look Before You Leap versus Easier to Ask Forgiveness than Permission. In LBYL you check for the exceptional condition early, so you avoid exceptions. In EAFP you proceed as if something is sure to work and clean up after if you were wrong. In many cases EAFP produces code that makes fewer assumptions about its environment and is more suited to Python's dynamic style. In this simple case it doesn't make any difference. By the way don't use 'list' as the name of a variable (or 'file', 'dict', 'set' or 'str'), they are all the names of built-in types in Python and using them as variable names will hide the built-in name. Kent From python at venix.com Sat Oct 21 14:14:04 2006 From: python at venix.com (Python) Date: Sat, 21 Oct 2006 08:14:04 -0400 Subject: [Tutor] sending mails from python In-Reply-To: <4539FA5B.5020403@yahoo.es> References: <4539FA5B.5020403@yahoo.es> Message-ID: <1161432844.8103.884.camel@www.venix.com> On Sat, 2006-10-21 at 12:45 +0200, euoar wrote: > I'm trying to learn how to send e-mails with python. But I always become > this error: socket.error: (110, 'Connection timed out'). It sounds like you were unable to connect to the mail server. That could be due to a large number of network issues and is probably not a Python bug. from a terminal/cmd window try telnet smtpserver 25 That will connect to the smtpserver on the proper port (and works for most operating systems). I expect that to fail. Your Python code will not work until you can actually make a connection. Here's what I get trying to reach a non-existent smtpserver: telnet 10.10.10.10 25 Trying 10.10.10.10... telnet: connect to address 10.10.10.10: Connection timed out telnet: Unable to connect to remote host: Connection timed out > Is there > something bad in the code? Does anyone knows what could be wrong? I'm > using python from linux, and have no proxy... > > The code that I use is this (of course, filling with my persona data the > " "): > > import smtplib > > smtpserver = 'my smtp server goes here' > AUTHREQUIRED = 1 > smtpuser = 'my user name' > smtppass = 'my password' > > RECIPIENTS = ['the recipients'] > SENDER = 'my mail' > mssg = "una prueba desde python" > > session = smtplib.SMTP(smtpserver) > if AUTHREQUIRED: > session.login(smtpuser, smtppass) > smtpresult = session.sendmail(SENDER, RECIPIENTS, mssg) > > if smtpresult: > errstr = "" > for recip in smtpresult.keys(): > errstr = """Could not delivery mail to: %s > > Server said: %s > %s > > %s""" % (recip, smtpresult[recip][0], smtpresult[recip][1], errstr) > raise smtplib.SMTPException, errstr > > > > Thank you for your help > > > > > > > ______________________________________________ > LLama Gratis a cualquier PC del Mundo. > Llamadas a fijos y m?viles desde 1 c?ntimo por minuto. > http://es.voice.yahoo.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From andrew.arobert at gmail.com Sat Oct 21 14:20:27 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Sat, 21 Oct 2006 08:20:27 -0400 Subject: [Tutor] sending mails from python In-Reply-To: <4539FA5B.5020403@yahoo.es> References: <4539FA5B.5020403@yahoo.es> Message-ID: <453A108B.2070607@gmail.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 How about something like this? Create a function and then call it with the required optins of server url, sender address, destination address, subject, and message text? def send(serverURL=None, sender='', to='', subject='', text=''): """ Form and send an e-mail message """ import smtplib headers = "From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n" % (sender, to, subject) message = headers + text mailServer = smtplib.SMTP(serverURL) # replace serverURL with site specific mail server check_valid=mailer.isAddressValid(to) if check_valid==1 : mailServer.sendmail(sender, to, message) mailServer.quit() else: print "\n\nDestination e-mail address %s is invalid. \n\n\tPlease check and run again" % to def isAddressValid(addr): """ Validate e-mail addresses based on lexical rules set forth in RFC 822 Ported from Recipe 3.9 in Secure Programming Cookbook for C and C++ by John Viega and Matt Messier (O'Reilly 2003) If the supplied email address is syntactically valid, isAddressValid() will return 1; otherwise, it will return 0. """ # Mail variables rfc822_specials = '()<>@,;:\\"[]' c = 0 while c < len(addr): if addr[c] == '"' and (not c or addr[c - 1] == '.' or addr[c - - 1] == '"'): c = c + 1 while c < len(addr): if addr[c] == '"': break if addr[c] == '\\' and addr[c + 1] == ' ': c = c + 2 continue if ord(addr[c]) < 32 or ord(addr[c]) >= 127: return 0 c = c + 1 else: return 0 if addr[c] == '@': break if addr[c] != '.': return 0 c = c + 1 continue if addr[c] == '@': break if ord(addr[c]) <= 32 or ord(addr[c]) >= 127: return 0 if addr[c] in rfc822_specials: return 0 c = c + 1 if not c or addr[c - 1] == '.': return 0 # Next we validate the domain portion (name at domain) domain = c = c + 1 if domain >= len(addr): return 0 count = 0 while c < len(addr): if addr[c] == '.': if c == domain or addr[c - 1] == '.': return 0 count = count + 1 if ord(addr[c]) <= 32 or ord(addr[c]) >= 127: return 0 if addr[c] in rfc822_specials: return 0 c = c + 1 return count >= 1 euoar wrote: > I'm trying to learn how to send e-mails with python. But I always become > this error: socket.error: (110, 'Connection timed out'). Is there > something bad in the code? Does anyone knows what could be wrong? I'm > using python from linux, and have no proxy... > > The code that I use is this (of course, filling with my persona data the > " "): > > import smtplib > > smtpserver = 'my smtp server goes here' > AUTHREQUIRED = 1 > smtpuser = 'my user name' > smtppass = 'my password' > > RECIPIENTS = ['the recipients'] > SENDER = 'my mail' > mssg = "una prueba desde python" > > session = smtplib.SMTP(smtpserver) > if AUTHREQUIRED: > session.login(smtpuser, smtppass) > smtpresult = session.sendmail(SENDER, RECIPIENTS, mssg) > > if smtpresult: > errstr = "" > for recip in smtpresult.keys(): > errstr = """Could not delivery mail to: %s > > Server said: %s > %s > > %s""" % (recip, smtpresult[recip][0], smtpresult[recip][1], errstr) > raise smtplib.SMTPException, errstr > > > > Thank you for your help > > > > > > > ______________________________________________ > LLama Gratis a cualquier PC del Mundo. > Llamadas a fijos y m?viles desde 1 c?ntimo por minuto. > http://es.voice.yahoo.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.1 (MingW32) Comment: GnuPT 2.7.2 iD8DBQFFOhCLDvn/4H0LjDwRAm9AAJwOkrtF/R4zWQhhCwjlBrBVQ4XpwwCgpGHy ukZIoIuoAh/hmBZ/r/ZbQmM= =6weK -----END PGP SIGNATURE----- From ajkadri at googlemail.com Sat Oct 21 15:07:12 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Sat, 21 Oct 2006 14:07:12 +0100 Subject: [Tutor] what is PIL..??? Message-ID: Folks, Continuing my journey into "Tkinter world"....... May I ask someone to tell what PIL is and how can it be helpful in drawing 2-dimensional graphs... Thanks.. Regards, Asrarahmed -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061021/e9ea5160/attachment.html From rob.andrews at gmail.com Sat Oct 21 15:46:02 2006 From: rob.andrews at gmail.com (Rob Andrews) Date: Sat, 21 Oct 2006 08:46:02 -0500 Subject: [Tutor] what is PIL..??? In-Reply-To: References: Message-ID: <8d757d2e0610210646u51d8b00eucb5f57e30abfa7e7@mail.gmail.com> On 10/21/06, Asrarahmed Kadri wrote: > May I ask someone to tell what PIL is and how can it be helpful in drawing > 2-dimensional graphs... PIL = Python Imaging Library PIL provides a bunch of nifty tools for handling images and is well worth a google. -Rob A. From klappnase at freenet.de Sat Oct 21 16:31:24 2006 From: klappnase at freenet.de (Michael Lange) Date: Sat, 21 Oct 2006 16:31:24 +0200 Subject: [Tutor] PyAlsaAudio with Multiple Sound Cards? In-Reply-To: References: Message-ID: <20061021163124.2c9eec1c.klappnase@freenet.de> On Fri, 20 Oct 2006 18:13:04 -0400 "Rick Sterling" wrote: > > Hi. > > I am pretty new to Python, but am trying to get up to speed so I move over > to Python from Perl. One progam I wrote in Perl I am trying to re-write in > Python. It controls the mixer settings on my sound card. I managed to > rewrite most of it by borrowing and stealing from the mixertest.py included > with PyAlsaAudio. > > I haven't been able to figure out on thing however. I know that normally > when you assign the mixer with: > > mixer = alsaaudio.Mixer("Master") > > It seems to use the first card in the system. My system has two sound > cards, and I can't figure out how to access the second card. Digging around > online I found the following syntax: > > mixdev = alsaaudio.Mixer(mixer, id, device) > > I don't know what values it expects for id and device. I have tried using 0 > for the id and using "hw:1" for the device to no avail. I am sure it is > something simple, but after trying many different things I still haven't > been able to figure out how to access my second sound card. > Hi Rick, isn't there any documentation for pyalsaaudio? If no, maybe you would be better off using ossaudiodev, which works well with ALSA, too. For the device question, I guess they might want something like device=/dev/snd/hwC0D0 or however these device files are named on your system. I hope this helps Michael From kent37 at tds.net Sat Oct 21 17:41:18 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 21 Oct 2006 11:41:18 -0400 Subject: [Tutor] what is PIL..??? In-Reply-To: References: Message-ID: <453A3F9E.20003@tds.net> Asrarahmed Kadri wrote: > > Folks, > > Continuing my journey into "Tkinter world"....... > > May I ask someone to tell what PIL is and how can it be helpful in > drawing 2-dimensional graphs... Python Imaging Library - just Google PIL. I don't think it will help much with graphs though, if you mean things like pie charts and bar graphs. For that you might look at matplotlib or one of the other packages listed here: http://wiki.python.org/moin/NumericAndScientific/Plotting Kent From ajkadri at googlemail.com Sat Oct 21 18:00:40 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Sat, 21 Oct 2006 17:00:40 +0100 Subject: [Tutor] what is PIL..??? In-Reply-To: <453A3F9E.20003@tds.net> References: <453A3F9E.20003@tds.net> Message-ID: Yeah, I am looling for bar graphs.... On 10/21/06, Kent Johnson wrote: > > Asrarahmed Kadri wrote: > > > > Folks, > > > > Continuing my journey into "Tkinter world"....... > > > > May I ask someone to tell what PIL is and how can it be helpful in > > drawing 2-dimensional graphs... > > Python Imaging Library - just Google PIL. > I don't think it will help much with graphs though, if you mean things > like pie charts and bar graphs. For that you might look at matplotlib or > one of the other packages listed here: > http://wiki.python.org/moin/NumericAndScientific/Plotting > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061021/7211f1a5/attachment.html From alan.gauld at btinternet.com Sat Oct 21 18:31:08 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 21 Oct 2006 17:31:08 +0100 Subject: [Tutor] what is PIL..??? References: <453A3F9E.20003@tds.net> Message-ID: "Asrarahmed Kadri" wrote in message news:b4e894c70610210900x8df57aaw2d2a8c2254e9131a at mail.gmail.com... > Yeah, I am looling for bar graphs.... > If its simple 2D bar graphs they are almost as easy to draw yourself on a Canvas widget using coloured rectangles. The only trickiness is in drawing axes and scales. But its not rocket science. But if you want to get into power features like stacked graphs, 3D boxes, and other graph types a charting/plotting library will be better even given the extra learning curve. Alan G. From dyoo at hkn.eecs.berkeley.edu Sat Oct 21 18:34:46 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 21 Oct 2006 09:34:46 -0700 (PDT) Subject: [Tutor] checking for robots on a python script based site In-Reply-To: References: Message-ID: On Sat, 21 Oct 2006, Tsila Hassine wrote: > 1: write a robots.txt file - but then I'd have to rely on the bots' good > will. > 2: implement a "captcha" mechanism, which I am not sure I want. > > Does Python provide anything to deal with such problems ? I think you're asking the question: "Has anyone written a system in Python that tries to deal with this problem?" You may want to look at: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440588 Good luck! From cappy2112 at gmail.com Sat Oct 21 19:18:11 2006 From: cappy2112 at gmail.com (Tony Cappellini) Date: Sat, 21 Oct 2006 10:18:11 -0700 Subject: [Tutor] what is PIL..??? Message-ID: <8249c4ac0610211018mf92b21ftba43f1cc7490a4bb@mail.gmail.com> Also checkout GnuPlot http://www.gnuplot.info/ and the Python bindings for it http://gnuplot-py.sourceforge.net/ Date: Sat, 21 Oct 2006 14:07:12 +0100 From: "Asrarahmed Kadri" Subject: [Tutor] what is PIL..??? To: pythontutor Message-ID: Content-Type: text/plain; charset="iso-8859-1" Folks, Continuing my journey into "Tkinter world"....... May I ask someone to tell what PIL is and how can it be helpful in drawing 2-dimensional graphs... Thanks.. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061021/6c696167/attachment.html From kent37 at tds.net Sat Oct 21 22:49:09 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 21 Oct 2006 16:49:09 -0400 Subject: [Tutor] checking for robots on a python script based site In-Reply-To: References: Message-ID: <453A87C5.8010002@tds.net> Tsila Hassine wrote: > Hello All! > > I have a site that takes some input from the user and then produces a > dynamic page based on the input. In the last months bots (not only > search engine ones) have been hitting the site pretty heavily, so my sys > admin disabled it. As far as I know there are 2 options to fight this : > 1: write a robots.txt file - but then I'd have to rely on the bots' good > will. Seems to me this is worth doing, at least you will screen out the white hat robots. Kent From nephish at gmail.com Sun Oct 22 03:20:45 2006 From: nephish at gmail.com (shawn bright) Date: Sat, 21 Oct 2006 20:20:45 -0500 Subject: [Tutor] can i pass a list to a function and get one back ? Message-ID: <384c93600610211820s65dee397q4b8b0847396d146c@mail.gmail.com> hey there, i was just wondering if i could get a list back from a function. something like def return_a_list(some_var): some_list = [] for i in range(5): var = some_var + i some_list.append(var) return some_list is this cool ? thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061021/5e50016f/attachment.htm From bill at celestial.net Sun Oct 22 03:26:14 2006 From: bill at celestial.net (Bill Campbell) Date: Sat, 21 Oct 2006 18:26:14 -0700 Subject: [Tutor] can i pass a list to a function and get one back ? In-Reply-To: <384c93600610211820s65dee397q4b8b0847396d146c@mail.gmail.com> References: <384c93600610211820s65dee397q4b8b0847396d146c@mail.gmail.com> Message-ID: <20061022012614.GA15729@ayn.mi.celestial.com> On Sat, Oct 21, 2006, shawn bright wrote: > > hey there, i was just wondering if i could get a list back from a > function. > something like > def return_a_list(some_var): > some_list = [] > for i in range(5): > var = some_var + i > some_list.append(var) > return some_list > is this cool ? Ayup! The best way to find answers to questions like this is to just do it, and see what python does. Bill -- INTERNET: bill at Celestial.COM Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 ``It will be of little avail to the people that the laws are made by men of their own choice if the laws be so voluminous that they cannot be read, or so incoherent that they cannot be understood.'' -James Madison, Federalist Paper #62 From paulino1 at sapo.pt Sun Oct 22 03:35:13 2006 From: paulino1 at sapo.pt (Paulino) Date: Sun, 22 Oct 2006 02:35:13 +0100 Subject: [Tutor] Exception and sys.exit() in a cgi script In-Reply-To: References: Message-ID: <453ACAD1.9070507@sapo.pt> > *Mike Hansen* > Mike.Hansen at atmel.com > > > /Mon Oct 16 18:43:29 CEST 2006/ > >/ This is a peace of a CGI script i have. > />/ > />/ 1 import cgi > />/ 2 form=cgi.FieldStorage() > />/ 3 try : > />/ 4 ano=form["ano"].value > />/ 5 conta=form["conta"].value > />/ 6 except KeyError : > />/ 7 print '

Please enter values in the > />/ fields

' > />/ 8 sys.exit(0) > />/ > />/ > />/ When the excption occurs, no message is shown on the browser. > />/ > />/ If I run the script with IDLE, the message is printed and then the > />/ script exits. > />/ > />/ What's wrong here? > />/ > />/ > />/ > />/ _______________________________________________ > />/ Tutor maillist - Tutor at python.org > />/ http://mail.python.org/mailman/listinfo/tutor > />/ / > I'm catching up on the weekend's tutor messages. > > import cgitb; cgitb.enable() > That spits errors to the web page which is great for debugging cgi > scripts. > > I think you need > print "Content-Type: text/html\n\n" > http://docs.python.org/lib/cgi-intro.html > > http://docs.python.org/lib/node560.html > > Mike Thats not the point (sorry). when all the values are provided in the form (no excetion is raised) it runs as expected! The point is when one of the values "ano", "conta" is missing in the form, I want the error message to be shown on the browser, and the script to stop running. When there is an exception, the script actually stops running, but no message is sent to the browser. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061022/4963c3fb/attachment.html From nephish at gmail.com Sun Oct 22 04:12:36 2006 From: nephish at gmail.com (shawn bright) Date: Sat, 21 Oct 2006 21:12:36 -0500 Subject: [Tutor] can i pass a list to a function and get one back ? In-Reply-To: <20061022012614.GA15729@ayn.mi.celestial.com> References: <384c93600610211820s65dee397q4b8b0847396d146c@mail.gmail.com> <20061022012614.GA15729@ayn.mi.celestial.com> Message-ID: <384c93600610211912x503861cbx200c0a5f17736614@mail.gmail.com> great, thanks, i have idle right here, would have been just as easy. sorry about that sk On 10/21/06, Bill Campbell wrote: > > On Sat, Oct 21, 2006, shawn bright wrote: > > > > hey there, i was just wondering if i could get a list back from a > > function. > > something like > > def return_a_list(some_var): > > some_list = [] > > for i in range(5): > > var = some_var + i > > some_list.append(var) > > return some_list > > is this cool ? > > Ayup! > > The best way to find answers to questions like this is to just do > it, and see what python does. > > Bill > -- > INTERNET: bill at Celestial.COM Bill Campbell; Celestial Software LLC > URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way > FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) > 236-1676 > > ``It will be of little avail to the people that the laws are made by men > of > their own choice if the laws be so voluminous that they cannot be read, or > so incoherent that they cannot be understood.'' > -James Madison, Federalist Paper #62 > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061021/4a8abdf5/attachment.htm From dyoo at hkn.eecs.berkeley.edu Sun Oct 22 04:40:20 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 21 Oct 2006 19:40:20 -0700 (PDT) Subject: [Tutor] can i pass a list to a function and get one back ? In-Reply-To: <384c93600610211912x503861cbx200c0a5f17736614@mail.gmail.com> References: <384c93600610211820s65dee397q4b8b0847396d146c@mail.gmail.com> <20061022012614.GA15729@ayn.mi.celestial.com> <384c93600610211912x503861cbx200c0a5f17736614@mail.gmail.com> Message-ID: > great, thanks, i have idle right here, would have been just as easy. > sorry about that No problem; it's cool. >> > hey there, i was just wondering if i could get a list back from a >> > function. >> > something like >> > def return_a_list(some_var): >> > some_list = [] >> > for i in range(5): >> > var = some_var + i >> > some_list.append(var) >> > return some_list >> > is this cool ? It's cool. *grin* One small comment: we often don't need to use temporary variables like 'var'. def return_a_list(some_var): some_list = [] for i in range(5): some_list.append(some_var + i) return some_list Sometimes a temporary variable is useful, and sometimes not. Here, it seems like it's not too necessary. Good luck! From dyoo at hkn.eecs.berkeley.edu Sun Oct 22 06:55:11 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 21 Oct 2006 21:55:11 -0700 (PDT) Subject: [Tutor] 'json' should probably be the response to 'can we use eval to parse { ... }?' Message-ID: Hi everyone, I ran across the JSON data format today: http://json.org/ with a nice Python implementation in 'simplejson'. http://undefined.org/python/#simple_json The JSON format matches very closely with Python data structure syntax. So the next time someone asks if they can use eval() to turn a string into a data structure, let's point them to simplejson. Best of wishes! From nephish at gmail.com Sun Oct 22 08:14:58 2006 From: nephish at gmail.com (shawn bright) Date: Sun, 22 Oct 2006 01:14:58 -0500 Subject: [Tutor] can i pass a list to a function and get one back ? In-Reply-To: References: <384c93600610211820s65dee397q4b8b0847396d146c@mail.gmail.com> <20061022012614.GA15729@ayn.mi.celestial.com> <384c93600610211912x503861cbx200c0a5f17736614@mail.gmail.com> Message-ID: <384c93600610212314q1bcecc47uef722b22c25232f8@mail.gmail.com> way cool, thanks. I am always looking for ways to clean things up -sk On 10/21/06, Danny Yoo wrote: > > > > > great, thanks, i have idle right here, would have been just as easy. > > sorry about that > > No problem; it's cool. > > > >> > hey there, i was just wondering if i could get a list back from a > >> > function. > >> > something like > >> > def return_a_list(some_var): > >> > some_list = [] > >> > for i in range(5): > >> > var = some_var + i > >> > some_list.append(var) > >> > return some_list > >> > is this cool ? > > It's cool. *grin* > > One small comment: we often don't need to use temporary variables like > 'var'. > > def return_a_list(some_var): > some_list = [] > for i in range(5): > some_list.append(some_var + i) > return some_list > > Sometimes a temporary variable is useful, and sometimes not. Here, it > seems like it's not too necessary. > > > Good luck! > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061022/c4db9313/attachment.htm From pine508 at hotmail.com Sun Oct 22 08:39:57 2006 From: pine508 at hotmail.com (Pine Marten) Date: Sun, 22 Oct 2006 02:39:57 -0400 Subject: [Tutor] 5 questions Message-ID: 1. Is there a searchable archive of this list? 2. Is there list ettiquette one should be aware of? 3. Besides Vaults of Parnassus, are there other webpages which list projects written in Python? I'm mainly interested in looking at non-technical software, things for the common user to use. I've been surprised at just how little of that type I've found so far. 4. Can anyone recommend good books for non-programmers starting out learning Python? I've looked through a few so far and they are ok ("Learning Python", "Python: How to Program") but am still hoping to find one that doesn't assume any prior knowledge of programming and defines terms when they are first presented. (That might be a tall order, I know...) 5. If I want to take user information from text boxes, check boxes, etc., and store it for later re-display to the person (imagine a movie rating diary, with text review of the film and checkboxes or sliders to give it 5 stars, or has action, or is a comedy, etc.) and have all of it be efficiently searchable, what are some good ways to go in terms of how to save the information? For now I have textbox info saving just to a .txt file, but that can't be a good way to go about it. I have the vague sense I should learn about databases, but really am not sure what to read about... Suggestions? _________________________________________________________________ All-in-one security and maintenance for your PC. Get a free 90-day trial! http://clk.atdmt.com/MSN/go/msnnkwlo0050000002msn/direct/01/?href=http://www.windowsonecare.com/?sc_cid=msn_hotmail From alan.gauld at btinternet.com Sun Oct 22 09:16:12 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 22 Oct 2006 08:16:12 +0100 Subject: [Tutor] 5 questions References: Message-ID: > 1. Is there a searchable archive of this list? Yes, the ActiveState archive is searchable. The gmane version might be too? > 2. Is there list ettiquette one should be aware of? Yes, but I'm not sure how you get a copy. Moderators??? > 3. Besides Vaults of Parnassus, are there other webpages which list > projects > written in Python? I'm mainly interested in looking at > non-technical > software, things for the common user to use. I've been surprised at > just > how little of that type I've found so far. Thee are a few such sites around. The Vaults seem to be falling into obsolesece now, although its still my first choice. Others will give you their favourites I'm sure. > 4. Can anyone recommend good books for non-programmers starting out > learning > Python? I've looked through a few so far and they are ok ("Learning > Python", "Python: How to Program") but am still hoping to find one > that > doesn't assume any prior knowledge of programming and defines terms > when > they are first presented. (That might be a tall order, I know...) Well, my book assumes zero knowledge and tries to define all terms as they arise. The book is quite old in Python terms but because it is a basics book only it still works quite well, the only significant drop off is that it uses the old string module rather than the newer string methods. Ivan Lanningham's Teah Yourself Python... is also targetted at complete beginners but also is focussed on version 1.5.1 with the same failings. I believe there are a couple of newer books around for beginners too, but I confess I havemn't kept up to date on that front. There are so many Python books available now we are spoilt for choice. That having been said I personally tend to recommend sticking with web based tutorials in the beginning since novice books become irrelevant fairly quickly. The web sites tend to be updated more often than books too. My book uses Python 1.5.1, but the web tutor is for Python 2.3 > 5. If I want to take user information from text boxes, check boxes, > etc., > and store it for later re-display to the person (imagine a movie > rating > diary, with text review of the film and checkboxes or sliders to > give it 5 > stars, or has action, or is a comedy, etc.) and have all of it be > efficiently searchable, what are some good ways to go in terms of > how to > save the information? For now I have textbox info saving just to a > .txt > file, but that can't be a good way to go about it. I have the vague > sense I > should learn about databases, but really am not sure what to read > about... Yes databases are a good searchable storage facility. There is a database topic in my web tuitorial that should be enough to get you started. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Sun Oct 22 13:33:54 2006 From: kent37 at tds.net (Kent Johnson) Date: Sun, 22 Oct 2006 07:33:54 -0400 Subject: [Tutor] can i pass a list to a function and get one back ? In-Reply-To: References: <384c93600610211820s65dee397q4b8b0847396d146c@mail.gmail.com> <20061022012614.GA15729@ayn.mi.celestial.com> <384c93600610211912x503861cbx200c0a5f17736614@mail.gmail.com> Message-ID: <453B5722.6010201@tds.net> Danny Yoo wrote: > One small comment: we often don't need to use temporary variables like > 'var'. > > def return_a_list(some_var): > some_list = [] > for i in range(5): > some_list.append(some_var + i) > return some_list > > Sometimes a temporary variable is useful, and sometimes not. Here, it > seems like it's not too necessary. some_list is not too necessary either; this is a good place for a list comprehension: def return_a_list(some_var): return [ some_var + i for i in range(5) ] or for that matter return range(some_var:some_var+5) Kent From arcege at gmail.com Sun Oct 22 15:06:51 2006 From: arcege at gmail.com (Michael P. Reilly) Date: Sun, 22 Oct 2006 09:06:51 -0400 Subject: [Tutor] Exception and sys.exit() in a cgi script In-Reply-To: <453ACAD1.9070507@sapo.pt> References: <453ACAD1.9070507@sapo.pt> Message-ID: <7e5ba9220610220606h3e9cacf3w5e432a8a8a11e4fb@mail.gmail.com> On 10/21/06, Paulino wrote: > > > *Mike Hansen* > Mike.Hansen at atmel.com > > > *Mon Oct 16 18:43:29 CEST 2006* > >* This is a peace of a CGI script i have. > *>* > *>* 1 import cgi > *>* 2 form=cgi.FieldStorage() > *>* 3 try : > *>* 4 ano=form["ano"].value > *>* 5 conta=form["conta"].value > *>* 6 except KeyError : > *>* 7 print '

Please enter values in the > *>* fields

' > *>* 8 sys.exit(0) > *>* > *>* > *>* When the excption occurs, no message is shown on the browser. > *>* > *>* If I run the script with IDLE, the message is printed and then the > *>* script exits. > *>* > *>* What's wrong here? > *>* > *>* > *>* > *>* _______________________________________________ > *>* Tutor maillist - Tutor at python.org *>* http://mail.python.org/mailman/listinfo/tutor*>* * > > I'm catching up on the weekend's tutor messages. > > import cgitb; cgitb.enable() > That spits errors to the web page which is great for debugging cgi > scripts. > > I think you need > print "Content-Type: text/html\n\n" > http://docs.python.org/lib/cgi-intro.html > http://docs.python.org/lib/node560.html > > Mike > > > Thats not the point (sorry). > > when all the values are provided in the form (no excetion is raised) it > runs as expected! > > The point is when one of the values "ano", "conta" is missing in the form, > I want the error message to be shown on the browser, and the script to stop > running. > > When there is an exception, the script actually stops running, but no > message is sent to the browser. > Actually, this is the point. The first lines of output from your CGI script, even on an error, needs to be header information to the web server and to the web browser, then a blank line, and then the content to be displayed (text, html, image, etc.). If you don't include the "print 'Content-type: text/html\n'" line that Mike suggests, then your HTML will be swallowed by the system as configuration information (and erroneous information at that). Mike suggested some webpages to review. It might be good to pour over them to learn more about the CGI protocols. -Arcege -- There's so many different worlds, So many different suns. And we have just one world, But we live in different ones. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061022/91ccb19d/attachment.htm From picioslug at gmail.com Sun Oct 22 19:45:05 2006 From: picioslug at gmail.com (Picio) Date: Sun, 22 Oct 2006 19:45:05 +0200 Subject: [Tutor] rabbit core microcontrollers - Django Message-ID: <825bef0c0610221045q3c88a986i9a1e163ae8cd1a54@mail.gmail.com> Hello, I would wonder if anyone knows something about programming Rabbit Core Modules, that normally were programmed diretctly with Dynamic C, with Python. I mean either: - something like using python to create code in dynamic suitable for the rabbit core - writing machine code for the rabbit core using a python API. Sorry if I'm not using the rights technicals words. Picio From ajkadri at googlemail.com Sun Oct 22 21:19:17 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Sun, 22 Oct 2006 20:19:17 +0100 Subject: [Tutor] getopt module.. Message-ID: Can somebody explain getopt function using a simple example.. Thanks.. Regards, Asrarahmed Kadri -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061022/8fa8859f/attachment.html From david at graniteweb.com Sun Oct 22 21:41:45 2006 From: david at graniteweb.com (David Rock) Date: Sun, 22 Oct 2006 14:41:45 -0500 Subject: [Tutor] getopt module.. In-Reply-To: References: Message-ID: <20061022194145.GA32060@wdfs.graniteweb.com> * Asrarahmed Kadri [2006-10-22 20:19]: > Can somebody explain getopt function using a simple example.. > > Thanks.. This really does have a good example of usage http://docs.python.org/lib/module-getopt.html Essentially, you define options and arguments and what you expect to see from them, then the for o, a in opts: section is used to replace default values with information from the commandline. -- David Rock david at graniteweb.com From kent37 at tds.net Mon Oct 23 00:02:25 2006 From: kent37 at tds.net (Kent Johnson) Date: Sun, 22 Oct 2006 18:02:25 -0400 Subject: [Tutor] 5 questions In-Reply-To: References: Message-ID: <453BEA71.2010909@tds.net> Alan Gauld wrote: > Pine Marten wrote: >> 2. Is there list ettiquette one should be aware of? > > Yes, but I'm not sure how you get a copy. > Moderators??? Hmm, I didn't get that as part of my new moderator's welcome package. We are pretty informal. The only real rule I can think of is, don't ask us to do your homework, and if someone does ask for a homework solution, don't give it. We will *help* with homework if you make an attempt and ask for help. The best way to ask a question is to make your best attempt at a solution and show it. Then we can see where you are stuck. If you get an exception traceback from your program, include the entire traceback in your post. > >> 3. Besides Vaults of Parnassus, are there other webpages which list >> projects >> written in Python? I'm mainly interested in looking at >> non-technical >> software, things for the common user to use. I've been surprised at >> just >> how little of that type I've found so far. > > Thee are a few such sites around. The Vaults seem to be falling into > obsolesece now, although its still my first choice. Others will give > you > their favourites I'm sure. The Python Package Index AKA the Cheese Shop is the current repository of choice: http://www.python.org/pypi If there is something specific you are looking for you could ask here or google for python plus the specific topic. > >> 4. Can anyone recommend good books for non-programmers starting out >> learning >> Python? I've looked through a few so far and they are ok ("Learning >> Python", "Python: How to Program") but am still hoping to find one >> that >> doesn't assume any prior knowledge of programming and defines terms >> when >> they are first presented. (That might be a tall order, I know...) Try these two: http://personalpages.tds.net/~kent37/BookList.html#learning-python From ajkadri at googlemail.com Mon Oct 23 01:19:50 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Mon, 23 Oct 2006 00:19:50 +0100 Subject: [Tutor] Has anyone tried matplotlib...?? Message-ID: Folks, Has anyone tried matplotlib ..//??? If yes, then is it easy to use...???? -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061023/e5e9e3fd/attachment.htm From shortpath at gmail.com Mon Oct 23 01:56:05 2006 From: shortpath at gmail.com (Matt Richardson) Date: Sun, 22 Oct 2006 16:56:05 -0700 Subject: [Tutor] Has anyone tried matplotlib...?? In-Reply-To: References: Message-ID: <4621e3520610221656p13a4e47x9141eec61711ab52@mail.gmail.com> I just used it a couple of weeks ago to produce a histogram of randomly generated numbers. Read the documentation, it's well written and has good examples. Matt On 10/22/06, Asrarahmed Kadri wrote: > > Folks, > > Has anyone tried matplotlib ..//??? > > If yes, then is it easy to use...???? > > > > > -- > To HIM you shall return. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > -- Matt From bill at celestial.net Mon Oct 23 02:45:32 2006 From: bill at celestial.net (Bill Campbell) Date: Sun, 22 Oct 2006 17:45:32 -0700 Subject: [Tutor] Has anyone tried matplotlib...?? In-Reply-To: <4621e3520610221656p13a4e47x9141eec61711ab52@mail.gmail.com> References: <4621e3520610221656p13a4e47x9141eec61711ab52@mail.gmail.com> Message-ID: <20061023004532.GA18651@ayn.mi.celestial.com> On Sun, Oct 22, 2006, Matt Richardson wrote: >I just used it a couple of weeks ago to produce a histogram of >randomly generated numbers. Read the documentation, it's well written >and has good examples. You might also want to look at gnuplot. Bill -- INTERNET: bill at Celestial.COM Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 ``If guns are outlawed, only the government will have guns. Only the police, the secret police, the military, the hired servants of our rulers. Only the government -- and a few outlaws. I intend to be among the outlaws.'' EDWARD ABBEY (1927-1989) From kent37 at tds.net Mon Oct 23 03:38:08 2006 From: kent37 at tds.net (Kent Johnson) Date: Sun, 22 Oct 2006 21:38:08 -0400 Subject: [Tutor] My first real python project: LOLLERSKATES In-Reply-To: <4539B3CB.6060207@ultraviolet.org> References: <4539B3CB.6060207@ultraviolet.org> Message-ID: <453C1D00.9070702@tds.net> Tracy R Reed wrote: > Questions/problems/TODO's: > > This is a fairly simple structured programming implementation. No OO. > Should I be using some classes somewhere? There doesn't seem to be any need for it. > > The config file is just a module which I import which causes all of my > configs to become globals. Globals are bad. Is there a better way or > would just about anything else be overkill? A singleton config class or > something? Overkill? Instead of from lollerskates_config import * try import lollerskates_config as config or some other abbreviated name. Then instead of using e.g. 'macros' in your program use 'config.macros'. This has the advantage that it is clear where macros is defined and the config variables are not global to your module. IMO singletons are greatly overused in general; in Python a module is a unique namespace. > > I have several loops in this code for processing the logfiles. I once > tried to convert these for loops to list comprehensions and totally > confused myself and backed out the change (yeay svn!). Is there any > benefit to list comprehensions in this case? I don't see any loops that lend themselves to list comprehensions. A list comp is a shorthand way to build a new list from an existing list. You don't do that. > > I would kinda like to play with unit tests. Not sure how I would > construct unit tests for this. And again, perhaps overkill. But some > people tell me you should write the unit tests before you even begin > coding and code until the tests are satisfied. So even on a small > project you would have tests. I run into a couple nasty bugs I created > which caused the script to never return anything from the logfile (so > you don't immediately realize something is broken) where I thought "It > sure would be nice to have a test to catch that if it ever happens again." Yep. Have you looked at the unit test module? Many of your functions are unit-testable though it will be easier if you write them so they don't rely on external state (i.e. globals) (this is one reason globals are evil). For example replace_tokens() could be tested, it would be easier if macros was a parameter instead of taken from the global state. process_line() would be easier to test if it didn't rely on the global events list, but either took the list as a parameter or returned the line or None and let the caller deal with it. Or maybe you do want a class that can hold the shared state... One more note: if re.match("^$",line): could just be if not line: Overall it looks pretty clean and well-written. Kent From rabidpoobear at gmail.com Mon Oct 23 04:29:40 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sun, 22 Oct 2006 21:29:40 -0500 Subject: [Tutor] 5 questions In-Reply-To: <453BEA71.2010909@tds.net> References: <453BEA71.2010909@tds.net> Message-ID: <453C2914.7080805@gmail.com> Kent Johnson wrote: > Alan Gauld wrote: > >> Pine Marten wrote: >> >>> 2. Is there list ettiquette one should be aware of? >>> >> Yes, but I'm not sure how you get a copy. >> Moderators??? >> > > Hmm, I didn't get that as part of my new moderator's welcome package. We > are pretty informal. The only real rule I can think of is, don't ask us > to do your homework, and if someone does ask for a homework solution, > don't give it. > > We will *help* with homework if you make an attempt and ask for help. > > The best way to ask a question is to make your best attempt at a > solution and show it. Then we can see where you are stuck. If you get an > exception traceback from your program, include the entire traceback in > your post. You should've gotten this e-mail when you registered: Your message for tutor at python.org, the Python programming tutor list, has been received and is being delivered. This automated response is sent to those of you new to the Tutor list, to point out a few resources that can help with answering your own questions, or improve the chances of getting a useful answer from the other subscribers. If your question is something akin to: "I've just heard about Python, and it sounds great! Where can I find out more on how to program with Python?" or: "What's Python?" please read section 1 below. On the other hand, if your question is: "I've heard that Python is good for hacking -- I want to know more!" or "Can you teach me how to break into a computer with Python?" please read section 2 at the bottom of this email. Section 1: ---------- The most comprehensive overview of python.org help resources is at http://www.python.org/Help.html The Python FAQ is available at http://www.python.org/doc/FAQ.html and it has answers to many questions that people ask, possibly including your question. Another wealth of information and experience can be found via the python.org searches, at http://www.python.org/search/ There you'll find comprehensive, easy-to-use searches over the python.org web site and the Python newsgroup, comp.lang.python. Python has an online tutorial, available freely from http://www.python.org/doc/current/tut/tut.html Finally, when you do send email to the Tutor list, be as clear as you can about the problem, including, when relevant, details like: - Precise error messages, including complete tracebacks - The hardware platform (available in the Python sys module as sys.platform) - The python version (sys.version) - The python search path (sys.path) In general, be specific about what was going on connected with the problem or what specific concept you're having difficulties with. The better the info you provide, the more likely the helpers will be able to glean the answer... There's a HOWTO that shows how to ask "smart" questions to technical folks: http://catb.org/~esr/faqs/smart-questions.html Although it is provocative, it does have some good points, and is an interesting read. Note that no one is paid to read the tutor list or provide answers, and most readers often have other work that demands their attention. Well-posed requests for help are usually answered fairly promptly, but occasionally a request slips by, so if you do not get a response with one or two working days (it's usually quicker than that), please feel free to send a followup, asking whether anyone is working on your question. Anyway, your message is being delivered to the Tutor list as this one is being sent. However, if your question was about as detailed as "Teach me how to program in Python", do not count on an answer -- this email contains all the information you need to start. Come back with a more precise question, and we'll be glad to help. Thanks! Section 2: ---------- We periodically get requests which ask about hacking or cracking or breaking into computers. If you haven't yet, go read Eric Raymond's article "How To Become a Hacker" at http://catb.org/esr/faqs/hacker-howto.html If, after you've read that, you want help learning how to hack the way Eric defines the word, then come back to us (and read Section 1 above). If you want help learning how to crack, go look elsewhere -- we're not interested in helping you do that. That about sums it up for me :) From jgcox39 at highstream.net Mon Oct 23 07:44:32 2006 From: jgcox39 at highstream.net (Joe Cox) Date: Sun, 22 Oct 2006 22:44:32 -0700 Subject: [Tutor] GUI new project Message-ID: As a new guy, I was trying to write a simple unit conversion program in Tk. I got this error message:TclError: unknown option "-command" >>> Traceback (most recent call last): File "D:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 310, in RunScript exec codeObject in __main__.__dict__ File "D:\Python24\Convert it\Tk Grid demo2py.py", line 70, in ? main() File "D:\Python24\Convert it\Tk Grid demo2py.py", line 67, in main Application().mainloop() File "D:\Python24\Convert it\Tk Grid demo2py.py", line 22, in __init__ , relief=SUNKEN) File "D:\Python24\lib\lib-tk\Tkinter.py", line 2409, in __init__ Widget.__init__(self, master, 'listbox', cnf, kw) File "D:\Python24\lib\lib-tk\Tkinter.py", line 1862, in __init__ self.tk.call( TclError: unknown option "-command" Any Ideas? Joe Cox 513-293-4830 -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: Tk Grid demo2py.py Url: http://mail.python.org/pipermail/tutor/attachments/20061022/49c1e4c3/attachment.pot From rabidpoobear at gmail.com Mon Oct 23 05:03:46 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sun, 22 Oct 2006 22:03:46 -0500 Subject: [Tutor] GUI new project In-Reply-To: References: Message-ID: <453C3112.8070101@gmail.com> > > > """Create the Second ListBox""" > > self.lbRSSItems = Listbox(self, exportselection=0 > ,command=self.reveal > , relief=SUNKEN) > Because whitespace is important in python, you can't arbitrarily put newlines into your text. Your program is getting confused because it doesn't know what ', relief=SUNKEN)' means. Try putting a '\' before your newlines. Like: x = \ 'a' HTH, -Luke From rabidpoobear at gmail.com Mon Oct 23 05:04:59 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sun, 22 Oct 2006 22:04:59 -0500 Subject: [Tutor] GUI new project In-Reply-To: References: Message-ID: <453C315B.6020708@gmail.com> Joe Cox wrote: > As a new guy, I was trying to write a simple unit conversion > program in Tk. I got this error message:TclError: unknown option "-command" > > > >>>> Traceback (most recent call last): >>>> > File > "D:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", > line 310, in RunScript > exec codeObject in __main__.__dict__ > File "D:\Python24\Convert it\Tk Grid demo2py.py", line 70, in ? > main() > File "D:\Python24\Convert it\Tk Grid demo2py.py", line 67, in main > Application().mainloop() > File "D:\Python24\Convert it\Tk Grid demo2py.py", line 22, in __init__ > , relief=SUNKEN) > File "D:\Python24\lib\lib-tk\Tkinter.py", line 2409, in __init__ > Widget.__init__(self, master, 'listbox', cnf, kw) > File "D:\Python24\lib\lib-tk\Tkinter.py", line 1862, in __init__ > self.tk.call( > TclError: unknown option "-command" > > Any Ideas? > > self.lbSites = Listbox(self,command=self.reveal, exportselection=0 > , relief=SUNKEN) > Acually I think it was this line that was causing trouble first :) Same reason, though. Cheers, -Luke From alan.gauld at btinternet.com Mon Oct 23 06:17:29 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 23 Oct 2006 05:17:29 +0100 Subject: [Tutor] GUI new project References: Message-ID: "Joe Cox" wrote > As a new guy, I was trying to write a simple unit conversion > program in Tk. I got this error message:TclError: unknown option > "-command" Which says that you are using an unknown option command... ie. Listboxes don't have a command option. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From jfabiani at yolo.com Mon Oct 23 07:26:11 2006 From: jfabiani at yolo.com (johnf) Date: Sun, 22 Oct 2006 22:26:11 -0700 Subject: [Tutor] GUI new project In-Reply-To: <453C3112.8070101@gmail.com> References: <453C3112.8070101@gmail.com> Message-ID: <200610222226.11596.jfabiani@yolo.com> On Sunday 22 October 2006 20:03, Luke Paireepinart wrote: > > """Create the Second ListBox""" > > > > self.lbRSSItems = Listbox(self, exportselection=0 > > ,command=self.reveal > > , relief=SUNKEN) > > Because whitespace is important in python, > you can't arbitrarily put newlines into your text. > Your program is getting confused because it doesn't know what ', > relief=SUNKEN)' means. > Try putting a '\' before your newlines. > Like: > x = \ > 'a' > > > HTH, > -Luke I'm not an expert Luke but I thought a statement can take more than one line when enclosed in parentheses, square brackets or braces (also when triple quoted). Is this correct???? John From rabidpoobear at gmail.com Mon Oct 23 07:32:11 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 23 Oct 2006 00:32:11 -0500 Subject: [Tutor] GUI new project In-Reply-To: <200610222226.11596.jfabiani@yolo.com> References: <453C3112.8070101@gmail.com> <200610222226.11596.jfabiani@yolo.com> Message-ID: <453C53DB.3020404@gmail.com> johnf wrote: > On Sunday 22 October 2006 20:03, Luke Paireepinart wrote: > >>> """Create the Second ListBox""" >>> >>> self.lbRSSItems = Listbox(self, exportselection=0 >>> ,command=self.reveal >>> , relief=SUNKEN) >>> >> Because whitespace is important in python, >> you can't arbitrarily put newlines into your text. >> Your program is getting confused because it doesn't know what ', >> relief=SUNKEN)' means. >> Try putting a '\' before your newlines. >> Like: >> x = \ >> 'a' >> >> >> HTH, >> -Luke >> > I'm not an expert Luke but I thought a statement can take more than one line > when enclosed in parentheses, square brackets or braces (also when triple > quoted). Is this correct???? > Yep, yep. I confess, I didn't look too closely at that, and I guess I heard one should use backslashes whenever a command goes to a new line, and I assumed it was always true, and never tried without them! You're right, of course, John, and I apologize to the OP. Alan had the correct answer to the problem. Listboxes don't take a command argument. Hope that helps! -Luke From kent37 at tds.net Mon Oct 23 13:56:05 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 23 Oct 2006 07:56:05 -0400 Subject: [Tutor] ANN: Resources for Python Newbies Message-ID: <453CADD5.4020209@tds.net> I thought this notice from the python-announce list might be of interest here. Kent Subject: ANN: Resources for Python Newbies - a 30 minute video tour of the web (2 New ShowMeDo videos) From: Ian Ozsvald Date: Sun, 22 Oct 2006 16:50:56 +0100 To: python-announce at python.org, Kyran Dale , i.m.ozsvald at btinternet.com Summary: Ian Ozsvald (joint founder of ShowMeDo.com) introduces all the usual Python on-line resources that a new Python programmer should know about. The videos cover the main Python sites, news, books, blogs, community and some of the major projects: http://showmedo.com/videos/series?name=pythonOzsvaldIntroToPyResourcesSeries Detail: Here I give a 30 minute tour of all the main Python resources that a programmer should know about. This is the kind of introduction I'd give to any new Python programmer when they ask me 'what's out there?'. Resources covered include the main Python site, Tutorials, Cheeseshop, ShowMeDo's Python videos, the Cookbook, DiveIntoPython, Daily Python, several new-programmer blogs, comp.lang.python, books (Beginning Python, Python in a Nutshell, Dive Into Python, Cookbook) and five of the larger Python projects. About ShowMeDo.com: Free videos (we call them ShowMeDos) showing you how to do things. The videos are made by us and our users, for everyone. 38 videos for Python, 71 in total, and the collection is growing. We'd love to have more contributions - would you share what you know? The founders, Ian Ozsvald, Kyran Dale From ajkadri at googlemail.com Mon Oct 23 14:12:45 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Mon, 23 Oct 2006 13:12:45 +0100 Subject: [Tutor] Thanks.....KentRe: ANN: Resources for Python Newbies Message-ID: Hi folks... Thanks a lot, Kent for this great resource. Remain blessed. Regards, Asrarahmed Kadri On 10/23/06, Kent Johnson wrote: > > I thought this notice from the python-announce list might be of interest > here. > > Kent > > Subject: > ANN: Resources for Python Newbies - a 30 minute video tour of the web (2 > New ShowMeDo videos) > From: > Ian Ozsvald > Date: > Sun, 22 Oct 2006 16:50:56 +0100 > To: > python-announce at python.org, Kyran Dale , > i.m.ozsvald at btinternet.com > > Summary: > Ian Ozsvald (joint founder of ShowMeDo.com) introduces all the usual > Python on-line resources that a new Python programmer should know > about. The videos cover the main Python sites, news, books, blogs, > community and some of the major projects: > > http://showmedo.com/videos/series?name=pythonOzsvaldIntroToPyResourcesSeries > > Detail: > Here I give a 30 minute tour of all the main Python resources that a > programmer should know about. This is the kind of introduction I'd > give to any new Python programmer when they ask me 'what's out there?'. > > Resources covered include the main Python site, Tutorials, Cheeseshop, > ShowMeDo's Python videos, the Cookbook, DiveIntoPython, Daily Python, > several new-programmer blogs, comp.lang.python, books (Beginning > Python, Python in a Nutshell, Dive Into Python, Cookbook) and > five of the larger Python projects. > > About ShowMeDo.com: > Free videos (we call them ShowMeDos) showing you how to do things. > The videos are made by us and our users, for everyone. 38 videos > for Python, 71 in total, and the collection is growing. > > We'd love to have more contributions - would you share what you know? > > The founders, > Ian Ozsvald, Kyran Dale > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061023/282d2a10/attachment.htm From ajkadri at googlemail.com Mon Oct 23 15:56:33 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Mon, 23 Oct 2006 14:56:33 +0100 Subject: [Tutor] Unable to install Matplotlib... help me... Message-ID: Folks.. I am trying to install Matplotlib on my windows machine. I have ActivePython 2.4.3 Build 12 (ActiveState Software Inc.) based on Python 2.4.3 (#69, Apr 11 2006, 15:32:42) [MSC v.1310 32 bit (Intel)] on win32. When I try to install matplotlib-0.87.6, it gives me an error message *"Python version 2.3 required, which was not found in the registry".* Any idea about resolving this issue....!!! Thanks. REgards, Asrarahmed Kadri ** -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061023/77d54cf1/attachment.htm From kent37 at tds.net Mon Oct 23 16:17:01 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 23 Oct 2006 10:17:01 -0400 Subject: [Tutor] Unable to install Matplotlib... help me... In-Reply-To: References: Message-ID: <453CCEDD.4070602@tds.net> Asrarahmed Kadri wrote: > > Folks.. > > I am trying to install Matplotlib on my windows machine. I have > ActivePython 2.4.3 Build 12 (ActiveState Software Inc.) based on > Python 2.4.3 (#69, Apr 11 2006, 15:32:42) [MSC v.1310 32 bit (Intel)] on > win32. > > When I try to install matplotlib-0.87.6, it gives me an error message > *_"Python version 2.3 required, which was not found in the registry"._* > Any idea about resolving this issue....!!! It sounds like you downloaded the wrong installer, you need the Windows installer for Python 2.4, it is called matplotlib-0.87.6.win32-py2.4.exe Kent From ajkadri at googlemail.com Mon Oct 23 17:07:54 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Mon, 23 Oct 2006 16:07:54 +0100 Subject: [Tutor] A new error while running matplotlib.... Message-ID: >>> from pylab import * #When i issued the above command, teh following error message is being displayed. -------------------------------------------------------------------------------- RuntimeError: module compiled against version 1000002 of C-API but this version of numpy is 1000009 The import of the numpy version of the nxutils module, _nsnxutils, failed. This is is either because numpy was unavailable when matplotlib was compiled, because a dependency of _nsnxutils could not be satisfied, or because the build flag for this module was turned off in setup.py. If it appears that _nsnxutils was not built, make sure you have a working copy of numpy and then re-install matplotlib. Otherwise, the following traceback gives more details: Traceback (most recent call last): File "", line 1, in ? File "C:\python\Lib\site-packages\pylab.py", line 1, in ? from matplotlib.pylab import * File "C:\python\Lib\site-packages\matplotlib\pylab.py", line 199, in ? import mlab #so I can override hist, psd, etc... File "C:\python\Lib\site-packages\matplotlib\mlab.py", line 64, in ? import nxutils File "C:\python\Lib\site-packages\matplotlib\nxutils.py", line 17, in ? from matplotlib._ns_nxutils import * ImportError: numpy.core.multiarray failed to import -------------------------------------------------------------------------------------------- Any idea how to get aroudn with this.. On 10/23/06, Kent Johnson wrote: > > Asrarahmed Kadri wrote: > > > > Folks.. > > > > I am trying to install Matplotlib on my windows machine. I have > > ActivePython 2.4.3 Build 12 (ActiveState Software Inc.) based on > > Python 2.4.3 (#69, Apr 11 2006, 15:32:42) [MSC v.1310 32 bit (Intel)] on > > win32. > > > > When I try to install matplotlib-0.87.6, it gives me an error message > > *_"Python version 2.3 required, which was not found in the registry"._* > > Any idea about resolving this issue....!!! > > It sounds like you downloaded the wrong installer, you need the Windows > installer for Python 2.4, it is called matplotlib-0.87.6.win32-py2.4.exe > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061023/1d7e2193/attachment.html From david at graniteweb.com Mon Oct 23 17:28:10 2006 From: david at graniteweb.com (David Rock) Date: Mon, 23 Oct 2006 10:28:10 -0500 Subject: [Tutor] Has anyone tried matplotlib...?? In-Reply-To: <4621e3520610221656p13a4e47x9141eec61711ab52@mail.gmail.com> References: <4621e3520610221656p13a4e47x9141eec61711ab52@mail.gmail.com> Message-ID: <20061023152810.GA20739@wdfs.graniteweb.com> * Matt Richardson [2006-10-22 16:56]: > I just used it a couple of weeks ago to produce a histogram of > randomly generated numbers. Read the documentation, it's well written > and has good examples. I met the current maintainer at the chipy (Chicago Python user group) http://www.chipy.org meeting a few months ago. He's a great guy and he did some pretty impressive things with it. It also appears to interact well with ipython, an extremely powerful python interpreter shell (much better than the built-in shell) http://ipython.scipy.org/ -- David Rock david at graniteweb.com From dyoo at hkn.eecs.berkeley.edu Mon Oct 23 17:30:49 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 23 Oct 2006 08:30:49 -0700 (PDT) Subject: [Tutor] rabbit core microcontrollers - Django In-Reply-To: <825bef0c0610221045q3c88a986i9a1e163ae8cd1a54@mail.gmail.com> References: <825bef0c0610221045q3c88a986i9a1e163ae8cd1a54@mail.gmail.com> Message-ID: On Sun, 22 Oct 2006, Picio wrote: > I would wonder if anyone knows something about programming Rabbit Core > Modules, that normally were programmed diretctly with Dynamic C, with > Python. > I mean either: > - something like using python to create code in dynamic suitable for > the rabbit core > - writing machine code for the rabbit core using a python API. Unfortunately, no, it doesn't look like many people here are familiar with this. You might want to try the comp.lang.python newsgroup next; it has a wider audience, and you may find someone there who's knowledgable with it. Good luck! From ajkadri at googlemail.com Mon Oct 23 14:37:57 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Mon, 23 Oct 2006 13:37:57 +0100 Subject: [Tutor] regarding GNUPLOT and MATPLOTLIB.. Message-ID: Is it possible to use these tools on WIndows machine ???? -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061023/b3b87dc0/attachment-0001.html From jason.massey at gmail.com Mon Oct 23 19:17:10 2006 From: jason.massey at gmail.com (Jason Massey) Date: Mon, 23 Oct 2006 12:17:10 -0500 Subject: [Tutor] regarding GNUPLOT and MATPLOTLIB.. In-Reply-To: References: Message-ID: <7e3eab2c0610231017q7b3906e4t5526bc9f271467d8@mail.gmail.com> Very possible: For gnuplot: http://gnuplot-py.sourceforge.net/ See the instructions for using on Windows. For Matplotlib: http://matplotlib.sourceforge.net/installing.html Possibly what's confusing you is that both versions have external dependencies such as Numpy and Numeric (are those the same? I'll admit to being confused on the whole numpy, numeric, numarray which is which probelm). Both pages have the dependencies listed as well as links and installation instructions. In fact the error message you posted earlier about importing Matplotlib includes detailed information about why you couldn't import matplotlib: You didn't have numeric installed. - A bit of googling goes a long way. On 10/23/06, Asrarahmed Kadri wrote: > > > > > > Is it possible to use these tools on WIndows machine ???? > > > > -- > To HIM you shall return. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061023/24fb0bc3/attachment.html From wescpy at gmail.com Mon Oct 23 19:34:46 2006 From: wescpy at gmail.com (wesley chun) Date: Mon, 23 Oct 2006 10:34:46 -0700 Subject: [Tutor] Exception and sys.exit() in a cgi script In-Reply-To: <7e5ba9220610220606h3e9cacf3w5e432a8a8a11e4fb@mail.gmail.com> References: <453ACAD1.9070507@sapo.pt> <7e5ba9220610220606h3e9cacf3w5e432a8a8a11e4fb@mail.gmail.com> Message-ID: <78b3a9580610231034o7cbc7b4eu70dd53a842e36044@mail.gmail.com> > > > 7 print '

Please enter values in the > > > fields

' > > > > > > When the excption occurs, no message is shown on the browser. > > > If I run the script with IDLE, the message is printed and then the script exits. > > > > > > import cgitb; cgitb.enable() > > That spits errors to the web page which is great for debugging cgi > > scripts. > > > > Thats not the point (sorry). > > when all the values are provided in the form (no excetion is raised) it > runs as expected! > > > > The point is when one of the values "ano", "conta" is missing in the form, > I want the error message to be shown on the browser, and the script to stop > running. > > > > When there is an exception, the script actually stops running, but no > message is sent to the browser. paulino, mike and michael are correct. i know your script runs fine when the form fields are entered. the output is quite different tho. as alan and everyone has alluded to, sending output to the screen is different than sending to a browser there is "more work" in order to get the text to it. when you display to the screen, it is a direct connect to the standard output (not nec stdout) display, which is your monitor. when you send things to a browser, you have to remember that web pages flow on the network (even on the same machine). the protocol that is used is called HTTP, and as the writer of software that runs on the server side, you need to communicate to the client using that protocol properly to the client (otherwise that defeats the purpose of even *having* a protocol). the headers which michael has mentioned in his above post are the required part of the HTTP protocol that must come before any HTML is sent (by your script). review the recommended documents to get a good idea of how CGI works with HTTP and HTML, and then you will be ok. here is a Core Tip i placed on p.882 in the web programming chapter my book (see below): CORE TIP: HTTP headers separate from HTML One thing that always nails CGI beginners is that when sending results back to a CGI script, it must return the appropriate HTTP headers first before any HTML. Furthermore, to distinguish between these headers and the resulting HTML, several NEWLINE characters must be inserted between both sets of data, as in line 5 of our friends1.py example, as well as for the code in the remaining part of the chapter. if you happen to have access to a copy of the book, that chapter will really help you really understand how to write a CGI script successfully. basically, my summary is this: you will see a lot of 500/ISE errors and cgitb is your friend. :-) hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From ajkadri at googlemail.com Mon Oct 23 21:12:34 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Mon, 23 Oct 2006 20:12:34 +0100 Subject: [Tutor] regarding GNUPLOT and MATPLOTLIB.. In-Reply-To: <7e3eab2c0610231017q7b3906e4t5526bc9f271467d8@mail.gmail.com> References: <7e3eab2c0610231017q7b3906e4t5526bc9f271467d8@mail.gmail.com> Message-ID: I have installed numpy module.. Isnt that enough for using matplotlib...?? Or I need both numeric as well as Numpy.. Please reply. Regards, Asrar On 10/23/06, Jason Massey wrote: > > Very possible: > > For gnuplot: > > http://gnuplot-py.sourceforge.net/ > > See the instructions for using on Windows. > > > For Matplotlib: > > http://matplotlib.sourceforge.net/installing.html > > > Possibly what's confusing you is that both versions have external > dependencies such as Numpy and Numeric (are those the same? I'll admit to > being confused on the whole numpy, numeric, numarray which is which > probelm). Both pages have the dependencies listed as well as links and > installation instructions. > > In fact the error message you posted earlier about importing Matplotlib > includes detailed information about why you couldn't import matplotlib: You > didn't have numeric installed. > > - > > A bit of googling goes a long way. > > > > On 10/23/06, Asrarahmed Kadri wrote: > > > > > > > > > > > > Is it possible to use these tools on WIndows machine ???? > > > > > > > > -- > > To HIM you shall return. > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061023/0154a076/attachment.html From ajkadri at googlemail.com Mon Oct 23 23:03:10 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Mon, 23 Oct 2006 22:03:10 +0100 Subject: [Tutor] Please comment on this code...WORD FREQUENCY COUNTER Message-ID: Folks, I have written a program which calculates teh frequency of each word that appears in a file. I would like to have your feedback. *This program only handles .txt files. I want it to handle word documents also. How to accomplish this ..???* Thanks. Regards. Asrarahmed *Code is as under:* ** fname = raw_input("Enter the file name to be opened") fd = open(fname, 'r') done = 0 dict1 = {} # create an empty dictionary to hold word as a key and its freq. as the value while not done: aLine = fd.readline() if aLine != "" : string1 = aLine.split() for item in string1: dict1[item] = 0 #enter each word as the key and intial value as 0 else: done = 1 fd.seek(0,0) # go to the beginning of the file done = 0 while not done: aLine = fd.readline() # read one line at a time if aLine != "" : string1 = aLine.split() # split the line into a list of words... for item in string1: dict1[item] += 1 # counter for the word else: done = 1 print "Word \t Frequency" for k,v in dict1.iteritems(): # print the word and its corresponding frequency print k, "\t\t", v -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061023/5fa61181/attachment.html From wescpy at gmail.com Mon Oct 23 23:21:49 2006 From: wescpy at gmail.com (wesley chun) Date: Mon, 23 Oct 2006 14:21:49 -0700 Subject: [Tutor] Please comment on this code...WORD FREQUENCY COUNTER In-Reply-To: References: Message-ID: <78b3a9580610231421g368577bq62d159a731cba592@mail.gmail.com> > I have written a program which calculates teh frequency of each word that > appears in a file. I would like to have your feedback. > This program only handles .txt files. I want it to handle word documents > also. How to accomplish this ..??? Asrarahmed, you have made a good start. one area of improvement you can make is that your current code scans a file twice. see if you can do it using a single pass. for doing it with Word, you can just use the same algorithm you have developed above. all you need to do is to use the Win32 COM client libraries in the Python Extensions for Windows to open up a Word document and pull out the text. there are many places to find out how to open a Word document from Python, so i won't discuss it here. hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From john at fouhy.net Mon Oct 23 23:22:28 2006 From: john at fouhy.net (John Fouhy) Date: Tue, 24 Oct 2006 10:22:28 +1300 Subject: [Tutor] Please comment on this code...WORD FREQUENCY COUNTER In-Reply-To: References: Message-ID: <5e58f2e40610231422j75da3044oafa7ffae37734179@mail.gmail.com> On 24/10/06, Asrarahmed Kadri wrote: > I have written a program which calculates teh frequency of each word that > appears in a file. I would like to have your feedback. > This program only handles .txt files. I want it to handle word documents > also. How to accomplish this ..??? Dealing with word documents will be tricky. You will probably have to use pythonwin to control Microsoft Word. > fname = raw_input("Enter the file name to be opened") > > fd = open(fname, 'r') > > done = 0 > dict1 = {} # create an empty dictionary to hold word as a key > and its freq. as the value > while not done: > aLine = fd.readline() > if aLine != "" : What happens if aLine is (for example) " "? > fd.seek(0,0) # go > to the beginning of the file Ok, you don't need to go through the file twice. The normal idiom would be something like: try: dict1[item] += 1 except KeyError: dict1[item] = 1 That will allow you to do the whole thing in just one pass through the file. Hmm, and you are stopping on the first empty line, even if there is more text below. You can use a for loop to iterate through the lines of a file: textfile = open(fname, 'r') for line in textfile: # process line You might also want to think about giving your variables better names. Eg: instead of 'dict1', say 'frequencies' instead of 'item' say 'word' So you could end up with: textfile = open(fname, 'r') for line in textfile: for word in line.split(): # do something with word HTH! -- John. From john at fouhy.net Mon Oct 23 23:31:10 2006 From: john at fouhy.net (John Fouhy) Date: Tue, 24 Oct 2006 10:31:10 +1300 Subject: [Tutor] can i pass a list to a function and get one back ? In-Reply-To: <453B5722.6010201@tds.net> References: <384c93600610211820s65dee397q4b8b0847396d146c@mail.gmail.com> <20061022012614.GA15729@ayn.mi.celestial.com> <384c93600610211912x503861cbx200c0a5f17736614@mail.gmail.com> <453B5722.6010201@tds.net> Message-ID: <5e58f2e40610231431n9b30c4doaeb551b19f1e9606@mail.gmail.com> On 23/10/06, Kent Johnson wrote: > or for that matter > return range(some_var:some_var+5) [nit-pick] That would be range(some_var, some_var+5) :-) -- John. From ajkadri at googlemail.com Tue Oct 24 00:10:51 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Mon, 23 Oct 2006 23:10:51 +0100 Subject: [Tutor] regarding GNUPLOT and MATPLOTLIB.. In-Reply-To: <7e3eab2c0610231017q7b3906e4t5526bc9f271467d8@mail.gmail.com> References: <7e3eab2c0610231017q7b3906e4t5526bc9f271467d8@mail.gmail.com> Message-ID: I have installed numpy but still I am not able to use matplotlib. the error is same: >>> >>> from pylab import * RuntimeError: module compiled against version 1000002 of C-API but this version of numpy is 1000009 The import of the numpy version of the nxutils module, _nsnxutils, failed. This is is either because numpy was unavailable when matplotlib was compiled, because a dependency of _nsnxutils could not be satisfied, or because the build flag for this module was turned off in setup.py. If it appears that _nsnxutils was not built, make sure you have a working copy of numpy and then re-install matplotlib. Otherwise, the following traceback gives more details: Traceback (most recent call last): File "", line 1, in ? File "C:\python\Lib\site-packages\pylab.py", line 1, in ? from matplotlib.pylab import * File "C:\python\Lib\site-packages\matplotlib\pylab.py", line 199, in ? import mlab #so I can override hist, psd, etc... File "C:\python\Lib\site-packages\matplotlib\mlab.py", line 64, in ? import nxutils File "C:\python\Lib\site-packages\matplotlib\nxutils.py", line 17, in ? from matplotlib._ns_nxutils import * ImportError: numpy.core.multiarray failed to import On 10/23/06, Jason Massey wrote: > > Very possible: > > For gnuplot: > > http://gnuplot-py.sourceforge.net/ > > See the instructions for using on Windows. > > > For Matplotlib: > > http://matplotlib.sourceforge.net/installing.html > > > Possibly what's confusing you is that both versions have external > dependencies such as Numpy and Numeric (are those the same? I'll admit to > being confused on the whole numpy, numeric, numarray which is which > probelm). Both pages have the dependencies listed as well as links and > installation instructions. > > In fact the error message you posted earlier about importing Matplotlib > includes detailed information about why you couldn't import matplotlib: You > didn't have numeric installed. > > - > > A bit of googling goes a long way. > > > > On 10/23/06, Asrarahmed Kadri wrote: > > > > > > > > > > > > Is it possible to use these tools on WIndows machine ???? > > > > > > > > -- > > To HIM you shall return. > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061023/7efcaa25/attachment.htm From jason.massey at gmail.com Tue Oct 24 00:32:00 2006 From: jason.massey at gmail.com (Jason Massey) Date: Mon, 23 Oct 2006 17:32:00 -0500 Subject: [Tutor] regarding GNUPLOT and MATPLOTLIB.. In-Reply-To: References: <7e3eab2c0610231017q7b3906e4t5526bc9f271467d8@mail.gmail.com> Message-ID: <7e3eab2c0610231532u439647v3e078cc0e31a1467@mail.gmail.com> Asrarahmed, I saw this on the matplotlib site, perhaps it pertains to your situation: The latest matplotlib-0.87.6 for windows was compiled with numpy 1.0rc2. Please do not upgrade matplotlib for windows if you are running the latest numpy 1.0rc3. Check back soon as we hope to get a binary build for the latest numpy ASAP. You can check your numpy version by doing >>> import numpy >>> print numpy.__version__ Note, the latest matplotlib compiles and runs fine against the latest numpy -- this only affects binary builds such as the windows installer. On 10/23/06, Asrarahmed Kadri wrote: > > I have installed numpy but still I am not able to use matplotlib. > the error is same: > > >>> > >>> from pylab import * > RuntimeError: module compiled against version 1000002 of C-API but this > version > of numpy is 1000009 > > The import of the numpy version of the nxutils module, > _nsnxutils, failed. This is is either because numpy was > unavailable when matplotlib was compiled, because a dependency of > _nsnxutils could not be satisfied, or because the build flag for > this module was turned off in setup.py. If it appears that > _nsnxutils was not built, make sure you have a working copy of > numpy and then re-install matplotlib. Otherwise, the following > traceback gives more details: > > Traceback (most recent call last): > File "", line 1, in ? > File "C:\python\Lib\site-packages\pylab.py", line 1, in ? > from matplotlib.pylab import * > File "C:\python\Lib\site-packages\matplotlib\pylab.py", line 199, in ? > import mlab #so I can override hist, psd, etc... > File "C:\python\Lib\site-packages\matplotlib\mlab.py", line 64, in ? > import nxutils > File "C:\python\Lib\site-packages\matplotlib\nxutils.py", line 17, in ? > from matplotlib._ns_nxutils import * > ImportError: numpy.core.multiarray failed to import > > > > On 10/23/06, Jason Massey wrote: > > > > Very possible: > > > > For gnuplot: > > > > http://gnuplot-py.sourceforge.net/ > > > > See the instructions for using on Windows. > > > > > > For Matplotlib: > > > > http://matplotlib.sourceforge.net/installing.html > > > > > > Possibly what's confusing you is that both versions have external > > dependencies such as Numpy and Numeric (are those the same? I'll admit to > > being confused on the whole numpy, numeric, numarray which is which > > probelm). Both pages have the dependencies listed as well as links and > > installation instructions. > > > > In fact the error message you posted earlier about importing Matplotlib > > includes detailed information about why you couldn't import matplotlib: You > > didn't have numeric installed. > > > > - > > > > A bit of googling goes a long way. > > > > > > > > On 10/23/06, Asrarahmed Kadri < ajkadri at googlemail.com> wrote: > > > > > > > > > > > > > > > > > > Is it possible to use these tools on WIndows machine ???? > > > > > > > > > > > > -- > > > To HIM you shall return. > > > > > > _______________________________________________ > > > Tutor maillist - Tutor at python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > > > > > > -- > To HIM you shall return. > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061023/8f980d8b/attachment.html From tiagosaboga at terra.com.br Tue Oct 24 03:34:45 2006 From: tiagosaboga at terra.com.br (Tiago Saboga) Date: Mon, 23 Oct 2006 22:34:45 -0300 Subject: [Tutor] Please comment on this code...WORD FREQUENCY COUNTER In-Reply-To: References: Message-ID: <200610232234.45940.tiagosaboga@terra.com.br> Em Segunda 23 Outubro 2006 18:03, Asrarahmed Kadri escreveu: > Folks, > > I have written a program which calculates teh frequency of each word that > appears in a file. I would like to have your feedback. Sorry, I couldn't resist. Others talked about your code, but here's what I use (no, it's not python, it's just linux utils): $ sed -e 's/[[:space:]]/\n/g' -e 's/.*/\L&/g' -e 's/[][,;.:()]//g' myfile.txt | sort -d | uniq -c | sort -n Tiago. From python-tutor at adamgomaa.com Tue Oct 24 04:00:36 2006 From: python-tutor at adamgomaa.com (Adam Gomaa) Date: Mon, 23 Oct 2006 22:00:36 -0400 Subject: [Tutor] Evaluate my script? Message-ID: <453D73C4.7040800@adamgomaa.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hello, -tutor. I wrote this script in chemistry class, which gets the user's input for various parts of the PV=nRT ideal gas law, then calculates the missing variable, which you indicate by putting in an 'x'. I've tried to follow 'best practices' per se, and I'm looking for feedback on if I've done anything that's a Python or programming no-no. I've attached the script, and it's online with highlighting here: http://www.adamgomaa.com/docuwiki/doku.php?id=pvnrt2.py Incidentally, that's a wiki, so you can edit it there if you like. Thanks for your time. Full disclosure: I am taking an Intro. to Programming course in which we use Python, but this is not my homework- we're actually moving much more slowly than I would like :/ And, this isn't work for the chemistry class either. I do use this script in class, but not on graded assignments/tests during which we can't use computers anyway... -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.2.2 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD4DBQFFPXOrOvYxdjZi+ggRAjl3AJUSlJNb3g9vqIJ9TDht2Ga/e7OQAJ9+jinx ddN7X9VJghNwtwROhlA78A== =MP74 -----END PGP SIGNATURE----- -------------- next part -------------- A non-text attachment was scrubbed... Name: pvnrt2.py Type: text/x-python Size: 5303 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20061023/93f93d15/attachment-0001.py From python-tutor at adamgomaa.com Tue Oct 24 04:16:57 2006 From: python-tutor at adamgomaa.com (Adam Gomaa) Date: Mon, 23 Oct 2006 22:16:57 -0400 Subject: [Tutor] Evaluate my script? In-Reply-To: <453D73C4.7040800@adamgomaa.com> References: <453D73C4.7040800@adamgomaa.com> Message-ID: <453D7799.9030207@adamgomaa.com> I'm sorry; I somehow lost a newline in copypasting. At about line #105, a newline is needed after "#return For loop" (this has been fixed on the HTML version that was linked before.) Adam Gomaa wrote: > Hello, -tutor. I wrote this script in chemistry class, which gets the > user's input for various parts of the PV=nRT ideal gas law, then > calculates the missing variable, which you indicate by putting in an 'x'. > > I've tried to follow 'best practices' per se, and I'm looking for > feedback on if I've done anything that's a Python or programming no-no. > > I've attached the script, and it's online with highlighting here: > http://www.adamgomaa.com/docuwiki/doku.php?id=pvnrt2.py > Incidentally, that's a wiki, so you can edit it there if you like. > > Thanks for your time. > > Full disclosure: I am taking an Intro. to Programming course in which > we use Python, but this is not my homework- we're actually moving much > more slowly than I would like :/ > And, this isn't work for the chemistry class either. I do use this > script in class, but not on graded assignments/tests during which we > can't use computers anyway... From project5 at redrival.net Tue Oct 24 09:54:42 2006 From: project5 at redrival.net (Andrei) Date: Tue, 24 Oct 2006 07:54:42 +0000 (UTC) Subject: [Tutor] Evaluate my script? References: <453D73C4.7040800@adamgomaa.com> <453D7799.9030207@adamgomaa.com> Message-ID: Adam Gomaa adamgomaa.com> writes: > Hello, -tutor. I wrote this script in chemistry class, which gets the > user's input for various parts of the PV=nRT ideal gas law, then > calculates the missing variable, which you indicate by putting in an 'x'. > > I've tried to follow 'best practices' per se, and I'm looking for > feedback on if I've done anything that's a Python or programming no-no. Hi Adam, The script looks ok. You make good use of functions, have documented your intents and use decent variable names. Of course there's always room for improvement :). The string module defines the constants digits and lowercase, so you don't have to define them yourself. I would also choose to initialize the other constant, R, simply at the top of the module, instead of inside an init function. This is important because if I'd want to use your module, I'd expect not to have to call init() to make sure it exists. In your current implementation init is called automatically, but that's a violation of Python idiom that I'll address below. I would recommend using "from __future__ import division" at the top of your script, so division behaves properly (3/2 == 1.5 instead of 1). This way you don't have to make sure you write 3.0/2 everywhere you need to divide something. There's something to be said for your approach as well though, since someone reading your code would know what to expect when seeing 3.0/2, without caring whether "from __future__ import division" is used. But I consider the integer division in Python improper behavior that is fixed by this statement. A quick glance at the parsingLogic function shows it's much larger and more complex than its siblings. This is a sign that it's a good candidate for some improvement work. First, the name: functions should describe an action and therefore start with a verb - parseInput would be better. This new name also raises certain expectations: I put in the user input (strings) and I get out some numbers. At this point, the function does not do this, which leads to the ugly float() calls all over the place. If you look inside the function, two things are striking: repeated behavior patterns and the presence of 4 indentation levels. Let's start with the repeats: the splitting of values into a number and an unit. Have a look at what happens for p, v and t: all of them have the same logic. Can you refactor that (in other words, extract the common behavior into a separate function) and thereby simplify the code? This logic should A) split the input into a numerical value and an unit (may be unspecified), B) return the value as a number and the unit as a string. Then the excessive indentation levels: the temp_list is the cause of this. Lists are great if you want to perform the same processing on all of their elements. In this case, the list just takes a bunch of unrelated things together and then you treat the individual things in different ways. It's like going to the market to buy an apple and doing this by taking a bag, filling it with one piece of every fruit type on offer, then taking every fruit out of the bag, examining whether it is an apple and buy the one where this test returns True. The sanity check at the top could easily be written as follows (slightly shorter, one variable less and just as clear): if 'x'==p: unknown_variable='p' elif 'x'==v: unknown_variable='v' elif 'x'==t: unknown_variable='t' elif 'x' ==m: unknown_variable='m' else: # user didn't specify any unknowns print "########## No variable found! ############" return False # Causes an error, hence the noticable string The "for each in temp_list" loop will disappear completely and be replaced by something like (with splitInput being the refactored function I mentioned above): pvalue, punit = splitInput(p) if punit in ['a', 'atm']: # easier than "if punit=='a' or punit=='atm' pvalue = pvalue * 101.325 elif punit in ['torr', 'tor', 'mmhg']: pvalue = pvalue * 101.325 / 760 # similar code for v and t If splitInput is implemented correctly, you don't even have to check whether p=='x': splitInput just returns pvalue==0 and punit=='x' and the code would work just fine! This has removed two indentation levels. Of course you'd have to return pvalue instead of p at the end of parseInput. The calculations function could use a better name that indicates an action, like calculateUnknown. It's a pity that you've defined calcPress and its siblings inside calculateUnknown instead of outside: they're functions that would be reusable in other chemistry/physics-related applications if they were contained as normal functions inside the module. The float() stuff will disappear if you modify parseInput as described above. The output() function seems a bit pointless in the current implementation - I'd just use "print" directly in main. Now onto the Python idiom I mentioned at the beginning: for reuse it's better to not always run the main() function. If I import your module because I want to reuse calcVol, I'd end up running the complete code. In order to avoid this, write at the bottom of the module: if __name__=='__main__': main() This way main is only called if the script is running on its own, not by being imported in some other application. Some generic remarks: 1. I can think of an potentially useful use case for specifying all 4 input values with no unknowns: check whether the combination is valid while doing homework, without getting the correct answer. This is a bit tricky because you can't assume pV is *exactly* equal to nRT when floats are used, so you'd have to build in a bit of tolerance. 2. Functions can be assigned as variables, like this: >>> def myfunc(a, b): ... print a + b ... >>> f = myfunc # note the absence of parentheses - myfunc is not called! >>> f(3, 4) # calls myfunc 7 To make things even better, you can convert lists to function arguments like this: >>> args = [3,4] >>> f(*args) # the * 'unpacks' the list 7 Using these two techniques makes it possible to get rid of "unknown_variable": parseInput could return a function and a list of arguments to be supplied to it. There is an argument to be made both in favor and against this approach, but it's interesting anyway. 3. Mirror user input: the highly tolerant unit parsing is potentially dangerous. Say I accidentally specify p=2atn. The program will calculate with 2 kPa, but I wouldn't know that. If instead it displayed its interpretation of my input by writing "p = 2 kPa" to the screen, I'd have a better chance of noticing. Alternatively, you could provide a warning like "unknown pressure unit: atn. Assuming kPa.". That's a lot of comments for such a small program, so keep in mind you don't have to do everything I (or others :)) write. Some of the advice is generic in nature: e.g. you might not care about reuse in this particular case, but it's still good to know what you should pay attention to in the cases where you DO care. Yours, Andrei From ajkadri at googlemail.com Tue Oct 24 12:42:24 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Tue, 24 Oct 2006 11:42:24 +0100 Subject: [Tutor] Question abt numpy and Numeric........... Message-ID: Folks, Is numpy different from Numeric; or are both one and the same >?? Kindly explain the difference .. Regards, Asrarahmed -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061024/260b3ec4/attachment.html From kent37 at tds.net Tue Oct 24 13:43:01 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 24 Oct 2006 07:43:01 -0400 Subject: [Tutor] Question abt numpy and Numeric........... In-Reply-To: References: Message-ID: <453DFC45.8040207@tds.net> Asrarahmed Kadri wrote: > > Folks, > > Is numpy different from Numeric; or are both one and the same >?? > > Kindly explain the difference .. See http://numpy.scipy.org/#older_array From paulino1 at sapo.pt Tue Oct 24 14:23:29 2006 From: paulino1 at sapo.pt (paulino1 at sapo.pt) Date: Tue, 24 Oct 2006 13:23:29 +0100 Subject: [Tutor] Exception and sys.exit() in a cgi script In-Reply-To: <78b3a9580610231034o7cbc7b4eu70dd53a842e36044@mail.gmail.com> References: <453ACAD1.9070507@sapo.pt> <7e5ba9220610220606h3e9cacf3w5e432a8a8a11e4fb@mail.gmail.com> <78b3a9580610231034o7cbc7b4eu70dd53a842e36044@mail.gmail.com> Message-ID: <1161692609.23vnnww2roao@w10.mail.sapo.pt> I was wrong! Now it works fine! Thank you! I have another similar script where the print HTTP headers statement is in a previous line... In this one it is not the case. Sorry for my inconvenience! Paulino Citando wesley chun : > > > >> > > paulino, > > mike and michael are correct. (...) > > -- wesley > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > "Core Python Programming", Prentice Hall, (c)2007,2001 > http://corepython.com > > wesley.j.chun :: wescpy-at-gmail.com > python training and technical consulting > cyberweb.consulting : silicon valley, ca > http://cyberwebconsulting.com > From ajkadri at googlemail.com Tue Oct 24 14:36:59 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Tue, 24 Oct 2006 13:36:59 +0100 Subject: [Tutor] Question abt numpy and Numeric........... In-Reply-To: <453DFC45.8040207@tds.net> References: <453DFC45.8040207@tds.net> Message-ID: I got it, both are same, numpy is the latest. Numeric being the oldest, numarray in the middle and the latest is numpy. Got it .. Thanks Kent.. On 10/24/06, Kent Johnson wrote: > > Asrarahmed Kadri wrote: > > > > Folks, > > > > Is numpy different from Numeric; or are both one and the same >?? > > > > Kindly explain the difference .. > > See > http://numpy.scipy.org/#older_array > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061024/56eacd31/attachment.html From dyoo at hkn.eecs.berkeley.edu Tue Oct 24 17:15:13 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 24 Oct 2006 08:15:13 -0700 (PDT) Subject: [Tutor] Evaluate my script? In-Reply-To: <453D73C4.7040800@adamgomaa.com> References: <453D73C4.7040800@adamgomaa.com> Message-ID: On Mon, 23 Oct 2006, Adam Gomaa wrote: > Hello, -tutor. I wrote this script in chemistry class, which gets the > user's input for various parts of the PV=nRT ideal gas law, then > calculates the missing variable, which you indicate by putting in an > 'x'. Hi Adam, I haven't looked at your program in-depth yet, but nothing I've skimmed so far raises any terribly crimson red alarms yet. A side comment: what you've done is something that a "constraint-based" system helps with. You've written a program to handle the missing unknown by writing explicitely what to do in each case. But a constraint-based system tries to do this hard work without your intervention. For example, see: http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-22.html#%_sec_3.3.5 which discusses the design of a constraint system. Translating this code from Scheme to Python isn't too bad. Perhaps someone here would like to give it a shot? Best of wishes! From rabidpoobear at gmail.com Tue Oct 24 17:16:01 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 24 Oct 2006 10:16:01 -0500 Subject: [Tutor] Evaluate my script? In-Reply-To: References: <453D73C4.7040800@adamgomaa.com> <453D7799.9030207@adamgomaa.com> Message-ID: <453E2E31.7090208@gmail.com> > I would recommend using "from __future__ import division" at the top of your > script, so division behaves properly (3/2 == 1.5 instead of 1). This way you > don't have to make sure you write 3.0/2 everywhere you need to divide something. > There's something to be said for your approach as well though, since someone > reading your code would know what to expect when seeing 3.0/2, without caring > whether "from __future__ import division" is used. But I consider the integer > division in Python improper behavior that is fixed by this statement. so in Python 3000 there's no more integer division? I hope this is not the case. Sometimes it's the desired action, like when you repeatedly divide/mod a variable. From kent37 at tds.net Tue Oct 24 17:34:10 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 24 Oct 2006 11:34:10 -0400 Subject: [Tutor] Evaluate my script? In-Reply-To: <453E2E31.7090208@gmail.com> References: <453D73C4.7040800@adamgomaa.com> <453D7799.9030207@adamgomaa.com> <453E2E31.7090208@gmail.com> Message-ID: <453E3272.7000907@tds.net> Luke Paireepinart wrote: > so in Python 3000 there's no more integer division? > I hope this is not the case. > Sometimes it's the desired action, like when you repeatedly divide/mod a > variable. Integer division is still available using the // operator: In [1]: from __future__ import division In [2]: 3/2 Out[2]: 1.5 In [3]: 3//2 Out[3]: 1 Kent From rabidpoobear at gmail.com Tue Oct 24 17:35:35 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 24 Oct 2006 10:35:35 -0500 Subject: [Tutor] Evaluate my script? In-Reply-To: <453E3272.7000907@tds.net> References: <453D73C4.7040800@adamgomaa.com> <453D7799.9030207@adamgomaa.com> <453E2E31.7090208@gmail.com> <453E3272.7000907@tds.net> Message-ID: <453E32C7.4050200@gmail.com> Kent Johnson wrote: > Luke Paireepinart wrote: > >> so in Python 3000 there's no more integer division? >> I hope this is not the case. >> Sometimes it's the desired action, like when you repeatedly divide/mod a >> variable. >> > > Integer division is still available using the // operator: > > In [1]: from __future__ import division > > In [2]: 3/2 > Out[2]: 1.5 > > In [3]: 3//2 > Out[3]: 1 > Ah, that's good news. It also makes it more clear what you expect the result to be. Thanks for the info. From arunkumarpg at gmail.com Tue Oct 24 18:59:27 2006 From: arunkumarpg at gmail.com (Arun Kumar PG) Date: Tue, 24 Oct 2006 22:29:27 +0530 Subject: [Tutor] Writing serialized objects from BaseHTTPServer In-Reply-To: <3cffff920610190411l1b868314oad2ad5e53a5f052@mail.gmail.com> References: <3cffff920610190411l1b868314oad2ad5e53a5f052@mail.gmail.com> Message-ID: <3cffff920610240959q22bea73ajde929de21931b656@mail.gmail.com> any replies for the below ? On 10/19/06, Arun Kumar PG wrote: > > Hi Guys, > > I wrote a simple server using sockets ,the traditional whille True: > scoket.accept() approach. This server reads some pickled parameters sent > by the client using the cPickle module -> do some processing -> and finally > writes a list of tuples, objects using cPickle back to the client output > stream ( cPickle.dump). > > Now I want to replace this server with an HTTP server. Python's > BaseHTTPServer basically. I was wondering when using BaseHTTPServer if I > want to read/write a serialized object to meet the above behavior how could > I achive this using HTTP server ? We need a content-type to specify before > writing back to the client -- whats the content-type for serialised objects > which I want to write back to the client using cPickle ? > > Thanks. > > Arun > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061024/43fb8d0b/attachment.htm From kent37 at tds.net Tue Oct 24 19:25:45 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 24 Oct 2006 13:25:45 -0400 Subject: [Tutor] Writing serialized objects from BaseHTTPServer In-Reply-To: <3cffff920610190411l1b868314oad2ad5e53a5f052@mail.gmail.com> References: <3cffff920610190411l1b868314oad2ad5e53a5f052@mail.gmail.com> Message-ID: <453E4C99.7080501@tds.net> Arun Kumar PG wrote: > We need a content-type to > specify before writing back to the client -- whats the content-type for > serialised objects which I want to write back to the client using cPickle ? Maybe application/octet-stream or application/x-pickle? Kent From python-tutor at adamgomaa.com Tue Oct 24 19:32:55 2006 From: python-tutor at adamgomaa.com (Adam Gomaa) Date: Tue, 24 Oct 2006 13:32:55 -0400 Subject: [Tutor] Evaluate my script? In-Reply-To: References: <453D73C4.7040800@adamgomaa.com> <453D7799.9030207@adamgomaa.com> Message-ID: <453E4E47.60101@adamgomaa.com> Thanks for your help! I've rewritten it with many of your suggestions and will definitely use this as a reference for future scripts. Here's the updated one. (I also played around with lambdas, I don't know if they're actually needed/useful there, but I haven't used them before and I wanted some practice with them). I ran into some trouble with string.strip(). I worked around it by simply piling on more strip statements, although I doubt that's the correct way to do it :P. It's in the splitInput() function, inside the parseInput() function. > That's a lot of comments for such a small program, so keep in mind you don't > have to do everything I (or others :)) write. Some of the advice is generic in > nature: e.g. you might not care about reuse in this particular case, but it's > still good to know what you should pay attention to in the cases where you DO > care. I was afraid I hadn't commented enough! Well, now I know... Thanks again, Adam -------------- next part -------------- A non-text attachment was scrubbed... Name: pvnrt3.py Type: text/x-python Size: 5593 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20061024/a2a9879d/attachment-0001.py From kent37 at tds.net Tue Oct 24 19:53:51 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 24 Oct 2006 13:53:51 -0400 Subject: [Tutor] Evaluate my script? In-Reply-To: <453E4E47.60101@adamgomaa.com> References: <453D73C4.7040800@adamgomaa.com> <453D7799.9030207@adamgomaa.com> <453E4E47.60101@adamgomaa.com> Message-ID: <453E532F.8050309@tds.net> Adam Gomaa wrote: > Thanks for your help! I've rewritten it with many of your suggestions > and will definitely use this as a reference for future scripts. > > Here's the updated one. > userInputString=userInput.strip(string.digits) > userInputString=userInputString.strip(string.punctuation)# this one > userInputString=userInputString.strip(string.digits) > userInputString=userInputString.strip(string.whitespace) > userInputString=userInputString.strip(string.digits)# and this one. > > > userInputValue=userInput.strip(string.letters) > userInputValue=userInputValue.strip(string.whitespace) I'm not entirely sure I follow this but I think you could use userInputString=userInput.strip(string.digits+string.punctuation+string.digits+string.whitespace) userInputValue=userInput.strip(string.letters+string.whitespace) > def convertUnits(startingUnit,value): > """Convert the passed value, with startingUnit, into appropriate units > for the rest of the module.""" > > #For next if block, each of these should pass value into a lambda > # function from the dictionaries above. In theory, then, it should > # always convert into kPa, l, or k. > if startingUnit in pressureUnitDict.keys(): #WHY the error? > return pressureUnitDict[startingUnit](value) > > elif startingUnit in volumeUnitDict.keys(): > return volumeUnitDict[startingUnit](value) > > elif startingUnit in temperatureUnitDict.keys(): > return temperatureUnitDict[startingUnit](value) > > elif startingUnit=='x': > return value > else: > print '### Unknown unit "%s" -- Using default. ###' % startingUnit > return value This is ugly. I would either - pass the correct dict as an argument - make separate convertPressure(), convertVolume(), convertTemperature() functions, which probably will pass the correct dict to a helper function. - Just put all the conversions in one dict, which will give the same functionality you have now. Kent From nephish at gmail.com Wed Oct 25 00:24:39 2006 From: nephish at gmail.com (shawn bright) Date: Tue, 24 Oct 2006 17:24:39 -0500 Subject: [Tutor] can i pass a list to a function and get one back ? In-Reply-To: <5e58f2e40610231431n9b30c4doaeb551b19f1e9606@mail.gmail.com> References: <384c93600610211820s65dee397q4b8b0847396d146c@mail.gmail.com> <20061022012614.GA15729@ayn.mi.celestial.com> <384c93600610211912x503861cbx200c0a5f17736614@mail.gmail.com> <453B5722.6010201@tds.net> <5e58f2e40610231431n9b30c4doaeb551b19f1e9606@mail.gmail.com> Message-ID: <384c93600610241524g77a54986k842c28c17a385de9@mail.gmail.com> he he he On 10/23/06, John Fouhy wrote: > > On 23/10/06, Kent Johnson wrote: > > or for that matter > > return range(some_var:some_var+5) > > [nit-pick] > > That would be > range(some_var, some_var+5) > > :-) > > -- > John. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061024/ff56a7aa/attachment.html From anilmrn at yahoo.com Wed Oct 25 09:02:34 2006 From: anilmrn at yahoo.com (anil maran) Date: Wed, 25 Oct 2006 00:02:34 -0700 (PDT) Subject: [Tutor] http://www.google.com/coop/cse?cx=010104417661136834118%3Aat1-hsftvfo Message-ID: <20061025070234.92128.qmail@web55211.mail.re4.yahoo.com> http://www.google.com/coop/cse?cx=010104417661136834118%3Aat1-hsftvfo Anil __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From ajkadri at googlemail.com Wed Oct 25 11:16:58 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Wed, 25 Oct 2006 10:16:58 +0100 Subject: [Tutor] OOP and Python.. a gentle remark Message-ID: Folks... Please dont take it in a wrong sense. But I have a point to make regarding OOP and the way it is implemented in Python. Why is it necessary to explicity use self argument in the class functions ?? I feel the language/interpreter should figure out which object has called the function? Isnt it ? (the use of 'self' keyword really confuses me. and to make matter worse the variables can be accessed from outside teh class. Isnt it a violation of the OOP principle of ENCAPSULATION) Also please let me know hwo can we declare PRIVATE VARIABLES in Python...?? Regards, Asrarahmed P.S. : I love Python. :)- -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061025/a8b8f25c/attachment.html From simon at brunningonline.net Wed Oct 25 11:40:25 2006 From: simon at brunningonline.net (Simon Brunning) Date: Wed, 25 Oct 2006 10:40:25 +0100 Subject: [Tutor] OOP and Python.. a gentle remark In-Reply-To: References: Message-ID: <8c7f10c60610250240v3a08f03aj22133389855b4337@mail.gmail.com> On 10/25/06, Asrarahmed Kadri wrote: > Why is it necessary to explicity use self argument in the class functions > ?? I feel the language/interpreter should figure out which object has called > the function? Isnt it ? (the use of 'self' keyword really confuses me. and > to make matter worse the variables can be accessed from outside teh class. > Isnt it a violation of the OOP principle of ENCAPSULATION) > Also please let me know hwo can we declare PRIVATE VARIABLES in Python...?? -- Cheers, Simon B simon at brunningonline.net http://www.brunningonline.net/simon/blog/ From euoar at yahoo.es Wed Oct 25 11:46:10 2006 From: euoar at yahoo.es (euoar) Date: Wed, 25 Oct 2006 11:46:10 +0200 Subject: [Tutor] OOP and Python.. a gentle remark In-Reply-To: References: Message-ID: <453F3262.6070507@yahoo.es> Asrarahmed Kadri escribi?: > > > Folks... > > Please dont take it in a wrong sense. But I have a point to make > regarding OOP and the way it is implemented in Python. > > Why is it necessary to explicity use self argument in the class > functions ?? I feel the language/interpreter should figure out which > object has called the function? Isnt it ? (the use of 'self' keyword > really confuses me. and to make matter worse the variables can be > accessed from outside teh class. Isnt it a violation of the OOP > principle of ENCAPSULATION) > > Also please let me know hwo can we declare PRIVATE VARIABLES in > Python...?? > > Regards, > Asrarahmed > > P.S. : I love Python. :)- > > -- > To HIM you shall return. > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > That's something that I also don't understand, but I'm just a beginner in python, coming from java and C#, where this is not necessary. It seems to me quite annoying having to write this "self" each time, and I think it makes the code less readable. I have googled a little to see if there is an explanation to this particularity, with no sucess, so I will pay much attention to the answers here... ______________________________________________ LLama Gratis a cualquier PC del Mundo. Llamadas a fijos y m?viles desde 1 c?ntimo por minuto. http://es.voice.yahoo.com From project5 at redrival.net Wed Oct 25 13:13:32 2006 From: project5 at redrival.net (Andrei) Date: Wed, 25 Oct 2006 11:13:32 +0000 (UTC) Subject: [Tutor] OOP and Python.. a gentle remark References: Message-ID: Asrarahmed Kadri googlemail.com> writes: > the use of 'self' keyword really confuses me. I see how it can annoy you, but not how it can *confuse* you - if anything, "self" removes any confusion about whether you're looking at a local variable or an object property. By the way, the use of special identifiers is not uncommon in dynamic languages. Ruby for example uses the prefixes @, @@ and $ to define variable scope (which are not particularly self-explanatory - I think they're class, instance and global vars) and keywords (private, protected, public) to define method visibility. > and to make matter worse the variables can be accessed from outside teh class. > Isnt it a violation of the OOP principle of ENCAPSULATION) Python has conventions for this: prepend _ for protected and __ for private (private names get mangled). In an interactive session: >>> class a(object): ... def _protected(s): # don't *have* to use "self" :) ... print s ... def __private(s): ... print "private" >>> A = a() >>> A._protected() <__main__.a object at 0x00AF2E10> >>> A.__private() Traceback (most recent call last): File "", line 1, in ? AttributeError: 'a' object has no attribute '__private' Lets's examine what's happened: >>> dir(A) [, '_a__private', '_protected'] See, __private was mangled to _a__private. We can still access it of course: >>> A._a__private() private Python approaches the programmer as a responsible person: if I see a method name is mangled (or marked with _), I know I'm not supposed to use it - but can use it if I really need to (and suffer the consequences if the next version of the class breaks my code). Other languages choose the opposite approach: private is private, don't trust the programmer, tough luck if you really really need access to that private. Unfortunately you will invariably encounter cases when you need to access privates and these are major PITA's. Usually you can get your hands on the secret stuff, it's just very annoying and silly (e.g. by creating shadow classes or other workarounds). In the end it comes down to a choice between making some unavoidable cases very cumbersome to deal with, or trusting the programmer to do the right thing - thereby making it easier to stick his grubby little fingers in places where he shouldn't. Some people prefer the former, some the latter. Yours, Andrei From alan.gauld at btinternet.com Wed Oct 25 21:23:49 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 25 Oct 2006 20:23:49 +0100 Subject: [Tutor] OOP and Python.. a gentle remark References: Message-ID: "Asrarahmed Kadri" wrote > Why is it necessary to explicity use self argument in the class > functions Because Guido made it that way. :-) But he did it for good reasons which others have pointed out already. Although languages like C++ and Java use implicit object references, you can make them explicit with the 'this' keyword and most industrial coding standards mandate that 'this' be used when referencing class level variables inside methods. As in so many things Python simply takes best practice and makes it mandatory. > the function? Isnt it ? (the use of 'self' keyword really confuses > me. and If its the actual term 'self' then you can change it to anything you prefer. C++/Java programmers might prefer 'this', some others have used 'my': class C: def __init__(my, aValue): my.value = aValue is perfectly valid Python. > to make matter worse the variables can be accessed from outside teh > class. > Isnt it a violation of the OOP principle of ENCAPSULATION) The original OOP concept of encapsulation refers to the ability to bind functions and data together in a single unit - a class or object - and had nothing to do with data hiding which is the ability to conceal the implementation details behind an API. It was only after C++ came out with its gazillion access controls (public, private, protected, friend etc) that people started to confuse data hiding and encapsulation. Many early OOP languages (most Lisps included) do not offer explicit or strict data hiding. > Also please let me know hwo can we declare > PRIVATE VARIABLES in Python...?? Why do you think you need them? Do you frequently hit bugs because you couldn't resist the urge to access members directly? While there can be problems with badly behaved programmers on large projects, in the things Python is typically used for its very rarely a problem. And it can add significantly to the complexity of the code when you try to derive a class from one with private data. Very few designers are sufficiently ppsychic to predict exactly how all future users will want to modify their class! The result is they supply get/set methods for all data which are simply pass through methods. In doing so they completely annull any benefit of private members and introduce potential performance problems. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From pyro9219 at gmail.com Wed Oct 25 21:59:00 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Wed, 25 Oct 2006 12:59:00 -0700 Subject: [Tutor] OOP and Python.. a gentle remark In-Reply-To: References: Message-ID: I dont know about the rest of you, but this thread posting from Alan cleared up some fuzzyness I've had about classes. /me is happier using this. instead of self. =D Great post! On 10/25/06, Alan Gauld wrote: > > > "Asrarahmed Kadri" wrote > > Why is it necessary to explicity use self argument in the class > > functions > > Because Guido made it that way. :-) > But he did it for good reasons which others have pointed out already. > > Although languages like C++ and Java use implicit object references, > you can make them explicit with the 'this' keyword and most industrial > coding standards mandate that 'this' be used when referencing class > level variables inside methods. As in so many things Python simply > takes best practice and makes it mandatory. > > > the function? Isnt it ? (the use of 'self' keyword really confuses > > me. and > > If its the actual term 'self' then you can change it to anything > you prefer. C++/Java programmers might prefer 'this', some > others have used 'my': > > class C: > def __init__(my, aValue): > my.value = aValue > > is perfectly valid Python. > > > to make matter worse the variables can be accessed from outside teh > > class. > > Isnt it a violation of the OOP principle of ENCAPSULATION) > > The original OOP concept of encapsulation refers to the ability > to bind functions and data together in a single unit - a class or > object - and had nothing to do with data hiding which is the ability > to conceal the implementation details behind an API. > > It was only after C++ came out with its gazillion access > controls (public, private, protected, friend etc) that people started > to confuse data hiding and encapsulation. Many early OOP > languages (most Lisps included) do not offer explicit or strict > data hiding. > > > Also please let me know hwo can we declare > > PRIVATE VARIABLES in Python...?? > > Why do you think you need them? > Do you frequently hit bugs because you couldn't resist the > urge to access members directly? While there can be problems > with badly behaved programmers on large projects, in the > things Python is typically used for its very rarely a problem. > > And it can add significantly to the complexity of the code > when you try to derive a class from one with private data. > Very few designers are sufficiently ppsychic to predict > exactly how all future users will want to modify their class! > The result is they supply get/set methods for all data which > are simply pass through methods. In doing so they > completely annull any benefit of private members and > introduce potential performance problems. > > HTH, > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061025/f46a1054/attachment.html From ajkadri at googlemail.com Wed Oct 25 22:07:57 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Wed, 25 Oct 2006 21:07:57 +0100 Subject: [Tutor] OOP and Python.. a gentle remark In-Reply-To: References: Message-ID: Thanks a lot for explanation. Regards, Asrarahmed On 10/25/06, Alan Gauld wrote: > > > "Asrarahmed Kadri" wrote > > Why is it necessary to explicity use self argument in the class > > functions > > Because Guido made it that way. :-) > But he did it for good reasons which others have pointed out already. > > Although languages like C++ and Java use implicit object references, > you can make them explicit with the 'this' keyword and most industrial > coding standards mandate that 'this' be used when referencing class > level variables inside methods. As in so many things Python simply > takes best practice and makes it mandatory. > > > the function? Isnt it ? (the use of 'self' keyword really confuses > > me. and > > If its the actual term 'self' then you can change it to anything > you prefer. C++/Java programmers might prefer 'this', some > others have used 'my': > > class C: > def __init__(my, aValue): > my.value = aValue > > is perfectly valid Python. > > > to make matter worse the variables can be accessed from outside teh > > class. > > Isnt it a violation of the OOP principle of ENCAPSULATION) > > The original OOP concept of encapsulation refers to the ability > to bind functions and data together in a single unit - a class or > object - and had nothing to do with data hiding which is the ability > to conceal the implementation details behind an API. > > It was only after C++ came out with its gazillion access > controls (public, private, protected, friend etc) that people started > to confuse data hiding and encapsulation. Many early OOP > languages (most Lisps included) do not offer explicit or strict > data hiding. > > > Also please let me know hwo can we declare > > PRIVATE VARIABLES in Python...?? > > Why do you think you need them? > Do you frequently hit bugs because you couldn't resist the > urge to access members directly? While there can be problems > with badly behaved programmers on large projects, in the > things Python is typically used for its very rarely a problem. > > And it can add significantly to the complexity of the code > when you try to derive a class from one with private data. > Very few designers are sufficiently ppsychic to predict > exactly how all future users will want to modify their class! > The result is they supply get/set methods for all data which > are simply pass through methods. In doing so they > completely annull any benefit of private members and > introduce potential performance problems. > > HTH, > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061025/36179e59/attachment.htm From ajkadri at googlemail.com Wed Oct 25 22:11:03 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Wed, 25 Oct 2006 21:11:03 +0100 Subject: [Tutor] OOP and Python.. a gentle remark In-Reply-To: References: Message-ID: Chris, you are right. He (Alan) hits the bull's eye, always !! Cheers... Asrarahmed On 10/25/06, Chris Hengge wrote: > > I dont know about the rest of you, but this thread posting from Alan > cleared up some fuzzyness I've had about classes. /me is happier using this. > instead of self. =D > > Great post! > > On 10/25/06, Alan Gauld wrote: > > > > > > "Asrarahmed Kadri" wrote > > > Why is it necessary to explicity use self argument in the class > > > functions > > > > Because Guido made it that way. :-) > > But he did it for good reasons which others have pointed out already. > > > > Although languages like C++ and Java use implicit object references, > > you can make them explicit with the 'this' keyword and most industrial > > coding standards mandate that 'this' be used when referencing class > > level variables inside methods. As in so many things Python simply > > takes best practice and makes it mandatory. > > > > > the function? Isnt it ? (the use of 'self' keyword really confuses > > > me. and > > > > If its the actual term 'self' then you can change it to anything > > you prefer. C++/Java programmers might prefer 'this', some > > others have used 'my': > > > > class C: > > def __init__(my, aValue): > > my.value = aValue > > > > is perfectly valid Python. > > > > > to make matter worse the variables can be accessed from outside teh > > > class. > > > Isnt it a violation of the OOP principle of ENCAPSULATION) > > > > The original OOP concept of encapsulation refers to the ability > > to bind functions and data together in a single unit - a class or > > object - and had nothing to do with data hiding which is the ability > > to conceal the implementation details behind an API. > > > > It was only after C++ came out with its gazillion access > > controls (public, private, protected, friend etc) that people started > > to confuse data hiding and encapsulation. Many early OOP > > languages (most Lisps included) do not offer explicit or strict > > data hiding. > > > > > Also please let me know hwo can we declare > > > PRIVATE VARIABLES in Python...?? > > > > Why do you think you need them? > > Do you frequently hit bugs because you couldn't resist the > > urge to access members directly? While there can be problems > > with badly behaved programmers on large projects, in the > > things Python is typically used for its very rarely a problem. > > > > And it can add significantly to the complexity of the code > > when you try to derive a class from one with private data. > > Very few designers are sufficiently ppsychic to predict > > exactly how all future users will want to modify their class! > > The result is they supply get/set methods for all data which > > are simply pass through methods. In doing so they > > completely annull any benefit of private members and > > introduce potential performance problems. > > > > HTH, > > -- > > Alan Gauld > > Author of the Learn to Program web site > > http://www.freenetpages.co.uk/hp/alan.gauld > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061025/96b68eaa/attachment-0001.html From doug.shawhan at gmail.com Thu Oct 26 00:21:49 2006 From: doug.shawhan at gmail.com (doug shawhan) Date: Wed, 25 Oct 2006 17:21:49 -0500 Subject: [Tutor] Self, Scopes and my unbelievable muddleheadedness. Message-ID: <5e1ceb8a0610251521j5400adb5sd8e5cc5ddcb3872d@mail.gmail.com> I'm having a rather difficult time understanding the proper use of "self". I have two functions (yes, they are ugly, I was getting ready to split them in to smaller bits when this particular hole in my skull opened up) in a module. They use the same list of dictionaries to create some tables in a gadfly database. I know I could fix this in any number of ways (including, but not limited to, acting on the same input list twice, or acting on it in such a fashion in the first place), but I am trying to actually understand "self". Here's the horrid, horrid mess: class Create: def freshDB(self, DBPATH, Fields): self.Fields = Fields for field in self.Fields.keys(): columns = self.Fields[field] columns = columns.split(',') query = '' for each in columns: query = "%s, %s varchar"%(query,each) query = query[1:] query = "Create Table %s (%s)"%(field,query) self.Fields[field] = query connection = gadfly.gadfly() connection.startup("InventoryDB", DBPATH) cursor = connection.cursor() for field in self.Fields.keys(): cursor.execute(self.Fields[field]) connection.commit() for field in self.Fields.keys(): cursor.execute("Select * from %s"%field) print cursor.pp() connection.close() def comparisonTable(self, DBPATH, Fields, columns, mode): query = "" if mode == 'new': connection = gadfly.gadfly("InventoryDB",DBPATH) cursor = connection.cursor() try: cursor.execute("drop table comparison") except: print "No old table found." columns = Fields["Common"].split(',') for each in columns: query = "%s, %s varchar"%(query,each) query = query[1:] query = "Create Table comparison (%s)"%query cursor.execute(query) connection.commit() cursor.execute("select * from comparison") print cursor.pp() Now when I run freshDB from the other script: Fields = {"Common":"Inventory_Number, Stock_Number, Location, Year, Make, Model, Part_Type, Mileage, Description, Interchange_Data, Condition, Price", "EvilBay":"EvilBay_Title, EvilBay_Description", "HappyBase":"HappyBase_Description, HappyBase_Long_Description"} d = DBMod d.Create().freshDB(DBPATH, Fields) d.Create().comparisonTable(DBPATH, Fields, columns, "new") the resulting query is: Create Table comparison ( Inventory_Number varchar, Stock_Number varchar, Location varchar, Year varchar, Make varchar, Model varchar, Part_Type varchar, Mileage varchar, Description varchar, Interchange_Data varchar, Condition varchar, Price varchar) The query from comparisonTable gives me: Create Table comparison ( Create Table Common ( Inventory_Number varchar varchar, Stock_Number varchar varchar, Location varchar varchar, Year varchar varchar, Make varchar varchar, Model varchar varchar, Part_Type varchar varchar, Mileage varchar varchar, Description varchar varchar, Interchange_Data varchar varchar, Condition varchar varchar, Price varchar) varchar) If I restate the "Fields" input list before running comparisonTable, my results are as expected (i.e. exactly like the first query, exept the table is named "comparison"). I thought that when "self" was invoked for a function then that data was acted on only for the scope of that function, yet the data is changed in the original. Why? I'm sure this is so obvious that a crack-addled tapeworm head down in a bucket of stupid could understand it, unfortunately, I'm not quite at that level today. Sorry. Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061025/afe84c8c/attachment.html From wescpy at gmail.com Thu Oct 26 00:22:07 2006 From: wescpy at gmail.com (wesley chun) Date: Wed, 25 Oct 2006 15:22:07 -0700 Subject: [Tutor] OOP and Python.. a gentle remark In-Reply-To: References: Message-ID: <78b3a9580610251522n5c8154edh4997c9615d846ea7@mail.gmail.com> on a related topic, if you're concerned about security, esp. of your instance attributes, new-style classes offer you significantly more control over them using descriptors (including properties [and to a lesser extent, slots]). there is plenty of docs available on those, so i'll defer describing them here. good luck! -wesley From rabidpoobear at gmail.com Thu Oct 26 00:29:50 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 25 Oct 2006 17:29:50 -0500 Subject: [Tutor] Self, Scopes and my unbelievable muddleheadedness. In-Reply-To: <5e1ceb8a0610251521j5400adb5sd8e5cc5ddcb3872d@mail.gmail.com> References: <5e1ceb8a0610251521j5400adb5sd8e5cc5ddcb3872d@mail.gmail.com> Message-ID: <453FE55E.8010608@gmail.com> > > I'm sure this is so obvious that a crack-addled tapeworm head down in > a bucket of stupid could understand it, unfortunately, I'm not quite > at that level today. Sorry. Uh, I don't understand why you're passing Fields to the functions but then putting the value in self.Fields... but we'll ignore that for now :) The problem it sounds like you're having is that you think that passing lists to functions copies them, when in fact it just creates a reference to them. Take this, for example: >>> def append_five(alist): alist.append(5) >>> a = [1,2,3,4] >>> append_five(a) >>> a [1, 2, 3, 4, 5] >>> append_five(a) >>> a [1, 2, 3, 4, 5, 5] Other than that, Maybe you think self is used for something other than what it's intended to be used for... but I can't be sure. I'm sure someone else can give you a good example. I, however, have to run. HTH, -Luke From john at fouhy.net Thu Oct 26 00:53:19 2006 From: john at fouhy.net (John Fouhy) Date: Thu, 26 Oct 2006 11:53:19 +1300 Subject: [Tutor] Self, Scopes and my unbelievable muddleheadedness. In-Reply-To: <5e1ceb8a0610251521j5400adb5sd8e5cc5ddcb3872d@mail.gmail.com> References: <5e1ceb8a0610251521j5400adb5sd8e5cc5ddcb3872d@mail.gmail.com> Message-ID: <5e58f2e40610251553gd86399cm31739ce736848e5b@mail.gmail.com> On 26/10/06, doug shawhan wrote: > class Create: > def freshDB(self, DBPATH, Fields): > # ... > def comparisonTable(self, DBPATH, Fields, columns, mode): > # ... > Now when I run freshDB from the other script: > > Fields = {"Common":"Inventory_Number, Stock_Number, Location, Year, Make, > Model, Part_Type, Mileage, Description, Interchange_Data, Condition, Price", > "EvilBay":"EvilBay_Title, EvilBay_Description", > "HappyBase":"HappyBase_Description, > HappyBase_Long_Description"} > > d = DBMod > > d.Create().freshDB(DBPATH, Fields) > > d.Create().comparisonTable(DBPATH, Fields, columns, "new") What is the purpose of your Create class? It seems to me that you are not actually doing anything object-oriented here. So maybe you're confused about 'self' because you've got no object orientation? I think you've got a couple of ways forward. You could abandon your class, and just put the functions directly into a module; ie: ###### creategadfly.py ####### def freshDB(dbpath, fields): # etc def comparisonTable(dbpath, fields, columns, mode): # etc ###### and then, in your code, you would do: import creategadfly creategadfly.freshDB(DBPATH, Fields) creategadfly.comparisonTable(DBPATH, Fields, columns, "new") Alternatively, you could restructure your code to make it OO. Something like this: ###### class GadflyConnection(object): def __init__(self, dbpath, dbname, fields): self.createDB(dbpath, dbname, fields) def createDB(self, dbpath, dbname, fields): self.db = gadfly.gadfly() self.db.startup(dbname, dbpath) # etc def comparisonTable(self, mode): if mode == 'new': # insert code to create 'query' cursor = self.db.cursor() cursor.execute(query) cursor.close() Maybe you would want a call to self.comparisonTable inside __init__? Then to use: gadflyDB = GadflyConnection(...) I'm not sure what you want to do with your database, so I can't really give you a bigger use example. But do you see what is going on? In createDB(), you create a new gadfly connection, and then assign it to 'self.db'. Then, in comparisonTable, you can reference self.db to access that connection. Hope this helps. -- John. From jgcox39 at highstream.net Thu Oct 26 04:03:59 2006 From: jgcox39 at highstream.net (Joe Cox) Date: Wed, 25 Oct 2006 19:03:59 -0700 Subject: [Tutor] Decimal truncation, rounding etc. Message-ID: My next project is to read a doc file and do some number editing. I can alter numbers in the Interactive Shell OK: import math print round(7.12345,4) 7.1234 from decimal import* Decimal('7.00000').quantize(Decimal('1.000'),rounding = decimal.ROUND_DOWN) Decimal("7.0000") But when I go in to IDLE, I just don't seem to be able to make this work. A typical line of code for me to read and edit will look like: G01 G91 X7.12345 Y7.0000 Z-0.0086 The underlines is what I need to edit, as above. I must not understand something fundamental. Joe Cox 513-293-4830 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061025/5eb771ef/attachment.html From rabidpoobear at gmail.com Thu Oct 26 01:16:38 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 25 Oct 2006 18:16:38 -0500 Subject: [Tutor] Decimal truncation, rounding etc. In-Reply-To: References: Message-ID: <453FF056.10806@gmail.com> Joe Cox wrote: > My next project is to read a doc file and do some number editing. > I can alter numbers in the Interactive Shell OK: > > import math > print round(7.12345,4) > 7.1234 > > from decimal import* > Decimal('7.00000').quantize(Decimal('1.000'),rounding = > decimal.ROUND_DOWN) > Decimal("7.0000") > > But when I go in to IDLE, I just don't seem to be able to make this work. > What have you tried? > A typical line of code for me to read and edit will look like: > G01 G91 X_7.12345_ Y_7.0000_ Z-0.0086 > The underlines is what I need to edit, as above. Okay, and what does it look like when you input these values? Are you storing them in Decimal instances, or floats, or what? What exactly is it that doesn't work? From jason.massey at gmail.com Thu Oct 26 01:25:13 2006 From: jason.massey at gmail.com (Jason Massey) Date: Wed, 25 Oct 2006 18:25:13 -0500 Subject: [Tutor] Decimal truncation, rounding etc. In-Reply-To: References: Message-ID: <7e3eab2c0610251625v4a8482abn6b60cb573a1df837@mail.gmail.com> More specifically, Joe, where and what types of errors are you getting? When I type in your example exactly as above I get the following: >>>from decimal import * >>> Decimal('7.0000').quantize(Decimal('1.000'),rounding=decimal.ROUND_DOWN) Traceback (most recent call last): File "", line 1, in ? NameError: name 'decimal' is not defined That error appears because you've imported all of the decimal functions into the global namespace and you're trying to reference a value in the decimal namespace. In your example it'd have to look like this to work: >>>Decimal('7.0000').quantize(Decimal('1.000'),rounding=ROUND_DOWN) #note the lack of decimal in front of ROUND_DOWN Decimal("7.000") Or is the problem that you're not able to read and parse the text file properly? On 10/25/06, Joe Cox wrote: > > My next project is to read a doc file and do some number editing. > I can alter numbers in the Interactive Shell OK: > > import math > print round(7.12345,4) > 7.1234 > > from decimal import* > Decimal('7.00000').quantize(Decimal('1.000'),rounding = decimal.ROUND_DOWN > ) > Decimal("7.0000") > > But when I go in to IDLE, I just don't seem to be able to make this work. > > A typical line of code for me to read and edit will look like: > G01 G91 X*7.12345* Y*7.0000* Z-0.0086 > The underlines is what I need to edit, as above. > > I must not understand something fundamental. > > > Joe Cox > 513-293-4830 > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061025/f0ba53b1/attachment.htm From jgcox39 at highstream.net Thu Oct 26 04:43:01 2006 From: jgcox39 at highstream.net (Joe Cox) Date: Wed, 25 Oct 2006 19:43:01 -0700 Subject: [Tutor] Decimal truncation, rounding etc. In-Reply-To: <7e3eab2c0610251625v4a8482abn6b60cb573a1df837@mail.gmail.com> Message-ID: Yes, I made a typo in the quantize. You are correct I am not able to read and parse the text file properly? I just face that IDE screen and it's all white. I am lost. -----Original Message----- From: Jason Massey [mailto:jason.massey at gmail.com] Sent: Wednesday, October 25, 2006 4:25 PM To: jgcox39 at highstream.net Cc: tutor Subject: Re: [Tutor] Decimal truncation, rounding etc. More specifically, Joe, where and what types of errors are you getting? When I type in your example exactly as above I get the following: >>>from decimal import * >>> Decimal('7.0000').quantize(Decimal('1.000'),rounding=decimal.ROUND_DOWN) Traceback (most recent call last): File "", line 1, in ? NameError: name 'decimal' is not defined That error appears because you've imported all of the decimal functions into the global namespace and you're trying to reference a value in the decimal namespace. In your example it'd have to look like this to work: >>>Decimal('7.0000').quantize(Decimal('1.000'),rounding=ROUND_DOWN) #note the lack of decimal in front of ROUND_DOWN Decimal("7.000") Or is the problem that you're not able to read and parse the text file properly? On 10/25/06, Joe Cox wrote: My next project is to read a doc file and do some number editing. I can alter numbers in the Interactive Shell OK: import math print round(7.12345,4) 7.1234 from decimal import* Decimal('7.00000').quantize(Decimal('1.000'),rounding = decimal.ROUND_DOWN) Decimal("7.0000") But when I go in to IDLE, I just don't seem to be able to make this work. A typical line of code for me to read and edit will look like: G01 G91 X7.12345 Y7.0000 Z-0.0086 The underlines is what I need to edit, as above. I must not understand something fundamental. Joe Cox 513-293-4830 _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061025/0772c7b2/attachment.html From jazedo at netcabo.pt Thu Oct 26 02:53:14 2006 From: jazedo at netcabo.pt (Jorge Azedo) Date: Thu, 26 Oct 2006 01:53:14 +0100 Subject: [Tutor] New to programming and Python Message-ID: <454006FA.4000600@netcabo.pt> Hi guys ( and gals ) I'm totally new to the whole programming scene (I decided to enter it for many reasons, one of which is the fact that I *want* to know how to program my computer) and I decided to start out with Python. I'm reading lots of tutorials on it, trying to understand how to work with it, but for some reason or another, it all seems a great mess to me. Am I doing something wrong? Also, can anyone give me any pointers on how to start working with Python? Thanks in advance for any help you can give me - Jorge From hokkakada at khmeros.info Thu Oct 26 03:20:06 2006 From: hokkakada at khmeros.info (hok kakada) Date: Thu, 26 Oct 2006 08:20:06 +0700 Subject: [Tutor] python2vb.net Message-ID: <200610260820.06561.hokkakada@khmeros.info> Dear All, A friend of mine is well programming in vb.net and C#. He got a python sourcecode of KhmerConverter tool. He would like to port to either vn.net or C#. Are there any tools to do this? Thanks, da From pyro9219 at gmail.com Thu Oct 26 09:04:30 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Thu, 26 Oct 2006 00:04:30 -0700 Subject: [Tutor] New to programming and Python In-Reply-To: <454006FA.4000600@netcabo.pt> References: <454006FA.4000600@netcabo.pt> Message-ID: I'm sure I speak for us all when I ask what sort of things are giving you problems? Maybe that would help us point you in the right direction. Good Luck! On 10/25/06, Jorge Azedo wrote: > > Hi guys ( and gals ) > > I'm totally new to the whole programming scene (I decided to enter it > for many reasons, one of which is the fact that I *want* to know how to > program my computer) and I decided to start out with Python. I'm reading > lots of tutorials on it, trying to understand how to work with it, but > for some reason or another, it all seems a great mess to me. Am I doing > something wrong? Also, can anyone give me any pointers on how to start > working with Python? > > Thanks in advance for any help you can give me > - Jorge > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061026/3fbd1bd8/attachment.htm From alan.gauld at btinternet.com Thu Oct 26 09:55:23 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 26 Oct 2006 08:55:23 +0100 Subject: [Tutor] Self, Scopes and my unbelievable muddleheadedness. References: <5e1ceb8a0610251521j5400adb5sd8e5cc5ddcb3872d@mail.gmail.com> Message-ID: "doug shawhan" wrote > I'm having a rather difficult time understanding the proper use of > "self". Doug, I think you may be having a more fundamental problem. Looking at your code at the most superficial level it seems you may not understand objects. Classes are used to generate objects. Objects represent things. By logical deduction objects correspond to nouns in language. Objects do things when they receive messages (Possibly from other objects). Messages cause methods to be invoked, methods therefore correspond to verbs in language. Looking at your code we find: class Create: # a verb def freshDB(self, DBPATH, Fields): # a noun def comparisonTable(self, DBPATH, Fields, columns, mode): #a noun In other words you have the concept inside out. you are trying to create Create objects and call Table and Database methods. It doesn't make sense. Normally we would expect to see DB and Table objects to which you send create messages. Now if you think of the objects as verbs then self is a confusing concept. But if you think of the objects as nouns then self is simply a reference to the object instance in question, a particular database or table. I'd recommend going back and rethinking the design of your objects before going much further. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld > > I have two functions (yes, they are ugly, I was getting ready to > split them > in to smaller bits when this particular hole in my skull opened up) > in a > module. They use the same list of dictionaries to create some tables > in a > gadfly database. > > I know I could fix this in any number of ways (including, but not > limited > to, acting on the same input list twice, or acting on it in such a > fashion > in the first place), but I am trying to actually understand "self". > > Here's the horrid, horrid mess: > > class Create: > def freshDB(self, DBPATH, Fields): > self.Fields = Fields > for field in self.Fields.keys(): > columns = self.Fields[field] > columns = columns.split(',') > query = '' > for each in columns: > query = "%s, %s varchar"%(query,each) > query = query[1:] > query = "Create Table %s (%s)"%(field,query) > self.Fields[field] = query > > connection = gadfly.gadfly() > connection.startup("InventoryDB", DBPATH) > cursor = connection.cursor() > > for field in self.Fields.keys(): > cursor.execute(self.Fields[field]) > connection.commit() > > for field in self.Fields.keys(): > cursor.execute("Select * from %s"%field) > print cursor.pp() > connection.close() > > def comparisonTable(self, DBPATH, Fields, columns, mode): > query = "" > if mode == 'new': > connection = gadfly.gadfly("InventoryDB",DBPATH) > cursor = connection.cursor() > try: > cursor.execute("drop table comparison") > except: > print "No old table found." > columns = Fields["Common"].split(',') > > for each in columns: > query = "%s, %s varchar"%(query,each) > query = query[1:] > query = "Create Table comparison (%s)"%query > cursor.execute(query) > connection.commit() > cursor.execute("select * from comparison") > print cursor.pp() > > Now when I run freshDB from the other script: > > Fields = {"Common":"Inventory_Number, Stock_Number, Location, Year, > Make, > Model, Part_Type, Mileage, Description, Interchange_Data, Condition, > Price", > "EvilBay":"EvilBay_Title, EvilBay_Description", > "HappyBase":"HappyBase_Description, HappyBase_Long_Description"} > > d = DBMod > > d.Create().freshDB(DBPATH, Fields) > > d.Create().comparisonTable(DBPATH, Fields, columns, "new") > > > the resulting query is: > > Create Table comparison ( Inventory_Number varchar, Stock_Number > varchar, > Location varchar, Year varchar, Make varchar, Model varchar, > Part_Type > varchar, Mileage varchar, Description varchar, Interchange_Data > varchar, > Condition varchar, Price varchar) > > The query from comparisonTable gives me: > Create Table comparison ( Create Table Common ( Inventory_Number > varchar > varchar, Stock_Number varchar varchar, Location varchar varchar, > Year > varchar varchar, Make varchar varchar, Model varchar varchar, > Part_Type varchar varchar, Mileage varchar varchar, Description > varchar > varchar, Interchange_Data varchar varchar, Condition varchar > varchar, > Price varchar) varchar) > > If I restate the "Fields" input list before running comparisonTable, > my > results are as expected (i.e. exactly like the first query, exept > the table > is named "comparison"). > > I thought that when "self" was invoked for a function then that data > was > acted on only for the scope of that function, yet the data is > changed in the > original. Why? > > I'm sure this is so obvious that a crack-addled tapeworm head down > in a > bucket of stupid could understand it, unfortunately, I'm not quite > at that > level today. Sorry. > > Thanks! > -------------------------------------------------------------------------------- > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Thu Oct 26 10:00:28 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 26 Oct 2006 09:00:28 +0100 Subject: [Tutor] Decimal truncation, rounding etc. References: Message-ID: "Joe Cox" wrote > A typical line of code for me to read and edit will look like: > G01 G91 X7.12345 Y7.0000 Z-0.0086 > The underlines is what I need to edit, as above. What underlines? email and news readers do not necessarily support rich text formatting. Do not assume that colour, bold highlighting etc will survive when posting email or news items. There are a set of conventions used to indicate *highlighted* text and _undelined_ text in ascii messages, its safer to use them. Alan G. (Who always displays in plain text as God intended:-) From finalyugi at sapo.pt Thu Oct 26 10:44:41 2006 From: finalyugi at sapo.pt (rolando) Date: Thu, 26 Oct 2006 09:44:41 +0100 Subject: [Tutor] New to programming and Python In-Reply-To: <454006FA.4000600@netcabo.pt> References: <454006FA.4000600@netcabo.pt> Message-ID: <45407579.3060801@sapo.pt> Jorge Azedo escreveu: > Hi guys ( and gals ) > > I'm totally new to the whole programming scene (I decided to enter it > for many reasons, one of which is the fact that I *want* to know how to > program my computer) and I decided to start out with Python. I'm reading > lots of tutorials on it, trying to understand how to work with it, but > for some reason or another, it all seems a great mess to me. Am I doing > something wrong? Also, can anyone give me any pointers on how to start > working with Python? > > Thanks in advance for any help you can give me > - Jorge > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > Well, I?m also kind of new to the scene, so I still don?t know much. But you can try this book that I?ve been reading: Dive Into Python: http://www.diveintopython.org/ (you can download the PDF from there, which I belive has already a group of exemples to see when using the book). Also I?ve been reading the Python Wikibook that you can download from here: http://en.wikibooks.org/wiki/Python (it still has a few parts missing but it can give you a few pointers). (The part below problaby won?t make sense except if you are portuguese) I don?t know what type of Netcabo you have, if you want I can upload the pdf to a national host to count national traffic :) From kent37 at tds.net Thu Oct 26 12:04:27 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 26 Oct 2006 06:04:27 -0400 Subject: [Tutor] New to programming and Python In-Reply-To: <454006FA.4000600@netcabo.pt> References: <454006FA.4000600@netcabo.pt> Message-ID: <4540882B.7030505@tds.net> Jorge Azedo wrote: > Hi guys ( and gals ) > > I'm totally new to the whole programming scene (I decided to enter it > for many reasons, one of which is the fact that I *want* to know how to > program my computer) and I decided to start out with Python. I'm reading > lots of tutorials on it, trying to understand how to work with it, but > for some reason or another, it all seems a great mess to me. Am I doing > something wrong? Also, can anyone give me any pointers on how to start > working with Python? You don't say which tutorials you are reading; make sure it is a beginners tutorial. There are several listed here: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers Spend as much time trying things out as you do reading. Read a little, then start up the Python interpreter and type in the examples from the tutorial. Change them a little bit. Experiment. Don't go on in the reading until you are comfortable using what you have learned so far. You have to write, you can't learn to program just by reading. Ask questions here if you get stuck. Show us what you tried, what happened, and what you expected to happen. Kent From paulino1 at sapo.pt Thu Oct 26 12:22:56 2006 From: paulino1 at sapo.pt (paulino1 at sapo.pt) Date: Thu, 26 Oct 2006 11:22:56 +0100 Subject: [Tutor] New to programming and Python (Jorge Azedo) In-Reply-To: References: Message-ID: <1161858176.6zx2e6t26mbk@w12.mail.sapo.pt> Parece que ja temos elementos para estabelecer uma comunidade portuguesa de Python ;-) Jorge, Sugiro os tutoriais do site www.devshed.com. s?o simples e explicam bem o significado do codigo! Tb sou novo na programa??o, tenho ai 6 meses de Python. A Caixa Magica promove cursos de Python em Lisboa, este ano houve ja 2 de 3 dias, penso que em Fevereiro e Junho. For?a, isto no inicio parece confuso, mas breve faz-se luz! Paulino Citando tutor-request at python.org: >> 2. New to programming and Python (Jorge Azedo) > 7. Re: New to programming and Python (rolando) > > > Date: Thu, 26 Oct 2006 09:44:41 +0100 > From: rolando > Subject: Re: [Tutor] New to programming and Python > To: tutor at python.org > Message-ID: <45407579.3060801 at sapo.pt> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Jorge Azedo escreveu: > > Hi guys ( and gals ) > > > > I'm totally new to the whole programming scene (I decided to enter it > > for many reasons, one of which is the fact that I *want* to know how to > > program my computer) and I decided to start out with Python. I'm reading > > lots of tutorials on it, trying to understand how to work with it, but > > for some reason or another, it all seems a great mess to me. Am I doing > > something wrong? Also, can anyone give me any pointers on how to start > > working with Python? > > > > Thanks in advance for any help you can give me > > - Jorge > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > Well, I?m also kind of new to the scene, so I still don?t know much. > > But you can try this book that I?ve been reading: > Dive Into Python: > http://www.diveintopython.org/ (you can download the PDF from there, > which I belive has already a group of exemples to see when using the book). > > Also I?ve been reading the Python Wikibook that you can download from here: > http://en.wikibooks.org/wiki/Python (it still has a few parts missing > but it can give you a few pointers). > > > (The part below problaby won?t make sense except if you are portuguese) > > I don?t know what type of Netcabo you have, if you want I can upload the > pdf to a national host to count national traffic :) > > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > End of Tutor Digest, Vol 32, Issue 110 > ************************************** > From paulino1 at sapo.pt Thu Oct 26 12:32:29 2006 From: paulino1 at sapo.pt (paulino1 at sapo.pt) Date: Thu, 26 Oct 2006 11:32:29 +0100 Subject: [Tutor] cgi form field and popup window Message-ID: <1161858749.4zaxot5go41s@w12.mail.sapo.pt> I would like to have a popup window to show the possible options to a form field (supplier ID) and that by clicking on the desired item, the field is automatically filled. The options are a database field values. I wonder if this is possible to do with python (point me some resources please), or have I to deal with javascript ? Many thanks, Paulino From finalyugi at sapo.pt Thu Oct 26 13:12:29 2006 From: finalyugi at sapo.pt (rolando) Date: Thu, 26 Oct 2006 12:12:29 +0100 Subject: [Tutor] New to programming and Python (Jorge Azedo) In-Reply-To: <1161858176.6zx2e6t26mbk@w12.mail.sapo.pt> References: <1161858176.6zx2e6t26mbk@w12.mail.sapo.pt> Message-ID: <4540981D.2030303@sapo.pt> I tought that we could only speak English in here :D Also I'm newer to python, about a mounth and a half since I started studing it. paulino1 at sapo.pt escreveu: > Parece que ja temos elementos para estabelecer uma comunidade portuguesa de > Python ;-) > > Jorge, > > Sugiro os tutoriais do site www.devshed.com. s?o simples e explicam bem o > significado do codigo! > > Tb sou novo na programa??o, tenho ai 6 meses de Python. > > A Caixa Magica promove cursos de Python em Lisboa, este ano houve ja 2 de 3 > dias, penso que em Fevereiro e Junho. > > For?a, isto no inicio parece confuso, mas breve faz-se luz! > > Paulino > > > Citando tutor-request at python.org: > > >>> 2. New to programming and Python (Jorge Azedo) >>> >> 7. Re: New to programming and Python (rolando) >> >> >> Date: Thu, 26 Oct 2006 09:44:41 +0100 >> From: rolando >> Subject: Re: [Tutor] New to programming and Python >> To: tutor at python.org >> Message-ID: <45407579.3060801 at sapo.pt> >> Content-Type: text/plain; charset=ISO-8859-1; format=flowed >> >> Jorge Azedo escreveu: >> >>> Hi guys ( and gals ) >>> >>> I'm totally new to the whole programming scene (I decided to enter it >>> for many reasons, one of which is the fact that I *want* to know how to >>> program my computer) and I decided to start out with Python. I'm reading >>> lots of tutorials on it, trying to understand how to work with it, but >>> for some reason or another, it all seems a great mess to me. Am I doing >>> something wrong? Also, can anyone give me any pointers on how to start >>> working with Python? >>> >>> Thanks in advance for any help you can give me >>> - Jorge >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> http://mail.python.org/mailman/listinfo/tutor >>> >>> >>> >>> >> Well, I?m also kind of new to the scene, so I still don?t know much. >> >> But you can try this book that I?ve been reading: >> Dive Into Python: >> http://www.diveintopython.org/ (you can download the PDF from there, >> which I belive has already a group of exemples to see when using the book). >> >> Also I?ve been reading the Python Wikibook that you can download from here: >> http://en.wikibooks.org/wiki/Python (it still has a few parts missing >> but it can give you a few pointers). >> >> >> (The part below problaby won?t make sense except if you are portuguese) >> >> I don?t know what type of Netcabo you have, if you want I can upload the >> pdf to a national host to count national traffic :) >> >> >> ------------------------------ >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> >> End of Tutor Digest, Vol 32, Issue 110 >> ************************************** >> >> > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From kent37 at tds.net Thu Oct 26 13:38:58 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 26 Oct 2006 07:38:58 -0400 Subject: [Tutor] New to programming and Python (Jorge Azedo) In-Reply-To: <4540981D.2030303@sapo.pt> References: <1161858176.6zx2e6t26mbk@w12.mail.sapo.pt> <4540981D.2030303@sapo.pt> Message-ID: <45409E52.5080602@tds.net> rolando wrote: > I tought that we could only speak English in here :D English is preferred and increases your chances of getting an answer :-) Kent > > Also I'm newer to python, about a mounth and a half since I started > studing it. > > paulino1 at sapo.pt escreveu: >> Parece que ja temos elementos para estabelecer uma comunidade portuguesa de >> Python ;-) >> >> Jorge, >> >> Sugiro os tutoriais do site www.devshed.com. s?o simples e explicam bem o >> significado do codigo! >> >> Tb sou novo na programa??o, tenho ai 6 meses de Python. >> >> A Caixa Magica promove cursos de Python em Lisboa, este ano houve ja 2 de 3 >> dias, penso que em Fevereiro e Junho. >> >> For?a, isto no inicio parece confuso, mas breve faz-se luz! >> >> Paulino >> >> >> Citando tutor-request at python.org: >> >> >>>> 2. New to programming and Python (Jorge Azedo) >>>> >>> 7. Re: New to programming and Python (rolando) >>> >>> >>> Date: Thu, 26 Oct 2006 09:44:41 +0100 >>> From: rolando >>> Subject: Re: [Tutor] New to programming and Python >>> To: tutor at python.org >>> Message-ID: <45407579.3060801 at sapo.pt> >>> Content-Type: text/plain; charset=ISO-8859-1; format=flowed >>> >>> Jorge Azedo escreveu: >>> >>>> Hi guys ( and gals ) >>>> >>>> I'm totally new to the whole programming scene (I decided to enter it >>>> for many reasons, one of which is the fact that I *want* to know how to >>>> program my computer) and I decided to start out with Python. I'm reading >>>> lots of tutorials on it, trying to understand how to work with it, but >>>> for some reason or another, it all seems a great mess to me. Am I doing >>>> something wrong? Also, can anyone give me any pointers on how to start >>>> working with Python? >>>> >>>> Thanks in advance for any help you can give me >>>> - Jorge >>>> _______________________________________________ >>>> Tutor maillist - Tutor at python.org >>>> http://mail.python.org/mailman/listinfo/tutor >>>> >>>> >>>> >>>> >>> Well, I?m also kind of new to the scene, so I still don?t know much. >>> >>> But you can try this book that I?ve been reading: >>> Dive Into Python: >>> http://www.diveintopython.org/ (you can download the PDF from there, >>> which I belive has already a group of exemples to see when using the book). >>> >>> Also I?ve been reading the Python Wikibook that you can download from here: >>> http://en.wikibooks.org/wiki/Python (it still has a few parts missing >>> but it can give you a few pointers). >>> >>> >>> (The part below problaby won?t make sense except if you are portuguese) >>> >>> I don?t know what type of Netcabo you have, if you want I can upload the >>> pdf to a national host to count national traffic :) >>> >>> >>> ------------------------------ >>> >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> http://mail.python.org/mailman/listinfo/tutor >>> >>> >>> End of Tutor Digest, Vol 32, Issue 110 >>> ************************************** >>> >>> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> >> > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From kent37 at tds.net Thu Oct 26 13:46:14 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 26 Oct 2006 07:46:14 -0400 Subject: [Tutor] cgi form field and popup window In-Reply-To: <1161858749.4zaxot5go41s@w12.mail.sapo.pt> References: <1161858749.4zaxot5go41s@w12.mail.sapo.pt> Message-ID: <4540A006.1040201@tds.net> paulino1 at sapo.pt wrote: > I would like to have a popup window to show the possible options to a form field > (supplier ID) and that by clicking on the desired item, the field is > automatically filled. The options are a database field values. > > I wonder if this is possible to do with python (point me some resources please), > or have I to deal with javascript ? The browser-side programming has to be in javascript. The server-side program that sends the javascript and the list of options to the browser can be in Python. You might want to look at the TurboGears widget set which provides many browser-side widgets that are configured from Python. Widgets are part of TG 1.0. Unfortunately the docs seem to be a bit thin and sorting it all out is probably not a beginner project. http://www.turbogears.org/ http://tgwidgets.toscat.net/ Kent From ajkadri at googlemail.com Thu Oct 26 14:31:37 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Thu, 26 Oct 2006 13:31:37 +0100 Subject: [Tutor] Help me.. problem in building calculator application Message-ID: Hi folks, I am trying to build a rudimentary calculator application using Tkinter... I have used one Entry widget for displaying the input and output data. All this is put in a class. The porblem is when I click teh '+' button, teh callback function is called but it gives me an error message: AttributeError: 'str' object has no attribute 'get' I have defined a variable, self.str1 = StringVar() to bind it with the entry widget and I am calling the function when + is clciked. The function is as follows: self.buttonPlu = Button(self.container3,text='+',command = lambda: self.oprClick('+',*self.str1.get()))* Can't we use the get() method to access the contents of the entry widget. Is there any other way to access the contents of the entry widget....??? Thanks in anticipation. Regards, Asrar -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061026/7e90f0dd/attachment.html From bashu at yandex.ru Thu Oct 26 14:47:14 2006 From: bashu at yandex.ru (Basil Shubin) Date: Thu, 26 Oct 2006 19:47:14 +0700 Subject: [Tutor] Python and config files? Message-ID: <4540AE52.7010307@yandex.ru> Hi, friends! Is there exist a module for working with config file? Simple enough, just read/write config file (like for most unix app), determine where row is contain config words with it's parameters (like 'config_word=parameter') or it's a comments (#)? -- Basil Shubin Freelance Software Developer From kent37 at tds.net Thu Oct 26 15:21:47 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 26 Oct 2006 09:21:47 -0400 Subject: [Tutor] Help me.. problem in building calculator application In-Reply-To: References: Message-ID: <4540B66B.8060705@tds.net> Asrarahmed Kadri wrote: > > > Hi folks, > > I am trying to build a rudimentary calculator application using Tkinter... > > I have used one Entry widget for displaying the input and output data. > All this is put in a class. > The porblem is when I click teh '+' button, teh callback function is > called but it gives me an error message: AttributeError: 'str' object > has no attribute 'get' > > I have defined a variable, self.str1 = StringVar() to bind it with the > entry widget and I am calling the function when + is clciked. The > function is as follows: > > self.buttonPlu = Button(self.container3,text='+',command = lambda: > self.oprClick('+',*self.str1.get()))* > > Can't we use the get() method to access the contents of the entry > widget. Is there any other way to access the contents of the entry > widget....??? The error message is saying that the object you are calling get() on is a string, not a StringVar. Please post complete code and the complete error message including traceback. Kent From kent37 at tds.net Thu Oct 26 15:24:16 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 26 Oct 2006 09:24:16 -0400 Subject: [Tutor] Python and config files? In-Reply-To: <4540AE52.7010307@yandex.ru> References: <4540AE52.7010307@yandex.ru> Message-ID: <4540B700.8070109@tds.net> Basil Shubin wrote: > Hi, friends! > > Is there exist a module for working with config file? Simple enough, > just read/write config file (like for most unix app), determine where > row is contain config words with it's parameters (like > 'config_word=parameter') or it's a comments (#)? Take a look at the ConfigParser module: http://docs.python.org/lib/module-ConfigParser.html Kent From ajkadri at googlemail.com Thu Oct 26 15:37:35 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Thu, 26 Oct 2006 14:37:35 +0100 Subject: [Tutor] Code with traceback...Re: Help me.. problem in building calculator application Message-ID: Traceback is as under: Traceback (most recent call last): File "C:\python\lib\lib-tk\Tkinter.py", line 1345, in __call__ return self.func(*args) File "calculator_version2.py", line 105, in self.buttonPlu = Button(self.container3,text='+',command = lambda: self.oprC lick('+',self.str1.get())) AttributeError: 'str' object has no attribute 'get' from Tkinter import * import string class Mycalc: def buttonClick(self,str2,str3): if str2 == ".": if self.dotFlag: pass else: self.dotFlag = True self.operand = str3 + str2 else: self.operand = str3 + str2 def oprClick(self,str11,oprt): self.dotFlag = False if oprt == "+": if self.result == "0": self.result = str11 else: self.result = string.atof(self.result) + string.atof(str11) elif oprt == "-": if self.result == "0": self.result = str11 else: self.result = string.atof(self.result) - string.atof(str11) elif str2 == "*": if self.result == "0": self.result = str11 else: self.result = string.atof(self.result) * string.atof(str11) elif str2 == "/": if self.result == "0": self.result = str11 else: self.result = string.atof(self.result) / string.atof(str11) self.entryWidget.icursor(0) self.entryWidget.delete(0,END) self.entryWidget.insert(INSERT,self.result) def __init__(self,master): self.container1 = Frame(master,width=200,height=200,background='brown') self.container1.pack() self.str1 = StringVar() self.str1 = "0" self.entryWidget = Entry(self.container1,textvariable=self.str1) self.entryWidget.pack(side=TOP) self.container2 = Frame(master,background='cyan') self.container2.pack() self.container3 = Frame(master,background='grey') self.container3.pack() self.operand = "0" self.result = "0" self.dotFlag = False def make_buttons(self): self.buttonOne = Button(self.container2,text='1') self.buttonOne.grid(row=0,column=0) self.buttonTwo = Button(self.container2,text='2') self.buttonTwo.grid(row=0,column=1) self.buttonThree = Button(self.container2,text='3') self.buttonThree.grid(row=0,column=2) self.buttonFour = Button(self.container2,text='4') self.buttonFour.grid(row=1,column=0) self.buttonFive = Button(self.container2,text='5') self.buttonFive.grid(row=1,column=1) self.buttonSix = Button(self.container2,text='6') self.buttonSix.grid(row=1,column=2) self.buttonSeven = Button(self.container2,text='7') self.buttonSeven.grid(row=2,column=0) self.buttonEight = Button(self.container2,text='8') self.buttonEight.grid(row=2,column=1) self.buttonNine = Button(self.container2,text='9') self.buttonNine.grid(row=2,column=2) self.buttonZero = Button(self.container2,text='0') self.buttonZero.grid(row=3,column=0) self.buttonPoint = Button(self.container2,text='.') self.buttonPoint.grid(row=3,column=1) def make_oprbuttons(self): self.buttonPlu = Button(self.container3,text='+',command = lambda: self.oprClick('+',self.str1.get())) self.buttonPlu.pack(side=LEFT) self.buttonMin = Button(self.container3,text='-',command = lambda: self.oprClick('-',self.str1.get())) self.buttonMin.pack(side=LEFT) self.buttonMul = Button(self.container3,text='*',command = lambda: self.oprClick('*',self.str1.get())) self.buttonMul.pack(side=LEFT) self.buttonDiv = Button(self.container3,text='/',command = lambda: self.oprClick('/',self.str1.get())) self.buttonDiv.pack(side=LEFT) self.buttonEqu = Button(self.container3,text='=',command = lambda: self.oprClick('=',self.str1.get())) self.buttonEqu.pack(side=LEFT) root = Tk() mycalc = Mycalc(root) mycalc.make_buttons() mycalc.make_oprbuttons() root.mainloop() On 10/26/06, Kent Johnson wrote: > > Asrarahmed Kadri wrote: > > > > > > Hi folks, > > > > I am trying to build a rudimentary calculator application using > Tkinter... > > > > I have used one Entry widget for displaying the input and output data. > > All this is put in a class. > > The porblem is when I click teh '+' button, teh callback function is > > called but it gives me an error message: AttributeError: 'str' object > > has no attribute 'get' > > > > I have defined a variable, self.str1 = StringVar() to bind it with the > > entry widget and I am calling the function when + is clciked. The > > function is as follows: > > > > self.buttonPlu = Button(self.container3,text='+',command = lambda: > > self.oprClick('+',*self.str1.get()))* > > > > Can't we use the get() method to access the contents of the entry > > widget. Is there any other way to access the contents of the entry > > widget....??? > > The error message is saying that the object you are calling get() on is > a string, not a StringVar. Please post complete code and the complete > error message including traceback. > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061026/f97988c9/attachment.htm From kent37 at tds.net Thu Oct 26 16:01:42 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 26 Oct 2006 10:01:42 -0400 Subject: [Tutor] Code with traceback...Re: Help me.. problem in building calculator application In-Reply-To: References: Message-ID: <4540BFC6.2070003@tds.net> Immediately following the line self.str1 = StringVar() you have self.str1 = "0" at which point self.str1 is a string, not a StringVar. Maybe you mean self.str1.set("0") ? Kent Asrarahmed Kadri wrote: > > Traceback is as under: > > Traceback (most recent call last): > File "C:\python\lib\lib-tk\Tkinter.py", line 1345, in __call__ > return self.func(*args) > File "calculator_version2.py", line 105, in > self.buttonPlu = Button(self.container3,text='+',command = lambda: > self.oprC > lick('+',self.str1.get())) > AttributeError: 'str' object has no attribute 'get' > > > > from Tkinter import * > import string > > > class Mycalc: > > def buttonClick(self,str2,str3): > if str2 == ".": > if self.dotFlag: > pass > else: > self.dotFlag = True > self.operand = str3 + str2 > else: > self.operand = str3 + str2 > > > > def oprClick(self,str11,oprt): > > self.dotFlag = False > > if oprt == "+": > if self.result == "0": > self.result = str11 > else: > self.result = string.atof(self.result) + string.atof(str11) > > > > elif oprt == "-": > if self.result == "0": > self.result = str11 > else: > self.result = string.atof(self.result) - string.atof(str11) > > > elif str2 == "*": > if self.result == "0": > self.result = str11 > else: > self.result = string.atof(self.result) * string.atof(str11) > > > elif str2 == "/": > if self.result == "0": > self.result = str11 > else: > self.result = string.atof (self.result) / string.atof(str11) > > > self.entryWidget.icursor(0) > self.entryWidget.delete(0,END) > self.entryWidget.insert(INSERT,self.result) > > > > > > def __init__(self,master): > > self.container1 = > Frame(master,width=200,height=200,background='brown') > self.container1.pack() > self.str1 = StringVar() > self.str1 = "0" > self.entryWidget = Entry( > self.container1,textvariable=self.str1) > self.entryWidget.pack(side=TOP) > > self.container2 = Frame(master,background='cyan') > self.container2.pack() > > self.container3 = Frame(master,background='grey') > self.container3.pack() > > self.operand = "0" > self.result = "0" > self.dotFlag = False > > def make_buttons(self): > self.buttonOne = Button(self.container2,text='1') > self.buttonOne.grid(row=0,column=0) > self.buttonTwo = Button(self.container2,text='2') > self.buttonTwo.grid (row=0,column=1) > self.buttonThree = Button(self.container2,text='3') > self.buttonThree.grid(row=0,column=2) > self.buttonFour = Button(self.container2,text='4') > self.buttonFour.grid (row=1,column=0) > self.buttonFive = Button(self.container2,text='5') > self.buttonFive.grid(row=1,column=1) > self.buttonSix = Button(self.container2,text='6') > self.buttonSix.grid(row=1,column=2) > self.buttonSeven = Button(self.container2,text='7') > self.buttonSeven.grid(row=2,column=0) > self.buttonEight = Button(self.container2,text='8') > self.buttonEight.grid(row=2,column=1) > self.buttonNine = Button(self.container2,text='9') > self.buttonNine.grid(row=2,column=2) > self.buttonZero = Button(self.container2,text='0') > self.buttonZero.grid(row=3,column=0) > self.buttonPoint = Button(self.container2,text='.') > self.buttonPoint.grid(row=3,column=1) > > def make_oprbuttons(self): > > self.buttonPlu = Button(self.container3,text='+',command = > lambda: self.oprClick('+',self.str1.get())) > self.buttonPlu.pack(side=LEFT) > > self.buttonMin = Button(self.container3,text='-',command = > lambda: self.oprClick('-',self.str1.get())) > self.buttonMin.pack(side=LEFT) > > self.buttonMul = Button(self.container3,text='*',command = > lambda: self.oprClick('*',self.str1.get())) > self.buttonMul.pack(side=LEFT) > > self.buttonDiv = Button(self.container3,text='/',command = > lambda: self.oprClick('/',self.str1.get())) > self.buttonDiv.pack(side=LEFT) > > self.buttonEqu = Button(self.container3,text='=',command = > lambda: self.oprClick('=',self.str1.get())) > self.buttonEqu.pack(side=LEFT) > > > > root = Tk() > mycalc = Mycalc(root) > mycalc.make_buttons() > mycalc.make_oprbuttons() > > root.mainloop() > > > On 10/26/06, *Kent Johnson* > wrote: > > Asrarahmed Kadri wrote: > > > > > > Hi folks, > > > > I am trying to build a rudimentary calculator application using > Tkinter... > > > > I have used one Entry widget for displaying the input and output > data. > > All this is put in a class. > > The porblem is when I click teh '+' button, teh callback function is > > called but it gives me an error message: AttributeError: 'str' > object > > has no attribute 'get' > > > > I have defined a variable, self.str1 = StringVar() to bind it > with the > > entry widget and I am calling the function when + is clciked. The > > function is as follows: > > > > self.buttonPlu = Button(self.container3,text='+',command = lambda: > > self.oprClick('+',*self.str1.get()))* > > > > Can't we use the get() method to access the contents of the entry > > widget. Is there any other way to access the contents of the entry > > widget....??? > > The error message is saying that the object you are calling get() on is > a string, not a StringVar. Please post complete code and the complete > error message including traceback. > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > > > > -- > To HIM you shall return. From andreas at kostyrka.org Thu Oct 26 15:51:07 2006 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Thu, 26 Oct 2006 15:51:07 +0200 Subject: [Tutor] Python and config files? In-Reply-To: <4540B700.8070109@tds.net> References: <4540AE52.7010307@yandex.ru> <4540B700.8070109@tds.net> Message-ID: <1161870667.16385.40.camel@andi-lap> Actually, for Unixish config files, shlex seems the better module. Andreas Am Donnerstag, den 26.10.2006, 09:24 -0400 schrieb Kent Johnson: > Basil Shubin wrote: > > Hi, friends! > > > > Is there exist a module for working with config file? Simple enough, > > just read/write config file (like for most unix app), determine where > > row is contain config words with it's parameters (like > > 'config_word=parameter') or it's a comments (#)? > > Take a look at the ConfigParser module: > http://docs.python.org/lib/module-ConfigParser.html > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20061026/04637ddf/attachment-0001.pgp From alan.gauld at btinternet.com Thu Oct 26 17:16:50 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 26 Oct 2006 16:16:50 +0100 Subject: [Tutor] Code with traceback...Re: Help me.. problem in buildingcalculator application References: Message-ID: Kent has already pointed out the problem of overwriting the stringvar, but there is another problem too: > def oprClick(self,str11,oprt): > self.buttonPlu = Button(self.container3,text='+', command = lambda: self.oprClick('+',self.str1.get())) Check the position of the operator string in the definition versus the lambda call.... Alan G. From nephish at gmail.com Thu Oct 26 18:07:22 2006 From: nephish at gmail.com (shawn bright) Date: Thu, 26 Oct 2006 11:07:22 -0500 Subject: [Tutor] problem importing class Message-ID: <384c93600610260907p9287dc5qcf187262779bcef4@mail.gmail.com> hey there i have written a module called site.py in the file i have this: import DbConnector import sensor class Site(object): "site object" def __init__(self, id): self.id = id self.con = DbConnector.DbConnector() id = str(self.id) stats = self.con.getOne("selct `group_id`, `name`, `ivr_code`, \ `site_type`, `notes`, `sensor_id` \ from `sites` where `id` = '"+str(id)+"' ") self.group_id = stats[0] self.name = stats[1] self.ivr_code = stats[2] self.site_type = stats[3] self.notes = stats[4] self.sensor_id = stats[5] def get_sensor(self): self.sensor = sensor.Sensor(self.sensor_id) return self.sensor ok, in the program i am trying to run i have these lines: import site new_site = site.Site(id_number) and this is what my output is: Traceback (most recent call last): File "./new_camp.py", line 2014, in on_site_tree_view_row_activated acitve_site = site.Site(id_number) AttributeError: 'module' object has no attribute 'Site' It looks like the same code works for a different module i have ; i don't get what i could be missing here, any tips? if you have read this far, thanks for your time. sk -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061026/17139a00/attachment.html From jason.massey at gmail.com Thu Oct 26 18:21:18 2006 From: jason.massey at gmail.com (Jason Massey) Date: Thu, 26 Oct 2006 11:21:18 -0500 Subject: [Tutor] problem importing class In-Reply-To: <384c93600610260907p9287dc5qcf187262779bcef4@mail.gmail.com> References: <384c93600610260907p9287dc5qcf187262779bcef4@mail.gmail.com> Message-ID: <7e3eab2c0610260921m77282534x71d7185dd77458e7@mail.gmail.com> Shawn, Python already has a module called site. From http://docs.python.org/lib/module-site.html : * This module is automatically imported during initialization.* The automatic import can be suppressed using the interpreter's *-S* option. Importing this module will append site-specific paths to the module search path. Easiest thing would be to rename your module. On 10/26/06, shawn bright wrote: > > hey there > > i have written a module called site.py > in the file i have this: > > import DbConnector > import sensor > > class Site(object): > "site object" > > def __init__(self, id): > self.id = id > self.con = DbConnector.DbConnector() > id = str(self.id) > stats = self.con.getOne("selct `group_id`, `name`, `ivr_code`, \ > `site_type`, `notes`, `sensor_id` \ > from `sites` where `id` = '"+str(id)+"' ") > self.group_id = stats[0] > self.name = stats[1] > self.ivr_code = stats[2] > self.site_type = stats[3] > self.notes = stats[4] > self.sensor_id = stats[5] > > def get_sensor(self): > self.sensor = sensor.Sensor (self.sensor_id) > return self.sensor > > ok, in the program i am trying to run i have these lines: > import site > new_site = site.Site(id_number) > > and this is what my output is: > Traceback (most recent call last): > File "./new_camp.py", line 2014, in on_site_tree_view_row_activated > acitve_site = site.Site(id_number) > AttributeError: 'module' object has no attribute 'Site' > > It looks like the same code works for a different module i have ; > i don't get what i could be missing here, any tips? > > if you have read this far, thanks for your time. > sk > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061026/99b80aeb/attachment.htm From simon at brunningonline.net Thu Oct 26 18:21:58 2006 From: simon at brunningonline.net (Simon Brunning) Date: Thu, 26 Oct 2006 17:21:58 +0100 Subject: [Tutor] problem importing class In-Reply-To: <384c93600610260907p9287dc5qcf187262779bcef4@mail.gmail.com> References: <384c93600610260907p9287dc5qcf187262779bcef4@mail.gmail.com> Message-ID: <8c7f10c60610260921s5d7623d0x9de21e47e7343610@mail.gmail.com> On 10/26/06, shawn bright wrote: > import site Try this for a clue: print site.__file__ -- Cheers, Simon B simon at brunningonline.net http://www.brunningonline.net/simon/blog/ From kent37 at tds.net Thu Oct 26 18:33:17 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 26 Oct 2006 12:33:17 -0400 Subject: [Tutor] problem importing class In-Reply-To: <384c93600610260907p9287dc5qcf187262779bcef4@mail.gmail.com> References: <384c93600610260907p9287dc5qcf187262779bcef4@mail.gmail.com> Message-ID: <4540E34D.5060207@tds.net> shawn bright wrote: > hey there > > i have written a module called site.py Use a different name, there is a library module called site that is automatically imported when Python starts up. So when you 'import site' you are getting the already-imported library module. Kent > in the file i have this: > > import DbConnector > import sensor > > class Site(object): > "site object" > > def __init__(self, id): > self.id = id > self.con = DbConnector.DbConnector() > id = str(self.id ) > stats = self.con.getOne("selct `group_id`, `name`, `ivr_code`, \ > `site_type`, `notes`, `sensor_id` \ > from `sites` where `id` = '"+str(id)+"' ") > self.group_id = stats[0] > self.name = stats[1] > self.ivr_code = stats[2] > self.site_type = stats[3] > self.notes = stats[4] > self.sensor_id = stats[5] > > def get_sensor(self): > self.sensor = sensor.Sensor (self.sensor_id) > return self.sensor > > ok, in the program i am trying to run i have these lines: > import site > new_site = site.Site(id_number) > > and this is what my output is: > Traceback (most recent call last): > File "./new_camp.py", line 2014, in on_site_tree_view_row_activated > acitve_site = site.Site(id_number) > AttributeError: 'module' object has no attribute 'Site' > > It looks like the same code works for a different module i have ; > i don't get what i could be missing here, any tips? > > if you have read this far, thanks for your time. > sk > > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From dyoo at hkn.eecs.berkeley.edu Thu Oct 26 18:37:27 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 26 Oct 2006 09:37:27 -0700 (PDT) Subject: [Tutor] problem importing class In-Reply-To: <7e3eab2c0610260921m77282534x71d7185dd77458e7@mail.gmail.com> References: <384c93600610260907p9287dc5qcf187262779bcef4@mail.gmail.com> <7e3eab2c0610260921m77282534x71d7185dd77458e7@mail.gmail.com> Message-ID: Hi Shawn, It looks like people have identified the problem, that your site.py module isn't being found because it conflicts with something from Python's Standard Library. This isn't the first time this kind of problem has hit people. This problem is well known and is the subject of a Python Enhancement Proposal (PEP 328). If you're using Python 2.5, you can use a new feature called 'absolute_import' to avoid the import problem. See: http://docs.python.org/whatsnew/pep-328.html for more details. In the meantime, if you can't depend on using Python 2.5 yet, just rename your site.py module to something else to avoid the collision between Python's own site.py module and your own. From jazedo at netcabo.pt Thu Oct 26 18:37:43 2006 From: jazedo at netcabo.pt (Jorge Azedo) Date: Thu, 26 Oct 2006 17:37:43 +0100 Subject: [Tutor] New to programming and Python In-Reply-To: References: Message-ID: <4540E457.40004@netcabo.pt> First off, I don't know if I'm doing this right, I've never used a mailing list before, so I'm not sure if I'm sending this to the right place. Thanks for all the help you guys gave me ( e voc?s tamb?m pessoal, ? bom saber que h? pessoal portugu?s por aqui :-) ). I'll try and read as many tutorials as I can and start to work on some programs of my own. Let's hope I can make something useful or fun. From nephish at gmail.com Thu Oct 26 18:54:28 2006 From: nephish at gmail.com (shawn bright) Date: Thu, 26 Oct 2006 11:54:28 -0500 Subject: [Tutor] problem importing class In-Reply-To: References: <384c93600610260907p9287dc5qcf187262779bcef4@mail.gmail.com> <7e3eab2c0610260921m77282534x71d7185dd77458e7@mail.gmail.com> Message-ID: <384c93600610260954x692b4850j16c9f25283f59bd9@mail.gmail.com> Hey thanks for the help, gents, i renamed site.py to site_obj.py and my import and statement. everything is working now. Thank you guys very very much. shawn On 10/26/06, Danny Yoo wrote: > > > Hi Shawn, > > It looks like people have identified the problem, that your site.py module > isn't being found because it conflicts with something from Python's > Standard Library. > > This isn't the first time this kind of problem has hit people. This > problem is well known and is the subject of a Python Enhancement Proposal > (PEP 328). If you're using Python 2.5, you can use a new feature called > 'absolute_import' to avoid the import problem. See: > > http://docs.python.org/whatsnew/pep-328.html > > for more details. > > In the meantime, if you can't depend on using Python 2.5 yet, just rename > your site.py module to something else to avoid the collision between > Python's own site.py module and your own. > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061026/58841993/attachment-0001.html From dyoo at hkn.eecs.berkeley.edu Thu Oct 26 19:22:32 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 26 Oct 2006 10:22:32 -0700 (PDT) Subject: [Tutor] New to programming and Python In-Reply-To: <4540E457.40004@netcabo.pt> References: <4540E457.40004@netcabo.pt> Message-ID: On Thu, 26 Oct 2006, Jorge Azedo wrote: > First off, I don't know if I'm doing this right, I've never used a > mailing list before, so I'm not sure if I'm sending this to the right > place. > > Thanks for all the help you guys gave me ( e voc?s tamb?m pessoal, ? bom > saber que h? pessoal portugu?s por aqui :-) ). I'll try and read as many > tutorials as I can and start to work on some programs of my own. Let's > hope I can make something useful or fun. I'd second the recommendation to Dive into Python; it has great practical examples. Feel free to ask questions on the list; we're all here to help each other. As a non-Python tangent: if you'd like to read a textbook on learning introductory programming, you might be interested in How to Design Programs: http://www.htdp.org/ The first few chapters might feel a little slow, and the language used is not Python. But even with that, the material in the book is top notch, better than most introductory textbooks I've seen. If I were to point someone new to computing toward learning to program, this is the book I'd be oblidged to recommend. Good luck to you! From kent37 at tds.net Thu Oct 26 19:45:36 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 26 Oct 2006 13:45:36 -0400 Subject: [Tutor] problem importing class In-Reply-To: References: <384c93600610260907p9287dc5qcf187262779bcef4@mail.gmail.com> <7e3eab2c0610260921m77282534x71d7185dd77458e7@mail.gmail.com> Message-ID: <4540F440.9020305@tds.net> Danny Yoo wrote: > Hi Shawn, > > It looks like people have identified the problem, that your site.py module > isn't being found because it conflicts with something from Python's > Standard Library. > > This isn't the first time this kind of problem has hit people. This > problem is well known and is the subject of a Python Enhancement Proposal > (PEP 328). If you're using Python 2.5, you can use a new feature called > 'absolute_import' to avoid the import problem. See: > > http://docs.python.org/whatsnew/pep-328.html > > for more details. Hmm, I don't see how that would help since AFAICT shawn's site.py is not in a package. Or maybe I don't understand what you are suggesting? Kent From doug.shawhan at gmail.com Thu Oct 26 21:18:44 2006 From: doug.shawhan at gmail.com (doug shawhan) Date: Thu, 26 Oct 2006 14:18:44 -0500 Subject: [Tutor] Self, Scopes and my unbelievable muddleheadedness. In-Reply-To: <453FE55E.8010608@gmail.com> References: <5e1ceb8a0610251521j5400adb5sd8e5cc5ddcb3872d@mail.gmail.com> <453FE55E.8010608@gmail.com> Message-ID: <5e1ceb8a0610261218v7fb24c33r73af34df639673f0@mail.gmail.com> On 10/25/06, Luke Paireepinart wrote: > > > > > > I'm sure this is so obvious that a crack-addled tapeworm head down in > > a bucket of stupid could understand it, unfortunately, I'm not quite > > at that level today. Sorry. > Uh, I don't understand why you're passing Fields to the functions but > then putting the value in self.Fields... > but we'll ignore that for now :) http://www.penzilla.net/tutorials/python/modules/ I explain my confusion more coherently in my reply to Mr. Gald. :-) The problem it sounds like you're having is that you think that passing > lists to functions copies them, > when in fact it just creates a reference to them. > Take this, for example: Close! I thought that "self" would somehow automagically create a copy of the list, leaving a global intact. I am disillusioned. >>> def append_five(alist): > alist.append(5) > >>> a = [1,2,3,4] > >>> append_five(a) > >>> a > [1, 2, 3, 4, 5] > >>> append_five(a) > >>> a > [1, 2, 3, 4, 5, 5] Which answers my question "why is my list of dictionaries turning in to a list with a dictionary with a list of dictionaries therein! :-) Other than that, > Maybe you think self is used for something other than what it's intended > to be used for... > but I can't be sure. Again, see my reply to Mr. Gald. I am starting to get my head around "self". I searched usenet for explanations, apparently I'm not the only one. :-). It seems to be pretty simple, for most. I'm reminded of learning to solve for polynomials or diagram sentences: It's elementary to some and completely obtuse to others, depending on mindset and experience. I'm sure someone else can give you a good example. > I, however, have to run. > HTH, > -Luke Thanks! I appreciate it! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061026/bbf31203/attachment.html From doug.shawhan at gmail.com Thu Oct 26 21:19:32 2006 From: doug.shawhan at gmail.com (doug shawhan) Date: Thu, 26 Oct 2006 14:19:32 -0500 Subject: [Tutor] Fwd: Self, Scopes and my unbelievable muddleheadedness. In-Reply-To: <5e1ceb8a0610261145l17b38ee6kc3ec7e30bd3fbeab@mail.gmail.com> References: <5e1ceb8a0610251521j5400adb5sd8e5cc5ddcb3872d@mail.gmail.com> <5e1ceb8a0610261145l17b38ee6kc3ec7e30bd3fbeab@mail.gmail.com> Message-ID: <5e1ceb8a0610261219k77373818y732a593e109f1af@mail.gmail.com> ---------- Forwarded message ---------- From: doug shawhan Date: Oct 26, 2006 1:45 PM Subject: Re: [Tutor] Self, Scopes and my unbelievable muddleheadedness. To: Alan Gauld On 10/26/06, Alan Gauld wrote: > > "doug shawhan" wrote > > I'm having a rather difficult time understanding the proper use of > > "self". > > Doug, I think you may be having a more fundamental problem. > Looking at your code at the most superficial level it seems > you may not understand objects. I've always been confused by much of the OOP terminology. I'm about to go off on a tangent below regarding your explaination. I think it is helping me, but I want to be sure. Bear with me. :-) My original question should have been: "Why is this dictionary coming back weird?" The dictionary was just a placeholder for a future .ini file to be read with ConfigParser. In playing around with different ideas. I thought "I'd like to put each particular set of activities into modules anyway, so let's just figure out how that might work". I ran onto the problem of the dictionary being changed globally, when I thought that use of "self" meant that any changes to that data were limited to the scope of the method in that particular class (and it's resultant object), thereby insulating it from other methods in the same class and other objects which inherit from the same class" (Don't reply to this yet! :-) I'm sure that I have simply thought that my global declaration was not going to be changed in place by misunderstanding what "self" means. My confusion stemmed from just how weird the change appeard to be. I.e. "But I just looked at the dang thing and it was what I expected! Where dem extra parentheis come from? Huh?" I apologize for my incoherence in asking the question. I was in the middle of trying out different ideas and ran onto this weirdness and could not let it go. I should taken the time to write a generic example, but frankly, I was frustrated and was not thinking about how best to frame the question. It was impolite of me to subject the list to my half-baked meanderings. Again, sorry. You guys have helped so much and you deserve a little more effort on my part. So, fortified with 8 hours of sleep and 15mg of Adderall, here we go! Classes are used to generate objects. Objects represent things. > By logical deduction objects correspond to nouns in language. > Objects do things when they receive messages (Possibly > from other objects). Messages cause methods to be invoked, > methods therefore correspond to verbs in language. > I felt like I was being told an integer is a "counting number" here. ;-) > Looking at your code we find: > > class Create: # a verb > def freshDB(self, DBPATH, Fields): # a noun > def comparisonTable(self, DBPATH, Fields, columns, mode): #a noun > > In other words you have the concept inside out. > you are trying to create Create objects and call Table and Database > methods. It doesn't make sense. > > Normally we would expect to see DB and Table objects to which > you send create messages. I was even more confused. Were you objecting to my nomenclature? So I thought, "If I named the class "Steve" and called the methods createFreshDB() and createComparisonTable() so it would read: "Steve, create a fresh database which includes tables named for the keys and columns named for the values in this dictionary I'm handing you." "Steve, create a comparison table just like above, but with a different key." which would be followed (eventually, if I hadn't gotten bogged down) by "Steve, tell gadfly to collate those two tables I just had you make and put them in another table so I can generate a report" Would that make any difference? No especially in how the code was written (it was still ugly and half-baked, and showing tons of bad habits), but I did suddenly realize what you meant by "noun". I have been treating objects like a corporate sales droid treats nouns. I've been "Gifting" and "Tableing" the objects "TheGift" and "TheTable" in my mind. (I fear I've also been "Impacting" the method "impact()" without asking Steve.Please() first, (I.E. not quite understanding why my classes within the modules were not showing up like I expected, but that's another story.) I've not been thinking of an object as a verb, rather more like a gerund. Still wrong, but a different kind of wrong. Now if you think of the objects as verbs then self is a confusing > concept. > But if you think of the objects as nouns then self is simply a > reference > to the object instance in question, a particular database or table. Which leads me back to the "why is it there?" question I saw on the list recently. If "self" is simply a reference to the object instance in question, then why does one have to basically mirror the variable at the top of the class? The example I was working from is at: http://www.penzilla.net/tutorials/python/modules/ # Intro To Python: Modules # book.py """ Class: Book( title, author, keywords ) Each book object takes a title, optional author, and optional keywords. """ *class** Book*: *def* * __init__*(self, title, author="Unknown", keywords=[]): """ Books take three arguments to their constructor The first and only required argument is the title, followed by the optional arguments, author, and a list of keywords that can be used to look up a specific book. """ self.title = title self.author = author self.keywords = keywords *def** setTitle* (self, title): This seems bizzare and redundant, but I did it anyway, all the time thinking, "Why not just clone the variable, I.E. 'titleForMyPurposesHereInThisInstance = title'? " Does it follow that if one does not prepend "self" to the variable, any change will affect all instances of an object (say in a threading situation)? That is the only thing that seems to make sense to me, otherwise "self" would just be silly. I'd recommend going back and rethinking the design of your > objects before going much further. As I said, all that stuff was throwaway anyway and I should have made a more generic example. Thanks! HTH, > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061026/363725cf/attachment.htm From jazedo at netcabo.pt Thu Oct 26 22:08:59 2006 From: jazedo at netcabo.pt (Jorge Azedo) Date: Thu, 26 Oct 2006 21:08:59 +0100 Subject: [Tutor] Mailing list question Message-ID: <454115DB.8050104@netcabo.pt> Not so much a question about Python, but here goes: How do I reply to a specific thread in the mailing list? If I place "Re:bla bla" in the subject line, I notice that I start a new thread, I don't continue one that already exists. How do I go about doing this? Thanks for any info From rabidpoobear at gmail.com Thu Oct 26 22:44:51 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 26 Oct 2006 15:44:51 -0500 Subject: [Tutor] Mailing list question In-Reply-To: <454115DB.8050104@netcabo.pt> References: <454115DB.8050104@netcabo.pt> Message-ID: <45411E43.9010600@gmail.com> Jorge Azedo wrote: > Not so much a question about Python, but here goes: > > How do I reply to a specific thread in the mailing list? If I place > "Re:bla bla" in the subject line, I notice that I start a new thread, > I don't continue one that already exists. How do I go about doing this? > Thanks for any info What e-mail client are you using? Most have a reply-to-all button you can use so that you won't have to start a new message to reply to someone. From dyoo at hkn.eecs.berkeley.edu Thu Oct 26 23:31:02 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 26 Oct 2006 14:31:02 -0700 (PDT) Subject: [Tutor] Mailing list question In-Reply-To: <45411E43.9010600@gmail.com> References: <454115DB.8050104@netcabo.pt> <45411E43.9010600@gmail.com> Message-ID: >> Not so much a question about Python, but here goes: >> >> How do I reply to a specific thread in the mailing list? If I place >> "Re:bla bla" in the subject line, I notice that I start a new thread, >> I don't continue one that already exists. How do I go about doing this? >> Thanks for any info > > What e-mail client are you using? Most have a reply-to-all button you > can use so that you won't have to start a new message to reply to > someone. There's a little bit of extra information that Mailman uses to detect threads. The archives don't cluster messages based on the subject line, but instead use a specific header value whose name I'm completely forgetting right now... *grin* (I think it's the 'In-Reply-To' header line.) Your email client should be the one responsible for maintaining that threading information. From paulino1 at sapo.pt Thu Oct 26 23:48:03 2006 From: paulino1 at sapo.pt (Paulino) Date: Thu, 26 Oct 2006 22:48:03 +0100 Subject: [Tutor] Help me.. problem in building calculator application In-Reply-To: References: Message-ID: <45412D13.8050605@sapo.pt> > > Message: 7 > Date: Thu, 26 Oct 2006 13:31:37 +0100 > From: "Asrarahmed Kadri" > Subject: [Tutor] Help me.. problem in building calculator application > To: pythontutor > Message-ID: > > Content-Type: text/plain; charset="iso-8859-1" > > Hi folks, > > I am trying to build a rudimentary calculator application using Tkinter... > > Hi, Asrar! Try this article instead: http://www.devshed.com/c/a/Python/Designing-a-Calculator-in-wxPython/ Paulino From jazedo at netcabo.pt Fri Oct 27 00:07:36 2006 From: jazedo at netcabo.pt (Jorge Azedo) Date: Thu, 26 Oct 2006 23:07:36 +0100 Subject: [Tutor] Mailing list question In-Reply-To: References: <454115DB.8050104@netcabo.pt> <45411E43.9010600@gmail.com> Message-ID: <454131A8.5050005@netcabo.pt> Danny Yoo wrote: > > >>> Not so much a question about Python, but here goes: >>> >>> How do I reply to a specific thread in the mailing list? If I place >>> "Re:bla bla" in the subject line, I notice that I start a new >>> thread, I don't continue one that already exists. How do I go about >>> doing this? Thanks for any info >> >> What e-mail client are you using? Most have a reply-to-all button >> you can use so that you won't have to start a new message to reply to >> someone. > > There's a little bit of extra information that Mailman uses to detect > threads. The archives don't cluster messages based on the subject > line, but instead use a specific header value whose name I'm > completely forgetting right now... *grin* (I think it's the > 'In-Reply-To' header line.) Your email client should be the one > responsible for maintaining that threading information. > I'm trying to use the Reply All button on my mail client (I use Thunderbird, by the way) like you guys suggested. Let's see if it works :-P From rabidpoobear at gmail.com Fri Oct 27 00:15:30 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 26 Oct 2006 17:15:30 -0500 Subject: [Tutor] Fwd: Self, Scopes and my unbelievable muddleheadedness. In-Reply-To: <5e1ceb8a0610261219k77373818y732a593e109f1af@mail.gmail.com> References: <5e1ceb8a0610251521j5400adb5sd8e5cc5ddcb3872d@mail.gmail.com> <5e1ceb8a0610261145l17b38ee6kc3ec7e30bd3fbeab@mail.gmail.com> <5e1ceb8a0610261219k77373818y732a593e109f1af@mail.gmail.com> Message-ID: <45413382.8080701@gmail.com> doug shawhan wrote: > [lots of stuff!] You seem to have a penchant for choosing entertaining, albeit confusing, words to explain what you're thinking. I have a similar inclination; however, I'll attempt to avoid this so that my explanation will make more sense :) Now we begin. First, an example, then an explanation. #given the following definition... class AClass(object): aClassVariable = 'Hello' def aMethod(self): print self.hello def __init__(self): self.hello = "Hi!" >>> AClass.aClassVariable 'Hello' >>> anInstance = AClass() >>> AClass.hello Traceback (most recent call last): File "", line 1, in ? AClass.hello AttributeError: type object 'AClass' has no attribute 'hello' >>> anInstance.hello 'Hi!' >>> AClass.aMethod() Traceback (most recent call last): File "", line 1, in ? AClass.aMethod() TypeError: unbound method aMethod() must be called with AClass instance as first argument (got nothing instead) >>> anInstance.aMethod() Hi! >>> anInstance.aClassVariable 'Hello' >>> anInstance.aClassVariable = 'Ho!' >>> anInstance.aClassVariable 'Ho!' >>> AClass.aClassVariable 'Hello' #---- end of example. Believe it or not, this short example should tell you everything you need to know about objects ;) However, that doesn't mean it makes any sense! So I will try to explain it. I had a huge problem with Objects when I first ran into them, but now they're easy to understand. Hope I can do the same for you. Okay, take this example: class aClass(object): aVariable = 'hi' What the interpreter does is creates a variable called aClass that points to this object. Yes, class definitions are objects. >>> aClass Since the variable that we defined in the aClass object was defined in the main scope of the class, and not in a class method (it wasn't defined inside a function that was in the class) it's global to the class object. so... >>> aClass.aVariable 'hi' we don't even need to make an instance of the class to access this variable. We can make an instance if we want... >>> b = aClass() >>> b.aVariable 'hi' But there's really no point, is there? Now take this class. class aClass(object): value = 'hi' def __init__(self): self.value = 'hello' Because the 'self.value' is only defined inside of the '__init__' method, it's not global to the class definition, but the 'value' variable is global to the class definition. >>> aClass.value 'hi' But when we make an instance of this class, >>> instance = aClass() The init method is called, >>> instance.value 'hello' which replaces the class-global 'value' variable with the instance-global 'self.variable' version. One thing it's important to note is this: #given these two definitions class aClass(object): aVar = 1 aList = [1,2,3] b = aClass() #we get this. >>> aClass.aVar 1 >>> aClass.aList [1, 2, 3] >>> b.aVar 1 >>> b.aList [1, 2, 3] >>> b.aVar = 23 >>> b.aList.append(4) >>> b.aVar 23 >>> b.aList [1, 2, 3, 4] >>> aClass.aVar 1 >>> aClass.aList [1, 2, 3, 4] Notice how changing the value of b.aList changes the value of aClass.aList? So any object you make after this, >>> a = aClass() >>> a.aList [1, 2, 3, 4] will have the modified value of aList, >>> a.aVar 1 but not the modified version of aVar. However, if you were to change aVar in the class definition (and not in an instance of the class) >>> aClass.aVar = 2 >>> a.aVar 2 then the value of aVar is changed. This is interesting and a little scary, since changing a list in an instance can change this list in all class instances, but not if it's an integer or a tuple or something else. This is a good reason to use 'self'. That way, each class has its own set of data that can't be messed with. You say in your e-mail " Does it follow that if one does not prepend "self" to the variable, any change will affect all instances of an object (say in a threading situation)? That is the only thing that seems to make sense to me, otherwise "self" would just be silly. " No, this is not the point of self at all. Imagine that you have this class. class Poem(object): def __init__(self,title,text): #args: string, list of strings self.title = title self.text = text def readPoem(self): print "Poem: %s" % self.title for line in self.text: print line def reversePoem(self): self.text.reverse() Now say you want two poems... >>> aolHaiku = Poem('Unwanted AOL CD Haiku',['A shiny let-down,','AOL CDs are good','Only for artwork']) >>> windowsHaiku = Poem('Microsoft Haiku',['Yesterday it worked.','Today it is not working.','Windows is like that.']) And you want to read them. >>> aolHaiku.readPoem() Poem: Unwanted AOL CD Haiku A shiny let-down, AOL CDs are good Only for artwork >>> windowsHaiku.readPoem() Poem: Microsoft Haiku Yesterday it worked. Today it is not working. Windows is like that. So it doesn't matter to us what's acually _in_ each class instance, we know if we call the readPoem on the Poem object, it'll do something. similarly, >>> aolHaiku.reversePoem() >>> aolHaiku.readPoem() Poem: Unwanted AOL CD Haiku Only for artwork AOL CDs are good A shiny let-down, Do you see the point? an object has a specific set of data on which it operates with a specific set of methods. So you create a generic template (the class definition) which people create instances of to hold their own data. Or, if your class doesn't do exactly what they want, they can make their own class definition based on yours! example: class myPoemClass(Poem): def readPoem(self): print "The title of this poem is: %s" % self.title print "The text of the poem is as follows:" for line in self.text: print line when we use this, >>> aolHaiku = myPoemClass('Unwanted AOL CD Haiku',['A shiny let-down,','AOL CDs are good','Only for artwork']) #we created the same poem in our new class. >>> aolHaiku.readPoem() The title of this poem is: Unwanted AOL CD Haiku The text of the poem is as follows: A shiny let-down, AOL CDs are good Only for artwork #the output is different, >>> aolHaiku.reversePoem() #but since we didn't declare a reversePoem function in our derived class, >>> aolHaiku.readPoem() The title of this poem is: Unwanted AOL CD Haiku The text of the poem is as follows: Only for artwork AOL CDs are good A shiny let-down, #it still reverses it like it did before. Are you starting to see the benefits of classes? I hope so! To summarize, the purpose of self is so you don't have to define data for each function in your class. You define the data once (probably in the initialization of your class) and then it's defined throughout that instance (as long as you pass the instance variable around). So the function reversePoem and readPoem didn't have to know how to get the data 'self.text' or 'self.title', it was just available to them. It could've gotten there from the __init__ method, or any other method of the class. Another example that might help, or might just confuse further: >>> class aClass(object): def __init__(self): self.variable = 'hello!' def printVariable(self): print self.variable >>> an_instance = aClass() >>> an_instance.printVariable() hello! >>> aClass.printVariable(an_instance) hello! If you understand this, you probably understand self. Hope that helps, reply with anything that doesn't make sense, or just to tell me that I wasted my time and didn't address any issues you actually had :) -Luke From rabidpoobear at gmail.com Fri Oct 27 00:18:39 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 26 Oct 2006 17:18:39 -0500 Subject: [Tutor] Mailing list question In-Reply-To: <454131A8.5050005@netcabo.pt> References: <454115DB.8050104@netcabo.pt> <45411E43.9010600@gmail.com> <454131A8.5050005@netcabo.pt> Message-ID: <4541343F.4080103@gmail.com> >> > I'm trying to use the Reply All button on my mail client (I use > Thunderbird, by the way) like you guys suggested. Let's see if it > works :-P > That's what I use (Reply All and Thunderbird) and whenever I check my gmail account from the website, the messages I write appear threaded correctly. Well, that's assuming threading is the same as gmail conversations. Hope that helps From paulino1 at sapo.pt Fri Oct 27 00:25:17 2006 From: paulino1 at sapo.pt (Paulino) Date: Thu, 26 Oct 2006 23:25:17 +0100 Subject: [Tutor] cgi form field and popup window In-Reply-To: References: Message-ID: <454135CD.1060704@sapo.pt> > paulino wrote: > >> I would like to have a popup window to show the possible options to a form field >> (supplier ID) and that by clicking on the desired item, the field is >> automatically filled. The options are a database field values. >> >> I wonder if this is possible to do with python (point me some resources please), >> or have I to deal with javascript ? >> > > The browser-side programming has to be in javascript. The server-side > program that sends the javascript and the list of options to the browser > can be in Python. > > You might want to look at the TurboGears widget set which provides many > browser-side widgets that are configured from Python. Widgets are part > of TG 1.0. Unfortunately the docs seem to be a bit thin and sorting it > all out is probably not a beginner project. > http://www.turbogears.org/ > http://tgwidgets.toscat.net/ > > Kent > > > Many thanks, Kent, that's what I was afraid of. Well an alternative would be to use a drop down box with all the suppliers ID's as options - a few thousands, is it viable? But this way the user can not introduce manually any ID, he would be forced to pick one from the drop down box. In order to give users booth possibilities, I can put an input field and a drop down box that would be dealt by a try / except clause. what do you think? Paulino -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061026/3ce3a0eb/attachment.html From alan.gauld at btinternet.com Fri Oct 27 00:25:25 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 26 Oct 2006 23:25:25 +0100 Subject: [Tutor] Self, Scopes and my unbelievable muddleheadedness. References: <5e1ceb8a0610251521j5400adb5sd8e5cc5ddcb3872d@mail.gmail.com><5e1ceb8a0610261145l17b38ee6kc3ec7e30bd3fbeab@mail.gmail.com> <5e1ceb8a0610261219k77373818y732a593e109f1af@mail.gmail.com> Message-ID: > I ran onto the problem of the dictionary being changed globally, > when I > thought that use of "self" meant that any changes to that data were > limited > to the scope of the method in that particular class No, but you know that now :-) Let me try an alternative explanaytion for self, since we already had a discussion about self recently... self is simply a pointer to the object whose method is being called. Lets try writing some OO code without using Pythons OOP mechanism and see if we can spot why we need self (whether implicitly or explicitly). First we need a way to create objects since we dont have classes...so we write a function that returns a dictionary. We'll make it simple and have a message class that stores a string and has a display method. def display(aMessage): print aMessage['text'] def Message(theText): theObject = {} theObject['text'] = theText return theObject Now we create a couple of instances and display them: m1 = createMessage('Good morning') m2 = createMessage('Hello world') display(m1) display(m2) Notice how we need to pass the instance that we want to display into the display function? Now lets write the same thing using real OOP: class Message: def __init__(self, theText): self.text = theText def display(self): print self.text m1 = Message('Good morning') m2 = Message('Hello world') Message.display(m1) Message.display(m2) If you compare the definition of the display function and the definition of the display method can you see the similarity, and the correspondence of self to aMessage? Now look at the two calls to display in the real OOP example. Can you see the similarity to the calls to display in the non OOP version? Again can you see the correspondence between the values passed in to the function and the values passed via the class. In both cases its m1,m2, ie the instances we created. In both cases the function needs those values to know which objects message it should print. Finally we have the more conventionalOOP notation for calling methods: m1.display() m2.display() These are exactly the same as the previous calls via the Message class, but are more intuitive (once you start feeling comfortable with OOP notation as used with strings and the like) I've never tried explaining self with that set of examples so it may have confused things even more! But maybe its more conventional approach to functions v methods might make sense. The final caveat is that message dispatch gets more complex when you factor in inheritance so the simple non OOP example breaks down fairly quickly... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Fri Oct 27 00:28:54 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 26 Oct 2006 23:28:54 +0100 Subject: [Tutor] Mailing list question References: <454115DB.8050104@netcabo.pt> Message-ID: "Jorge Azedo" wrote > How do I reply to a specific thread in the mailing list? Just hit Reply All. There should be a command or button in your mail tool to do that, even if you use web mail. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From finalyugi at sapo.pt Fri Oct 27 00:34:28 2006 From: finalyugi at sapo.pt (rolando) Date: Thu, 26 Oct 2006 23:34:28 +0100 Subject: [Tutor] Mailing list question In-Reply-To: <454131A8.5050005@netcabo.pt> References: <454115DB.8050104@netcabo.pt> <45411E43.9010600@gmail.com> <454131A8.5050005@netcabo.pt> Message-ID: <454137F4.3050402@sapo.pt> I just use the reply button in my Thunderbird, and then change the email I want to send to tutor at python.org Jorge Azedo escreveu: > Danny Yoo wrote: > >> >>>> Not so much a question about Python, but here goes: >>>> >>>> How do I reply to a specific thread in the mailing list? If I place >>>> "Re:bla bla" in the subject line, I notice that I start a new >>>> thread, I don't continue one that already exists. How do I go about >>>> doing this? Thanks for any info >>>> >>> What e-mail client are you using? Most have a reply-to-all button >>> you can use so that you won't have to start a new message to reply to >>> someone. >>> >> There's a little bit of extra information that Mailman uses to detect >> threads. The archives don't cluster messages based on the subject >> line, but instead use a specific header value whose name I'm >> completely forgetting right now... *grin* (I think it's the >> 'In-Reply-To' header line.) Your email client should be the one >> responsible for maintaining that threading information. >> >> > I'm trying to use the Reply All button on my mail client (I use > Thunderbird, by the way) like you guys suggested. Let's see if it works > :-P > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From alan.gauld at btinternet.com Fri Oct 27 01:07:05 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 27 Oct 2006 00:07:05 +0100 Subject: [Tutor] Self, Scopes and my unbelievable muddleheadedness. References: <5e1ceb8a0610251521j5400adb5sd8e5cc5ddcb3872d@mail.gmail.com><5e1ceb8a0610261145l17b38ee6kc3ec7e30bd3fbeab@mail.gmail.com><5e1ceb8a0610261219k77373818y732a593e109f1af@mail.gmail.com> Message-ID: Replying to my own post, how sad... "Alan Gauld" wrote > First we need a way to create objects since we dont have > classes...so we write a function that returns a dictionary. > We'll make it simple and have a message class that stores > a string and has a display method. > > def display(aMessage): > print aMessage['text'] > > def Message(theText): > theObject = {} > theObject['text'] = theText > return theObject Oops I lost the plot somewhere here, the create function should have been called createMessage and looked like: def createMessage(theText): theObject = {} theObject['text'] = theText theObject['display'] = display return theObject > Now we create a couple of instances and display them: > > m1 = createMessage('Good morning') > m2 = createMessage('Hello world') > > display(m1) > display(m2) And the display calls should have been via the dictionary: m1['display'](m1) m2['display'](m2) > Notice how we need to pass the instance that we want > to display into the display call? And that should make more sense and be closer to the true OOP version... > Now lets write the same thing using real OOP: > > class Message: > def __init__(self, theText): > self.text = theText > def display(self): > print self.text > > m1 = Message('Good morning') > m2 = Message('Hello world') > Message.display(m1) > Message.display(m2) > > If you compare the definition of the display function and > the definition of the display method can you see the similarity, > and the correspondence of self to aMessage? > > Now look at the two calls to display in the real OOP example. > Can you see the similarity to the calls to display in the non OOP > version? > > Again can you see the correspondence between the values > passed in to the function and the values passed via the class. > In both cases its m1,m2, ie the instances we created. > In both cases the function needs those values to know > which objects message it should print. > > Finally we have the more conventionalOOP notation for calling > methods: > > m1.display() > m2.display() > > These are exactly the same as the previous calls via the > Message class, but are more intuitive (once you start > feeling comfortable with OOP notation as used with strings > and the like) > > I've never tried explaining self with that set of examples so > it may have confused things even more! But maybe its more > conventional approach to functions v methods might make sense. > > The final caveat is that message dispatch gets more complex > when you factor in inheritance so the simple non OOP example > breaks down fairly quickly... > > HTH, > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld From rabidpoobear at gmail.com Fri Oct 27 02:26:21 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 26 Oct 2006 19:26:21 -0500 Subject: [Tutor] Mailing list question In-Reply-To: <454137F4.3050402@sapo.pt> References: <454115DB.8050104@netcabo.pt> <45411E43.9010600@gmail.com> <454131A8.5050005@netcabo.pt> <454137F4.3050402@sapo.pt> Message-ID: <4541522D.4060506@gmail.com> rolando wrote: > I just use the reply button in my Thunderbird, and then change the email > I want to send to tutor at python.org It's better to use reply-all, in my opinion, because then, if someone's involved in an e-mail thread, they'll get an instant update on it even if they only get the Tutor Digest and not every individual mail. Cheers, -Luke From sisson.j at gmail.com Thu Oct 26 11:41:17 2006 From: sisson.j at gmail.com (Jonathon Sisson) Date: Thu, 26 Oct 2006 04:41:17 -0500 Subject: [Tutor] Mailing list question In-Reply-To: References: <454115DB.8050104@netcabo.pt> Message-ID: <454082BD.2070006@gmail.com> Greetings everyone... I use Thunderbird, too. I've noticed that it handles threads a bit strange...for instance, I have pytutor set up to send me copies of my replies (so I can track threads better), but Thunderbird won't display my replies inline with the threads... If you go to the folder you want to see threads in, then click on view, you can look at your thread settings. Under "sort by" you should be able to set "Threaded" or "unthreaded", and under Threads (under the view menu) you should have it set to "all". I know that there are subtle differences between Firefox for Windows and Firefox for *nix, but I don't know about Thunderbird. If you're using Windows, there might be slight differences between what you see what I see in the menus. I don't know if that helps at all, but that's how I have Thunderbird set up when it comes to threads. Jonathon Alan Gauld wrote: > "Jorge Azedo" wrote >> How do I reply to a specific thread in the mailing list? > > Just hit Reply All. > There should be a command or button in your mail tool > to do that, even if you use web mail. > From pyro9219 at gmail.com Fri Oct 27 08:37:00 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Thu, 26 Oct 2006 23:37:00 -0700 Subject: [Tutor] Why is this only catching one occurance? Message-ID: Here is my code: for unWantedItem in directoryList: try: if "hex" in unWantedItem.lower(): if not "bmc" in unWantedItem.lower(): print unWantedItem + " removed!" directoryList.remove(unWantedItem) This only seems to loop through once, and removes 1 of 2 occurances from this list that should be captured. Should "for" keep the list going through each instance? Thanks alot. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061026/e2614336/attachment.html From rabidpoobear at gmail.com Fri Oct 27 08:38:59 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 27 Oct 2006 01:38:59 -0500 Subject: [Tutor] Why is this only catching one occurance? In-Reply-To: References: Message-ID: <4541A983.1080509@gmail.com> Chris Hengge wrote: > Here is my code: > for unWantedItem in directoryList: > try: > if "hex" in unWantedItem.lower(): > if not "bmc" in unWantedItem.lower(): > print unWantedItem + " removed!" > directoryList.remove(unWantedItem) > > This only seems to loop through once, and removes 1 of 2 occurances > from this list that should be captured. Should "for" keep the list > going through each instance? > You're removing stuff from something you're iterating over! *slaps your fingers with a ruler* Make a copy of the list! HTH, -Luke From finalyugi at sapo.pt Fri Oct 27 09:20:38 2006 From: finalyugi at sapo.pt (rolando) Date: Fri, 27 Oct 2006 08:20:38 +0100 Subject: [Tutor] Mailing list question In-Reply-To: <4541522D.4060506@gmail.com> References: <454115DB.8050104@netcabo.pt> <45411E43.9010600@gmail.com> <454131A8.5050005@netcabo.pt> <454137F4.3050402@sapo.pt> <4541522D.4060506@gmail.com> Message-ID: <4541B346.8000607@sapo.pt> Oh, ok :D Luke Paireepinart escreveu: > rolando wrote: >> I just use the reply button in my Thunderbird, and then change the >> email I want to send to tutor at python.org > It's better to use reply-all, in my opinion, because then, if > someone's involved in an e-mail thread, they'll get an instant > update on it even if they only get the Tutor Digest and not every > individual mail. > Cheers, > -Luke > > From finalyugi at sapo.pt Fri Oct 27 10:57:09 2006 From: finalyugi at sapo.pt (rolando) Date: Fri, 27 Oct 2006 09:57:09 +0100 Subject: [Tutor] Witch gui to choose for this script? Message-ID: <4541C9E5.8040203@sapo.pt> Well, I don't know if I can ask this question here, but never mind that :) It?s like this, I created this python script that translates "human language" to Al-bhed language (it's a language from the game Final Fantasy 10, it's basicly a change in the letters for example A becomes W or B become H). Since I like the script, and it's my first "program", I am now trying to create a GUI for it. So what do you recommend? I'm going to attach the script, just in case you want to see it. -------------- next part -------------- A non-text attachment was scrubbed... Name: tradutor0.4.py Type: text/x-python Size: 1732 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20061027/5d59a1a7/attachment.py From bashu at yandex.ru Fri Oct 27 10:46:25 2006 From: bashu at yandex.ru (Basil Shubin) Date: Fri, 27 Oct 2006 15:46:25 +0700 Subject: [Tutor] Python and config files? In-Reply-To: <4540B700.8070109@tds.net> References: <4540AE52.7010307@yandex.ru> <4540B700.8070109@tds.net> Message-ID: <4541C761.5010805@yandex.ru> Kent Johnson ?????: > Basil Shubin wrote: >> Hi, friends! >> >> Is there exist a module for working with config file? Simple enough, >> just read/write config file (like for most unix app), determine where >> row is contain config words with it's parameters (like >> 'config_word=parameter') or it's a comments (#)? > > Take a look at the ConfigParser module: > http://docs.python.org/lib/module-ConfigParser.html Thanks! Exactly what I need! -- Basil Shubin Freelance Software Developer From rabidpoobear at gmail.com Fri Oct 27 11:13:17 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 27 Oct 2006 04:13:17 -0500 Subject: [Tutor] Witch gui to choose for this script? In-Reply-To: <4541C9E5.8040203@sapo.pt> References: <4541C9E5.8040203@sapo.pt> Message-ID: <4541CDAD.2090001@gmail.com> rolando wrote: > Well, I don't know if I can ask this question here, but never mind > that :) > > It?s like this, I created this python script that translates "human > language" to Al-bhed language (it's a language from the game Final > Fantasy 10, it's basicly a change in the letters for example A becomes > W or B become H). > > Since I like the script, and it's my first "program", I am now trying > to create a GUI for it. > > So what do you recommend? > I don't think something like this lends itself to a particular GUI set, so the question I have to ask you is: Do you feel lucky? Just kidding. It's really up to you on this one. TKInter would probably be easier to learn, since it's your first program. You could go the route of a GUI builder such as Boa Constructor, but I'd recommend that you learn how to use a GUI toolkit before you use a builder, so that you know exactly what the builder is automating for you. However, are you sure you want to jump into a GUI right now? If you're just going for a simple two-textbox, one button, 'type here, hit the button, and the translated text appears in the other box' type thing, and not something fancy, I guess it's about as simple of an introduction to a GUI toolkit as you can get, aside from a label that says "Hello, World" or other such thing. Just remember that it's important that you have a firm understanding of python's built-ins, and I guess Python in general, before you start trying to use a big external package like a GUI toolkit, and a little up-front time learning the basics will help you a great deal in the long run. >I'm going to attach the script, just in case you want to see it. Good job on attaching the script! I did want to see it. I can't read the comments, though, but I think I got what it was doing. Good luck in whatever you choose to do. -Luke From duncan at thermal.esa.int Fri Oct 27 11:35:40 2006 From: duncan at thermal.esa.int (Duncan Gibson) Date: Fri, 27 Oct 2006 11:35:40 +0200 Subject: [Tutor] line number when reading files using csv module Message-ID: <20061027093540.9F5DD202C@zeeman.thermal.esa.int> If I have the following data file, data.csv: 1 2 3 2 3 4 5 then I can read it in Python 2.4 on linux using: import csv f = file('data.csv', 'rb') reader = csv.reader(f) for data in reader: print data OK, that's all well and good, but I would like to record the line number in the file. According to the documentation, each reader object has a public 'line_num' attribute http://docs.python.org/lib/node265.html and http://docs.python.org/lib/csv-examples.html supports this. If I now change the loop to read: for data in reader: print reader.line_num, data I'm presented with the error: AttributeError: '_csv.reader' object has no attribute 'line_num' This has floored me. I've even looked at the source code and I can see the line_num variable in the underlying _csv.c file. I can even see the test_csv.py code that checks it! def test_read_linenum(self): r = csv.reader(['line,1', 'line,2', 'line,3']) self.assertEqual(r.line_num, 0) I suspect this is something so obvious that I just can't see the wood for the trees and I will kick myself. Any ideas? Cheers Duncan From finalyugi at sapo.pt Fri Oct 27 11:36:23 2006 From: finalyugi at sapo.pt (rolando) Date: Fri, 27 Oct 2006 10:36:23 +0100 Subject: [Tutor] Witch gui to choose for this script? In-Reply-To: <4541CDAD.2090001@gmail.com> References: <4541C9E5.8040203@sapo.pt> <4541CDAD.2090001@gmail.com> Message-ID: <4541D317.2040504@sapo.pt> > If you're just going for a simple two-textbox, one button, 'type here, > hit the button, and the translated text appears in the other box' Yeah, its something like that :D Nothing to much fancy, it just that it can get kind of boring always going to the linux console to run the script. I'm going to try the Boa Contructor. > > >I'm going to attach the script, just in case you want to see it. > Good job on attaching the script! > I did want to see it. > I can't read the comments, though, but I think I got what it was doing. Yeah, I kind of forgot to translate the comments. Now I have attached the script with the translated comments. Also any comments about the program are welcome. Luke Paireepinart escreveu: > rolando wrote: >> Well, I don't know if I can ask this question here, but never mind >> that :) >> >> It?s like this, I created this python script that translates "human >> language" to Al-bhed language (it's a language from the game Final >> Fantasy 10, it's basicly a change in the letters for example A >> becomes W or B become H). >> >> Since I like the script, and it's my first "program", I am now trying >> to create a GUI for it. >> >> So what do you recommend? >> > I don't think something like this lends itself to a particular GUI set, > so the question I have to ask you is: > Do you feel lucky? > > Just kidding. > It's really up to you on this one. > TKInter would probably be easier to learn, since it's your first program. > You could go the route of a GUI builder such as Boa Constructor, but > I'd recommend that you learn > how to use a GUI toolkit before you use a builder, so that you know > exactly what the builder is automating for you. > > However, are you sure you want to jump into a GUI right now? > If you're just going for a simple two-textbox, one button, 'type here, > hit the button, and the translated text appears in the other box' > type thing, and not something fancy, I guess it's about as simple of > an introduction to a GUI toolkit as you can get, aside from a > label that says "Hello, World" or other such thing. > Just remember that it's important that you have a firm understanding > of python's built-ins, and I guess Python in general, > before you start trying to use a big external package like a GUI > toolkit, and a little up-front time learning the basics will help you > a great deal in the long run. > > >I'm going to attach the script, just in case you want to see it. > Good job on attaching the script! > I did want to see it. > I can't read the comments, though, but I think I got what it was doing. > > Good luck in whatever you choose to do. > -Luke > > -------------- next part -------------- A non-text attachment was scrubbed... Name: tradutor0.4-translated.py Type: text/x-python Size: 1821 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20061027/c063fe96/attachment.py From euoar at yahoo.es Fri Oct 27 11:51:07 2006 From: euoar at yahoo.es (euoar) Date: Fri, 27 Oct 2006 11:51:07 +0200 Subject: [Tutor] database question Message-ID: <4541D68B.1020809@yahoo.es> I'm learning to use python with the database mysql. I'm writing a widget in pygtk that should show the results of a sql query. For example with "SELECT * FROM a", I use this code count = 0 a = db.cursor.description for tuple in a: print tuple[0][0] count = count + 1 ... to know how many columns are in the result, and then, what I have to do is to create a liststore with "count" columns. The method to create a ListStore is: liststore = gtk.ListStore(str, str, str, ...[number of columns]). I was wondering how to create the liststore with the proper number of columns, if there would a way to do something like this with python: # to store the number of columns that will be needed count = 0 a = db.cursor.description for tuple in a: print tuple[0][0] count = count + 1 # this is the string with the method to execute method_string = "gtk.ListStore(" for var in range(count): method_string = function_string + "str," function_string = function_string + ")" # is there something like this "execute_function"? list_store = execute_function(method_string) Thank you very much for your advices. ______________________________________________ LLama Gratis a cualquier PC del Mundo. Llamadas a fijos y m?viles desde 1 c?ntimo por minuto. http://es.voice.yahoo.com From kent37 at tds.net Fri Oct 27 11:52:20 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 27 Oct 2006 05:52:20 -0400 Subject: [Tutor] Witch gui to choose for this script? In-Reply-To: <4541C9E5.8040203@sapo.pt> References: <4541C9E5.8040203@sapo.pt> Message-ID: <4541D6D4.4030000@tds.net> rolando wrote: > Well, I don't know if I can ask this question here, but never mind that :) Yes, it's fine. > > It?s like this, I created this python script that translates "human > language" to Al-bhed language (it's a language from the game Final > Fantasy 10, it's basicly a change in the letters for example A becomes W > or B become H). > > Since I like the script, and it's my first "program", I am now trying to > create a GUI for it. > > So what do you recommend? I think Tkinter is the easiest to get started with. You might also like to try PythonCard which is a wrapper around wxPython that makes it easier to use. > > I'm going to attach the script, just in case you want to see it. I have a few comments below. > > > ------------------------------------------------------------------------ > > #!/usr/bin/python > #V 0.4 > import string > > contador = "s" # Cria um contador que verifica que deve ou nao executar o script > > while contador.lower() == "s" or contador.lower() == "sim": # Enquanto o valor for "s" ou "sim" o programa nao sai (converte a palavra em minusculas) > > print "Escolhe a lingua que queres traduzir. [p]ortugues ou [a]l-bhed" > > lingua = raw_input() # Escolhe a lingua > > if lingua.isspace() == True: # Se "lingua" e constituida por espacos em branco > > print "Tens de escrever alguma coisa ok?" > > if lingua == "": # Se lingua estiver vazia > > print "Tens de escrever alguma coisa ok?" These two tests could be combined into if not lingua.strip(): print "Tens de escrever alguma coisa ok?" > > if lingua.lower() == "a" or lingua.lower() == "al-bhed": > lista = string.maketrans('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', 'epstiwknuvgclrybxhmdofzqajEPSTIWKNUVGCLRYBXHMDOFZQAJ') # Cria a lista de palavra e de que maneira vao ser trocadas > > print "Escreve a palavra que queres traduzir." > > palavra = raw_input() # Pede por uma palavra > > print "" + palavra.translate(lista) + "" # Imprime as palavras trocadas > > if lingua.lower() == "p" or lingua.lower() == "portugues": > lista = string.maketrans('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', 'ypltavkrezgmshubxncdijfqowYPLTAVkREZGMSHUBXNCDIJFQOW') # Cria a lista de palavra e de que maneira vao ser trocadas I would define the two listas outside the loop at the top of the program and give them more descriptive names like portugueseToAlBled. I think it would make the loop easier to read. Kent > > print "Escreve a palavra que queres traduzir." > > palavra = raw_input() # Pede por uma palavra > > print "" + palavra.translate(lista) + "" # Imprime as palavras trocadas You don't need the extra "", just print palavra.translate(lista). Kent > > > print "Ainda tens mais alguma coisa para traduzir? [S/N]" > > contador = raw_input() # Modifica o contador que esta inicio do script > > if contador.lower() == "n" or contador.lower() == "nao": # Se contador igual a "n" ou "nao" minusculos > print "Entao adeus." > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From duncan at thermal.esa.int Fri Oct 27 11:52:55 2006 From: duncan at thermal.esa.int (Duncan Gibson) Date: Fri, 27 Oct 2006 11:52:55 +0200 Subject: [Tutor] line number when reading files using csv module In-Reply-To: <20061027093540.9F5DD202C@zeeman.thermal.esa.int> References: <20061027093540.9F5DD202C@zeeman.thermal.esa.int> Message-ID: <20061027115255.1a438e06.duncan@thermal.esa.int> On Fri, 27 Oct 2006 11:35:40 +0200 Duncan Gibson wrote: > > If I have the following data file, data.csv: > 1 2 3 > 2 3 4 5 > > then I can read it in Python 2.4 on linux using: > > import csv > f = file('data.csv', 'rb') > reader = csv.reader(f) > for data in reader: > print data Oops, mixing examples here. I forgot to say that I'm actually using reader = csv.reader(f, delimiter=' ') so it will read the data correctly even if there isn't a comma in sight in the csv file, but that's a side issue to the line number problem. Cheers Duncan From kent37 at tds.net Fri Oct 27 12:02:33 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 27 Oct 2006 06:02:33 -0400 Subject: [Tutor] Why is this only catching one occurance? In-Reply-To: References: Message-ID: <4541D939.7080303@tds.net> Chris Hengge wrote: > Here is my code: > for unWantedItem in directoryList: > try: > if "hex" in unWantedItem.lower(): > if not "bmc" in unWantedItem.lower(): > print unWantedItem + " removed!" > directoryList.remove(unWantedItem) > > This only seems to loop through once, and removes 1 of 2 occurances from > this list that should be captured. Should "for" keep the list going > through each instance? The problem is that when you remove the item from the list, the iterator that is looping over the list gets confused and skips the next item. (The iterator keeps an internal counter that is not updated when you remove an item.) See http://effbot.org/zone/python-list.htm#modifying for more. The simplest fix is to use a list comprehension to create a new list with only the elements you want, and assign it to the same name: directoryList = [ item for item in directoryList if 'hex not in item.lower() or 'bmc' in item.lower() ] Note I changed the sense of the conditional because it is now selecting items to include. The list comp doesn't have exactly the same result as your (intended) code, it creates a new list rather than modifying the old one in place. Most of the time this doesn't matter but if you have other references to dictionaryList only one will be changed. Kent From kent37 at tds.net Fri Oct 27 12:11:16 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 27 Oct 2006 06:11:16 -0400 Subject: [Tutor] line number when reading files using csv module In-Reply-To: <20061027093540.9F5DD202C@zeeman.thermal.esa.int> References: <20061027093540.9F5DD202C@zeeman.thermal.esa.int> Message-ID: <4541DB44.5070206@tds.net> Duncan Gibson wrote: > If I have the following data file, data.csv: > 1 2 3 > 2 3 4 5 > > then I can read it in Python 2.4 on linux using: > > import csv > f = file('data.csv', 'rb') > reader = csv.reader(f) > for data in reader: > print data > > OK, that's all well and good, but I would like to record > the line number in the file. According to the documentation, > each reader object has a public 'line_num' attribute > http://docs.python.org/lib/node265.html and > http://docs.python.org/lib/csv-examples.html supports this. > > If I now change the loop to read: > > for data in reader: > print reader.line_num, data > > I'm presented with the error: > AttributeError: '_csv.reader' object has no attribute 'line_num' The line_num attribute is new in Python 2.5. This is a doc bug, it should be noted in the description of line_num. Kent From ajkadri at googlemail.com Fri Oct 27 12:24:00 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Fri, 27 Oct 2006 11:24:00 +0100 Subject: [Tutor] XML parsing in Python.. resources needed Message-ID: Hi Folks, ANy comments about ELementTree module... I have heard that it is more 'Pythonic'... I need some basic examples to start learning the stuff.. If anyone has got the information, please pass it along.. Thanks. Regards, Asrarahmed Kadri -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061027/825e1e08/attachment.html From kent37 at tds.net Fri Oct 27 13:16:06 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 27 Oct 2006 07:16:06 -0400 Subject: [Tutor] XML parsing in Python.. resources needed In-Reply-To: References: Message-ID: <4541EA76.6070908@tds.net> Asrarahmed Kadri wrote: > > > Hi Folks, > > ANy comments about ELementTree module... > > I have heard that it is more 'Pythonic'... > > I need some basic examples to start learning the stuff.. If anyone has > got the information, please pass it along.. http://effbot.org/zone/element.htm Kent From ajkadri at googlemail.com Fri Oct 27 13:30:33 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Fri, 27 Oct 2006 12:30:33 +0100 Subject: [Tutor] I am terribly confused about "generators" and "iterators".. Help me Message-ID: Hi Folks, What are generators and iterators...??And why are they are needed..?? I can do my stuff with a 'for' or a 'while' loop.. so why do I need an ITERATOR..? And what is a generator ..? I did try to read about these two things on the web, but still I AM CONFUSED. To be honest, I am used to the nice and lucid style of the wonderful people on this forum.. :)- Regards, Asrarahmed Kadri -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061027/83b8a2c7/attachment.htm From euoar at yahoo.es Fri Oct 27 14:03:19 2006 From: euoar at yahoo.es (euoar) Date: Fri, 27 Oct 2006 14:03:19 +0200 Subject: [Tutor] [pygtk] ListStore question In-Reply-To: <453FEBB5.4060409@yahoo.es> References: <453DDA64.3030004@yahoo.es> <453FC171.2000507@free.fr> <453FEBB5.4060409@yahoo.es> Message-ID: <4541F587.2040604@yahoo.es> euoar escribi?: > mc collilieux escribi?: >> euoar wrote: >> >>>> I'm learning the use of liststores and treeviews. I have wrotten >>>> this litle class as exercice: >> >> >>>> # name is the name of the new column to add, values is a tuple with >>>> the values to add def add_result (self, name, values): self.iter = >>>> self.liststore.append(values[0]) for value in values: >>>> self.liststore.insert_after(self.iter, value) >> >> >> rereading the tutorial, I note "...The row parameter specifies the data >> that should be inserted in the row after it is created ... If row is >> specified it must be a tuple or list containing as many items as the >> number of columns in the ListStore...so >> >> self.liststore.insert_after(self.iter, [value]) >> >> Hope it's the good answer... >> >> PS : sorry for the answer directly to your mail. too quickly clic >> > That's exactly the solution. It has to be a tuple. Thank you very much > for your help! > > > ______________________________________________ LLama Gratis a > cualquier PC del Mundo. Llamadas a fijos y m?viles desde 1 c?ntimo por > minuto. http://es.voice.yahoo.com > _______________________________________________ > pygtk mailing list pygtk at daa.com.au > http://www.daa.com.au/mailman/listinfo/pygtk > Read the PyGTK FAQ: http://www.async.com.br/faq/pygtk/ > I think I have the solution (I'm answering myself to avoid people to waste time thinking in my question): args = [str, str, str] gtk.ListStore(*args) ______________________________________________ LLama Gratis a cualquier PC del Mundo. Llamadas a fijos y m?viles desde 1 c?ntimo por minuto. http://es.voice.yahoo.com From duncan at thermal.esa.int Fri Oct 27 14:25:28 2006 From: duncan at thermal.esa.int (Duncan Gibson) Date: Fri, 27 Oct 2006 14:25:28 +0200 Subject: [Tutor] line number when reading files using csv module In-Reply-To: Your message of "Fri, 27 Oct 2006 06:11:16 EDT." <4541DB44.5070206@tds.net> Message-ID: <20061027122528.79E48202C@zeeman.thermal.esa.int> Kent Johnson wrote: > The line_num attribute is new in Python 2.5. This is a doc bug, > it should be noted in the description of line_num. Is there some way to create a wrapper around a 2.4 csv.reader to give me pseudo line number handling? I've been experimenting with: import csv class MyReader(object): def __init__(self, inputFile): self.reader = csv.reader(inputFile, delimiter=' ') self.lineNumber = 0 def __iter__(self): self.lineNumber += 1 return self.reader.__iter__() def next(self): self.lineNumber += 1 # do I need this one? return self.reader.next() if __name__ == '__main__': inputFile = file('data.csv', 'rb') reader = MyReader(inputFile) for data in reader: print reader.lineNumber, data But that doesn't seem to do what I want. If I add some print statements to the methods, I can see that it calls __iter__ only once: __iter__ 1 ['1', '2', '3'] 1 ['2', '3', '4', '5'] 1 ['3', '4', '5', '6', '7'] 1 ['4', '5', '6', '7'] 1 ['5', '6', '7', '8', '9'] Is there some other __special__ method that I need to forward to the csv.reader, or have I lost all control once __iter__ has done its job? Cheers Duncan From kent37 at tds.net Fri Oct 27 14:53:31 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 27 Oct 2006 08:53:31 -0400 Subject: [Tutor] line number when reading files using csv module In-Reply-To: <20061027122528.79E48202C@zeeman.thermal.esa.int> References: <20061027122528.79E48202C@zeeman.thermal.esa.int> Message-ID: <4542014B.7000100@tds.net> Duncan Gibson wrote: > > Kent Johnson wrote: >> The line_num attribute is new in Python 2.5. This is a doc bug, >> it should be noted in the description of line_num. > > Is there some way to create a wrapper around a 2.4 csv.reader to > give me pseudo line number handling? I've been experimenting with: > > import csv > > class MyReader(object): > > def __init__(self, inputFile): > self.reader = csv.reader(inputFile, delimiter=' ') > self.lineNumber = 0 > > def __iter__(self): > self.lineNumber += 1 > return self.reader.__iter__() __iter__() should return self, not self.reader.__iter__(), otherwise Python is using the actual csv.reader not your wrapper. And don't increment line number here. > > def next(self): > self.lineNumber += 1 # do I need this one? Yes. > return self.reader.next() An easier way to do this is to use enumerate(): inputFile = file('data.csv', 'rb') reader = csv.reader(inputFile) for i, data in enumerate(reader): print i, data Of course this will not necessarily give you the true line number, as a record may span multiple file lines and you may be processing header and blank lines at the start of the file before you get any records. But it is probably the best you can do and maybe it is what you need. > > if __name__ == '__main__': > inputFile = file('data.csv', 'rb') > reader = MyReader(inputFile) > for data in reader: > print reader.lineNumber, data > > But that doesn't seem to do what I want. If I add some print statements > to the methods, I can see that it calls __iter__ only once: __iter__() will only be called once, it is next() that is called multiple times. > > __iter__ > 1 ['1', '2', '3'] > 1 ['2', '3', '4', '5'] > 1 ['3', '4', '5', '6', '7'] > 1 ['4', '5', '6', '7'] > 1 ['5', '6', '7', '8', '9'] > > Is there some other __special__ method that I need to forward to the > csv.reader, or have I lost all control once __iter__ has done its job? You lost control because you gave it away. Kent > > Cheers > Duncan > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From nephish at gmail.com Fri Oct 27 15:01:32 2006 From: nephish at gmail.com (shawn bright) Date: Fri, 27 Oct 2006 08:01:32 -0500 Subject: [Tutor] [pygtk] ListStore question In-Reply-To: <4541F587.2040604@yahoo.es> References: <453DDA64.3030004@yahoo.es> <453FC171.2000507@free.fr> <453FEBB5.4060409@yahoo.es> <4541F587.2040604@yahoo.es> Message-ID: <384c93600610270601n63d389b1y57af0149993176f1@mail.gmail.com> this is cool, ill give it a shot sk On 10/27/06, euoar wrote: > > euoar escribi?: > > mc collilieux escribi?: > >> euoar wrote: > >> > >>>> I'm learning the use of liststores and treeviews. I have wrotten > >>>> this litle class as exercice: > >> > >> > >>>> # name is the name of the new column to add, values is a tuple with > >>>> the values to add def add_result (self, name, values): self.iter = > >>>> self.liststore.append(values[0]) for value in values: > >>>> self.liststore.insert_after(self.iter, value) > >> > >> > >> rereading the tutorial, I note "...The row parameter specifies the data > >> that should be inserted in the row after it is created ... If row is > >> specified it must be a tuple or list containing as many items as the > >> number of columns in the ListStore...so > >> > >> self.liststore.insert_after(self.iter, [value]) > >> > >> Hope it's the good answer... > >> > >> PS : sorry for the answer directly to your mail. too quickly clic > >> > > That's exactly the solution. It has to be a tuple. Thank you very much > > for your help! > > > > > > ______________________________________________ LLama Gratis a > > cualquier PC del Mundo. Llamadas a fijos y m?viles desde 1 c?ntimo por > > minuto. http://es.voice.yahoo.com > > _______________________________________________ > > pygtk mailing list pygtk at daa.com.au > > http://www.daa.com.au/mailman/listinfo/pygtk > > Read the PyGTK FAQ: http://www.async.com.br/faq/pygtk/ > > > I think I have the solution (I'm answering myself to avoid people to > waste time thinking in my question): > > args = [str, str, str] > gtk.ListStore(*args) > > > ______________________________________________ > LLama Gratis a cualquier PC del Mundo. > Llamadas a fijos y m?viles desde 1 c?ntimo por minuto. > http://es.voice.yahoo.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061027/0eec1d1e/attachment.htm From etrade.griffiths at dsl.pipex.com Fri Oct 27 15:12:12 2006 From: etrade.griffiths at dsl.pipex.com (Etrade Griffiths) Date: Fri, 27 Oct 2006 14:12:12 +0100 Subject: [Tutor] Getting the type of a variable Message-ID: <6.1.2.0.2.20061027140707.03e54520@pop.dsl.pipex.com> Hi I want to check the type of a variable so that I know which format to use for printing eg def print_correct_format(a): if type(a) == 'int': print "a is an integer, value %i" % (a) elif type(a) == 'float': print "a is a float, value %f" % (a) else: print "a is unknown type" The comparison type(a) == 'int' etc does not work - I'm sure there's a simple way to fix this but can't see it at the moment - any suggestions? From gtnorton at earthlink.net Fri Oct 27 15:22:41 2006 From: gtnorton at earthlink.net (Glenn T Norton) Date: Fri, 27 Oct 2006 08:22:41 -0500 Subject: [Tutor] Getting the type of a variable In-Reply-To: <6.1.2.0.2.20061027140707.03e54520@pop.dsl.pipex.com> References: <6.1.2.0.2.20061027140707.03e54520@pop.dsl.pipex.com> Message-ID: <45420821.2090304@earthlink.net> Etrade Griffiths wrote: >Hi > >I want to check the type of a variable so that I know which format to use >for printing eg > >def print_correct_format(a): > > if type(a) == 'int': > print "a is an integer, value %i" % (a) > elif type(a) == 'float': > print "a is a float, value %f" % (a) > else: > print "a is unknown type" > >The comparison type(a) == 'int' etc does not work - I'm sure there's a >simple way to fix this but can't see it at the moment - any suggestions? > > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > > You have two options here, but the idea is, you have to compare type to type, not type to string say a is an integer a = 5 type(a) == type(1) True or a is a string type(a) == type('') or you can use the types module import types x = 1 type(x) == types.IntType True x = 'String' type(x) == types.StringType True Good Luck, Glenn -- "Ketchup. For the good times... " - Ketchup Advisory Board Glenn Norton Application Developer Nebraska.gov 1-402-471-2777 glenn at nebraska.gov From kent37 at tds.net Fri Oct 27 15:26:40 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 27 Oct 2006 09:26:40 -0400 Subject: [Tutor] Getting the type of a variable In-Reply-To: <6.1.2.0.2.20061027140707.03e54520@pop.dsl.pipex.com> References: <6.1.2.0.2.20061027140707.03e54520@pop.dsl.pipex.com> Message-ID: <45420910.1090005@tds.net> Etrade Griffiths wrote: > Hi > > I want to check the type of a variable so that I know which format to use > for printing eg > > def print_correct_format(a): > > if type(a) == 'int': > print "a is an integer, value %i" % (a) > elif type(a) == 'float': > print "a is a float, value %f" % (a) > else: > print "a is unknown type" > > The comparison type(a) == 'int' etc does not work - I'm sure there's a > simple way to fix this but can't see it at the moment - any suggestions? You need to compare to the actual type, not the name of the type: if type(a) == int: or if type(a) == float: You could also use if isinstance(a, int): which will succeed if a is an instance of a subclass of int as well. Kent From ajkadri at googlemail.com Fri Oct 27 15:27:09 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Fri, 27 Oct 2006 14:27:09 +0100 Subject: [Tutor] Getting the type of a variable In-Reply-To: <6.1.2.0.2.20061027140707.03e54520@pop.dsl.pipex.com> References: <6.1.2.0.2.20061027140707.03e54520@pop.dsl.pipex.com> Message-ID: Use this: if type(a) == type(1): print "a is int %d" elif type(a) == type(1.1): ....... HTH.. Regards, Asrarahmed Kadri On 10/27/06, Etrade Griffiths wrote: > > Hi > > I want to check the type of a variable so that I know which format to use > for printing eg > > def print_correct_format(a): > > if type(a) == 'int': > print "a is an integer, value %i" % (a) > elif type(a) == 'float': > print "a is a float, value %f" % (a) > else: > print "a is unknown type" > > The comparison type(a) == 'int' etc does not work - I'm sure there's a > simple way to fix this but can't see it at the moment - any suggestions? > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061027/b4ee2547/attachment.html From etrade.griffiths at dsl.pipex.com Fri Oct 27 16:24:29 2006 From: etrade.griffiths at dsl.pipex.com (Etrade Griffiths) Date: Fri, 27 Oct 2006 15:24:29 +0100 Subject: [Tutor] Getting the type of a variable In-Reply-To: References: <6.1.2.0.2.20061027140707.03e54520@pop.dsl.pipex.com> Message-ID: <6.1.2.0.2.20061027152346.03e50720@pop.dsl.pipex.com> Thanks, guys - like so many things, easy when you know how! Alun Griffiths At 14:27 27/10/2006, you wrote: >Use this: > >if type(a) == type(1): > print "a is int %d" >elif type(a) == type(1.1): > ....... > >HTH.. >Regards, >Asrarahmed Kadri > > > >On 10/27/06, Etrade Griffiths ><etrade.griffiths at dsl.pipex.com> wrote: >Hi > >I want to check the type of a variable so that I know which format to use >for printing eg > >def print_correct_format(a): > > if type(a) == 'int': > print "a is an integer, value %i" % (a) > elif type(a) == 'float': > print "a is a float, value %f" % (a) > else: > print "a is unknown type" > >The comparison type(a) == 'int' etc does not work - I'm sure there's a >simple way to fix this but can't see it at the moment - any suggestions? > > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > > > > >-- >To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061027/a1c8a15a/attachment.html From bgailer at alum.rpi.edu Fri Oct 27 18:03:29 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri, 27 Oct 2006 09:03:29 -0700 Subject: [Tutor] Why is this only catching one occurance? In-Reply-To: References: Message-ID: <45422DD1.6010006@alum.rpi.edu> Chris Hengge wrote: > Here is my code: > for unWantedItem in directoryList: > try: > if "hex" in unWantedItem.lower(): > if not "bmc" in unWantedItem.lower(): > print unWantedItem + " removed!" > directoryList.remove(unWantedItem) > > This only seems to loop through once, and removes 1 of 2 occurances > from this list that should be captured. Should "for" keep the list > going through each instance? "for" goes thru the list accessing item[0], item[1], item[2], etc. Let's say "for" is on item[1] and you remove item[1]. All the subsequent items "move left", so item[2] becomes item[1], item[3] becomes item[2], etc. "for" then steps to item[2], skipping the original item[2]. There are several ways around this. The easiest is to process the list backwards: for unWantedItem in directoryList[,,-1]: -- Bob Gailer 510-978-4454 From bgailer at alum.rpi.edu Fri Oct 27 18:10:46 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri, 27 Oct 2006 09:10:46 -0700 Subject: [Tutor] I am terribly confused about "generators" and "iterators".. Help me In-Reply-To: References: Message-ID: <45422F86.1070401@alum.rpi.edu> Asrarahmed Kadri wrote: > > > Hi Folks, > > What are generators and iterators...??And why are they are needed..?? > > I can do my stuff with a 'for' or a 'while' loop.. so why do I need an > ITERATOR..? iterators & generators do not replace while or for loops! > > And what is a generator ..? I did try to read about these two things > on the web, but still I AM CONFUSED. Well at risk of offering more web stuff, try http://heather.cs.ucdavis.edu/~matloff/Python/PyIterGen.pdf > > To HIM you shall return. I am glad that this thought brings you some comfort or stimulation. I used to believe something similar, and all it did was bring me fear guilt and shame. -- Bob Gailer 510-978-4454 From bgailer at alum.rpi.edu Fri Oct 27 18:18:26 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri, 27 Oct 2006 09:18:26 -0700 Subject: [Tutor] line number when reading files using csv module In-Reply-To: <20061027093540.9F5DD202C@zeeman.thermal.esa.int> References: <20061027093540.9F5DD202C@zeeman.thermal.esa.int> Message-ID: <45423152.6060904@alum.rpi.edu> Duncan Gibson wrote: > If I have the following data file, data.csv: > 1 2 3 > 2 3 4 5 > > then I can read it in Python 2.4 on linux using: > > import csv > f = file('data.csv', 'rb') > reader = csv.reader(f) > for data in reader: > print data > > OK, that's all well and good, but I would like to record > the line number in the file. According to the documentation, > each reader object has a public 'line_num' attribute > http://docs.python.org/lib/node265.html and > http://docs.python.org/lib/csv-examples.html supports this. > > If I now change the loop to read: > > for data in reader: > print reader.line_num, data > > I'm presented with the error: > AttributeError: '_csv.reader' object has no attribute 'line_num' > Well I get the same exception. dir(reader) does not show line_num. > This has floored me. I've even looked at the source code and I can > see the line_num variable in the underlying _csv.c file. I can even > see the test_csv.py code that checks it! > > def test_read_linenum(self): > r = csv.reader(['line,1', 'line,2', 'line,3']) > self.assertEqual(r.line_num, 0) > > I suspect this is something so obvious that I just can't see the > wood for the trees and I will kick myself. > > Any ideas? > > Cheers > Duncan > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Bob Gailer 510-978-4454 From kent37 at tds.net Fri Oct 27 18:35:13 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 27 Oct 2006 12:35:13 -0400 Subject: [Tutor] I am terribly confused about "generators" and "iterators".. Help me In-Reply-To: <45422F86.1070401@alum.rpi.edu> References: <45422F86.1070401@alum.rpi.edu> Message-ID: <45423541.4020306@tds.net> Bob Gailer wrote: > Asrarahmed Kadri wrote: >> >> What are generators and iterators...??And why are they are needed..?? >> >> I can do my stuff with a 'for' or a 'while' loop.. so why do I need an >> ITERATOR..? > iterators & generators do not replace while or for loops! No, actually iterators and generators are the foundation of for loops. Whenever you write a for loop, Python creates an iterator to return the values that are assigned to the loop variables. Writing your own iterator is a way to make a new kind of thing that can be iterated in a for loop. Generators are a convenient way to make iterators. They can be used to encapsulate loop logic. For some examples see these recent threads: http://thread.gmane.org/gmane.comp.python.tutor/36068/focus=36069 http://article.gmane.org/gmane.comp.python.tutor/36105/match=generator >> >> And what is a generator ..? I did try to read about these two things >> on the web, but still I AM CONFUSED. > Well at risk of offering more web stuff, try > http://heather.cs.ucdavis.edu/~matloff/Python/PyIterGen.pdf Thanks, that is very nice! Kent >> To HIM you shall return. > I am glad that this thought brings you some comfort or stimulation. I > used to believe something similar, and all it did was bring me fear > guilt and shame. > > From David.Heiser at intelliden.com Fri Oct 27 18:41:51 2006 From: David.Heiser at intelliden.com (David Heiser) Date: Fri, 27 Oct 2006 10:41:51 -0600 Subject: [Tutor] I am terribly confused about "generators" and "iterators".. Help me Message-ID: May I invite EVERYONE to NOT introduce political or religious elements into these discussions. It has no place here and can destroy this excellent discussion group. I've seen it happen. PLEASE take it elsewhere. -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Bob Gailer Sent: Friday, October 27, 2006 10:11 AM To: Asrarahmed Kadri Cc: pythontutor Subject: Re: [Tutor] I am terribly confused about "generators" and "iterators".. Help me Asrarahmed Kadri wrote: > > > Hi Folks, > > What are generators and iterators...??And why are they are needed..?? > > I can do my stuff with a 'for' or a 'while' loop.. so why do I need an > ITERATOR..? iterators & generators do not replace while or for loops! > > And what is a generator ..? I did try to read about these two things > on the web, but still I AM CONFUSED. Well at risk of offering more web stuff, try http://heather.cs.ucdavis.edu/~matloff/Python/PyIterGen.pdf > > To HIM you shall return. I am glad that this thought brings you some comfort or stimulation. I used to believe something similar, and all it did was bring me fear guilt and shame. -- Bob Gailer 510-978-4454 _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From std3rr at gmail.com Fri Oct 27 20:06:50 2006 From: std3rr at gmail.com (Joshua Simpson) Date: Fri, 27 Oct 2006 11:06:50 -0700 Subject: [Tutor] Getting the type of a variable In-Reply-To: <6.1.2.0.2.20061027152346.03e50720@pop.dsl.pipex.com> References: <6.1.2.0.2.20061027140707.03e54520@pop.dsl.pipex.com> <6.1.2.0.2.20061027152346.03e50720@pop.dsl.pipex.com> Message-ID: <3ed9caa10610271106r2d2ae570vd864e5314c52f3f2@mail.gmail.com> > > > On 10/27/06, *Etrade Griffiths* wrote: > Hi > > I want to check the type of a variable so that I know which format to use > for printing eg > > Alternatively, you could just cast it as a string. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061027/fcc3e666/attachment.html From wescpy at gmail.com Fri Oct 27 20:32:53 2006 From: wescpy at gmail.com (wesley chun) Date: Fri, 27 Oct 2006 11:32:53 -0700 Subject: [Tutor] Getting the type of a variable In-Reply-To: <3ed9caa10610271106r2d2ae570vd864e5314c52f3f2@mail.gmail.com> References: <6.1.2.0.2.20061027140707.03e54520@pop.dsl.pipex.com> <6.1.2.0.2.20061027152346.03e50720@pop.dsl.pipex.com> <3ed9caa10610271106r2d2ae570vd864e5314c52f3f2@mail.gmail.com> Message-ID: <78b3a9580610271132k6fada252qd5e188bd68c5d622@mail.gmail.com> > > I want to check the type of a variable so that I know which format to use > > for printing eg > > > Alternatively, you could just cast it as a string. what joshua is saying is that for just displaying something, that it's just as easy to convert it to a string, or, if you're using print, to not do anything at all (since objects which are part of print statements are automagically sent to str()), e.g., print "a is a number with a value of", a # no need to convert a as many others have pointed out, using type() works too, but "type(x) is type(0)" works slightly faster than "type(x) == type(0)" ... can any non-tutors guess why? also, isinstance() works great if you want to do multi-compares. for example, here's a snippet out of chapter 4 in my book: def displayNumType(num): print num, 'is', if isinstance(num, (int, long, float, complex)): print 'a number of type:', type(num).__name__ else: print 'not a number at all!!' displayNumType(-69) displayNumType(9999999999999999999999L) displayNumType(98.6) displayNumType(-5.2+1.9j) displayNumType('xxx') when you run it, you get: -69 is a number of type: int 9999999999999999999999 is a number of type: long 98.6 is a number of type: float (-5.2+1.9j) is a number of type: complex xxx is not a number at all!! the good news is that isinstance() means only one function call, and it's pretty fast. if there's any downside of isinstance(), and it's pretty minor -- well, perhaps it's a feature -- is that it is *not* a direct type/class comparison, meaning that subclasses will match too: >>> isinstance(1, object) True >>> isinstance('xxx', object) True anyway, hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From bgailer at alum.rpi.edu Fri Oct 27 20:42:35 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri, 27 Oct 2006 11:42:35 -0700 Subject: [Tutor] line number when reading files using csv module In-Reply-To: <20061027093540.9F5DD202C@zeeman.thermal.esa.int> References: <20061027093540.9F5DD202C@zeeman.thermal.esa.int> Message-ID: <4542531B.2090609@alum.rpi.edu> Duncan Gibson wrote: > [snip] > but I would like to record the line number in the file. > How about using enumerate(): > > for line_num, data in enumerate(reader): > print reader.line_num, data > > -- Bob Gailer 510-978-4454 From wescpy at gmail.com Fri Oct 27 20:42:39 2006 From: wescpy at gmail.com (wesley chun) Date: Fri, 27 Oct 2006 11:42:39 -0700 Subject: [Tutor] I am terribly confused about "generators" and "iterators".. Help me In-Reply-To: References: Message-ID: <78b3a9580610271142x1f2cd3d5ic20a6dc39f044540@mail.gmail.com> > What are generators and iterators...??And why are they are needed..?? > > I can do my stuff with a 'for' or a 'while' loop.. so why do I need an > ITERATOR..? > > And what is a generator ..? I did try to read about these two things on the > web, but still I AM CONFUSED. here are some more places to look in addition to what others have already posted... 1. i wrote a short article in Linux Journal back when Python 2.2 was released, highlighting its new features; it includes a discussion and examples of iterators and generators: http://www2.linuxjournal.com/article/5597 my short take on it is that iterators let you use for-loops over sequence-*like* objects. in older versions of Python, they had to *be* sequences, i.e. strings, lists, tuples. but with iterators, you can now go through lines of a file, keys of a dictionary, etc. and generators are like "iterators with brains" because you can "generate" successive items to be iterated over, in addition to the cool co-routine-like resumable function features. 2. i do Python training professionally, and for people considering my services, i offer a free 5 minute sample podcast/video of what it's like to take a course from me. the example filmed is where i discuss generators right after i introduce iterators. http://cyberwebconsulting.com (click "Python Training") hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From pyro9219 at gmail.com Fri Oct 27 21:07:50 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Fri, 27 Oct 2006 12:07:50 -0700 Subject: [Tutor] Why is this only catching one occurance? In-Reply-To: <4541A983.1080509@gmail.com> References: <4541A983.1080509@gmail.com> Message-ID: Thats for this very humorous reply =D On 10/26/06, Luke Paireepinart wrote: > > Chris Hengge wrote: > > Here is my code: > > for unWantedItem in directoryList: > > try: > > if "hex" in unWantedItem.lower(): > > if not "bmc" in unWantedItem.lower(): > > print unWantedItem + " removed!" > > directoryList.remove(unWantedItem) > > > > This only seems to loop through once, and removes 1 of 2 occurances > > from this list that should be captured. Should "for" keep the list > > going through each instance? > > > You're removing stuff from something you're iterating over! > *slaps your fingers with a ruler* > Make a copy of the list! > HTH, > -Luke > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061027/ae1a548e/attachment.html From pyro9219 at gmail.com Fri Oct 27 21:20:51 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Fri, 27 Oct 2006 12:20:51 -0700 Subject: [Tutor] Why is this only catching one occurance? In-Reply-To: <45422DD1.6010006@alum.rpi.edu> References: <45422DD1.6010006@alum.rpi.edu> Message-ID: I've tried to use your example: for unWantedItem in directoryList[,,-1]: but I get an error: for unWantedItem in directoryList[,,-1]: ^ SyntaxError: invalid syntax I understand what you are saying to do, and it makes sense, but I'm not sure how to impliment it. On 10/27/06, Bob Gailer wrote: > > Chris Hengge wrote: > > Here is my code: > > for unWantedItem in directoryList: > > try: > > if "hex" in unWantedItem.lower(): > > if not "bmc" in unWantedItem.lower(): > > print unWantedItem + " removed!" > > directoryList.remove(unWantedItem) > > > > This only seems to loop through once, and removes 1 of 2 occurances > > from this list that should be captured. Should "for" keep the list > > going through each instance? > "for" goes thru the list accessing item[0], item[1], item[2], etc. Let's > say "for" is on item[1] and you remove item[1]. All the subsequent items > "move left", so item[2] becomes item[1], item[3] becomes item[2], etc. > "for" then steps to item[2], skipping the original item[2]. > > There are several ways around this. The easiest is to process the list > backwards: for unWantedItem in directoryList[,,-1]: > > -- > Bob Gailer > 510-978-4454 > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061027/4df3a2c5/attachment.html From bgailer at alum.rpi.edu Fri Oct 27 21:23:50 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri, 27 Oct 2006 12:23:50 -0700 Subject: [Tutor] line number when reading files using csv module CORRECTION In-Reply-To: <4542531B.2090609@alum.rpi.edu> References: <20061027093540.9F5DD202C@zeeman.thermal.esa.int> <4542531B.2090609@alum.rpi.edu> Message-ID: <45425CC6.6050306@alum.rpi.edu> Bob Gailer wrote: > Duncan Gibson wrote: > >> [snip] >> > > >> but I would like to record the line number in the file. >> >> > How about using enumerate(): > >> for line_num, data in enumerate(reader): >> # print reader.line_num, data # SHOULD BE: >> print line_num, data >> >> >> > -- Bob Gailer 510-978-4454 From pyro9219 at gmail.com Fri Oct 27 21:49:25 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Fri, 27 Oct 2006 12:49:25 -0700 Subject: [Tutor] Why is this only catching one occurance? In-Reply-To: References: <4541A983.1080509@gmail.com> Message-ID: That was supposed to say "Thanks for this" but I was in a hurry. Anyways, here is my solution: # Remove any copies of .hex that aren't BMC for foundItem in directoryList: try: if ".hex" in foundItem.lower(): if "bmc" in foundItem.lower(): wantedList.append(foundItem) else: print foundItem + " removed!" else: wantedList.append(foundItem) except: print "Failed to strip excess hex files." On 10/27/06, Chris Hengge wrote: > > Thats for this very humorous reply =D > > On 10/26/06, Luke Paireepinart wrote: > > > > Chris Hengge wrote: > > > Here is my code: > > > for unWantedItem in directoryList: > > > try: > > > if "hex" in unWantedItem.lower(): > > > if not "bmc" in unWantedItem.lower(): > > > print unWantedItem + " removed!" > > > directoryList.remove(unWantedItem) > > > > > > This only seems to loop through once, and removes 1 of 2 occurances > > > from this list that should be captured. Should "for" keep the list > > > going through each instance? > > > > > You're removing stuff from something you're iterating over! > > *slaps your fingers with a ruler* > > Make a copy of the list! > > HTH, > > -Luke > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061027/e164997f/attachment-0001.htm From Barry.Carroll at psc.com Fri Oct 27 22:16:01 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Fri, 27 Oct 2006 13:16:01 -0700 Subject: [Tutor] Why is this only catching one occurance? Message-ID: <2BBAEE949D384D40A2B851287ADB6A4304595A0B@eugsrv400.psc.pscnet.com> Chris: See below. > -----Original Message----- > Message: 7 > Date: Fri, 27 Oct 2006 12:20:51 -0700 > From: "Chris Hengge" > Subject: Re: [Tutor] Why is this only catching one occurance? > To: "Bob Gailer" > Cc: Tutor > Message-ID: > > Content-Type: text/plain; charset="iso-8859-1" > > I've tried to use your example: > for unWantedItem in directoryList[,,-1]: > > but I get an error: > for unWantedItem in directoryList[,,-1]: > ^ > SyntaxError: invalid syntax > <> The problem is the commas. Python uses colons to describe slices. Try this instead: >>>>> for unWantedItem in directoryList[::-1]: I think that will work for you. Regards, Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed From gsf at panix.com Fri Oct 27 22:32:43 2006 From: gsf at panix.com (Gabriel Farrell) Date: Fri, 27 Oct 2006 16:32:43 -0400 Subject: [Tutor] XML parsing in Python.. resources needed In-Reply-To: References: Message-ID: <20061027203243.GC7864@panix.com> On Fri, Oct 27, 2006 at 11:24:00AM +0100, Asrarahmed Kadri wrote: > Hi Folks, > > ANy comments about ELementTree module... > > I have heard that it is more 'Pythonic'... > > I need some basic examples to start learning the stuff.. If anyone has got > the information, please pass it along.. > ElementTree is great, and will be in Python2.5, so it's good to know. Go through the documentation at http://effbot.org/zone/element.htm, as Kent mentioned, and return to the list with specific questions. I recommend you also take a look at Amara[1], which I enjoy using because of it's clear API and clean output. gabe [1] http://uche.ogbuji.net/tech/4suite/amara/ From Barry.Carroll at psc.com Fri Oct 27 22:28:02 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Fri, 27 Oct 2006 13:28:02 -0700 Subject: [Tutor] (OT) Non-Python discussions (Was: I am terribly confused about "generators" ...) Message-ID: <2BBAEE949D384D40A2B851287ADB6A4304595A0C@eugsrv400.psc.pscnet.com> Greetings: I agree completely with David. There are plenty of places to discuss controvercial topics. Let's not do it here, where it will only disrupt, and possibly ruin, an exceptionally useful teaching and learning channel. Regards, Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed > -----Original Message----- > Message: 1 > Date: Fri, 27 Oct 2006 10:41:51 -0600 > From: David Heiser > Subject: Re: [Tutor] I am terribly confused about "generators" and > "iterators".. Help me > To: pythontutor > Message-ID: > > Content-Type: text/plain; charset="us-ascii" > > May I invite EVERYONE to NOT introduce political or religious elements > into these discussions. It has no place here and can destroy this > excellent discussion group. I've seen it happen. > > PLEASE take it elsewhere. > > -----Original Message----- > From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On > Behalf Of Bob Gailer > Sent: Friday, October 27, 2006 10:11 AM > To: Asrarahmed Kadri > Cc: pythontutor > Subject: Re: [Tutor] I am terribly confused about "generators" and > "iterators".. Help me > > Asrarahmed Kadri wrote: > > > > Hi Folks, > > <> > > To HIM you shall return. > I am glad that this thought brings you some comfort or stimulation. I > used to believe something similar, and all it did was bring me fear > guilt and shame. > > -- > Bob Gailer > 510-978-4454 > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From pine508 at hotmail.com Fri Oct 27 23:22:28 2006 From: pine508 at hotmail.com (Pine Marten) Date: Fri, 27 Oct 2006 17:22:28 -0400 Subject: [Tutor] recommendations for database module based on my needs In-Reply-To: Message-ID: I'm hoping to create an app which takes user data via a GUI with checkboxes, textcontrols, spinner controls, etc. The data would be some text, some numbers, some checkboxes checked or not, etc. I've been making a little progress on that via wxPython and Boa Constructor. Now I want to save that info such that: - the user can later search for any piece of data (search by date entered, for example). - the non-text data can be plotted on a chart and simple line regression, etc., applied to it. this could be some variable over time line graph or one variable vs. another scatterplot. The plotting I will pursue at another time, possibly via MatPlotLib or something. But as for databases, I've heard a few choices, including gadfly or SQL and others. I know zero about this, but I've heard gadfly is good if it is just a small dataset. But how small is small? The app I'm thinking of would take maybe 10-20 numbers/day and a few textboxes worth for potentially years. Or should I just pony up to SQL or some other option that I don't know about? Any recommendations or small python projects which are like this I might want to check out? thanks. _________________________________________________________________ Try the next generation of search with Windows Live Search today! http://imagine-windowslive.com/minisites/searchlaunch/?locale=en-us&source=hmtagline From alan.gauld at btinternet.com Sat Oct 28 01:00:45 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 28 Oct 2006 00:00:45 +0100 Subject: [Tutor] Getting the type of a variable References: <6.1.2.0.2.20061027140707.03e54520@pop.dsl.pipex.com> Message-ID: "Etrade Griffiths" wrote > > I want to check the type of a variable so that I know which format > to use > for printing eg That's sometimes necessary but you may find that just using %s will suffice. print "%s\n" % 42 print "%s\n" % "42" print "%s\n" % 42.0 You usually only need to check the type if the format string includes type specific precision and justification characters. but the %s format will work for most types most of the time. > The comparison type(a) == 'int' etc does not work type(a) == type(1) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Sat Oct 28 01:10:56 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 28 Oct 2006 00:10:56 +0100 Subject: [Tutor] recommendations for database module based on my needs References: Message-ID: "Pine Marten" wrote > it is just a small dataset. But how small is small? A potentially big topic. But heres my purely arbitrary guidelines: Less than 1000 records use a text file (or maybe XML) 1,000 - 100,000 records consider an in memory database or something like gdm (or gadfly in this case) 100,000=1000,000 records small scale or industrial SQL Access, or SqlLite would be good examples over 1,000,000 records go industrial. Postgres, MySql, Firebird/Interbase, Oracle, DB2, Sql server etc There are lots of other issues to consider too, like numbers of tables, indexes, need for stored procedures etc etc. But for simple data storage those rough guidelines should suffice. Caveat: Hardware improvements are changing the rules all the time. If its only simple one-off lookup, a text file could be used for 1,000,000 records on a fast machine nowadays, and if your server has 16G RAM say, then an in-memory database may scale up much farther. My figures assume long term multiple access during the application and average PC hardware. And all IMHO of course :-) -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Sat Oct 28 01:14:39 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 28 Oct 2006 00:14:39 +0100 Subject: [Tutor] database question References: <4541D68B.1020809@yahoo.es> Message-ID: > For example > with "SELECT * FROM a", I use this code > > ... to know how many columns are in the result, As a general rule its better to avoid "Select * From" in production SQL. If the table definition changes the data returned can change in unexpected ways and break your application. In addition you can wind up sucking up an awful lot of unnecessary data (think bandwidth and server throughput). Its much safer to explicitly list all of the columns you want to pull back if at all possible. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From ravikondamuru at gmail.com Sat Oct 28 04:07:49 2006 From: ravikondamuru at gmail.com (Ravi Kondamuru) Date: Fri, 27 Oct 2006 19:07:49 -0700 Subject: [Tutor] basic question ... Message-ID: <36601b010610271907n6f90a0ddr219183b558fafb56@mail.gmail.com> Hi, How does one figure all the builtin libraries/ classes that python supports? For example if I want to sort a list of names, I would normally think of implementing the sorting routine in C. I am just beginning to learn python. It looks like there is a rich set available builtin libraries. So, is there one place where I can look to figure out I dont have to write afresh. thanks, Ravi. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061027/b3b17b4d/attachment.html From gtnorton at earthlink.net Sat Oct 28 04:40:35 2006 From: gtnorton at earthlink.net (Glenn T Norton) Date: Fri, 27 Oct 2006 21:40:35 -0500 Subject: [Tutor] basic question ... In-Reply-To: <36601b010610271907n6f90a0ddr219183b558fafb56@mail.gmail.com> References: <36601b010610271907n6f90a0ddr219183b558fafb56@mail.gmail.com> Message-ID: <4542C323.2070701@earthlink.net> Ravi Kondamuru wrote: > Hi, > > How does one figure all the builtin libraries/ classes that python > supports? > > For example if I want to sort a list of names, I would normally think > of implementing the sorting routine in C. I am just beginning to learn > python. It looks like there is a rich set available builtin libraries. > So, is there one place where I can look to figure out I dont have to > write afresh. > > thanks, > Ravi. > >------------------------------------------------------------------------ > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > A good way to start is the dir() method which will show what is available to an object >>> mylist = [] >>> dir(mylist) ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__str__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] >>> >>> myString = '' >>> dir(myString) ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__str__', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'replace', 'rfind', 'rindex', 'rjust', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'] >>> also, try the builtin help in the interpreter >>> help(mylist.sort) Help on built-in function sort: sort(...) L.sort(cmpfunc=None) -- stable sort *IN PLACE*; cmpfunc(x, y) -> -1, 0, 1 >>> Good Luck, Glenn -- "Ketchup. For the good times... " - Ketchup Advisory Board Glenn Norton Application Developer Nebraska.gov 1-402-471-2777 glenn at nebraska.gov From dyoo at hkn.eecs.berkeley.edu Sat Oct 28 05:54:52 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 27 Oct 2006 20:54:52 -0700 (PDT) Subject: [Tutor] basic question ... In-Reply-To: <36601b010610271907n6f90a0ddr219183b558fafb56@mail.gmail.com> References: <36601b010610271907n6f90a0ddr219183b558fafb56@mail.gmail.com> Message-ID: On Fri, 27 Oct 2006, Ravi Kondamuru wrote: > How does one figure all the builtin libraries/ classes that python > supports? > > For example if I want to sort a list of names, I would normally think of > implementing the sorting routine in C. I am just beginning to learn > python. It looks like there is a rich set available builtin libraries. > So, is there one place where I can look to figure out I dont have to > write afresh. Hi Ravi, As with any reference material, it's a good idea to try the "index" of the relevant documentation. You might not always find what you're looking for, but it can be effective. In this particular case, you've guessed that there might be something in the Library that might help you. If you search for "sort" in the Library Reference: http://www.python.org/doc/lib/genindex.html You should see an index entry labeled "sort() (list method)". Looking up that index entry should bring you to a page describing the methods on lists: http://www.python.org/doc/lib/typesseq-mutable.html So looking at the reference is useful if you already know what you're looking for. In this case, yes, there is a built-in sort. Even better, there's a dedicated guide to using Python's sort functionality: http://wiki.python.org/moin/HowTo/Sorting If you want to get an overview of the extent of Python's library, try the table of contents: http://www.python.org/doc/lib/ There's a heck of a lot of stuff there, so asking someone to memorize it is ridiculous. Still, it can help to scan through it sometimes to get a better idea of what services the Library provides. I've often been amazed at the gems in there. ("bisect? Wow, I don't have to code my own binary search anymore!) Another good way to learn the library is to look at what libraries other people use: you can read other people's code. For example, the Python Cookbook provides a good source of programs that you can browse: http://aspn.activestate.com/ASPN/Python/Cookbook/ Finally, well, ask other people. You've done so on Tutor, so that's a good start. Many of us are happy to act as librarians to point you in some direction, and we usually aim not to mislead. *grin* From dyoo at hkn.eecs.berkeley.edu Sat Oct 28 06:29:52 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 27 Oct 2006 21:29:52 -0700 (PDT) Subject: [Tutor] problem importing class In-Reply-To: <4540F440.9020305@tds.net> References: <384c93600610260907p9287dc5qcf187262779bcef4@mail.gmail.com> <7e3eab2c0610260921m77282534x71d7185dd77458e7@mail.gmail.com> <4540F440.9020305@tds.net> Message-ID: >> It looks like people have identified the problem, that your site.py >> module isn't being found because it conflicts with something from >> Python's Standard Library. >> >> This isn't the first time this kind of problem has hit people. This >> problem is well known and is the subject of a Python Enhancement Proposal >> (PEP 328). If you're using Python 2.5, you can use a new feature called >> 'absolute_import' to avoid the import problem. See: >> >> http://docs.python.org/whatsnew/pep-328.html >> >> for more details. > > Hmm, I don't see how that would help since AFAICT shawn's site.py is not > in a package. Or maybe I don't understand what you are suggesting? Hi Kent, I don't think I replied back to you on this one! Python loads up 'site.py' on startup if called without the '-S' option: http://docs.python.org/lib/module-site.html So imagine if we're a program, and we run Python on it. For some reason --- at least on startup --- Python places precendence on the modules located in Python's library directory. So we pick up the Standard Library's site.py, which is then cached in sys.modules like any other module import. Later on, if we try to 'import site', Python reuses the already-loaded site.py (because it's already cached in sys.modules) , regardless if there's a 'site.py' module in the current working directory. The reason PEP 328 can be a solution here is because, if the absolute_import feature were on, we'd be able to do: from . import site which would pick up the correct relative path. Concretely, here's what probably happened with the original poster: ############################################################################## mumak:~ dyoo$ echo "print 'hi'" > site.py mumak:~ dyoo$ python Python 2.3.5 (#1, Mar 20 2005, 20:38:20) [GCC 3.3 20030304 (Apple Computer, Inc. build 1809)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import site >>> print site.__file__ /System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/site.pyc ############################################################################### Note that the 'site.py' in the current directory was not used. I have no idea why. I suspect that this has some relation to the way that site.py is handled by a special case in the Python interpreter, but I have really no clue. Python's module import lookup was handled in an implicit way which goes against its traditional "explicit instead of implicit" philosophy. That's why PEP 328 is so critically important: the name-collision problem gets much worse as either Standard Library or our own programs grow. I'm amazed that we've been able to tolerate this situation for so long. *grin* From ravikondamuru at gmail.com Sat Oct 28 07:11:44 2006 From: ravikondamuru at gmail.com (Ravi Kondamuru) Date: Fri, 27 Oct 2006 22:11:44 -0700 Subject: [Tutor] basic question ... In-Reply-To: References: <36601b010610271907n6f90a0ddr219183b558fafb56@mail.gmail.com> Message-ID: <36601b010610272211r54e6f4d8t3f9c25646d0bdc79@mail.gmail.com> Thanks a lot for all that info. I am going to start with the doc/lib index for an overview and dir looks like a good runtime help command. Ravi. On 10/27/06, Danny Yoo wrote: > > > > On Fri, 27 Oct 2006, Ravi Kondamuru wrote: > > > How does one figure all the builtin libraries/ classes that python > > supports? > > > > For example if I want to sort a list of names, I would normally think of > > implementing the sorting routine in C. I am just beginning to learn > > python. It looks like there is a rich set available builtin libraries. > > So, is there one place where I can look to figure out I dont have to > > write afresh. > > > Hi Ravi, > > As with any reference material, it's a good idea to try the "index" of the > relevant documentation. You might not always find what you're looking > for, but it can be effective. > > In this particular case, you've guessed that there might be something in > the Library that might help you. If you search for "sort" in the Library > Reference: > > http://www.python.org/doc/lib/genindex.html > > You should see an index entry labeled "sort() (list method)". Looking up > that index entry should bring you to a page describing the methods on > lists: > > http://www.python.org/doc/lib/typesseq-mutable.html > > So looking at the reference is useful if you already know what you're > looking for. In this case, yes, there is a built-in sort. Even better, > there's a dedicated guide to using Python's sort functionality: > > http://wiki.python.org/moin/HowTo/Sorting > > > > If you want to get an overview of the extent of Python's library, try the > table of contents: > > http://www.python.org/doc/lib/ > > There's a heck of a lot of stuff there, so asking someone to memorize it > is ridiculous. Still, it can help to scan through it sometimes to get a > better idea of what services the Library provides. I've often been amazed > at the gems in there. ("bisect? Wow, I don't have to code my own binary > search anymore!) > > Another good way to learn the library is to look at what libraries other > people use: you can read other people's code. For example, the Python > Cookbook provides a good source of programs that you can browse: > > http://aspn.activestate.com/ASPN/Python/Cookbook/ > > > Finally, well, ask other people. You've done so on Tutor, so that's a > good start. Many of us are happy to act as librarians to point you in > some direction, and we usually aim not to mislead. *grin* > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061027/ddd1d09a/attachment.html From contact at endarion.com Sat Oct 28 08:42:19 2006 From: contact at endarion.com (Michael Shulman) Date: Sat, 28 Oct 2006 02:42:19 -0400 Subject: [Tutor] move forward in arbitrary direction Message-ID: <4542FBCB.2070301@endarion.com> Hello, I have what should be a basic math question, but I keep messing it up. How do I code an equation so that when I have an object facing an arbitrary vector, pressing a key will make it move forwards in that direction? (I understand all the key-based setup, it's just the equation for moving in the arbitrary vector direction that's got me stuck) right now i can make something move up and down, or left and right, but if I want to rotate a triangle, then move it so that the 'tip' always points in the direction it's going to move, I get stuck. the thing I have which doesn't work is something like _____________________ vector = [0 0 0] def specialKey(key,x,y): if key == 'up': vector[0] = vector[0] + 1 _______________________ which I assume should be more like -------------------------------- vector = [0 0 0] def specialKey(key,x,y): if key == 'up': vector[0] = vector[0] * math.cos(something???)+ 1 vector[2] = vector[2] * math.sin(something??)+1 ---------------------------------- Any help would be greatly appreciated! ty, Mike From pyro9219 at gmail.com Sat Oct 28 11:01:23 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Sat, 28 Oct 2006 02:01:23 -0700 Subject: [Tutor] VNC library for python Message-ID: Does this exist? I see projects talking about writing viewers in python, and talking about their flaws or potential, but I've not seen a single library. Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061028/9f1c0a22/attachment.html From euoar at yahoo.es Sat Oct 28 12:42:34 2006 From: euoar at yahoo.es (euoar) Date: Sat, 28 Oct 2006 12:42:34 +0200 Subject: [Tutor] python decorators Message-ID: <4543341A.9050509@yahoo.es> Could somebody explain or point to a good place to learn what are python decorators, and when should they be used? Thanks. ______________________________________________ LLama Gratis a cualquier PC del Mundo. Llamadas a fijos y m?viles desde 1 c?ntimo por minuto. http://es.voice.yahoo.com From sisson.j at gmail.com Fri Oct 27 23:07:56 2006 From: sisson.j at gmail.com (Jonathon Sisson) Date: Fri, 27 Oct 2006 16:07:56 -0500 Subject: [Tutor] move forward in arbitrary direction In-Reply-To: <4542FBCB.2070301@endarion.com> References: <4542FBCB.2070301@endarion.com> Message-ID: <4542752C.7060603@gmail.com> The "something" you're stuck on is the angle the triangle has rotated, measured in radians. If the concept of radians is not familiar, then here's a quick review: There are 2*pi radians in a complete circle (about 6.28) There are 360 degrees in a complete circle 1 radian is approximately 57 degrees Going by radians, 0.0*pi is pointing to the right, 0.5*pi is pointing down, 1.0*pi is pointing to the left, and 1.5*pi is pointing straight up. Keep in mind that python has a math function radians(x), which converts "x" degrees to radians. If you use that, you can use degrees instead and convert on the fly. (i.e. something to the effect of: math.cos(math.radians(degrees)) would give you the change in vector[0]). If you would rather use radians, keep in mind that the python math module also has the pi constant, which is pretty self explanatory... Hope that helps you... Jonathon Michael Shulman wrote: > Hello, I have what should be a basic math question, but I keep messing > it up. > > How do I code an equation so that when I have an object facing an > arbitrary vector, pressing a key will make it move forwards in that > direction? > (I understand all the key-based setup, it's just the equation for moving > in the arbitrary vector direction that's got me stuck) > > right now i can make something move up and down, or left and right, but > if I want to rotate a triangle, then move it so that the 'tip' always > points in the direction it's going to move, I get stuck. > > the thing I have which doesn't work is something like > _____________________ > vector = [0 0 0] > > def specialKey(key,x,y): > if key == 'up': > vector[0] = vector[0] + 1 > _______________________ > which I assume should be more like > -------------------------------- > vector = [0 0 0] > > def specialKey(key,x,y): > if key == 'up': > vector[0] = vector[0] * math.cos(something???)+ 1 > vector[2] = vector[2] * math.sin(something??)+1 > ---------------------------------- > Any help would be greatly appreciated! > > ty, Mike > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From sisson.j at gmail.com Fri Oct 27 23:55:10 2006 From: sisson.j at gmail.com (Jonathon Sisson) Date: Fri, 27 Oct 2006 16:55:10 -0500 Subject: [Tutor] I am terribly confused about "generators" and "iterators".. Help me In-Reply-To: References: Message-ID: <4542803E.80405@gmail.com> My understanding is that an iterator is basically a facade` pattern. If you aren't familiar with patterns, a facade` pattern basically makes something really easy to use or convenient. Yes, you can "do it by hand", and many times that is indeed the preferred method, but sometimes it's easier to use an iterator...particularly if it isn't a special case. Nothing in the manual says you HAVE to use iterators, but they *can* make life easier. Jonathon Asrarahmed Kadri wrote: > > > Hi Folks, > > What are generators and iterators...??And why are they are needed..?? > > I can do my stuff with a 'for' or a 'while' loop.. so why do I need an > ITERATOR..? > > And what is a generator ..? I did try to read about these two things on > the web, but still I AM CONFUSED. > > To be honest, I am used to the nice and lucid style of the wonderful > people on this forum.. :)- > > Regards, > Asrarahmed Kadri > > > -- > To HIM you shall return. > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From amonroe at columbus.rr.com Sat Oct 28 17:54:43 2006 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Sat, 28 Oct 2006 11:54:43 -0400 Subject: [Tutor] move forward in arbitrary direction In-Reply-To: <4542FBCB.2070301@endarion.com> References: <4542FBCB.2070301@endarion.com> Message-ID: <146-679045246.20061028115443@columbus.rr.com> > right now i can make something move up and down, or left and right, but > if I want to rotate a triangle, then move it so that the 'tip' always > points in the direction it's going to move, I get stuck. http://freespace.virgin.net/hugo.elias/routines/rotate.htm Alan From dyoo at hkn.eecs.berkeley.edu Sat Oct 28 23:21:19 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 28 Oct 2006 14:21:19 -0700 (PDT) Subject: [Tutor] I am terribly confused about "generators" and "iterators".. Help me In-Reply-To: <4542803E.80405@gmail.com> References: <4542803E.80405@gmail.com> Message-ID: > My understanding is that an iterator is basically a facade` pattern. > If you aren't familiar with patterns, a facade` pattern basically makes > something really easy to use or convenient. Yes, you can "do it by > hand", and many times that is indeed the preferred method, but sometimes > it's easier to use an iterator...particularly if it isn't a special > case. Nothing in the manual says you HAVE to use iterators, but they > *can* make life easier. Concretely, we can write a program that will find all the even-length strings in some sequence, and give it back to us as a list: ################################ def filterEvenStrings(sequence): results = [] for x in sequence: if len(x) % 2 == 0: results.append(x) return results ################################ Now, we can use this function on a list of strings, as one would expect: ########################################################### >>> filterEvenStrings('hello world this is a test'.split()) ['this', 'is', 'test'] ########################################################### But we can also use this on a file: ########################################################################## >>> evenWords = filterEvenStrings( ... [x.strip() ... for x in open('/usr/share/dict/words').readlines()]) >>> evenWords[:10] ['aa', 'Aani', 'aardvark', 'aardwolf', 'Aaronite', 'Aaru', 'Ab', 'Ababua', 'abac', 'abacay'] ########################################################################## Note the nice thing here: we've been able to reuse filterEvenStrings on two entirely different things! We can use the same function on different things because those two things support a common interface: "iteration" support. Most of Python's interesting data structures have built-in iterators. But there are plenty of things that don't by default, but for which we might want to add such iteration support. 'for' loops expect things that iterate: if we try to apply them on things that don't, we'll get an error. For example: ############################################## >>> class Candy: ... def __init__(self, name): ... self.name = name ... >>> class CandyBag: ... def __init__(self): ... self.contents = [] ... def addCandy(self, aCandy): ... if isinstance(aCandy, Candy): ... self.contents.append(aCandy) ... ############################################### Ok, so we can make a CandyBag, and we might like to start adding things to it: ####### >>> bag = CandyBag() >>> bag.addCandy(42) >>> bag.addCandy(Candy("snickers")) >>> bag.addCandy(Candy("salt water taffy")) >>> bag.addCandy("spam") ####### We'd expect 42 and spam to be ignored, because they're not Candy. Anyway, so let's go over the bag with a loop: ####################################### >>> for c in bag: ... print c ... Traceback (most recent call last): File "", line 1, in ? TypeError: iteration over non-sequence ####################################### This bag is not a sequence. It may CONTAIN a sequence, but it itself isn't one. Now, we can either pull out the bag.contents if we're naughty, but we want to be good: let's have CandyBag support iteration. ######################################## class CandyBag: def __init__(self): """Creates an empty CandyBag.""" self.contents = [] def addCandy(self, aCandy): """Adds aCandy if it's a Candy. Otherwise, ignore it.""" if isinstance(aCandy, Candy): self.contents.append(aCandy) def __iter__(self): """Returns an iterator to all the candy in us.""" return iter(self.contents) ######################################## We've added a method __iter__() that produces an iterator when requested. In this case, we'll reuse the built-in iterator for lists. The iter() function takes anything that supports iteration, and gives us a iterator: ###### >>> myiterator = iter([3, 1, 4]) >>> myiterator >>> myiterator.next() 3 >>> myiterator.next() 1 >>> myiterator.next() 4 >>> myiterator.next() Traceback (most recent call last): File "", line 1, in ? StopIteration ###### And now that CandyBags support iteration, we can satisfy our sweet tooth and loop over a CandyBag using our for loop: ########################################### >>> bag = CandyBag() >>> bag.addCandy(42) >>> bag.addCandy(Candy("snickers")) >>> bag.addCandy(Candy("salt water taffy")) >>> bag.addCandy("spam") >>> for c in bag: ... print c ... <__main__.Candy instance at 0x22893f0> <__main__.Candy instance at 0x22896c0> ########################################### There's our two pieces of candy. We didn't add str() support to our Candy, so that's why they're printing in that peculiar form. From rabidpoobear at gmail.com Sun Oct 29 00:57:24 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sat, 28 Oct 2006 17:57:24 -0500 Subject: [Tutor] move forward in arbitrary direction In-Reply-To: <4542752C.7060603@gmail.com> References: <4542FBCB.2070301@endarion.com> <4542752C.7060603@gmail.com> Message-ID: > > Going by radians, 0.0*pi is pointing to the right, 0.5*pi is pointing > down, 1.0*pi is pointing to the left, and 1.5*pi is pointing straight up. uh, wouldn't pi/2 be pointing up? Don't you set 0 radians to be the positive-x axis and then go counter-clockwise? Or does it not matter? It seems like it would. Thanks, -Luke -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061028/b49ddf1c/attachment.htm From anilmrn at yahoo.com Sun Oct 29 02:14:29 2006 From: anilmrn at yahoo.com (anil maran) Date: Sat, 28 Oct 2006 17:14:29 -0700 (PDT) Subject: [Tutor] Adding voting to several object in python and db Message-ID: <20061029001429.95692.qmail@web55212.mail.re4.yahoo.com> I m having lots of fun with python it is like all of sudden I m unshackled from the days of java Man it is a lot of fun. It is super simple and easy... Ok now to my question, I m trying to add a ranking feature to various objects in the system, the users, their posts, their media etc, suffice to say I have to rank a lot of objects. I can think of implementing this rudimentarily, add python code and copy to do everything. Each object is a postgres db.. eg Table user { username, metadata, RANKING int4, } and so on... I cant but woefully look at Ruby_oN_rails guys adding ranking with just one line @act_as_votable and they are set.. no more bugs to fix, Do you guys have any ideas on how to do this, somehting similar to @checkaccess in auth also seems reasonable.. thanks a lot for your time and patience keep rockin in the web/python world Anil Anil --------------------------------- Access over 1 million songs - Yahoo! Music Unlimited Try it today. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061028/da556818/attachment.htm From bgailer at alum.rpi.edu Sun Oct 29 02:30:47 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sat, 28 Oct 2006 17:30:47 -0700 Subject: [Tutor] Adding voting to several object in python and db In-Reply-To: <20061029001429.95692.qmail@web55212.mail.re4.yahoo.com> References: <20061029001429.95692.qmail@web55212.mail.re4.yahoo.com> Message-ID: <4543F637.3080002@alum.rpi.edu> anil maran wrote: > I m having lots of fun with python it is like all of sudden I m > unshackled from the days of java Man it is a lot of fun. It is super > simple and easy... Ok now to my question, I m trying to add a ranking > feature to various objects in the system, the users, their posts, > their media etc, suffice to say I have to rank a lot of objects. I can > think of implementing this rudimentarily, add python code and copy to > do everything. > > Each object is a postgres db.. eg > Table user > { > username, metadata, > RANKING int4, > > } > > and so on... > I cant but woefully look at Ruby_oN_rails guys adding ranking with just > one line @act_as_votable and they are set.. no more bugs to fix, Do you > guys have any ideas on how to do this, somehting similar to > > @checkaccess in auth also seems reasonable.. I for one could not begin to address your question as I do not know what you mean by ranking, nor am I familiar with Ruby or @act_as_votable. Nor do I understand "implementing this rudimentarily, add python code and copy to do everything" Perhaps others have the background to help you. If you don't get any useful replies, please explain the desired behavior. > > thanks a lot for your time and patience > > keep rockin in the web/python world > > > Anil -- Bob Gailer 510-978-4454 From tktucker at gmail.com Sun Oct 29 02:55:57 2006 From: tktucker at gmail.com (Tom Tucker) Date: Sat, 28 Oct 2006 20:55:57 -0400 Subject: [Tutor] Matching on multiple log lines Message-ID: <2a278ffe0610281755x7966f651m405527fdbf6dfb46@mail.gmail.com> I would appreciate any recommendations or assistance on how to read and parse this log. The log is constantly growing and has the potential of being large. For this reason, we are reading in line by line. How do I match on multiple lines, while reading a log line by line. Hopefully the logic example and sample log will make more sense. Thank you, Logic: ------ 1) Search for this string 'Writing Message to' 2) Search ahead for this string 'TRANSPORT_STREAM_ID' 3) Followed by a blank line 4) If 1,2, and 3: increase a counter or something (counter +=1) 4) Repeat process Example log ############ 2006/10/24 20:46:05.853 Writing Message to 192.168.1.1:3211 Protocol: 2 Message Type: PROVISION Parameters: Parameter type: CHANNEL_ID Parameter value: 0001 Parameter type: SCG_ID Parameter value: 0001 Parameter type: TRANSPORT_STREAM_ID Parameter value: 0160 Parameter type: PROGRAM_NUMBER Parameter value: 0001 Parameter type: GROUP Parameter value: 0009 0002 2006/10/24 20:46:05.957 Receiving message from 192.168.1.1:3211 2006/10/24 20:47:05.011 Writing Message to 192.168.1.2:3211 Protocol: 2 Message Type: PROVISION Parameters: Parameter type: CHANNEL_ID Parameter value: 0001 Parameter type: SCG_ID Parameter value: 0001 Parameter type: TRANSPORT_STREAM_ID Parameter value: 0160 2006/10/24 20:47:05.057 Blah Blah..more logging From dyoo at hkn.eecs.berkeley.edu Sun Oct 29 02:34:31 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 28 Oct 2006 18:34:31 -0700 (PDT) Subject: [Tutor] Adding voting to several object in python and db In-Reply-To: <20061029001429.95692.qmail@web55212.mail.re4.yahoo.com> References: <20061029001429.95692.qmail@web55212.mail.re4.yahoo.com> Message-ID: > Ok now to my question, I m trying to add a ranking feature to various > objects in the system, the users, their posts, their media etc, suffice > to say I have to rank a lot of objects. Hi Anil, It sounds like you want to add some sort of feature to a heterogeneous set of classes. Traditionally, you could use a design pattern like "decorator" do to do this. Another way to add some feature to several different classes is to use multiple inheritance. Python's classes give us another tool in our toolbox called "mixins". The idea is that we can systematically build new classes with enhanced behavior in a cookie-cutter way. Here's a concrete example: ############################################ _counter = 0 def makeAutoincrementingClass(superClass): class NewClass(superClass): def __init__(self, *args, **kwargs): global _counter superClass.__init__(self, *args, **kwargs) self.__id = _counter _counter = _counter + 1 def id(self): return self.__id return NewClass ############################################ This is something that should look really weird at first! makeAutoincrementingClass() is a function that takes in a superClass, and returns a new class. Let's try using it: ################################################## >>> class Candy: ... def __init__(self, name): ... self.name = name ... def __str__(self): ... return "%s" % self.name ... >>> CountedCandy = makeAutoincrementingClass(Candy) >>> c = CountedCandy("reeses") >>> c.id() 0 >>> print c reeses >>> g = CountedCandy("gumdrops") >>> g.id() 1 #################################################### So here we've added some auto-incrementing id assignment to Candy. That's sorta cool. But we can add auto-incrementing behavior to any preexisting class: ########################################################## >>> from StringIO import StringIO >>> StringIO >>> CountedStringIO = makeAutoincrementingClass(StringIO) >>> s1 = CountedStringIO("hello world, this is a test") >>> s2 = CountedStringIO("happy halloween") >>> s1.id() 2 >>> s2.id() 3 >>> s2.read(5) 'happy' ########################################################## Now we've added this id-allocating behavior to a class from the Standard Library. Cool stuff. > I cant but woefully look at Ruby_oN_rails guys adding ranking with just > one line @act_as_votable and they are set.. no more bugs to fix, Do you > guys have any ideas on how to do this, somehting similar to My recommendatio is to really get functions down cold. They are much more powerful than you might guess. What the Ruby folks are doing when they define @act_as_votable is pretty much a mixin technique, just in different syntax. (And Python has this syntax in the form of "decorators".) The idea that drives this is that one can write functions from classes to classes, and it's a neat idea. There was a very old article about this in: http://www.linuxjournal.com/node/4540/print where they implement mixins with some __bases__ hackery. Personally, I don't like their approach of mutating the input class. So the example I wrote above does not mess with the existing class: makeAutoincrementingClass derives a new class that doesn't interfere. Best of wishes! From jim at well.com Sun Oct 29 03:04:53 2006 From: jim at well.com (jim stockford) Date: Sat, 28 Oct 2006 19:04:53 -0700 Subject: [Tutor] Matching on multiple log lines In-Reply-To: <2a278ffe0610281755x7966f651m405527fdbf6dfb46@mail.gmail.com> References: <2a278ffe0610281755x7966f651m405527fdbf6dfb46@mail.gmail.com> Message-ID: so it's guaranteed that 'Writing Message to' will always be followed by 'TRANSPORT_STREAM_ID' before the next occurrence of 'Writing Message to' and all text between can be ignored, and we increment the counter if and only if there is a newline immediately after 'TRANSPORT_STREAM_ID' yes? I.e. in your example, log, while there are two 'Writing Message to' blah blah 'TRANSPORT_STREAM_ID' sequences, only one has the required newline and proper counting increments the counter just once, yes? I'd keep a line counter to record the total number of lines read. I'd use a boolean flag to record the occurrence of 'Writing Message to' If flag is TRUE and if 'TRANSPORT_STREAM_ID' then test for newline and if TRUE then add the line number to a list of line numbers for the newline then reset flag to FALSE and resume testing down the file. when all done, save the line number of the very last line in the logfile to a stash file. upon next read-through, read the line number of the last line from the stash file and blindly read and discard that many lines before resuming the process. maybe a good idea to save not only the last line number but also the line itself into the stash file and after dropping to the line of the last number , compare text--call police if no match. On Oct 28, 2006, at 5:55 PM, Tom Tucker wrote: > I would appreciate any recommendations or assistance on how to read > and parse this log. The log is constantly growing and has the > potential of being large. For this reason, we are reading in line by > line. How do I match on multiple lines, while reading a log line by > line. Hopefully the logic example and sample log will make more > sense. > Thank you, > > > Logic: > ------ > 1) Search for this string 'Writing Message to' > 2) Search ahead for this string 'TRANSPORT_STREAM_ID' > 3) Followed by a blank line > 4) If 1,2, and 3: increase a counter or something (counter +=1) > 4) Repeat process > > > Example log > ############ > 2006/10/24 20:46:05.853 Writing Message to 192.168.1.1:3211 > Protocol: 2 > Message Type: PROVISION > Parameters: > Parameter type: CHANNEL_ID Parameter value: 0001 > Parameter type: SCG_ID Parameter value: 0001 > Parameter type: TRANSPORT_STREAM_ID Parameter value: 0160 > Parameter type: PROGRAM_NUMBER Parameter value: 0001 > Parameter type: GROUP Parameter value: 0009 0002 > 2006/10/24 20:46:05.957 Receiving message from 192.168.1.1:3211 > 2006/10/24 20:47:05.011 Writing Message to 192.168.1.2:3211 > Protocol: 2 > Message Type: PROVISION > Parameters: > Parameter type: CHANNEL_ID Parameter value: 0001 > Parameter type: SCG_ID Parameter value: 0001 > Parameter type: TRANSPORT_STREAM_ID Parameter value: 0160 > > 2006/10/24 20:47:05.057 Blah Blah..more logging > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From sisson.j at gmail.com Sat Oct 28 11:51:39 2006 From: sisson.j at gmail.com (Jonathon Sisson) Date: Sat, 28 Oct 2006 04:51:39 -0500 Subject: [Tutor] move forward in arbitrary direction In-Reply-To: References: <4542FBCB.2070301@endarion.com> <4542752C.7060603@gmail.com> Message-ID: <4543282B.8040501@gmail.com> Hrmmm...I do believe you are right, Luke. My bad...it's been a bit since I actually used this stuff (about 12 years ago in college...heh). And yes, it would matter, unless you swapped the key functionality around...but let's keep it simple, yes? Good thing I'm not programming this project...haha. Doh? Jonathon Luke Paireepinart wrote: > > > Going by radians, 0.0*pi is pointing to the right, 0.5*pi is pointing > down, 1.0*pi is pointing to the left, and 1.5*pi is pointing > straight up. > > > uh, wouldn't pi/2 be pointing up? > Don't you set 0 radians to be the positive-x axis and then go > counter-clockwise? > Or does it not matter? > It seems like it would. > Thanks, > -Luke > From alan.gauld at btinternet.com Sun Oct 29 09:58:06 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 29 Oct 2006 08:58:06 -0000 Subject: [Tutor] Adding voting to several object in python and db References: <20061029001429.95692.qmail@web55212.mail.re4.yahoo.com> Message-ID: Anil, You've been asking a lot of very web specific questions. But you haven't told us much about how you are building your application. You mebntion Ruby on Rails here. Are you using any of the Python web development frameworks - TurboGears, Zope, etc? If you are serious about web development then you really should be using one of these frameworks. Using bare Python is good for learning but not the most efficient way to build a real web application. If you are using one of the frameworks you should find that it has its own community forums to answer specific questions. This community is best suited to questions about the core Python language and libraries. The more specific the subject area the more specific the help forum to answer it. But without knowing what environment you are using it is difficult to give any kind of help. Alan G. "anil maran" wrote in message news:20061029001429.95692.qmail at web55212.mail.re4.yahoo.com... >I m having lots of fun with python it is like all of sudden I m > unshackled from the days of java Man it is a lot of fun. It is super > simple and easy... Ok now to my question, I m trying to add a > ranking > feature to various objects in the system, the users, their posts, > their media etc, suffice to say I have to rank a lot of objects. From kdidriksson at gmail.com Sun Oct 29 17:30:57 2006 From: kdidriksson at gmail.com (Kristinn Didriksson) Date: Sun, 29 Oct 2006 11:30:57 -0500 Subject: [Tutor] name is not defined error Message-ID: <3F327D8C-46C5-4EB5-A42C-6BB95BDB8F2F@gmail.com> Hello, I am new to Python and programming and going through the "Python Programming " book by Zelle. I am trying to solve the following exercise and get a name is not defined error. It is my understanding that eval turns a string into a number and then I can do math operations on it. Any help is greatly appreciated. Regards, Kristinn I input Kristinn at the prompt and this is the error message: ------------------ Please enter your name: Kristinn Traceback (most recent call last): File "/Users/krissd/Desktop/python/code_zelle/chapter3/6.py", line 18, in main() File "/Users/krissd/Desktop/python/code_zelle/chapter3/6.py", line 12, in main numEquiv = eval(eachLetter) File "", line 1, in NameError: name 'k' is not defined ---------------------- This is the program code: ------------------- # Numerology. Calculate the numeric value of a name. a =1, b=1,...z = 26 # Add the values for each letter for a total. def main(): import string print "This program calculates the numeric value of your name for divination." name = raw_input("Please enter your name: ") totalValue = 0 for eachLetter in string.lower(name): numEquiv = eval(eachLetter) letterValue = numEquiv -96 totalValue = totalValue + numEquiv print "The total numerical value of your name is " + totalValue +"!" main() ------------------- From dyoo at hkn.eecs.berkeley.edu Sun Oct 29 18:15:11 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 29 Oct 2006 09:15:11 -0800 (PST) Subject: [Tutor] name is not defined error In-Reply-To: <3F327D8C-46C5-4EB5-A42C-6BB95BDB8F2F@gmail.com> References: <3F327D8C-46C5-4EB5-A42C-6BB95BDB8F2F@gmail.com> Message-ID: > It is my understanding that eval turns a string into a number and then I > can do math operations on it. Hi Kristinn, No, no, that's not what it does. *grin* Where did you read about eval() from? If you saw it in a beginner's tutorial, tell us who the guilty party is so we can knock some sense into that tutorial. Don't use eval(): it's "unsafe" in the sense that it does something much more than what one might expect. I won't say too much more about it at the moment, but if you're interested, see the threads: http://mail.python.org/pipermail/tutor/2001-September/008967.html http://mail.python.org/pipermail/tutor/2004-December/033828.html for examples. Again, I have to say this again: don't use eval() unless you really know what you're doing. Anyway, I think you're looking for the ord() function: http://docs.python.org/lib/built-in-funcs.html#l2h-55 Its inverse is the chr() function: http://docs.python.org/lib/built-in-funcs.html#l2h-15 Good luck! From alan.gauld at btinternet.com Sun Oct 29 18:37:26 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 29 Oct 2006 17:37:26 -0000 Subject: [Tutor] name is not defined error References: <3F327D8C-46C5-4EB5-A42C-6BB95BDB8F2F@gmail.com> Message-ID: "Kristinn Didriksson" wrote > I am trying to solve the following exercise and get a name is not > defined error. It is my understanding that eval turns a string into > a > number and then I can do math operations on it. Not really. eval takes a string and interprets it as a python expression. Thus you can do things like: >>> a = 6 >>> b = 9 >>> eval("a+b") 15 So eval recognised a and b as local variables and added them together. But if I now try: >>> eval("c+d") I get an error because Python doesn't know about c or d. Because Python will try to evaluate and string as a piece of python it is potentially dangerous and a security risk since the code it evaluates could be malicious code. For that reason you should be very careful about how you use eval, and its partner exec, usually there are better alternatives. > # Numerology. Calculate the numeric value of a name. a =1, b=1,...z > = 26 > # Add the values for each letter for a total. You will need more than a comment, you will need to actually create variables for each of the letters of the alphabet. Either manually: a = 1 b = 2 or using a loop and exec: import string for ch in string.lowercase: command = "%s = ord('%s') - ord('a') + 1" % (ch,ch) exec(command) Or to avoid using the risky exec call, you could use a dictionary: vals = {} for ch in string.lowercase: vals[ch] = ord(ch) - ord('a') + 1 > name = raw_input("Please enter your name: ") > > totalValue = 0 > for eachLetter in string.lower(name): > numEquiv = eval(eachLetter) > letterValue = numEquiv -96 # not sure why you subratact 96... > totalValue = totalValue + numEquiv Of course a little thought will show that you could do the whole thing with ord and not use eval at all! That also removes the need for the list of variables. But I'll leave that as an exercise :-) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From dyoo at hkn.eecs.berkeley.edu Sun Oct 29 18:43:04 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 29 Oct 2006 09:43:04 -0800 (PST) Subject: [Tutor] name is not defined error (fwd) Message-ID: ---------- Forwarded message ---------- Date: Sun, 29 Oct 2006 12:33:58 -0500 From: Kristinn Didriksson To: Danny Yoo Subject: Re: [Tutor] name is not defined error Hi Danny, Thanks :) The program works now. I'll take a look at those threads. Here is what the book says " This function (eval) takes any string and evaluates it as if it were a Python expression." I took that to mean that it would turn a sting into an integer. Oops. it is a little confusing to get started, but lots of practice will change that. Thanks for your help. Regards, Kristinn On Oct 29, 2006, at 12:15 PM, Danny Yoo wrote: > > >> It is my understanding that eval turns a string into a number and then I can >> do math operations on it. > > Hi Kristinn, > > No, no, that's not what it does. *grin* > > Where did you read about eval() from? If you saw it in a beginner's > tutorial, tell us who the guilty party is so we can knock some sense into > that tutorial. > > Don't use eval(): it's "unsafe" in the sense that it does something much more > than what one might expect. I won't say too much more about it at the moment, > but if you're interested, see the threads: > > http://mail.python.org/pipermail/tutor/2001-September/008967.html > http://mail.python.org/pipermail/tutor/2004-December/033828.html > > for examples. Again, I have to say this again: don't use eval() unless you > really know what you're doing. > > > Anyway, I think you're looking for the ord() function: > > http://docs.python.org/lib/built-in-funcs.html#l2h-55 > > Its inverse is the chr() function: > > http://docs.python.org/lib/built-in-funcs.html#l2h-15 > > Good luck! From wescpy at gmail.com Mon Oct 30 01:54:00 2006 From: wescpy at gmail.com (wesley chun) Date: Sun, 29 Oct 2006 16:54:00 -0800 Subject: [Tutor] Matching on multiple log lines In-Reply-To: References: <2a278ffe0610281755x7966f651m405527fdbf6dfb46@mail.gmail.com> Message-ID: <78b3a9580610291654v653b8124o5f4b10e9884e3ece@mail.gmail.com> > so it's guaranteed that 'Writing Message to' > will always be followed by 'TRANSPORT_STREAM_ID' > before the next occurrence of 'Writing Message to' > and all text between can be ignored, > and we increment the counter if and only if > there is a newline immediately after 'TRANSPORT_STREAM_ID' > yes? just throwing this out there... would anyone do something like a open('log.txt', 'w').write(str(len(re.split(r'Writing Message to([\w\d\s:/\.]+?)TRANSPORT_STREAM_ID Parameter value: 0160\r?\n'))), or is this unseemly due the fact that the file may be very large? advantages i see here include: no counter to maintain since you get the one answer at the end, your python code is not iterating thru the file one line at a time (the faster C code in 're' is), you auto matically skip the TRANSPORT_STREAM_IDs that are *not* followed by a NEWLINE, etc. just wondering, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From jhlaks at gmail.com Mon Oct 30 03:25:28 2006 From: jhlaks at gmail.com (jhl) Date: Sun, 29 Oct 2006 19:25:28 -0700 Subject: [Tutor] re-import Message-ID: <63f2a80c0610291825g4e5f0492ja979c19095518e16@mail.gmail.com> Hi- How is the 1st import of a module removed so that new edits on the module can be re-imported? DETAIL: I am working on a module/file and importing it into a python shell, trying it out and then tweaking/editing the module. Then to see the effects of the edits, I want to re-import the file and find that the original import persists-- can't get the new/edited module without exiting and restarting the python shell. I've used dir() and del'd every reference to the module (and its contents/defs), but the 1st import seems to remain as the source for future imports. Thanks in advance for any & all help, -J -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061029/74c1d9cd/attachment.html From gtnorton at earthlink.net Mon Oct 30 03:34:26 2006 From: gtnorton at earthlink.net (Glenn T Norton) Date: Sun, 29 Oct 2006 20:34:26 -0600 Subject: [Tutor] re-import In-Reply-To: <63f2a80c0610291825g4e5f0492ja979c19095518e16@mail.gmail.com> References: <63f2a80c0610291825g4e5f0492ja979c19095518e16@mail.gmail.com> Message-ID: <454564B2.5080307@earthlink.net> jhl wrote: > Hi- > > How is the 1st import of a module removed so that new edits on the > module can be re-imported? > > DETAIL: > > I am working on a module/file and importing it into a python shell, > trying it out and then tweaking/editing the module. Then to see the > effects of the edits, I want to re-import the file and find that the > original import persists-- can't get the new/edited module without > exiting and restarting the python shell. I've used dir() and del'd > every reference to the module (and its contents/defs), but the 1st > import seems to remain as the source for future imports. > > Thanks in advance for any & all help, > -J > >------------------------------------------------------------------------ > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > Read about reload here: http://docs.python.org/lib/built-in-funcs.html Good Luck, Glenn -- "Ketchup. For the good times... " - Ketchup Advisory Board Glenn Norton Application Developer Nebraska.gov 1-402-471-2777 glenn at nebraska.gov From jfabiani at yolo.com Mon Oct 30 03:37:41 2006 From: jfabiani at yolo.com (johnf) Date: Sun, 29 Oct 2006 18:37:41 -0800 Subject: [Tutor] re-import In-Reply-To: <63f2a80c0610291825g4e5f0492ja979c19095518e16@mail.gmail.com> References: <63f2a80c0610291825g4e5f0492ja979c19095518e16@mail.gmail.com> Message-ID: <200610291837.41188.jfabiani@yolo.com> On Sunday 29 October 2006 18:25, jhl wrote: > Hi- > > How is the 1st import of a module removed so that new edits on the module > can be re-imported? > > DETAIL: > > I am working on a module/file and importing it into a python shell, trying > it out and then tweaking/editing the module. Then to see the effects of > the edits, I want to re-import the file and find that the original import > persists-- can't get the new/edited module without exiting and restarting > the python shell. I've used dir() and del'd every reference to the module > (and its contents/defs), but the 1st import seems to remain as the source > for future imports. > > Thanks in advance for any & all help, > -J reload(module) John From jhlaks at gmail.com Mon Oct 30 04:23:52 2006 From: jhlaks at gmail.com (jhl) Date: Sun, 29 Oct 2006 20:23:52 -0700 Subject: [Tutor] re-import In-Reply-To: <454564B2.5080307@earthlink.net> References: <63f2a80c0610291825g4e5f0492ja979c19095518e16@mail.gmail.com> <454564B2.5080307@earthlink.net> Message-ID: <63f2a80c0610291923i73d0a160y236348f8b41273aa@mail.gmail.com> Thanks again! That is just what I need. -J On 10/29/06, Glenn T Norton wrote: > > jhl wrote: > > > Hi- > > > > How is the 1st import of a module removed so that new edits on the > > module can be re-imported? > > > > DETAIL: > > > > I am working on a module/file and importing it into a python shell, > > trying it out and then tweaking/editing the module. Then to see the > > effects of the edits, I want to re-import the file and find that the > > original import persists-- can't get the new/edited module without > > exiting and restarting the python shell. I've used dir() and del'd > > every reference to the module (and its contents/defs), but the 1st > > import seems to remain as the source for future imports. > > > > Thanks in advance for any & all help, > > -J > > > >------------------------------------------------------------------------ > > > >_______________________________________________ > >Tutor maillist - Tutor at python.org > >http://mail.python.org/mailman/listinfo/tutor > > > > > Read about reload here: > http://docs.python.org/lib/built-in-funcs.html > > Good Luck, > Glenn > > -- > "Ketchup. For the good times... " - Ketchup Advisory Board > Glenn Norton > Application Developer > Nebraska.gov > 1-402-471-2777 > glenn at nebraska.gov > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061029/8410ea78/attachment-0001.htm From anilmrn at yahoo.com Mon Oct 30 04:59:11 2006 From: anilmrn at yahoo.com (anil maran) Date: Sun, 29 Oct 2006 19:59:11 -0800 (PST) Subject: [Tutor] automatically add it to all the classes Message-ID: <20061030035911.73699.qmail@web55201.mail.re4.yahoo.com> All the classes in my webpy application have the following lines is there anyway to automatically add it to all the classes in code.py, user.py If it is too basic, please pardon my naivette. thanks John These are the lines shared by all classes, @checkaccess(auth=True) sess = web.ctx.environ['com.saddi.service.session'].session meta_desc = 'myMetaData' title = 'title' session=web.cookies() in a class class index: @checkaccess(auth=True) def GET(self): sess = web.ctx.environ['com.saddi.service.session'].session meta_desc = 'myMetaData' title = 'title' session=web.cookies() Anil --------------------------------- We have the perfect Group for you. Check out the handy changes to Yahoo! Groups. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061029/2c0c7644/attachment.html From rabidpoobear at gmail.com Mon Oct 30 05:03:01 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sun, 29 Oct 2006 22:03:01 -0600 Subject: [Tutor] automatically add it to all the classes In-Reply-To: <20061030035911.73699.qmail@web55201.mail.re4.yahoo.com> References: <20061030035911.73699.qmail@web55201.mail.re4.yahoo.com> Message-ID: <45457975.2000407@gmail.com> anil maran wrote: > [some stuff] > > thanks > John Okay... So this is an e-mail from john... > [some other stuff] > > Anil And this is the reply by Anil? What is the question here, exactly? From alan.gauld at btinternet.com Mon Oct 30 09:18:59 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 30 Oct 2006 08:18:59 -0000 Subject: [Tutor] automatically add it to all the classes References: <20061030035911.73699.qmail@web55201.mail.re4.yahoo.com> Message-ID: "anil maran" wrote > All the classes in my webpy application have the following lines > is there anyway to automatically add it to all the classes in > code.py, > user.py Without more information about your application we can't give a definitive answer. But if they inherit from a common ancestor you could put the code there. Alternativelyyou could create a mixin class that all other classes inherit using multiple inheritance. Alternatively you could create a function and call that from all classes. Alternatively you could create a new class that does what you want and create an instance in the constructor of each of the other classes. Alternatively you could create a global variable and store everything there, maybe using a dictionary or list if necessary. There are other possibilities too but we really don't know enough about what you are trying to do to be able to say anything more specific.. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld > If it is too basic, please pardon my naivette. > thanks > John > These are the lines shared by all classes, > @checkaccess(auth=True) > > sess = web.ctx.environ['com.saddi.service.session'].session > meta_desc = 'myMetaData' > title = 'title' > session=web.cookies() > > in a class > class index: > @checkaccess(auth=True) > def GET(self): > sess = web.ctx.environ['com.saddi.service.session'].session > meta_desc = 'myMetaData' > title = 'title' > session=web.cookies() > > > Anil > > --------------------------------- > We have the perfect Group for you. Check out the handy changes to > Yahoo! Groups. -------------------------------------------------------------------------------- > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From duncan at thermal.esa.int Mon Oct 30 09:49:20 2006 From: duncan at thermal.esa.int (Duncan Gibson) Date: Mon, 30 Oct 2006 09:49:20 +0100 Subject: [Tutor] line number when reading files using csv module In-Reply-To: <4542014B.7000100@tds.net> References: <20061027122528.79E48202C@zeeman.thermal.esa.int> <4542014B.7000100@tds.net> Message-ID: <20061030094920.0771a1bc.duncan@thermal.esa.int> Duncan Gibson wrote: > > > > import csv > > > > class MyReader(object): > > > > def __init__(self, inputFile): > > self.reader = csv.reader(inputFile, delimiter=' ') > > self.lineNumber = 0 > > > > def __iter__(self): > > self.lineNumber += 1 > > return self.reader.__iter__() > > > > Is there some other __special__ method that I need to forward to the > > csv.reader, or have I lost all control once __iter__ has done its job? Kent Johnson wrote: > __iter__() should return self, not self.reader.__iter__(), otherwise > Python is using the actual csv.reader not your wrapper. And don't > increment line number here. > > You lost control because you gave it away. Thanks Kent. The penny has dropped and it makes a lot more sense now. I was looking for at __iter__ as a special function that *created* an iterator, but all it really does is signal that the returned object will implement the iterator interface, and the next() method in particular. Cheers Duncan From md at holisticgp.com.au Mon Oct 30 10:38:27 2006 From: md at holisticgp.com.au (Michael Daly) Date: Mon, 30 Oct 2006 20:38:27 +1100 Subject: [Tutor] am I a dope? - nasty_exception_str =..... Message-ID: <005501c6fc07$27dfb220$0100000a@P4> Hello python tutor when I tried to start a program called 'zope' that depends on python, I got this message at the bottom of a lot of 'traceback'*, and 'zope' didn't start: nasty_exception_str = Exception.__str__.im_func AttributeError: 'wrapper_descriptor' object has no attribute 'im_func' zope seemed to install OK in the same dir (/home/digium400p/zope) to which I directed (via prefix option) the python 2.5 install. I did this because python 2.3.4 is also installed in the default location on the operating system (which is centos 4.4), and I wanted to keep it that way. Zope requires at least python 2.4.3 I didn't use the 'make altinstall' option for the python 2.5 install-should I redo this? *this is the output: Traceback (most recent call last): File "/home/digium400p/zope/lib/python/Zope2/Startup/zopectl.py", line 322, in main() File "/home/digium400p/zope/lib/python/Zope2/Startup/zopectl.py", line 280, in main options.realize(args) File "/home/digium400p/zope/lib/python/Zope2/Startup/zopectl.py", line 91, in realize ZDOptions.realize(self, *args, **kw) etc etc, finally ending in File "/home/digium400p/zope/lib/python/DocumentTemplate/html_quote.py ", line 4, in from ustr import ustr File "/home/digium400p/zope/lib/python/DocumentTemplate/ustr.py", line 18, in nasty_exception_str = Exception.__str__.im_func AttributeError: 'wrapper_descriptor' object has no attribute 'im_func' Any help would be great Signed.. ...very compused From kent37 at tds.net Mon Oct 30 12:02:02 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 30 Oct 2006 06:02:02 -0500 Subject: [Tutor] automatically add it to all the classes In-Reply-To: <20061030035911.73699.qmail@web55201.mail.re4.yahoo.com> References: <20061030035911.73699.qmail@web55201.mail.re4.yahoo.com> Message-ID: <4545DBAA.3050202@tds.net> anil maran wrote: > All the classes in my webpy application have the following lines > is there anyway to automatically add it to all the classes in code.py, > user.py > If it is too basic, please pardon my naivette. > thanks > John > These are the lines shared by all classes, > @checkaccess(auth=True) > sess = web.ctx.environ['com.saddi.service.session'].session > meta_desc = 'myMetaData' > title = 'title' > session=web.cookies() > in a class > class index: > @checkaccess(auth=True) > def GET(self): > sess = web.ctx.environ['com.saddi.service.session'].session > meta_desc = 'myMetaData' > title = 'title' > session=web.cookies() If this is an entire method that is shared by all your classes, then you can make a base class that contains the method. If the method doesn't need access to member attributes (doesn't use self) then it doesn't have to be part of the class definition, it can be a standalone function in a utility module. If just part of a method is shared by all the classes, see if you can put the shared code into a separate method and then use one of the approaches described above. If neither of those will work then please give a little more context. Kent From kent37 at tds.net Mon Oct 30 12:07:33 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 30 Oct 2006 06:07:33 -0500 Subject: [Tutor] re-import In-Reply-To: <454564B2.5080307@earthlink.net> References: <63f2a80c0610291825g4e5f0492ja979c19095518e16@mail.gmail.com> <454564B2.5080307@earthlink.net> Message-ID: <4545DCF5.9090305@tds.net> Glenn T Norton wrote: > jhl wrote: > >> Hi- >> >> How is the 1st import of a module removed so that new edits on the >> module can be re-imported? >> > Read about reload here: > http://docs.python.org/lib/built-in-funcs.html Make sure you understand the limitations of reload(). In particular, names that are imported using 'from xxx import *' or 'from xxx import yyy' will not be updated if you reload(xxx), and objects created from class definitions in xxx will still refer to the old classes. You can read a little more about it here: http://www.python.org/doc/faq/programming/#when-i-edit-an-imported-module-and-reimport-it-the-changes-don-t-show-up-why-does-this-happen Kent From smiles at worksmail.net Mon Oct 30 11:54:39 2006 From: smiles at worksmail.net (C or L Smith) Date: Mon, 30 Oct 2006 16:39:39 +0545 Subject: [Tutor] documentation/sourceforge bug help Message-ID: <005701c6fc11$def3c8c0$0e2c4fca@csmith> I know this is off topic, but can anyone give me a hand? I have a sourceforge account. I want to make a correction to the python documentation. I click on the appropriate link at the bottom of the documentation page and then the bug tracker link on the page that I am sent to which takes me to http://sourceforge.net/bugs/?group_id=5470 "Login and Submit New" appears just under the "Tracker" tab on that page as does the message ""Please log in!" at the bottom of the detailed summary text box. Clicking on either of them just gets me into a loop, returning me to the bug page but treating me as though I have not logged in. I don't get an "incorrect password/user error. I just am sent back to the bug page as though nothing has happened. If I go ahead and try to submit the bug, it doesn't let me because I am trying to do so "anonymously. Can anyone help me figure out how to actually get logged in so I can file the report? /chris From kent37 at tds.net Mon Oct 30 12:47:12 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 30 Oct 2006 06:47:12 -0500 Subject: [Tutor] name is not defined error (fwd) In-Reply-To: References: Message-ID: <4545E640.1010104@tds.net> Danny Yoo wrote: > > ---------- Forwarded message ---------- > Date: Sun, 29 Oct 2006 12:33:58 -0500 > From: Kristinn Didriksson > To: Danny Yoo > Subject: Re: [Tutor] name is not defined error > > Hi Danny, > Thanks :) > The program works now. I'll take a look at those threads. > Here is what the book says " This function (eval) takes any string and > evaluates it as if it were a Python expression." I took that to mean that it > would turn a sting into an integer. Oops. eval() evaluates a Python expression and returns a value. This is similar to what happens when you enter text on the command line. eval() will take a string like '123' and turn it into the integer 123. eval() will also take the string 'import shutil;shutil.rmtree("/")' and turn it into a really bad day. A better way to convert a string that represents an integer into an integer is to use the int() function. Danny's warnings apply, I just wanted to clarify eval() a bit. Kent > it is a little confusing to get started, but lots of practice will change that. > Thanks for your help. > Regards, > Kristinn > > On Oct 29, 2006, at 12:15 PM, Danny Yoo wrote: > >> >>> It is my understanding that eval turns a string into a number and then I can >>> do math operations on it. >> Hi Kristinn, >> >> No, no, that's not what it does. *grin* >> >> Where did you read about eval() from? If you saw it in a beginner's >> tutorial, tell us who the guilty party is so we can knock some sense into >> that tutorial. >> >> Don't use eval(): it's "unsafe" in the sense that it does something much more >> than what one might expect. I won't say too much more about it at the moment, >> but if you're interested, see the threads: >> >> http://mail.python.org/pipermail/tutor/2001-September/008967.html >> http://mail.python.org/pipermail/tutor/2004-December/033828.html >> >> for examples. Again, I have to say this again: don't use eval() unless you >> really know what you're doing. >> >> >> Anyway, I think you're looking for the ord() function: >> >> http://docs.python.org/lib/built-in-funcs.html#l2h-55 >> >> Its inverse is the chr() function: >> >> http://docs.python.org/lib/built-in-funcs.html#l2h-15 >> >> Good luck! > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From kent37 at tds.net Mon Oct 30 12:55:08 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 30 Oct 2006 06:55:08 -0500 Subject: [Tutor] Matching on multiple log lines In-Reply-To: <78b3a9580610291654v653b8124o5f4b10e9884e3ece@mail.gmail.com> References: <2a278ffe0610281755x7966f651m405527fdbf6dfb46@mail.gmail.com> <78b3a9580610291654v653b8124o5f4b10e9884e3ece@mail.gmail.com> Message-ID: <4545E81C.5030401@tds.net> wesley chun wrote: >> so it's guaranteed that 'Writing Message to' >> will always be followed by 'TRANSPORT_STREAM_ID' >> before the next occurrence of 'Writing Message to' >> and all text between can be ignored, >> and we increment the counter if and only if >> there is a newline immediately after 'TRANSPORT_STREAM_ID' >> yes? > > > just throwing this out there... would anyone do something like a > open('log.txt', 'w').write(str(len(re.split(r'Writing Message > to([\w\d\s:/\.]+?)TRANSPORT_STREAM_ID Parameter value: > 0160\r?\n'))), or is this unseemly due the fact that the file may be > very large? If the log file can be read into memory then a regex-based solution might work well though your code looks a bit scrambled to me. Rather than re.split() I would use re.findall(). To solve this line-by-line I would make a simple state machine that looks for lines of interest and moves through the states Begin, Found_Transport_Stream_Id and Found_Writing_Message. Kent > > advantages i see here include: no counter to maintain since you get > the one answer at the end, your python code is not iterating thru the > file one line at a time (the faster C code in 're' is), you auto > matically skip the TRANSPORT_STREAM_IDs that are *not* followed by a > NEWLINE, etc. > > just wondering, > -- wesley > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > "Core Python Programming", Prentice Hall, (c)2007,2001 > http://corepython.com > > wesley.j.chun :: wescpy-at-gmail.com > python training and technical consulting > cyberweb.consulting : silicon valley, ca > http://cyberwebconsulting.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From ajkadri at googlemail.com Mon Oct 30 13:01:35 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Mon, 30 Oct 2006 12:01:35 +0000 Subject: [Tutor] Does it helps to learn "Regular Expressions" or ... Message-ID: Hi Folks, Is it useful to know re module and its functions..?? Or the string module has enough utilities to accomplish string manipulation..!!! Any suggestions?? Regards, Asrarahmed -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061030/30aaef4e/attachment.htm From dyoo at hkn.eecs.berkeley.edu Mon Oct 30 13:14:35 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 30 Oct 2006 04:14:35 -0800 (PST) Subject: [Tutor] documentation/sourceforge bug help In-Reply-To: <005701c6fc11$def3c8c0$0e2c4fca@csmith> References: <005701c6fc11$def3c8c0$0e2c4fca@csmith> Message-ID: On Mon, 30 Oct 2006, C or L Smith wrote: > Can anyone help me figure out how to actually get logged in so I can > file the report? Do you happen to have cookies disabled? You might need to enable them, since that's what SF will use to track your login status. I'm getting the feeling that it's a cookie-management issue, but I have no real evidence for this yet. Let's try isolating the problem separate from bug submission. Can you log into SF by using their page at: https://sourceforge.net/account/login.php?return_to=%2Fmy%2F If this doesn't work with your current setup, another option to try is to switch your web browser and see if that has any effect. Firefox 2.0 just came out, so you can try it and see if that helps. But you should really get in touch with the SF folks; they'd probably be able to diagnose this more effectively than us on Tutor. From dyoo at hkn.eecs.berkeley.edu Mon Oct 30 13:28:54 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 30 Oct 2006 04:28:54 -0800 (PST) Subject: [Tutor] Does it helps to learn "Regular Expressions" or ... In-Reply-To: References: Message-ID: > Is it useful to know re module and its functions..?? HI Asrarahmed, Yes. Most people find them to be invaluable in their day-to-day work. The problem is that they're powerful enough that they look like an all-in-one tool: it's tempting to use them, even when they are the wrong tool for the job. *grin* So at least know about regular expressions, enough to know when and when not to use them. You might want to look at the Regex HOWTO: http://www.amk.ca/python/howto/regex/ to get more familiar with regular expressions. > Or the string module has enough utilities to accomplish string > manipulation..!!! For simple things, I'd stick with the methods in strings. For other complicated tasks, regular expressions may be the right tool. But for anything that deals with structure (i.e. HTML, XML, JSON), using a real parser for that language is more appropriate. (Those parsers will usually be built on top of regular expressions, to hide some ugliness from you.) Concretely, if anyone asks you to if they can use regular expressions to parse XML, try to convince them to look into the ElementTree library first. Good luck! From ajkadri at googlemail.com Mon Oct 30 13:44:12 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Mon, 30 Oct 2006 12:44:12 +0000 Subject: [Tutor] Does it helps to learn "Regular Expressions" or ... In-Reply-To: References: Message-ID: Thanks a lot, Danny. Yeah, my goal is to do XML parsing and for that I will be using ElementTree. As you pointed out, regular expressions are very powerful, so I better get some idea of about them. Cheers. Asrarahmed On 10/30/06, Danny Yoo wrote: > > > > Is it useful to know re module and its functions..?? > > HI Asrarahmed, > > Yes. Most people find them to be invaluable in their day-to-day work. > The problem is that they're powerful enough that they look like an > all-in-one tool: it's tempting to use them, even when they are the wrong > tool for the job. *grin* So at least know about regular expressions, > enough to know when and when not to use them. > > You might want to look at the Regex HOWTO: > > http://www.amk.ca/python/howto/regex/ > > to get more familiar with regular expressions. > > > > > Or the string module has enough utilities to accomplish string > > manipulation..!!! > > For simple things, I'd stick with the methods in strings. For other > complicated tasks, regular expressions may be the right tool. But for > anything that deals with structure (i.e. HTML, XML, JSON), using a real > parser for that language is more appropriate. (Those parsers will usually > be built on top of regular expressions, to hide some ugliness from you.) > > Concretely, if anyone asks you to if they can use regular expressions to > parse XML, try to convince them to look into the ElementTree library > first. > > > Good luck! > -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061030/9afdfb41/attachment.html From kent37 at tds.net Mon Oct 30 13:55:15 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 30 Oct 2006 07:55:15 -0500 Subject: [Tutor] python decorators In-Reply-To: <4543341A.9050509@yahoo.es> References: <4543341A.9050509@yahoo.es> Message-ID: <4545F633.1070403@tds.net> euoar wrote: > Could somebody explain or point to a good place to learn what are python > decorators, and when should they be used? http://www.python.org/doc/2.4.4/whatsnew/node6.html http://wiki.python.org/moin/PythonDecoratorLibrary http://www.phyast.pitt.edu/~micheles/python/documentation.html Kent From kent37 at tds.net Mon Oct 30 14:01:26 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 30 Oct 2006 08:01:26 -0500 Subject: [Tutor] basic question ... In-Reply-To: References: <36601b010610271907n6f90a0ddr219183b558fafb56@mail.gmail.com> Message-ID: <4545F7A6.6050606@tds.net> Danny Yoo wrote: > If you want to get an overview of the extent of Python's library, try the > table of contents: > > http://www.python.org/doc/lib/ > > There's a heck of a lot of stuff there, so asking someone to memorize it > is ridiculous. Still, it can help to scan through it sometimes to get a > better idea of what services the Library provides. I've often been amazed > at the gems in there. ("bisect? Wow, I don't have to code my own binary > search anymore!) Section 2.1 Built-in Functions and Chapter 3 Built-in Types are well worth at least skimming and revisiting. All of the global functions such as dir(), len(), open(), etc, etc are documented in section 2.1. Built-in types such as str, list and dict are documented in chapter 3. Kent From kent37 at tds.net Mon Oct 30 14:14:12 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 30 Oct 2006 08:14:12 -0500 Subject: [Tutor] problem importing class In-Reply-To: References: <384c93600610260907p9287dc5qcf187262779bcef4@mail.gmail.com> <7e3eab2c0610260921m77282534x71d7185dd77458e7@mail.gmail.com> <4540F440.9020305@tds.net> Message-ID: <4545FAA4.30804@tds.net> Danny Yoo wrote: >>> This isn't the first time this kind of problem has hit people. This >>> problem is well known and is the subject of a Python Enhancement Proposal >>> (PEP 328). If you're using Python 2.5, you can use a new feature called >>> 'absolute_import' to avoid the import problem. See: >>> >>> http://docs.python.org/whatsnew/pep-328.html >>> >>> for more details. >> Hmm, I don't see how that would help since AFAICT shawn's site.py is not >> in a package. Or maybe I don't understand what you are suggesting? > > Hi Kent, > > I don't think I replied back to you on this one! Python loads up > 'site.py' on startup if called without the '-S' option: > > http://docs.python.org/lib/module-site.html > > So imagine if we're a program, and we run Python on it. For some reason > --- at least on startup --- Python places precendence on the modules > located in Python's library directory. So we pick up the Standard > Library's site.py, which is then cached in sys.modules like any other > module import. > > Later on, if we try to 'import site', Python reuses the already-loaded > site.py (because it's already cached in sys.modules) , regardless if > there's a 'site.py' module in the current working directory. The reason > PEP 328 can be a solution here is because, if the absolute_import feature > were on, we'd be able to do: > > from . import site > > which would pick up the correct relative path. This only works for code that is in a package, when you want to import a module in the same package. It doesn't work for code that is not in a package. For example, F:\Tutor>cat site.py print 'imported site.py' F:\Tutor>cat siteimporter.py from __future__ import absolute_import from . import site F:\Tutor>py siteimporter.py F:\Tutor>C:\Python25\python siteimporter.py Traceback (most recent call last): File "siteimporter.py", line 2, in from . import site ValueError: Attempted relative import in non-package > > > Concretely, here's what probably happened with the original poster: > > ############################################################################## > mumak:~ dyoo$ echo "print 'hi'" > site.py > mumak:~ dyoo$ python > Python 2.3.5 (#1, Mar 20 2005, 20:38:20) > [GCC 3.3 20030304 (Apple Computer, Inc. build 1809)] on darwin > Type "help", "copyright", "credits" or "license" for more information. >>>> import site >>>> print site.__file__ > /System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/site.pyc > ############################################################################### > > Note that the 'site.py' in the current directory was not used. I have no > idea why. I suspect that this has some relation to the way that site.py > is handled by a special case in the Python interpreter, but I have really > no clue. site.py is a special case just in being loaded automatically. Other than that this is standard behaviour. If you import a module that has already been imported, you will get a reference to the already-imported module, sys.path is not searched again. Since the library module site has already been imported when your program starts, 'import site' will always return a reference to the library module. Kent From Senthil_OR at Dell.com Mon Oct 30 14:19:44 2006 From: Senthil_OR at Dell.com (Senthil_OR at Dell.com) Date: Mon, 30 Oct 2006 18:49:44 +0530 Subject: [Tutor] documentation/sourceforge bug help In-Reply-To: <005701c6fc11$def3c8c0$0e2c4fca@csmith> Message-ID: C or L Smith wrote: > I know this is off topic, but can anyone give me a hand? I have a > sourceforge account. I want to make a correction to the python > documentation. I click on the appropriate link at the bottom of the > documentation page and then the bug tracker link on the page that I > am sent to which takes me to > > http://sourceforge.net/bugs/?group_id=5470 1) Log in to http://sf.net with your account. 2) Click the above link to submit a bug. 3) There you go! I was able do it. Thanks, -- Senthil From kent37 at tds.net Mon Oct 30 14:21:56 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 30 Oct 2006 08:21:56 -0500 Subject: [Tutor] line number when reading files using csv module In-Reply-To: <20061030094920.0771a1bc.duncan@thermal.esa.int> References: <20061027122528.79E48202C@zeeman.thermal.esa.int> <4542014B.7000100@tds.net> <20061030094920.0771a1bc.duncan@thermal.esa.int> Message-ID: <4545FC74.6060607@tds.net> Duncan Gibson wrote: > Duncan Gibson wrote: >>> import csv >>> >>> class MyReader(object): >>> >>> def __init__(self, inputFile): >>> self.reader = csv.reader(inputFile, delimiter=' ') >>> self.lineNumber = 0 >>> >>> def __iter__(self): >>> self.lineNumber += 1 >>> return self.reader.__iter__() >>> >>> Is there some other __special__ method that I need to forward to the >>> csv.reader, or have I lost all control once __iter__ has done its job? > > Kent Johnson wrote: >> __iter__() should return self, not self.reader.__iter__(), otherwise >> Python is using the actual csv.reader not your wrapper. And don't >> increment line number here. >> >> You lost control because you gave it away. > > > Thanks Kent. The penny has dropped and it makes a lot more sense now. > > I was looking for at __iter__ as a special function that *created* an > iterator, but all it really does is signal that the returned object > will implement the iterator interface, and the next() method in > particular. I think you might still be a tiny bit confused. __iter__() is not just a marker, it does return an iterator. It helps if you distinguish two cases - iterable and iterator. An iterable object is one for which iter(obj) returns an iterator. An iterator is an object with a next() method. As a special case, iterators are also iterable - if obj is already an iterator, then iter(obj) is just obj. In modern Python (since 2.2) iter() is implemented by calling the special method __iter__() which should return an iterator. For a sequence like a list, __iter__() will return a new iterator object. Again, as a special case, __iter__() for an iterator returns the iterator itself. You might want to read this: http://www.python.org/doc/2.2.3/whatsnew/node4.html I hope I am shedding light here :-) Kent From euoar at yahoo.es Mon Oct 30 14:36:19 2006 From: euoar at yahoo.es (euoar) Date: Mon, 30 Oct 2006 14:36:19 +0100 Subject: [Tutor] python decorators In-Reply-To: <4545F633.1070403@tds.net> References: <4543341A.9050509@yahoo.es> <4545F633.1070403@tds.net> Message-ID: <4545FFD3.4020206@yahoo.es> Kent Johnson escribi?: > euoar wrote: >> Could somebody explain or point to a good place to learn what are >> python decorators, and when should they be used? > > http://www.python.org/doc/2.4.4/whatsnew/node6.html > http://wiki.python.org/moin/PythonDecoratorLibrary > http://www.phyast.pitt.edu/~micheles/python/documentation.html > > Kent > > Thank you for the links ______________________________________________ LLama Gratis a cualquier PC del Mundo. Llamadas a fijos y m?viles desde 1 c?ntimo por minuto. http://es.voice.yahoo.com From dyoo at hkn.eecs.berkeley.edu Mon Oct 30 15:06:27 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 30 Oct 2006 06:06:27 -0800 (PST) Subject: [Tutor] problem importing class In-Reply-To: <4545FAA4.30804@tds.net> References: <384c93600610260907p9287dc5qcf187262779bcef4@mail.gmail.com> <7e3eab2c0610260921m77282534x71d7185dd77458e7@mail.gmail.com> <4540F440.9020305@tds.net> <4545FAA4.30804@tds.net> Message-ID: > This only works for code that is in a package, when you want to import a > module in the same package. It doesn't work for code that is not in a > package. For example, > > F:\Tutor>cat site.py > print 'imported site.py' > > F:\Tutor>cat siteimporter.py > from __future__ import absolute_import > from . import site > > F:\Tutor>py siteimporter.py > > F:\Tutor>C:\Python25\python siteimporter.py > Traceback (most recent call last): > File "siteimporter.py", line 2, in > from . import site > ValueError: Attempted relative import in non-package Hi Kent, Yikes! Really? Thank you for the correction; I completely misread the intention of PEP 328 then. But now I'm very miffed and unhappy. Darn it, then that means this issue isn't repaired after all. Most beginner programmers won't use packages, and so we'll still see the same problems pop up all the time. Why is this restricted just to packages? Let me see... http://mail.python.org/pipermail/python-list/2006-October/367267.html Hmmm... Is that the issue then? It being the main module? I'm now reading PEP 338 and looking at the section "Import Statements and the Main module": http://www.python.org/dev/peps/pep-0338/ ... ok. Good grief. Then the current state of affairs still doesn't address the common case problem that we see on Tutor on module imports. The PEPs maintain that this is the situation for Python 2.5, emphasizing that this might be revisited in 2.6, which gives me some fleeting hope that this might get fixed in the future. I apologize about giving the bad advice. I was really hoping never to see another import problem again. From overstock at gmail.com Mon Oct 30 16:52:36 2006 From: overstock at gmail.com (Over Stock) Date: Mon, 30 Oct 2006 16:52:36 +0100 Subject: [Tutor] paypal alternative Message-ID: <1d7842330610300752y1e497c5ev3784c9038f1062d6@mail.gmail.com> International Money Transfer money transfer. Send money to anyone with an email address! http://www.vegacash.com/ paypal alternative From Matthew.Warren at Digica.com Mon Oct 30 17:26:58 2006 From: Matthew.Warren at Digica.com (Matthew Warren) Date: Mon, 30 Oct 2006 16:26:58 -0000 Subject: [Tutor] Matching on multiple log lines In-Reply-To: <4545E81C.5030401@tds.net> Message-ID: > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of Kent Johnson > Sent: 30 October 2006 11:55 > Cc: tutor at python.org > Subject: Re: [Tutor] Matching on multiple log lines > > wesley chun wrote: > >> so it's guaranteed that 'Writing Message to' > >> will always be followed by 'TRANSPORT_STREAM_ID' > >> before the next occurrence of 'Writing Message to' > >> and all text between can be ignored, > >> and we increment the counter if and only if > >> there is a newline immediately after 'TRANSPORT_STREAM_ID' > >> yes? > > > > > > just throwing this out there... would anyone do something like a > > open('log.txt', 'w').write(str(len(re.split(r'Writing Message > > to([\w\d\s:/\.]+?)TRANSPORT_STREAM_ID Parameter value: > > 0160\r?\n'))), or is this unseemly due the fact that the file may be > > very large? > > If the log file can be read into memory then a regex-based solution > might work well though your code looks a bit scrambled to me. Rather > than re.split() I would use re.findall(). > > To solve this line-by-line I would make a simple state machine that > looks for lines of interest and moves through the states Begin, > Found_Transport_Stream_Id and Found_Writing_Message. > > Kent Exactly how I have solved this in the past writing a general purpose tool for scanning logs for things. More code, but much easier to follow. -- [BEGIN silly disclaimer] This email is confidential and may be privileged. If you are not the intended recipient please notify the sender immediately and delete the email from your computer. You should not copy the email, use it for any purpose or disclose its contents to any other person. Please note that any views or opinions presented in this email may be personal to the author and do not necessarily represent the views or opinions of Digica. It is the responsibility of the recipient to check this email for the presence of viruses. Digica accepts no liability for any damage caused by any virus transmitted by this email. UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UK Reception Tel: + 44 (0) 115 977 1177 Support Centre: 0845 607 7070 Fax: + 44 (0) 115 977 7000 http://www.digica.com SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South Africa Tel: + 27 (0) 21 957 4900 Fax: + 27 (0) 21 948 3135 http://www.digica.com From smiles at worksmail.net Mon Oct 30 18:22:10 2006 From: smiles at worksmail.net (C or L Smith) Date: Mon, 30 Oct 2006 23:07:10 +0545 Subject: [Tutor] documentation/sourceforge bug help References: <005701c6fc11$def3c8c0$0e2c4fca@csmith> Message-ID: <010701c6fc48$1b39b750$0e2c4fca@csmith> Danny Yoo wrote: | On Mon, 30 Oct 2006, C or L Smith wrote: | || Can anyone help me figure out how to actually get logged in so I can || file the report? | | Do you happen to have cookies disabled? You might need to enable | them, since that's what SF will use to track your login status. I'm | getting the feeling that it's a cookie-management issue, but I have | no real evidence for this yet. | Yes, I have them enabled. | Let's try isolating the problem separate from bug submission. Can | you log into SF by using their page at: | | https://sourceforge.net/account/login.php?return_to=%2Fmy%2F | Yes, I get sent to "My" page. From there I don't know how to navigate to the bug tracker page other than by using the direct link: http://sourceforge.net/bugs/?group_id=5470 But something different happens tonight when I put https instead of http: I am able to successfully be recognized as being logged in on the bug tracker page (there isn't a message telling me to log in first) BUT when I submit the bug, it tells me that anonymous submissions are not allowed. :-( I was able to file a report to sourceforge on an page with nearly identical layout. And on this page, it took the report. I wonder if I have to be recognized as a group member of the python project.... | If this doesn't work with your current setup, another option to try | is to switch your web browser and see if that has any effect. I tried setting the agent to Internet Explorer (but didn't actually try internet explorer) and that didn't work. I'll let you know if I am ever successful with this. Thanks for the tips, /c From dyoo at hkn.eecs.berkeley.edu Mon Oct 30 20:22:38 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 30 Oct 2006 11:22:38 -0800 (PST) Subject: [Tutor] paypal alternative In-Reply-To: <1d7842330610300752y1e497c5ev3784c9038f1062d6@mail.gmail.com> References: <1d7842330610300752y1e497c5ev3784c9038f1062d6@mail.gmail.com> Message-ID: On Mon, 30 Oct 2006, Over Stock wrote: > International Money Transfer money transfer. [disgusting advertisement cut] [META: admin] This is crass, and deserves an appropriate response. I'm kicking 'Over Stock' off the python-tutor mailing list. I'm now CCing the other list admins on the other python mailing lists to see if this 'overstock' person has done similiar nonsense. Actions taken: * Unsubscribed overstock at gmail.com. * Added overstock at gmail.com to banned list. * Contacted abuse at gmail.com. From alan.gauld at btinternet.com Mon Oct 30 21:07:12 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 30 Oct 2006 20:07:12 -0000 Subject: [Tutor] am I a dope? - nasty_exception_str =..... References: <005501c6fc07$27dfb220$0100000a@P4> Message-ID: "Michael Daly" wrote > when I tried to start a program called 'zope' that depends on > python, Hmm, Zope is rather more than a mere program. It is a very powerful environment containing lots of fairly sophisticated bits n pieces. Did you read through all the Zope installation and configuration stuff (READMEs and the like) before trying to start it? There should be a tutorial/beginners guide for Zope somewhere on-line. > zope seemed to install OK in the same dir (/home/digium400p/zope) > which I directed (via prefix option) the python 2.5 install. I did > this because > python 2.3.4 is also installed in the default location on the > operating > system (which is centos 4.4), and I wanted to keep it that way. Zope > requires at least python 2.4.3 I'm not sure what the current Zope default is, but it used to want a directory of its own... > I didn't use the 'make altinstall' option for the python 2.5 > install-should > I redo this? Probably not. > Traceback (most recent call last): > File "/home/digium400p/zope/lib/python/Zope2/Startup/zopectl.py", > line 322, in > main() > File "/home/digium400p/zope/lib/python/Zope2/Startup/zopectl.py", > line 280, in main > options.realize(args) > File "/home/digium400p/zope/lib/python/Zope2/Startup/zopectl.py", > line 91, in realize > ZDOptions.realize(self, *args, **kw) Looks like some config options may need to be set to tell it about your local environment. > nasty_exception_str = Exception.__str__.im_func > AttributeError: 'wrapper_descriptor' object has no > attribute 'im_func' But I have no idea exactl what. I only used Zope once several years ago. I did the tutorial, it worked. I deleted Zope having decided it was way overkill for what I was doing! Alan G. From alan.gauld at btinternet.com Mon Oct 30 21:13:00 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 30 Oct 2006 20:13:00 -0000 Subject: [Tutor] Does it helps to learn "Regular Expressions" or ... References: Message-ID: "Asrarahmed Kadri" wrote > > Is it useful to know re module and its functions..?? Yes. > Or the string module has enough utilities to accomplish string > manipulation..!!! The string module is deprecated but (most of) its features are now found as methods of string objects. However these are not always enough fopr all tasks and thats where regex comes in. In my own programming I probably only use a Python regex once or twice a month, but in Awk I use them at least every week... So if you use python for the kind of things I do in awk then you will use them much more often... My tutor has a basic intro to regex, and there is a more detailed HowTo online linked from the python site. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From rdm at rcblue.com Tue Oct 31 02:06:44 2006 From: rdm at rcblue.com (Dick Moores) Date: Mon, 30 Oct 2006 17:06:44 -0800 Subject: [Tutor] Using sys.exit() Message-ID: <7.0.1.0.2.20061030163602.0318b238@rcblue.com> I'd like to know how to use sys.exit() to quit a program. Here's a simple example: import sys c = 0 while True: c += 1 if c > 10000: sys.exit() Now, this will certainly exit, but not without a lot of extra noise. Is there a way to use it the way I want to? Maybe with an argument? I'm writing a script, which in a couple of places I can't use "break" to quit. Thanks, Dick Moores From lucidmonk at gmail.com Tue Oct 31 02:20:27 2006 From: lucidmonk at gmail.com (Todd Dahl) Date: Mon, 30 Oct 2006 20:20:27 -0500 Subject: [Tutor] Running multiple version of Python on 1 windows machine Message-ID: <44290fe50610301720v43cfc357p91e5756516c3722f@mail.gmail.com> At work I have installed Python 2.4 but at home I have Python 2.5. Until this point I didn't think nothing of it but now I have run into a issue. I have some code that I have worked on at work that uses the pySQLite module which doesn't support 2.5, yet. I can run my code at work but I can't even install the module at home. So my question is how do I configure my machine at home so I can have multiple versions of python running so I can run this code. Or is this a bad and/or confusing thing to do. Thanks -Todd From jazedo at netcabo.pt Tue Oct 31 02:29:25 2006 From: jazedo at netcabo.pt (Jorge Azedo) Date: Tue, 31 Oct 2006 01:29:25 +0000 Subject: [Tutor] Suggestions about documenting a function Message-ID: <4546A6F5.8060203@netcabo.pt> I'm writing a function that generates a list with user defined length, that consists only of non-repeating random integers in a user defined range. Even I don't understand what I just wrote, so I'm just going to post the code and an example of the results :P ## Test module ## Last revision 31 October 2006 import random def randomList(n1,n2,len): '''n1-n2 range of numbers, len - length of the final list Returns a list''' i=0 rndlist=[] if len > n2: return 'The length of the list must be greater than n2' else: while i < len: rand=random.randint(n1,n2) if rndlist.count(rand) == 0: rndlist.append(rand) i=i+1 return rndlist randomList(1,9,9) [9, 8, 1, 4, 7, 6, 5, 3, 2] Not sure if the indentation in this message is correct, but the module works, so that's not the problem. What I really want to ask is: Any suggestions on how to improve the documentation part of the module? I'd like to warn the user about the fact that len must be greater than n2 before he runs it, but I can't think of a short enough way to say it so that it still appears in that little window that shows up when you start writing the arguments to a function. Sorry if this is confusing From rabidpoobear at gmail.com Tue Oct 31 02:48:43 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 30 Oct 2006 19:48:43 -0600 Subject: [Tutor] Suggestions about documenting a function In-Reply-To: <4546A6F5.8060203@netcabo.pt> References: <4546A6F5.8060203@netcabo.pt> Message-ID: <4546AB7B.8070809@gmail.com> Jorge Azedo wrote: > I'm writing a function that generates a list with user defined length, > that consists only of non-repeating random integers in a user defined range. > Even I don't understand what I just wrote, so I'm just going to post the > code and an example of the results :P > > ## Test module > ## Last revision 31 October 2006 > > import random > > def randomList(n1,n2,len): > '''n1-n2 range of numbers, len - length of the final list > > Returns a list''' > > i=0 > rndlist=[] > if len > n2: > return 'The length of the list must be greater than n2' > else: > while i < len: > rand=random.randint(n1,n2) > if rndlist.count(rand) == 0: > rndlist.append(rand) > i=i+1 > return rndlist It doesn't seem like this code does what it should, does it? I mean, if you did randomList(9,9,9) wouldn't it go into an infinite loop? And why does the length have to be greater than n2? that doesn't make sense. What if I want to have 5 random numbers from within the 10 to 100 range? randomList(10,100,5) wouldn't work. Does this function really meet the requirements you need? -Luke From kent37 at tds.net Tue Oct 31 03:00:43 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 30 Oct 2006 21:00:43 -0500 Subject: [Tutor] Running multiple version of Python on 1 windows machine In-Reply-To: <44290fe50610301720v43cfc357p91e5756516c3722f@mail.gmail.com> References: <44290fe50610301720v43cfc357p91e5756516c3722f@mail.gmail.com> Message-ID: <4546AE4B.9060006@tds.net> Todd Dahl wrote: > At work I have installed Python 2.4 but at home I have Python 2.5. > Until this point I didn't think nothing of it but now I have run into > a issue. > > I have some code that I have worked on at work that uses the pySQLite > module which doesn't support 2.5, yet. I can run my code at work but I > can't even install the module at home. > > So my question is how do I configure my machine at home so I can have > multiple versions of python running so I can run this code. Or is this > a bad and/or confusing thing to do. pysqlite is included in the standard library in Python 2.5, that is why there is no support on the pysqlite web site. The package name is different, you can write the code with conditional imports e.g. try import sqlite3 as sqlite # Python 2.5 except ImportError: from pysqlite2 import dbapi2 as sqlite If changing the code is not an option you might be able to fake it out by making a pysqlite2.dbapi2 module that just contains from sqlite3 import * I haven't tried any of this so I could be off base. I'm assuming that the bundled version is the same as the one you have at work other than the package name You don't say what OS you are running but under Windows it is trivial to have multiple versions of Python installed, I have 2.3, 2.4 and 2.5. They are each in their own directories, all in the system path. I have aliases called py23, py24 and py25 that let me launch the version I want. I'm pretty sure you can do something similar with other OSes. Kent From john at fouhy.net Tue Oct 31 03:01:13 2006 From: john at fouhy.net (John Fouhy) Date: Tue, 31 Oct 2006 15:01:13 +1300 Subject: [Tutor] Suggestions about documenting a function In-Reply-To: <4546A6F5.8060203@netcabo.pt> References: <4546A6F5.8060203@netcabo.pt> Message-ID: <5e58f2e40610301801m1ceecb77ybdcb5b562a89591a@mail.gmail.com> On 31/10/06, Jorge Azedo wrote: > def randomList(n1,n2,len): > '''n1-n2 range of numbers, len - length of the final list > > Returns a list''' > > i=0 > rndlist=[] > if len > n2: > return 'The length of the list must be greater than n2' Comment --- think about raising an exception here, instead of returning an error message string. > Not sure if the indentation in this message is correct, but the module > works, so that's not the problem. What I really want to ask is: Any > suggestions on how to improve the documentation part of the module? I'd > like to warn the user about the fact that len must be greater than n2 > before he runs it, but I can't think of a short enough way to say it so > that it still appears in that little window that shows up when you > start writing the arguments to a function. > Sorry if this is confusing Not sure what you mean about the "little window" -- is that an IDLE thing? (I don't use IDLE, sorry) Another comment -- I would avoid using 'len' as the name of an argument, since 'len' is also the builtin length function. It's not an error to reuse the name, but most python programmers would expect len to be the builtin when reading code. For example, instead of n1,n2,len, I would probably do something like: def randomList(lo, hi, n) Comment three -- as Luke points out, you probably need another constraint to avoid looping endlessly. Perhaps 'hi-lo <= (n+1)'. Fourth comment -- you could enforce your range constraints by using assert. ie: def randomList(lo, hi, n): assert lo <= hi assert 0 <= n <= hi assert hi-lo <= n+1 What about this: def randomList(lo, hi, n): """Return n distinct random integers taken from range(lo, hi+1), where n <= hi. lo, hi, n :: int output :: [int] Constraints: lo <= hi 0 <= n <= hi hi-lo <= n+1 >>> sorted(randomList(1, 9, 9)) == range(1, 10) >>> randomList(1, 10, 0) == [] >>> randomList(4, 3, 2) AssertionError >>> randomList(7, 8, 5) AssertionError >>> randomList(-5, 7, 9) AssertionError """ (those things at the end are doctests. Read about them in the doctest module. Also, I haven't tested these doctests :-) ) (incidentally, apart from your condition on n <= hi, your function is equivalent to: def randomList(lo, hi, n): return random.sample(range(lo, hi+1), n) ) -- John. From rdm at rcblue.com Tue Oct 31 03:12:34 2006 From: rdm at rcblue.com (Dick Moores) Date: Mon, 30 Oct 2006 18:12:34 -0800 Subject: [Tutor] Using sys.exit() In-Reply-To: <7.0.1.0.2.20061030163602.0318b238@rcblue.com> References: <7.0.1.0.2.20061030163602.0318b238@rcblue.com> Message-ID: <7.0.1.0.2.20061030180949.08331238@rcblue.com> At 05:06 PM 10/30/2006, Dick Moores wrote: >I'd like to know how to use sys.exit() to quit a program. > >Here's a simple example: > >import sys > >c = 0 >while True: > c += 1 > if c > 10000: > sys.exit() > >Now, this will certainly exit, but not without a lot of extra noise. >Is there a way to use it the way I want to? Maybe with an argument? >I'm writing a script, which in a couple of places I can't use "break" to quit. I just found this: So the "noise" from sys.exit() is from using it "inside" Wing IDE. At the command line, the exit is silent. Sorry for the disturbance. Dick >Thanks, > >Dick Moores > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor From jazedo at netcabo.pt Tue Oct 31 03:33:39 2006 From: jazedo at netcabo.pt (Jorge Azedo) Date: Tue, 31 Oct 2006 02:33:39 +0000 Subject: [Tutor] Suggestions about documenting a function In-Reply-To: <5e58f2e40610301801m1ceecb77ybdcb5b562a89591a@mail.gmail.com> References: <4546A6F5.8060203@netcabo.pt> <5e58f2e40610301801m1ceecb77ybdcb5b562a89591a@mail.gmail.com> Message-ID: <4546B603.8000902@netcabo.pt> Thanks for your help guys. It will take me some time to understand exactly what you suggested to fix the function (I'm still a newb at this) but thanks for your help. I'll keep you posted on the updates :) From pyro9219 at gmail.com Tue Oct 31 07:14:25 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Mon, 30 Oct 2006 22:14:25 -0800 Subject: [Tutor] Using sys.exit() In-Reply-To: <7.0.1.0.2.20061030180949.08331238@rcblue.com> References: <7.0.1.0.2.20061030163602.0318b238@rcblue.com> <7.0.1.0.2.20061030180949.08331238@rcblue.com> Message-ID: Try using SPE, I've really liked it for some of extra features inside it like TODO tags that are automanaged. Also, its written in python, so thats kinda cool factor. It's also free. On 10/30/06, Dick Moores wrote: > > At 05:06 PM 10/30/2006, Dick Moores wrote: > >I'd like to know how to use sys.exit() to quit a program. > > > >Here's a simple example: > > > >import sys > > > >c = 0 > >while True: > > c += 1 > > if c > 10000: > > sys.exit() > > > >Now, this will certainly exit, but not without a lot of extra noise. > >Is there a way to use it the way I want to? Maybe with an argument? > >I'm writing a script, which in a couple of places I can't use "break" to > quit. > > I just found this: > < > http://www.velocityreviews.com/forums/t359590-how-to-terminate-a-main-script.html > > > > So the "noise" from sys.exit() is from using it "inside" Wing IDE. At > the command line, the exit is silent. > > Sorry for the disturbance. > > Dick > > > >Thanks, > > > >Dick Moores > > > >_______________________________________________ > >Tutor maillist - Tutor at python.org > >http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061030/0b9db79a/attachment.html From nephish at gmail.com Tue Oct 31 08:35:48 2006 From: nephish at gmail.com (shawn bright) Date: Tue, 31 Oct 2006 01:35:48 -0600 Subject: [Tutor] question about pylab Message-ID: <384c93600610302335p1d3ee357y1197867d0eba3264@mail.gmail.com> hey there, i am trying to use a graph and chart app called matplotlib, but i cannot figgure out how to have it plot a simple chart over time. the docs say to use the function plot_date() but i cannot seem to get the values to agree. I am sending datetimes to the charting app for x, and the y is a list of values that the our equipment reports. sometimes there are lots of reports in a row, and i would like the chart to show it like that instead of plotting out every time as an evenly spaced tick on the x scale. Does this make any sense, what i am after here? Anyway, if any of you have much experience with this sort of thing, or may suggest a package (pylab is my first attempt) please send me some advice. thanks for your time, sk -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061031/d31da568/attachment.htm From alan.gauld at btinternet.com Tue Oct 31 09:14:46 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 31 Oct 2006 08:14:46 -0000 Subject: [Tutor] Using sys.exit() References: <7.0.1.0.2.20061030163602.0318b238@rcblue.com> Message-ID: "Dick Moores" wrote > I'd like to know how to use sys.exit() to quit a program. > I see that you already figured that out. You can also quit by raising SystemExit, which is what sys.exit does... but you don't need to import sys... > Is there a way to use it the way I want to? Maybe with an argument? You can use an argument if you want to pass an error value back to the OS. This is good practice if your script might be used in a batch file or shell script > I'm writing a script, which in a couple of places I can't > use "break" to quit. break is not intended to quit programs, break is intended to quit loops. To exit a program you should use sys.exit() and if its an abnormal exit provide an argument. Alan G. From alan.gauld at btinternet.com Tue Oct 31 09:37:14 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 31 Oct 2006 08:37:14 -0000 Subject: [Tutor] Suggestions about documenting a function References: <4546A6F5.8060203@netcabo.pt> Message-ID: "Jorge Azedo" wrote > import random > > def randomList(n1,n2,len): > '''n1-n2 range of numbers, len - length of the final list > > Returns a list''' Don't worry too much about writing the doc string to fit in the IDE hint box. Think more about how it will look when people use help() or __doc__ to print the documentation. Specifically this doc string isn't actually too helpful since it only tells me the data types of the inputs and outputs but gives no clues about the actual purpose of the function. Specifically it doesn't make it clear that the returned list will contain *unique* random numbers from the range > i=0 > rndlist=[] > if len > n2: > return 'The length of the list must be greater than n2' Huh? This can never work. If I use 99,100,101 that implies you will give me 101 unique numbers between 99 and 100... Surely the constraint should be that len < n2-n1 Also, what happens if n1 > n2? (This is also a bug in randint IMHO...) > before he runs it, but I can't think of a short enough way to say it > so > that it still appears in that little window that shows up when you > start writing the arguments to a function. Don't even try... or if you must keep the input summary on one line and expand the second paragraph to describe what it does. BTW One common notation for defining functoion signatures is param,param,param... -> result. So in your case you could use: (n1 int, n2 int, length int) -> list : n1 < n2, ln < n2-n1 which is more concise and includes the constraints... but still doesn't convey the intent. HTH -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From markusro at element.fkp.physik.tu-darmstadt.de Tue Oct 31 09:41:21 2006 From: markusro at element.fkp.physik.tu-darmstadt.de (Markus Rosenstihl) Date: Tue, 31 Oct 2006 09:41:21 +0100 Subject: [Tutor] question about pylab In-Reply-To: <384c93600610302335p1d3ee357y1197867d0eba3264@mail.gmail.com> References: <384c93600610302335p1d3ee357y1197867d0eba3264@mail.gmail.com> Message-ID: Am 31.10.2006 um 08:35 schrieb shawn bright: > hey there, > i am trying to use a graph and chart app called matplotlib, but i > cannot figgure out how to have it plot a simple chart over time. > the docs say to use the function plot_date() but i cannot seem to get > the values to agree. > I am sending datetimes to the charting app for x, and the y is a list > of values that the our equipment reports. > sometimes there are lots of reports in a row, and i would like the > chart to show it like that instead of plotting out every time as an > evenly spaced tick on the x scale. Does this make any sense, what i am > after here? Anyway, if any of you have much experience with this sort > of thing, or may suggest a package (pylab is my first attempt) please > send me some advice. > > thanks for your time, > sk I am not sure if I get it right, could you give us some sample data and some code what you have tried? I never used plot_date, but I could give it a try. Regards, Markus From kent37 at tds.net Tue Oct 31 12:06:09 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 31 Oct 2006 06:06:09 -0500 Subject: [Tutor] question about pylab In-Reply-To: <384c93600610302335p1d3ee357y1197867d0eba3264@mail.gmail.com> References: <384c93600610302335p1d3ee357y1197867d0eba3264@mail.gmail.com> Message-ID: <45472E21.60400@tds.net> shawn bright wrote: > hey there, > i am trying to use a graph and chart app called matplotlib, but i cannot > figgure out how to have it plot a simple chart over time. > the docs say to use the function plot_date() but i cannot seem to get > the values to agree. > I am sending datetimes to the charting app for x, and the y is a list of > values that the our equipment reports. > sometimes there are lots of reports in a row, and i would like the chart > to show it like that instead of plotting out every time as an evenly > spaced tick on the x scale. Does this make any sense, what i am after > here? Anyway, if any of you have much experience with this sort of > thing, or may suggest a package (pylab is my first attempt) please send > me some advice. I have used pylab to create a scatterplot of date vs value. The date values were created by calling pylab.date2num() on a datetime.datetime value. The axes were set up with this code: # Set up the xaxis ax = axes([0.05, 0.05, 0.9, 0.9]) ax.xaxis.set_major_locator(MinuteLocator(interval=10)) ax.xaxis.set_minor_locator(MinuteLocator()) ax.xaxis.set_major_formatter(DateFormatter("%H:%M")) I called pylab.scatter() to create the plot. HTH, Kent From prem.sah at gmail.com Tue Oct 31 13:58:06 2006 From: prem.sah at gmail.com (Premnath Sah) Date: Tue, 31 Oct 2006 18:28:06 +0530 Subject: [Tutor] immutable objects Message-ID: <795ac870610310458mf07d9c4ra385b2375c46d3e0@mail.gmail.com> Hi, from http://docs.python.org/ref/objects.htm """Types affect almost all aspects of object behavior. Even the importance of object identity is affected in some sense: for immutable types, operations that compute new values may actually return a reference to any existing object with the same type and value, while for mutable objects this is not allowed. E.g., after "a = 1; b = 1", a and b may or may not refer to the same object with the value one, depending on the implementation, but after "c = []; d = []", c and d are guaranteed to refer to two different, unique, newly created empty lists. (Note that "c = d = []" assigns the same object to both c and d.)""" I would like to know how i can guarantee that a new immutable object is infact a new object. Example: >>> a = 1 >>> b = 1 >>> a is b True is what i get. i want a and b to be two different object. Thanks in advance Premnath Sah T. H. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061031/a158c552/attachment.htm From kent37 at tds.net Tue Oct 31 15:08:22 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 31 Oct 2006 09:08:22 -0500 Subject: [Tutor] immutable objects In-Reply-To: <795ac870610310458mf07d9c4ra385b2375c46d3e0@mail.gmail.com> References: <795ac870610310458mf07d9c4ra385b2375c46d3e0@mail.gmail.com> Message-ID: <454758D6.4080109@tds.net> Premnath Sah wrote: > I would like to know how i can guarantee that a new immutable object is > infact a new object. > > Example: > > >>> a = 1 > >>> b = 1 > >>> a is b > True > > is what i get. i want a and b to be two different object. I don't think there is any way to control this for the builtin types. Why do you care? Kent From prem.sah at gmail.com Tue Oct 31 15:26:37 2006 From: prem.sah at gmail.com (Premnath Sah) Date: Tue, 31 Oct 2006 19:56:37 +0530 Subject: [Tutor] immutable objects In-Reply-To: <454758D6.4080109@tds.net> References: <795ac870610310458mf07d9c4ra385b2375c46d3e0@mail.gmail.com> <454758D6.4080109@tds.net> Message-ID: <795ac870610310626p532f5bbajc5fbbcbc74ea9317@mail.gmail.com> On 10/31/06, Kent Johnson wrote: > > Premnath Sah wrote: > > I would like to know how i can guarantee that a new immutable object is > > infact a new object. > > > > Example: > > > > >>> a = 1 > > >>> b = 1 > > >>> a is b > > True > > > > is what i get. i want a and b to be two different object. > > I don't think there is any way to control this for the builtin types. > Why do you care? Im facing a problem with SOAPpy which checks for recursive objects using id(obj). In my case value for 2 SOAP headers are same and iam getting a recursion error. if i pass different object with same value SOAPpy does not complain (by using str(value) and unicode(value)). Thanks Premnath Sah T. H. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061031/32ab9164/attachment.html From nephish at gmail.com Tue Oct 31 15:45:39 2006 From: nephish at gmail.com (shawn bright) Date: Tue, 31 Oct 2006 08:45:39 -0600 Subject: [Tutor] question about pylab In-Reply-To: <45472E21.60400@tds.net> References: <384c93600610302335p1d3ee357y1197867d0eba3264@mail.gmail.com> <45472E21.60400@tds.net> Message-ID: <384c93600610310645i48f4a746n2d4c8b5778361ae3@mail.gmail.com> ok, looks like the date2num() function on a datetime.datetime object is working. So cool. i am very new at this, so i may be back ( read probably be back ). Thanks much for the tips. i appreciate it a lot. sk On 10/31/06, Kent Johnson wrote: > > shawn bright wrote: > > hey there, > > i am trying to use a graph and chart app called matplotlib, but i cannot > > figgure out how to have it plot a simple chart over time. > > the docs say to use the function plot_date() but i cannot seem to get > > the values to agree. > > I am sending datetimes to the charting app for x, and the y is a list of > > values that the our equipment reports. > > sometimes there are lots of reports in a row, and i would like the chart > > to show it like that instead of plotting out every time as an evenly > > spaced tick on the x scale. Does this make any sense, what i am after > > here? Anyway, if any of you have much experience with this sort of > > thing, or may suggest a package (pylab is my first attempt) please send > > me some advice. > > I have used pylab to create a scatterplot of date vs value. The date > values were created by calling pylab.date2num() on a datetime.datetime > value. The axes were set up with this code: > > # Set up the xaxis > ax = axes([0.05, 0.05, 0.9, 0.9]) > > ax.xaxis.set_major_locator(MinuteLocator(interval=10)) > ax.xaxis.set_minor_locator(MinuteLocator()) > ax.xaxis.set_major_formatter(DateFormatter("%H:%M")) > > > I called pylab.scatter() to create the plot. > > HTH, > Kent > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061031/86a396df/attachment.htm From carloslara at web.de Tue Oct 31 16:11:24 2006 From: carloslara at web.de (Carlos) Date: Tue, 31 Oct 2006 16:11:24 +0100 Subject: [Tutor] M Arch Thesis Message-ID: <4547679C.3030709@web.de> Hi to all, For my Thesis project, I want to use a Genetic Algorithm to generate multiple spatial organization solutions for Architectural projects. My idea is that a software that does this would be useful as a rapid prototyping tool and more important it will probably reach solutions that a human user would not. The problem is that I can't find a GA module for python that is reasonably easy to use, do you know if there is something out there that can help me? I would like to find something with a black box approach, in this case I would only need to feed the system some information and get a result in the end, forgetting a little about the process itself. Dont think me lazy is just that I'm new to python and my time is limited. By the way, do you think that a GA solution is good for this project, maybe someone has a better idea. Thanks, Carlos From dyoo at hkn.eecs.berkeley.edu Tue Oct 31 16:41:56 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 31 Oct 2006 07:41:56 -0800 (PST) Subject: [Tutor] immutable objects In-Reply-To: <795ac870610310626p532f5bbajc5fbbcbc74ea9317@mail.gmail.com> References: <795ac870610310458mf07d9c4ra385b2375c46d3e0@mail.gmail.com> <454758D6.4080109@tds.net> <795ac870610310626p532f5bbajc5fbbcbc74ea9317@mail.gmail.com> Message-ID: > Im facing a problem with SOAPpy which checks for recursive objects using > id(obj). > > In my case value for 2 SOAP headers are same and iam getting a recursion > error. if i pass different object with same value SOAPpy does not complain > (by using str(value) and unicode(value)). If you can include a stack trace of that error with SOAPpy, that would be excellent. This sounds bizarre. You won't be able to do anything with the ints: some of them are internally interned by the runtime, and you can't control this. So I'd instead focus on why SOAPpy is failing. It shouldn't have to worry about recursively traversing the ints: they don't have any structure to traverse! So a stack trace would be useful. From patrat46 at gmail.com Tue Oct 31 17:23:48 2006 From: patrat46 at gmail.com (patrat) Date: Tue, 31 Oct 2006 08:23:48 -0800 Subject: [Tutor] senior project Message-ID: <23f037950610310823x324cee58hcc5473ad3b23159a@mail.gmail.com> i am a senior in high school, my school requires me to get a mentor and interview 2 people for my senior project. i am wondering if any one would be my mentor or be willing to answer some questions. if you are interested please email me -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061031/1c3aec97/attachment.html From mhansen at cso.atmel.com Tue Oct 31 23:29:32 2006 From: mhansen at cso.atmel.com (Mike Hansen) Date: Tue, 31 Oct 2006 15:29:32 -0700 Subject: [Tutor] Mapping to object attributes Message-ID: <000301c6fd3c$09c10e70$28645f0a@1430A0316> I've got a web form with a lot of form fields. I'd like to be able to map the form fields to an object's attributes. I'm having a little trouble figuring out how. I was thinking of something like this.. form = cgi.FieldStorage() widget = Widget() form_field_object_map = {'widget_name' : widget.name, 'alt_widget_name' : widget.alt_name, ...} for form_field in form_field_object_map.keys(): form_field_object_map[form_field]...er.... I'd like to avoid a pile if elif elifs. It seems like there should be a cleaner way. if form_field == 'widget_name': widget.widget_name = form.getvalue(form_field) elif form_field == 'alt_widget_name': widget.alt_name = form.getvalue(form_field) elif ... There will be some fields I'll need to validate(boolean or int), but the majority are just text fields that can be passed to the object. Anyone got any ideas on how to do this? Thanks, Mike From john at fouhy.net Tue Oct 31 23:44:57 2006 From: john at fouhy.net (John Fouhy) Date: Wed, 1 Nov 2006 11:44:57 +1300 Subject: [Tutor] Mapping to object attributes In-Reply-To: <000301c6fd3c$09c10e70$28645f0a@1430A0316> References: <000301c6fd3c$09c10e70$28645f0a@1430A0316> Message-ID: <5e58f2e40610311444k2a9ff5bcmea138297f7f7c46f@mail.gmail.com> On 01/11/06, Mike Hansen wrote: > form = cgi.FieldStorage() > widget = Widget() > > form_field_object_map = {'widget_name' : widget.name, > 'alt_widget_name' : widget.alt_name, > ...} > > for form_field in form_field_object_map.keys(): > form_field_object_map[form_field]...er.... This won't work, because python will look up widget.name and replace it with the value of widget.name when it creates the dictionary. You can probably do something with setattr. Check the docs for details, but basically, setattr(thing, 'foo', 'bar') is equivalent to thing.foo = 'bar' eg: form_field_object_map = { 'widget_name':'name', 'alt_widget_name':'alt_name', } # etc form = cgi.FieldStorage() widget = Widget() for form_field in form_field_object_map: setattr(widget, form_field_object_map[form_field], form.getvalue(form_field)) HTH! -- John.