From modulok at gmail.com Sun Apr 1 00:28:15 2012 From: modulok at gmail.com (Modulok) Date: Sat, 31 Mar 2012 16:28:15 -0600 Subject: [Tutor] breeds of Python ..... In-Reply-To: <4F777931.5010204@crosswire.org> References: <4F777931.5010204@crosswire.org> Message-ID: After following the reading suggestions, I soon found myself looking at quite a few code examples that would only run under a particular version of python. Finally, I converted the example that I was working on to run under Python3. I just wondered if you guys would advise a newbie like me to concentrate on Python3 or stay with Python2 and get into bad habits when it comes to change eventually? Apart from the print and input functions, I haven't so far got a lot to re-learn. Kind regards, Barry. Barry, If you're just starting out, go with 3.x. If you have a need for some third party modules that aren't yet available for 3.x, you'll have to stick with 2.x. Most beginner tutorials will work without changes, except for the print statement is now a function, e.g: print "foo" Is now: print("foo") There isn't a whole lot of difference in syntax to learn. Some modules have been renamed, some module functions re-worked, etc. Probably the biggest change is the move to all unicode strings. One thing you can do if you're running 2.x but want to get into the 3.x swing of things is turn on 3.x warnings. It will tell you if you did something the 2to3 tool can't automatically fix: python2.6 -3 If you want, you can actually use the 3.x style print function and true division when using 2.x by putting this at the top of your code:: from __future__ import print_function from __future__ import division Now in 2.x, just like 3.x this will raise an exception: print "foo" #<-- Now fails in 2.x print("foo") #<-- Works. -Modulok- From alan.gauld at btinternet.com Sun Apr 1 01:50:30 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 01 Apr 2012 00:50:30 +0100 Subject: [Tutor] Syntax error help In-Reply-To: References: <4F7625EE.4090701@gmail.com> <9742C3BA-DFB0-4077-9749-D9DFD668B3A7@gmail.com> <4F7643F2.8080403@gmail.com> <4F7669FF.7020504@gmail.com> Message-ID: On 31/03/12 03:33, S.Irfan Rizvi wrote: > Please remove me from list....i can't do it....they are doing it Attention > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Only you could have joined the list and only you can unsubscribe. Go to the web page and follow the instructions. If it doesn't work email me and I'll try to figure out what's going wrong. -- Alan G Tutor list moderator (and just home from vacation...) From s.irfan.rizvi5 at gmail.com Sun Apr 1 05:52:44 2012 From: s.irfan.rizvi5 at gmail.com (S.Irfan Rizvi) Date: Sat, 31 Mar 2012 21:52:44 -0600 Subject: [Tutor] Syntax error help In-Reply-To: References: <4F7625EE.4090701@gmail.com> <9742C3BA-DFB0-4077-9749-D9DFD668B3A7@gmail.com> <4F7643F2.8080403@gmail.com> <4F7669FF.7020504@gmail.com> Message-ID: Its failing i can't able to unsubcribe please remove me from ....its not going to Span either *Error: **Authentication failed.*Tutor list: member options login pageIn order to change your membership option, you must first log in by giving your email address and membership password in the section below. If you don't remember your membership password, you can have it emailed to you by clicking on the button below. If you just want to unsubscribe from this list, click on the * Unsubscribe* button and a confirmation message will be sent to you. *Important:* From this point on, you must have cookies enabled in your browser, otherwise none of your changes will take effect. Email address: Password: UnsubscribeBy clicking on the *Unsubscribe* button, a confirmation message will be emailed to you. This message will have a link that you should click on to complete the removal process (you can also confirm by email; see the instructions in the confirmation message).Password reminderBy clicking on the *Remind* button, your password will be emailed to you. On Mar 31, 2012 6:51 PM, "Alan Gauld" wrote: > On 31/03/12 03:33, S.Irfan Rizvi wrote: > >> Please remove me from list....i can't do it....they are doing it Attention >> ______________________________**_________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/**mailman/listinfo/tutor >> > > Only you could have joined the list and only you can unsubscribe. > Go to the web page and follow the instructions. > > If it doesn't work email me and I'll try to figure out what's > going wrong. > > -- > Alan G > Tutor list moderator > (and just home from vacation...) > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From s.irfan.rizvi5 at gmail.com Sun Apr 1 05:58:08 2012 From: s.irfan.rizvi5 at gmail.com (S.Irfan Rizvi) Date: Sat, 31 Mar 2012 21:58:08 -0600 Subject: [Tutor] breeds of Python ..... In-Reply-To: References: <4F777931.5010204@crosswire.org> Message-ID: please remove me from here On Sat, Mar 31, 2012 at 4:28 PM, Modulok wrote: > After following the reading suggestions, I soon found myself looking > at quite a few code examples that would only run under a particular > version of python. ?Finally, I converted the example that I was > working on to run under Python3. ?I just wondered if you guys would > advise a newbie like me to concentrate on Python3 or stay with Python2 > and get into bad habits when it comes to change eventually? ?Apart > from the print and input functions, I haven't so far got a lot to > re-learn. > > Kind regards, ? ? ? ?Barry. > > > Barry, > > If you're just starting out, go with 3.x. If you have a need for some third > party modules that aren't yet available for 3.x, you'll have to stick with 2.x. > Most beginner tutorials will work without changes, except for the print > statement is now a function, e.g: > > ? ?print "foo" > > Is now: > > ? ?print("foo") > > There isn't a whole lot of difference in syntax to learn. Some modules have > been renamed, some module functions re-worked, etc. Probably the biggest change > is the move to all unicode strings. One thing you can do if you're running 2.x > but want to get into the 3.x swing of things is turn on 3.x warnings. It will > tell you if you did something the 2to3 tool can't automatically fix: > > ? ?python2.6 -3 > > If you want, you can actually use the 3.x style print function and true > division when using 2.x by putting this at the top of your code:: > > ? ?from __future__ import print_function > ? ?from __future__ import division > > Now in 2.x, just like 3.x this will raise an exception: > > ? ?print "foo" ? ? #<-- Now fails in 2.x > ? ?print("foo") ? ?#<-- Works. > > -Modulok- > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- ? ? ? ?Regards ? ?? ~ S. Irfan Rizvi ?ADR-TS From s.irfan.rizvi5 at gmail.com Sun Apr 1 05:59:20 2012 From: s.irfan.rizvi5 at gmail.com (S.Irfan Rizvi) Date: Sat, 31 Mar 2012 21:59:20 -0600 Subject: [Tutor] breeds of Python ..... In-Reply-To: References: <4F777931.5010204@crosswire.org> Message-ID: please remove me from here From swiftone at swiftone.org Sun Apr 1 07:19:55 2012 From: swiftone at swiftone.org (Brett Ritter) Date: Sun, 1 Apr 2012 01:19:55 -0400 Subject: [Tutor] breeds of Python ..... In-Reply-To: <4F777931.5010204@crosswire.org> References: <4F777931.5010204@crosswire.org> Message-ID: On Sat, Mar 31, 2012 at 5:37 PM, Barry Drake wrote: > concentrate on Python3 or stay with Python2 and get into bad habits when it > comes to change eventually? ?Apart from the print and input functions, I > haven't so far got a lot to re-learn. My recommendation is to go with Python2 - most major projects haven't made the switch and I'd expect another year or two before they do so. Many tutorials and examples are Python 2-based and there are not that many differences to unlearn in terms of habits. -- Brett Ritter / SwiftOne swiftone at swiftone.org From bdrake at crosswire.org Sun Apr 1 12:43:32 2012 From: bdrake at crosswire.org (Barry Drake) Date: Sun, 01 Apr 2012 11:43:32 +0100 Subject: [Tutor] breeds of Python ..... In-Reply-To: References: <4F777931.5010204@crosswire.org> Message-ID: <4F783154.7090003@crosswire.org> On 01/04/12 06:19, Brett Ritter wrote: > My recommendation is to go with Python2 - most major projects haven't > made the switch and I'd expect another year or two before they do so. > Many tutorials and examples are Python 2-based and there are not that > many differences to unlearn in terms of habits. Thanks Brett and those who replied. As my only reason for getting into Python is to be able to show the kids at the local school a bit about programming, and as I've no investment in existing code at all, I'm going to go with Python3. The tutorials and examples I have are as plentiful in Python3 as in Python2, and the ones I might want from the Python2 tutorial will be easy to convert and will help the learning process. The main reason I asked the opinion of this list was in case there was a vast opinion gap like there is in Ubuntu between Unity lovers and Unity haters. I guess Unity is a bit like Marmite. I get the view that Python3 is just a natural progression. I never experienced this with c as the standard library base on Kernighan and Ritchie never seemed to change its syntax from the word go. Kind regards, Barry. -- From Barry Drake - a member of the Ubuntu advertising team. From bdrake at crosswire.org Sun Apr 1 13:29:18 2012 From: bdrake at crosswire.org (Barry Drake) Date: Sun, 01 Apr 2012 12:29:18 +0100 Subject: [Tutor] breeds of Python ..... In-Reply-To: <4F783B4C.50600@crosswire.org> References: <4F783B4C.50600@crosswire.org> Message-ID: <4F783C0E.7080400@crosswire.org> On 01/04/12 12:03, Leam Hall wrote: > For that path I'd agree that Python 3 is the way to go. I believe > PyGame is Python 3 ready so you've got an automatic hook for the kids. > Heck, probably many of their parents as well! > Check out the book "More Python programming for the absolute beginner" > as it teaches Python and PyGame at the same time. I've played around with PyGame on Python2 - hadn't realised it was ready for Python3 yet. It's just the kind of thing that would have sparked my son off when he was a kid. He wrote hundreds of lines in the rather dumb Basic that the Speccy used in the olden days, and guess what - when he went to uni, his degree was in computer science! I really hated Basic, and programmed in Z80 assembler until I met with c and learned how much fun programming could really be. Python is even more fun. I was a bit taken aback a few years later when my son left his job as sys-admin for a big firm. He said that the work was a job for a twenty-year old whiz-kid. He was more interested in how business works. He now charges an absolute fortune as a freelance consultant. Kind regards, Barry -- From Barry Drake - a member of the Ubuntu advertising team. From alan.gauld at btinternet.com Sun Apr 1 16:26:15 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 01 Apr 2012 15:26:15 +0100 Subject: [Tutor] breeds of Python ..... In-Reply-To: <4F783154.7090003@crosswire.org> References: <4F777931.5010204@crosswire.org> <4F783154.7090003@crosswire.org> Message-ID: On 01/04/12 11:43, Barry Drake wrote: > On 01/04/12 06:19, Brett Ritter wrote: > is just a natural progression. I never experienced this with c as the > standard library base on Kernighan and Ritchie never seemed to change > its syntax from the word go. Actually the standardization of C sparked huge debates in the early 90's. There were lots of minor changes and one big style change that really polarised opinions. In traditional C you defined a functions parameters like int foo() int a; float b; { /* body here */ } in ANSI that changed to: inf foo(int a, float b) { // body here } The changes from Python 2 to Python 3 have been a model of harmony in comparison, and they are the biggest changes in Python's 20 year history. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From bdrake at crosswire.org Sun Apr 1 17:26:43 2012 From: bdrake at crosswire.org (Barry Drake) Date: Sun, 01 Apr 2012 16:26:43 +0100 Subject: [Tutor] breeds of Python ..... In-Reply-To: <4F78361C.4020603@gmail.com> References: <4F777931.5010204@crosswire.org> <4F783154.7090003@crosswire.org> <4F78361C.4020603@gmail.com> Message-ID: <4F7873B3.3070908@crosswire.org> On 01/04/12 12:03, Leam Hall wrote: > I believe PyGame is Python 3 ready so you've got an automatic hook for > the kids. Heck, probably many of their parents as well! PyGame is available for Python3 but not pre-built from the Ubuntu or Debian repos as far as I can see. I got the source from the PyGame site and built it. Note that the required c headers to build it are not in the standard install of Python3, so I had to get the matching source package and manually put the headers into the appropriate place. After that, it seems to build and work OK, and the PyGame examples are fun and helpful. I now await my Raspberry-pi to see what stuff I can run on it. I assume it comes with Python3 in the bootable Fedora OS. By the time it comes, I thinnk I'll have found my way around Python to a usable extent. Regards, Barry. -- From Barry Drake - a member of the Ubuntu advertising team. From bdrake at crosswire.org Sun Apr 1 17:34:17 2012 From: bdrake at crosswire.org (Barry Drake) Date: Sun, 01 Apr 2012 16:34:17 +0100 Subject: [Tutor] breeds of Python ..... In-Reply-To: References: <4F777931.5010204@crosswire.org> <4F783154.7090003@crosswire.org> Message-ID: <4F787579.4020200@crosswire.org> On 01/04/12 15:26, Alan Gauld wrote: > Actually the standardization of C sparked huge debates in the early > 90's. There were lots of minor changes and one big style change that > really polarised opinions. In traditional C you defined a functions > parameters like > > int foo() > int a; > float b; > { /* body here */ } I started with c in the 1980s using Mix Power C under Microsoft DOS 3.5. It was a number of years before I finished up with GCC under Linux. Power-C was the only version of c I worked with for several years. The input parameters were always inside the function brackets in that version, so it must have been ansi-c. I hadn't realised it was any different from the K&R specs. Interesting! -- From Barry Drake (The Revd) Health and Healing advisor to the East Midlands Synod of the United Reformed Church. See http://www.urc5.org.uk/index for information about the synod, and http://www.urc5.org.uk/?q=node/703 for the Synod Healing pages. Replies - b.drake at ntlworld.com From alan.gauld at btinternet.com Sun Apr 1 17:57:20 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 01 Apr 2012 16:57:20 +0100 Subject: [Tutor] breeds of Python ..... In-Reply-To: <4F787579.4020200@crosswire.org> References: <4F777931.5010204@crosswire.org> <4F783154.7090003@crosswire.org> <4F787579.4020200@crosswire.org> Message-ID: On 01/04/12 16:34, Barry Drake wrote: > On 01/04/12 15:26, Alan Gauld wrote: >> Actually the standardization of C sparked huge debates in the early >> 90's. There were lots of minor changes and one big style change that >> really polarised opinions. In traditional C you defined a functions >> parameters like >> >> int foo() >> int a; >> float b; >> { /* body here */ } Oops, a slight mistake there it should be: int foo(a,b) int a; float b; { /* body here */ } > I started with c in the 1980s using Mix Power C under Microsoft DOS 3.5. I still have my Mix C compiler and manual (It runs under dosemu in Linux :-), but mine was not "Power C"... and it came in dual CP/M and MS DOS versions (I had a CP/M Computer too at the time). So I'm guessing Power C was their ANSI version. I used it for years because I could carry the whole thing, including IDE, on a single 720K floppy disk - remember them! :-) Very handy for writing a quick ad-hoc tool on a customers site. Exactly the kind of thing I use python for nowadays! > different from the K&R specs. Interesting! Other differences included the introduction of const for constants, the void type, and the // style line comment. A lot of previously undefined behaviors became defined too. And the library was expanded beyond all recognition, bringing in lots of features that had been implementation dependant into the standard. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sun Apr 1 18:07:56 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 01 Apr 2012 17:07:56 +0100 Subject: [Tutor] breeds of Python ..... In-Reply-To: References: <4F777931.5010204@crosswire.org> <4F783154.7090003@crosswire.org> <4F787579.4020200@crosswire.org> Message-ID: On 01/04/12 16:57, Alan Gauld wrote: > On 01/04/12 16:34, Barry Drake wrote: >> different from the K&R specs. Interesting! A quick Google search threw up this useful PDF that does a tour of the "new" features of ANSI C and how best to use them. http://www.sascommunity.org/sugi/SUGI88/Sugi-13-229%20Gass.pdf Also the ANSI C standard was published in 1988 so the arguments must have been mid-80s not early 90's. How time flies... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From bdrake at crosswire.org Sun Apr 1 18:30:38 2012 From: bdrake at crosswire.org (Barry Drake) Date: Sun, 01 Apr 2012 17:30:38 +0100 Subject: [Tutor] breeds of Python ..... In-Reply-To: References: <4F777931.5010204@crosswire.org> <4F783154.7090003@crosswire.org> <4F787579.4020200@crosswire.org> Message-ID: <4F7882AE.6050309@crosswire.org> On 01/04/12 16:57, Alan Gauld wrote: > Oops, a slight mistake there it should be: > int foo(a,b) > int a; > float b; > { /* body here */ } Ah, now that rings bells .... It's all a very long time ago, but I think my Power-C was able to accept either format and not complain. I still have my Power-C carefully preserved on a CD. I'll have to dig it out sometime and try it under DosBox emulator. That seems to run most ancient DOS stuff. I think my version of Power-C came on a 5-1/4" floppy and would run from there. I seem to remember using it before I had a computer with a hard-drive, just two 5-1/4" floppies. Those were the days! Regards, Barry. -- From Barry Drake - a member of the Ubuntu advertising team. From stefan_ml at behnel.de Sun Apr 1 19:16:15 2012 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sun, 01 Apr 2012 19:16:15 +0200 Subject: [Tutor] breeds of Python ..... In-Reply-To: References: <4F777931.5010204@crosswire.org> Message-ID: Brett Ritter, 01.04.2012 07:19: > On Sat, Mar 31, 2012 at 5:37 PM, Barry Drake wrote: >> concentrate on Python3 or stay with Python2 and get into bad habits when it >> comes to change eventually? Apart from the print and input functions, I >> haven't so far got a lot to re-learn. > > My recommendation is to go with Python2 - most major projects haven't > made the switch This statement is a bit misleading because it implies that you actually "have to make the switch" at some point. Many projects are quite happily supporting both at the same time, be it in a single code base (e.g. helped by the "six" module) or by using the 2to3 conversion tool. Also, from what I see and hear, "most major projects" are at least on their way to adapting their code base for Python 3 compatibility, and many, many libraries and other small or large software packages are already available for Python 3. I don't see a major reason for a beginner to not go straight for Python 3, and then learn the necessary Py2 quirks in addition when the need arises. Stefan From bdrake at crosswire.org Sun Apr 1 23:37:06 2012 From: bdrake at crosswire.org (Barry Drake) Date: Sun, 01 Apr 2012 22:37:06 +0100 Subject: [Tutor] breeds of Python ..... In-Reply-To: References: <4F777931.5010204@crosswire.org> Message-ID: <4F78CA82.1020500@crosswire.org> On 01/04/12 18:16, Stefan Behnel wrote: > I don't see a major reason for a beginner to not go straight for > Python 3, and then learn the necessary Py2 quirks in addition when the > need arises. Thanks for that. Really re-assuring. Also, I hadn't looked at 2to3 until you mentioned it - and certainly I hadn't realised that I already have it as part of python3. Most of the simple examples that I would want to use should convert using 2to3 'out of the box'. Thanks. Regards, Barry. -- From Barry Drake - a menber of the Ubuntu advertising team. From steve at pearwood.info Mon Apr 2 03:40:32 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 02 Apr 2012 11:40:32 +1000 Subject: [Tutor] Problem Stripping In-Reply-To: References: Message-ID: <4F790390.3050509@pearwood.info> leam hall wrote: > Python 2.4.3 on Red Hat 5. Trying to use strip to remove characters > but it doesn't seem to work like I thought. > > > res = subprocess.Popen(['uname', '-a'], stdout=subprocess.PIPE) > uname = res.stdout.read().strip() For future reference, you should identify the shortest possible amount of code that demonstrates the problem. See also http://sscce.org/ You are asking a question about string.strip(). Where the string comes from is irrelevant -- there's no need to use an example as complicated as the above, when a simple string constant will do the job perfectly. So the shortest possible amount of code to demonstrate your problem is a single method call: >>> 'spam ham 1:2:3 eggs'.strip(':') 'spam ham 1:2:3 eggs' All the stuff with subprocess.Popen and reading from stout and whatnot doesn't have anything to do with the issue at hand. It cannot shed any light on the problem; at best it must be ignored, at worst it may confuse the issue. As others have already explained, strip() does not remove characters from anywhere in the string, it strips them from the ends only. There is also a lstrip() and rstrip() for times you only want to remove them from the left or right side. -- Steven From steve at pearwood.info Mon Apr 2 13:08:27 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 02 Apr 2012 21:08:27 +1000 Subject: [Tutor] Problem Stripping In-Reply-To: <4F79751A.7050000@gmail.com> References: <4F790390.3050509@pearwood.info> <4F79751A.7050000@gmail.com> Message-ID: <4F7988AB.6010501@pearwood.info> Please keep your reply on the list, unless you have something private to say. That way others can help, or learn from your questions. I've taken the liberty of putting this back into the list. Leam Hall wrote: > On 04/01/2012 09:40 PM, Steven D'Aprano wrote: >> leam hall wrote: >>> Python 2.4.3 on Red Hat 5. Trying to use strip to remove characters >>> but it doesn't seem to work like I thought. >>> >>> >>> res = subprocess.Popen(['uname', '-a'], stdout=subprocess.PIPE) >>> uname = res.stdout.read().strip() >> >> For future reference, you should identify the shortest possible amount >> of code that demonstrates the problem. See also http://sscce.org/ >> >> You are asking a question about string.strip(). Where the string comes >> from is irrelevant -- there's no need to use an example as complicated >> as the above, when a simple string constant will do the job perfectly. >> So the shortest possible amount of code to demonstrate your problem is a >> single method call: >> >> >>> 'spam ham 1:2:3 eggs'.strip(':') >> 'spam ham 1:2:3 eggs' >> >> >> All the stuff with subprocess.Popen and reading from stout and whatnot >> doesn't have anything to do with the issue at hand. It cannot shed any >> light on the problem; at best it must be ignored, at worst it may >> confuse the issue. >> >> As others have already explained, strip() does not remove characters >> from anywhere in the string, it strips them from the ends only. >> >> There is also a lstrip() and rstrip() for times you only want to remove >> them from the left or right side. > > Steve, > > How does one minimize the example code when one doesn't know the > problem? The short example seemed to work, the long one didn't. So the > options seemed to be that the long code changed the expected behavior, > the long code was transcribed incorrectly, or I misunderstood something. > At the point of asking the question I didn't know which of those was the > issue. That's a good question. Being able to diagnose errors or unexpected behaviour is an absolutely critical skill for a programmer. So how could you have diagnosed this (apparent) error? (Apart from reading the Fine Manual, of course.) You started off by reading some data with the subprocess module. So the first thing to do is to replace the calls res = subprocess.Popen(['uname', '-a'], stdout=subprocess.PIPE) uname = res.stdout.read().strip() with a single assignment using the exact same string: uname = 'Linux ando 2.6.18-53.el5 #1 SMP Mon Nov 12 02:22:48 EST 2007 i686 i686 i386 GNU/Linux' (The above should be a single line; my mail client wraps it over two lines.) Does the problem still exist? Yes: >>> uname.strip(':') # I expect the colons to disappear. 'Linux ando 2.6.18-53.el5 #1 SMP Mon Nov 12 02:22:48 EST 2007 i686 i686 i386 GNU/Linux' And lo, the colons don't disappear. The "problem" (as you saw it) continues. Clearly the problem has nothing to do with the *source* of the string. (It would be a bizarre and strange situation if it did!) Step two: Simplify simplify simplify. Why use 85 characters when fewer than a dozen will do? Cut out all the irrelevant bits of the string: >>> uname = '02:22:48' >>> uname.strip(':') '02:22:48' No change in the mysterious behaviour. At this point you have your short, simple example: >>> '02:22:48'.strip(':') # I expect '022248' '02:22:48' and you can ask for help. Or if you are keen to solve this yourself, you could try different strings and see if you can work out what's going on: >>> '0222:48'.strip(':') # maybe it works with only 1 colon? '0222:48' >>> '022248:'.strip(':') # or perhaps if I move the colon somewhere else? '022248' >>> ':02:22:48:'.strip(':') # which colons will be removed? '02:22:48' -- Steven From wluna93 at gmail.com Tue Apr 3 02:03:05 2012 From: wluna93 at gmail.com (Walter Luna) Date: Mon, 2 Apr 2012 17:03:05 -0700 Subject: [Tutor] New to Python programing Message-ID: <483ACC31-A4C3-4E0A-AFBF-440C83AC997A@gmail.com> Hi everybody, my name is Walter I am a new beginner with no programing experience. I am using OSX Lion, and successfully installed Python version 3. I am looking for a programing guide for beginners with no programing experience. Can you please suggest me a good one to use. Thank you. Walter From shane.d.keene at gmail.com Tue Apr 3 02:38:49 2012 From: shane.d.keene at gmail.com (Shane Keene) Date: Mon, 02 Apr 2012 17:38:49 -0700 Subject: [Tutor] New to Python programing In-Reply-To: <483ACC31-A4C3-4E0A-AFBF-440C83AC997A@gmail.com> References: <483ACC31-A4C3-4E0A-AFBF-440C83AC997A@gmail.com> Message-ID: <1333413529.3419.7.camel@siddartha> I don't currently use Python 3 and don't recommend that you use it to learn with, mostly because the bulk of the docs and learning resources are Python 2.x focused and the two are not compatible. That said, here are some resources that you may find useful (particularly if you choose to learn using 2.x): Learn Python the Hard Way: http://learnpythonthehardway.org/ How to Think Like a Computer Scientist: http://openbookproject.net/thinkcs/python/english2e/ and http://python.org/doc has a wealth of info as does http://wiki.python.org/moin/BeginnersGuide/NonProgrammers hope that's helpful. On Mon, 2012-04-02 at 17:03 -0700, Walter Luna wrote: > Hi everybody, my name is Walter I am a new beginner with no programing experience. I am using OSX Lion, and successfully installed Python version 3. I am looking for a programing guide for beginners with no programing experience. Can you please suggest me a good one to use. Thank you. > > Walter > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From questions.anon at gmail.com Tue Apr 3 05:59:36 2012 From: questions.anon at gmail.com (questions anon) Date: Tue, 3 Apr 2012 13:59:36 +1000 Subject: [Tutor] group txt files by month Message-ID: I think what I am trying to do is relatively easy but can't get my head around how to do it. I have a list of txt files that contain daily rainfall for many years. I would like to produce a list that contains the year-month and the max, min and mean of rainfall for each month. My main question at this stage is how to group the files by each month for each year? They are set out like: r20110101.txt r20110102.txt r20110103.txt r20110104.txt r20110105.txt r20110106.txt r20110107.txt r20110108.txt r20110109.txt r20110110.txt r20110111.txt r20110112.txt r20110113.txt r20110114.txt r20110115.txt r20110116.txt r20110117.txt r20110118.txt and so on for each day for many years. so far I am able to open each file and calculate the max, min and mean for each file (see below) but not sure about grouping to monthly for each year. MainFolder=r"E:/Rainfalldata/" outputFolder=r"E:/test/" for (path, dirs, files) in os.walk(MainFolder): path=path+'/' for fname in files: if fname.endswith('.txt'): filename=path+fname f=np.genfromtxt(filename, skip_header=6) print f.max(), f.min(), f.mean() the ideal output would be something like: year-month max min mean 2010-12 100 0 50 2011-01 200 0 100 2011-02 50 0 25 any feedback will be greatly appreciated. -------------- next part -------------- An HTML attachment was scrubbed... URL: From pasokan at talentsprint.com Tue Apr 3 07:14:06 2012 From: pasokan at talentsprint.com (Asokan Pichai) Date: Tue, 3 Apr 2012 10:44:06 +0530 Subject: [Tutor] group txt files by month In-Reply-To: References: Message-ID: On Tue, Apr 3, 2012 at 9:29 AM, questions anon wrote: > I think what I am trying to do is relatively easy but can't get my head > around how to do it. > I have a list of txt files that contain daily rainfall for many years. I > would like to produce a list that contains the year-month and the max, min > and mean of rainfall for each month. > My main question at this stage is how to group the files by each month for > each year? > They are set out like: > r20110101.txt > r20110102.txt > r20110103.txt > r20110104.txt > r20110105.txt > r20110106.txt > r20110107.txt > r20110108.txt > r20110109.txt > r20110110.txt > r20110111.txt > r20110112.txt > r20110113.txt > r20110114.txt > r20110115.txt > r20110116.txt > r20110117.txt > r20110118.txt > > and so on for each day for many years. > > so far I am able to open each file and calculate the max, min and mean for > each file (see below) but not sure about grouping to monthly for each year. # --------------------- Monthwise = {} # ---------------------- > MainFolder=r"E:/Rainfalldata/" > outputFolder=r"E:/test/" > for (path, dirs, files) in os.walk(MainFolder): > ??? path=path+'/' > ??? for fname in files: > ??????? if fname.endswith('.txt'): > ??????????? filename=path+fname > ??????????? f=np.genfromtxt(filename, skip_header=6) > ??????????? print f.max(), f.min(), f.mean() Replace the last two lines with # -------------------------- Monthwise[fname[1:7]] = .np.genfromtxt(filename, skip_header=6) # ------------------------- Now at the end you have a dictionary whose keys are the strings of type '201012' and the values are the f. You can now iterate over the sorted keys of Monthwise and print appropriately [Ideal output etc SNIPPED] HTH Asokan Pichai "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From wescpy at gmail.com Tue Apr 3 07:38:55 2012 From: wescpy at gmail.com (wesley chun) Date: Mon, 2 Apr 2012 22:38:55 -0700 Subject: [Tutor] New to Python programing In-Reply-To: <483ACC31-A4C3-4E0A-AFBF-440C83AC997A@gmail.com> References: <483ACC31-A4C3-4E0A-AFBF-440C83AC997A@gmail.com> Message-ID: greetings walter, and welcome to the Python family! it looks like you've got your machine all set up. hopefully installing Python 3 wasn't too difficult -- users constantly have issues with their own installs clash with the Python that's pre-installed by Apple. as far as learning Python for beginners goes, you have to decide what version to learn -- since you have both Python 2 & 3 on your system, you have a choice. if you have existing code that's written in Python 2.x, you should learn that first. if you have "no baggage," then Python 3.x is the way to go as it is the future. regardless of which you pick, you should realize: 1) once you learn one, you will learn the other as there are only seemingly minor (but backwards-incompatible differences), 2) most books and online materials are still in Python 2 although more and more Python 3 materials are becoming available. as far as books go, the best way to learn Python is by writing games. this is an approach that works both with children as well as adults. there are several excellent books that can help you with this regard: - Hello World! Computer Programming for Kids and Other Beginners by Warren Sande and Carter Sande, Manning, - Invent your Own Computer Games with Python second edition by Al Sweigart - How to Think Like a Computer Scientist by Allen B. Downey, Jeff Elkner and Chris Meyers, Green Tea Press - Python Programming for the Absolute Beginner by Michael Dawson, Course Technology i go into a bit more detail on these as well as the books shane recommends in my "Python Reading List" article (which actually describes 3 separate reading lists): http://www.informit.com/articles/article.aspx?p=1849069 as far as online resources go, try these: - How to Think Like a Computer Scientist (Downey, Elkner, Meyers) http://www.openbookproject.net/thinkcs/ - Learning to Program (Gauld) http://www.alan-g.me.uk/l2p - LiveWires Python http://www.livewires.org.uk/python/home http://pythongames.weebly.com/livewires.html - Snake Wrangling for Kids (Briggs) http://www.briggs.net.nz/snake-wrangling-for-kids.html http://code.google.com/p/swfk/ - Computer Programming is Fun! (Handy) http://www.handysoftware.com/cpif/ - Karel the Robot clone: Guido van Robot http://gvr.sf.net http://en.wikipedia.org/wiki/Guido_van_Robot - Karel the Robot clones: RUR-PLE http://rur-ple.sf.net http://en.wikipedia.org/wiki/RUR-PLE - A Byte of Python (Swaroop) http://www.swaroopch.com/notes/Python - Instant Hacking: Learning to Program with Python (Hetland) http://hetland.org/writing/instant-hacking.html hope this all helps, and again, welcome to Python!! --wesley On Mon, Apr 2, 2012 at 5:03 PM, Walter Luna wrote: > Hi everybody, my name is Walter I am a new beginner with no programing experience. I am using OSX Lion, and successfully installed Python version 3. I am looking for a programing guide for ?beginners with no programing experience. Can you please suggest me a good one to use. Thank you. > > Walter -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "A computer never does what you want... only what you tell it." ? ? wesley chun : wescpy at gmail?: @wescpy/+wescpy ? ? Python training & consulting :?CyberwebConsulting.com ? ? "Core Python" books :?CorePython.com ? ? Python blog: wescpy.blogspot.com From alan.gauld at btinternet.com Tue Apr 3 08:59:56 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 03 Apr 2012 07:59:56 +0100 Subject: [Tutor] group txt files by month In-Reply-To: References: Message-ID: On 03/04/12 04:59, questions anon wrote: > I have a list of txt files that contain daily rainfall for many years. > They are set out like: > r20110101.txt > r20110102.txt > r20110103.txt > and so on for each day for many years. > > MainFolder=r"E:/Rainfalldata/" > outputFolder=r"E:/test/" > for (path, dirs, files) in os.walk(MainFolder): If the files are all in a single folder you might be better using glob.glob() rather than os.walk. You can pass a filename pattern like *.txt to glob(). This might make it easier to group the files by year... 2010*.txt for example. You can do it with walk too its just a bit more effort. But if the files are in multiple folders walk() is probably better. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From wayne at waynewerner.com Tue Apr 3 12:02:13 2012 From: wayne at waynewerner.com (Wayne Werner) Date: Tue, 3 Apr 2012 05:02:13 -0500 (CDT) Subject: [Tutor] New to Python programing In-Reply-To: References: <483ACC31-A4C3-4E0A-AFBF-440C83AC997A@gmail.com> Message-ID: On Mon, 2 Apr 2012, wesley chun wrote: > greetings walter, and welcome to the Python family! > as far as books go, the best way to learn Python is by writing games. > this is an approach that works both with children as well as adults. > there are several excellent books that can help you with this regard: There is another book that I didn't notice mentioned: Game Programming: The L line, the express line to learning. The book is unfortunately named because it makes no mention of Python, but it's quite a good book for learning both programming and Python... and games! Good luck and welcome to Python! -Wayne Werner From wayne at waynewerner.com Tue Apr 3 12:12:38 2012 From: wayne at waynewerner.com (Wayne Werner) Date: Tue, 3 Apr 2012 05:12:38 -0500 (CDT) Subject: [Tutor] breeds of Python ..... In-Reply-To: References: <4F777931.5010204@crosswire.org> Message-ID: On Sat, 31 Mar 2012, Modulok wrote: > If you're just starting out, go with 3.x. If you have a need for some third > party modules that aren't yet available for 3.x, you'll have to stick with 2.x. For a handy list, check out the Python3 Wall of Shame (soon to be superpowers?) http://python3wos.appspot.com/ HTH, Wayne From cranky.frankie at gmail.com Tue Apr 3 15:50:01 2012 From: cranky.frankie at gmail.com (Cranky Frankie) Date: Tue, 3 Apr 2012 09:50:01 -0400 Subject: [Tutor] New to Python programing Message-ID: Another resourse for learning to program is YouTube. They just had a segment on "60 Minutes" about a guy who does all kinds of well regarded free courses on-line, unfortunately I can't remberber the URL. I've viewed several Stanford University programming courses, and there are many Python specific vidoes there as well. Just something else to check out. -- Frank L. "Cranky Frankie" Palmeri Risible Riding Raconteur & Writer ?The problem with quotes on the Internet is that it is often difficult to verify their authenticity.? - Abraham Lincoln From cwitts at compuscan.co.za Tue Apr 3 16:09:21 2012 From: cwitts at compuscan.co.za (Christian Witts) Date: Tue, 03 Apr 2012 16:09:21 +0200 Subject: [Tutor] New to Python programing In-Reply-To: References: Message-ID: <4F7B0491.6040800@compuscan.co.za> On 2012/04/03 03:50 PM, Cranky Frankie wrote: > Another resourse for learning to program is YouTube. They just had a > segment on "60 Minutes" about a guy who does all kinds of well > regarded free courses on-line, unfortunately I can't remberber the > URL. I've viewed several Stanford University programming courses, and > there are many Python specific vidoes there as well. Just something > else to check out. > Are you possibly thinking of the Khan Academy [1] ? [1] http://www.khanacademy.org/ -- Christian Witts Python Developer // -------------- next part -------------- An HTML attachment was scrubbed... URL: From cranky.frankie at gmail.com Tue Apr 3 16:12:36 2012 From: cranky.frankie at gmail.com (Cranky Frankie) Date: Tue, 3 Apr 2012 10:12:36 -0400 Subject: [Tutor] New to Python programing In-Reply-To: <4F7B0491.6040800@compuscan.co.za> References: <4F7B0491.6040800@compuscan.co.za> Message-ID: On Tue, Apr 3, 2012 at 10:09 AM, Christian Witts wrote: > Are you possibly thinking of the Khan Academy [1] ? > > [1] http://www.khanacademy.org/ Yes, that was it, thanks. -- Frank L. "Cranky Frankie" Palmeri Risible Riding Raconteur & Writer ?The problem with quotes on the Internet is that it is often difficult to verify their authenticity.? - Abraham Lincoln From simonyan at fedoraproject.org Tue Apr 3 16:45:48 2012 From: simonyan at fedoraproject.org (Simon Yan) Date: Tue, 3 Apr 2012 22:45:48 +0800 Subject: [Tutor] Open source projects build using Python Message-ID: Dear All, I've been working on Python for a while but haven't got any chance to work on any projects yet. I've spent most of my time reading codes. (I know this is bad when you want to actually learn a programming language) It would be a better idea that I can start to join an open source projects that is built with Python instead of starting up a new project. (I have no good ideas at this moment anyways) I know there are lots of projects which I can work on, but just wanted to hear some recommendations what are the ones good for a long time Python "reader"? -- Regards, YeeYaa (Simon Yan) http://simonyan.fedorapeople.org/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From emailkgnow at gmail.com Tue Apr 3 16:54:12 2012 From: emailkgnow at gmail.com (Khalid Al-Ghamdi) Date: Tue, 3 Apr 2012 17:54:12 +0300 Subject: [Tutor] Question about login=''.join(choice(lc) for j in range(llen)) Message-ID: Hi, The following code tries to generate some dummy data for regex exercises. My question is in reference the line before last: dom="".join(choice(lc) for j in range (dlen)) how does the interpreter know what "j" is supposed to refer to when it was not mentioned prior? from random import randrange, choice from string import ascii_lowercase as lc from sys import maxsize from time import ctime tlds = ('com', 'edu', 'net', 'org', 'gov') for i in range(randrange(5,11)): dtint=randrange(maxsize) #pick a random number to use to generate random date in next line dtstr=ctime(dtint) #date string llen=randrange(4,8) #login is shorter login=''.join(choice(lc) for j in range(llen)) dlen=randrange(llen,13) #domain is longer dom="".join(choice(lc) for j in range (dlen)) print('{}::{}@{}.{}::{}-{}-{}'.format(dtstr,login,dom,choice(tlds),dtint,llen,dlen)) -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Tue Apr 3 17:28:32 2012 From: emile at fenx.com (Emile van Sebille) Date: Tue, 03 Apr 2012 08:28:32 -0700 Subject: [Tutor] Question about login=''.join(choice(lc) for j in range(llen)) In-Reply-To: References: Message-ID: On 4/3/2012 7:54 AM Khalid Al-Ghamdi said... > Hi, > > The following code tries to generate some dummy data for regex > exercises. My question is in reference the line before last: > > dom="".join(choice(lc) for j in range (dlen)) > > how does the interpreter know what "j" is supposed to refer to when it > was not mentioned prior? Prior value or not, j is the loop variable that steps over range(dlen) and refers to the numbers 0 to dlen-1 in turn. Did you mean to ask something about the code below as well? Emile > > > from random import randrange, choice > from string import ascii_lowercase as lc > from sys import maxsize > from time import ctime > > tlds = ('com', 'edu', 'net', 'org', 'gov') > > for i in range(randrange(5,11)): > dtint=randrange(maxsize) #pick a random number to use to > generate random date in next line > dtstr=ctime(dtint) #date string > llen=randrange(4,8) #login is shorter > login=''.join(choice(lc) for j in range(llen)) > dlen=randrange(llen,13) #domain is longer > dom="".join(choice(lc) for j in range (dlen)) > > print('{}::{}@{}.{}::{}-{}-{}'.format(dtstr,login,dom,choice(tlds),dtint,llen,dlen)) > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From bgailer at gmail.com Tue Apr 3 18:59:27 2012 From: bgailer at gmail.com (bob gailer) Date: Tue, 03 Apr 2012 12:59:27 -0400 Subject: [Tutor] Open source projects build using Python In-Reply-To: References: Message-ID: <4F7B2C6F.7040306@gmail.com> On 4/3/2012 10:45 AM, Simon Yan wrote: > Dear All, > > I've been working on Python for a while but haven't got any chance to > work on any projects yet. I've spent most of my time reading codes. (I > know this is bad when you want to actually learn a programming language) > It would be a better idea that I can start to join an open source > projects that is built with Python instead of starting up a new > project. (I have no good ideas at this moment anyways) I know there > are lots of projects which I can work on, but just wanted to hear some > recommendations what are the ones good for a long time Python "reader"? I just sent a reply too a potential user of my fledgling project. Read and see if you are inspired. ---------------------------- reply -------------------------------------------------------------- On 4/2/2012 5:23 PM, Alexander Todorov wrote: > Hello folks, > I'm looking for a stream based/event based parser utilities which I > can use to build my application. > > All I managed to find is related to SAX and XML but I will not be > parsing XML documents. As an example there is a POD parser for Perl > which behaves like a SAX parser: > https://metacpan.org/module/Pod::Parser > > > I'm looking for something similar in Python. > > I will be parsing source code in various programming languages and > need to be able to identify when a class definition starts, when > function definition starts, etc. > > If possible I'd prefer to have a base module which does the hard work > and then small configuration modules for the various languages. > > Can you point me to some relevant modules/docs? Under development right now is an open-source project - Python Pipelines - a utility to do (amongst many other tasks) what you want. With Pipelines you specify the source(s) and destination(s) of data and the various filters and transforms you want done to the data using a fairly straightforward language. In your case (for starters) pipe "functions.txt" would read all the records (linies) in source.py, select just those containing 'def:' and write them to functions.txt. There is much more that can be accomplished. --------------------------------------- end reply --------------------------------------------------- If this sparks your interest I will send you the developer's guide. -- Bob Gailer 919-636-4239 Chapel Hill NC From alan.gauld at btinternet.com Tue Apr 3 19:22:48 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 03 Apr 2012 18:22:48 +0100 Subject: [Tutor] Open source projects build using Python In-Reply-To: References: Message-ID: On 03/04/12 15:45, Simon Yan wrote: > projects which I can work on, but just wanted to hear some > recommendations what are the ones good for a long time Python "reader"? One that interests you. I might think that a system to control the irrigation of my hydroponics garden is fascinating but you might find it boring compared to one that translated Norse runes into English... You will always be more motivated working on something that interests you and for which you have a personal use. (Or alternatively, one for which you get paid large sums of money! :-) Do a search on SourceForge and Google and see what comes up. Look for signs of activity otherwise you might wind up owning the project! Start with documenting, testing or bug fixing. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Apr 3 19:27:17 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 03 Apr 2012 18:27:17 +0100 Subject: [Tutor] Question about login=''.join(choice(lc) for j in range(llen)) In-Reply-To: References: Message-ID: On 03/04/12 15:54, Khalid Al-Ghamdi wrote: > dom="".join(choice(lc) for j in range (dlen)) > > how does the interpreter know what "j" is supposed to refer to when it > was not mentioned prior? In Python variables are defined by using them. In the code below you have i used in a for loop, even though not mentioned before. j is similarly being used in the generator expression for loop: choice(lc) for j in range (dlen) unwraps to: dummy = [] for j in range(dlen): dummy.append(choice(lc)) Which effectively creates a list of dlen choice items. > from random import randrange, choice > from string import ascii_lowercase as lc > from sys import maxsize > from time import ctime > > tlds = ('com', 'edu', 'net', 'org', 'gov') > > for i in range(randrange(5,11)): > dtint=randrange(maxsize) #pick a random number to use to HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From brad.hudson at gmail.com Tue Apr 3 19:32:42 2012 From: brad.hudson at gmail.com (Brad Hudson) Date: Tue, 3 Apr 2012 12:32:42 -0500 Subject: [Tutor] New to Python programing In-Reply-To: References: <4F7B0491.6040800@compuscan.co.za> Message-ID: >> Are you possibly thinking of the Khan Academy [1] ? >> >> [1] http://www.khanacademy.org/ If you're interested in free courses, MIT also has free programming courses (done in Python) via their OpenCourseWare and will be expanding this to MITx in the near future. OpenCourseWare - Intro to Computer Science & Programming (Python based) located here: http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-00sc-introduction-to-computer-science-and-programming-spring-2011/index.htm Brad From breamoreboy at yahoo.co.uk Tue Apr 3 19:41:32 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 03 Apr 2012 18:41:32 +0100 Subject: [Tutor] Open source projects build using Python In-Reply-To: References: Message-ID: On 03/04/2012 18:22, Alan Gauld wrote: > On 03/04/12 15:45, Simon Yan wrote: > > Do a search on SourceForge and Google and see what comes up. > Hopefully codeplex.com amongst others. -- Cheers. Mark Lawrence. From __peter__ at web.de Tue Apr 3 19:50:40 2012 From: __peter__ at web.de (Peter Otten) Date: Tue, 03 Apr 2012 19:50:40 +0200 Subject: [Tutor] Question about login=''.join(choice(lc) for j in range(llen)) References: Message-ID: Alan Gauld wrote: > On 03/04/12 15:54, Khalid Al-Ghamdi wrote: > >> dom="".join(choice(lc) for j in range (dlen)) >> >> how does the interpreter know what "j" is supposed to refer to when it >> was not mentioned prior? > > In Python variables are defined by using them. > > In the code below you have i used in a for loop, even though not > mentioned before. j is similarly being used in the generator expression > for loop: > > choice(lc) for j in range (dlen) > > unwraps to: > > dummy = [] > for j in range(dlen): > dummy.append(choice(lc)) An interesting aspect of these "generator expressions" is that they are "lazy", they deliver only as many items as necessary. >>> numbers = (n for n in range(1000)) >>> next(numbers) 0 >>> next(numbers) 1 >>> any(n>10 for n in numbers) True >>> next(numbers) 12 >>> any(n<10 for n in numbers) False >>> next(numbers) Traceback (most recent call last): File "", line 1, in StopIteration The StopIteration hints that we have consumed all numbers. We were already at 13 when we asked for a number < 10; therefore the complete rest from 13 to 999 was scanned in vain. From mgjack at gmx.com Tue Apr 3 20:38:59 2012 From: mgjack at gmx.com (mike jackson) Date: Tue, 03 Apr 2012 14:38:59 -0400 Subject: [Tutor] generators Message-ID: <20120403183859.261520@gmx.com> I am trying understand python and have done fairly well, So for it has been easy to learn and is concise. ?However I seem to not quite understand the use of a generator over a function(I am familiar with functions [other languages and math]). ?To me (excepting obvious syntax differences) a generator is a function. ?Why should I use a generator instead of a function or vice versa? ?Is perhaps specfic uses it was created to handle? ?A great web page with good examples would be nice. ?Of course if you can sum it up rather easy then by all means go ahead. ? From abhishek.vit at gmail.com Tue Apr 3 20:54:41 2012 From: abhishek.vit at gmail.com (Abhishek Pratap) Date: Tue, 3 Apr 2012 11:54:41 -0700 Subject: [Tutor] generators In-Reply-To: <20120403183859.261520@gmx.com> References: <20120403183859.261520@gmx.com> Message-ID: Hey Mike The following link should help you. http://www.dabeaz.com/generators/ . Cool slide deck with examples from David Beazley's explanation of generators. -A On Tue, Apr 3, 2012 at 11:38 AM, mike jackson wrote: > I am trying understand python and have done fairly well, So for it has been easy to learn and is concise. ?However I seem to not quite understand the use of a generator over a function(I am familiar with functions [other languages and math]). ?To me (excepting obvious syntax differences) a generator is a function. ?Why should I use a generator instead of a function or vice versa? ?Is perhaps specfic uses it was created to handle? ?A great web page with good examples would be nice. ?Of course if you can sum it up rather easy then by all means go ahead. > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From wescpy at gmail.com Tue Apr 3 21:15:06 2012 From: wescpy at gmail.com (wesley chun) Date: Tue, 3 Apr 2012 12:15:06 -0700 Subject: [Tutor] New to Python programing In-Reply-To: References: <4F7B0491.6040800@compuscan.co.za> Message-ID: a couple of other sources of video learning (DISCLAIMER: the 1st is from my employer, and the 2nd is from me -- the intention is to provide alternatives not shameless self-promotion so please don't take it that way!): 1. Google offers an internal Python training class to its employees. it's a 2-day course designed to teach existing programmers how to code in Python, covering syntax, data structures, etc. (it's not deep and thorough like the course i teach publicly but it may be just what you need.) i volunteer to deliver it a couple of times a year. anyway, you can get all the course contents, exercises, and a lively delivery by my colleague Nick Parlante (recorded a few years ago) across 7 videos which span both days here: http://code.google.com/edu/languages/google-python-class 2. a few years ago, i was asked to do a video version of my public course blended with material from the "Core Python Programming" book. the primary target audience includes existing programmers who need to learn Python (2.x & 3.x) quickly and comprehensively via video lectures (as opposed to the "show-me-do" style of onscreen hacking -- which is *also* a viable way of learning but just not for everyone). some people prefer the lecture-style, so if you do, then you may wish to consider it. i made the mistake of not being more public about this early on, hence some of the not-so-great Amazon reviews. :P anyway, if you're interested, you can get a free video clip here: http://www.informit.com/store/product.aspx?isbn=9780137143412. (the editors left some of my bleeping bloopers in the DVD, so it may be entertaining to you at my expense.) another free preview of my teaching style (if you want to learn about Python Generators) can be found at http://cyberwebconsulting.com cheers, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "A computer never does what you want... only what you tell it." ? ? wesley chun : wescpy at gmail?: @wescpy/+wescpy ? ? Python training & consulting :?CyberwebConsulting.com ? ? "Core Python" books :?CorePython.com ? ? Python blog: wescpy.blogspot.com From joel.goldstick at gmail.com Tue Apr 3 21:15:46 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Tue, 3 Apr 2012 15:15:46 -0400 Subject: [Tutor] generators In-Reply-To: <20120403183859.261520@gmx.com> References: <20120403183859.261520@gmx.com> Message-ID: On Tue, Apr 3, 2012 at 2:38 PM, mike jackson wrote: > I am trying understand python and have done fairly well, So for it has been easy to learn and is concise. ?However I seem to not quite understand the use of a generator over a function(I am familiar with functions [other languages and math]). ?To me (excepting obvious syntax differences) a generator is a function. ?Why should I use a generator instead of a function or vice versa? ?Is perhaps specfic uses it was created to handle? ?A great web page with good examples would be nice. ?Of course if you can sum it up rather easy then by all means go ahead. > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor A generator function is a special kind of function that uses the 'yield' statement to return a value. The next time the function is called, it starts up from the place following the yield statement. They are useful in producing the next value in a computed sequence of values without having to compute the whole sequence at one go. Here is a great tutorial about things you can do with generators: http://www.dabeaz.com/generators/ Here is some simple code with results below #! /usr/bin/env python """ generator vs normal function""" """ a 'Normal' function""" def n(r): v = [] for i in range(r): v.append(i*2) return v """ A generator function""" def g(r): for i in range(r): yield i*2 print n(3) for i in g(3): print i generated_list = [i for i in g(3)] print generated_list [0, 2, 4] 0 2 4 [0, 2, 4] -- Joel Goldstick From wescpy at gmail.com Tue Apr 3 22:40:36 2012 From: wescpy at gmail.com (wesley chun) Date: Tue, 3 Apr 2012 13:40:36 -0700 Subject: [Tutor] Question about login=''.join(choice(lc) for j in range(llen)) In-Reply-To: References: Message-ID: On Tue, Apr 3, 2012 at 10:50 AM, Peter Otten <__peter__ at web.de> wrote: > Alan Gauld wrote: >> On 03/04/12 15:54, Khalid Al-Ghamdi wrote: >> >>> ? ? ?dom="".join(choice(lc) for j in range (dlen)) >>> >>> how does the interpreter know what "j" is supposed to refer to when it >>> was not mentioned prior? +1 everyone else's replies so far. i'll add the following: you create variables by assigning things to them. in this example, no prior code used the variable 'x': >>> x = 10 >>> print x 10 similarly, when used in a for-loop, it's like you had an "invisible" assignment at the "top" of the loop. here's an example: >>> for i in range(5): ... print i ... 0 1 2 3 4 >>> print i 4 notice that the 'i' variable is still there even after the loop has ended. it's as if you did the following: >>> i = 0 >>> print i 0 >>> i = 1 : >>> i = 4 >>> print i # 1st time, part of the "loop" 4 >>> print i # 2nd time, "outside" of the loop 4 hope this helps! --wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "A computer never does what you want... only what you tell it." ? ? wesley chun : wescpy at gmail?: @wescpy/+wescpy ? ? Python training & consulting :?CyberwebConsulting.com ? ? "Core Python" books :?CorePython.com ? ? Python blog: wescpy.blogspot.com From wescpy at gmail.com Wed Apr 4 00:10:02 2012 From: wescpy at gmail.com (wesley chun) Date: Tue, 3 Apr 2012 15:10:02 -0700 Subject: [Tutor] generators In-Reply-To: References: <20120403183859.261520@gmx.com> Message-ID: > On Tue, Apr 3, 2012 at 2:38 PM, mike jackson wrote: > I am trying understand python and have done fairly well, So for it has been easy to learn and is concise. ?However I seem to not quite understand the use of a generator over a function(I am familiar with functions [other languages and math]). ?To me (excepting obvious syntax differences) a generator is a function. ?Why should I use a generator instead of a function or vice versa? ?Is perhaps specfic uses it was created to handle? ?A great web page with good examples would be nice. ?Of course if you can sum it up rather easy then by all means go ahead. dave beazley's lectures are *awesome*, and even more so if you can attend them in-person. below are my comments on generators off the top of my head: 1. syntactically, generators are merely functions with one or more "yield" statements/expressions 2. users of generators will see them primarily as "advanced" iterators, because they yield individual values until such an iterator has been exhausted (StopIteration). 3. creators of generators will see them more like functions that you can pause, "return" some intermediate value, then be resumable/resumed later. the C language has the concept of a "static function" where variables can maintain their values across function calls. while being "nice," it's not nearly as powerful as being able to save the values *and* the entire state of execution at the time the function is paused then resume right where it left off later, hence the comparisons with co-routines (which are even more independent threads of execution). 4. "generator expressions" are the lazy evaluation form of list comprehensions, and better for memory because of that. they'll behave just like generators but can be defined easily on a single line, just like normal listcomps. 5. i made a quick 5-minute video introducing Python developers to generators... it's a very ad hoc and informal session during one of my Python courses that a student recorded. if interested in viewing it, you can find it half-way down http://cyberwebconsulting.com hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "A computer never does what you want... only what you tell it." ? ? wesley chun : wescpy at gmail?: @wescpy/+wescpy ? ? Python training & consulting :?http://CyberwebConsulting.com ? ? "Core Python" books :?http://CorePython.com ? ? Python blog: http://wescpy.blogspot.com From simonyan at fedoraproject.org Wed Apr 4 07:40:47 2012 From: simonyan at fedoraproject.org (Simon Yan) Date: Wed, 4 Apr 2012 13:40:47 +0800 Subject: [Tutor] Open source projects build using Python In-Reply-To: References: Message-ID: On Wed, Apr 4, 2012 at 1:41 AM, Mark Lawrence wrote: > On 03/04/2012 18:22, Alan Gauld wrote: > >> On 03/04/12 15:45, Simon Yan wrote: >> >> Do a search on SourceForge and Google and see what comes up. >> >> > Hopefully codeplex.com amongst others. > > Hey Guys, Thank you all for the good suggestions. I'm gonna make some research and look around to find the sweet spot. > -- > Cheers. > > Mark Lawrence. > > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -- Regards, YeeYaa (Simon Yan) http://simonyan.fedorapeople.org/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Wed Apr 4 14:39:21 2012 From: bgailer at gmail.com (bob gailer) Date: Wed, 04 Apr 2012 08:39:21 -0400 Subject: [Tutor] generators In-Reply-To: References: <20120403183859.261520@gmx.com> Message-ID: <4F7C40F9.1010506@gmail.com> To Joel's and Wesley's valuable comments I add: Calling a generator function returns a /generator object/. >>> def x(n): ... for i in range(n): yield i ... >>> y = x(3) >>> print y A generator object can be used instead of some other "iterable" (e.g.) in for statements. >>> for i in y:print i 0 1 2 x in this case is equivalent to xrange() with exactly 1 argument. There is more that can be said regarding x.next(). x.send(), raise StopIteration but I've said enough for now. -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From wluna93 at gmail.com Wed Apr 4 18:35:49 2012 From: wluna93 at gmail.com (Walter Luna) Date: Wed, 4 Apr 2012 09:35:49 -0700 Subject: [Tutor] Tutor Digest, Vol 98, Issue 7 In-Reply-To: References: Message-ID: Dear Python friends: Thank you for the rapid response, I researched the information you sent me and it has a lot of resources that I can use. I will use some of those resources and continue with my learning journey, I am sure that I will have a lot of questions but I feel confident that I have your support. Best regards Walter Luna On Tue, Apr 3, 2012 at 7:54 AM, 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: New to Python programing (Wayne Werner) > 2. Re: breeds of Python ..... (Wayne Werner) > 3. New to Python programing (Cranky Frankie) > 4. Re: New to Python programing (Christian Witts) > 5. Re: New to Python programing (Cranky Frankie) > 6. Open source projects build using Python (Simon Yan) > 7. Question about login=''.join(choice(lc) for j in range(llen)) > (Khalid Al-Ghamdi) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Tue, 3 Apr 2012 05:02:13 -0500 (CDT) > From: Wayne Werner > To: wesley chun > Cc: "tutor at python.org" , Walter Luna > > Subject: Re: [Tutor] New to Python programing > Message-ID: > Content-Type: TEXT/PLAIN; charset=US-ASCII; format=flowed > > On Mon, 2 Apr 2012, wesley chun wrote: > > > greetings walter, and welcome to the Python family! > > > as far as books go, the best way to learn Python is by writing games. > > this is an approach that works both with children as well as adults. > > there are several excellent books that can help you with this regard: > > There is another book that I didn't notice mentioned: Game Programming: > The L line, the express > line to learning. > > The book is unfortunately named because it makes no mention of Python, but > it's > quite a good book for learning both programming and Python... and games! > > Good luck and welcome to Python! > -Wayne Werner > > > ------------------------------ > > Message: 2 > Date: Tue, 3 Apr 2012 05:12:38 -0500 (CDT) > From: Wayne Werner > To: Modulok > Cc: tutor at python.org > Subject: Re: [Tutor] breeds of Python ..... > Message-ID: > Content-Type: TEXT/PLAIN; charset=US-ASCII; format=flowed > > On Sat, 31 Mar 2012, Modulok wrote: > > If you're just starting out, go with 3.x. If you have a need for some > third > > party modules that aren't yet available for 3.x, you'll have to stick > with 2.x. > > For a handy list, check out the Python3 Wall of Shame (soon to be > superpowers?) > http://python3wos.appspot.com/ > > HTH, > Wayne > > > ------------------------------ > > Message: 3 > Date: Tue, 3 Apr 2012 09:50:01 -0400 > From: Cranky Frankie > To: tutor at python.org > Subject: [Tutor] New to Python programing > Message-ID: > > > Content-Type: text/plain; charset=windows-1252 > > Another resourse for learning to program is YouTube. They just had a > segment on "60 Minutes" about a guy who does all kinds of well > regarded free courses on-line, unfortunately I can't remberber the > URL. I've viewed several Stanford University programming courses, and > there are many Python specific vidoes there as well. Just something > else to check out. > > -- > Frank L. "Cranky Frankie" Palmeri > Risible Riding Raconteur & Writer > ?The problem with quotes on the Internet is that > it is often difficult to verify their authenticity.? > - Abraham Lincoln > > > ------------------------------ > > Message: 4 > Date: Tue, 03 Apr 2012 16:09:21 +0200 > From: Christian Witts > To: Cranky Frankie > Cc: tutor at python.org > Subject: Re: [Tutor] New to Python programing > Message-ID: <4F7B0491.6040800 at compuscan.co.za> > Content-Type: text/plain; charset="windows-1252"; Format="flowed" > > On 2012/04/03 03:50 PM, Cranky Frankie wrote: > > Another resourse for learning to program is YouTube. They just had a > > segment on "60 Minutes" about a guy who does all kinds of well > > regarded free courses on-line, unfortunately I can't remberber the > > URL. I've viewed several Stanford University programming courses, and > > there are many Python specific vidoes there as well. Just something > > else to check out. > > > Are you possibly thinking of the Khan Academy [1] ? > > [1] http://www.khanacademy.org/ > -- > > Christian Witts > Python Developer > // > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: < > http://mail.python.org/pipermail/tutor/attachments/20120403/68e50894/attachment-0001.html > > > > ------------------------------ > > Message: 5 > Date: Tue, 3 Apr 2012 10:12:36 -0400 > From: Cranky Frankie > To: tutor at python.org > Subject: Re: [Tutor] New to Python programing > Message-ID: > > > Content-Type: text/plain; charset=windows-1252 > > On Tue, Apr 3, 2012 at 10:09 AM, Christian Witts > wrote: > > > Are you possibly thinking of the Khan Academy [1] ? > > > > [1] http://www.khanacademy.org/ > > Yes, that was it, thanks. > > > -- > Frank L. "Cranky Frankie" Palmeri > Risible Riding Raconteur & Writer > ?The problem with quotes on the Internet is that > it is often difficult to verify their authenticity.? > - Abraham Lincoln > > > ------------------------------ > > Message: 6 > Date: Tue, 3 Apr 2012 22:45:48 +0800 > From: Simon Yan > To: Tutor at python.org > Subject: [Tutor] Open source projects build using Python > Message-ID: > > > Content-Type: text/plain; charset="iso-8859-1" > > Dear All, > > I've been working on Python for a while but haven't got any chance to work > on any projects yet. I've spent most of my time reading codes. (I know this > is bad when you want to actually learn a programming language) > It would be a better idea that I can start to join an open source projects > that is built with Python instead of starting up a new project. (I have no > good ideas at this moment anyways) I know there are lots of projects which > I can work on, but just wanted to hear some recommendations what are the > ones good for a long time Python "reader"? > > -- > Regards, > YeeYaa (Simon Yan) > > http://simonyan.fedorapeople.org/ > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: < > http://mail.python.org/pipermail/tutor/attachments/20120403/884be329/attachment-0001.html > > > > ------------------------------ > > Message: 7 > Date: Tue, 3 Apr 2012 17:54:12 +0300 > From: Khalid Al-Ghamdi > To: tutor at python.org > Subject: [Tutor] Question about login=''.join(choice(lc) for j in > range(llen)) > Message-ID: > > > Content-Type: text/plain; charset="iso-8859-1" > > Hi, > > The following code tries to generate some dummy data for regex exercises. > My question is in reference the line before last: > > dom="".join(choice(lc) for j in range (dlen)) > > how does the interpreter know what "j" is supposed to refer to when it was > not mentioned prior? > > > from random import randrange, choice > from string import ascii_lowercase as lc > from sys import maxsize > from time import ctime > > tlds = ('com', 'edu', 'net', 'org', 'gov') > > for i in range(randrange(5,11)): > dtint=randrange(maxsize) #pick a random number to use to generate > random date in next line > dtstr=ctime(dtint) #date string > llen=randrange(4,8) #login is shorter > login=''.join(choice(lc) for j in range(llen)) > dlen=randrange(llen,13) #domain is longer > dom="".join(choice(lc) for j in range (dlen)) > > > print('{}::{}@{}.{}::{}-{}-{}'.format(dtstr,login,dom,choice(tlds),dtint,llen,dlen)) > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: < > http://mail.python.org/pipermail/tutor/attachments/20120403/d57a8c0b/attachment.html > > > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > End of Tutor Digest, Vol 98, Issue 7 > ************************************ > -- Walter Luna -------------- next part -------------- An HTML attachment was scrubbed... URL: From bnyec at yahoo.com Wed Apr 4 19:25:38 2012 From: bnyec at yahoo.com (b. nyec) Date: Wed, 4 Apr 2012 10:25:38 -0700 (PDT) Subject: [Tutor] cPickle/pickle help Message-ID: <1333560338.81943.YahooMailClassic@web161505.mail.bf1.yahoo.com> Hello, I'm not sure if this is the correct list to post this on, but i was wondering i someone could help me. I'm wondering if there exists a pickler example written in C ? I understand the cPickle module was written in C, but looking at it seems daunting to create sample code from it. I found a post on this list here: http://mail.python.org/pipermail//tutor/2011-September/085414.html that shows an example of pickling data to disk. I'm wondering if that's pickle or cPickle (protocol version?) ?? What i'm trying to do is write a client in C that will send pickled data to a server written in python for unpicking over TCP. I'm still learning this stuff (pickle/serialization) as i go (i have zero knowledge of python), so apologies if i'm not making any sense as i've had trouble finding help on other places when explaining what i'm trying to accomplish. If this is off topic, feel free to e-mail me privately and i could explain in more detail without adding noise to this list. Thanks for any help. From alan.gauld at btinternet.com Wed Apr 4 19:46:40 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 04 Apr 2012 18:46:40 +0100 Subject: [Tutor] Tutor Digest, Vol 98, Issue 7 In-Reply-To: References: Message-ID: On 04/04/12 17:35, Walter Luna wrote: > Dear Python friends: > > Thank you for the rapid response, I researched the information you sent > me and it has a lot of resources that I can use. You are welcome however, when posting to the list in future, please do not reply to a digest message without: - change the subject to something meaningful (see quoted text below) - delete all content not directly relevant to your post. Some people pay by the byte, others are too busy to want to scan through a long post of mails they have already seen searching for new/relevant information. Finally, it is preferred if you post comments *under* the context rather than at the top of the message. This again makes it easier for readers to understand the context. Regards, Alan G. Tutor List moderator > > On Tue, Apr 3, 2012 at 7:54 AM, > wrote: > > Send Tutor mailing list submissions to > tutor at python.org > ... > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Apr 4 19:57:01 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 04 Apr 2012 18:57:01 +0100 Subject: [Tutor] cPickle/pickle help In-Reply-To: <1333560338.81943.YahooMailClassic@web161505.mail.bf1.yahoo.com> References: <1333560338.81943.YahooMailClassic@web161505.mail.bf1.yahoo.com> Message-ID: On 04/04/12 18:25, b. nyec wrote: > I'm not sure if this is the correct list to post this on, No its not, this list is for folks learning Python the language. > but i was wondering i someone could help me. You might get lucky here but are more likely to find responses on the main Python mailing list/newsgroup: comp.lang.python > I'm wondering if there exists a pickler example written in C ? The pickle module is intended to be used in Python rather than from C. The examples are therefore written from a Python users standpoint. However it is possible to embed Python into your C program and there are separate documents to describe how to do that. That might be the easiest way to approach this, but I' ve never tried so don't know. > I understand the cPickle module was written in C, but looking Many Python modules are written in C but they are all intended to be used from within Python. Reading the code could show you how to read/write the various data types, but you would need to replicate the C functions in the module in your code. > I found a post on this list here: http://mail.python.org/pipermail//tutor/2011-September/085414.html > that shows an example of pickling data to disk. It doesn't matter much since the Python code is the same, it just runs faster with cPickle. The only difference is whether you start with import pickle or import cPickle I recommend you try the main list. And the embedding Python option is worth investigating: http://docs.python.org/extending/embedding.html HTH, Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From breamoreboy at yahoo.co.uk Wed Apr 4 20:16:14 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 04 Apr 2012 19:16:14 +0100 Subject: [Tutor] cPickle/pickle help In-Reply-To: <1333560338.81943.YahooMailClassic@web161505.mail.bf1.yahoo.com> References: <1333560338.81943.YahooMailClassic@web161505.mail.bf1.yahoo.com> Message-ID: On 04/04/2012 18:25, b. nyec wrote: > Hello, > > I'm not sure if this is the correct list to post this on, but i was wondering i someone could help me. I'm wondering if there exists a pickler example written in C ? I understand the cPickle module was written in C, but looking at it seems daunting to create sample code from it. I found a post on this list here: http://mail.python.org/pipermail//tutor/2011-September/085414.html that shows an example of pickling data to disk. I'm wondering if that's pickle or cPickle (protocol version?) ?? What i'm trying to do is write a client in C that will send pickled data to a server written in python for unpicking over TCP. I'm still learning this stuff (pickle/serialization) as i go (i have zero knowledge of python), so apologies if i'm not making any sense as i've had trouble finding help on other > places when explaining what i'm trying to accomplish. If this is off topic, feel free to e-mail me privately and i could explain in more detail without adding noise to > this list. > > Thanks for any help. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > You're probably better off asking on comp.lang.python but the advice will almost certainly be don't do it see e.g. http://www.velocityreviews.com/forums/t944852-re-re-advise-of-programming-one-of-my-first-programs.html -- Cheers. Mark Lawrence. From bgailer at gmail.com Wed Apr 4 19:49:33 2012 From: bgailer at gmail.com (bob gailer) Date: Wed, 04 Apr 2012 13:49:33 -0400 Subject: [Tutor] How to reply - best practice. In-Reply-To: References: Message-ID: <4F7C89AD.8070606@gmail.com> On 4/4/2012 12:35 PM, Walter Luna wrote: > Dear Python friends: > > Thank you for the rapid response, I researched the information you > sent me and it has a lot of resources that I can use. I will use some > of those resources and continue with my learning journey, I am sure > that I will have a lot of questions but I feel confident that I have > your support. Glad we could help. To make our lives easier please only include relevant text, and make the subject also relevant. -- Bob Gailer 919-636-4239 Chapel Hill NC From bnyec at yahoo.com Wed Apr 4 20:24:46 2012 From: bnyec at yahoo.com (b. nyec) Date: Wed, 4 Apr 2012 11:24:46 -0700 (PDT) Subject: [Tutor] cPickle/pickle help In-Reply-To: Message-ID: <1333563886.39282.YahooMailClassic@web161505.mail.bf1.yahoo.com> --- On Wed, 4/4/12, Mark Lawrence wrote: > From: Mark Lawrence > Subject: Re: [Tutor] cPickle/pickle help > To: tutor at python.org > Date: Wednesday, April 4, 2012, 1:16 PM > On 04/04/2012 18:25, b. nyec wrote: > > Hello, > > > > I'm not sure if this is the correct list to post this > on, but i was wondering i someone could help me. I'm > wondering if there exists a pickler example written in C ? I > understand the cPickle module was written in C, but looking > at it seems daunting to create sample code from it. I found > a post on this list here: http://mail.python.org/pipermail//tutor/2011-September/085414.html > that shows an example of pickling data to disk. I'm > wondering if that's pickle or cPickle (protocol version?) ?? > What i'm trying to do is write a client in C that will send > pickled data to a server written in python for unpicking > over TCP. I'm still learning this stuff > (pickle/serialization) as i go (i have zero knowledge of > python), so apologies if i'm not making any sense as i've > had trouble finding help on other > >???places when explaining what i'm trying > to accomplish. If this is off topic, feel free to e-mail me > privately and i could explain in more detail without adding > noise to > >???this list. > > > > Thanks for any help. > > > > _______________________________________________ > > Tutor maillist? -? Tutor at python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > > > You're probably better off asking on comp.lang.python but > the advice > will almost certainly be don't do it see e.g. > http://www.velocityreviews.com/forums/t944852-re-re-advise-of-programming-one-of-my-first-programs.html > > -- > Cheers. > > Mark Lawrence. > > _______________________________________________ > Tutor maillist? -? Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Yep I'm fully aware of the ol "Validate user input" security 101 with pickle. :) Looking around the last few days for help, is point more and more to a project i didn;t quite intend on taking up. Oh well. Thanks. From questions.anon at gmail.com Thu Apr 5 03:11:57 2012 From: questions.anon at gmail.com (questions anon) Date: Thu, 5 Apr 2012 11:11:57 +1000 Subject: [Tutor] group txt files by month In-Reply-To: References: Message-ID: thanks for responding. Glob and os.walk will work but I would need to type up a separate command for each month of each year and that doesn't seem very efficient. Is there a way to make it go through and group txt files with similar filenames e.g something like: if fname.endswith('.txt')and fname[0:7]==fname[0:7] e.g. r20110101.txt and r20110102.txt should go together but r20110601 should not. thanks On Tue, Apr 3, 2012 at 4:59 PM, Alan Gauld wrote: > On 03/04/12 04:59, questions anon wrote: > > I have a list of txt files that contain daily rainfall for many years. >> They are set out like: >> r20110101.txt >> r20110102.txt >> r20110103.txt >> and so on for each day for many years. >> >> MainFolder=r"E:/Rainfalldata/" >> outputFolder=r"E:/test/" >> for (path, dirs, files) in os.walk(MainFolder): >> > > If the files are all in a single folder you might be better using > glob.glob() rather than os.walk. You can pass a filename pattern > like *.txt to glob(). This might make it easier to group the > files by year... 2010*.txt for example. > > You can do it with walk too its just a bit more effort. But if the files > are in multiple folders walk() is probably better. > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From tim at akwebsoft.com Thu Apr 5 03:27:45 2012 From: tim at akwebsoft.com (Tim Johnson) Date: Wed, 4 Apr 2012 17:27:45 -0800 Subject: [Tutor] __class__.__name__ for literal integer causes SyntaxError Message-ID: <20120405012745.GC351@mail.akwebsoft.com> See the following console session: >>> 4.6.__class__.__name__ 'float' >>> 6.__class__.__name__ File "", line 1 6.__class__.__name__ ^ SyntaxError: invalid syntax >>> x = 6 >>> x.__class__.__name__ 'int' >>> "me".__class__.__name__ 'str' I note that the reference to '__class__.__name__' for string and float literals is executed, but that there is a SyntaxError for that same reference of a 'int' literal. I'd welcome comments, explanations or URLs to discussions. thanks -- Tim tim at tee jay forty nine dot com or akwebsoft dot com http://www.akwebsoft.com From emile at fenx.com Thu Apr 5 04:27:54 2012 From: emile at fenx.com (Emile van Sebille) Date: Wed, 04 Apr 2012 19:27:54 -0700 Subject: [Tutor] __class__.__name__ for literal integer causes SyntaxError In-Reply-To: <20120405012745.GC351@mail.akwebsoft.com> References: <20120405012745.GC351@mail.akwebsoft.com> Message-ID: On 4/4/2012 6:27 PM Tim Johnson said... > See the following console session: >>>> 4.6.__class__.__name__ The first decimal is considered to be part of the float literal here... > 'float' >>>> 6.__class__.__name__ ... _and_ here... > File "", line 1 > 6.__class__.__name__ > ^ > SyntaxError: invalid syntax ... which explains the error -- the float value is improper. >>>> x = 6 >>>> x.__class__.__name__ > 'int' >>>> "me".__class__.__name__ > 'str' > I note that the reference to '__class__.__name__' for string and > float literals is executed, but that there is a SyntaxError for that > same reference of a 'int' literal. > > I'd welcome comments, explanations or URLs to discussions. > thanks Try >>> (6).__class__.__name__ 'int' >>> HTH, Emile From questions.anon at gmail.com Thu Apr 5 05:37:16 2012 From: questions.anon at gmail.com (questions anon) Date: Thu, 5 Apr 2012 13:37:16 +1000 Subject: [Tutor] group txt files by month In-Reply-To: References: Message-ID: I have been able to write up what I want to do (using glob) but I am not sure how to loop it or simplify it to make the script more efficient. I am currently: -grouping the same months in a year using glob -opening the files in a group and combining the data using a list -finding max, min etc for the list and printing it I need to do this for many years and therefore many months so really need a way to make this more efficient. Any feedback will be greatly appreciated MainFolder=r"E:/rainfall-2011/" OutputFolder=r"E:/test_out/" r201101=glob.glob(MainFolder+"r201101??.txt") r201102=glob.glob(MainFolder+"r201102??.txt") r201103=glob.glob(MainFolder+"r201103??.txt") rain201101=[] rain201102=[] rain201103=[] monthlyrainfall=[] for ifile in r201101: f=np.genfromtxt(ifile, skip_header=6) rain201101.append(f) for ifile in r201102: f=np.genfromtxt(ifile, skip_header=6) rain201102.append(f) for ifile in r201103: f=np.genfromtxt(ifile, skip_header=6) rain201103.append(f) print "jan", np.max(rain201101), np.min(rain201101), np.mean(rain201101), np.median(rain201101), np.std(rain201101) print "feb", np.max(rain201102), np.min(rain201102), np.mean(rain201102), np.median(rain201102), np.std(rain201102) print "mar", np.max(rain201103), np.min(rain201103), np.mean(rain201103), np.median(rain201103), np.std(rain201103) On Thu, Apr 5, 2012 at 11:11 AM, questions anon wrote: > thanks for responding. > Glob and os.walk will work but I would need to type up a separate command > for each month of each year and that doesn't seem very efficient. Is there > a way to make it go through and group txt files with similar filenames > e.g something like: > if fname.endswith('.txt')and fname[0:7]==fname[0:7] > e.g. r20110101.txt and r20110102.txt should go together but r20110601 > should not. > thanks > > > On Tue, Apr 3, 2012 at 4:59 PM, Alan Gauld wrote: > >> On 03/04/12 04:59, questions anon wrote: >> >> I have a list of txt files that contain daily rainfall for many years. >>> They are set out like: >>> r20110101.txt >>> r20110102.txt >>> r20110103.txt >>> and so on for each day for many years. >>> >>> MainFolder=r"E:/Rainfalldata/" >>> outputFolder=r"E:/test/" >>> for (path, dirs, files) in os.walk(MainFolder): >>> >> >> If the files are all in a single folder you might be better using >> glob.glob() rather than os.walk. You can pass a filename pattern >> like *.txt to glob(). This might make it easier to group the >> files by year... 2010*.txt for example. >> >> You can do it with walk too its just a bit more effort. But if the files >> are in multiple folders walk() is probably better. >> >> -- >> Alan G >> Author of the Learn to Program web site >> http://www.alan-g.me.uk/ >> >> ______________________________**_________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/**mailman/listinfo/tutor >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From mjolewis at gmail.com Thu Apr 5 06:59:50 2012 From: mjolewis at gmail.com (Michael Lewis) Date: Wed, 4 Apr 2012 21:59:50 -0700 Subject: [Tutor] Running scripts at login Message-ID: Hi everyone, I am researching how to automatically run some of my scripts after I log into my Windows machine. I don't want to have to manually run the script or setup a windows task. I'd like to have a piece of code that I can insert into my script that will allow it to run after I login. I found the piece by Alan G.; however, it deals with linux and I can't seem to find a good source for Windows machine: http://mail.python.org/pipermail/tutor/2010-July/077319.html Thanks for the help. -- Michael J. Lewis -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Thu Apr 5 08:57:27 2012 From: __peter__ at web.de (Peter Otten) Date: Thu, 05 Apr 2012 08:57:27 +0200 Subject: [Tutor] group txt files by month References: Message-ID: questions anon wrote: > I have been able to write up what I want to do (using glob) but I am not > sure how to loop it or simplify it to make the script more efficient. > I am currently: > -grouping the same months in a year using glob > -opening the files in a group and combining the data using a list > -finding max, min etc for the list and printing it > > I need to do this for many years and therefore many months so really need > a way to make this more efficient. > Any feedback will be greatly appreciated > > MainFolder=r"E:/rainfall-2011/" > OutputFolder=r"E:/test_out/" > r201101=glob.glob(MainFolder+"r201101??.txt") > r201102=glob.glob(MainFolder+"r201102??.txt") > r201103=glob.glob(MainFolder+"r201103??.txt") > > rain201101=[] > rain201102=[] > rain201103=[] > monthlyrainfall=[] > > for ifile in r201101: > f=np.genfromtxt(ifile, skip_header=6) > rain201101.append(f) > > for ifile in r201102: > f=np.genfromtxt(ifile, skip_header=6) > rain201102.append(f) > > for ifile in r201103: > f=np.genfromtxt(ifile, skip_header=6) > rain201103.append(f) > > print "jan", np.max(rain201101), np.min(rain201101), np.mean(rain201101), > np.median(rain201101), np.std(rain201101) > print "feb", np.max(rain201102), np.min(rain201102), np.mean(rain201102), > np.median(rain201102), np.std(rain201102) > print "mar", np.max(rain201103), np.min(rain201103), np.mean(rain201103), > np.median(rain201103), np.std(rain201103) Strip the code down to one month > r201103=glob.glob(MainFolder+"r201103??.txt") > rain201101=[] > for ifile in r201101: > f=np.genfromtxt(ifile, skip_header=6) > rain201101.append(f) then turn it into a function, roughly GLOBTEMPLATE = "e:/rainfall-{year}/r{year}{month:02}??.txt" def accumulate_month(year, month): files = glob.glob(GLOBTEMPLATE.format(year=year, month=month)) # read files, caculate and write stats and finally put it into a loop: from datetime import date, timedelta stop_month = date(2012, 4, 1) month = datetime(2011, 1, 1) while month < stop_month: accumulate_month(month.year, month.month) month += timedelta(days=32) month = month.replace(day=1) From alan.gauld at btinternet.com Thu Apr 5 10:02:20 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 05 Apr 2012 09:02:20 +0100 Subject: [Tutor] Running scripts at login In-Reply-To: References: Message-ID: On 05/04/12 05:59, Michael Lewis wrote: > Hi everyone, > > I am researching how to automatically run some of my scripts after I log > into my Windows machine. I don't want to have to manually run the script > or setup a windows task. The same way you run any Windows program on startup: Add the script to your startup programme group. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From d at davea.name Thu Apr 5 11:47:16 2012 From: d at davea.name (Dave Angel) Date: Thu, 05 Apr 2012 05:47:16 -0400 Subject: [Tutor] __class__.__name__ for literal integer causes SyntaxError In-Reply-To: References: <20120405012745.GC351@mail.akwebsoft.com> Message-ID: <4F7D6A24.1060103@davea.name> On 04/04/2012 10:27 PM, Emile van Sebille wrote: > On 4/4/2012 6:27 PM Tim Johnson said... >> See the following console session: >>>>> 4.6.__class__.__name__ > > The first decimal is considered to be part of the float literal here... > > >> 'float' >>>>> 6.__class__.__name__ > > ... _and_ here... > >> File "", line 1 >> 6.__class__.__name__ >> ^ >> SyntaxError: invalid syntax > > ... which explains the error -- the float value is improper. > >>>>> x = 6 >>>>> x.__class__.__name__ >> 'int' >>>>> "me".__class__.__name__ >> 'str' >> I note that the reference to '__class__.__name__' for string and >> float literals is executed, but that there is a SyntaxError for that >> same reference of a 'int' literal. >> >> I'd welcome comments, explanations or URLs to discussions. >> thanks > > Try > > >>> (6).__class__.__name__ > 'int' > >>> > > HTH, > > Emile Emile gave you the explanation. But another way to convince the parser to treat the decimal point differently is to leave a space(s) between the number and the separator. >>> 6.__class__.__name__ File "", line 1 6.__class__.__name__ ^ SyntaxError: invalid syntax >>> 6 .__class__.__name__ 'int' >>> -- DaveA From glchristian at comcast.net Fri Apr 6 02:39:39 2012 From: glchristian at comcast.net (Greg Christian) Date: Thu, 5 Apr 2012 18:39:39 -0600 Subject: [Tutor] How is the return statement working in this function? Message-ID: <9D09485777D44A5B95E6E8F729BC7E18@GREGPC> I am just wondering if anyone can explain how the return statement in this function is working (the code is from activestate.com)? Where does x come from ? it is not initialized anywhere else and then just appears in the return statement. Any help would be appreciated. def primes(n): """Prime number generator up to n - (generates a list)""" ## {{{ http://code.activestate.com/recipes/366178/ (r5) if n == 2: return [2] elif n < 2: return [] s = range(3, n + 1, 2) mroot = n ** 0.5 half = (n + 1)/2 - 1 i = 0 m = 3 while m <= mroot: if s[i]: j = (m * m - 3)/2 s[j] = 0 while j < half: s[j] = 0 j += m i = i + 1 m = 2 * i + 3 return [2]+[x for x in s if x] -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Fri Apr 6 03:01:55 2012 From: d at davea.name (Dave Angel) Date: Thu, 05 Apr 2012 21:01:55 -0400 Subject: [Tutor] How is the return statement working in this function? In-Reply-To: <9D09485777D44A5B95E6E8F729BC7E18@GREGPC> References: <9D09485777D44A5B95E6E8F729BC7E18@GREGPC> Message-ID: <4F7E4083.6030905@davea.name> On 04/05/2012 08:39 PM, Greg Christian wrote: > I am just wondering if anyone can explain how the return statement in this function is working (the code is from activestate.com)? Where does x come from ? it is not initialized anywhere else and then just appears in the return statement. Any help would be appreciated. > > > def primes(n): > """Prime number generator up to n - (generates a list)""" > ## {{{ http://code.activestate.com/recipes/366178/ (r5) > if n == 2: return [2] > elif n < 2: return [] > s = range(3, n + 1, 2) > mroot = n ** 0.5 > half = (n + 1)/2 - 1 > i = 0 > m = 3 > while m <= mroot: > if s[i]: > j = (m * m - 3)/2 > s[j] = 0 > while j < half: > s[j] = 0 > j += m > i = i + 1 > m = 2 * i + 3 > return [2]+[x for x in s if x] > The expression [x for x in s if x] is called a list comprehension, and it defines x as it needs it. The results of that expression is a list, which is concatenated to the end of the list [2], and the combined list is returned. For example, try the one-liner: print [i for i in xrange(5)] -- DaveA From steve at pearwood.info Fri Apr 6 03:07:49 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 06 Apr 2012 11:07:49 +1000 Subject: [Tutor] How is the return statement working in this function? In-Reply-To: <9D09485777D44A5B95E6E8F729BC7E18@GREGPC> References: <9D09485777D44A5B95E6E8F729BC7E18@GREGPC> Message-ID: <4F7E41E5.3070504@pearwood.info> Greg Christian wrote: > I am just wondering if anyone can explain how the return statement in this > function is working (the code is from activestate.com)? Where does x come > from ? it is not initialized anywhere else and then just appears in the > return statement. Any help would be appreciated. > return [2]+[x for x in s if x] It's called a list comprehension, and is like a one-liner specialist for loop. [x for x in s if x] builds a list using x as the loop variable. So the above line can be considered as the equivalent of this: result = [] for x in s: if x: result.append(x) return [2] + result -- Steven From brian.van.den.broek at gmail.com Fri Apr 6 03:29:30 2012 From: brian.van.den.broek at gmail.com (Brian van den Broek) Date: Fri, 6 Apr 2012 03:29:30 +0200 Subject: [Tutor] How is the return statement working in this function? In-Reply-To: <9D09485777D44A5B95E6E8F729BC7E18@GREGPC> References: <9D09485777D44A5B95E6E8F729BC7E18@GREGPC> Message-ID: On 6 Apr 2012 02:43, "Greg Christian" wrote: > > I am just wondering if anyone can explain how the return statement in this function is working (the code is from activestate.com)? Where does x come from ? it is not initialized anywhere else and then just appears in the return statement. Any help would be appreciated. > > > def primes(n): > """Prime number generator up to n - (generates a list)""" > ## {{{ http://code.activestate.com/recipes/366178/ (r5) > if n == 2: return [2] > elif n < 2: return [] > s = range(3, n + 1, 2) > return [2]+[x for x in s if x] Hi Greg, That it appears is a return isn't relevant. The bit '[x for x in s if x]' is a list comprehension. They build lists in an economical way. This one is equivalent to: result = [] for x in s: if x: result.append(x) Informally, you can think of the 'for x' as working kind of like "for every student" when a teacher reminds him or herself to praise students by repeating softly "for every student in my class praise that student". HTH, Brian vdB -------------- next part -------------- An HTML attachment was scrubbed... URL: From mjolewis at gmail.com Fri Apr 6 04:07:46 2012 From: mjolewis at gmail.com (Michael Lewis) Date: Thu, 5 Apr 2012 19:07:46 -0700 Subject: [Tutor] Running scripts at login Message-ID: > > > On 05/04/12 05:59, Michael Lewis wrote: > > Hi everyone, > > > > I am researching how to automatically run some of my scripts after I log > > into my Windows machine. I don't want to have to manually run the script > > or setup a windows task. > > The same way you run any Windows program on startup: > Add the script to your startup programme group. > What if I want to send the executable to someone and have their machine run the script at startup? Assume I don't have access to their machine to add the script to the startup program group. How can I make that happen? -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Fri Apr 6 04:18:45 2012 From: d at davea.name (Dave Angel) Date: Thu, 05 Apr 2012 22:18:45 -0400 Subject: [Tutor] Running scripts at login In-Reply-To: References: Message-ID: <4F7E5285.5030104@davea.name> On 04/05/2012 10:07 PM, Michael Lewis wrote: >> >> On 05/04/12 05:59, Michael Lewis wrote: >>> Hi everyone, >>> >>> I am researching how to automatically run some of my scripts after I log >>> into my Windows machine. I don't want to have to manually run the script >>> or setup a windows task. >> The same way you run any Windows program on startup: >> Add the script to your startup programme group. >> > What if I want to send the executable to someone and have their machine run > the script at startup? Assume I don't have access to their machine to add > the script to the startup program group. How can I make that happen? > Big difference between your original question "... my Windows machine..." and your present query "... access to their machine..." This forum doesn't support system crackers. -- DaveA From steve at pearwood.info Fri Apr 6 04:28:52 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 06 Apr 2012 12:28:52 +1000 Subject: [Tutor] Running scripts at login In-Reply-To: References: Message-ID: <4F7E54E4.4080005@pearwood.info> Michael Lewis wrote: >> >> On 05/04/12 05:59, Michael Lewis wrote: >>> Hi everyone, >>> >>> I am researching how to automatically run some of my scripts after I log >>> into my Windows machine. I don't want to have to manually run the script >>> or setup a windows task. >> The same way you run any Windows program on startup: >> Add the script to your startup programme group. >> > > What if I want to send the executable to someone and have their machine run > the script at startup? Assume I don't have access to their machine to add > the script to the startup program group. How can I make that happen? You tell them to add the script to their startup program group. If they don't know how, you give them instructions, or ask them for access so you can do it for them, or write an installer that will do it and tell them to run the installer. The installer could be as simple as a DOS batch file. This has nothing to do with Python. -- Steven From emailkgnow at gmail.com Fri Apr 6 05:27:27 2012 From: emailkgnow at gmail.com (Khalid Al-Ghamdi) Date: Fri, 6 Apr 2012 06:27:27 +0300 Subject: [Tutor] regex question Message-ID: hi all, I'm trying to extract the domain in the following string. Why doesn't my pattern (patt) work: >>> redata 'Tue Jan 14 00:43:21 2020::eaximi at gstwyysnbd.gov::1578951801-6-10 Sat Jul 31 15:17:39 1993::rzppg at wgxvhx.com::744121059-5-6 Mon Sep 21 20:22:37 1987::ttwqrf at rpybrct.edu::559243357-6-7 Fri Aug 2 07:15:23 1991::tjyp at mgfyitsks.net::681106523-4-9 Mon Mar 18 19:59:47 2024::dgzxmb at fhyykji.org::1710781187-6-7 ' >>> patt=r'\w+\.\w{3}(?<=@)' >>> re.findall(patt,redata) [] This pattern works but the first should, too. shouldn't it? >>> patt=r'\w+\.\w{3}' -------------- next part -------------- An HTML attachment was scrubbed... URL: From mjolewis at gmail.com Fri Apr 6 07:58:26 2012 From: mjolewis at gmail.com (Michael Lewis) Date: Thu, 5 Apr 2012 22:58:26 -0700 Subject: [Tutor] Running scripts at login In-Reply-To: <4F7E5285.5030104@davea.name> References: <4F7E5285.5030104@davea.name> Message-ID: > > > >>> Hi everyone, > >>> > >>> I am researching how to automatically run some of my scripts after I > log > >>> into my Windows machine. I don't want to have to manually run the > script > >>> or setup a windows task. > >> The same way you run any Windows program on startup: > >> Add the script to your startup programme group. > >> > > What if I want to send the executable to someone and have their machine > run > > the script at startup? Assume I don't have access to their machine to add > > the script to the startup program group. How can I make that happen? > > > > Big difference between your original question "... my Windows > machine..." and your present query "... access to their machine..." > > This forum doesn't support system crackers. > Oh, definitely not my intention - I can see how it came across that way though. For full disclosure, I wrote a script to check for new / move all my girlfriends pictures to dropbox. Nothing malicious intended. My apologies. > > -- > > DaveA > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From emailkgnow at gmail.com Fri Apr 6 08:10:40 2012 From: emailkgnow at gmail.com (Khalid Al-Ghamdi) Date: Fri, 6 Apr 2012 09:10:40 +0300 Subject: [Tutor] Is socket.socket() a func or a class Message-ID: hi all, I'm reading this book that says when creating a socket you have to use the socket.socket() *function *as in : ss=socket.socket() but whey i check they type it says it's a class which makes sense cause you're creating a socket object. >>> type(ss) so, which is it? or do authors loosely use these terms interchangeably in this context? -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Fri Apr 6 08:57:24 2012 From: __peter__ at web.de (Peter Otten) Date: Fri, 06 Apr 2012 08:57:24 +0200 Subject: [Tutor] regex question References: Message-ID: Khalid Al-Ghamdi wrote: > I'm trying to extract the domain in the following string. Why doesn't my > pattern (patt) work: > >>>> redata > 'Tue Jan 14 00:43:21 2020::eaximi at gstwyysnbd.gov::1578951801-6-10 Sat Jul > 31 15:17:39 1993::rzppg at wgxvhx.com::744121059-5-6 Mon Sep 21 20:22:37 > 1987::ttwqrf at rpybrct.edu::559243357-6-7 Fri Aug 2 07:15:23 > 1991::tjyp at mgfyitsks.net::681106523-4-9 Mon Mar 18 19:59:47 > 2024::dgzxmb at fhyykji.org::1710781187-6-7 ' >>>> patt=r'\w+\.\w{3}(?<=@)' >>>> re.findall(patt,redata) > [] > > This pattern works but the first should, too. shouldn't it? No. I think you want r'(?<=@)\w+\.\w{3}'. How do you handle a domain like web.de, by the way? From alan.gauld at btinternet.com Fri Apr 6 09:33:36 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 06 Apr 2012 08:33:36 +0100 Subject: [Tutor] Running scripts at login In-Reply-To: References: Message-ID: On 06/04/12 03:07, Michael Lewis wrote: > What if I want to send the executable to someone and have their machine > run the script at startup? Assume I don't have access to their machine > to add the script to the startup program group. How can I make that happen? When you say executable in reference to a Python script you need to be careful about what you mean. Because Python is an interpreted language the executable can be either the python interpreter (python.exe) or the script that the interpreter is executing (myscript.py). If your friend already has Python installed on their computer (and many nowadays do) then you just need to send the python script and ask them to save it into their startup group (or more likely create a link to it in their startup group) If they are non computer literate you could write an installer or batch file that copied the file to the relevant place. If your friend does not have Python installed you can either: 1) send them the Python installer and your script 2) get them to download and install python before running your script. 3) use a program like py2exe to bundle your script and the interpreter into a single self executing file HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri Apr 6 09:41:04 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 06 Apr 2012 08:41:04 +0100 Subject: [Tutor] Is socket.socket() a func or a class In-Reply-To: References: Message-ID: On 06/04/12 07:10, Khalid Al-Ghamdi wrote: > I'm reading this book that says when creating a socket you have to use > the socket.socket() _function _as in : ... > >>> type(ss) > > > so, which is it? or do authors loosely use these terms interchangeably > in this context? It just looks like sloppy terminology to me. >>> import socket as s >>> s.socket >>> s.gethostbyname -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From kliateni at gmail.com Fri Apr 6 10:47:56 2012 From: kliateni at gmail.com (Karim) Date: Fri, 06 Apr 2012 10:47:56 +0200 Subject: [Tutor] How to have the name of a function inside the code of this function? Message-ID: <4F7EADBC.1000006@gmail.com> Hello all, I have : def foo(): print( getattr(foo, 'func_name')) Where I get the name of the function but I add to give the name of this function. Indeed it is not very helpful... I checked the globals() but how I can do to get globals()['toto'].func_name. This is not more helpful ;o) If you have any idea to get the caller name inside the caller. Cheers Karim From steve at pearwood.info Fri Apr 6 12:06:50 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 06 Apr 2012 20:06:50 +1000 Subject: [Tutor] How to have the name of a function inside the code of this function? In-Reply-To: <4F7EADBC.1000006@gmail.com> References: <4F7EADBC.1000006@gmail.com> Message-ID: <4F7EC03A.40804@pearwood.info> Karim wrote: > > Hello all, > > > I have : > > def foo(): > print( getattr(foo, 'func_name')) Why not this? def foo(): print 'foo' You already know the name of the function. There is no portable way of retrieving the name of the current function from within that function. -- Steven From steve at pearwood.info Fri Apr 6 13:14:25 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 06 Apr 2012 21:14:25 +1000 Subject: [Tutor] Is socket.socket() a func or a class In-Reply-To: References: Message-ID: <4F7ED011.5090209@pearwood.info> Khalid Al-Ghamdi wrote: > hi all, > > I'm reading this book that says when creating a socket you have to use the > socket.socket() *function *as in : > > ss=socket.socket() > > but whey i check they type it says it's a class which makes sense cause > you're creating a socket object. > >>>> type(ss) > > > so, which is it? or do authors loosely use these terms interchangeably in > this context? Yes. Sometimes people call things a function when technically they mean a "callable". A callable is anything that can be called like a function: functions, classes, types, methods, etc. -- Steven From modulok at gmail.com Fri Apr 6 14:22:19 2012 From: modulok at gmail.com (Modulok) Date: Fri, 6 Apr 2012 06:22:19 -0600 Subject: [Tutor] How to have the name of a function inside the code of this function? In-Reply-To: <4F7EADBC.1000006@gmail.com> References: <4F7EADBC.1000006@gmail.com> Message-ID: On 4/6/12, Karim wrote: > > Hello all, > > > I have : > > def foo(): > print( getattr(foo, 'func_name')) > > Where I get the name of the function but I add to give the name of this > function. Indeed it is not very helpful... > I checked the globals() but how I can do to get > globals()['toto'].func_name. This is not more helpful ;o) > > If you have any idea to get the caller name inside the caller. > The following works, but only on implementations which provide stack frame support. As the docs kindly point out: "...this isn't guaranteed to exist in all implementations of Python." Example code: import inspect def foo(): '''Print my own name.''' frame_info = inspect.getframeinfo(inspect.currentframe()) print(frame_info.function) foo() That said, there's probably a better way to solve whatever bigger problem you're trying solve. -Modulok- From emailkgnow at gmail.com Fri Apr 6 15:44:10 2012 From: emailkgnow at gmail.com (Khalid Al-Ghamdi) Date: Fri, 6 Apr 2012 16:44:10 +0300 Subject: [Tutor] a problem with a server and client Message-ID: hi, i'm trying to implement a server that adds a time stamp to incoming text form a client. the server's code is (but doesn't seem to have the problem as demoed by the error below: from socket import * from time import ctime HOST = '' PORT = 21567 BUFSIZ = 1024 ADDR =(HOST, PORT) tcpSerSock = socket(AF_INET, SOCK_STREAM) tcpSerSock.bind(ADDR) tcpSerSock.listen(5) while True: print('waiting for connection ...') tcpCliSock, addr =tcpSerSock.accept() print('...connected from: ', addr) while True: data = tcpCliSock.recv(BUFSIZ) if not data: break tcpCliSock.send('[{}] {}'.format(bytes(ctime(), 'utf-8'),data)) tcpCliSock.close() tcpSerSock.close() the client's code is: from socket import * HOST = 'localhost' PORT = 21567 BUFSIZ = 1024 ADDR =(HOST, PORT) tcpCliSock = socket(AF_INET, SOCK_STREAM) tcpCliSock.bind(ADDR) while True: data=input('> ') if not data: break tcpCliSock.send(data) data = tcpCliSock.recv(BUFSIZ) if not data: break print(data.decode('utf-8')) tcpCliSock.close() the problem is i get the following error when i enter some text: Traceback (most recent call last): File "C:\Python32\tsTclnt3.py", line 17, in tcpCliSock.send(data) TypeError: 'str' does not support the buffer interface can you help? -------------- next part -------------- An HTML attachment was scrubbed... URL: From evert.rol at gmail.com Fri Apr 6 15:59:17 2012 From: evert.rol at gmail.com (Evert Rol) Date: Fri, 6 Apr 2012 15:59:17 +0200 Subject: [Tutor] a problem with a server and client In-Reply-To: References: Message-ID: <713A7D06-9E1A-4AF8-8CFC-58CEA36FB821@gmail.com> > i'm trying to implement a server that adds a time stamp to incoming text form a client. > > the server's code is (but doesn't seem to have the problem as demoed by the error below: > > from socket import * > from time import ctime > > HOST = '' > PORT = 21567 > BUFSIZ = 1024 > ADDR =(HOST, PORT) > > tcpSerSock = socket(AF_INET, SOCK_STREAM) > > tcpSerSock.bind(ADDR) > tcpSerSock.listen(5) > > while True: > print('waiting for connection ...') > tcpCliSock, addr =tcpSerSock.accept() > print('...connected from: ', addr) > > while True: > data = tcpCliSock.recv(BUFSIZ) > if not data: > break > tcpCliSock.send('[{}] {}'.format(bytes(ctime(), 'utf-8'),data)) > > tcpCliSock.close() > tcpSerSock.close() > > > > the client's code is: > > from socket import * > > > HOST = 'localhost' > PORT = 21567 > BUFSIZ = 1024 > ADDR =(HOST, PORT) > > tcpCliSock = socket(AF_INET, SOCK_STREAM) > > tcpCliSock.bind(ADDR) > > while True: > data=input('> ') > if not data: > break > tcpCliSock.send(data) > data = tcpCliSock.recv(BUFSIZ) > if not data: > break > print(data.decode('utf-8')) > > tcpCliSock.close() > > the problem is i get the following error when i enter some text: > > Traceback (most recent call last): > File "C:\Python32\tsTclnt3.py", line 17, in > tcpCliSock.send(data) > TypeError: 'str' does not support the buffer interface Did you try to search on the error string? That would have gotten you the solution (even) faster. The first two Google hits (and probably all the rest of them), tell me that Python 3's socket.send() method wants bytes as input, not str. See http://docs.python.org/py3k/library/socket.html#socket.socket.send Hope that helps, Evert > > can you help? > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From johnf at jfcomputer.com Fri Apr 6 15:54:28 2012 From: johnf at jfcomputer.com (John Fabiani) Date: Fri, 06 Apr 2012 06:54:28 -0700 Subject: [Tutor] which gets called Message-ID: <1794779.eFi0vLpn8h@linux-12> Hi, I want to create a class that inherits two other classes. class NewClass( A,B) But both "A" and "B" contain a method with the same name ("onKeyDown"). If my "NewClass" does not contain something to override the methods which one would be called if myinstance = NewClass() myinstance.onKeyDown() Second to insure the right one is called is it possible to do the following NewClass(object): def onKeyDown(self, event): b.onKeyDown(event) Johnf From emailkgnow at gmail.com Fri Apr 6 16:08:53 2012 From: emailkgnow at gmail.com (Khalid Al-Ghamdi) Date: Fri, 6 Apr 2012 17:08:53 +0300 Subject: [Tutor] a problem with a server and client In-Reply-To: <713A7D06-9E1A-4AF8-8CFC-58CEA36FB821@gmail.com> References: <713A7D06-9E1A-4AF8-8CFC-58CEA36FB821@gmail.com> Message-ID: yah i did the search, and tried the solution, but it didn't work.... nice of you to have tried, though... anyhow, i found where the problem is... on the client side it should be connect() instead of bind() in : > tcpCliSock.bind(ADDR) thanks On Fri, Apr 6, 2012 at 4:59 PM, Evert Rol wrote: > > i'm trying to implement a server that adds a time stamp to incoming text > form a client. > > > > the server's code is (but doesn't seem to have the problem as demoed by > the error below: > > > > from socket import * > > from time import ctime > > > > HOST = '' > > PORT = 21567 > > BUFSIZ = 1024 > > ADDR =(HOST, PORT) > > > > tcpSerSock = socket(AF_INET, SOCK_STREAM) > > > > tcpSerSock.bind(ADDR) > > tcpSerSock.listen(5) > > > > while True: > > print('waiting for connection ...') > > tcpCliSock, addr =tcpSerSock.accept() > > print('...connected from: ', addr) > > > > while True: > > data = tcpCliSock.recv(BUFSIZ) > > if not data: > > break > > tcpCliSock.send('[{}] {}'.format(bytes(ctime(), 'utf-8'),data)) > > > > tcpCliSock.close() > > tcpSerSock.close() > > > > > > > > the client's code is: > > > > from socket import * > > > > > > HOST = 'localhost' > > PORT = 21567 > > BUFSIZ = 1024 > > ADDR =(HOST, PORT) > > > > tcpCliSock = socket(AF_INET, SOCK_STREAM) > > > > tcpCliSock.bind(ADDR) > > > > while True: > > data=input('> ') > > if not data: > > break > > tcpCliSock.send(data) > > data = tcpCliSock.recv(BUFSIZ) > > if not data: > > break > > print(data.decode('utf-8')) > > > > tcpCliSock.close() > > > > the problem is i get the following error when i enter some text: > > > > Traceback (most recent call last): > > File "C:\Python32\tsTclnt3.py", line 17, in > > tcpCliSock.send(data) > > TypeError: 'str' does not support the buffer interface > > Did you try to search on the error string? That would have gotten you the > solution (even) faster. > The first two Google hits (and probably all the rest of them), tell me > that Python 3's socket.send() method wants bytes as input, not str. See > http://docs.python.org/py3k/library/socket.html#socket.socket.send > > Hope that helps, > > Evert > > > > > > can you help? > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From chnlion79 at gmail.com Fri Apr 6 16:17:15 2012 From: chnlion79 at gmail.com (Lion Chen) Date: Fri, 06 Apr 2012 22:17:15 +0800 Subject: [Tutor] How to use g_timeout_add () function? Message-ID: <4F7EFAEB.7050601@gmail.com> Hello all, i have a question: when i check gtk_time_out in the gtk+2 reference, it said " |gtk_timeout_add|has been deprecated since version 2.4 and should not be used in newly-written code. Use |g_timeout_add()|instead." but i don't know how tu use the g_timout_add() function: my_id = g_timeout_add(500, myfunction()) or: my_id = gtk.g_timeout_add(500, myfunction()) everytime i run the program, it prompted me a message like modules do not have g_timeout_add() attribute. so i still have to use gtk_timeout_add.... anybody help me? Lion Chen -------------- next part -------------- An HTML attachment was scrubbed... URL: From emailkgnow at gmail.com Fri Apr 6 16:19:07 2012 From: emailkgnow at gmail.com (Khalid Al-Ghamdi) Date: Fri, 6 Apr 2012 17:19:07 +0300 Subject: [Tutor] a problem with a server and client In-Reply-To: References: <713A7D06-9E1A-4AF8-8CFC-58CEA36FB821@gmail.com> Message-ID: actually, you are right... in addition to that problem, there was the encodeing/decoding issue you mentioned on both the client and server. thanks On Fri, Apr 6, 2012 at 5:08 PM, Khalid Al-Ghamdi wrote: > yah i did the search, and tried the solution, but it didn't work.... nice > of you to have tried, though... > > anyhow, i found where the problem is... on the client side it should be > connect() instead of bind() in : > > > tcpCliSock.bind(ADDR) > > thanks > > > On Fri, Apr 6, 2012 at 4:59 PM, Evert Rol wrote: > >> > i'm trying to implement a server that adds a time stamp to incoming >> text form a client. >> > >> > the server's code is (but doesn't seem to have the problem as demoed by >> the error below: >> > >> > from socket import * >> > from time import ctime >> > >> > HOST = '' >> > PORT = 21567 >> > BUFSIZ = 1024 >> > ADDR =(HOST, PORT) >> > >> > tcpSerSock = socket(AF_INET, SOCK_STREAM) >> > >> > tcpSerSock.bind(ADDR) >> > tcpSerSock.listen(5) >> > >> > while True: >> > print('waiting for connection ...') >> > tcpCliSock, addr =tcpSerSock.accept() >> > print('...connected from: ', addr) >> > >> > while True: >> > data = tcpCliSock.recv(BUFSIZ) >> > if not data: >> > break >> > tcpCliSock.send('[{}] {}'.format(bytes(ctime(), 'utf-8'),data)) >> > >> > tcpCliSock.close() >> > tcpSerSock.close() >> > >> > >> > >> > the client's code is: >> > >> > from socket import * >> > >> > >> > HOST = 'localhost' >> > PORT = 21567 >> > BUFSIZ = 1024 >> > ADDR =(HOST, PORT) >> > >> > tcpCliSock = socket(AF_INET, SOCK_STREAM) >> > >> > tcpCliSock.bind(ADDR) >> > >> > while True: >> > data=input('> ') >> > if not data: >> > break >> > tcpCliSock.send(data) >> > data = tcpCliSock.recv(BUFSIZ) >> > if not data: >> > break >> > print(data.decode('utf-8')) >> > >> > tcpCliSock.close() >> > >> > the problem is i get the following error when i enter some text: >> > >> > Traceback (most recent call last): >> > File "C:\Python32\tsTclnt3.py", line 17, in >> > tcpCliSock.send(data) >> > TypeError: 'str' does not support the buffer interface >> >> Did you try to search on the error string? That would have gotten you the >> solution (even) faster. >> The first two Google hits (and probably all the rest of them), tell me >> that Python 3's socket.send() method wants bytes as input, not str. See >> http://docs.python.org/py3k/library/socket.html#socket.socket.send >> >> Hope that helps, >> >> Evert >> >> >> > >> > can you help? >> > _______________________________________________ >> > Tutor maillist - Tutor at python.org >> > To unsubscribe or change subscription options: >> > http://mail.python.org/mailman/listinfo/tutor >> >> > -------------- next part -------------- An HTML attachment was scrubbed... URL: From evert.rol at gmail.com Fri Apr 6 16:33:21 2012 From: evert.rol at gmail.com (Evert Rol) Date: Fri, 6 Apr 2012 16:33:21 +0200 Subject: [Tutor] which gets called In-Reply-To: <1794779.eFi0vLpn8h@linux-12> References: <1794779.eFi0vLpn8h@linux-12> Message-ID: <25A9EA95-885D-4DD5-8E2D-0D1D83A3CA99@gmail.com> > Hi, > > I want to create a class that inherits two other classes. > > class NewClass( A,B) > > But both "A" and "B" contain a method with the same name ("onKeyDown"). > > If my "NewClass" does not contain something to override the methods which one > would be called if > > myinstance = NewClass() > > myinstance.onKeyDown() > If I remember correctly, A.onKeyDown. But things can get more complicated in other cases. See also the following post for a read on the MRO (method resolution order); could help to clarify things (or confuse you further): http://python-history.blogspot.com/2010/06/method-resolution-order.html > Second to insure the right one is called is it possible to do the following > > NewClass(object): > > def onKeyDown(self, event): > b.onKeyDown(event) What is b here? Are you (trying to) save(ing) a parent as a instance in the class? Or should that be uppercase B? The latter would work, I think, though you'll have to put `self` here explicitly (since you're calling it without an instance, *and* you want to tell the method the instance is NewClass() instead of eg B()): def onKeyDown(self, event): B.onKeyDown(self, event) Cheers, Evert From evert.rol at gmail.com Fri Apr 6 16:39:05 2012 From: evert.rol at gmail.com (Evert Rol) Date: Fri, 6 Apr 2012 16:39:05 +0200 Subject: [Tutor] How to use g_timeout_add () function? In-Reply-To: <4F7EFAEB.7050601@gmail.com> References: <4F7EFAEB.7050601@gmail.com> Message-ID: > Hello all, i have a question: > > when i check gtk_time_out in the gtk+2 reference, it said " gtk_timeout_add has been deprecated since version 2.4 and should not be used in newly-written code. Use g_timeout_add() instead." > > but i don't know how tu use the g_timout_add() function: > my_id = g_timeout_add(500, myfunction()) > > or: > > my_id = gtk.g_timeout_add(500, myfunction()) > > everytime i run the program, it prompted me a message like modules do not have g_timeout_add() attribute. Although the error is reasonably clear, it's always good to specify the whole traceback (copy-paste it). It could show other (non)obvious mistakes. If your module does not have g_timeout_add, then either your module is old, or it is in another (sub)module. You would have to search the documentation for the latter. You actually don't say whether the above statement comes from the GTK2 documentation, or the pygtk documentation; I would assume the latter, since that makes more sense. But if the former, GTK and PyGTK may not be 100% in sync. > so i still have to use gtk_timeout_add.... > > anybody help me? PyGTK has its own mailing list (and even an IRC channel), which may be more practical in this specific case. Have a look over there: http://www.pygtk.org/feedback.html Cheers, Evert From steve at pearwood.info Fri Apr 6 16:43:27 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 07 Apr 2012 00:43:27 +1000 Subject: [Tutor] which gets called In-Reply-To: <1794779.eFi0vLpn8h@linux-12> References: <1794779.eFi0vLpn8h@linux-12> Message-ID: <4F7F010F.1030500@pearwood.info> John Fabiani wrote: > Hi, > > I want to create a class that inherits two other classes. > > class NewClass( A,B) > > But both "A" and "B" contain a method with the same name ("onKeyDown"). > > If my "NewClass" does not contain something to override the methods which one > would be called if > > myinstance = NewClass() > > myinstance.onKeyDown() This depends on whether classes A and B are designed for cooperative multiple inheritance or not. The short answer is, A.onKeyDown will be called, because A is listed first. The longer answer is, if A.onKeyDown uses super() to manager multiple inheritance, both A and B.onKeyDown may be called. Here is an example with no cooperative multiple inheritance: class A(object): def onKeyDown(self): print('A deals with keydown event') class B(object): def onKeyDown(self): print('B deals with keydown event') class NewClass(A, B): pass And in use, you will see that A blocks B: py> instance = NewClass() py> instance.onKeyDown() A deals with keydown event And here is a second example using super() for cooperative multiple inheritance: class A(object): def onKeyDown(self): print('A deals with keydown event') super(A, self).onKeyDown() # in Python 3, you can just use "super().onKeyDown()" class B(object): def onKeyDown(self): print('B deals with keydown event') # B does not call super(), because there are no # further parent classes to call. class NewClass(A, B): pass And in use: py> instance = NewClass() py> instance.onKeyDown() A deals with keydown event B deals with keydown event > Second to insure the right one is called is it possible to do the following > > NewClass(object): > def onKeyDown(self, event): > b.onKeyDown(event) Yes, but that normally should not be necessary if you design your classes carefully. -- Steven From brian.van.den.broek at gmail.com Fri Apr 6 16:44:20 2012 From: brian.van.den.broek at gmail.com (Brian van den Broek) Date: Fri, 6 Apr 2012 16:44:20 +0200 Subject: [Tutor] which gets called In-Reply-To: <1794779.eFi0vLpn8h@linux-12> References: <1794779.eFi0vLpn8h@linux-12> Message-ID: On 6 April 2012 15:54, John Fabiani wrote: > Hi, > > I want to create a class that inherits two other classes. > > class NewClass( A,B) > > But both "A" and "B" contain a method with the same name ("onKeyDown"). > > If my "NewClass" does not contain something to override the methods which one > would be called if > > myinstance = NewClass() > > myinstance.onKeyDown() Hi John, Easy enough to sort out with a little experiment: >>> class A(object): def doit(self): print "A" >>> class B(object): def doit(self): print "B" >>> class C(A,B): def __init__(self): self.doit() >>> c=C() A > Second to insure the right one is called is it possible to do the following > > NewClass(object): > > ?def onKeyDown(self, event): > ? ? ?b.onKeyDown(event) > Perhaps this helps, some: >>> class D(A,B): def __init__(self): self.doit() def doit(self): print "D" super(D, self).doit() >>> d=D() D A >>> class E(A,B): def __init__(self): B.doit(self) >>> e=E() B >>> Best, Brian vdB From breamoreboy at yahoo.co.uk Fri Apr 6 16:50:53 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 06 Apr 2012 15:50:53 +0100 Subject: [Tutor] How to use g_timeout_add () function? In-Reply-To: <4F7EFAEB.7050601@gmail.com> References: <4F7EFAEB.7050601@gmail.com> Message-ID: On 06/04/2012 15:17, Lion Chen wrote: > Hello all, i have a question: > > when i check gtk_time_out in the gtk+2 reference, it said " > |gtk_timeout_add|has been deprecated since version 2.4 and should not be > used in newly-written code. Use |g_timeout_add()|instead." > > but i don't know how tu use the g_timout_add() function: > my_id = g_timeout_add(500, myfunction()) > > or: > > my_id = gtk.g_timeout_add(500, myfunction()) > > everytime i run the program, it prompted me a message like modules do > not have g_timeout_add() attribute. > > so i still have to use gtk_timeout_add.... > > anybody help me? > > Lion Chen > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor It's much easier for us to help if you provide an exact snippet of code that reproduces the problem with the error message cut and pasted. Having said that there's nothing to stop you using gtk_timeout_add as it's only deprecated, i.e. it's been marked for removal at some time in the future. -- Cheers. Mark Lawrence. From breamoreboy at yahoo.co.uk Fri Apr 6 17:07:34 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 06 Apr 2012 16:07:34 +0100 Subject: [Tutor] which gets called In-Reply-To: <1794779.eFi0vLpn8h@linux-12> References: <1794779.eFi0vLpn8h@linux-12> Message-ID: On 06/04/2012 14:54, John Fabiani wrote: > Hi, > > I want to create a class that inherits two other classes. > > class NewClass( A,B) > > But both "A" and "B" contain a method with the same name ("onKeyDown"). > > If my "NewClass" does not contain something to override the methods which one > would be called if > > myinstance = NewClass() > > myinstance.onKeyDown() > Please see http://docs.python.org/tutorial/classes.html#multiple-inheritance. This references http://www.python.org/download/releases/2.3/mro/ Having read these why not try typing code into the interactive prompt and see what happens? Worst case you get an exception, if you don't understand it cut and paste it to a reply to this and we'll help out. > > Second to insure the right one is called is it possible to do the following > > NewClass(object): > > def onKeyDown(self, event): > b.onKeyDown(event) It's B.onKeyDown(self, event), without the self you'll get an unbound method error. > > Johnf > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Cheers. Mark Lawrence. From johnf at jfcomputer.com Fri Apr 6 18:45:26 2012 From: johnf at jfcomputer.com (John Fabiani) Date: Fri, 06 Apr 2012 09:45:26 -0700 Subject: [Tutor] which gets called In-Reply-To: <1794779.eFi0vLpn8h@linux-12> References: <1794779.eFi0vLpn8h@linux-12> Message-ID: <4978751.jtsnjQA3oc@linux-12> On Friday, April 06, 2012 06:54:28 AM John Fabiani wrote: > Hi, > > I want to create a class that inherits two other classes. > > class NewClass( A,B) > > But both "A" and "B" contain a method with the same name ("onKeyDown"). > > If my "NewClass" does not contain something to override the methods which > one would be called if > > myinstance = NewClass() > > myinstance.onKeyDown() > > > Second to insure the right one is called is it possible to do the following > > NewClass(object): > > def onKeyDown(self, event): > b.onKeyDown(event) > > Johnf Thanks guys! The class I'm creating is inheriting from classes I did not create. And of course the inherited classes are from different authors. So I'm attempting to create a wrapper and the problem comes from the keyboard events. Each of the classes has a onKeyDown method and I only want one to work and then pass the data to the second. But you have helped (along with the links). And I have successfully got the right method called. The issue is now getting the second (B) to fire correctly. Johnf From alan.gauld at btinternet.com Fri Apr 6 19:31:10 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 06 Apr 2012 18:31:10 +0100 Subject: [Tutor] How to have the name of a function inside the code of this function? In-Reply-To: <4F7EADBC.1000006@gmail.com> References: <4F7EADBC.1000006@gmail.com> Message-ID: On 06/04/12 09:47, Karim wrote: > If you have any idea to get the caller name inside the caller. Its not normally very helpful since in Python the same function can have many names: def F(x): return x*x a = F b = F c - lambda y: F(y) print F(1), a(2), b(3), c(4) Now, why would knowing whether the caller used F,a or b to call the same function object help? And what do you do in the case of c()? Do you return 'c' or 'F'? Maybe you could use it to tell you the context from which they were calling? But in that case there are usually better, more reliable, techniques - like examining the stackframe. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From breamoreboy at yahoo.co.uk Fri Apr 6 19:39:47 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 06 Apr 2012 18:39:47 +0100 Subject: [Tutor] How to use g_timeout_add () function? In-Reply-To: <4F7EFAEB.7050601@gmail.com> References: <4F7EFAEB.7050601@gmail.com> Message-ID: Please don't top post and please reply to the list Top posting fixed. ----- Forwarded Message ----- From: Lion Chen To: Mark Lawrence Cc: Sent: Friday, 6 April 2012, 16:43 Subject: Re: [Tutor] How to use g_timeout_add () function? fixed top posting > On 06/04/2012 15:17, Lion Chen wrote: >> Hello all, i have a question: >> >> when i check gtk_time_out in the gtk+2 reference, it said " >> |gtk_timeout_add|has been deprecated since version 2.4 and should not be >> used in newly-written code. Use |g_timeout_add()|instead." >> >> but i don't know how tu use the g_timout_add() function: >> my_id = g_timeout_add(500, myfunction()) >> >> or: >> >> my_id = gtk.g_timeout_add(500, myfunction()) >> >> everytime i run the program, it prompted me a message like modules do >> not have g_timeout_add() attribute. >> >> so i still have to use gtk_timeout_add.... >> >> anybody help me? >> >> Lion Chen >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > > It's much easier for us to help if you provide an exact snippet of > code that reproduces the problem with the error message cut and > pasted. Having said that there's nothing to stop you using > gtk_timeout_add as it's only deprecated, i.e. it's been marked for > removal at some time in the future. > the problem is solved. in Python, should use gobject.timeout_add() replace the g_timeout_add() g_timeout_add() is for c. -- Cheers. Mark Lawrence. From mylesbroomes at hotmail.co.uk Fri Apr 6 21:14:11 2012 From: mylesbroomes at hotmail.co.uk (myles broomes) Date: Fri, 6 Apr 2012 19:14:11 +0000 Subject: [Tutor] Emailing code Message-ID: This question isnt so much related to a specific program, just something im curious about. What is the best way to email code? I find that when i copy and paste it into an email, the indentation and spacing gets all messed up. Myles Broomes -------------- next part -------------- An HTML attachment was scrubbed... URL: From kliateni at gmail.com Fri Apr 6 21:19:07 2012 From: kliateni at gmail.com (Karim) Date: Fri, 06 Apr 2012 21:19:07 +0200 Subject: [Tutor] How to have the name of a function inside the code of this function? In-Reply-To: References: <4F7EADBC.1000006@gmail.com> Message-ID: <4F7F41AB.7010407@gmail.com> Le 06/04/2012 19:31, Alan Gauld a ?crit : > On 06/04/12 09:47, Karim wrote: > >> If you have any idea to get the caller name inside the caller. > > > Its not normally very helpful since in Python the same function can > have many names: > > def F(x): > return x*x > > a = F > b = F > c - lambda y: F(y) > > print F(1), a(2), b(3), c(4) > > Now, why would knowing whether the caller used F,a or b > to call the same function object help? And what do you > do in the case of c()? Do you return 'c' or 'F'? > > Maybe you could use it to tell you the context from > which they were calling? But in that case there are > usually better, more reliable, techniques > - like examining the stackframe. > > HTH, Thanks Steven, Moduok and Steven for all your answers! The reason is simple I wanted to optimize some code using pyuno for openoffice.org doc generation I have several methods to set text with "Heading 1", ... "Heading " title style: def title(self, text='', style="Heading 1"): self._cursor_text.setPropertyValue('ParaStyleName', style) self.add_text(text) def title1(self, text=''): self.title(text=text) def title2(self, text=''): self.title(text='', style="Heading 2") ... def title9(self, text=''): self.title(text='', style="Heading 9") --------------------------------------------------------------------------------- I just wanted to improve a little by doing something like that (pseudo code): def title9(self, text=''): self.title(text='', style="Heading " + .split()[1]) In short the number in the funtion name is the number of the title depth in the document. There is no big deal if Iit's not feasible; Cheers Karim From emile at fenx.com Fri Apr 6 21:41:15 2012 From: emile at fenx.com (Emile van Sebille) Date: Fri, 06 Apr 2012 12:41:15 -0700 Subject: [Tutor] Emailing code In-Reply-To: References: Message-ID: On 4/6/2012 12:14 PM myles broomes said... > This question isnt so much related to a specific program, just something > im curious about. What is the best way to email code? I find that when i > copy and paste it into an email, the indentation and spacing gets all > messed up. > Set your email client content type to deliver plain text -- anything html-ish allows compression of spaces hence the formatting loss. Emile From tmujica at verizon.net Fri Apr 6 21:11:11 2012 From: tmujica at verizon.net (Thomas Mujica) Date: Fri, 06 Apr 2012 15:11:11 -0400 Subject: [Tutor] How do you save work in progress in Pyscripter ? Message-ID: Please help a newbie Was able to write and successfully run this but I can't seem to be able to "save" it Luckily I had saved it to Word and then I was able to copy and paste it back into PyScripter. I'm using Python Scripter Version 2.5.3.0 x86 *** Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32. *** *** Remote Python engine is active *** >>> >>> from decimal import * >>> getcontext() Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999, capitals=1, flags=[], traps=[DivisionByZero, InvalidOperation, Overflow]) >>> getcontext().prec=3 #change decimal precision to 3 decimal places >>> for a in xrange(1,30): #NESTED note no matter what the variables are the syntax is always xrange ... for b in xrange(1,30): #LOOPS DO 29 ITERATIONS ... c=pow(a,2)+pow(b,2) # this is really c squared because a and b are raised to exponent 2 ... h=pow(c,.5) #pow is .5 so h is the square root of c ...h is the hypotenuse ... d=round(h,2) ... if a==1 and b==1: #will allow titles to be printed at beginning of print out ... print "Side a","Side b","Hypotenuse" ... if h==d and d==h: #will eliminate all values of h that are not integers from printout ... print" ",a,"\t",b,"\t\t",h #for alignment purpose "3 spaces " before a then tab b, and 2tabs ... # before h Side a Side b Hypotenuse 3 4 5.0 4 3 5.0 5 12 13.0 6 8 10.0 7 24 25.0 8 6 10.0 8 15 17.0 9 12 15.0 10 24 26.0 12 5 13.0 12 9 15.0 12 16 20.0 15 8 17.0 15 20 25.0 16 12 20.0 18 24 30.0 20 15 25.0 20 21 29.0 21 20 29.0 21 28 35.0 24 7 25.0 24 10 26.0 24 18 30.0 28 21 35.0 -------------- next part -------------- An HTML attachment was scrubbed... URL: From wescpy at gmail.com Fri Apr 6 22:38:13 2012 From: wescpy at gmail.com (wesley chun) Date: Fri, 6 Apr 2012 13:38:13 -0700 Subject: [Tutor] Emailing code In-Reply-To: References: Message-ID: On Fri, Apr 6, 2012 at 12:14 PM, myles broomes wrote: > This question isnt?so much related to a specific program, just something im > curious about. What is the best way to email code? I find that when i copy > and paste it into an email, the indentation and spacing gets all messed up. as an alternative to emailing code, you can paste(bin) it online and just send (or tweet or G+ or otherwise post) the URL... there are many providers of this type of service out there: http://www.similarsitesearch.com/alternatives-to/pastebin.com cheers, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "A computer never does what you want... only what you tell it." ? ? wesley chun : wescpy at gmail?: @wescpy/+wescpy ? ? Python training & consulting :?http://CyberwebConsulting.com ? ? "Core Python" books :?http://CorePython.com ? ? Python blog: http://wescpy.blogspot.com From mylesbroomes at hotmail.co.uk Sat Apr 7 00:07:04 2012 From: mylesbroomes at hotmail.co.uk (myles broomes) Date: Fri, 6 Apr 2012 22:07:04 +0000 Subject: [Tutor] Tkinter GUI crashing problem Message-ID: Im working the Tkinter and I'm having a problem with the GUI I made. It crashes whenever I hit the submit button. Heres my code: #Guess my number 2.0 #The guess my number game but using a GUI import random from tkinter import * class Application(Frame): """GUI to hold widgets. """ def __init__(self,master): super(Application,self).__init__(master) self.grid() self.createWidgets() def createWidgets(self): """GUI widgets. """ #Label instructing the user to take a guess Label(self,text="Take a guess:").grid(row=0,column=0) #Entry widget where the user makes a guess self.guess_ent = Entry(self) self.guess_ent.grid(row=1,column=0) #Button that updates the text box self.submit_bttn = Button(self,command=self.update_txt,text="Submit guess") self.submit_bttn.grid(row=2,column=0) #Text box to update the user on whether their guess is correct self.txt_box = Text(self,width=35,height=5,wrap=WORD) self.txt_box.grid(row=3,column=0) def update_txt(self): """Updates the text box widget. """ #Get user input from the entry widget number = random.randint(1,100) message = "" guess = None while self.guess_ent.get(): guess = self.guess_ent.get() if int(guess) > number: message += "Lower..." self.txt_box.delete(0.0,END) self.txt_box.insert(0.0,message) else: message += "Higher..." self.txt_box.delete(0.0,END) self.txt_box.insert(0.0,message) if int(guess) == number: message += "Congrarulations! You guessed correctly! A new number has been generated." self.txt_box.delete(0.0,END) self.txt_box.insert(0.0,message) #main root = Tk() root.title("Guess my number") app = Application(root) root.mainloop() Its frustrating because I dont even get an error code. I coded the last function in a seperate program without a GUI and it runs fine so I have no clue what the problem can be. Any help would be much appreciated. Myles Broomes From emile at fenx.com Sat Apr 7 00:47:26 2012 From: emile at fenx.com (Emile van Sebille) Date: Fri, 06 Apr 2012 15:47:26 -0700 Subject: [Tutor] Tkinter GUI crashing problem In-Reply-To: References: Message-ID: On 4/6/2012 3:07 PM myles broomes said... > > import random > from tkinter import * What version of python on what platform please... Emile From alan.gauld at btinternet.com Sat Apr 7 01:24:45 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 07 Apr 2012 00:24:45 +0100 Subject: [Tutor] How do you save work in progress in Pyscripter ? In-Reply-To: References: Message-ID: On 06/04/12 20:11, Thomas Mujica wrote: > *Was able to write and successfully run this but I can?t seem to be able > to ?save? it* You have written the code at the interactive prompt which is really intended for experimenting. To save the code as a python script you need to create a plain text file and save it with a .py extension (assuming you are on Windows). You could use something as basic as Notepad to create it but most IDEs or specialist programming editors will be more useful. I don;t know pyscripter but usually you can use the File->New menu to create a new blank editor window where you can type the code. You then save it with File->Save/SaveAs as usual. How you run it varies by IDE... Note you don't type the >>> and other stuff that the interpreter puts out, so your code would look like: from decimal import * getcontext().prec=3 #change decimal precision to 3 decimal places* for a in xrange(1,30): #NESTED note no matter what the variables for b in xrange(1,30): #LOOPS DO 29 ITERATIONS* c=pow(a,2)+pow(b,2) # this is really c squared because a and b are h=pow(c,.5) #pow is .5 so h is the square root of c ?..h is the d=round(h,2) if a==1 and b==1: #will allow titles to be printed at beginning of print "Side a","Side b","Hypotenuse" if h==d and d==h: #will eliminate all values of h that are not print" ",a,"\t",b,"\t\t",h #for alignment purpose ?3 spaces ? There are some odd things in that code that I could comment on, but for now I'll ignore them and see if you can get the script running first. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sat Apr 7 01:33:25 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 07 Apr 2012 00:33:25 +0100 Subject: [Tutor] Tkinter GUI crashing problem In-Reply-To: References: Message-ID: On 06/04/12 23:07, myles broomes wrote: > > Im working the Tkinter and I'm having a problem with the GUI I made. > It crashes whenever I hit the submit button. Heres my code: What do you mean by crashes? It looks to me like it should lock up rather than crash. Your update_txt method goes into an infinite loop: > while self.guess_ent.get(): > guess = self.guess_ent.get() > if int(guess)> number: > message += "Lower..." > self.txt_box.delete(0.0,END) > self.txt_box.insert(0.0,message) > else: > message += "Higher..." > self.txt_box.delete(0.0,END) > self.txt_box.insert(0.0,message) > Since this never exits the screen never refreshes to allow the user to enter a new value in the guess_ent box. loops inside event handling methods are always risky and should be avoided if at all possible. Open ended while loops are especially prone to non termination. If you need to process something repeatedly its usually better in a GUI program to do it via a timer event that continually calls the function. (Or using a background thread but thats a whole different can of worms) But in this case the whole while loop is completely redundant. Tkinter provides an event loop, you just need to handle one guess at a time and let the user press submit each time. If you really are crashing please run the code from inside an OS console and capture the stack trace and send it to us. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Sat Apr 7 03:07:02 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 07 Apr 2012 11:07:02 +1000 Subject: [Tutor] Emailing code In-Reply-To: References: Message-ID: <4F7F9336.7020503@pearwood.info> myles broomes wrote: > This question isnt so much related to a specific program, just something im > curious about. What is the best way to email code? I find that when i copy > and paste it into an email, the indentation and spacing gets all messed up. Don't send HTML, because that is poison to correct formatting of Python code. Mail clients feel free to reformat indentation and spacing in arbitrary ways with HTML emails. Find the setting in your mail client to turn off all formatting. My guess is that you are using Outlook or Outlook Express -- look for the setting about "Rich Text", and turn that off. If you can't turn it off, at least turn on the option to send both HTML (rich text) and plain text. The HTML version will probably be mangled, but the plain text version should be okay. If you are using Thunderbird, turning off format=flowed can sometimes help. http://kb.mozillazine.org/Plain_text_e-mail_%28Thunderbird%29 For large amounts of code, don't copy and paste into your email. Nearly every email program in the world allows you to attach attachments. Just attach the .py file and send that. -- Steven From d at davea.name Sat Apr 7 04:01:55 2012 From: d at davea.name (Dave Angel) Date: Fri, 06 Apr 2012 22:01:55 -0400 Subject: [Tutor] How to have the name of a function inside the code of this function? In-Reply-To: <4F7F41AB.7010407@gmail.com> References: <4F7EADBC.1000006@gmail.com> <4F7F41AB.7010407@gmail.com> Message-ID: <4F7FA013.6000400@davea.name> On 04/06/2012 03:19 PM, Karim wrote: > Le 06/04/2012 19:31, Alan Gauld a ?crit : >> On 06/04/12 09:47, Karim wrote: >> >>> If you have any idea to get the caller name inside the caller. >> >> >> Its not normally very helpful since in Python the same function can >> have many names: >> >> def F(x): >> return x*x >> >> a = F >> b = F >> c - lambda y: F(y) >> >> print F(1), a(2), b(3), c(4) >> >> Now, why would knowing whether the caller used F,a or b >> to call the same function object help? And what do you >> do in the case of c()? Do you return 'c' or 'F'? >> >> Maybe you could use it to tell you the context from >> which they were calling? But in that case there are >> usually better, more reliable, techniques >> - like examining the stackframe. >> >> HTH, > > Thanks Steven, Moduok and Steven for all your answers! > > The reason is simple I wanted to optimize some code using pyuno for > openoffice.org doc generation I have several methods to set > text with "Heading 1", ... "Heading " title style: > > def title(self, text='', style="Heading 1"): > self._cursor_text.setPropertyValue('ParaStyleName', style) > self.add_text(text) > > def title1(self, text=''): > self.title(text=text) > > def title2(self, text=''): > self.title(text='', style="Heading 2") > > ... > > def title9(self, text=''): > self.title(text='', style="Heading 9") > > --------------------------------------------------------------------------------- > > > I just wanted to improve a little by doing something like that (pseudo > code): > > def title9(self, text=''): > self.title(text='', style="Heading " + .split()[1]) > > > In short the number in the funtion name is the number of the title > depth in the document. > There is no big deal if Iit's not feasible; > > Cheers > Karim > > > Those are methods, not functions. So if you have a bunch of methods, differing only in the numeric suffix their names have, and one of the parameters to a method they each call, there's probably a simpler way. First, you could create function objects (using approaches like partial), turn them into methods, and attach them to a class with generated names (somebody else will have to help you do it; I just am pretty sure it's possible) Second, ifyou can control the code which will be calling these methods, you could just have that code parameterize things a little differently. For example, instead of calling obj.title9("my text") it might call obj.title(9, "my text") where title() is a pretty simple, single method. -- DaveA From steve at pearwood.info Sat Apr 7 04:10:09 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 07 Apr 2012 12:10:09 +1000 Subject: [Tutor] Tkinter GUI crashing problem In-Reply-To: References: Message-ID: <4F7FA201.3070705@pearwood.info> myles broomes wrote: > Im working the Tkinter and I'm having a problem with the GUI I made. It > crashes whenever I hit the submit button. Heres my code: Define "crashes". Does it: * cause your computer to Blue Screen of Death? * lock up your computer until you Ctrl-Alt-Delete? * cause Windows to put up an error message saying the application has crashed and would you like to submit diagnostics to Microsoft? * print a standard Python traceback? * something else? If you get a traceback, please COPY AND PASTE the entire traceback into an email and send that. Do not retype it by hand, summarise, simplify or otherwise reword it. -- Steven From kliateni at gmail.com Sat Apr 7 04:14:07 2012 From: kliateni at gmail.com (Karim) Date: Sat, 07 Apr 2012 04:14:07 +0200 Subject: [Tutor] How to have the name of a function inside the code of this function? In-Reply-To: <4F7FA013.6000400@davea.name> References: <4F7EADBC.1000006@gmail.com> <4F7F41AB.7010407@gmail.com> <4F7FA013.6000400@davea.name> Message-ID: <4F7FA2EF.6070408@gmail.com> Le 07/04/2012 04:01, Dave Angel a ?crit : > On 04/06/2012 03:19 PM, Karim wrote: >> Le 06/04/2012 19:31, Alan Gauld a ?crit : >>> On 06/04/12 09:47, Karim wrote: >>> >>>> If you have any idea to get the caller name inside the caller. >>> >>> Its not normally very helpful since in Python the same function can >>> have many names: >>> >>> def F(x): >>> return x*x >>> >>> a = F >>> b = F >>> c - lambda y: F(y) >>> >>> print F(1), a(2), b(3), c(4) >>> >>> Now, why would knowing whether the caller used F,a or b >>> to call the same function object help? And what do you >>> do in the case of c()? Do you return 'c' or 'F'? >>> >>> Maybe you could use it to tell you the context from >>> which they were calling? But in that case there are >>> usually better, more reliable, techniques >>> - like examining the stackframe. >>> >>> HTH, >> Thanks Steven, Moduok and Steven for all your answers! >> >> The reason is simple I wanted to optimize some code using pyuno for >> openoffice.org doc generation I have several methods to set >> text with "Heading 1", ... "Heading" title style: >> >> def title(self, text='', style="Heading 1"): >> self._cursor_text.setPropertyValue('ParaStyleName', style) >> self.add_text(text) >> >> def title1(self, text=''): >> self.title(text=text) >> >> def title2(self, text=''): >> self.title(text='', style="Heading 2") >> >> ... >> >> def title9(self, text=''): >> self.title(text='', style="Heading 9") >> >> --------------------------------------------------------------------------------- >> >> >> I just wanted to improve a little by doing something like that (pseudo >> code): >> >> def title9(self, text=''): >> self.title(text='', style="Heading " +.split()[1]) >> >> >> In short the number in the funtion name is the number of the title >> depth in the document. >> There is no big deal if Iit's not feasible; >> >> Cheers >> Karim >> >> >> > Those are methods, not functions. So if you have a bunch of methods, > differing only in the numeric suffix their names have, and one of the > parameters to a method they each call, there's probably a simpler way. > > First, you could create function objects (using approaches like > partial), turn them into methods, and attach them to a class with > generated names (somebody else will have to help you do it; I just am > pretty sure it's possible) > > Second, ifyou can control the code which will be calling these methods, > you could just have that code parameterize things a little differently. > For example, instead of calling > > obj.title9("my text") > > it might call > obj.title(9, "my text") > > where title() is a pretty simple, single method. > Thanks Dave, In fact at first I did that: obj.title(text='my text', heading=9) But I wanted something more flashing to recognize and more simple to write because I've got a lot of call in my 1000 pages document creation. I will take a look at partial. Cheers PS: By the I thanked Steven twice this one an mistake sorry and thank you Alan! From mjolewis at gmail.com Sun Apr 8 16:50:13 2012 From: mjolewis at gmail.com (mjolewis at gmail.com) Date: Sun, 8 Apr 2012 07:50:13 -0700 Subject: [Tutor] Opensource projects / Subversion Message-ID: Hey everyone, I finally made my way into working on Opensource projects. I installed tortoisesvn. I included command line tools when running the installer. However when I invoke svn at command line, I get the following error: "svn: command not found" It seems like svn isn't installed, but again, I had the installer include command line tools. Please help. Sent from my iPhone From steve at pearwood.info Sun Apr 8 17:07:44 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 09 Apr 2012 01:07:44 +1000 Subject: [Tutor] Opensource projects / Subversion In-Reply-To: References: Message-ID: <4F81A9C0.5010700@pearwood.info> mjolewis at gmail.com wrote: > Hey everyone, > > I finally made my way into working on Opensource projects. I installed tortoisesvn. I included command line tools when running the installer. However when I invoke svn at command line, I get the following error: > > "svn: command not found" > > It seems like svn isn't installed, but again, I had the installer include command line tools. > > Please help. Does this have anything to do with learning Python? What's tortoisesvn? Since you're having a problem with that, shouldn't you be asking on a tortoisesvn mailing list? -- Steven From mail at timgolden.me.uk Sun Apr 8 17:28:00 2012 From: mail at timgolden.me.uk (Tim Golden) Date: Sun, 08 Apr 2012 16:28:00 +0100 Subject: [Tutor] Opensource projects / Subversion In-Reply-To: <4F81A9C0.5010700@pearwood.info> References: <4F81A9C0.5010700@pearwood.info> Message-ID: <4F81AE80.2010305@timgolden.me.uk> On 08/04/2012 16:07, Steven D'Aprano wrote: > mjolewis at gmail.com wrote: >> Hey everyone, >> >> I finally made my way into working on Opensource projects. I installed >> tortoisesvn. I included command line tools when running the installer. >> However when I invoke svn at command line, I get the following error: >> >> "svn: command not found" >> >> It seems like svn isn't installed, but again, I had the installer >> include command line tools. >> Please help. > > Does this have anything to do with learning Python? What's tortoisesvn? > Since you're having a problem with that, shouldn't you be asking on a > tortoisesvn mailing list? As Steven points out, this is more to do with installing particular development tools that with learning Python. However... TortoiseSVN is a popular Windows Shell extension offering easy access to Subversion via Windows Explorer. Although its installers have, for a long time, only offered Shell (in the Windows sense) access to the Subversion functions, more recent installers have offered to install the commandline svn tools as well. Since I have the commandline tools already installed, I've never actually selected this option when upgrading to newer versions. So what I don't know is whether they also add a suitable directory to the PATH environment variable. But, given the message you're getting, I imagine they don't. I suspect that they would install to somewhere like: %PROGRAMFILES%\TortoiseSvn\bin You can confirm that by cut-and-pasting that into your Start > Run menu or into an Explorer address bar and seeing if it comes up with a directory or not. If not, you'll have to scout around in likely places to see where it *has* installed svn.exe and its friends. Once you find them, add that directory to the PATH via: Control Panel > System > Advanced > Environment Variables depending somewhat on what setup you're running. And then try again at the command prompt with svn. Alternatively, don't bother with the command prompt; just use TortoiseSvn natively, so to speak. TJG From wayne at waynewerner.com Sun Apr 8 23:26:45 2012 From: wayne at waynewerner.com (Wayne Werner) Date: Sun, 8 Apr 2012 16:26:45 -0500 (CDT) Subject: [Tutor] regex question In-Reply-To: References: Message-ID: On Fri, 6 Apr 2012, Khalid Al-Ghamdi wrote: > hi all, > I'm trying to extract the domain in the following string. Why doesn't my pattern (patt) work: > > >>> redata > 'Tue Jan 14 00:43:21 2020::eaximi at gstwyysnbd.gov::1578951801-6-10 Sat Jul 31 15:17:39 1993::rzppg at wgxvhx.com::744121059-5-6 Mon Sep 21 20:22:37 > 1987::ttwqrf at rpybrct.edu::559243357-6-7 Fri Aug ?2 07:15:23 1991::tjyp at mgfyitsks.net::681106523-4-9 Mon Mar 18 19:59:47 2024::dgzxmb at fhyykji.org::1710781187-6-7 ' > >>> patt=r'\w+\.\w{3}(?<=@)' > >>> re.findall(patt,redata) > [] > > This pattern works but the first should, too. shouldn't it? The all too familiar quote looks like it applies here: "Often programmers, when faced with a problem, think 'Aha! I'll use a regex!'. Now you have two problems." It looks like you could easily split this string with redata.split('::') and then look at every second element in the list and split *that* element on the last '.' in the string. With data as well-formed as this, regex is probably overkill. HTH, Wayne From sdragon1984 at gmail.com Mon Apr 9 00:26:10 2012 From: sdragon1984 at gmail.com (Nathan) Date: Sun, 8 Apr 2012 18:26:10 -0400 Subject: [Tutor] Calling Classes From Tkinter Radio Buttons Message-ID: I'm using Tkinter for a GUI for a program of mine, and I'm trying to use radio buttons to select different functions, but it's not working right at all. Originally, I had something like class ClassOne(self): def ___str___(self): return "This is the base class." class ClassTwo(ClassOne): def __str__(self): return "This is the derived class." in, say, classes.py, and something like import classes from Tkinter import * class Application(Frame): def __init__(self, master): Frame.__init__(self, master) self.grid() self.widgets() LabelText = classes.ClassOne() def widgets(self): ClassLabel = Label(self, text = self.LabelText) ClassLabel.grid() root = Tk() app = Application(root) root.mainloop() in, say, GUI.py. This works perfectly fine, but it only sets the label as "This is the base class." What I'd like is a way to use radio buttons to configure the text of ClassLabel so that the user can choose between the two classes. Currently, I'm trying changing GUI.py to something like: import classes from Tkinter import * class Application(Frame): def __init__(self, master): Frame.__init__(self, master) self.grid() self.widgets() LabelText = classes.ClassOne() classes = ["ClassOne", "ClassTwo"] def widgets(self): self.variable = IntVar() ClassLabel = Label(self, text = self.LabelText) ClassLabel.grid(row = 0) ClassOneButton = Radiobutton(self, text = "This selects the base class.", variable = self.variable, value = 0, command = self.ChangeClass) ClassOneButton.grid(row = 1, column = 0) ClassTwoButton = Radiobutton(self, text = "This selects the derived class.", variable = self.variable, value = 1, command = self.ChangeClass) ResetButton = Button(self, text = "Reset the label", command = self.ResetLabel) def ResetLabel(self): self.ClassLabel.configure(text = LabelText) def ChangeClass(self): self.selection = self.variable.get() # This should get the value of the selected radio button, right? self.LabelText = self.classes[self.selection]() # LabelText changes according to the radio button. root = Tk() app = Application(root) root.mainloop() ... but when I run this, BOTH radio buttons are selected, and it still just gives me the base class. What am I doing wrong? Is there a way to first call a class with a radio button, and then reconfigure the label with that class? Any help that can be offered is appreciated! From alan.gauld at btinternet.com Mon Apr 9 02:57:22 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 09 Apr 2012 01:57:22 +0100 Subject: [Tutor] Calling Classes From Tkinter Radio Buttons In-Reply-To: References: Message-ID: On 08/04/12 23:26, Nathan wrote: > I'm using Tkinter for a GUI for a program of mine, and I'm trying to > use radio buttons to select different functions, Sorry, its too late for my brain to try and decipher your code (even though you have tried to shorten it!). But you can see a simple example of radio button usage in the case study topic of my tutorial... HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From jkfbupt at gmail.com Mon Apr 9 06:09:05 2012 From: jkfbupt at gmail.com (kaifeng jin) Date: Mon, 9 Apr 2012 12:09:05 +0800 Subject: [Tutor] regex question In-Reply-To: References: Message-ID: I think you can do this: a=[] b=redata.split('::') for e in b: if e.find('@') != -1: a.append(e.split('@')[1]) list a includes all the domain ? 2012?4?9? ??5:26?Wayne Werner ??? > On Fri, 6 Apr 2012, Khalid Al-Ghamdi wrote: > > hi all, >> I'm trying to extract the domain in the following string. Why doesn't my >> pattern (patt) work: >> >> >>> redata >> 'Tue Jan 14 00:43:21 2020::eaximi at gstwyysnbd.gov::**1578951801-6-10 Sat >> Jul 31 15:17:39 1993::rzppg at wgxvhx.com::**744121059-5-6 Mon Sep 21 >> 20:22:37 >> 1987::ttwqrf at rpybrct.edu::**559243357-6-7 Fri Aug 2 07:15:23 >> 1991::tjyp at mgfyitsks.net::**681106523-4-9 Mon Mar 18 19:59:47 >> 2024::dgzxmb at fhyykji.org::**1710781187-6-7 ' >> >>> patt=r'\w+\.\w{3}(?<=@)' >> >>> re.findall(patt,redata) >> [] >> >> This pattern works but the first should, too. shouldn't it? >> > > The all too familiar quote looks like it applies here: "Often programmers, > when faced with a problem, think 'Aha! I'll use a regex!'. Now you have two > problems." > > It looks like you could easily split this string with redata.split('::') > and then look at every second element in the list and split *that* element > on the last '.' in the string. > > With data as well-formed as this, regex is probably overkill. > > HTH, > Wayne > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- twitter:@zybest ?????@??? ?openshift???wordpress?http://blog-mking.rhcloud.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From existentialleo at gmail.com Mon Apr 9 08:26:39 2012 From: existentialleo at gmail.com (leo degon) Date: Mon, 9 Apr 2012 02:26:39 -0400 Subject: [Tutor] Game of python, help please. Message-ID: Hello all, Im trying to learn python and programming in my free time, and I'm trying to do a little personal project to trying and gain some skills. Im trying to do version of John conways game of life. I have a working version of the game. Written for 3.2.2 on a mac to be accessed through terminal. I'm trying to give it a number of options. it dimensions, the max number of turns, initial set up, and boundary conditions. The dimensions and turns were pretty easy to include. The boundary conditions more difficult, and now I'm getting stuck on the initial set up options. I can set it up randomly but Im having problems implementing a checker board pattern. '''displays: the text of the game of life for a set number of X x Y for a set of R turns. [-][-][-][-][-] [-][-][-][-][-] [-][-][-][-][-] [-][-][-][-][-] [-][-][-][-][-] Get X,Y,T, Initial value Create a data space X x Y Assign initial value print initial value and the text' initial value' do while turns -------------- next part -------------- A non-text attachment was scrubbed... Name: iam.py Type: application/octet-stream Size: 8681 bytes Desc: not available URL: From __peter__ at web.de Mon Apr 9 10:51:18 2012 From: __peter__ at web.de (Peter Otten) Date: Mon, 09 Apr 2012 10:51:18 +0200 Subject: [Tutor] Calling Classes From Tkinter Radio Buttons References: Message-ID: Nathan wrote: > I'm using Tkinter for a GUI for a program of mine, and I'm trying to > use radio buttons to select different functions, but it's not working > right at all. Originally, I had something like > > class ClassOne(self): You didn't run that code. > def ___str___(self): > return "This is the base class." > > class ClassTwo(ClassOne): > > def __str__(self): > return "This is the derived class." > > in, say, classes.py, and something like > > import classes > from Tkinter import * > > class Application(Frame): > > def __init__(self, master): > Frame.__init__(self, master) > self.grid() > self.widgets() > > LabelText = classes.ClassOne() > > def widgets(self): > ClassLabel = Label(self, text = self.LabelText) > ClassLabel.grid() > > root = Tk() > app = Application(root) > root.mainloop() > > in, say, GUI.py. This works perfectly fine, but it only sets the label > as "This is the base class." What I'd like is a way to use radio > buttons to configure the text of ClassLabel so that the user can > choose between the two classes. > > Currently, I'm trying changing GUI.py to something like: Don't handwave, fix the errors you *can* fix. > import classes > from Tkinter import * > > class Application(Frame): > > def __init__(self, master): > Frame.__init__(self, master) > self.grid() > self.widgets() > > LabelText = classes.ClassOne() > classes = ["ClassOne", "ClassTwo"] > > def widgets(self): > self.variable = IntVar() > ClassLabel = Label(self, text = self.LabelText) > ClassLabel.grid(row = 0) > ClassOneButton = Radiobutton(self, text = "This selects the > base class.", variable = self.variable, value = 0, command = > self.ChangeClass) > ClassOneButton.grid(row = 1, column = 0) > ClassTwoButton = Radiobutton(self, text = "This selects the > derived class.", variable = self.variable, value = 1, command = > self.ChangeClass) > ResetButton = Button(self, text = "Reset the label", command = > self.ResetLabel) > > def ResetLabel(self): > self.ClassLabel.configure(text = LabelText) > > def ChangeClass(self): > self.selection = self.variable.get() # This should get the > value of the selected radio button, right? > self.LabelText = self.classes[self.selection]() # LabelText > changes according to the radio button. > > root = Tk() > app = Application(root) > root.mainloop() > > > ... but when I run this, BOTH radio buttons are selected, and it still > just gives me the base class. What am I doing wrong? Is there a way to > first call a class with a radio button, and then reconfigure the label > with that class? Any help that can be offered is appreciated! Keep it simple. If str(ClassOne()) stays the same throughout the lifetime of the instance I'd use that string as the associated radio button's value and have the label and the radio buttons share the same StringVar. Below is an example that assumes that the string may change and you want a snapshot. Instead of reacting to radio button events all changes of the underlying IntVar are traced. import Tkinter as tk import datetime class One(object): def time(self): return datetime.datetime.now().strftime("%H:%M:%S") def __str__(self): return self.__class__.__name__ + " at " + self.time() class Two(One): pass class Application(tk.Frame): def __init__(self, master): tk.Frame.__init__(self, master) self.classes = [One(), Two()] self.grid() self.widgets() def widgets(self): self.radiovar = tk.IntVar() self.radiovar.trace("w", self.update_label) self.labelvar = tk.StringVar() label = tk.Label(self, textvariable=self.labelvar) label.grid(row=0, column=0) for index, text in enumerate([ "This selects the base class.", "This selects the derived class.",]): button = tk.Radiobutton( self, text=text, variable=self.radiovar, value=index) button.grid(row=index+1, column=0, sticky=tk.W) self.radiovar.set(0) def update_label(self, *args): text = self.classes[self.radiovar.get()] self.labelvar.set(text) if __name__ == "__main__": root = tk.Tk() app = Application(root) root.mainloop() From suryak at live.com Mon Apr 9 11:13:11 2012 From: suryak at live.com (Surya K) Date: Mon, 9 Apr 2012 14:43:11 +0530 Subject: [Tutor] GUI for python Google App Engine Message-ID: Hi there, I just wrote a small game in python and would like to make it a facebook app. These are the things I wish to know: 1. How to write GUI for my app. I believe, PyQt or Wx wouldn't work in Google App Engine.2. How to integrate my app with facebook. I went through facebook documentation but couldn't get it clearly.. this is what I require as per the game: Two players join a game and each player inputs a character.. Any small tutorials that would teach me would be appreciated.. Right now I don't want to learn about GAE or Facebook API in detail. I just want to build my app. -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Mon Apr 9 14:19:09 2012 From: d at davea.name (Dave Angel) Date: Mon, 09 Apr 2012 08:19:09 -0400 Subject: [Tutor] Game of python, help please. In-Reply-To: References: Message-ID: <4F82D3BD.8010501@davea.name> On 04/09/2012 02:26 AM, leo degon wrote: > Hello all, Im trying to learn python and programming in my free time Welcome to the list; I think you'll enjoy Python programming, and think it makes an excellent first language. > , and > I'm trying to do a little personal project to trying and gain some skills. > Im trying to do version of John conways game of life. I have a working > version of the game. Written for 3.2.2 on a mac to be accessed through > terminal. Thanks for giving that information. Many people skip the step of describing the environment. Some general comments first. You've managed in the code below to avoid many of the beginner mistakes in Python, like building a two dimensional array by replicating one row. But you do have a few quirks, by inspection. I've not tried to run any of the code. The biggest one is that you have only one function. Much of this code is very repetitive, and thus likely to have errors in some portion that doesn't run too often. And when you fix one place, you have to check many others to see whether it has the same problem. So factor it out into functions according to feature. A good start is to write a function for each line in your docstring, except for the the do-while statement. Then when you realize the biggest function is the "nextmove" one, factor that as well. Most of it is spent calculating 'surronding'. I also found it strange that each element of the grid is itself a list, with exactly one element (an integer 0 or 1) in it. Why not just make it an integer ? There are a lot of places which would then change, so probably you shouldn't do that till you've refactored things to simplify. > I'm trying to give it a number of options. it dimensions, the max > number of turns, initial set up, and boundary conditions. The dimensions > and turns were pretty easy to include. The boundary conditions more > difficult, and now I'm getting stuck on the initial set up options. I can > set it up randomly but Im having problems implementing a checker board > pattern. > > > > #while not(initial=='r' or initial=='c' or initial=='g' or initial=='e'): > # initial=input(' > SPACE=[] > for i in range(X): > SPACE.append([]) > for j in range(Y): > SPACE[i].append([0]) > > print(SPACE) > > #initial set up-random, checker board, glider, eternal. > initial=0 > while not(initial =='r' or initial =='c' or initial=='g' or initial=='e'): > initial=input('Chose inital setup: press "r" for random,"c" for > checker, "g" for glider,"e"=eternal') > > > if initial=='c': > idex=0 > for i in range(X): > jdex=0 > for j in range(Y): > if (idex+jdex)%2==0: > SPACE[idex][jdex]=[0,] > jdex+=1 > else: > SPACE[idex][jdex]=[1,] > jdex+=1 > idex+=1 Here you have set each element of the grid to be a list containing a tuple containing an int. To be consistent with the rest of the code as it currently is, you should use SPACE[idex][jdex] = [0] or if/when you take my earlier suggestion to make it just an int, SPACE[idex][jdex] = 0 Note, though, that you don't want to make too many changes to the logic at the same time. > > turn=0 > > > while turn References: Message-ID: <4F839BED.4040704@gmail.com> On 4/9/2012 2:26 AM, leo degon wrote: > Hello all, Im trying to learn python and programming in my free time, > and I'm trying to do a little personal project to trying and gain some > skills. Im trying to do version of John conways game of life. I have a > working version of the game. Written for 3.2.2 on a mac to be accessed > through terminal. In addition to Dave's comments I add: > I'm trying to give it a number of options. it dimensions, the max > number of turns, initial set up, and boundary conditions. Please explain "boundary conditions" > The dimensions and turns were pretty easy to include. > The boundary conditions more difficult, and now I'm getting stuck on > the initial set up options. I can set it up randomly but Im having > problems implementing a checker board pattern. It really helps when you explain the problem. What does not work as expected? > '''displays: the text of the game of life for a set number of X x Y > for a set of R turns. > > [-][-][-][-][-] > [-][-][-][-][-] > [-][-][-][-][-] > [-][-][-][-][-] > [-][-][-][-][-] I suggest you simplify the display by using - or x e.g.: -------- -------- ---xx--- ---xxx-- ----xx-- -------- > Get X,Y,T, Initial value > > Create a data space X x Y > Assign initial value > print initial value and the text' initial value' > > do while turns check data space > create new data space according to rules and old data space. > replace dataspace > print data space. > > print end. ''' > > import random > > > X,Y,T=0,0,0 > while not 4 X=int(input('How many rows? enter a integer between 5 and 101: ')) > while not 4 Y=int(input('How many columns? enter a integer between 5 and 101: ')) > while not 4 T=int(input('How many turns? enter a integer between 5 and 101: ')) > Good place for a function: (untested). Also note it's common practice to use names starting with lower case for variables. Note how we validate input to ensure it is integer. def getNum(prompt, lower, upper): while True: n = input(prompt + " enter a integer between %s and %s" % (lower, upper)) if n.isdigit(): n = int(n) if lower <= n <= upper: return n x = getNum("How many rows?", 5, 101) y = getNum("How many rows?", 5, 101) t = getNum("How many rows?", 5, 101) entry=0 > while not (entry=='b' or entry=='l' or entry=='d'): can be simplified to while entry not in ('b', 'l', 'd') > entry=input('Press "b" for bound dimensions, press "l" for live > boundry, or press "d" for dead boundry: ') > > > #while not(initial=='r' or initial=='c' or initial=='g' or initial=='e'): > # initial=input(' > SPACE=[] Note (again) it's common practice to use names starting with lower case for variables. These nested loops > for i in range(X): > SPACE.append([]) > for j in range(Y): > SPACE[i].append([0]) > can be replaced with: space = [0]*y]*x Assuming you decide to have each cell contain either 1 or 0. You might also consider giving space an extra row at the top and one at the bottom, ditto for extra columns. That will make calculating the neighbor count a lot easier, at the cost of maintaining the extra rows/columns. for r in range(1,x+1): for c in range1,(y+1): surrounding = sum([sum(space[r+z][c-1:c+2]) for z in(-1,0,1)]) .... OK enough for now - there's more but I'm out of time/energy right now. -- Bob Gailer 919-636-4239 Chapel Hill NC From d at davea.name Tue Apr 10 04:56:58 2012 From: d at davea.name (Dave Angel) Date: Mon, 09 Apr 2012 22:56:58 -0400 Subject: [Tutor] Game of python, help please. In-Reply-To: <4F839BED.4040704@gmail.com> References: <4F839BED.4040704@gmail.com> Message-ID: <4F83A17A.5020805@davea.name> On 04/09/2012 10:33 PM, bob gailer wrote: > On 4/9/2012 2:26 AM, leo degon wrote: >> Hello all, Im trying to learn python and programming in my free time, >> and I'm trying to do a little personal project to trying and gain >> some skills. Im trying to do version of John conways game of life. I >> have a working version of the game. Written for 3.2.2 on a mac to be >> accessed through terminal. > > These nested loops >> for i in range(X): >> SPACE.append([]) >> for j in range(Y): >> SPACE[i].append([0]) >> > can be replaced with: > > space = [0]*y]*x > not counting the typo, that's the trap I was warning about. If he does NOT replace the individual cells with zeroes and ones, this is wrong. You pointed that out. But it's also wrong for the rows, as you only have one row here, duplicated x times. -- DaveA From roger.bakkestuen at vegvesen.no Tue Apr 10 11:13:20 2012 From: roger.bakkestuen at vegvesen.no (Bakkestuen Roger) Date: Tue, 10 Apr 2012 11:13:20 +0200 Subject: [Tutor] ADO with python 2.6 without additional installs Message-ID: Hi I'm struggling with finding a way to access and query an MSAccess base in an organisation with a very standardised environment. Python 2.6 is available and Office 2010. Is there a way to access and query trough for instance ADO without having to install the Win32 package? Any suggestions or even sample code? Best regards Roger Bakkestuen Norwegian Public Roads Administration Eastern Region - Geodata Post adress: Statens vegvesen Region ?st, Postboks 1010, 2605 LILLEHAMMER Office adress: Industrigaten 17, LILLEHAMMER Phone: +47 61271236 Mobile: +47 94833636 e-mail: roger.bakkestuen at vegvesen.no www.vegvesen.no e-mail: firmapost-ost at vegvesen.no -------------- next part -------------- An HTML attachment was scrubbed... URL: From cwitts at compuscan.co.za Tue Apr 10 11:23:34 2012 From: cwitts at compuscan.co.za (Christian Witts) Date: Tue, 10 Apr 2012 11:23:34 +0200 Subject: [Tutor] ADO with python 2.6 without additional installs In-Reply-To: References: Message-ID: <4F83FC16.90007@compuscan.co.za> On 2012/04/10 11:13 AM, Bakkestuen Roger wrote: > > Hi > > I?m struggling with finding a way to access and query an MSAccess base > in an organisation with a very standardised environment. > > Python 2.6 is available and Office 2010. > > Is there a way to access and query trough for instance ADO without > having to install the Win32 package? > > Any suggestions or even sample code? > > *Best regards* > > *Roger Bakkestuen* > > ** > > Norwegian Public Roads Administration > > Eastern Region ? Geodata > > *Post adress:*Statens vegvesen Region ?st, Postboks 1010, 2605 LILLEHAMMER > > *Office adress*: Industrigaten 17, LILLEHAMMER > *Phone:* +47 61271236 *Mobile:* +47 94833636 *e-mail:* > roger.bakkestuen at vegvesen.no > www.vegvesen.no *e-mail:* > firmapost-ost at vegvesen.no > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor You can give PyODBC [1] a try as it does support MS Access [2]. [1] http://code.google.com/p/pyodbc/ [2] http://code.google.com/p/pyodbc/wiki/ConnectionStrings -- Christian Witts Python Developer // -------------- next part -------------- An HTML attachment was scrubbed... URL: From cwitts at compuscan.co.za Tue Apr 10 15:25:47 2012 From: cwitts at compuscan.co.za (Christian Witts) Date: Tue, 10 Apr 2012 15:25:47 +0200 Subject: [Tutor] ADO with python 2.6 without additional installs In-Reply-To: References: <4F83FC16.90007@compuscan.co.za> Message-ID: <4F8434DB.7080004@compuscan.co.za> On 2012/04/10 03:07 PM, Bakkestuen Roger wrote: > > This requires install of pyodbc. > > I was looking for modules in std python 2.6 or higher. > > Med hilsen > Roger Bakkestuen > > *Telefon:* +47 61271236 *Mobil:* +47 94833636 *e-post:* > roger.bakkestuen at vegvesen.no > > --------------------------------------------------------------------------------------------------------------- > > *Fra:*Christian Witts [mailto:cwitts at compuscan.co.za] > *Sendt:* 10. april 2012 11:24 > *Til:* Bakkestuen Roger > *Kopi:* tutor at python.org > *Emne:* Re: [Tutor] ADO with python 2.6 without additional installs > > On 2012/04/10 11:13 AM, Bakkestuen Roger wrote: > > Hi > > I?m struggling with finding a way to access and query an MSAccess base > in an organisation with a very standardised environment. > > Python 2.6 is available and Office 2010. > > Is there a way to access and query trough for instance ADO without > having to install the Win32 package? > > Any suggestions or even sample code? > > *Best regards* > > *Roger Bakkestuen* > > ** > > Norwegian Public Roads Administration > > Eastern Region ? Geodata > > *Post adress:*Statens vegvesen Region ?st, Postboks 1010, 2605 LILLEHAMMER > > *Office adress*: Industrigaten 17, LILLEHAMMER > *Phone:* +47 61271236 *Mobile:* +47 94833636 *e-mail:* > roger.bakkestuen at vegvesen.no > www.vegvesen.no *e-mail:* > firmapost-ost at vegvesen.no > > > > > _______________________________________________ > Tutor maillist -Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > You can give PyODBC [1] a try as it does support MS Access [2]. > > [1] http://code.google.com/p/pyodbc/ > [2] http://code.google.com/p/pyodbc/wiki/ConnectionStrings > > -- > > Christian Witts > Python Developer > Unfortunately the only DB Access that's built into Python is SQLite, for all other databases you'll need to install 3rd party packages. -- Christian Witts Python Developer // -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Tue Apr 10 16:44:08 2012 From: bgailer at gmail.com (bob gailer) Date: Tue, 10 Apr 2012 10:44:08 -0400 Subject: [Tutor] Game of python, help please. In-Reply-To: <4F83A17A.5020805@davea.name> References: <4F839BED.4040704@gmail.com> <4F83A17A.5020805@davea.name> Message-ID: <4F844738.1020304@gmail.com> On 4/9/2012 10:56 PM, Dave Angel wrote: > On 04/09/2012 10:33 PM, bob gailer wrote: >> On 4/9/2012 2:26 AM, leo degon wrote: >>> Hello all, Im trying to learn python and programming in my free time, >>> and I'm trying to do a little personal project to trying and gain >>> some skills. Im trying to do version of John conways game of life. I >>> have a working version of the game. Written for 3.2.2 on a mac to be >>> accessed through terminal. >> >> These nested loops >>> for i in range(X): >>> SPACE.append([]) >>> for j in range(Y): >>> SPACE[i].append([0]) >>> >> can be replaced with: >> >> space = [0]*y]*x >> > not counting the typo, that's the trap I was warning about. If he does > NOT replace the individual cells with zeroes and ones, this is wrong. > You pointed that out. But it's also wrong for the rows, as you only > have one row here, duplicated x times. OOPS - what comes of trying to be creative while tired. Sorry and thanks for pointing out my error. > -- Bob Gailer 919-636-4239 Chapel Hill NC From bgailer at gmail.com Tue Apr 10 17:08:31 2012 From: bgailer at gmail.com (bob gailer) Date: Tue, 10 Apr 2012 11:08:31 -0400 Subject: [Tutor] ADO with python 2.6 without additional installs In-Reply-To: References: Message-ID: <4F844CEF.8050705@gmail.com> Please always reply-all so a copy goes to the list On 4/10/2012 5:13 AM, Bakkestuen Roger wrote: > > Hi > > I'm struggling with finding a way to access and query an MSAccess base > in an organisation with a very standardised environment. > I gather from your other comments this means no installing of 3rd party software. True? I presume that policy is to prevent malicious code from running. True? Please say more about your objectives. Can you export the Access data and operate on it outside the Access environment? -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From ilhs_hs at yahoo.com Tue Apr 10 17:22:22 2012 From: ilhs_hs at yahoo.com (Hs Hs) Date: Tue, 10 Apr 2012 08:22:22 -0700 (PDT) Subject: [Tutor] summing lists Message-ID: <1334071342.85795.YahooMailNeo@web111215.mail.gq1.yahoo.com> Hi: I have 4 lists: >>> a [40] >>> b [2] >>> c [23] >>> d [12] how is it possible to do add elements in list. I can do this using tupples, but I do not know how to append elements to tuple, thats the reason I am using list.? I want to find the value of a+c/a+b+c+d - which is 40+23/40+2+23+12.? Any help appreciated.? thanks Hs. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ilhs_hs at yahoo.com Tue Apr 10 17:28:03 2012 From: ilhs_hs at yahoo.com (Hs Hs) Date: Tue, 10 Apr 2012 08:28:03 -0700 (PDT) Subject: [Tutor] summing lists In-Reply-To: <1334071342.85795.YahooMailNeo@web111215.mail.gq1.yahoo.com> References: <1334071342.85795.YahooMailNeo@web111215.mail.gq1.yahoo.com> Message-ID: <1334071683.91083.YahooMailNeo@web111213.mail.gq1.yahoo.com> sorry I did this following, please advise if any better way exist: gc = lambda x,y: x[0]+y[0] atgc = lambda x,y,k,l: x[0]+y[0]+k[0]+l[0] >>> gc(a,b)/atgc(a,b,c,d) 0.54545454545454541 Hi: I have 4 lists: >>> a [40] >>> b [2] >>> c [23] >>> d [12] how is it possible to do add elements in list. I can do this using tupples, but I do not know how to append elements to tuple, thats the reason I am using list.? I want to find the value of a+c/a+b+c+d - which is 40+23/40+2+23+12.? Any help appreciated.? thanks Hs. -------------- next part -------------- An HTML attachment was scrubbed... URL: From eire1130 at gmail.com Tue Apr 10 17:32:03 2012 From: eire1130 at gmail.com (James Reynolds) Date: Tue, 10 Apr 2012 11:32:03 -0400 Subject: [Tutor] summing lists In-Reply-To: <1334071342.85795.YahooMailNeo@web111215.mail.gq1.yahoo.com> References: <1334071342.85795.YahooMailNeo@web111215.mail.gq1.yahoo.com> Message-ID: On Tue, Apr 10, 2012 at 11:22 AM, Hs Hs wrote: > Hi: > > I have 4 lists: > > >>> a > [40] > >>> b > [2] > >>> c > [23] > >>> d > [12] > > > how is it possible to do add elements in list. I can do this using > tupples, but I do not know how to append elements to tuple, thats the > reason I am using list. > > I want to find the value of a+c/a+b+c+d - which is 40+23/40+2+23+12. > > Any help appreciated. > > thanks > Hs. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > In python, the '+' operator when applied to lists will concatenate the lists together. So: >>> a = [1] >>> b = [2] >>> print a+b [1,2] the 'sum' function in python can be used on lists. >>> a = [1] >>> b = [2] >>> print sum(a+b) 3 -------------- next part -------------- An HTML attachment was scrubbed... URL: From evert.rol at gmail.com Tue Apr 10 17:37:37 2012 From: evert.rol at gmail.com (Evert Rol) Date: Tue, 10 Apr 2012 17:37:37 +0200 Subject: [Tutor] summing lists In-Reply-To: <1334071342.85795.YahooMailNeo@web111215.mail.gq1.yahoo.com> References: <1334071342.85795.YahooMailNeo@web111215.mail.gq1.yahoo.com> Message-ID: <8E75AC79-ABA0-4BE5-89AD-5233C7A94915@gmail.com> > I have 4 lists: > > >>> a > [40] > >>> b > [2] > >>> c > [23] > >>> d > [12] > Why are you using lists with a single element, instead of single integer variables? (thus, a=40, b=2, c=23, d=12.) > how is it possible to do add elements in list. sum() > I can do this using tupples, but I do not know how to append elements to tuple You can't. but you can make a a new tuple from two existing tuples: >>> (1, 2) + (3, 4) (1, 2, 3, 4) However, > , thats the reason I am using list. Lists have little to do with your problem below (the sums + division), and certainly not tuples. If possible, better to use plain variables. In this specific case, however, you can just add the lists together (which forms a new list), and then use sum(): >>> a+b [40, 2] >>> a+b+c+d [40, 2, 23, 12] >>> sum(a+b)/sum(a+b+c+d) 0 >>> # oops, I'm using Python 2, not Python 3 here >>> from __future__ import division >>> sum(a+b)/sum(a+b+c+d) 0.5454545454545454 You can also extend lists, which adds a list to an existing list: >>> a.extend(b) >>> a [40, 2] >>> a.extend(c) >>> a [40, 2, 23] etc. Evert > > I want to find the value of a+c/a+b+c+d - which is 40+23/40+2+23+12. > > Any help appreciated. > > thanks > Hs. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From d at davea.name Tue Apr 10 17:45:13 2012 From: d at davea.name (Dave Angel) Date: Tue, 10 Apr 2012 11:45:13 -0400 Subject: [Tutor] summing lists In-Reply-To: <1334071683.91083.YahooMailNeo@web111213.mail.gq1.yahoo.com> References: <1334071342.85795.YahooMailNeo@web111215.mail.gq1.yahoo.com> <1334071683.91083.YahooMailNeo@web111213.mail.gq1.yahoo.com> Message-ID: <4F845589.90900@davea.name> On 04/10/2012 11:28 AM, Hs Hs wrote: > sorry I did this following, please advise if any better way exist: > You top-posted, so we lose the context you were using. You never really say why you're using lists with exactly one element in them, but presuming that the real lists consist of something like a = [4, "Tom Jones"] b = [12, "Peter Rabbit", "March Hare"] I'll follow your convention of assuming only the zeroth element is relevant to your 'definition of add'. > gc = lambda x,y: x[0]+y[0] > > atgc = lambda x,y,k,l: x[0]+y[0]+k[0]+l[0] > > No point in using lambda for that purpose. Since you are not trying to make it anonymous, you could simply use def gc(x, y): return x[0] + y[0] for example. But the more interesting question is how to combine the two functions, and make one which can take a variable number of items. def gc(*many): return sum( [ x[0] for x in many ] ) -- DaveA From ilhs_hs at yahoo.com Tue Apr 10 17:43:50 2012 From: ilhs_hs at yahoo.com (Hs Hs) Date: Tue, 10 Apr 2012 08:43:50 -0700 (PDT) Subject: [Tutor] summing lists In-Reply-To: <8E75AC79-ABA0-4BE5-89AD-5233C7A94915@gmail.com> References: <1334071342.85795.YahooMailNeo@web111215.mail.gq1.yahoo.com> <8E75AC79-ABA0-4BE5-89AD-5233C7A94915@gmail.com> Message-ID: <1334072630.50874.YahooMailNeo@web111209.mail.gq1.yahoo.com> thanks all for quick reply. ?In my previous e-mail I send adding using lambda function. I now know that I am using too much functionality where simple ways to solve exist. That's python! thanks again.? Hs. ________________________________ From: Evert Rol To: Hs Hs Cc: "tutor at python.org" Sent: Tuesday, April 10, 2012 11:37 AM Subject: Re: [Tutor] summing lists > I have 4 lists: > > >>> a > [40] > >>> b > [2] > >>> c > [23] > >>> d > [12] > Why are you using lists with a single element, instead of single integer variables? (thus, a=40, b=2, c=23, d=12.) > how is it possible to do add elements in list. sum() > I can do this using tupples, but I do not know how to append elements to tuple You can't. but you can make a a new tuple from two existing tuples: >>> (1, 2) + (3, 4) (1, 2, 3, 4) However, > , thats the reason I am using list. Lists have little to do with your problem below (the sums + division), and certainly not tuples. If possible, better to use plain variables. In this specific case, however, you can just add the lists together (which forms a new list), and then use sum(): >>> a+b [40, 2] >>> a+b+c+d [40, 2, 23, 12] >>> sum(a+b)/sum(a+b+c+d) 0 >>> # oops, I'm using Python 2, not Python 3 here >>> from __future__ import division >>> sum(a+b)/sum(a+b+c+d) 0.5454545454545454 You can also extend lists, which adds a list to an existing list: >>> a.extend(b) >>> a [40, 2] >>> a.extend(c) >>> a [40, 2, 23] etc. ? Evert > > I want to find the value of a+c/a+b+c+d - which is 40+23/40+2+23+12. > > Any help appreciated. > > thanks > Hs. > _______________________________________________ > Tutor maillist? -? Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Apr 10 18:29:33 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 10 Apr 2012 17:29:33 +0100 Subject: [Tutor] ADO with python 2.6 without additional installs In-Reply-To: References: Message-ID: On 10/04/12 10:13, Bakkestuen Roger wrote: > Is there a way to access and query trough for instance ADO without > having to install the Win32 package? Yes, you can use ctypes to access the Microsoft DLL functions and Win32 API directly. But thats going to be non trivial and probably painful! There is a ctypes mailing list/forum who may have people who can help. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From flitrfli at gmail.com Tue Apr 10 22:25:33 2012 From: flitrfli at gmail.com (Laura Scearce) Date: Tue, 10 Apr 2012 15:25:33 -0500 Subject: [Tutor] Biopython Message-ID: Hello, I am using Linux version 2.6 and python version 2.6.6 (gcc version 4.4.5). I have a list of protein names and am trying to get their sequences. I thought I would download Biopython, and am having troubles. I first downloaded and installed easyinstall from http://pypi.python.org/pypi/setuptools I followed the instructions and it seemed to work (see below error messages). This is the error I get when I try to install biopython: root at debbie-VirtualBox:/usr/local/bin# easy_install biopython Searching for biopython Reading http://pypi.python.org/simple/biopython/ Reading http://www.biopython.org/ Reading http://biopython.org/DIST/ Best match: biopython 1.59 Downloading http://biopython.org/DIST/biopython-1.59.zip Processing biopython-1.59.zip Running biopython-1.59/setup.py -q bdist_egg --dist-dir /tmp/easy_install-qMfJsF/biopython-1.59/egg-dist-tmp-W4L1YX warning: no previously-included files found matching 'Tests/Graphics/*' warning: no previously-included files matching '.cvsignore' found under directory '*' warning: no previously-included files matching '*.pyc' found under directory '*' Bio/cpairwise2module.c:12: fatal error: Python.h: No such file or directory compilation terminated. error: Setup script exited with error: command 'gcc' failed with exit status 1 *I also tried it in the directory Downloads, because this is where the easyinstall was downloaded to. Same message. Then I tried downloading Biopython from http://pypi.python.org/pypi/biopython I downloaded biopython-1.59.tar.gz. and extracted it to the folder BLAST-SW in my Documents folder. Here is what I tried: debbie at debbie-VirtualBox:~/Documents/BLAST-SW$ sh biopython-1.59.tar.gz sh: Can't open biopython-1.59.tar.gz debbie at debbie-VirtualBox:~$ sh biopython-1.59.tar.gz sh: Can't open biopython-1.59.tar.gz debbie at debbie-VirtualBox:~/Documents/BLAST-SW$ sh biopython-1.59 *This had no error message, but I think that Biopython is not installed because: >>> import Bio Traceback (most recent call last): File "", line 1, in ImportError: No module named Bio The end goal is to use ncbi Eutils to get protein sequences, so if anyone has experience with this please let me know. Thanks! Laura Scearce -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Tue Apr 10 22:56:53 2012 From: emile at fenx.com (Emile van Sebille) Date: Tue, 10 Apr 2012 13:56:53 -0700 Subject: [Tutor] Biopython In-Reply-To: References: Message-ID: On 4/10/2012 1:25 PM Laura Scearce said... > Hello, > I am using Linux version 2.6 and python version 2.6.6 (gcc version 4.4.5). > I have a list of protein names and am trying to get their sequences. I > thought I would download Biopython, and am having troubles. Your best source for answers pertaining to third party packages if the third party itself. Try http://biopython.org/wiki/Mailing_lists -- they'll get you going faster than we will... unless of course someone here has sufficient experience with that package. Emile From wprins at gmail.com Tue Apr 10 23:01:01 2012 From: wprins at gmail.com (Walter Prins) Date: Tue, 10 Apr 2012 23:01:01 +0200 Subject: [Tutor] Biopython In-Reply-To: References: Message-ID: Hi Laura, On 10 April 2012 22:25, Laura Scearce wrote: > I am using Linux version 2.6 and python version 2.6.6 (gcc version 4.4.5). > What distribution of Linux? (Ubuntu, Debian, Centos or something else?) I followed the instructions and it seemed to work (see below error > messages). > > [snip...] > compilation terminated. > error: Setup script exited with error: command 'gcc' failed with exit > status 1 > That means gcc is likely not installed. GCC is the GNU C compiler. On Linux, Python modules written in C needs GCC to be able to install. I imagine BioPython is written in C, which would explain why it wants GCC during installation. On Ubuntu/Debian, you can fix the lack of GCC by using the following command: sudo apt-get install build-essential This will install the "build-essential" package which includes GCC and a bunch of other development tools. (If you're not using Debian or Ubuntu or a distribution based on Debian the above command won't work.) > *I also tried it in the directory Downloads, because this is where the > easyinstall was downloaded to. Same message. > After installing "easy_install" into your Python environment, the originally downloaded file is redundant/irrelevant to the functioning of easy_install, so the folder you're in doesn't actually matter. Which is why you get the same message. :) > > Then I tried downloading Biopython from > http://pypi.python.org/pypi/biopython > I downloaded biopython-1.59.tar.gz. > and extracted it to the folder BLAST-SW in my Documents folder. > > Here is what I tried: > debbie at debbie-VirtualBox:~/Documents/BLAST-SW$ sh biopython-1.59.tar.gz > sh: Can't open biopython-1.59.tar.gz > debbie at debbie-VirtualBox:~$ sh biopython-1.59.tar.gz > sh: Can't open biopython-1.59.tar.gz > debbie at debbie-VirtualBox:~/Documents/BLAST-SW$ sh biopython-1.59 > *This had no error message, but I think that Biopython is not installed > because: > >>> import Bio > Traceback (most recent call last): > File "", line 1, in > ImportError: No module named Bio > A .tar.gz file is not a shellscript file or bundle. It is a type of archive file, and to extract it you need to use the "tar" command or a GUI tool that can read tar.gz files. (I'm a tad puzzled as you seem to understand this file needs to be extracted, yet the commands you issue implies you seem to think you can run the file as-is?) Normally you'd use a command like this: tar -zxvf biopython-1.59.tar.gz ... which will extract the the biopython-1.59.tar.gz file into the current folder. In case the files in the archive are not in a subfolder it's therefore a bit safer to create your own targer folder first, then extract from within this new folder, e.g. something like: mkdir biopython cd biopython tar -zxvf ../biopython-1.59.tar.gz Finally having briefly scanned the biopython download page, I want to point out that there are Biopython packages available for Ubuntu/Debian systems, so if you're using one of these Linux distributions you should preferentially use Synaptic (or another Debian package tool like apt-get or aptitude) to install BioPython as this will be a lot less grief. Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Apr 11 00:20:10 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 10 Apr 2012 23:20:10 +0100 Subject: [Tutor] Biopython In-Reply-To: References: Message-ID: On 10/04/12 21:25, Laura Scearce wrote: > Hello, > I am using Linux version 2.6 and python version 2.6.6 (gcc version 4.4.5). > I have a list of protein names and am trying to get their sequences. OK, That's not unusual and there is a forum somewhere for Python users doing bio type work. However, it helps if you tell us what distribution of Linux since their installers etc all work slightly differently (or more specifically there are three or four different installer packages that work differently across the dozens of Linux distros.) > thought I would download Biopython, and am having troubles. This is a list for people learning python. There may be people on the list that also know biopython but I wouldn't count on it. If you can find a biopython forum you are more likely to get useful help. > Bio/cpairwise2module.c:12: fatal error: Python.h: No such file or directory > compilation terminated. > error: Setup script exited with error: command 'gcc' failed with exit > status 1 This means its trying to build from source. Does your PC have a working development environment set up? Specifically can you build C programs using make? If you don;t, or don;t know, you are probably out of your depth and should try to find a pre-built package for your system. > Here is what I tried: > debbie at debbie-VirtualBox:~/Documents/BLAST-SW$ sh biopython-1.59.tar.gz > sh: Can't open biopython-1.59.tar.gz OK, the fact that you are trying to run sh on a tar.gz file tells me you are also a newbie to Linux as well as biopython. You need to find the tool that your distro uses to open/install "gunzip compressed tape archives" - which is what a tar.gz file is... You can do it manually but thats likely to lead to even more problems if you don't really understand what you are doing. You might be lucky and the distro has already set up the associations, what happens if you just run biopython-1.59.tar.gz? That might start the right tool automatically. Although what the tool will do depends on what is inside the archive. > The end goal is to use ncbi Eutils to get protein sequences, so if > anyone has experience with this please let me know. You really are asking on the wrong forum. First have you read this? I found it at the top ofd my first google search on biopython... http://biopython.org/wiki/Biopython There is a download and installation guide. Also a page full of bio help sources: http://biopython.org/wiki/Mailing_lists In programming it always helps to read the manual first, it is invariably faster than guessing. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From questions.anon at gmail.com Wed Apr 11 06:09:16 2012 From: questions.anon at gmail.com (questions anon) Date: Wed, 11 Apr 2012 14:09:16 +1000 Subject: [Tutor] group txt files by month In-Reply-To: References: Message-ID: Thank you for this response it was a tremedous help. It still took me awhile to work it all out and thought I would post what worked for me. Thanks again GLOBTEMPLATE = r"e:/rainfall-{year}/r{year}{month:02}??.txt" def accumulate_month(year, month): files = glob.glob(GLOBTEMPLATE.format(year=year, month=month)) monthlyrain=[] for ifile in files: f=np.genfromtxt(ifile,skip_header=6) monthlyrain.append(f) print "year-month: ",year,"-",month, ", maximum: ", np.max(monthlyrain), "minimum: ", np.min(monthlyrain), "mean: ", np.mean(monthlyrain) stop_month = datetime(2011, 12, 31) month = datetime(2011, 01, 01) while month < stop_month: accumulate_month(month.year, month.month) month += timedelta(days=32) month = month.replace(day=01) On Thu, Apr 5, 2012 at 4:57 PM, Peter Otten <__peter__ at web.de> wrote: > questions anon wrote: > > > I have been able to write up what I want to do (using glob) but I am not > > sure how to loop it or simplify it to make the script more efficient. > > I am currently: > > -grouping the same months in a year using glob > > -opening the files in a group and combining the data using a list > > -finding max, min etc for the list and printing it > > > > I need to do this for many years and therefore many months so really need > > a way to make this more efficient. > > Any feedback will be greatly appreciated > > > > MainFolder=r"E:/rainfall-2011/" > > OutputFolder=r"E:/test_out/" > > r201101=glob.glob(MainFolder+"r201101??.txt") > > r201102=glob.glob(MainFolder+"r201102??.txt") > > r201103=glob.glob(MainFolder+"r201103??.txt") > > > > rain201101=[] > > rain201102=[] > > rain201103=[] > > monthlyrainfall=[] > > > > for ifile in r201101: > > f=np.genfromtxt(ifile, skip_header=6) > > rain201101.append(f) > > > > for ifile in r201102: > > f=np.genfromtxt(ifile, skip_header=6) > > rain201102.append(f) > > > > for ifile in r201103: > > f=np.genfromtxt(ifile, skip_header=6) > > rain201103.append(f) > > > > print "jan", np.max(rain201101), np.min(rain201101), np.mean(rain201101), > > np.median(rain201101), np.std(rain201101) > > print "feb", np.max(rain201102), np.min(rain201102), np.mean(rain201102), > > np.median(rain201102), np.std(rain201102) > > print "mar", np.max(rain201103), np.min(rain201103), np.mean(rain201103), > > np.median(rain201103), np.std(rain201103) > > Strip the code down to one month > > > r201103=glob.glob(MainFolder+"r201103??.txt") > > rain201101=[] > > for ifile in r201101: > > f=np.genfromtxt(ifile, skip_header=6) > > rain201101.append(f) > > > then turn it into a function, roughly > > GLOBTEMPLATE = "e:/rainfall-{year}/r{year}{month:02}??.txt" > def accumulate_month(year, month): > files = glob.glob(GLOBTEMPLATE.format(year=year, month=month)) > # read files, caculate and write stats > > and finally put it into a loop: > > from datetime import date, timedelta > stop_month = date(2012, 4, 1) > month = datetime(2011, 1, 1) > while month < stop_month: > accumulate_month(month.year, month.month) > month += timedelta(days=32) > month = month.replace(day=1) > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From suryak at live.com Wed Apr 11 12:02:28 2012 From: suryak at live.com (Surya K) Date: Wed, 11 Apr 2012 15:32:28 +0530 Subject: [Tutor] how to build a multiplayer game? Message-ID: I have written the basic part of the game. Now I want to make it a multiplayer one. (Its not a web app, a OS application) So, I just wanted to know how do it. Which topics I should refer? Network Programming or Web Programming or Internet Client Programming. (There were the topics mentioned in Core Python Programming book). Can anyone tell me how do we achieve such a application (I mean without having a web server). I am not really ready to setup a Apache HTTP server..... and all. -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Wed Apr 11 12:42:40 2012 From: d at davea.name (Dave Angel) Date: Wed, 11 Apr 2012 06:42:40 -0400 Subject: [Tutor] how to build a multiplayer game? In-Reply-To: References: Message-ID: <4F856020.6030103@davea.name> On 04/11/2012 06:02 AM, Surya K wrote: > > I have written the basic part of the game. Now I want to make it a multiplayer one. (Its not a web app, a OS application) > So, I just wanted to know how do it. > Which topics I should refer? Network Programming or Web Programming or Internet Client Programming. > (There were the topics mentioned in Core Python Programming book). > > Can anyone tell me how do we achieve such a application (I mean without having a web server). I am not really ready to setup a Apache HTTP server..... and all. > You want to make two instances of the app talk to each other. If they're on the same machine (unlikely for a real game, but might be used for testing), or if they're on the same local network, then the features you need are available in the stdlib. If you're going out on the web, you need a host out there which will cooperate with the two apps (players). Same local network: Generally when both machines share a router or a wifi connection, and would get to the web through the same ISP connection. If you figure out what their IP addresses are, they can talk directly, using sockets. Out on the web: You need a server that's on the web that each machine can reach. It doesn't have to be your own, and I can't recommend any particular one, but I'd bet google appserver would work. For that matter, email would work, if you don't mind a pretty long delay between turns. For any more specific advice, somebody else had better pop in. -- DaveA From suryak at live.com Wed Apr 11 15:30:21 2012 From: suryak at live.com (Surya K) Date: Wed, 11 Apr 2012 19:00:21 +0530 Subject: [Tutor] how to build a multiplayer game? In-Reply-To: <4F856020.6030103@davea.name> References: , <4F856020.6030103@davea.name> Message-ID: > Date: Wed, 11 Apr 2012 06:42:40 -0400 > From: d at davea.name > To: suryak at live.com > CC: tutor at python.org > Subject: Re: [Tutor] how to build a multiplayer game? > > On 04/11/2012 06:02 AM, Surya K wrote: > > > > I have written the basic part of the game. Now I want to make it a multiplayer one. (Its not a web app, a OS application) > > So, I just wanted to know how do it. > > Which topics I should refer? Network Programming or Web Programming or Internet Client Programming. > > (There were the topics mentioned in Core Python Programming book). > > > > Can anyone tell me how do we achieve such a application (I mean without having a web server). I am not really ready to setup a Apache HTTP server..... and all. > > > > You want to make two instances of the app talk to each other. If > they're on the same machine (unlikely for a real game, but might be used > for testing), or if they're on the same local network, then the features > you need are available in the stdlib. If you're going out on the web, > you need a host out there which will cooperate with the two apps (players). > > Same local network: Generally when both machines share a router or a > wifi connection, and would get to the web through the same ISP > connection. If you figure out what their IP addresses are, they can > talk directly, using sockets. > Well, can we make the program so that user enters his IP, DNS addresses before starting? Don't you think DNS is required as IP addr may be same for some people in this world.. after all, we only have limited number of combinations. (xx.xx.xx.xx .. ) * I even got a wild idea, can't we use a IRC channel, create a group and we make sure that each user of the game will be a member of the group??approx, how much delay would be there?? > Out on the web: You need a server that's on the web that each machine > can reach. It doesn't have to be your own, and I can't recommend any > particular one, but I'd bet google appserver would work. For that > matter, email would work, if you don't mind a pretty long delay between > turns. > Hmm, google app engine is a nice option but thing is I don't know how to use it. > For any more specific advice, somebody else had better pop in. > > -- > > DaveA > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From barthpi at gmail.com Wed Apr 11 15:49:10 2012 From: barthpi at gmail.com (Pierre Barthelemy) Date: Wed, 11 Apr 2012 15:49:10 +0200 Subject: [Tutor] python connect() function Message-ID: Hello, I have a question about event handling and the use of the connect function. I have a data object, that contains a series of signals, one being "new_data_point" . When i want to plot the data, i also connect the "new_data_point" event to the function "analysis_client.update_plot". I therefore run the line: data.connect('new_data_point', analysis_client.update_plot) In this case, everytime the data object is updated, i also update the plot. I would like to adapt this code to allow to have several plots, connected to several data objects. I would therefore need to specify, when i connect the "update_plot" function, which plots needs to be updated. Is it possible to specify arguments to be used by the connected function when the event occurs ? For instance, is there a way to write something like: data.connect('new_data_point', analysis_client.update_plot(specific_plot_instance)) So that when the event occurs, the corresponding plot (and only this one) is updated ? Pierre -------------- next part -------------- An HTML attachment was scrubbed... URL: From emailkgnow at gmail.com Wed Apr 11 15:50:10 2012 From: emailkgnow at gmail.com (Khalid Al-Ghamdi) Date: Wed, 11 Apr 2012 16:50:10 +0300 Subject: [Tutor] need help with a script.. Message-ID: Hi All, I'm using python 3.2 on a windows xp. I wrote the below script and ran it with the hope of returning a list of proctors (list_proc), but when it runs it doesn't call the function convert_proctors() as intended. On the other hand, when i import the module from the IDLE prompt and call the convert_proctors() function, the function returns the desired list. Why is this so? Thanks 1. import csv 2. 3. proctor_file=r'c:\Python32\Khalid Stuff\Testing_Scheduler\p roctors.csv' 4. 5. 6. def convert_proctors(): 7. proctor_csv_reader = csv.reader(open(proctor_file)) 8. proctor_list=list(proctor_csv_reader) 9. list_proc=[] 10. for row in range(len(proctor_list)): 11. list_proc.append(proctor_list[row][0]) 12. return (list_proc) 13. 14. 15. convert_proctors() -------------- next part -------------- An HTML attachment was scrubbed... URL: From malaclypse2 at gmail.com Wed Apr 11 15:56:04 2012 From: malaclypse2 at gmail.com (Jerry Hill) Date: Wed, 11 Apr 2012 09:56:04 -0400 Subject: [Tutor] how to build a multiplayer game? In-Reply-To: References: <4F856020.6030103@davea.name> Message-ID: On Wed, Apr 11, 2012 at 9:30 AM, Surya K wrote: > Well, can we make the program so that user enters his IP, DNS addresses > before starting? You could, sure. That's fine for testing purposes, but most people don't know their own IP addresses. Many people don't have a DNS entry for their home PC. Also, what about NAT? > Don't you think DNS is required as IP addr may be same for some people in > this world.. after all, we only have limited number of combinations. > (xx.xx.xx.xx .. ) Again, not every computer has a DNS address. If you are going to ask a user to hand enter their IP address, it would make sense to accept either a numeric IP address, or a DNS name. > * I even got a wild idea, can't we use a IRC channel, create a group and we > make sure that each user of the game will be a member of the group?? Sure, but now you have to write (or embed) an IRC client. Do you need to worry about someone joining your channel that isn't using your game client? Does that have potential security implications? > approx, how much delay would be there?? That depends on the delay from each client to the IRC server. > Hmm, google app engine is a nice option but thing is I don't know how to use > it. You're going to have to learn quite a bit about networking and probably client / server architecture to write a networked game. -- Jerry From malaclypse2 at gmail.com Wed Apr 11 15:59:56 2012 From: malaclypse2 at gmail.com (Jerry Hill) Date: Wed, 11 Apr 2012 09:59:56 -0400 Subject: [Tutor] need help with a script.. In-Reply-To: References: Message-ID: On Wed, Apr 11, 2012 at 9:50 AM, Khalid Al-Ghamdi wrote: > Hi All, > > I'm using python 3.2 on a windows xp. > > I wrote the below script and ran it with the hope of returning a list of > proctors (list_proc), but when it runs it ?doesn't call the function > convert_proctors() as intended. On the other hand, when i import the module > from the IDLE prompt and call the convert_proctors() function, the function > returns the desired list. > > Why is this so? When you run that code as a script, it does call your convert_proctors() function. But since all you do is create a list, and you never save it to disk, or print it to the screen, or even assign it to a variable, the result is just thrown away. Try changing the last line to: print(convert_proctors()) and you'll see the results you were expecting. -- Jerry From cwitts at compuscan.co.za Wed Apr 11 16:00:50 2012 From: cwitts at compuscan.co.za (Christian Witts) Date: Wed, 11 Apr 2012 16:00:50 +0200 Subject: [Tutor] need help with a script.. In-Reply-To: References: Message-ID: <4F858E92.5010801@compuscan.co.za> On 2012/04/11 03:50 PM, Khalid Al-Ghamdi wrote: > Hi All, > > I'm using python 3.2 on a windows xp. > > I wrote the below script and ran it with the hope of returning a list > of proctors (list_proc), but when it runs it doesn't call the > function convert_proctors() as intended. On the other hand, when i > import the module from the IDLE prompt and call the convert_proctors() > function, the function returns the desired list. > > Why is this so? > > Thanks > > 1. > import csv > 2. > 3. > proctor_file=r'c:\Python32\Khalid > Stuff\Testing_Scheduler\proctors.csv' > 4. > 5. > 6. > def convert_proctors(): > 7. > proctor_csv_reader = csv.reader(open(proctor_file)) > 8. > proctor_list=list(proctor_csv_reader) > 9. > list_proc=[] >10. > for row in range(len(proctor_list)): >11. > list_proc.append(proctor_list[row][0]) >12. > return (list_proc) >13. >14. >15. > convert_proctors() > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor convert_proctors() will get called when you run the application from say the command line, but because there's no explicit printing of the resulting list it will never get displayed to your console. Whereas when you run it from IDLE it will implicitly print the return value of a function if you do not "save" the data to a variable. -- Christian Witts Python Developer // -------------- next part -------------- An HTML attachment was scrubbed... URL: From emailkgnow at gmail.com Wed Apr 11 16:18:42 2012 From: emailkgnow at gmail.com (Khalid Al-Ghamdi) Date: Wed, 11 Apr 2012 17:18:42 +0300 Subject: [Tutor] need help with a script.. In-Reply-To: References: Message-ID: got it.... thanks a lot On Wed, Apr 11, 2012 at 4:59 PM, Jerry Hill wrote: > On Wed, Apr 11, 2012 at 9:50 AM, Khalid Al-Ghamdi > wrote: > > Hi All, > > > > I'm using python 3.2 on a windows xp. > > > > I wrote the below script and ran it with the hope of returning a list of > > proctors (list_proc), but when it runs it doesn't call the function > > convert_proctors() as intended. On the other hand, when i import the > module > > from the IDLE prompt and call the convert_proctors() function, the > function > > returns the desired list. > > > > Why is this so? > > When you run that code as a script, it does call your > convert_proctors() function. But since all you do is create a list, > and you never save it to disk, or print it to the screen, or even > assign it to a variable, the result is just thrown away. Try changing > the last line to: > > print(convert_proctors()) > > and you'll see the results you were expecting. > > -- > Jerry > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Wed Apr 11 17:10:18 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 11 Apr 2012 16:10:18 +0100 Subject: [Tutor] need help with a script.. In-Reply-To: References: Message-ID: On 11/04/2012 14:50, Khalid Al-Ghamdi wrote: > Hi All, > > I'm using python 3.2 on a windows xp. > > I wrote the below script and ran it with the hope of returning a list of > proctors (list_proc), but when it runs it doesn't call the function > convert_proctors() as intended. On the other hand, when i import the module > from the IDLE prompt and call the convert_proctors() function, the function > returns the desired list. > > Why is this so? > > Thanks > > > 1. import csv > 2. > 3. proctor_file=r'c:\Python32\Khalid Stuff\Testing_Scheduler\p > roctors.csv' > 4. > 5. > 6. def convert_proctors(): > 7. proctor_csv_reader = csv.reader(open(proctor_file)) > 8. proctor_list=list(proctor_csv_reader) > 9. list_proc=[] > 10. for row in range(len(proctor_list)): > 11. list_proc.append(proctor_list[row][0]) > 12. return (list_proc) > 13. > 14. > 15. convert_proctors() > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Your main query has already been answered, but I'd like to point out that your function could be written something like this. def convert_proctors(): list_proc = [] for row in csv.reader(open(proctor_file)): list_proc.append(row[0]) return list_proc -- Cheers. Mark Lawrence. From cfuller084 at thinkingplanet.net Wed Apr 11 17:34:47 2012 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Wed, 11 Apr 2012 10:34:47 -0500 Subject: [Tutor] how to build a multiplayer game? In-Reply-To: References: Message-ID: <201204111034.47959.cfuller084@thinkingplanet.net> I think you're on the right track with the IRC idea, but start with something simpler. You can find tutorials or working programs using the asynchat module to make a really basic chat client. Then you build a higher level protocol on top of that. It should take care of most of the low level networking for you. But when you're ready for that, look up nonblocking I/O and the select() system call. http://pypi.python.org/ http://code.activestate.com/recipes/langs/python/ http://docs.python.org/howto/sockets.html#non-blocking-sockets Cheers From alan.gauld at btinternet.com Wed Apr 11 19:32:54 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 11 Apr 2012 18:32:54 +0100 Subject: [Tutor] how to build a multiplayer game? In-Reply-To: References: Message-ID: On 11/04/12 11:02, Surya K wrote: > I have written the basic part of the game. Now I want to make it a > multiplayer one. (Its not a web app, a OS application) > > So, I just wanted to know how do it. > > Which topics I should refer? Network Programming or Web Programming or > Internet Client Programming. That all depends on how you decide to build the game. And what kind of interaction you need. The fastest most direct route is to use raw peer to peer sockets and send string messages between the two computers. But then you need to decide how to set up the connection, who is master anmd who is slave per session etc. A lot less work if you adopt the web model of an app server in the middle and both players connect to that. For straight sockets you should find examples in Wes' book. Or you can read the network programming topic in my tutorial. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Apr 11 19:42:19 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 11 Apr 2012 18:42:19 +0100 Subject: [Tutor] how to build a multiplayer game? In-Reply-To: References: , <4F856020.6030103@davea.name> Message-ID: On 11/04/12 14:30, Surya K wrote: > Don't you think DNS is required as IP addr may be same for some people > in this world.. after all, we only have limited number of combinations. DNS only translates a names IP address into a numeric IP address. It does not create any extra addresses - thats why we are running out of IP numbers! You may be thinking of NAT which translates a public IP address into a local network address and thus allows many computers to share the same set of private IP addrewsses - 198.162,x.y for example can be used on any LAN and the LAN will be seen from the outside as another public IP address. But all of that would be handled by whatever network configuration you and your users have set up. The only exception might be that to get through a firewall you need to open up a particular port number. > * I even got a wild idea, can't we use a IRC channel, create a group and > we make sure that each user of the game will be a member of the group?? > approx, how much delay would be there?? Yes thats a possibility too. But then you will need an IRC server somewhere. Setting up an IRC server is not much different from setting up a web app server. Delay on the internet is highly dependant on routing. If your packet happens to go the wrong way it can wind up jumping around all manner of very busy/slow networks before it reaches you, in which case it might take a few seconds to reach you. OTOH it might rout via a direct link betwen the two ISPs involved and the delay will be <=100ms... Part of the challenge of network programming is deciding how to deal with those two scenarios. It's perfectly possible for packets to arrive out of sync (ie packet two arrives before packet 1 because they were routed differently). Do you hold packet 2 and wait for the late packet or request a resend as soon as packet 2 arrives? There are no right or wrong answers, just different choices for a given scenario. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From wprins at gmail.com Wed Apr 11 22:21:28 2012 From: wprins at gmail.com (Walter Prins) Date: Wed, 11 Apr 2012 22:21:28 +0200 Subject: [Tutor] python connect() function In-Reply-To: References: Message-ID: Hi Pierre, On 11 April 2012 15:49, Pierre Barthelemy wrote: > I have a question about event handling and the use of the connect > function. I have a data object, that contains a series of signals, one > being "new_data_point" . Where does this "connect function" come from and how does it work? Did you write it or is it part of some framework/third party software? Suffice it to say there is no standard "connect function" in plain Python itself that has to do with signals and event driven programming, so you really need to tell us a bit more about what frameworks etc you're using and what you're doing, otherwise we can't try to help you effectively. Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From questions.anon at gmail.com Thu Apr 12 04:31:13 2012 From: questions.anon at gmail.com (questions anon) Date: Thu, 12 Apr 2012 12:31:13 +1000 Subject: [Tutor] write list to columns Message-ID: I am trying to simply write a list of values to txt file in one column. I would then like to add another list in a second column. Somehow they only appear as one long row. Any feedback will be greatly appreciated. print "rain max values", rmax print "yearmonth", monthyear OutputFolder=r"E:/test_out/" myfile=open(OutputFolder+'test.txt','w') myfile.write(str(monthyear)) myfile.write(str(rmax)) myfile.close() In python: rain max values [43.8748, 35.838270000000001, 18.659849999999999, 60.201709999999999, 21.69989, 25.27929, 16.081009999999999, 14.198729999999999, 33.5246, 19.710170000000002, 22.904209999999999, 17.301929999999999, 39.372410000000002, 39.290640000000003, 25.442820000000001, 33.322339999999997, 28.252970000000001, 40.388719999999999, 8.7627600000000001, 54.516460000000002, 109.756, 15.863519999999999, 31.598600000000001] yearmonth ['20110906', '20110907', '20110908', '20110909', '20110910', '20110911', '20110912', '20110913', '20110914', '20110915', '20110916', '20110917', '20110918', '20110919', '20110920', '20110921', '20110922', '20110923', '20110924', '20110925', '20110926', '20110927', '20110928'] in my text file: ['20110906', '20110907', '20110908', '20110909', '20110910', '20110911', '20110912', '20110913', '20110914', '20110915', '20110916', '20110917', '20110918', '20110919', '20110920', '20110921', '20110922', '20110923', '20110924', '20110925', '20110926', '20110927', '20110928'][43.8748, 35.838270000000001, 18.659849999999999, 60.201709999999999, 21.69989, 25.27929, 16.081009999999999, 14.198729999999999, 33.5246, 19.710170000000002, 22.904209999999999, 17.301929999999999, 39.372410000000002, 39.290640000000003, 25.442820000000001, 33.322339999999997, 28.252970000000001, 40.388719999999999, 8.7627600000000001, 54.516460000000002, 109.756, 15.863519999999999, 31.598600000000001] -------------- next part -------------- An HTML attachment was scrubbed... URL: From shantanoo at gmail.com Thu Apr 12 04:51:39 2012 From: shantanoo at gmail.com (=?utf-8?B?4KS24KSC4KSk4KSo4KWC?=) Date: Thu, 12 Apr 2012 08:21:39 +0530 Subject: [Tutor] write list to columns In-Reply-To: References: Message-ID: <680D713E-0AAE-4F5C-90CB-7E5DAA027BB0@gmail.com> On 12-Apr-2012, at 8:01 AM, questions anon wrote: > I am trying to simply write a list of values to txt file in one column. > I would then like to add another list in a second column. > Somehow they only appear as one long row. > Any feedback will be greatly appreciated. > > print "rain max values", rmax > print "yearmonth", month year 'print' adds newline automatically. More info: http://docs.python.org/reference/simple_stmts.html#print > OutputFolder=r"E:/test_out/" > myfile=open(OutputFolder+'test.txt','w') > myfile.write(str(monthyear)) > myfile.write(str(rmax)) > myfile.close() 'write' does not add newline. You need to add '\n' where you want new line. -- shantanoo From punchagan at gmail.com Thu Apr 12 05:03:21 2012 From: punchagan at gmail.com (Puneeth Chaganti) Date: Thu, 12 Apr 2012 08:33:21 +0530 Subject: [Tutor] write list to columns In-Reply-To: References: Message-ID: On Thu, Apr 12, 2012 at 8:01 AM, questions anon wrote: > I am trying to simply write a list of values to txt file in one column. > I would then like to add another list in a second column. > Somehow they only appear as one long row. > Any feedback will be greatly appreciated. You will need to write each line of the file separately, with the formatting you desire for each line. The following example may help. A = range(5) B = range(5, 10) records = zip(A, B) output_format = '%s %s' with open('output.txt', 'w') as f: for record in records: f.write(output_format %(record)) f.write('\n') HTH, Puneeth From moorejohnpaul at yahoo.com Thu Apr 12 06:42:46 2012 From: moorejohnpaul at yahoo.com (john moore) Date: Wed, 11 Apr 2012 21:42:46 -0700 (PDT) Subject: [Tutor] user created lists Message-ID: <1334205766.87330.YahooMailClassic@web160503.mail.bf1.yahoo.com> Hello Pyhton World, I'm new at this and was wondering how I create a number of user specified lists? Example: "How many list would you like to create?" User inputs 5 creates five lists, list1 [] list2 [] list3 [] list4 [] list5 [] I can create one with append, but I don't know how to loop it to create five different named list.. From questions.anon at gmail.com Thu Apr 12 07:33:05 2012 From: questions.anon at gmail.com (questions anon) Date: Thu, 12 Apr 2012 15:33:05 +1000 Subject: [Tutor] write list to columns In-Reply-To: References: Message-ID: Perfect, thank you. Is there a way I could easily/quickly add headings to each column? On Thu, Apr 12, 2012 at 1:03 PM, Puneeth Chaganti wrote: > On Thu, Apr 12, 2012 at 8:01 AM, questions anon > wrote: > > I am trying to simply write a list of values to txt file in one column. > > I would then like to add another list in a second column. > > Somehow they only appear as one long row. > > Any feedback will be greatly appreciated. > > You will need to write each line of the file separately, with the > formatting you desire for each line. > The following example may help. > > > A = range(5) > B = range(5, 10) > > records = zip(A, B) > output_format = '%s %s' > > with open('output.txt', 'w') as f: > for record in records: > f.write(output_format %(record)) > f.write('\n') > > > HTH, > Puneeth > -------------- next part -------------- An HTML attachment was scrubbed... URL: From cwitts at compuscan.co.za Thu Apr 12 07:44:09 2012 From: cwitts at compuscan.co.za (Christian Witts) Date: Thu, 12 Apr 2012 07:44:09 +0200 Subject: [Tutor] user created lists In-Reply-To: <1334205766.87330.YahooMailClassic@web160503.mail.bf1.yahoo.com> References: <1334205766.87330.YahooMailClassic@web160503.mail.bf1.yahoo.com> Message-ID: <4F866BA9.5090006@compuscan.co.za> On 2012/04/12 06:42 AM, john moore wrote: > Hello Pyhton World, > > I'm new at this and was wondering how I create a number of user specified lists? > > Example: > > "How many list would you like to create?" > User inputs 5 > creates five lists, > list1 [] > list2 [] > list3 [] > list4 [] > list5 [] > > I can create one with append, but I don't know how to loop it to create five different named list.. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > You can use vars() to create the variables on the fly. vars() is just a dictionary containing the variable name as the key, and the data as the value so you can do `vars()['list1'] = []` and it's easy enough to create them en masse # Set the start to 1, and add 1 to what the user inputted # as range/xrange doesn't include the top number for i in xrange(1, user_input + 1): vars()['list%s' % i] = [] Hope that helps. -- Christian Witts Python Developer // -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Thu Apr 12 08:59:24 2012 From: __peter__ at web.de (Peter Otten) Date: Thu, 12 Apr 2012 08:59:24 +0200 Subject: [Tutor] user created lists References: <1334205766.87330.YahooMailClassic@web160503.mail.bf1.yahoo.com> <4F866BA9.5090006@compuscan.co.za> Message-ID: Christian Witts wrote: > On 2012/04/12 06:42 AM, john moore wrote: >> Hello Pyhton World, >> >> I'm new at this and was wondering how I create a number of user specified >> lists? >> >> Example: >> >> "How many list would you like to create?" >> User inputs 5 >> creates five lists, >> list1 [] >> list2 [] >> list3 [] >> list4 [] >> list5 [] >> >> I can create one with append, but I don't know how to loop it to create >> five different named list.. > You can use vars() to create the variables on the fly. vars() is just a > dictionary containing the variable name as the key, and the data as the > value so you can do `vars()['list1'] = []` and it's easy enough to > create them en masse > > # Set the start to 1, and add 1 to what the user inputted > # as range/xrange doesn't include the top number > for i in xrange(1, user_input + 1): > vars()['list%s' % i] = [] This will stop working once you move your code into a function: >>> def f(): ... vars()["list1"] = ["a", "b"] ... print list1 ... >>> f() Traceback (most recent call last): File "", line 1, in File "", line 3, in f NameError: global name 'list1' is not defined I recommend that you bite the bullet and use a dedicated dictionary or list to hold your five lists from the very begining: >>> num_lists = int(raw_input("How many lists? ")) How many lists? 5 >>> list_of_lists = [[] for i in range(num_lists)] You then have to access the first list as "list_of_list[0]" instead of "list1" and so on: >>> list_of_lists[0].append(1) >>> list_of_lists[4].append(2) >>> list_of_lists [[1], [], [], [], [2]] From __peter__ at web.de Thu Apr 12 09:21:30 2012 From: __peter__ at web.de (Peter Otten) Date: Thu, 12 Apr 2012 09:21:30 +0200 Subject: [Tutor] python connect() function References: Message-ID: Pierre Barthelemy wrote: > I have a question about event handling and the use of the connect > function. I have a data object, that contains a series of signals, one > being "new_data_point" . > > When i want to plot the data, i also connect the "new_data_point" event to > the function "analysis_client.update_plot". I therefore run the line: > > data.connect('new_data_point', analysis_client.update_plot) > > In this case, everytime the data object is updated, i also update the > plot. > > > I would like to adapt this code to allow to have several plots, connected > to several data objects. I would therefore need to specify, when i connect > the "update_plot" function, which plots needs to be updated. > Is it possible to specify arguments to be used by the connected function > when the event occurs ? For instance, is there a way to write something > like: > > data.connect('new_data_point', > analysis_client.update_plot(specific_plot_instance)) > > So that when the event occurs, the corresponding plot (and only this one) > is updated ? Like Walter I have no idea what framework or library you are talking about. The generic answer is yes: Basically you have to make a new function that calls the method with a specifc plot instance. def update_specific_plot(): analysis_client.update_plot(specific_plot_instance) data.connect("new_data_point", update_specific_plot) A more elegant and more general version of the above would create the helper function on the fly using functools.partial(): from functools import partial data.connect("new_data_point", partial(analysis_client.update_plot, specific_plot_instance)) From cwitts at compuscan.co.za Thu Apr 12 09:25:53 2012 From: cwitts at compuscan.co.za (Christian Witts) Date: Thu, 12 Apr 2012 09:25:53 +0200 Subject: [Tutor] user created lists In-Reply-To: References: <1334205766.87330.YahooMailClassic@web160503.mail.bf1.yahoo.com> <4F866BA9.5090006@compuscan.co.za> Message-ID: <4F868381.5020507@compuscan.co.za> On 2012/04/12 08:59 AM, Peter Otten wrote: > Christian Witts wrote: > >> On 2012/04/12 06:42 AM, john moore wrote: >>> Hello Pyhton World, >>> >>> I'm new at this and was wondering how I create a number of user specified >>> lists? >>> >>> Example: >>> >>> "How many list would you like to create?" >>> User inputs 5 >>> creates five lists, >>> list1 [] >>> list2 [] >>> list3 [] >>> list4 [] >>> list5 [] >>> >>> I can create one with append, but I don't know how to loop it to create >>> five different named list.. > >> You can use vars() to create the variables on the fly. vars() is just a >> dictionary containing the variable name as the key, and the data as the >> value so you can do `vars()['list1'] = []` and it's easy enough to >> create them en masse >> >> # Set the start to 1, and add 1 to what the user inputted >> # as range/xrange doesn't include the top number >> for i in xrange(1, user_input + 1): >> vars()['list%s' % i] = [] > > This will stop working once you move your code into a function: > >>>> def f(): > ... vars()["list1"] = ["a", "b"] > ... print list1 > ... >>>> f() > Traceback (most recent call last): > File "", line 1, in > File "", line 3, in f > NameError: global name 'list1' is not defined > > I recommend that you bite the bullet and use a dedicated dictionary or list > to hold your five lists from the very begining: You could use globals() then instead of var(), although it's a do-it-at-your-own-risk situation then if you overwrite built-ins and other functions in the namespace. Creating your own dictionary with the 'variable name' as the key, would be the nicer solution instead. -- Christian Witts Python Developer // -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Apr 12 09:48:24 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 12 Apr 2012 08:48:24 +0100 Subject: [Tutor] write list to columns In-Reply-To: References: Message-ID: On 12/04/12 03:31, questions anon wrote: > I am trying to simply write a list of values to txt file in one column. > I would then like to add another list in a second column. That's going to be quite awkward to do. Files like to be written one complete line at a time. The normal approach would be to build up the table structure in memory and then write the entire table out in one go. If it won't fit in memory use a simple database like SQLite to build the table then print that out row by row. > Somehow they only appear as one long row. You need to write newlines but you probably also want to use string formatting to control the amount of space required so that your columns line up. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Apr 12 09:55:09 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 12 Apr 2012 08:55:09 +0100 Subject: [Tutor] user created lists In-Reply-To: <4F868381.5020507@compuscan.co.za> References: <1334205766.87330.YahooMailClassic@web160503.mail.bf1.yahoo.com> <4F866BA9.5090006@compuscan.co.za> <4F868381.5020507@compuscan.co.za> Message-ID: On 12/04/12 08:25, Christian Witts wrote: >> I recommend that you bite the bullet and use a dedicated dictionary or list >> to hold your five lists from the very begining: > You could use globals() then instead of var(), although it's a > do-it-at-your-own-risk situation then if you overwrite built-ins and > other functions in the namespace. Creating your own dictionary with the > 'variable name' as the key, would be the nicer solution instead. Trying to create variables on the fly is usually a bad idea, although it seems to appeal to beginners a lot. The problem is: how does the rest of the pre-existing code know about these new variable names so as to access them. If you keep the new values in a collection they can be access via a loop. But randomly named variables in your code require all sorts of extra effort to create the name and deference the namespace each time you want to access them. Anonymous values are best kept in anonymous structures IMHO. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Apr 12 09:56:53 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 12 Apr 2012 08:56:53 +0100 Subject: [Tutor] write list to columns In-Reply-To: References: Message-ID: On 12/04/12 06:33, questions anon wrote: > Perfect, thank you. > Is there a way I could easily/quickly add headings to each column? Headings are no different to any other line of text... > with open('output.txt', 'w') as f: write your headings here > for record in records: > f.write(output_format %(record)) > f.write('\n') > -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From suryak at live.com Thu Apr 12 13:38:15 2012 From: suryak at live.com (Surya K) Date: Thu, 12 Apr 2012 17:08:15 +0530 Subject: [Tutor] should we use multithreading for multiple clients in socket class Message-ID: I am learning networking and just wrote a primitive client server program.. server: from time import ctimefrom socket import * HOST = ""PORT = 21567BUFSIZ = 1024ADDR = (HOST, PORT) tcpSerSoc = socket(AF_INET, SOCK_STREAM)tcpSerSoc.bind(ADDR)tcpSerSoc.listen(5) while True: print "waiting for connection.." tcpCliSoc, addr = tcpSerSoc.accept() print "# Connected from:", addr while True: data = tcpCliSoc.recv(BUFSIZ) if not data: break tcpCliSoc.send( "[%s] %s" % (ctime(), data )) tcpCliSoc.clock()tcpSerSoc.close() Client: from socket import * HOST = 'localhost'PORT = 21567BUFSIZ = 1024ADDR = (HOST, PORT) tcpCliSoc = socket(AF_INET, SOCK_STREAM)tcpCliSoc.connect(ADDR) while True: data = raw_input(">") if not data: break tcpCliSoc.send(data) data = tcpCliSoc.recv(BUFSIZ) if not data: break print datatcpCliSoc.close() This client sends a string, and receives the same string with current time... So, I tried to run another client (same code but from different file) but found that its now working. why its happening, should I use multithreading so that I can handle two clients simultaneously?? -------------- next part -------------- An HTML attachment was scrubbed... URL: From mjolewis at gmail.com Thu Apr 12 15:53:18 2012 From: mjolewis at gmail.com (mjolewis at gmail.com) Date: Thu, 12 Apr 2012 06:53:18 -0700 Subject: [Tutor] Re.findall() Message-ID: <1AFAD675-3236-4B62-A4E2-0E5A32A9B230@gmail.com> Hi everyone, I am having trouble understanding re.findall(). I've read through the documentation and looked at at some examples online, but I still don't have a clear picture. I am going through pythonchallenge.com and I am on challenge 3. I've see. The answer to the problem, but I don't understand the "pattern" portion of re.findall(). Thanks! Sent from my iPhone From breamoreboy at yahoo.co.uk Thu Apr 12 16:32:18 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 12 Apr 2012 15:32:18 +0100 Subject: [Tutor] write list to columns In-Reply-To: References: Message-ID: On 12/04/2012 08:48, Alan Gauld wrote: > On 12/04/12 03:31, questions anon wrote: >> I am trying to simply write a list of values to txt file in one column. >> I would then like to add another list in a second column. > > That's going to be quite awkward to do. Files like to be written one > complete line at a time. The normal approach would be to build up the > table structure in memory and then write the entire table out in one go. > If it won't fit in memory use a simple database like SQLite to build the > table then print that out row by row. > Built-in zip? Or have I missed something? > >> Somehow they only appear as one long row. > > You need to write newlines but you probably also want to use string > formatting to control the amount of space required so that your columns > line up. > > HTH -- Cheers. Mark Lawrence. From breamoreboy at yahoo.co.uk Thu Apr 12 16:37:32 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 12 Apr 2012 15:37:32 +0100 Subject: [Tutor] user created lists In-Reply-To: <1334205766.87330.YahooMailClassic@web160503.mail.bf1.yahoo.com> References: <1334205766.87330.YahooMailClassic@web160503.mail.bf1.yahoo.com> Message-ID: On 12/04/2012 05:42, john moore wrote: > Hello Pyhton World, Hello Hojn Rooem and welcome :) > > I'm new at this and was wondering how I create a number of user specified lists? Why? Tell us what you're trying to achieve and we may well come up with a better solution. > > Example: > > "How many list would you like to create?" > User inputs 5 > creates five lists, > list1 [] > list2 [] > list3 [] > list4 [] > list5 [] > > I can create one with append, but I don't know how to loop it to create five different named list.. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Cheers. Mark Lawrence. From steve at pearwood.info Thu Apr 12 16:47:30 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 13 Apr 2012 00:47:30 +1000 Subject: [Tutor] Re.findall() In-Reply-To: <1AFAD675-3236-4B62-A4E2-0E5A32A9B230@gmail.com> References: <1AFAD675-3236-4B62-A4E2-0E5A32A9B230@gmail.com> Message-ID: <4F86EB02.1000104@pearwood.info> mjolewis at gmail.com wrote: > Hi everyone, > > I am having trouble understanding re.findall(). I've read through the > documentation and looked at at some examples online, but I still don't have > a clear picture. > > I am going through pythonchallenge.com and I am on challenge 3. I've see. > The answer to the problem, but I don't understand the "pattern" portion of > re.findall(). What part don't you understand? Do you understand what a so-called regular expression is? Regular expressions are like super-charged wildcards. In the DOS or Windows command.com or cmd.exe shell, you can use wildcards * and ? to match any characters, or a single character. In Linux and Macintosh shells, you have the same thing only even more so. Regular expressions are a mini programming language for wildcards. For example, 'a.*z' is a pattern that matches any string starting with the letter 'a' and ending with the letter 'z'. Here's a more complicated example: 'm[aeiou]{1,2}n' This regular expression pattern, or regex, matches the letter 'm', followed by 1 or 2 vowels ('a', 'e', 'i', 'o', or 'u') in a row, followed by 'n'. So it will match "moon" or "mean" or "moan" or "man", but not "mpg" or "marvelous" or "meeeeen". You can learn more about regexes here: http://docs.python.org/library/re.html http://docs.python.org/howto/regex.html -- Steven From breamoreboy at yahoo.co.uk Thu Apr 12 16:58:20 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 12 Apr 2012 15:58:20 +0100 Subject: [Tutor] Re.findall() In-Reply-To: <1AFAD675-3236-4B62-A4E2-0E5A32A9B230@gmail.com> References: <1AFAD675-3236-4B62-A4E2-0E5A32A9B230@gmail.com> Message-ID: On 12/04/2012 14:53, mjolewis at gmail.com wrote: > Hi everyone, > > I am having trouble understanding re.findall(). I've read through the documentation and looked at at some examples online, but I still don't have a clear picture. > > I am going through pythonchallenge.com and I am on challenge 3. I've see. The answer to the problem, but I don't understand the "pattern" portion of re.findall(). > > Thanks! > > Sent from my iPhone > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Please give us an example of the code that you've tried, what you expect to see and what the actual output from your program was. If an exception occurred please cut and paste the entire exception traceback into this thread. -- Cheers. Mark Lawrence. From barthpi at gmail.com Thu Apr 12 17:42:06 2012 From: barthpi at gmail.com (Pierre Barthelemy) Date: Thu, 12 Apr 2012 17:42:06 +0200 Subject: [Tutor] python connect() function In-Reply-To: References: Message-ID: Thanks for the fast reply. I went a bit deeper into the code and i found where my problem was. The connect function comes from gobject, and the gobject.connect function accepts extra arguments that are passed to the connected function. So i can solve my problem by: data.connect('new_data_point', analysis_client.update_plot, specific_arguments) Bests, Pierre On Thu, Apr 12, 2012 at 9:21 AM, Peter Otten <__peter__ at web.de> wrote: > Pierre Barthelemy wrote: > > > I have a question about event handling and the use of the connect > > function. I have a data object, that contains a series of signals, one > > being "new_data_point" . > > > > When i want to plot the data, i also connect the "new_data_point" event > to > > the function "analysis_client.update_plot". I therefore run the line: > > > > data.connect('new_data_point', analysis_client.update_plot) > > > > In this case, everytime the data object is updated, i also update the > > plot. > > > > > > I would like to adapt this code to allow to have several plots, connected > > to several data objects. I would therefore need to specify, when i > connect > > the "update_plot" function, which plots needs to be updated. > > Is it possible to specify arguments to be used by the connected function > > when the event occurs ? For instance, is there a way to write something > > like: > > > > data.connect('new_data_point', > > analysis_client.update_plot(specific_plot_instance)) > > > > So that when the event occurs, the corresponding plot (and only this one) > > is updated ? > > Like Walter I have no idea what framework or library you are talking about. > The generic answer is yes: Basically you have to make a new function that > calls the method with a specifc plot instance. > > def update_specific_plot(): > analysis_client.update_plot(specific_plot_instance) > data.connect("new_data_point", update_specific_plot) > > A more elegant and more general version of the above would create the > helper > function on the fly using functools.partial(): > > from functools import partial > > data.connect("new_data_point", > partial(analysis_client.update_plot, specific_plot_instance)) > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Apr 12 18:02:11 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 12 Apr 2012 17:02:11 +0100 Subject: [Tutor] write list to columns In-Reply-To: References: Message-ID: On 12/04/12 15:32, Mark Lawrence wrote: >> That's going to be quite awkward to do. Files like to be written one >> complete line at a time. The normal approach would be to build up the >> table structure in memory and then write the entire table out in one go. > > Built-in zip? Or have I missed something? The OP specifically said he wanted to write out one *column* at a time to the file. Then go back and write the next column etc. zip would be one way to build the structure in memory prior to printing, as I suggested. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From mjolewis at gmail.com Thu Apr 12 18:06:53 2012 From: mjolewis at gmail.com (Michael Lewis) Date: Thu, 12 Apr 2012 09:06:53 -0700 Subject: [Tutor] Re.findall() Message-ID: > > mjolewis at gmail.com wrote: > > Hi everyone, > > > > I am having trouble understanding re.findall(). I've read through the > > documentation and looked at at some examples online, but I still don't > have > > a clear picture. > > > > I am going through pythonchallenge.com and I am on challenge 3. I've > see. > > The answer to the problem, but I don't understand the "pattern" portion > of > > re.findall(). > > > What part don't you understand? Do you understand what a so-called regular > expression is? > Here's the "pattern" portion that I don't understand: re.findall("[^A-Z]+[A-Z]{3}([a-z])[A-Z]{3}[^A-Z]+" What is going on here? The ^ means to apply this pattern from what I read. The first pattern and last pattern are in opposite order, meaning that it goes from [^A-Z]+[A-Z]{3} to [A-Z]{3}[^A-Z]+ - why does the pattern flip-flop? The first pattern starts as [^A-Z] but the last pattern end with [^A-Z]. Why do I need the "+" signs? Also, why does this ([a-z]) need the parenthesis? > > Regular expressions are like super-charged wildcards. In the DOS or Windows > command.com or cmd.exe shell, you can use wildcards * and ? to match any > characters, or a single character. In Linux and Macintosh shells, you have > the > same thing only even more so. > I am familiar with wildcards, but I've mostly used * and nothing else. > > Regular expressions are a mini programming language for wildcards. For > example, 'a.*z' is a pattern that matches any string starting with the > letter > 'a' and ending with the letter 'z'. > > Here's a more complicated example: > > 'm[aeiou]{1,2}n' > > This regular expression pattern, or regex, matches the letter 'm', > followed by > 1 or 2 vowels ('a', 'e', 'i', 'o', or 'u') in a row, followed by 'n'. So it > will match "moon" or "mean" or "moan" or "man", but not "mpg" or > "marvelous" > or "meeeeen". > > You can learn more about regexes here: > > http://docs.python.org/library/re.html > http://docs.python.org/howto/regex.html > > > -- > Steven > > mjolewis at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Apr 12 18:24:12 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 12 Apr 2012 17:24:12 +0100 Subject: [Tutor] should we use multithreading for multiple clients in socket class In-Reply-To: References: Message-ID: On 12/04/12 12:38, Surya K wrote: > I am learning networking and just wrote a primitive client server program.. ... > So, I tried to run another client (same code but from different file) > but found that its now working. I assume that should be *not working*? A more detailed description of what you did and the result would help diagnose the issue. > why its happening, should I use multithreading so that I can handle two > clients simultaneously?? It's not strictly necessary if there are no resource conflicts such as two attempts to write to the same file/data structure. But in the general case multi-threading a server (or forking a separate process) is a good idea. However, there is some implicit "threading" takes place in the socket library insofar as each session is given a separate temporary port to communicate over once the connection has been accepted so unless the connections are using conflicting resource it should still work. See the network programming topic in my tutorial for an example and screenshots of two clients talking to one server... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Apr 12 18:28:09 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 12 Apr 2012 17:28:09 +0100 Subject: [Tutor] Re.findall() In-Reply-To: <4F86EB02.1000104@pearwood.info> References: <1AFAD675-3236-4B62-A4E2-0E5A32A9B230@gmail.com> <4F86EB02.1000104@pearwood.info> Message-ID: On 12/04/12 15:47, Steven D'Aprano wrote: > Regular expressions are like super-charged wildcards. In the DOS or > Windows command.com or cmd.exe shell, you can use wildcards * and ? to > match any characters, or a single character. In Linux and Macintosh > shells, you have the same thing only even more so. Just being picky but from Windows 2000 onwards you can use full regex in the "DOS" command shell too. You need to toggle a registry option I believe but "help cmd" will tell all. File and command completion are likewise available if desired. The Windows command line has most of the stuff Bash has. It's the scripting language that still sucks! (And for that there is WSH or Power Shell) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Apr 12 18:32:36 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 12 Apr 2012 17:32:36 +0100 Subject: [Tutor] python connect() function In-Reply-To: References: Message-ID: On 12/04/12 16:42, Pierre Barthelemy wrote: > Thanks for the fast reply. I went a bit deeper into the code and i found > where my problem was. The connect function comes from gobject, and the > gobject.connect function accepts extra arguments that are passed to the > connected function. So i can solve my problem by: > > data.connect('new_data_point', analysis_client.update_plot, specific_arguments) Glad you got it working but what is gobject? It isn't part of the Python standard library that I recognize so presumably you are using some kind of add-in Framework or library? Any questions to the list need to specify what you are using, if it's not in the standard library we will be pretty much in the dark and unlikely to be able to help until you tell us. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From barthpi at gmail.com Thu Apr 12 18:42:43 2012 From: barthpi at gmail.com (Pierre Barthelemy) Date: Thu, 12 Apr 2012 18:42:43 +0200 Subject: [Tutor] python connect() function In-Reply-To: References: Message-ID: sorry, gobject comes from the PyGTK package. On Thu, Apr 12, 2012 at 6:32 PM, Alan Gauld wrote: > On 12/04/12 16:42, Pierre Barthelemy wrote: > >> Thanks for the fast reply. I went a bit deeper into the code and i found >> where my problem was. The connect function comes from gobject, and the >> gobject.connect function accepts extra arguments that are passed to the >> connected function. So i can solve my problem by: >> >> data.connect('new_data_point', analysis_client.update_plot, >> specific_arguments) >> > > Glad you got it working but what is gobject? > > It isn't part of the Python standard library that I recognize > so presumably you are using some kind of add-in Framework > or library? > > Any questions to the list need to specify what you are > using, if it's not in the standard library we will be > pretty much in the dark and unlikely to be able to > help until you tell us. > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From andipersti at gmail.com Thu Apr 12 20:51:59 2012 From: andipersti at gmail.com (Andreas Perstinger) Date: Thu, 12 Apr 2012 20:51:59 +0200 Subject: [Tutor] Re.findall() In-Reply-To: References: Message-ID: <20120412205159.e84554501904abb5aedfb788@gmail.com> On Thu, 12 Apr 2012 09:06:53 -0700 Michael Lewis wrote: > Here's the "pattern" portion that I don't understand: > > re.findall("[^A-Z]+[A-Z]{3}([a-z])[A-Z]{3}[^A-Z]+" > You have 5 different parts here: 1) [^A-Z]+ - this matches one or more non-uppercase characters. The brackets [] describe a set of wanted characters. A-Z would match any uppercase character, but the caret ^ at the first position inside the brackets means to inverse the set (i.e., match any character not in the set). + means to match at least one of the character(s) described before. 2) [A-Z]{3} - this matches exactly three uppercase characters. With the braces {} you can define how many characters should match: {3} matches exactly 3, {3,} matches at least 3, {,3} matches up to three and {3,6} matches 3 to 6. 3) ([a-z]) - this matches exactly one lowercase character. The parens () are used to save the character for later use. (using the group()/groups()-methods, see the docs). 4) [A-Z]{3} - again matches exactly three uppercase characters. 5) [^A-Z]+ - again matches at least one non-uppercase character. HTH, Andreas From questions.anon at gmail.com Fri Apr 13 09:47:35 2012 From: questions.anon at gmail.com (questions anon) Date: Fri, 13 Apr 2012 17:47:35 +1000 Subject: [Tutor] write list to columns In-Reply-To: References: Message-ID: thanks all! On Fri, Apr 13, 2012 at 2:02 AM, Alan Gauld wrote: > On 12/04/12 15:32, Mark Lawrence wrote: > > That's going to be quite awkward to do. Files like to be written one >>> complete line at a time. The normal approach would be to build up the >>> table structure in memory and then write the entire table out in one go. >>> >> > >> Built-in zip? Or have I missed something? >> > > The OP specifically said he wanted to write out one *column* at a time to > the file. Then go back and write the next column etc. zip would be one way > to build the structure in memory prior to printing, as I suggested. > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Fri Apr 13 16:46:04 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 13 Apr 2012 15:46:04 +0100 Subject: [Tutor] write list to columns In-Reply-To: References: Message-ID: On 13/04/2012 08:47, questions anon wrote: > thanks all! > No problem, but I would like like to point out, albeit repeating myself, that my normal profesional fees apply, i.e. two pints of Ringwood Old Thumper or equivalent should you ever be in my neck of the woods. -- Cheers. Mark Lawrence. From tktucker at gmail.com Sat Apr 14 17:27:21 2012 From: tktucker at gmail.com (Tom Tucker) Date: Sat, 14 Apr 2012 11:27:21 -0400 Subject: [Tutor] Iterate Suggestion Message-ID: Hello all. Any suggestions how I could easily iterate over a list and print the output 3 across (when possible)? One method I was considering was removing the recently printed item from the list, checking list length, etc. Based on the remaining length of the list I would then print X across. Yah? Is their and easier approach I might be overlooking? For example... mylist = ['serverA', 'serverB', 'serverC', 'serverD',' serverE', 'serverF', 'serverG'] Desired Output ============ serverA serverB serverC serverD serverE serverF serverG -------------- next part -------------- An HTML attachment was scrubbed... URL: From lemieliste at gmail.com Sat Apr 14 17:46:11 2012 From: lemieliste at gmail.com (Karim Gorjux) Date: Sat, 14 Apr 2012 17:46:11 +0200 Subject: [Tutor] Problem with mechanize and forms Message-ID: <4F899BC3.4000406@gmail.com> Hi all, I have a problem with mechanize and I can't get out from it. I have this code: br = mechanize.Browser() br.open('http://wwww.example.com/formpage.html') forms = br.forms() for i in forms: print type(i) I get all the forms on the page. But I can't get any of these forms! I need the first form so I tried br.select_form(nr=0) but I get None! Any number I tried get None as result for i in range(6): print br.select_form(nr=i) None None None None None None Anyone can help me? Thanks -- Karim Gorjux From emailkgnow at gmail.com Sat Apr 14 18:41:43 2012 From: emailkgnow at gmail.com (Khalid Al-Ghamdi) Date: Sat, 14 Apr 2012 19:41:43 +0300 Subject: [Tutor] Questions Regarding Sockets Message-ID: Hi All, (python 3.2 on windows) I have a couple of questions regarding the below code: 1- In line (15), what are these variables tcpCliSock, addr supposed to hold and do? 2- Why do I have to specify the buffer size and what does it mean? 3- When I try to run the below code and its corresponding client it works ok for the first time, but then it gives me this error: Traceback (most recent call last): File "C:\Python32\Khalid Stuff\tsTserv3.py", line 12, in tcpSerSock.bind(ADDR) socket.error: [Errno 10048] Only one usage of each socket address (protocol/network address/port) is normally permitted I thought it had to do with the address so I changed the port and it worked ok. so,: A/ isn't the optional tcpSerSock.close() supposed to close the connection for later reuse? B/ why is it when i go to the IDLE and enter tcpSerSock.close() and it accepts it, it still gives the same error and doesn't close the connection for reuse by my code? Thanks a lot 1. from socket import * 2. from time import ctime 3. 4. HOST = '' 5. PORT = 21567 6. BUFSIZ = 1024 7. ADDR =(HOST, PORT) 8. 9. tcpSerSock = socket(AF_INET, SOCK_STREAM) 10. tcpSerSock.bind(ADDR) 11. tcpSerSock.listen(5) 12. 13. while True: 14. print('waiting for connection ...') 15. tcpCliSock, addr = tcpSerSock.accept() 16. print('...connected from: ', addr) 17. 18. while True: 19. data = tcpCliSock.recv(BUFSIZ) 20. if not data: 21. break 22. tcpCliSock.send(bytes('[{}] {}'.format(ctime(),data.decode( 'utf-8')),'utf-8')) 23. 24. tcpCliSock.close() 25. tcpSerSock.close() -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Apr 14 19:18:52 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 14 Apr 2012 18:18:52 +0100 Subject: [Tutor] Iterate Suggestion In-Reply-To: References: Message-ID: On 14/04/12 16:27, Tom Tucker wrote: > > Hello all. Any suggestions how I could easily iterate over a list and > print the output 3 across (when possible)? Using the step size argument to range: L = range(12) >>> for n in range(0,len(L),3): ... print L[n],L[n+1],L[n+2] ... 0 1 2 3 4 5 6 7 8 9 10 11 >>> HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From bodsda at googlemail.com Sat Apr 14 19:19:47 2012 From: bodsda at googlemail.com (Bod Soutar) Date: Sat, 14 Apr 2012 18:19:47 +0100 Subject: [Tutor] Questions Regarding Sockets In-Reply-To: References: Message-ID: On 14 April 2012 17:41, Khalid Al-Ghamdi wrote: > Hi All, > > (python 3.2 on windows) > > I have a couple of questions regarding the below code: > > 1- In line (15), what are these variables tcpCliSock, addr supposed to > hold and do? > 2- Why do I have to specify the buffer size and what does it mean? > 3- When I try to run the below code and its corresponding client it works > ok for the first time, but then it gives me this error: > > Traceback (most recent call last): > File "C:\Python32\Khalid Stuff\tsTserv3.py", line 12, in > tcpSerSock.bind(ADDR) > socket.error: [Errno 10048] Only one usage of each socket address > (protocol/network address/port) is normally permitted > > I thought it had to do with the address so I changed the port and it > worked ok. so,: > > A/ isn't the optional tcpSerSock.close() supposed to close the connection > for later reuse? > B/ why is it when i go to the IDLE and enter tcpSerSock.close() and it > accepts it, it still gives the same error and doesn't close the connection > for reuse by my code? > > Thanks a lot > > > 1. from socket import * > 2. from time import ctime > 3. > 4. HOST = '' > 5. PORT = 21567 > 6. BUFSIZ = 1024 > 7. ADDR =(HOST, PORT) > 8. > 9. tcpSerSock = socket(AF_INET, SOCK_STREAM) > 10. tcpSerSock.bind(ADDR) > 11. tcpSerSock.listen(5) > 12. > 13. while True: > 14. print('waiting for connection ...') > 15. tcpCliSock, addr = tcpSerSock.accept() > 16. print('...connected from: ', addr) > 17. > 18. while True: > 19. data = tcpCliSock.recv(BUFSIZ) > 20. if not data: > 21. break > 22. tcpCliSock.send(bytes('[{}] {}'.format(ctime(),data.decode( > 'utf-8')),'utf-8')) > 23. > 24. tcpCliSock.close() > 25. tcpSerSock.close() > > > In response to question A: >From python docs: http://docs.python.org/py3k/library/socket.html?highlight=socket.close#socket.socket.close Close the socket. All future operations on the socket object will fail. The remote end will receive no more data (after queued data is flushed). Sockets are automatically closed when they are garbage-collected. Note close()releases the resource associated with a connection but does not necessarily close the connection immediately. If you want to close the connection in a timely fashion, call shutdown()before close() . Bodsda > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bodsda at googlemail.com Sat Apr 14 19:29:31 2012 From: bodsda at googlemail.com (Bod Soutar) Date: Sat, 14 Apr 2012 18:29:31 +0100 Subject: [Tutor] Iterate Suggestion In-Reply-To: References: Message-ID: On 14 April 2012 16:27, Tom Tucker wrote: > > Hello all. Any suggestions how I could easily iterate over a list and > print the output 3 across (when possible)? One method I was considering > was removing the recently printed item from the list, checking list length, > etc. Based on the remaining length of the list I would then print X > across. Yah? Is their and easier approach I might be overlooking? > > > For example... > > mylist = ['serverA', 'serverB', 'serverC', 'serverD',' serverE', > 'serverF', 'serverG'] > > > Desired Output > ============ > serverA serverB serverC > serverD serverE serverF > serverG > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > How about something like this mylist = ['serverA', 'serverB', 'serverC', 'serverD','serverE', 'serverF', 'serverG'] tempstr = "" count = 0 for item in mylist: count += 1 if count == 3: tempstr += (i + "\n") count = 0 else: tempstr += (i + " ") print tempstr The above code prepares an empty string variable, and a count variable. On each iteration, it checks to see if the count is equal to 3. If it is, then it appends the current list element to the string and also adds a newline character("\n"), then the count is reset to 0. If the count isn't 3, it simply appends the current list element along with a space. Hope this helps, Bodsda -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Apr 14 19:32:15 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 14 Apr 2012 18:32:15 +0100 Subject: [Tutor] Questions Regarding Sockets In-Reply-To: References: Message-ID: On 14/04/12 17:41, Khalid Al-Ghamdi wrote: > 1- In line (15), what are these variables tcpCliSock,addr supposed to > hold and do? The socket object and the IP address of the client that is connecting to the server. When a client connects to a server the server assigns a new temporary socket connection that the client uses. Each connection gets a new temporary socket assignment. What happens to the old one is implementation dependent and you should not try to reuse it. > 2- Why do I have to specify the buffer size and what does it mean? A buffer is an area of memory used as a kind of holding bay into which data is put, usually temporarily. You need to specify where the incoming data will go and how much space you expect to use. > 3- When I try to run the below code and its corresponding client it > works ok for the first time, but then it gives me this error: > > Traceback (most recent call last): > File "C:\Python32\Khalid Stuff\tsTserv3.py", line 12, in > tcpSerSock.bind(ADDR) > socket.error: [Errno 10048] Only one usage of each socket address > (protocol/network address/port) is normally permitted > > I thought it had to do with the address so I changed the port and it > worked ok. so,: > > A/ isn't the optional tcpSerSock.close() supposed to close the > connection for later reuse? Yes, but there is sometimes a delay before the OS cleans up, it may be that which you are seeing. > B/ why is it when i go to the IDLE and enter tcpSerSock.close() and it > accepts it, it still gives the same error and doesn't close the > connection for reuse by my code? It may be an OS level thing. But I'm by no means an expert on the OS networking layers! Which OS are you running under? > HOST = '' > PORT = 21567 > BUFSIZ = 1024 > ADDR =(HOST, PORT) > tcpSerSock = socket(AF_INET, SOCK_STREAM) > tcpSerSock.bind(ADDR) > tcpSerSock.listen(5) > > while True: > print('waiting for connection ...') > tcpCliSock, addr = tcpSerSock.accept() > print('...connected from: ', addr) > while True: > data = tcpCliSock.recv(BUFSIZ) > if not data: > break > tcpCliSock.send(bytes('[{}] > {}'.format(ctime(),data.decode('utf-8')),'utf-8')) > tcpCliSock.close() > tcpSerSock.close() I can't help but think you should check if there actually is a connection before starting the second loop... What do you expect if the accept() fails to find anything? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From bodsda at googlemail.com Sat Apr 14 19:33:10 2012 From: bodsda at googlemail.com (Bod Soutar) Date: Sat, 14 Apr 2012 18:33:10 +0100 Subject: [Tutor] Iterate Suggestion In-Reply-To: References: Message-ID: On 14 April 2012 18:29, Bod Soutar wrote: > > > On 14 April 2012 16:27, Tom Tucker wrote: > >> >> Hello all. Any suggestions how I could easily iterate over a list and >> print the output 3 across (when possible)? One method I was considering >> was removing the recently printed item from the list, checking list length, >> etc. Based on the remaining length of the list I would then print X >> across. Yah? Is their and easier approach I might be overlooking? >> >> >> For example... >> >> mylist = ['serverA', 'serverB', 'serverC', 'serverD',' serverE', >> 'serverF', 'serverG'] >> >> >> Desired Output >> ============ >> serverA serverB serverC >> serverD serverE serverF >> serverG >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > How about something like this > > > mylist = ['serverA', 'serverB', 'serverC', 'serverD','serverE', > 'serverF', 'serverG'] > tempstr = "" > count = 0 > > for item in mylist: > count += 1 > if count == 3: > tempstr += (i + "\n") > count = 0 > else: > tempstr += (i + " ") > > print tempstr > > > The above code prepares an empty string variable, and a count variable. On > each iteration, it checks to see if the count is equal to 3. If it is, then > it appends the current list element to the string and also adds a newline > character("\n"), then the count is reset to 0. If the count isn't 3, it > simply appends the current list element along with a space. > > Hope this helps, > Bodsda > > > erm, I screwed up my variable names. where you see 'i', this should be item (or the other way around). My bad. -- Bodsda -------------- next part -------------- An HTML attachment was scrubbed... URL: From tktucker at gmail.com Sat Apr 14 19:55:51 2012 From: tktucker at gmail.com (Tom Tucker) Date: Sat, 14 Apr 2012 13:55:51 -0400 Subject: [Tutor] Iterate Suggestion In-Reply-To: References: Message-ID: All, Thanks for the help. On Sat, Apr 14, 2012 at 1:33 PM, Bod Soutar wrote: > > > On 14 April 2012 18:29, Bod Soutar wrote: > >> >> >> On 14 April 2012 16:27, Tom Tucker wrote: >> >>> >>> Hello all. Any suggestions how I could easily iterate over a list and >>> print the output 3 across (when possible)? One method I was considering >>> was removing the recently printed item from the list, checking list length, >>> etc. Based on the remaining length of the list I would then print X >>> across. Yah? Is their and easier approach I might be overlooking? >>> >>> >>> For example... >>> >>> mylist = ['serverA', 'serverB', 'serverC', 'serverD',' serverE', >>> 'serverF', 'serverG'] >>> >>> >>> Desired Output >>> ============ >>> serverA serverB serverC >>> serverD serverE serverF >>> serverG >>> >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> To unsubscribe or change subscription options: >>> http://mail.python.org/mailman/listinfo/tutor >>> >>> >> How about something like this >> >> >> mylist = ['serverA', 'serverB', 'serverC', 'serverD','serverE', >> 'serverF', 'serverG'] >> tempstr = "" >> count = 0 >> >> for item in mylist: >> count += 1 >> if count == 3: >> tempstr += (i + "\n") >> count = 0 >> else: >> tempstr += (i + " ") >> >> print tempstr >> >> >> The above code prepares an empty string variable, and a count variable. >> On each iteration, it checks to see if the count is equal to 3. If it is, >> then it appends the current list element to the string and also adds a >> newline character("\n"), then the count is reset to 0. If the count isn't >> 3, it simply appends the current list element along with a space. >> >> Hope this helps, >> Bodsda >> >> >> erm, I screwed up my variable names. where you see 'i', this should be > item (or the other way around). > My bad. > > -- Bodsda > -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Sat Apr 14 21:22:43 2012 From: d at davea.name (Dave Angel) Date: Sat, 14 Apr 2012 15:22:43 -0400 Subject: [Tutor] Iterate Suggestion In-Reply-To: References: Message-ID: <4F89CE83.3080109@davea.name> On 04/14/2012 01:55 PM, Tom Tucker wrote: > All, > Thanks for the help. Please try to post your messages AFTER the part you're quoting. Another very useful feature is enumerate(). Instead of doing for item in mylist: count += 1 if count... do something like: for index, item in enumerate(mylist): if index%3 == 0: #the modulo operator is also very useful print print item, -- DaveA From steve at pearwood.info Sun Apr 15 04:40:29 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 15 Apr 2012 12:40:29 +1000 Subject: [Tutor] Iterate Suggestion In-Reply-To: References: Message-ID: <4F8A351D.4030003@pearwood.info> Bod Soutar wrote: > How about something like this > > mylist = ['serverA', 'serverB', 'serverC', 'serverD','serverE', 'serverF', > 'serverG'] > tempstr = "" > count = 0 > > for item in mylist: > count += 1 > if count == 3: > tempstr += (i + "\n") > count = 0 > else: > tempstr += (i + " ") > > print tempstr Warning: this is a good way to write HORRIBLY slow code that potentially takes many minutes or even hours to generate output. And even worst, it will occur inconsistently, making it really hard to debug. The right way to join many strings into one is with the join method: accumulate the substrings into a list, and then join them in one go: ' '.join(list_of_words) The problem with your code is that you are doing repeated string concatenation, which is slow. If you understand Big Oh notation, string concatenation is O(n**2), which means that (roughly speaking) if you increase the amount of data by a hundred, the time taken will increase by a factor of ten thousand. You can read more about why this happens here: http://www.joelonsoftware.com/articles/fog0000000319.html CPython (the implementation you are using) has a clever optimization that *sometimes* can speed up this situation, which is why you may never have noticed how slow it gets. But other implementations such as Jython and IronPython do not, and so your code will be pathologically slow on these implementations. Worse, the clever optimization is easily defeated. On some operating systems or memory schemes, it can fail and become horribly slow -- and debugging it is a real pain because others will report no slowdown. A few years ago, a similar situation was reported in the urllib or urllib2 module in the standard library. Thanks to the clever optimization, most people never noticed, but one user reported that Python was taken twenty or thirty minutes to download a file that Internet Explorer and wget would download in five or ten seconds. At first nobody believed him, because they couldn't replicate the bug. Then they thought it was a network issue. Eventually this fellow persevered and tracked the bug down to repeated string concatenation in the standard library. The inventor of Python, Guido van Rossum, described it as "embarrassing". You can search the Python-Dev mailing list archives for this. Here's an example of how slow repeated string concatenation can be, with and without the clever optimization: py> from timeit import Timer py> t = Timer('for i in range(500): s = s + "x"', 's = ""') py> t.timeit(300) # repeat the test 300 times 0.038927078247070312 That's not too bad: less than half a second to do 150 thousand string concatenations. But see what happens when I defeat the optimizer with a small change to the code: py> t = Timer('for i in range(500): s = "x" + s', 's = ""') py> t.timeit(300) 5.8992829322814941 That's 152 times slower. -- Steven From andrew.jahner at gmail.com Sun Apr 15 06:02:48 2012 From: andrew.jahner at gmail.com (Andrew Jahn) Date: Sun, 15 Apr 2012 00:02:48 -0400 Subject: [Tutor] Python Fails to Change Directory Message-ID: Hi all, I am attempting to use a Python program to change into a specified directory before executing some commands. However, when I call the Python program from my Unix shell (tcsh) using a command such as "python myprogram.py" It runs without changing directory. Just to clarify, the lines of code in question are the following: import os MyDir = "/usr/local/myDir" os.system("cd "+myDir) I have also tried "os.chdir(MyDir)", but that doesn't work either - it just runs without actually changing directory. As a side note, when I run the same commands above within the Python interactive environment, it works just fine. I am running Python version 2.4. Thanks! -Andy -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sun Apr 15 07:32:29 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 15 Apr 2012 15:32:29 +1000 Subject: [Tutor] Python Fails to Change Directory In-Reply-To: References: Message-ID: <4F8A5D6D.9010204@pearwood.info> Andrew Jahn wrote: > Hi all, > > I am attempting to use a Python program to change into a specified > directory before executing some commands. However, when I call the Python > program from my Unix shell (tcsh) using a command such as > > "python myprogram.py" > > It runs without changing directory. Just to clarify, the lines of code in > question are the following: > > import os > MyDir = "/usr/local/myDir" > os.system("cd "+myDir) That's not the code you are running, because it gives a NameError. Please copy and paste any code snippets you give, don't retype them (especially not from memory!) since you will likely introduce errors. The above error is trivial to fix, but who knows what other errors you have introduced? In any case, os.system can't help you, because that starts a new external process, it doesn't change the directory of the current process (your Python script). > I have also tried "os.chdir(MyDir)", but that doesn't work either - it just > runs without actually changing directory. I find that very hard to believe. Can you explain why you think it doesn't change directory? Try this: import os print os.getcwd() os.chdir("/usr/local/myDir") print os.getcwd() What does it print? -- Steven From mjolewis at gmail.com Sun Apr 15 09:10:35 2012 From: mjolewis at gmail.com (Michael Lewis) Date: Sun, 15 Apr 2012 00:10:35 -0700 Subject: [Tutor] re.search() help Message-ID: Hi everyone, I am a bit confused on how one would ever use re.search(). It essentially tells me the location on (RAM?) if the pattern matches? What is the purpose of this? Can you give me a good example of where it would be useful? Thanks! re.search(*pattern*, *string*, *flags=0*) Scan through *string* looking for a location where the regular expression * pattern* produces a match, and return a corresponding MatchObject instance. Return None if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string. -- Michael J. Lewis mjolewis at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Apr 15 09:48:10 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 15 Apr 2012 08:48:10 +0100 Subject: [Tutor] re.search() help In-Reply-To: References: Message-ID: On 15/04/12 08:10, Michael Lewis wrote: > Hi everyone, > > I am a bit confused on how one would ever use re.search(). It > essentially tells me the location on (RAM?) if the pattern matches? No it returns a MatchObject instance. You can then perform various operations on the MatchObject to, for example find the substring which actually matched. > What is the purpose of this? So that you can find the section of a long string that first matches your regex. > Can you give me a good example of where it would > be useful? Searching for the first occurence of a regex in a long string. > Scan through /string/ looking for a location where the regular > expression /pattern/ produces a match, and return a corresponding > MatchObject Try reading the docs on MatchObject, here is a simple example: >>> s = "Here is a string" >>> m = re.search("is", s) >>> m <_sre.SRE_Match object at 0x153b780> >>> dir(m) ['__copy__', '__deepcopy__', 'end', 'expand', 'group', 'groupdict', 'groups', 'span', 'start'] >>> m.start >>> m.start() 5 >>> m.end() 7 >>> m.group() 'is' >>> m.span() (5, 7) Hopefully that gives you the basic idea? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From syedzaidi85 at hotmail.co.uk Sun Apr 15 09:55:53 2012 From: syedzaidi85 at hotmail.co.uk (syed zaidi) Date: Sun, 15 Apr 2012 08:55:53 +0100 Subject: [Tutor] Help with regular expression In-Reply-To: References: Message-ID: Dear all Can someone please tell me how to solve the following problem. I have developed a python code to extract specific information from more than 1000 files which have slightly different format. The problem I am facing is that I have to develop specific RE for each of the file which is very difficult when it comes to handle 1000s of files. can someone please tell me how to solve this problem. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sun Apr 15 10:36:16 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 15 Apr 2012 18:36:16 +1000 Subject: [Tutor] Help with regular expression In-Reply-To: References: Message-ID: <4F8A8880.1090007@pearwood.info> syed zaidi wrote: > > Dear all Can someone please tell me how to solve the following problem. I > have developed a python code to extract specific information from more than > 1000 files which have slightly different format. The problem I am facing is > that I have to develop specific RE for each of the file which is very > difficult when it comes to handle 1000s of files. can someone please tell > me how to solve this problem. Change the files so that they all have the same format. Without knowing what the format is, how it differs from file to file, and what RE you use, what sort of answer did you expect? -- Steven From emailkgnow at gmail.com Sun Apr 15 10:56:24 2012 From: emailkgnow at gmail.com (Khalid Al-Ghamdi) Date: Sun, 15 Apr 2012 11:56:24 +0300 Subject: [Tutor] Questions Regarding Sockets In-Reply-To: References: Message-ID: Thanks a lot. You've been, as usual, very helpful. On Sat, Apr 14, 2012 at 8:32 PM, Alan Gauld wrote: > On 14/04/12 17:41, Khalid Al-Ghamdi wrote: > > 1- In line (15), what are these variables tcpCliSock,addr supposed to >> hold and do? >> > > The socket object and the IP address of the client that is connecting to > the server. When a client connects to a server the server assigns a new > temporary socket connection that the client uses. Each connection gets a > new temporary socket assignment. What happens to the old one is > implementation dependent and you should not try to reuse it. > > > 2- Why do I have to specify the buffer size and what does it mean? >> > > A buffer is an area of memory used as a kind of holding bay into which > data is put, usually temporarily. You need to specify where the incoming > data will go and how much space you expect to use. > > > 3- When I try to run the below code and its corresponding client it >> works ok for the first time, but then it gives me this error: >> >> Traceback (most recent call last): >> File "C:\Python32\Khalid Stuff\tsTserv3.py", line 12, in >> tcpSerSock.bind(ADDR) >> socket.error: [Errno 10048] Only one usage of each socket address >> (protocol/network address/port) is normally permitted >> >> I thought it had to do with the address so I changed the port and it >> worked ok. so,: >> >> A/ isn't the optional tcpSerSock.close() supposed to close the >> connection for later reuse? >> > > Yes, but there is sometimes a delay before the OS cleans up, it may be > that which you are seeing. > > > B/ why is it when i go to the IDLE and enter tcpSerSock.close() and it >> accepts it, it still gives the same error and doesn't close the >> connection for reuse by my code? >> > > It may be an OS level thing. But I'm by no means an expert on the OS > networking layers! Which OS are you running under? > > > HOST = '' >> PORT = 21567 >> BUFSIZ = 1024 >> ADDR =(HOST, PORT) >> tcpSerSock = socket(AF_INET, SOCK_STREAM) >> tcpSerSock.bind(ADDR) >> tcpSerSock.listen(5) >> >> while True: >> print('waiting for connection ...') >> tcpCliSock, addr = tcpSerSock.accept() >> print('...connected from: ', addr) >> while True: >> data = tcpCliSock.recv(BUFSIZ) >> if not data: >> break >> tcpCliSock.send(bytes('[{}] >> {}'.format(ctime(),data.** >> decode('utf-8')),'utf-8')) >> tcpCliSock.close() >> tcpSerSock.close() >> > > I can't help but think you should check if there actually is a connection > before starting the second loop... What do you expect > if the accept() fails to find anything? > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Sun Apr 15 13:34:21 2012 From: d at davea.name (Dave Angel) Date: Sun, 15 Apr 2012 07:34:21 -0400 Subject: [Tutor] Python Fails to Change Directory In-Reply-To: <4F8A5D6D.9010204@pearwood.info> References: <4F8A5D6D.9010204@pearwood.info> Message-ID: <4F8AB23D.4000705@davea.name> On 04/15/2012 01:32 AM, Steven D'Aprano wrote: > Andrew Jahn wrote: >> Hi all, >> >> I am attempting to use a Python program to change into a specified >> directory before executing some commands. However, when I call the >> Python >> program from my Unix shell (tcsh) using a command such as >> >> "python myprogram.py" >> >> It runs without changing directory. Just to clarify, the lines of >> code in >> question are the following: >> >> import os >> MyDir = "/usr/local/myDir" >> os.system("cd "+myDir) > > That's not the code you are running, because it gives a NameError. > Please copy and paste any code snippets you give, don't retype them > (especially not from memory!) since you will likely introduce errors. > The above error is trivial to fix, but who knows what other errors you > have introduced? > > In any case, os.system can't help you, because that starts a new > external process, it doesn't change the directory of the current > process (your Python script). > > I interpreted Andrew's description somewhat differently. He's executing a Python program before executing some other commands. So those other commands are shell commands, not Python lines. In that case, Python has nothing to do with the problem. Andrew, are you trying to do this sort of thing ? davea at think:~/tmp$ python program.py davea at think:~/tmp$ myother davea at think:~/tmp$ programs davea at think:~/tmp$ where 'myother' and 'programs' are other "commands" or (programs and shell scripts)? In that case, nothing that your python program can normally do can alter either the cwd or the environment. The shell explicitly creates a new environment for the python program, and tosses it away when it exits. You can demonstrate it for yourself, easily enough. The following in my (bash) environment. With an executable file called change.sh, as follows: davea at think:~/tmp$ cat change.sh #!/bin/bash cd other pwd davea at think:~/tmp$ ./change.sh /home/davea/tmp/other davea at think:~/tmp$ pwd /home/davea/tmp ( Notice the pwd of the shell did NOT change. ) davea at think:~/tmp$ source ./change.sh /home/davea/tmp/other davea at think:~/tmp/other$ pwd /home/davea/tmp/other davea at think:~/tmp/other$ Unfortunately, I don't know of any workaround for this. The obvious extension would be: davea at think:~/tmp$ source python myprogram.py bash: source: /usr/bin/python: cannot execute binary file When I've had this type of problem I've resorted to creating a text file from the Python script, and doing a chmod +x on that file and source'ing it from bash. -- DaveA From sburoff at optonline.net Sun Apr 15 13:28:48 2012 From: sburoff at optonline.net (Steven Buroff) Date: Sun, 15 Apr 2012 07:28:48 -0400 Subject: [Tutor] Python Fails to Change Directory In-Reply-To: <4F8A5D6D.9010204@pearwood.info> References: <4F8A5D6D.9010204@pearwood.info> Message-ID: <002201cd1afa$ee3c7c60$cab57520$@net> Just to support Andrew, I've got several scripts that use os.chdir and they all run fine with 3.2.3. Steve > -----Original Message----- > From: tutor-bounces+sburoff=optonline.net at python.org [mailto:tutor- > bounces+sburoff=optonline.net at python.org] On Behalf Of Steven D'Aprano > Sent: Sunday, April 15, 2012 1:32 AM > To: tutor at python.org > Subject: Re: [Tutor] Python Fails to Change Directory > > Andrew Jahn wrote: > > Hi all, > > > > I am attempting to use a Python program to change into a specified > > directory before executing some commands. However, when I call the > > Python program from my Unix shell (tcsh) using a command such as > > > > "python myprogram.py" > > > > It runs without changing directory. Just to clarify, the lines of code > > in question are the following: > > > > import os > > MyDir = "/usr/local/myDir" > > os.system("cd "+myDir) > > That's not the code you are running, because it gives a NameError. Please > copy and paste any code snippets you give, don't retype them (especially > not from > memory!) since you will likely introduce errors. The above error is trivial > to fix, but who knows what other errors you have introduced? > > In any case, os.system can't help you, because that starts a new external > process, it doesn't change the directory of the current process (your > Python script). > > > > I have also tried "os.chdir(MyDir)", but that doesn't work either - it > > just runs without actually changing directory. > > I find that very hard to believe. Can you explain why you think it doesn't > change directory? Try this: > > > import os > print os.getcwd() > os.chdir("/usr/local/myDir") > print os.getcwd() > > What does it print? > > > > > -- > Steven > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From andipersti at gmail.com Sun Apr 15 14:50:59 2012 From: andipersti at gmail.com (Andreas Perstinger) Date: Sun, 15 Apr 2012 14:50:59 +0200 Subject: [Tutor] Problem with mechanize and forms In-Reply-To: <4F899BC3.4000406@gmail.com> References: <4F899BC3.4000406@gmail.com> Message-ID: <4F8AC433.4070902@gmail.com> On 2012-04-14 17:46, Karim Gorjux wrote: > But I can't get any of these forms! I need the first form so I tried > > br.select_form(nr=0) > > but I get None! With "br.select_form()" you set the current form which is accessible through the "br.form" attribute. The method itself doesnt't return anything and thus you get "None" if you do "print br.select_form(nr=0)". For further processing you have to work with "br.form" and its methods. See also help(br.select_form) and help(br.form). Bye, Andreas From steve at pearwood.info Sun Apr 15 16:24:17 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 16 Apr 2012 00:24:17 +1000 Subject: [Tutor] Help with regular expression In-Reply-To: References: , , <4F8A8880.1090007@pearwood.info> Message-ID: <4F8ADA11.6020502@pearwood.info> syed zaidi wrote: > Dear Steve,Tutor doesn't allow attachment of huge files. I am attaching > the files I am taking as input, code and the output CSV file. I hope then > you would be able to help me. DOT keg files open in file viewer, you can > also view them in python. The CSV file is the desired output file. There is no need to send four files when one will do. Also no need to send a file with multiple thousands of lines long when a dozen or so lines should be sufficient. It would also help if you told us what the fields in the file should be called. You are probably familiar with them, but we aren't. Since I don't know what the fields are called, I'm going to just make up some names. def parse_d_line(line): # Expects a line like this: # D SBG_0147 aceE; xxx xxx\tK00163 xxx xxx [EC:1.2.4.1] a, b = line.split('\t') # split on tab character c, d = a.split(';') letter, sbg_code, other_code = c.split() compound1 = d.strip() words = b.split() k_code = words[0] ec = words[-1] compound2 = " ".join(words[1:-1]) return (letter, sbg_code, other_code, compound1, k_code, compound2, ec) kegfile = open('something.keg') # skip lines until a bare exclamation mark for line in kegfile: if line.strip() == '!': break # analyse D lines only, skipping all others for line in kegfile: if line.startswith('D'): print(parse_d_line(dline)) elif line.strip() == '!': break # stop processing You will notice I don't use regular expressions in this. Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems. -- Jamie Zawinski -- Steven From mjolewis at gmail.com Mon Apr 16 01:20:49 2012 From: mjolewis at gmail.com (Michael Lewis) Date: Sun, 15 Apr 2012 16:20:49 -0700 Subject: [Tutor] re.search() help Message-ID: > > Message: 6 > Date: Sun, 15 Apr 2012 08:48:10 +0100 > From: Alan Gauld > To: tutor at python.org > Subject: Re: [Tutor] re.search() help > Message-ID: > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > On 15/04/12 08:10, Michael Lewis wrote: > > Hi everyone, > > > > I am a bit confused on how one would ever use re.search(). It > > essentially tells me the location on (RAM?) if the pattern matches? > > No it returns a MatchObject instance. > You can then perform various operations on the > MatchObject to, for example find the substring > which actually matched. > > > What is the purpose of this? > > So that you can find the section of a long string that > first matches your regex. > Why not use re.findall() for that? It seems like re.findall() can fill this need and I wouldn't need to use re.search()? Can you compare an example circumstance where one would be better suited than the other? > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > -- Michael J. Lewis mjolewis at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Apr 16 01:28:59 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 16 Apr 2012 00:28:59 +0100 Subject: [Tutor] re.search() help In-Reply-To: References: Message-ID: On 16/04/12 00:20, Michael Lewis wrote: > > What is the purpose of this? > > So that you can find the section of a long string that > first matches your regex. > > > Why not use re.findall() for that? It seems like re.findall() can fill > this need and I wouldn't need to use re.search()? Can you compare an > example circumstance where one would be better suited than the other? Performance. It's faster to find just the first occurrence. Especially if the string is long - say several million characters. If you only need the first one why search for all the rest? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From wprins at gmail.com Mon Apr 16 02:12:26 2012 From: wprins at gmail.com (Walter Prins) Date: Mon, 16 Apr 2012 02:12:26 +0200 Subject: [Tutor] re.search() help In-Reply-To: References: Message-ID: Hi Michael, On 16 April 2012 01:20, Michael Lewis wrote: > So that you can find the section of a long string that >> first matches your regex. >> >> > Why not use re.findall() for that? It seems like re.findall() can fill > this need and I wouldn't need to use re.search()? Can you compare an > example circumstance where one would be better suited than the other? > To add to what Alan's said: Regular expressions is a textual specification language that is often used in the specification of tokens, e.g. when designing (for example) some type of computer language, or perhaps a preprocessor for a computer language, the tokens themselves will typically be specified using regular expressions (or something similar), while the grammar of the language will typically be expressed using something like BNF or more typically EBNF (which stands for Extended Backus-Naur Form, after the creators of the syntax.) Anyway, so as an example then of where you would not use re.findall() (or indeed re.search()), in terms of compilers you typically have a scanner and parser component where the scanner has the job of taking the input text which can be seen as a sequence of text characters and and converting it into a sequence of tokens, and this tokenization process may well involve the use of regular expressions, where it only makes sense to match only at the beginning of the text being tokenized/scanned. So in such a context you'd definitely not even want to use re.search() or re.findall() but rather would probably use re.match() since you're expressly trying to recognize the next "word" (token) from the text being scanned (and ultimately, parsed.) Another example: Suppose you're implementing a preprocessor for a programming language, and you therefore want to ignore most of the actual programming language text (since you're really only interested in the pre-processor language that interspersed with the "normal" programming language.) In such a scenario the first (or next) pre-processor language token will likely not be at the beginning of your current program text block, so in such a case re.match() or re.findall() would not be helpful since you want to then find the first token in the text, which may or may not be at the beginning of the string. In such a case you'd therefore like to use re.search(). HTH, Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Mon Apr 16 04:54:43 2012 From: bgailer at gmail.com (bob gailer) Date: Sun, 15 Apr 2012 22:54:43 -0400 Subject: [Tutor] Iterate Suggestion In-Reply-To: References: Message-ID: <4F8B89F3.7040606@gmail.com> On 4/14/2012 11:27 AM, Tom Tucker wrote: > > Hello all. Any suggestions how I could easily iterate over a list and > print the output 3 across (when possible)? One method I was > considering was removing the recently printed item from the list, > checking list length, etc. Based on the remaining length of the list > I would then print X across. Yah? Is their and easier approach I might > be overlooking? > > > For example... > > mylist = ['serverA', 'serverB', 'serverC', 'serverD',' serverE', > 'serverF', 'serverG'] > > > Desired Output > ============ > serverA serverB serverC > serverD serverE serverF > serverG print '\n'.join(' '.join(mylist[i:i+3]) for i in range(0,len(mylist),3)) -- Bob Gailer 919-636-4239 Chapel Hill NC From syedzaidi85 at hotmail.co.uk Mon Apr 16 06:59:19 2012 From: syedzaidi85 at hotmail.co.uk (syed zaidi) Date: Mon, 16 Apr 2012 05:59:19 +0100 Subject: [Tutor] Help with regular expression In-Reply-To: <4F8ADA11.6020502@pearwood.info> References: , , , , <4F8A8880.1090007@pearwood.info>, , <4F8ADA11.6020502@pearwood.info> Message-ID: Thanks for the help I need the whole line starting from 'D' but in seperate columns.like KO, EC, Gene ID, Enzyme Name etc > Date: Mon, 16 Apr 2012 00:24:17 +1000 > From: steve at pearwood.info > To: tutor at python.org > Subject: Re: [Tutor] Help with regular expression > > syed zaidi wrote: > > Dear Steve,Tutor doesn't allow attachment of huge files. I am attaching > > the files I am taking as input, code and the output CSV file. I hope then > > you would be able to help me. DOT keg files open in file viewer, you can > > also view them in python. The CSV file is the desired output file. > > > There is no need to send four files when one will do. Also no need to send a > file with multiple thousands of lines long when a dozen or so lines should be > sufficient. > > It would also help if you told us what the fields in the file should be > called. You are probably familiar with them, but we aren't. > > Since I don't know what the fields are called, I'm going to just make up some > names. > > def parse_d_line(line): > # Expects a line like this: > # D SBG_0147 aceE; xxx xxx\tK00163 xxx xxx [EC:1.2.4.1] > a, b = line.split('\t') # split on tab character > c, d = a.split(';') > letter, sbg_code, other_code = c.split() > compound1 = d.strip() > words = b.split() > k_code = words[0] > ec = words[-1] > compound2 = " ".join(words[1:-1]) > return (letter, sbg_code, other_code, compound1, k_code, compound2, ec) > > > kegfile = open('something.keg') > # skip lines until a bare exclamation mark > for line in kegfile: > if line.strip() == '!': > break > > # analyse D lines only, skipping all others > for line in kegfile: > if line.startswith('D'): > print(parse_d_line(dline)) > elif line.strip() == '!': > break # stop processing > > > You will notice I don't use regular expressions in this. > > Some people, when confronted with a problem, think "I know, > I'll use regular expressions." Now they have two problems. > -- Jamie Zawinski > > > > > -- > Steven > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Mon Apr 16 08:55:29 2012 From: __peter__ at web.de (Peter Otten) Date: Mon, 16 Apr 2012 08:55:29 +0200 Subject: [Tutor] Iterate Suggestion References: Message-ID: Tom Tucker wrote: > Hello all. Any suggestions how I could easily iterate over a list and > print the output 3 across (when possible)? One method I was considering > was removing the recently printed item from the list, checking list > length, > etc. Based on the remaining length of the list I would then print X > across. Yah? Is their and easier approach I might be overlooking? > > > For example... > > mylist = ['serverA', 'serverB', 'serverC', 'serverD',' serverE', > 'serverF', 'serverG'] > > > Desired Output > ============ > serverA serverB serverC > serverD serverE serverF > serverG Here's another approach that works with arbitrary iterables, not just lists: >>> from itertools import islice >>> def chunks(items, n, rowtype=tuple): ... items = iter(items) ... while True: ... row = rowtype(islice(items, n)) ... if not row: break ... yield row ... >>> for row in chunks(range(7), 3): ... print row ... (0, 1, 2) (3, 4, 5) (6,) >>> mylist = ["server" + c for c in "ABCDEFG"] >>> for row in chunks(mylist, 3, " ".join): ... print row ... serverA serverB serverC serverD serverE serverF serverG From bgailer at gmail.com Mon Apr 16 15:15:06 2012 From: bgailer at gmail.com (bob gailer) Date: Mon, 16 Apr 2012 09:15:06 -0400 Subject: [Tutor] Iterate Suggestion In-Reply-To: <4F8B89F3.7040606@gmail.com> References: <4F8B89F3.7040606@gmail.com> Message-ID: <4F8C1B5A.2010308@gmail.com> On 4/15/2012 10:54 PM, bob gailer wrote: > On 4/14/2012 11:27 AM, Tom Tucker wrote: >> >> Hello all. Any suggestions how I could easily iterate over a list >> and print the output 3 across (when possible)? One method I was >> considering was removing the recently printed item from the list, >> checking list length, etc. Based on the remaining length of the list >> I would then print X across. Yah? Is their and easier approach I >> might be overlooking? >> >> >> For example... >> >> mylist = ['serverA', 'serverB', 'serverC', 'serverD',' serverE', >> 'serverF', 'serverG'] >> >> >> Desired Output >> ============ >> serverA serverB serverC >> serverD serverE serverF >> serverG > I amend my prior solution to add a constant for the # of columns COLS = 3 > print '\n'.join(' '.join(mylist[i:i+COLS]) for i in > range(0,len(mylist),COLS)) > -- Bob Gailer 919-636-4239 Chapel Hill NC From suryak at live.com Mon Apr 16 17:11:56 2012 From: suryak at live.com (Surya K) Date: Mon, 16 Apr 2012 20:41:56 +0530 Subject: [Tutor] How to interact with users on IRC using Python Message-ID: Actually, I am writing a small IRC bot for a game (A Multiplayer one). This how my code looks. (I this code, I am just trying to read from IRC client and send a message to it..) import sysimport socketimport string HOST="irc.freenode.net"PORT=6667NICK="MyBot"IDENT="Mybot"REALNAME="Python"readbuffer="" s=socket.socket( )s.connect((HOST, PORT))s.send("NICK %s\r\n" % NICK)s.send("USER %s %s bla :%s\r\n" % (IDENT, HOST, REALNAME))s.send("JOIN ##MyChannel\n") while 1: readbuffer=readbuffer+s.recv(1024) print readbuffer s.send("text:") .... # MY Code goes like this. Actually, I am not even aware of IRC commands.. so I thought to take some help to carry on This is what I require: As my game is quite simple, I just need to transfer a small string from each player to another. My game will have a two players.. so, Each user will join my ##myExampleChannel.Say, a player (or a IRC user) "p1" wants to play with "p2". They simply have to exchange private messages from each other. So, what IRC commands should I use and how do I typically implement them? Let me put the above this way: How do I create a small IRC program which can send and receive private messages from users? Thanks for reading! Hope you help me. -------------- next part -------------- An HTML attachment was scrubbed... URL: From sam at pognet.org.uk Mon Apr 16 19:07:30 2012 From: sam at pognet.org.uk (Samuel Toogood) Date: Mon, 16 Apr 2012 18:07:30 +0100 Subject: [Tutor] How to interact with users on IRC using Python In-Reply-To: References: Message-ID: <4F8C51D2.8020202@pognet.org.uk> On 16/04/12 16:11, Surya K wrote: > Actually, I am writing a small IRC bot for a game (A Multiplayer one). > > > This how my code looks. (I this code, I am just trying to read from IRC > client and send a message to it..) > > import sys > > import socket > > import string > > > HOST="irc.freenode.net" > > PORT=6667 > > NICK="MyBot" > > IDENT="Mybot" > > REALNAME="Python" > > readbuffer="" > > > s=socket.socket( ) > > s.connect((HOST, PORT)) > > s.send("NICK %s\r\n" % NICK) > > s.send("USER %s %s bla :%s\r\n" % (IDENT, HOST, REALNAME)) > > s.send("JOIN ##MyChannel\n") > > > while 1: > > readbuffer=readbuffer+s.recv(1024) > > print readbuffer > > s.send("text:") > > .... # MY Code goes like this. > > > Actually, I am not even aware of IRC commands.. so I thought to take > some help to carry on > > > This is what I require: > > As my game is quite simple, I just need to transfer a small string from > each player to another. > > My game will have a two players.. so, Each user will join my > ##myExampleChannel. > Say, a player (or a IRC user) "p1" wants to play with "p2". They simply > have to exchange private messages from each other. > > So, what IRC commands should I use and how do I typically implement them? > > > Let me put the above this way: > > How do I create a small IRC program which can send and receive private > messages from users? > > > > Thanks for reading! Hope you help me. Does http://www.devshed.com/c/a/Python/Python-and-IRC/ help at all? Kind regards, Sam From wprins at gmail.com Mon Apr 16 19:11:15 2012 From: wprins at gmail.com (Walter Prins) Date: Mon, 16 Apr 2012 19:11:15 +0200 Subject: [Tutor] How to interact with users on IRC using Python In-Reply-To: References: Message-ID: Hi, On 16 April 2012 17:11, Surya K wrote: > Actually, I am writing a small IRC bot for a game (A Multiplayer one). > > This how my code looks. (I this code, I am just trying to read from IRC > client and send a message to it..) > > > s.send("NICK %s\r\n" % NICK) > > s.send("USER %s %s bla :%s\r\n" % (IDENT, HOST, REALNAME)) > > s.send("JOIN ##MyChannel\n") > > > while 1: > > readbuffer=readbuffer+s.recv(1024) > > print readbuffer > > s.send("text:") > > .... # MY Code goes like this. > > Am I right in thinking this is based on the code here? : http://oreilly.com/pub/h/1968 Does it work for you? It appears to demonstrate the basic ability to ping/pong a message. Actually, I am not even aware of IRC commands.. so I thought to take some > help to carry on > OK its many years since I've used IRC, but anyhow, I suggest you learn how IRC works and what commands you can use -- Here's a link from a google search: http://www.ircbeginner.com/ircinfo/ircc-commands.html > This is what I require: > > As my game is quite simple, I just need to transfer a small string from > each player to another. > > My game will have a two players.. so, Each user will join my > ##myExampleChannel. > Say, a player (or a IRC user) "p1" wants to play with "p2". They simply > have to exchange private messages from each other. > > So, what IRC commands should I use and how do I typically implement them? > Probably the "/join" an the "/msg" commands. As for how to implement it, I found the following tutorials/pages from a google search: http://www.devshed.com/c/a/Python/Python-and-IRC/ http://www.devshed.com/c/a/Python/Basic-IRC-Tasks/ http://www.devshed.com/c/a/Python/IRC-on-a-Higher-Level/ http://www.devshed.com/c/a/Python/IRC-on-a-Higher-Level-Continued/ http://www.devshed.com/c/a/Python/IRC-on-a-Higher-Level-Concluded/ Also see this library which turned up in the same search: http://python-irclib.sourceforge.net/ Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From punchagan at gmail.com Mon Apr 16 19:21:16 2012 From: punchagan at gmail.com (Puneeth Chaganti) Date: Mon, 16 Apr 2012 22:51:16 +0530 Subject: [Tutor] How to interact with users on IRC using Python In-Reply-To: References: Message-ID: On Mon, Apr 16, 2012 at 8:41 PM, Surya K wrote: [snip] > So, what IRC commands should I use and how do I typically implement them? I found this useful -- http://www.irchelp.org/irchelp/rfc/rfc.html From 0x657573 at googlemail.com Tue Apr 17 10:44:23 2012 From: 0x657573 at googlemail.com (Tadeus (Eus) Prastowo) Date: Tue, 17 Apr 2012 15:44:23 +0700 Subject: [Tutor] Unwanted "close failed in file object destructor" after broken pipe Message-ID: Hi! First, generate a file named "data.txt" as follows: -- 8< ---------------------------------- for i in range(1,100): print '.' * 80 -- 8< ---------------------------------- After that, save the following snippet as "test.py" in the directory containing "data.txt": -- 8< ---------------------------------- import sys object_file = open('data.txt', 'rb') for line in object_file: sys.stdout.write(line) -- 8< ---------------------------------- Finally, run the following Unix shell command in the containing directory: -- 8< ---------------------------------- python test.py | head -- 8< ---------------------------------- At the end of printing some lines, the following error is reported: -- 8< ---------------------------------- close failed in file object destructor: Error in sys.excepthook: Original exception was: -- 8< ---------------------------------- How to suppress that unwanted error message? After all doing something like the following does not give such an error: -- 8< ---------------------------------- cat data.txt | head -- 8< ---------------------------------- Thank you very much. -- Best regards, Eus (FSF member #4445) From evert.rol at gmail.com Tue Apr 17 11:14:21 2012 From: evert.rol at gmail.com (Evert Rol) Date: Tue, 17 Apr 2012 11:14:21 +0200 Subject: [Tutor] Unwanted "close failed in file object destructor" after broken pipe In-Reply-To: References: Message-ID: > First, generate a file named "data.txt" as follows: > > -- 8< ---------------------------------- > for i in range(1,100): > print '.' * 80 > -- 8< ---------------------------------- > > After that, save the following snippet as "test.py" in the directory > containing "data.txt": > > -- 8< ---------------------------------- > import sys > > object_file = open('data.txt', 'rb') > > for line in object_file: > sys.stdout.write(line) > -- 8< ---------------------------------- > > Finally, run the following Unix shell command in the containing directory: > > -- 8< ---------------------------------- > python test.py | head > -- 8< ---------------------------------- > > At the end of printing some lines, the following error is reported: > > -- 8< ---------------------------------- > close failed in file object destructor: > Error in sys.excepthook: > > Original exception was: > -- 8< ---------------------------------- > > How to suppress that unwanted error message? It's a problem with how the Python interpreter handles a broken pipe while shutting down. I.e., head terminates before Python has cleaned up the IO. A search shows it as a bug report here: http://bugs.python.org/issue11380, and a good explanation here http://www.velocityreviews.com/forums/t749747-help-with-a-piping-error.html The latter suggest using sys.stdout.flush() at the end. It may still throw an exception, but it then throws the proper exception (IOError: [Errno 32] Broken pipe), which you can wrap in a try-except block. In fact, with sys.stdout.flush(), I don't see any error. Note that on my Mac, btw, I don't have the problem (with or without the flush): possibly that either head or IO in general is behaving slightly different there. Hope that helps, Evert > After all doing something like the following does not give such an error: > > -- 8< ---------------------------------- > cat data.txt | head > -- 8< ---------------------------------- > Thank you very much. > > -- > Best regards, > Eus (FSF member #4445) > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From existentialleo at gmail.com Tue Apr 17 20:23:58 2012 From: existentialleo at gmail.com (leo degon) Date: Tue, 17 Apr 2012 14:23:58 -0400 Subject: [Tutor] Game of python, help please. In-Reply-To: <4F844738.1020304@gmail.com> References: <4F839BED.4040704@gmail.com> <4F83A17A.5020805@davea.name> <4F844738.1020304@gmail.com> Message-ID: Ok so I've done a bit of work on the program and rewrote it. I tried to take everyones advice. I've used more functions, I've made it so that it is a list of lists each containing an integer instead of another list with a single entry. Im am having problems thinking of how to simply and elegantly calculate the surrounding cells.I could brute force it as i did originally, but I'd like some pointers of how to avoid that. As of now, the script is finished for that 'small' detail. I have it so that instead of actually calculating the surrounding cells, that functions says that all the cells on the board are surrounding by three cells. Therefore setting the entire board alive after the turn zero. I am still trying to include three different versions of the boundry conditions. Boundary conditions, what happens when a cell on the edge of the board tries to calculate the number of surrounding live cells. Dead- Those nonexistent cells add nothing. Live-Those nonexistent cells add one per cell. So add 5 to the corners, and one to edges. Bound- The dimensions are bound. So you get to the end and loop around. the script follows #leoslife.py # John Conways Game of Life. plan='''displays: the text of the game of life for a set number of X x Y for a set of R turns. [-][-][-][-][-] [-][-][-][-][-] [-][-][-][-][-] [-][-][-][-][-] [-][-][-][-][-] Get X,Y,T, Initial Values, Boundry conditions Create a data space X x Y Assign initial value print initial value and the text' initial value' do while turns3): return(0) else: if space[i][j]==1: return(1) else: return(0) #get x,y,t initial value, boundry condition x=getnum('How many rows?') y=getnum('How many columns?') t=getnum('How many turns?') #get boundry conditions boundry=0 while boundry not in ("b","d","l"): boundry=input("Press 'b' for bound dimenions, 'd' for dead boundry, or 'l' for live boundry. : ") #get initial set up of space initial=0 while initial not in ('r','c','g','e'): initial=input("Press 'r' for random intitial set up, 'c' for a checker board pattern, 'g' for a single glider, or 'e' for a pattern that repeats infinitely. : ") if initial=='g': if x<5: x=5 if y<5: y=5 if initial=='e': if x<6: x=6 if y<6: y=6 #create space space = [] for i in range(x): space.append([]) for j in range(y): space[i].append(0) #set intital distribution if initial=='r': for i in range(x): for j in range(y): space[i].__setitem__(j,random.randint(0,1)) elif initial=='c': for i in range(x): for j in range(y): if (i+j)%2==0: space[i].__setitem__(j,1) else: space[i].__setitem__(j,0) elif initial=='g': space[1].__setitem__(2,1) space[2].__setitem__(3,1) space[3].__setitem__(1,1) space[3].__setitem__(2,1) space[3].__setitem__(3,1) elif initial=='e': space[2].__setitem__(2,1) space[2].__setitem__(3,1) space[2].__setitem__(4,1) space[3].__setitem__(1,1) space[3].__setitem__(2,1) space[3].__setitem__(3,1) #show initial conditions of board on turn 0 print("-------Initial Board-------\n") printset(space) for turn in range(t): #Create new empty space new=[] for i in range(x): new.append([]) for j in range(y): new[i].append(0) #rewrite each space for i in range(x): for j in range(y): surronding=findsurronding(space,i,j,boundry) mortality=determinelife(surronding,space,i,j) new[i][j]=mortality space=new[:] print('-------Turn %s--------' %(str(turn+1))) printset(space) print("This is the end ") On Tue, Apr 10, 2012 at 10:44 AM, bob gailer wrote: > On 4/9/2012 10:56 PM, Dave Angel wrote: > >> On 04/09/2012 10:33 PM, bob gailer wrote: >> >>> On 4/9/2012 2:26 AM, leo degon wrote: >>> >>>> Hello all, Im trying to learn python and programming in my free time, >>>> and I'm trying to do a little personal project to trying and gain >>>> some skills. Im trying to do version of John conways game of life. I >>>> have a working version of the game. Written for 3.2.2 on a mac to be >>>> accessed through terminal. >>>> >>> >>> These nested loops >>> >>>> for i in range(X): >>>> SPACE.append([]) >>>> for j in range(Y): >>>> SPACE[i].append([0]) >>>> >>>> can be replaced with: >>> >>> space = [0]*y]*x >>> >>> not counting the typo, that's the trap I was warning about. If he does >> NOT replace the individual cells with zeroes and ones, this is wrong. >> You pointed that out. But it's also wrong for the rows, as you only >> have one row here, duplicated x times. >> > OOPS - what comes of trying to be creative while tired. Sorry and thanks > for pointing out my error. > > >> > > -- > Bob Gailer > 919-636-4239 > Chapel Hill NC > > -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: leoslife.py Type: application/octet-stream Size: 3678 bytes Desc: not available URL: From alan.gauld at btinternet.com Tue Apr 17 21:14:58 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 17 Apr 2012 20:14:58 +0100 Subject: [Tutor] Game of python, help please. In-Reply-To: References: <4F839BED.4040704@gmail.com> <4F83A17A.5020805@davea.name> <4F844738.1020304@gmail.com> Message-ID: On 17/04/12 19:23, leo degon wrote: > Ok so I've done a bit of work on the program and rewrote it. I tried to > take everyones advice. I've used more functions, I've made it so that it > is a list of lists each containing an integer instead of another list > with a single entry. It still looks too complicated to me. > #set intital distribution > > if initial=='r': > for i in range(x): > for j in range(y): > space[i].__setitem__(j,random.randint(0,1)) What's with the __setitem__ stuff? You should never normally need to call that directly. I would expect something like for i in range(x): for j in range(y): space[i][j] = randint(0,1) Or, using list comprehensions: for i in range(x): space[i] = [randint(0,1) for j in range(y)] Or even: space = [[randint(0,1) for j in range(y)] for i in range(x)] Which, for x,y = 3,4 gives a structure like: >>> space [[1, 0, 0, 0], [1, 0, 1, 1], [0, 1, 1, 0]] >>> > elif initial=='c': > for i in range(x): > for j in range(y): > if (i+j)%2==0: > space[i].__setitem__(j,1) Again I'd just use space[i][j] = 1 HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From existentialleo at gmail.com Wed Apr 18 03:05:15 2012 From: existentialleo at gmail.com (leo degon) Date: Tue, 17 Apr 2012 21:05:15 -0400 Subject: [Tutor] Game of python, help please. In-Reply-To: References: <4F839BED.4040704@gmail.com> <4F83A17A.5020805@davea.name> <4F844738.1020304@gmail.com> Message-ID: Ok that was simple change. Dont know why but there was a small error preventing that from working before. But the problem is with the creating findsurrounding function On Tue, Apr 17, 2012 at 3:14 PM, Alan Gauld wrote: > On 17/04/12 19:23, leo degon wrote: > >> Ok so I've done a bit of work on the program and rewrote it. I tried to >> take everyones advice. I've used more functions, I've made it so that it >> is a list of lists each containing an integer instead of another list >> with a single entry. >> > > It still looks too complicated to me. > > > #set intital distribution >> >> if initial=='r': >> for i in range(x): >> for j in range(y): >> space[i].__setitem__(j,random.**randint(0,1)) >> > > What's with the __setitem__ stuff? You should never normally need to call > that directly. I would expect something like > > > for i in range(x): > for j in range(y): > space[i][j] = randint(0,1) > > Or, using list comprehensions: > > for i in range(x): > space[i] = [randint(0,1) for j in range(y)] > > Or even: > > space = [[randint(0,1) for j in range(y)] for i in range(x)] > > > Which, for x,y = 3,4 gives a structure like: > > >>> space > [[1, 0, 0, 0], [1, 0, 1, 1], [0, 1, 1, 0]] > > >>> > > > elif initial=='c': >> for i in range(x): >> for j in range(y): >> if (i+j)%2==0: >> space[i].__setitem__(j,1) >> > > Again I'd just use > > space[i][j] = 1 > > HTH > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Wed Apr 18 18:53:33 2012 From: bgailer at gmail.com (bob gailer) Date: Wed, 18 Apr 2012 12:53:33 -0400 Subject: [Tutor] Game of python, help please. In-Reply-To: References: <4F839BED.4040704@gmail.com> <4F83A17A.5020805@davea.name> <4F844738.1020304@gmail.com> Message-ID: <4F8EF18D.7050100@gmail.com> On 4/17/2012 2:23 PM, leo degon wrote: > Ok so I've done a bit of work on the program and rewrote it. I tried to take everyones advice. I've used more functions, > I've made it so that it is a list of lists each containing an integer instead of another list with a single entry. I'm glad to see you using some of my ideas! > Im am having problems thinking of how to simply and elegantly calculate the surrounding cells. > I could brute force it as i did originally, but I'd like some pointers of how to avoid that. > As of now, the script is finished for that 'small' detail. I have it so that instead of actually calculating the surrounding cells, > that functions says that all the cells on the board are surrounding by three cells. > Therefore setting the entire board alive after the turn zero. I am still trying to include three different versions of the bounadry conditions. >Boundary conditions, what happens when a cell on the edge of the board tries to calculate the number of surrounding live cells. > Dead- Those nonexistent cells add nothing. > Live-Those nonexistent cells add one per cell. So add 5 to the corners, and one to edges. > Bound- The dimensions are bound. So you get to the end and loop around. [snip] I again recommend you add extra rows and columns around the space so you always use one formula for surround. For dead initialize the extra cells to 0 For live initialize the extra cells to 1 For bound - every time you change a boundary cell make the same change to the corresponding extra cell. I hope that makes sense. Does it? Also recall my condensed way of summing surrounding cells. I realize I made a mistake in my original proposal - in that it counted the cell itself as well as the neighbors. Easy to fix. Originally I suggested: for r in range(1,x+1): for c in range1,(y+1): surrounding = sum([sum(space[r+z][c-1:c+2]) for z in(-1,0,1)]) New suggestion: def determinelife(surronding,space,i,j): return sum(space[i-1][j-1:j+2]) + sum(space[i][j-1:j+2:2]) + sum(space[i+1][j-1:j+2]) HTH -- Bob Gailer 919-636-4239 Chapel Hill NC From existentialleo at gmail.com Wed Apr 18 19:06:39 2012 From: existentialleo at gmail.com (leo degon) Date: Wed, 18 Apr 2012 13:06:39 -0400 Subject: [Tutor] Game of python, help please. In-Reply-To: <4F8EF18D.7050100@gmail.com> References: <4F839BED.4040704@gmail.com> <4F83A17A.5020805@davea.name> <4F844738.1020304@gmail.com> <4F8EF18D.7050100@gmail.com> Message-ID: I actually just finished it, without the extra cells. I used a combiniation of two functions and a some exception handling to do so. Here is the script. #leoslife.py # John Conways Game of Life. plan='''displays: the text of the game of life for a set number of X x Y for a set of R turns. [-][-][-][-][-] [-][-][-][-][-] [-][-][-][-][-] [-][-][-][-][-] [-][-][-][-][-] Get X,Y,T, Initial Values, Boundry conditions Create a data space X x Y Assign initial value print initial value and the text' initial value' do while turns3): return(0) else: if space[i][j]==1: return(1) else: return(0) #get x,y,t initial value, boundry condition x=getnum('How many rows?') y=getnum('How many columns?') t=getnum('How many turns?') #get boundry conditions boundry=0 while boundry not in ("b","d","l"): boundry=input("Press 'b' for bound dimenions, 'd' for dead boundry, or 'l' for live boundry. : ") #get initial set up of space initial=0 while initial not in ('r','c','g','e'): initial=input("Press 'r' for random intitial set up, 'c' for a checker board pattern, 'g' for a single glider, or 'e' for a pattern that repeats infinitely. : ") if initial=='g': if x<5: x=5 if y<5: y=5 if initial=='e': if x<6: x=6 if y<6: y=6 #create space space = [] for i in range(x): space.append([]) for j in range(y): space[i].append(0) #set intital distribution if initial=='r': for i in range(x): for j in range(y): space[i][j]=random.randint(0,1) elif initial=='c': for i in range(x): for j in range(y): if (i+j)%2==0: space[i][j]=1 else: space[i][j]=0 elif initial=='g': space[1][2]=1 space[2][3]=1 space[3][1]=1 space[3][2]=1 space[3][3]=1 elif initial=='e': space[2][2]=1 space[2][3]=1 space[2][4]=1 space[3][1]=1 space[3][2]=1 space[3][3]=1 #show initial conditions of board on turn 0 print("---------Turn 0---------\n") printset(space) for turn in range(t): #Create new empty space new=[] for i in range(x): new.append([]) for j in range(y): new[i].append(0) #rewrite each space for i in range(x): for j in range(y): surrounding=findsurrounding(space,i,j,boundry,basesurrounding(space,i,j)) mortality=determinelife(surrounding,space,i,j) new[i][j]=mortality space=new[:] print('-------Turn %s--------' %(str(turn+1))) printset(space) print("This is the end ") On Wed, Apr 18, 2012 at 12:53 PM, bob gailer wrote: > On 4/17/2012 2:23 PM, leo degon wrote: > > > Ok so I've done a bit of work on the program and rewrote it. I tried to > take everyones advice. I've used more functions, > > I've made it so that it is a list of lists each containing an integer > instead of another list with a single entry. > > I'm glad to see you using some of my ideas! > > > > Im am having problems thinking of how to simply and elegantly calculate > the surrounding cells. > > I could brute force it as i did originally, but I'd like some pointers > of how to avoid that. > > As of now, the script is finished for that 'small' detail. I have it so > that instead of actually calculating the surrounding cells, > > that functions says that all the cells on the board are surrounding by > three cells. > > Therefore setting the entire board alive after the turn zero. I am still > trying to include three different versions of the bounadry conditions. > > >Boundary conditions, what happens when a cell on the edge of the board > tries to calculate the number of surrounding live cells. > > Dead- Those nonexistent cells add nothing. > > Live-Those nonexistent cells add one per cell. So add 5 to the corners, > and one to edges. > > Bound- The dimensions are bound. So you get to the end and loop around. > > [snip] > > I again recommend you add extra rows and columns around the space so you > always use one formula for surround. > > For dead initialize the extra cells to 0 > For live initialize the extra cells to 1 > For bound - every time you change a boundary cell make the same change to > the corresponding extra cell. > > I hope that makes sense. Does it? > > Also recall my condensed way of summing surrounding cells. I realize I > made a mistake in my original proposal - in that it counted the cell itself > as well as the neighbors. Easy to fix. > > Originally I suggested: > > for r in range(1,x+1): > for c in range1,(y+1): > surrounding = sum([sum(space[r+z][c-1:c+2]) for z in(-1,0,1)]) > > New suggestion: > def determinelife(surronding,**space,i,j): > return sum(space[i-1][j-1:j+2]) + sum(space[i][j-1:j+2:2]) + > sum(space[i+1][j-1:j+2]) > > HTH > > > > -- > Bob Gailer > 919-636-4239 > Chapel Hill NC > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From missive at hotmail.com Thu Apr 19 01:42:10 2012 From: missive at hotmail.com (Lee Harr) Date: Thu, 19 Apr 2012 04:12:10 +0430 Subject: [Tutor] How to interact with users on IRC using Python Message-ID: > How do I create a small IRC program which can send and receive private > messages from users? I created a multiplayer game that can create a standalone server like a MUD, or communicate over IRC, or both (I think) acting as a gateway between the two. It uses Twisted, which some find arcane, but it is very cool once you get the hang of it. I have never deployed the IRC bot (beyond basic testing) as I was not sure about acceptable use of bots on the various servers. Also I am not certain of the security of the whole thing. The code may be of use to you though: http://acromania.googlecode.com/ From glez_b at comunidad.unam.mx Thu Apr 19 02:52:54 2012 From: glez_b at comunidad.unam.mx (Boris Vladimir Comi) Date: Thu, 19 Apr 2012 00:52:54 +0000 Subject: [Tutor] Tutor Digest, Vol 98, Issue 51 In-Reply-To: References: Message-ID: Hi I have the following code that calculates the position and the value of each pixel of the image: def scm(directory): import os; fs = os.listdir(directory); # now fs will be a list of all the files in directory from edu.wisc.ssec.mcidas import AreaFile; for name in fs: print "Reading in:",name af = AreaFile(directory+"/"+name); ad = af.getAreaDirectory(); count = 0; data = af.getFloatData(); # now look through the first band y count pixels # MCS detected when his temperature infrared (TIR) is < 219 K for i in xrange(ad.getLines()): for j in xrange(ad.getElements()): if 552 < i < 900 and 244 < j < 572: if (data[0][i][j]) > 206 and (data[0][i][j]) < 208: print i, j, data[0][i][j]; Where in the code I can add the condition: to only print those values ??(206-208) to be maintained for three hours or more Boris Vladimir Comi Gonzalez Universidad Nacional Aut?noma de M?xico Grupo de Tormentas Convecivas -------------- next part -------------- An HTML attachment was scrubbed... URL: From lina.lastname at gmail.com Thu Apr 19 05:11:15 2012 From: lina.lastname at gmail.com (lina) Date: Thu, 19 Apr 2012 11:11:15 +0800 Subject: [Tutor] How to examine the following problem Message-ID: <4F8F8253.3000006@gmail.com> Hi, I meet a problem, mainly some error waring: CmdException Exception in Tk callback Function: at 0x46fdde8> (type: ) Args: () Traceback (innermost last): File "/usr/lib/python2.7/dist-packages/Pmw/Pmw_1_3/lib/PmwBase.py", line 1747, in __call__ return apply(self.func, args) File "/usr/lib/python2.7/dist-packages/Pmw/Pmw_1_3/lib/PmwDialog.py", line 153, in command=lambda self=self, name=name: self._doCommand(name)) File "/usr/lib/python2.7/dist-packages/Pmw/Pmw_1_3/lib/PmwDialog.py", line 132, in _doCommand return command(name) File "/usr/local/bin/modules/pmg_tk/startup/dssp_stride_pymol.py", line 864, in execute rtn = self.runDSSP() File "/usr/local/bin/modules/pmg_tk/startup/dssp_stride_pymol.py", line 533, in runDSSP sse_sel_name = self.selectSSE(sse) File "/usr/local/bin/modules/pmg_tk/startup/dssp_stride_pymol.py", line 719, in selectSSE cmd.select(sel_name_chn, sel_expr) File "/usr/local/bin/modules/pymol/selecting.py", line 118, in select if _self._raising(r,_self): raise pymol.CmdException CmdException: The code I was downloading from http://www.biotec.tu-dresden.de/~hongboz/dssp_pymol/pymol_script/dssp_stride_pymol.py I am not experienced to fix it. Thanks ahead for your suggestions about how to solve this problem. From where to examine. Best regards, From alan.gauld at btinternet.com Thu Apr 19 09:27:08 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 19 Apr 2012 08:27:08 +0100 Subject: [Tutor] How to examine the following problem In-Reply-To: <4F8F8253.3000006@gmail.com> References: <4F8F8253.3000006@gmail.com> Message-ID: On 19/04/12 04:11, lina wrote: > I meet a problem, mainly some error waring: > > CmdException Exception in Tk callback > Function: at 0x46fdde8> (type: ) > Args: () > Traceback (innermost last): > File "/usr/lib/python2.7/dist-packages/Pmw/Pmw_1_3/lib/PmwBase.py", line This tells us the problem originates in a PMW file > File "/usr/local/bin/modules/pymol/selecting.py", line 118, in select And this says its from pymol code. > The code I was downloading from > http://www.biotec.tu-dresden.de/~hongboz/dssp_pymol/pymol_script/dssp_stride_pymol.py This list is for problems with the Python language and its standard library. We are not equipped to support all of the 3rd party modules out there so unless you are very lucky and somebody on the list uses pymol and can help, you will be better off asking for help on a pymol forum, or by contacting the authors. If you do that, one thing that might help is to provide information about the OS you are using, the Python version, and how you are running the code. For example, you have not provided any clues above as to what actual python code you were trying to run which caused the error message. The more context you can provide the easier it will be for the pymol experts to see what's gone wrong. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From lina.lastname at gmail.com Thu Apr 19 10:17:12 2012 From: lina.lastname at gmail.com (lina) Date: Thu, 19 Apr 2012 16:17:12 +0800 Subject: [Tutor] How to examine the following problem In-Reply-To: References: <4F8F8253.3000006@gmail.com> Message-ID: <4F8FCA08.2090401@gmail.com> On Thursday 19,April,2012 03:27 PM, Alan Gauld wrote: > On 19/04/12 04:11, lina wrote: > >> I meet a problem, mainly some error waring: >> >> CmdException Exception in Tk callback >> Function: at 0x46fdde8> (type: ) >> Args: () >> Traceback (innermost last): >> File "/usr/lib/python2.7/dist-packages/Pmw/Pmw_1_3/lib/PmwBase.py", line > > This tells us the problem originates in a PMW file Seems I have not update PMW recently. > >> File "/usr/local/bin/modules/pymol/selecting.py", line 118, in select > > And this says its from pymol code. > >> The code I was downloading from >> http://www.biotec.tu-dresden.de/~hongboz/dssp_pymol/pymol_script/dssp_stride_pymol.py >> > > This list is for problems with the Python language and its standard > library. > > We are not equipped to support all of the 3rd party modules out there so > unless you are very lucky and somebody on the list uses pymol and can > help, you will be better off asking for help on a pymol forum, or by > contacting the authors. I have asked on pymol list. none response. I also sent email to the author, none feedback yet. haha ... get my luck is a bit late? Well, I have some faith about this list. > > If you do that, one thing that might help is to provide information > about the OS you are using, the Python version, and how you are running > the code. For example, you have not provided clues above as to what > actual python code you were trying to run which caused the error > message. The more context you can provide the easier it will be for the > pymol experts to see what's gone wrong. I installed 2.6, 2.7, 3.1, 3.2, 3.2mu But in this situation it uses the 2.7. I use debian. I guess something become incompatible using his plugin. > Thanks, From suryak at live.com Thu Apr 19 12:54:49 2012 From: suryak at live.com (Surya K) Date: Thu, 19 Apr 2012 16:24:49 +0530 Subject: [Tutor] how to select a player to play first on a multiplayer game which runs on IRC Message-ID: I am writing tic tac toe game which runs on IRC (i am using freenode now). Each player will be a channel member. So, players send private messages between each other to play game. This sounds fine but I need the below things to get done, but I don't know how to do them.. How my game works: Each player will have my program (tictactoe.exe). So, each player has to enter a unique Nick Name for them and a their's friend's nick name to play : ## Now, I want to know whether the player is on the channel or not. for that I need a list of nick's on the channel. How to get them? The biggest problem is here: ## How to select a player to play first... ??? How do I get this done? Help me!!! -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Thu Apr 19 13:24:33 2012 From: d at davea.name (Dave Angel) Date: Thu, 19 Apr 2012 07:24:33 -0400 Subject: [Tutor] how to select a player to play first on a multiplayer game which runs on IRC In-Reply-To: References: Message-ID: <4F8FF5F1.3000402@davea.name> On 04/19/2012 06:54 AM, Surya K wrote: > I am writing tic tac toe game which runs on IRC (i am using freenode now). > Each player will be a channel member. So, players send private messages between each other to play game. This sounds fine but I need the below things to get done, but I don't know how to do them.. > How my game works: > Each player will have my program (tictactoe.exe). > So, each player has to enter a unique Nick Name for them and a their's friend's nick name to play : > ## Now, I want to know whether the player is on the channel or not. for that I need a list of nick's on the channel. How to get them? I can't help there. > The biggest problem is here: > ## How to select a player to play first... ??? How do I get this done? > > In a peer-to-peer connection, there are a number of situations where you have to break symmetry. This is one of them, though not the first. Since you don't have a 3rd party arbiter, the two endpoints have to agree between themselves which of them is to be the arbiter when both sides need to agree on something. Once you've chosen the arbiter, then each decision is made by asking the arbiter. Start by choosing a large "random" number (or guid) at each end. Each sends his own guid along with the two nick-names to propose the new game. One of the guids will be larger, and that machine is the arbiter. The first conflict to be resolved this way is not who goes first, but how you make sure you only have one game between any two endpoints. What happens if more than two players are present, and what happens if more than one of them picks the same nickname? Are you going to permit one of the players to play against two others at the same time, and how will you keep the games straight? You need a connection token for each running game, and that's probably the first time you need an arbiter. The second case is choosing who goes first. The arbiter probably chooses that randomly, and notifies the other player. The third case is how to handle miscommunication. Messages can be lost between the end points, and you may have to reconstruct the state, so both ends get back in synch. Fourth is how to quit. If one player quits, the other might not get notified correctly, so you have to keep the connection token for a while, to aid cleanup. -- DaveA From oberoc at gmail.com Thu Apr 19 15:29:33 2012 From: oberoc at gmail.com (Tino Dai) Date: Thu, 19 Apr 2012 09:29:33 -0400 Subject: [Tutor] Readabilty vs 80 characters Message-ID: Hi! I have a question about style. In PEP-8, it says don't exceed 79 characters, but can this rule ever be trumped by readability? Eg. if someobject.filter(something) \ .filter(somethingreallyreallyreallyreallylong == somethingelsereallyreallylong) \ .filter(othethingreallylongreallyreally == ternarythingreallyreallyreallylong) \ .filter(thirdthingreallylessreallymaybelong == thirdotherthingreallylong) \ .first(): < do something > if someobject.filter(something) \ .filter(somethingreallyreallyreallyreallylong == \ somethingelsereallyreallylong) \ .filter(othethingreallylongreallyreally == \ ternarythingreallyreallyreallylong ) \ .filter(thirdthingreallylessreallymaybelong == \ thirdotherthingreallylong) \ .first(): < do something > The first example is more readable to me but violates the 80 character rule. The second is less readable, but doesn't violate the 80 character rule. Is there a guideline or convention that pythonistas follow about this style case? Thanks, Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: From suryak at live.com Thu Apr 19 15:41:31 2012 From: suryak at live.com (Surya K) Date: Thu, 19 Apr 2012 19:11:31 +0530 Subject: [Tutor] how to select a player to play first on a multiplayer game which runs on IRC In-Reply-To: <4F8FF5F1.3000402@davea.name> References: , <4F8FF5F1.3000402@davea.name> Message-ID: > Date: Thu, 19 Apr 2012 07:24:33 -0400 > From: d at davea.name > To: suryak at live.com > CC: tutor at python.org; bgailer at gmail.com > Subject: Re: [Tutor] how to select a player to play first on a multiplayer game which runs on IRC > > On 04/19/2012 06:54 AM, Surya K wrote: > > I am writing tic tac toe game which runs on IRC (i am using freenode now). > > Each player will be a channel member. So, players send private messages between each other to play game. This sounds fine but I need the below things to get done, but I don't know how to do them.. > > How my game works: > > Each player will have my program (tictactoe.exe). > > So, each player has to enter a unique Nick Name for them and a their's friend's nick name to play : > > ## Now, I want to know whether the player is on the channel or not. for that I need a list of nick's on the channel. How to get them? > I can't help there. > > > The biggest problem is here: > > ## How to select a player to play first... ??? How do I get this done? > > > > > > In a peer-to-peer connection, there are a number of situations where you > have to break symmetry. This is one of them, though not the first. > Since you don't have a 3rd party arbiter, the two endpoints have to > agree between themselves which of them is to be the arbiter when both > sides need to agree on something. Once you've chosen the arbiter, then > each decision is made by asking the arbiter. > > Start by choosing a large "random" number (or guid) at each end. Each > sends his own guid along with the two nick-names to propose the new > game. One of the guids will be larger, and that machine is the arbiter. > > The first conflict to be resolved this way is not who goes first, but > how you make sure you only have one game between any two endpoints. > What happens if more than two players are present, and what happens if > more than one of them picks the same nickname? Are you going to permit > one of the players to play against two others at the same time, and how > will you keep the games straight? You need a connection token for each > running game, and that's probably the first time you need an arbiter. > Actually, as in a IRC channel, each user should have a unique nick name, the problem is resolved.Actually, in this game, the 2 players will have a private chat.. so, there would be no chance that other person will come into picture. Rather that doing all this mess, I want to put a server on Google App Engine and run clients on my PC. But I don't know how!! I have to know Google API for writing GAE app's using python 2.7 Lets say, I have created a server using python 2.7, can you tell me how to run it on GAE ?? (Assuming, I haven't used any google api).. Actually, I don't need any Templates, nice HTML pages on Google App. Its enough to just mention how many peers are connected at that particular instant... can you tell me how to do that?? > The second case is choosing who goes first. The arbiter probably > chooses that randomly, and notifies the other player. The third case is > how to handle miscommunication. Messages can be lost between the end > points, and you may have to reconstruct the state, so both ends get back > in synch. Fourth is how to quit. If one player quits, the other might > not get notified correctly, so you have to keep the connection token for > a while, to aid cleanup. > > > > -- > > DaveA > -------------- next part -------------- An HTML attachment was scrubbed... URL: From wayne at waynewerner.com Thu Apr 19 15:50:39 2012 From: wayne at waynewerner.com (Wayne Werner) Date: Thu, 19 Apr 2012 08:50:39 -0500 (CDT) Subject: [Tutor] Readabilty vs 80 characters In-Reply-To: References: Message-ID: On Thu, 19 Apr 2012, Tino Dai wrote: > Hi! > ? ? ?I have a question about style. In PEP-8, it says > don't exceed 79 characters, but can this rule ever be > trumped by? > readability? PEP 8 is style guidelines, not hard and fast rules or they wouls be syntax errors. But that would just be annoying, so yes, there are cases where you would want to extend... > Eg. > > ? ? ? > ? ? ?if someobject.filter(something) \ > ? ? ? ? ? .filter(somethingreallyreallyreallyreallylong > == somethingelsereallyreallylong) \ > ? ? ? ? ? .filter(othethingreallylongreallyreally == > ternarythingreallyreallyreallylong) \ > ? ? ? ? ? .filter(thirdthingreallylessreallymaybelong == > thirdotherthingreallylong) \ > ? ? ? ? ? .first(): > ? ? ? ? ? < do something > > > ? ? ? if someobject.filter(something) \ > ? ? ? ? ? > .filter(somethingreallyreallyreallyreallylong?== \ > ? ? ? ? ? ? ? ?somethingelsereallyreallylong) \ > ? ? ? ? ? .filter(othethingreallylongreallyreally?== \ > ? ? ? ? ? ? ??ternarythingreallyreallyreallylong?) \ > ? ? ? ? ? .filter(thirdthingreallylessreallymaybelong?== > \ > ? ? ? ? ? ? ? ?thirdotherthingreallylong) \ > ? ? ? ? ? .first(): > ? ? ? ? ? < do something > > > ? ?? > The first example is more readable to me but violates > the 80 character rule. The second is less readable, but > doesn't violate > the 80 character rule. This is exactly what the style guide is meant to help. Regardless of which format you chose here I would tell you that both ways are wrong. The right way is to fix your algorithm (how you solve the problem) so you don't have to have such an insane amount of code on one line. Of course this isn't a hard and fast rule either, but I'd say about 99% of the time a lot of nesting or chaining indicates a broken flow (even if the logic is 100% accurate). > > Is there a guideline or convention that pythonistas > follow about this style case? Refactor! hth, Wayne From ramit.prasad at jpmorgan.com Thu Apr 19 15:47:25 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 19 Apr 2012 13:47:25 +0000 Subject: [Tutor] Readabilty vs 80 characters In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF474092F1128@SCACMX008.exchad.jpmchase.net> > I have a question about style. In PEP-8, it says don't exceed 79 > characters, but can this rule ever be trumped by > readability? > > Eg. > > > if someobject.filter(something) \ > .filter(somethingreallyreallyreallyreallylong == > somethingelsereallyreallylong) \ > .filter(othethingreallylongreallyreally == > ternarythingreallyreallyreallylong) \ > .filter(thirdthingreallylessreallymaybelong == > thirdotherthingreallylong) \ > .first(): > < do something > > > if someobject.filter(something) \ > .filter(somethingreallyreallyreallyreallylong == \ > somethingelsereallyreallylong) \ > .filter(othethingreallylongreallyreally == \ > ternarythingreallyreallyreallylong ) \ > .filter(thirdthingreallylessreallymaybelong == \ > thirdotherthingreallylong) \ > .first(): > < do something > > > > The first example is more readable to me but violates the 80 character > rule. The second is less readable, but doesn't violate > the 80 character rule. > > Is there a guideline or convention that pythonistas follow about this > style case? It is a guideline, not a rule. Usually your (work) environment or common sense trumps the guideline. On a side note, if you wrap that if statement with a parenthesis you can avoid the error prone '\' at the end of each line if ( someobject.filter(something) .filter(somethingreallyreallyreallyreallylong == somethingelsereallyreallylong) .filter(othethingreallylongreallyreally == ternarythingreallyreallyreallylong ) .filter(thirdthingreallylessreallymaybelong == thirdotherthingreallylong) .first() ): < do something > Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From __peter__ at web.de Thu Apr 19 16:00:45 2012 From: __peter__ at web.de (Peter Otten) Date: Thu, 19 Apr 2012 16:00:45 +0200 Subject: [Tutor] Readabilty vs 80 characters References: Message-ID: Tino Dai wrote: > Hi! > > I have a question about style. In PEP-8, it says don't exceed 79 > characters, but can this rule ever be trumped by > readability? > > Eg. > > > if someobject.filter(something) \ > .filter(somethingreallyreallyreallyreallylong == > somethingelsereallyreallylong) \ > .filter(othethingreallylongreallyreally == > ternarythingreallyreallyreallylong) \ > .filter(thirdthingreallylessreallymaybelong == > thirdotherthingreallylong) \ > .first(): > < do something > > > if someobject.filter(something) \ > .filter(somethingreallyreallyreallyreallylong == \ > somethingelsereallyreallylong) \ > .filter(othethingreallylongreallyreally == \ > ternarythingreallyreallyreallylong ) \ > .filter(thirdthingreallylessreallymaybelong == \ > thirdotherthingreallylong) \ > .first(): > < do something > > > > The first example is more readable to me but violates the 80 character > rule. The second is less readable, but doesn't violate > the 80 character rule. > > Is there a guideline or convention that pythonistas follow about this > style case? I would give you a thoughtful answer, but I am currently facing a serious problem myself: my stretch limo doesn't fit into my garage. Should I drive through the back wall or block the street with the part that sticks out? Seriously, learn that you don't need backslashes if you put the expression into parens, precalculate parts of the expression and put them into temporary variables -- and if that doesn't suffice to keep the code readable and below the 80 char threshold reread the part of the PEP with the Emerson quote ("A foolish consistency..."). From evert.rol at gmail.com Thu Apr 19 16:01:53 2012 From: evert.rol at gmail.com (Evert Rol) Date: Thu, 19 Apr 2012 16:01:53 +0200 Subject: [Tutor] Readabilty vs 80 characters In-Reply-To: References: Message-ID: On 19 Apr, 2012, at 15:29 , Tino Dai wrote: > Hi! > > I have a question about style. In PEP-8, it says don't exceed 79 characters, but can this rule ever be trumped by > readability? > Yes, it obviously can. I am a big fan of the 79 character "rule", though. Even with screens and terminals being well over 79 characters wide these days: with the 79 character limit, I can have multiple things side by side (*without* using multiple screens). > Eg. > > > if someobject.filter(something) \ > .filter(somethingreallyreallyreallyreallylong == somethingelsereallyreallylong) \ > .filter(othethingreallylongreallyreally == ternarythingreallyreallyreallylong) \ > .filter(thirdthingreallylessreallymaybelong == thirdotherthingreallylong) \ > .first(): > < do something > > > if someobject.filter(something) \ > .filter(somethingreallyreallyreallyreallylong == \ > somethingelsereallyreallylong) \ > .filter(othethingreallylongreallyreally == \ > ternarythingreallyreallyreallylong ) \ > .filter(thirdthingreallylessreallymaybelong == \ > thirdotherthingreallylong) \ > .first(): > < do something > I would let the parenthesis do the line breaking, so not use backslashes (a hidden space after a backslash can be hard to spot). In my case, it would become something like: if someobject.filter( something).filter( somethingreallyreallyreallyreallylong == somethingelsereallyreallylong).filter( othethingreallylongreallyreally == ternarythingreallyreallyreallylong).filter( thirdthingreallylessreallymaybelong == thirdotherthingreallylong).first(): pass Of course, this isn't very readable either: the filter() function starts at the end of a line, and the comparison is broken over two lines. Note that I've left my editor (emacs) do the indentation. It would have helped to indent the second part of the comparison just a bit. Then again, one can (and should) ask whether somethingreallyreallyreallyreallylong is really a good name for a variable. Occasionally, it does happen in case of dicts within dicts within list, eg mylist[counter]['somekey']['anotherkey'], but those are the cases where you would assign this to a separate (temporary) variable. > The first example is more readable to me but violates the 80 character rule. The second is less readable, but doesn't violate > the 80 character rule. > > Is there a guideline or convention that pythonistas follow about this style case? Not as such, I think. But, if lines get long or indentation gets heavy (4 or more indents), it may be good to consider two things: - move parts to a separate function - assign parts to a temporary variable. In your case, the outcome of the various comparisons could be assigned to individual variables: result1 = somethingreallyreallyreallyreallylong == somethingelsereallyreallylong result2 = othethingreallylongreallyreally == ternarythingreallyreallyreallylong etc and then the last line becomes someobject.filter(something).filter(result1).filter(result2).filter(? Or, since filter() apparently returns a new object: results1 = someobject.filter(something) results2 = result1.filter(somethingreallyreallyreallyreallylong == somethingelsereallyreallylong) results3 = result2.filter(othethingreallylongreallyreally == ternarythingreallyreallyreallylong) etc In both cases, you have changed the backslashes into actual separate statements. (And yes, those lines still are longer than 79 characters, but to me it becomes more readable overall, even if you would break those individual statements.) So, basically, when you run into something like your suggestion here, try and see another way of breaking it up then just splitting across multiple lines. Cheers, Evert > > Thanks, > Tino > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From suryak at live.com Thu Apr 19 16:33:26 2012 From: suryak at live.com (Surya K) Date: Thu, 19 Apr 2012 20:03:26 +0530 Subject: [Tutor] How to run a small python client-server on Google App Engine Message-ID: I wrote a small python Client-Server program.. (I use python 2.7) and want to make it real. I mean, I want to put the server on Google App Engine.. I went through it and found that, I need to use Google API so that it should work on GAE. So, How could I create such a small Google App Engine's app. I mean.. Can anyone help me on it..(Assuming that there is a server.py which just shows how many clients are connected to it, how do I make a app of such program) -------------- next part -------------- An HTML attachment was scrubbed... URL: From ian.douglas at iandouglas.com Thu Apr 19 16:46:39 2012 From: ian.douglas at iandouglas.com (ian douglas) Date: Thu, 19 Apr 2012 07:46:39 -0700 Subject: [Tutor] How to run a small python client-server on Google App Engine In-Reply-To: References: Message-ID: I suppose you could run something persistent on a reserved instance at Google App Engine, but typically they kill any process running longer than 30 seconds. And the persistent servers aren't free. On Apr 19, 2012 7:36 AM, "Surya K" wrote: > I wrote a small python Client-Server program.. (I use python 2.7) > > and want to make it real. I mean, I want to put the server on Google App > Engine.. > > I went through it and found that, I need to use Google API so that it > should work on GAE. > > So, How could I create such a small Google App Engine's app. I mean.. > > Can anyone help me on it.. > (Assuming that there is a server.py which just shows how many clients are > connected to it, how do I make a app of such program) > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From maxskywalker1 at gmail.com Thu Apr 19 16:47:53 2012 From: maxskywalker1 at gmail.com (Max S.) Date: Thu, 19 Apr 2012 10:47:53 -0400 Subject: [Tutor] .py vs .pyc Message-ID: Could anyone tell me why I should use a .pyc file rather than a .py? After doing some research, I have found that a .py file is first precompiled and then run, while a .pyc file is already precompiled and is simply run. But unless I'm mistaken, it seems that a .pyc is no faster or better than a .py file. When should I use a .py, and when should I use a .pyc? -------------- next part -------------- An HTML attachment was scrubbed... URL: From maxskywalker1 at gmail.com Thu Apr 19 16:57:37 2012 From: maxskywalker1 at gmail.com (Max S.) Date: Thu, 19 Apr 2012 10:57:37 -0400 Subject: [Tutor] .py vs .pyc In-Reply-To: <1334847358.27755.7.camel@lionors.winder.org.uk> References: <1334847358.27755.7.camel@lionors.winder.org.uk> Message-ID: Then if I understand correctly, I work with .py files and (should) run them as .pyc files? On Thu, Apr 19, 2012 at 10:55 AM, Russel Winder wrote: > On Thu, 2012-04-19 at 10:47 -0400, Max S. wrote: > > Could anyone tell me why I should use a .pyc file rather than a .py? > After > > doing some research, I have found that a .py file is first precompiled > and > > then run, while a .pyc file is already precompiled and is simply run. > But > > unless I'm mistaken, it seems that a .pyc is no faster or better than a > .py > > file. When should I use a .py, and when should I use a .pyc? > > pyc files are just internal PVM files. Although they appear on the > filestore visible to the programmer, just leave management of them to > the PVM. Humans deal only with .py files -- or possibly pyx if you are > using Cython. > > -- > Russel. > > ============================================================================= > Dr Russel Winder t: +44 20 7585 2200 voip: > sip:russel.winder at ekiga.net > 41 Buckmaster Road m: +44 7770 465 077 xmpp: russel at winder.org.uk > London SW11 1EN, UK w: www.russel.org.uk skype: russel_winder > -------------- next part -------------- An HTML attachment was scrubbed... URL: From russel at winder.org.uk Thu Apr 19 16:55:58 2012 From: russel at winder.org.uk (Russel Winder) Date: Thu, 19 Apr 2012 15:55:58 +0100 Subject: [Tutor] .py vs .pyc In-Reply-To: References: Message-ID: <1334847358.27755.7.camel@lionors.winder.org.uk> On Thu, 2012-04-19 at 10:47 -0400, Max S. wrote: > Could anyone tell me why I should use a .pyc file rather than a .py? After > doing some research, I have found that a .py file is first precompiled and > then run, while a .pyc file is already precompiled and is simply run. But > unless I'm mistaken, it seems that a .pyc is no faster or better than a .py > file. When should I use a .py, and when should I use a .pyc? pyc files are just internal PVM files. Although they appear on the filestore visible to the programmer, just leave management of them to the PVM. Humans deal only with .py files -- or possibly pyx if you are using Cython. -- Russel. ============================================================================= Dr Russel Winder t: +44 20 7585 2200 voip: sip:russel.winder at ekiga.net 41 Buckmaster Road m: +44 7770 465 077 xmpp: russel at winder.org.uk London SW11 1EN, UK w: www.russel.org.uk skype: russel_winder -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 198 bytes Desc: This is a digitally signed message part URL: From russel at winder.org.uk Thu Apr 19 17:04:43 2012 From: russel at winder.org.uk (Russel Winder) Date: Thu, 19 Apr 2012 16:04:43 +0100 Subject: [Tutor] Readabilty vs 80 characters In-Reply-To: References: Message-ID: <1334847883.27755.15.camel@lionors.winder.org.uk> On Thu, 2012-04-19 at 16:00 +0200, Peter Otten wrote: [...] > Seriously, learn that you don't need backslashes if you put the expression > into parens, precalculate parts of the expression and put them into > temporary variables -- and if that doesn't suffice to keep the code readable > and below the 80 char threshold reread the part of the PEP with the Emerson > quote ("A foolish consistency..."). I agree that where there is a backslash in a Python program, there is a better layout that doesn't have it. I wouldn't agree though that, necessarily, decomposing long expression using temporary variables improves anything. A good fluent API leads to function call chaining, far fewer variables, and far more readable code. Much of the time, not always, of course. There is currently a definite trend (*) away from 1960s FORTRAN style code structuring, to a 1980s Miranda (think Haskell and Scala) type thinking about how to structure code. There is experimental evidence in psychology of programming that declarative expression leads to more easily comprehensible code. This isn't advocacy research as much of programming research has been. Even C++ is going to a more declarative mode of expression, along with Java. Python's list comprehensions fit into this trend. (*) Which may turn out just to be just the latest fashion ready to be replaced in 2013. -- Russel. ============================================================================= Dr Russel Winder t: +44 20 7585 2200 voip: sip:russel.winder at ekiga.net 41 Buckmaster Road m: +44 7770 465 077 xmpp: russel at winder.org.uk London SW11 1EN, UK w: www.russel.org.uk skype: russel_winder -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 198 bytes Desc: This is a digitally signed message part URL: From russel at winder.org.uk Thu Apr 19 17:07:03 2012 From: russel at winder.org.uk (Russel Winder) Date: Thu, 19 Apr 2012 16:07:03 +0100 Subject: [Tutor] .py vs .pyc In-Reply-To: References: <1334847358.27755.7.camel@lionors.winder.org.uk> Message-ID: <1334848023.27755.18.camel@lionors.winder.org.uk> On Thu, 2012-04-19 at 10:57 -0400, Max S. wrote: > Then if I understand correctly, I work with .py files and (should) run > them as .pyc files? No, you always run the py files, don't worry about the pyc files at all, the PVM will do what it does. -- Russel. ============================================================================= Dr Russel Winder t: +44 20 7585 2200 voip: sip:russel.winder at ekiga.net 41 Buckmaster Road m: +44 7770 465 077 xmpp: russel at winder.org.uk London SW11 1EN, UK w: www.russel.org.uk skype: russel_winder -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 198 bytes Desc: This is a digitally signed message part URL: From emile at fenx.com Thu Apr 19 17:21:24 2012 From: emile at fenx.com (Emile van Sebille) Date: Thu, 19 Apr 2012 08:21:24 -0700 Subject: [Tutor] Readabilty vs 80 characters In-Reply-To: References: Message-ID: On 4/19/2012 6:29 AM Tino Dai said... > Hi! > > I have a question about style. In PEP-8, it says don't exceed 79 > characters, but can this rule ever be trumped by > readability? It's trumped by something: >>> for ii in range(10): ... D="*/"*ii+"*.py" ... L=glob.glob(D) ... for pypgm in L: ... pgm = open(pypgm,'r').readlines() ... totalLines+=len(pgm) ... LongLines.extend([(pypgm,jj) for jj in pgm if len(jj)>79]) ... >>> >>> print len(LongLines),totalLines 12043 606760 >>> Emile From alan.gauld at btinternet.com Thu Apr 19 19:28:38 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 19 Apr 2012 18:28:38 +0100 Subject: [Tutor] .py vs .pyc In-Reply-To: References: Message-ID: On 19/04/12 15:47, Max S. wrote: > Could anyone tell me why I should use a .pyc file rather than a .py? You don't, python handles that for you. They only come into effect on import statement. When Python imports the module it will use the pyc if available (and more recent that the .py). Don't try to second guess this just let Python do what it does. > After doing some research, I have found that a .py file is first > precompiled and then run, while a .pyc file is already precompiled and > is simply run. But unless I'm mistaken, it seems that a .pyc is no > faster or better than a .py file. The pyc file will be imported faster because python will not need to do the initial precompile. Other than that small improvement it should make no difference. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Apr 19 19:32:48 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 19 Apr 2012 18:32:48 +0100 Subject: [Tutor] how to select a player to play first on a multiplayer game which runs on IRC In-Reply-To: References: , <4F8FF5F1.3000402@davea.name> Message-ID: On 19/04/12 14:41, Surya K wrote: > Rather that doing all this mess, I want to put a server on Google App > Engine and run clients on my PC. But I don't know how!! Neither do I, nor I suspect most folks on this list. But there might be a few who do. The list is for learning the core Python language and library, esoteric 3rd party libraries and frameworks are a bit off topic. But you might get lucky. > I have to know Google API for writing GAE app's using python 2.7 That seems reasonable if you want to use it. Presumably Google have support forums that you can ask questions on? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From james.stauble at gmail.com Thu Apr 19 21:51:03 2012 From: james.stauble at gmail.com (James Stauble) Date: Thu, 19 Apr 2012 15:51:03 -0400 Subject: [Tutor] RuntimeError: maximum recursion depth exceeded Message-ID: I have seen in a few places where this means my program is essentially in an endless loop, but as far as I can see it is formatted correctly. Any help would be greatly appreciated. Thanks in advance. #This function defines the main calls in this program def main(): mealPrice = getMeal() #call to get the meal price before tip and tax tipPercent = getTip(mealPrice) #call to get the total tip based on meal price stateTax = getTax(mealPrice) #call to get the total tax based on meal price mealTotal = getTotal(mealPrice,tipPercent,stateTax) #call to get the total cost including tip and tax #This function gets the original meal price before tax and tip are added def getMeal(): mealPrice = input ('Enter the price of the meal $ ') mealPrice = float (mealPrice) return mealPrice #This function gets the tip which will be added to the meal def getTip(mealPrice): tipPercent = getTip(mealPrice) if mealPrice >= 25.01: tipPercent == .22 elif mealPrice >= 17.01: tipPercent == .19 elif mealPrice >= 12.01: tipPercent == .16 elif mealPrice >= 6: tipPercent == .13 else: tipPercent == .10 return tipPercent -------------- next part -------------- An HTML attachment was scrubbed... URL: From andipersti at gmail.com Thu Apr 19 22:05:37 2012 From: andipersti at gmail.com (Andreas Perstinger) Date: Thu, 19 Apr 2012 22:05:37 +0200 Subject: [Tutor] RuntimeError: maximum recursion depth exceeded In-Reply-To: References: Message-ID: <4F907011.1060603@gmail.com> On 2012-04-19 21:51, James Stauble wrote: > I have seen in a few places where this means my program is essentially in an > endless loop, but as far as I can see it is formatted correctly. Any help would > be greatly appreciated. Thanks in advance. [snip] > #This function gets the tip which will be added to the meal > def getTip(mealPrice): > tipPercent = getTip(mealPrice) As soon as you enter "getTip()" you immediately call it again and again and again ... without a chance to break out of this endless loop. As far as I can tell from your code snippet you don't need the line tipPercent = getTip(mealPrice) Bye, Andreas From alan.gauld at btinternet.com Thu Apr 19 23:25:01 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 19 Apr 2012 22:25:01 +0100 Subject: [Tutor] RuntimeError: maximum recursion depth exceeded In-Reply-To: References: Message-ID: On 19/04/12 20:51, James Stauble wrote: > I have seen in a few places where this means my program is essentially > in an endless loop, Yes same here. Its not necessarily an endless loop it may just be processing more items that Pythons call stack can hamndle, but in this case it is endless. > #This function gets the tip which will be added to the meal > def getTip(mealPrice): > tipPercent = getTip(mealPrice) Here it is, you call the same function recursively with no break condition. But you don't want a loop here anyway you just want the tip which is a one-off calculation. In general its best to restrict the use of recursion in Python to traversing recursive data structures (like trees and linked lists), and even then only where you know the depth will be well within Python's recursion limit (usually set to 1000 I think). And always, always, always, write recursive functions to have a termination condition, usually at the top of the function. Then ensure the recursive calls move the function towards that condition if at all possible. If you can't write it that way you should recode it as a regular loop. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From james.stauble at gmail.com Thu Apr 19 23:34:25 2012 From: james.stauble at gmail.com (James Stauble) Date: Thu, 19 Apr 2012 17:34:25 -0400 Subject: [Tutor] Thanks Everyone!!! Message-ID: Thanks for the tips everyone! I am fairly new to programming and am finding myself both bewildered and amazed. Its fun when it works, but boy oh boy, when it doesn't.... Anyway thanks again, you all have been very helpful. [?] -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: 330.gif Type: image/gif Size: 96 bytes Desc: not available URL: From __peter__ at web.de Fri Apr 20 12:14:10 2012 From: __peter__ at web.de (Peter Otten) Date: Fri, 20 Apr 2012 12:14:10 +0200 Subject: [Tutor] Readabilty vs 80 characters References: <1334847883.27755.15.camel@lionors.winder.org.uk> Message-ID: Russel Winder wrote: > On Thu, 2012-04-19 at 16:00 +0200, Peter Otten wrote: > [...] >> Seriously, learn that you don't need backslashes if you put the >> expression into parens, precalculate parts of the expression and put them >> into temporary variables -- and if that doesn't suffice to keep the code >> readable and below the 80 char threshold reread the part of the PEP with >> the Emerson quote ("A foolish consistency..."). > > I agree that where there is a backslash in a Python program, there is a > better layout that doesn't have it. > I wouldn't agree though that, > necessarily, decomposing long expression using temporary variables > improves anything. A good fluent API leads to function call chaining, > far fewer variables, and far more readable code. Much of the time, not > always, of course. For the examples in http://www.dabeaz.com/generators/Generators.pdf David Beazley uses a = f(...) b = g(a) c = h(b) rather than c = h(g(f(...))) I think this makes for very readable code, especially with well-chosen names for a and b. I remembered it because you mention "declarative" style and list comprehensions further down. > There is currently a definite trend (*) away from 1960s FORTRAN style > code structuring, to a 1980s Miranda (think Haskell and Scala) type > thinking about how to structure code. There is experimental evidence in > psychology of programming that declarative expression leads to more > easily comprehensible code. This isn't advocacy research as much of > programming research has been. I still won't trust it one bit until I've seen what was measured and how. If /Fortran/ is " go to the refrigerator, open it and bring the first bottle on the left " and /Haskell/ "get me a beer" the results are both obvious and meaningless. > Even C++ is going to a more declarative mode of expression, along with Java. Python's list comprehensions fit into this trend. New in Python 2.0, released in October 2000. For me the addition of generators was much more important. From suryak at live.com Fri Apr 20 17:32:11 2012 From: suryak at live.com (Surya K) Date: Fri, 20 Apr 2012 21:02:11 +0530 Subject: [Tutor] static methods & class methods Message-ID: I have a class, and want to use a method of it in the class itself. How can I do it? I mean, say I defined foo() , bar() methods in a class myClass. So, how can we i use foo() in bar(). I tried to use @staticmethod, @classmethod, but I am getting some errors.. sometimes saying "unbound " and sometimes "given more than 1 parameters".. can any one tell me how to do this... I java it really works well. -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Fri Apr 20 18:27:54 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Fri, 20 Apr 2012 12:27:54 -0400 Subject: [Tutor] static methods & class methods In-Reply-To: References: Message-ID: On Fri, Apr 20, 2012 at 11:32 AM, Surya K wrote: > I have a class, and want to use a method of it in the class itself. > > How can I do it? > > I mean, say I defined foo() , bar() methods in a class myClass. So, how can > we i use foo() in bar(). I tried to use @staticmethod, @classmethod, but I > am getting some errors.. > > sometimes saying "unbound " and sometimes "given more than 1 parameters" > .. can any one tell me how to do this... > > > I java it really works well. > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > class MyClass(object): def foo(self): print "I am foo" def bar(self): print "I am bar" self.foo() my_instance = MyClass() my_instance.foo() my_instance.bar() -- Joel Goldstick From steve at pearwood.info Fri Apr 20 18:28:54 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 21 Apr 2012 02:28:54 +1000 Subject: [Tutor] static methods & class methods In-Reply-To: References: Message-ID: <4F918EC6.9050708@pearwood.info> Surya K wrote: > I have a class, and want to use a method of it in the class itself. How can > I do it? > I mean, say I defined foo() , bar() methods in a class myClass. So, how can > we i use foo() in bar(). class C: def foo(self): print("foo") def bar(self): self.foo() print("bar") instance = C() instance.bar() > I tried to use @staticmethod, @classmethod, but I > am getting some errors.. sometimes saying "unbound " and sometimes "given > more than 1 parameters".. can any one tell me how to do this... Do you expect us to guess what you do? Please show the SMALLEST example and the actual error: http://homepage1.nifty.com/algafield/sscce.html > I java it really works well. It works really well in Python too. -- Steven From ramit.prasad at jpmorgan.com Fri Apr 20 18:00:58 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 20 Apr 2012 16:00:58 +0000 Subject: [Tutor] static methods & class methods In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF474092F242E@SCACMX008.exchad.jpmchase.net> > I have a class, and want to use a method of it in the class itself. > > How can I do it? > > I mean, say I defined foo() , bar() methods in a class myClass. So, how > can we i use foo() in bar(). I tried to use @staticmethod, @classmethod, > but I am getting some errors.. > > sometimes saying "unbound " and sometimes "given more than 1 parameters" > .. can any one tell me how to do this... You should read about object oriented programming in Python. http://www.alan-g.me.uk/tutor/index.htm is a good starting point (on the left under 'Advanced Topics'). I take this to mean you want to call a method in the class from another method in the class. I assume you do not need to use "staticmethod" and do something like below: class A Method foo: Method bar < do something including calling foo > Every method in a class *must* take in the instance. The convention is to call this "self". To access another method you use the instance and call the method desired. An unbound function is a function that is not tied to an object/class. This is also why you got "given more than 1 parameters" error. I assume you did not include self in the function definition and Python was passing it. This becomes the following: class A( object ): # I use Python 2.x def foo( self ): # must include self print 'foo' def bar( self ): print 'bar' self.foo() # This uses the instance to call foo Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From alan.gauld at btinternet.com Fri Apr 20 21:11:25 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 20 Apr 2012 20:11:25 +0100 Subject: [Tutor] static methods & class methods In-Reply-To: References: Message-ID: On 20/04/12 16:32, Surya K wrote: > I java it really works well. Java: this.foo() Python: self.foo() Works almost identically in both. Of course in Java the 'this' is optional but many style guides recommend its use to make it clear where the function lives... If you really like 'this' over 'self' you can even do that too: class C: def foo(this): pass def bar(this): this.foo() -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From wprins at gmail.com Fri Apr 20 23:41:31 2012 From: wprins at gmail.com (Walter Prins) Date: Fri, 20 Apr 2012 23:41:31 +0200 Subject: [Tutor] static methods & class methods In-Reply-To: References: Message-ID: Hi Surya On 20 April 2012 17:32, Surya K wrote: > I mean, say I defined foo() , bar() methods in a class myClass. So, how > can we i use foo() in bar(). I tried to use @staticmethod, @classmethod, > but I am getting some errors.. > > sometimes saying "unbound " and sometimes "given more than 1 parameters" > .. can any one tell me how to do this... > Please, just copy *exactly* what you've done, and the exact error message. The above implies you got the syntax slightly wrong but without code and without the exact stack trace we must guess. That said, my spidey sense tells me you want to declare a classmethod. You do it like this: #define a class Foo and define a class method in it: class Foo: @classmethod #decorator to indicate this is a class method def class_method(self): #for class methods, self refers to class itself print "This is a classmethod called from class", self #call the class method: Foo.class_method() Aside, @staticmethod is simpler, it is basically is a way to declare a pure function (not bound to an object instance or a class as such, e.g. it doesn't receive a "self" parameter) as part of a class. Cheers, Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From chnlion79 at gmail.com Mon Apr 23 14:40:23 2012 From: chnlion79 at gmail.com (Lion Chen) Date: Mon, 23 Apr 2012 20:40:23 +0800 Subject: [Tutor] why gtk.Entry does not give me right answers? Message-ID: <4F954DB7.4080000@gmail.com> Hi, All, i am trying write a calculator, now normal calculation works ok. but if i enter long numbers, for example 333333333333333333 + 7, it gives me "333333333333333312"..... there are 18 "3"s, if the length is more than 17, the calculation will be wrong on Windows and Ubuntu. the following is some of my codes: def pre_calc(self, op): #if entry is empty, any operators are invalid except "-" if not self.entry.get_text() and op != "-": return if not self.entry.get_text() and op == "-": self.entry.set_text(op) self.cleared = 1 self.negative_sign = True#indicates there's already a "-" return #retrieve the 1st num and operator if not self.op and self.entry.get_text(): if op != "=": self.op = op #print "text typ:", type(self.entry.get_text()) self.first_num = self.entry.get_text() self.cleared = 0 # ready to input 2nd num #print "op:", self.op, "-----", "1st num:", self.first_num return else: self.first_num = None self.second_num = None self.op = None self.cleared = 0 self.negative_sign = False return #retrieve the second num and begin calculation elif self.op and self.first_num and self.entry.get_text() != "-": if op == "=": self.second_num = self.entry.get_text() self.calc() #reset the following varibles, awaiting next round of inputs self.first_num = None self.second_num = None self.op = None self.cleared = 0 self.negative_sign = False return elif op == "-": if self.cleared == 1: #if user has input 2nd num already self.second_num = self.entry.get_text() self.calc() self.first_num = self.entry.get_text() self.op = op self.cleared = 0 self.negative_sign = False return else: self.entry.set_text(op) self.cleared = 1 self.negative_sign = True#indicates there's already a "-" return else: self.op = op if self.cleared == 1: self.second_num = self.entry.get_text() self.calc() self.first_num = self.entry.get_text() self.cleared = 0 self.negative_sign = False return else: return def calc(self, unary_op = None): if not unary_op: if (not self.first_num) or (not self.second_num) or \ (not self.op): return result = None calc_methods = {"+": self.add, "-": self.subtract, "*": self.multiply, "/": self.divide, "%": self.mod, "pwr": self.power, "|": self.b_or, "&": self.b_and, "^": self.b_exc, "<<": self.b_lshift, ">>": self.b_rshift } unary_methods ={"~": self.b_invert, "1/x": self.a_fraction, "sqrt": self.sqrt } if not unary_op: for op, method in calc_methods.items(): if self.op == op: result = calc_methods[op]() else: for op, method in unary_methods.items(): if unary_op == op: result = unary_methods[op]() self.entry.set_text(result) def add(self): result = None #if hex system #print type(self.first_num) if self.hdob["h"].get_active(): self.first_num = long(self.first_num, 16) self.second_num = long(self.second_num, 16) r = self.first_num + self.second_num r = self.convert.d2h(r) return r #if decimal system elif self.hdob["d"].get_active(): self.first_num = float(self.first_num) self.second_num = float(self.second_num) result = self.first_num + self.second_num if result - long(result) == 0: #print str(long(result)) return str(long(result)) else: return str(result) #if octal system elif self.hdob["o"].get_active(): self.first_num = long(self.first_num, 8) self.second_num = long(self.second_num, 8) result = self.first_num + self.second_num result = self.convert.d2o(result) return result else: self.first_num = long(self.first_num, 2) self.second_num = long(self.second_num, 2) result = bin(self.first_num + self.second_num) result = self.convert.d2b(result) return result but if i run the following codes on command line, it works ok: >>>a = 33333333333333333333333333333333333333L >>>b= str(a) >>>b '33333333333333333333333333333333333333' why? i don't understand.... anybody can help me? thanks. Lion -------------- next part -------------- An HTML attachment was scrubbed... URL: From gerhardus.geldenhuis at gmail.com Mon Apr 23 14:56:17 2012 From: gerhardus.geldenhuis at gmail.com (Gerhardus Geldenhuis) Date: Mon, 23 Apr 2012 13:56:17 +0100 Subject: [Tutor] Converting a string into dictionary references Message-ID: Hi Appologies about the subject I could not think of a better description. I have this very simple function: def readcsvfile(filename): f = open(filename, 'ro') csvdata = csv.DictReader(f) for row in csvdata: print row["column3"]+','+row["column1"] I have another inputfile that will be comma separated list of values. Eg: column3,column4,column10 The idea is that I use this inputfile to tranform the original csv file. I thus want a new file with only the specified columns. I am sure there is an elegant way of doing this but I am not sure how to convert my print statement into something more dynamic. Any pointers would be appreciated. Regards -- Gerhardus Geldenhuis -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Mon Apr 23 15:41:49 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Mon, 23 Apr 2012 09:41:49 -0400 Subject: [Tutor] Converting a string into dictionary references In-Reply-To: References: Message-ID: On Mon, Apr 23, 2012 at 8:56 AM, Gerhardus Geldenhuis wrote: > Hi > Appologies about the subject I could not think of a better description. > > I have this very simple function: > > def readcsvfile(filename): > ? f = open(filename, 'ro') > ? csvdata = csv.DictReader(f) > ? for row in csvdata: > ? ? print row["column3"]+','+row["column1"] > > I have another inputfile that will be comma?separated?list of values. > Eg: > column3,column4,column10 > > The idea is that I use this inputfile to tranform the original csv file. I > thus want a new file with only the specified columns. I am sure there is an > elegant way of doing this but I am not sure how to convert my print > statement into something more dynamic. Any pointers would be appreciated. > > Regards > > -- > Gerhardus Geldenhuis > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > So you want to take 'column1' and get back 1?, 'column10' and get back 10? s = 'column1' i = int(s[6:]) This will only work if your strings all start with the text 'column' -- Joel Goldstick From gerhardus.geldenhuis at gmail.com Mon Apr 23 15:46:14 2012 From: gerhardus.geldenhuis at gmail.com (Gerhardus Geldenhuis) Date: Mon, 23 Apr 2012 14:46:14 +0100 Subject: [Tutor] Converting a string into dictionary references In-Reply-To: References: Message-ID: Not quite, I have csvfile1: column1, column2, column3, ... column200 That is my raw data but I want to use only 5 columns for example in a specific application. I thus want a file with the following: column33,column1,column5 I then want to read the original csv file and write a new csv file with the requested columns only. Does that make more sense? Regards On 23 April 2012 14:41, Joel Goldstick wrote: > On Mon, Apr 23, 2012 at 8:56 AM, Gerhardus Geldenhuis > wrote: > > Hi > > Appologies about the subject I could not think of a better description. > > > > I have this very simple function: > > > > def readcsvfile(filename): > > f = open(filename, 'ro') > > csvdata = csv.DictReader(f) > > for row in csvdata: > > print row["column3"]+','+row["column1"] > > > > I have another inputfile that will be comma separated list of values. > > Eg: > > column3,column4,column10 > > > > The idea is that I use this inputfile to tranform the original csv file. > I > > thus want a new file with only the specified columns. I am sure there is > an > > elegant way of doing this but I am not sure how to convert my print > > statement into something more dynamic. Any pointers would be appreciated. > > > > Regards > > > > -- > > Gerhardus Geldenhuis > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > > > So you want to take 'column1' and get back 1?, 'column10' and get back 10? > > s = 'column1' > i = int(s[6:]) > > This will only work if your strings all start with the text 'column' > > -- > Joel Goldstick > -- Gerhardus Geldenhuis -------------- next part -------------- An HTML attachment was scrubbed... URL: From gerhardus.geldenhuis at gmail.com Mon Apr 23 16:01:32 2012 From: gerhardus.geldenhuis at gmail.com (Gerhardus Geldenhuis) Date: Mon, 23 Apr 2012 15:01:32 +0100 Subject: [Tutor] Converting a string into dictionary references In-Reply-To: <4F956034.8040805@compuscan.co.za> References: <4F956034.8040805@compuscan.co.za> Message-ID: Yip, Unfortunately I am not, this needs to happen in python. Regards On 23 April 2012 14:59, Christian Witts wrote: > On 2012/04/23 03:46 PM, Gerhardus Geldenhuis wrote: > > Not quite, > > I have csvfile1: > column1, column2, column3, ... column200 > > That is my raw data but I want to use only 5 columns for example in a > specific application. > I thus want a file with the following: > column33,column1,column5 > > I then want to read the original csv file and write a new csv file with > the requested columns only. > > Does that make more sense? > > Regards > > On 23 April 2012 14:41, Joel Goldstick wrote: > >> On Mon, Apr 23, 2012 at 8:56 AM, Gerhardus Geldenhuis >> wrote: >> > Hi >> > Appologies about the subject I could not think of a better description. >> > >> > I have this very simple function: >> > >> > def readcsvfile(filename): >> > f = open(filename, 'ro') >> > csvdata = csv.DictReader(f) >> > for row in csvdata: >> > print row["column3"]+','+row["column1"] >> > >> > I have another inputfile that will be comma separated list of values. >> > Eg: >> > column3,column4,column10 >> > >> > The idea is that I use this inputfile to tranform the original csv >> file. I >> > thus want a new file with only the specified columns. I am sure there >> is an >> > elegant way of doing this but I am not sure how to convert my print >> > statement into something more dynamic. Any pointers would be >> appreciated. >> > >> > Regards >> > >> > -- >> > Gerhardus Geldenhuis >> > >> > _______________________________________________ >> > Tutor maillist - Tutor at python.org >> > To unsubscribe or change subscription options: >> > http://mail.python.org/mailman/listinfo/tutor >> > >> >> So you want to take 'column1' and get back 1?, 'column10' and get back 10? >> >> s = 'column1' >> i = int(s[6:]) >> >> This will only work if your strings all start with the text 'column' >> >> -- >> Joel Goldstick >> > > > > -- > Gerhardus Geldenhuis > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options:http://mail.python.org/mailman/listinfo/tutor > > If you don't need to use Python and are on a *nix machine you can use cut > to do the work for you for eg and it might simplify your workflow. > > -d specifies the delimiter of the file, in this case a comma > -f specifies the fields you want, in this case 1 to 3, 5, and 10 > cut -d, -f1-3,5,10 input_filename > output_filename > > -- > > Christian Witts > Python Developer > ** > -- Gerhardus Geldenhuis -------------- next part -------------- An HTML attachment was scrubbed... URL: From cwitts at compuscan.co.za Mon Apr 23 15:59:16 2012 From: cwitts at compuscan.co.za (Christian Witts) Date: Mon, 23 Apr 2012 15:59:16 +0200 Subject: [Tutor] Converting a string into dictionary references In-Reply-To: References: Message-ID: <4F956034.8040805@compuscan.co.za> On 2012/04/23 03:46 PM, Gerhardus Geldenhuis wrote: > Not quite, > > I have csvfile1: > column1, column2, column3, ... column200 > > That is my raw data but I want to use only 5 columns for example in a > specific application. > I thus want a file with the following: > column33,column1,column5 > > I then want to read the original csv file and write a new csv file > with the requested columns only. > > Does that make more sense? > > Regards > > On 23 April 2012 14:41, Joel Goldstick > wrote: > > On Mon, Apr 23, 2012 at 8:56 AM, Gerhardus Geldenhuis > > wrote: > > Hi > > Appologies about the subject I could not think of a better > description. > > > > I have this very simple function: > > > > def readcsvfile(filename): > > f = open(filename, 'ro') > > csvdata = csv.DictReader(f) > > for row in csvdata: > > print row["column3"]+','+row["column1"] > > > > I have another inputfile that will be comma separated list of > values. > > Eg: > > column3,column4,column10 > > > > The idea is that I use this inputfile to tranform the original > csv file. I > > thus want a new file with only the specified columns. I am sure > there is an > > elegant way of doing this but I am not sure how to convert my print > > statement into something more dynamic. Any pointers would be > appreciated. > > > > Regards > > > > -- > > Gerhardus Geldenhuis > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > > > So you want to take 'column1' and get back 1?, 'column10' and get > back 10? > > s = 'column1' > i = int(s[6:]) > > This will only work if your strings all start with the text 'column' > > -- > Joel Goldstick > > > > > -- > Gerhardus Geldenhuis > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor If you don't need to use Python and are on a *nix machine you can use cut to do the work for you for eg and it might simplify your workflow. -d specifies the delimiter of the file, in this case a comma -f specifies the fields you want, in this case 1 to 3, 5, and 10 cut -d, -f1-3,5,10 input_filename > output_filename -- Christian Witts Python Developer // -------------- next part -------------- An HTML attachment was scrubbed... URL: From nehal.dattani at gmail.com Mon Apr 23 16:18:17 2012 From: nehal.dattani at gmail.com (nehal dattani) Date: Mon, 23 Apr 2012 19:48:17 +0530 Subject: [Tutor] Converting a string into dictionary references In-Reply-To: References: <4F956034.8040805@compuscan.co.za> Message-ID: Hi, > Unfortunately I am not, this needs to happen in python. > > > Please see if following helps. http://stackoverflow.com/questions/5863999/python-cut-example Regards, Nehal Dattani -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Mon Apr 23 16:26:22 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Mon, 23 Apr 2012 10:26:22 -0400 Subject: [Tutor] Converting a string into dictionary references In-Reply-To: References: <4F956034.8040805@compuscan.co.za> Message-ID: On Mon, Apr 23, 2012 at 10:18 AM, nehal dattani wrote: > Hi, > >> >> Unfortunately I am not, this needs to happen in python. >> >> > > Please see if following helps. > > http://stackoverflow.com/questions/5863999/python-cut-example > > Regards, > Nehal Dattani > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Apparently I misunderstood. I thought you might have been asking how to convert the key strings used in your 3rd file to make keys that you could use to select only those columns you want to output. But, now I think you are saying you want to select only certain columns, and maybe change the order of the output. Dicts don't have an order, so you might be better off using the normal reader method which returns a list. Iterate over each row in your input dataset and then use your output column list to do something like this: So you could read the third file, and create a column_list = [1, 2, 3, 44, 22, ..] as appropriate. for r in in.csvreader(): for c in column_list: out_list.append(r[c]) write the line to the output file Sorry for double reply. I didn't reply all before -- Joel Goldstick From gerhardus.geldenhuis at gmail.com Mon Apr 23 16:28:08 2012 From: gerhardus.geldenhuis at gmail.com (Gerhardus Geldenhuis) Date: Mon, 23 Apr 2012 15:28:08 +0100 Subject: [Tutor] Converting a string into dictionary references In-Reply-To: References: <4F956034.8040805@compuscan.co.za> Message-ID: Hi Thanks for all the replies, I will try a the suggestions and post my solution back. Regards -- Gerhardus Geldenhuis -------------- next part -------------- An HTML attachment was scrubbed... URL: From gerhardus.geldenhuis at gmail.com Mon Apr 23 17:08:28 2012 From: gerhardus.geldenhuis at gmail.com (Gerhardus Geldenhuis) Date: Mon, 23 Apr 2012 16:08:28 +0100 Subject: [Tutor] Converting a string into dictionary references In-Reply-To: References: <4F956034.8040805@compuscan.co.za> Message-ID: Hi Here is my solution: def readcsvfile(filename,headerstring): headers = headerstring.split(',') f = open(filename, 'ro') csvdata = csv.DictReader(f) for row in csvdata: for column in headers[0:-1]: print row[column]+',', print row[headers[-1]] Regards On 23 April 2012 15:28, Gerhardus Geldenhuis wrote: > Hi > Thanks for all the replies, I will try a the suggestions and post my > solution back. > > Regards > > -- > Gerhardus Geldenhuis > -- Gerhardus Geldenhuis -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Mon Apr 23 17:08:13 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 24 Apr 2012 01:08:13 +1000 Subject: [Tutor] why gtk.Entry does not give me right answers? In-Reply-To: <4F954DB7.4080000@gmail.com> References: <4F954DB7.4080000@gmail.com> Message-ID: <4F95705D.4080908@pearwood.info> Lion Chen wrote: > Hi, All, > > i am trying write a calculator, now normal calculation works ok. but if > i enter long numbers, for example 333333333333333333 + 7, it gives me > "333333333333333312"..... > > there are 18 "3"s, if the length is more than 17, the calculation will > be wrong on Windows and Ubuntu. You are losing precision by converting into a float. Watch: >>> n = 333333333333333333 >>> n + 7 333333333333333340 >>> int(float(n)) 333333333333333312 >>> int(float(n)+7) 333333333333333312 Your integer value 333...333 requires 59 bits to store the entire number, but Python floats are C doubles, which only have 52 bits available for the numeric digits. (The other 12 bits encode the sign and exponent.) http://www.johndcook.com/blog/2009/04/06/anatomy-of-a-floating-point-number/ You cannot store 3333...333 exactly as a float. The two closest floats are: 333333333333333312.0 333333333333333376.0 so all numbers between them will be rounded up or down. Some possible solutions: * Don't try to mix infinite-precision integer arithmetic with finite-precision float arithmetic. * Don't convert to float unless you really need to, e.g. if the string contains a decimal point. * Use the decimal module instead of floats. You still have finite precision, but you can choose how many *decimal* places to store instead of having a fixed number of *binary* places. (But decimal is much slower.) By the way, the code that you sent is unreadable. Please make sure that you send plain text email, and that indentation is not lost. Without indentation, it is impossible to understand your code. -- Steven From joel.goldstick at gmail.com Mon Apr 23 17:17:55 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Mon, 23 Apr 2012 11:17:55 -0400 Subject: [Tutor] Converting a string into dictionary references In-Reply-To: References: <4F956034.8040805@compuscan.co.za> Message-ID: On Mon, Apr 23, 2012 at 11:08 AM, Gerhardus Geldenhuis wrote: > Hi > Here is my solution: > > def readcsvfile(filename,headerstring): > ? headers = headerstring.split(',') > > ? f = open(filename, 'ro') > ? csvdata = csv.DictReader(f) > ? for row in csvdata: > ? ? for column in headers[0:-1]: > ? ? ? print row[column]+',', > ? ? print row[headers[-1]] > > Regards > > On 23 April 2012 15:28, Gerhardus Geldenhuis > wrote: >> >> Hi >> Thanks for all the replies, I will try a the suggestions and post my >> solution back. >> >> Regards >> >> -- >> Gerhardus Geldenhuis > > > > > -- > Gerhardus Geldenhuis > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > nice! -- Joel Goldstick From russel at winder.org.uk Mon Apr 23 17:36:44 2012 From: russel at winder.org.uk (Russel Winder) Date: Mon, 23 Apr 2012 16:36:44 +0100 Subject: [Tutor] why gtk.Entry does not give me right answers? In-Reply-To: <4F95705D.4080908@pearwood.info> References: <4F954DB7.4080000@gmail.com> <4F95705D.4080908@pearwood.info> Message-ID: <1335195404.2984.6.camel@launcelot.winder.org.uk> On Tue, 2012-04-24 at 01:08 +1000, Steven D'Aprano wrote: [...] > > * Use the decimal module instead of floats. You still have finite precision, > but you can choose how many *decimal* places to store instead of having a > fixed number of *binary* places. (But decimal is much slower.) Alternatively use http://packages.python.org/bigfloat/ or possibly http://code.google.com/p/mpmath/ > > By the way, the code that you sent is unreadable. Please make sure that you > send plain text email, and that indentation is not lost. Without indentation, > it is impossible to understand your code. Indeed. The lack of indentation was a barrier to contemplating looking at the code. Especially since indentation is meaningful in Python! -- Russel. ============================================================================= Dr Russel Winder t: +44 20 7585 2200 voip: sip:russel.winder at ekiga.net 41 Buckmaster Road m: +44 7770 465 077 xmpp: russel at winder.org.uk London SW11 1EN, UK w: www.russel.org.uk skype: russel_winder -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 198 bytes Desc: This is a digitally signed message part URL: From dfjennings at gmail.com Mon Apr 23 18:40:14 2012 From: dfjennings at gmail.com (Don Jennings) Date: Mon, 23 Apr 2012 12:40:14 -0400 Subject: [Tutor] Converting a string into dictionary references In-Reply-To: References: Message-ID: <742783D1-E861-4059-AE70-E9703E4F7675@gmail.com> Remember, the keys for the dictionary in your example are simply strings. It just so happens that those strings are in another file. Read the file which contains the specified columns and split on the comma into variable names for your output: with open(spec_file, 'r') as f: outcol1, outcol2, outcol3 = f.readline().split(',') # use variable names to access dictionary print row[outcol1] + ',' + row[outcol2] + ',' + row[outcol3] Now, if you are unsure how many columns will be in the file with specified columns, that changes things slightly: # get a list of the requested columns outcols = [] with open(spec_file, 'r') as f: line = f.readline() outcols.extend(line.split(',')) # later, use that list to do something with the output (I assume strings for your data here) print ','.join([row[outcol] for outcol in outcols]) Helpful? Take care, Don > Not quite, > > I have csvfile1: > column1, column2, column3, ... column200 > > That is my raw data but I want to use only 5 columns for example in a > specific application. > I thus want a file with the following: > column33,column1,column5 > > I then want to read the original csv file and write a new csv file with the > requested columns only. > > Does that make more sense? > > Regards > > On 23 April 2012 14:41, Joel Goldstick wrote: > >> On Mon, Apr 23, 2012 at 8:56 AM, Gerhardus Geldenhuis >> wrote: >>> Hi >>> Appologies about the subject I could not think of a better description. >>> >>> I have this very simple function: >>> >>> def readcsvfile(filename): >>> f = open(filename, 'ro') >>> csvdata = csv.DictReader(f) >>> for row in csvdata: >>> print row["column3"]+','+row["column1"] >>> >>> I have another inputfile that will be comma separated list of values. >>> Eg: >>> column3,column4,column10 >>> >>> The idea is that I use this inputfile to tranform the original csv file. >> I >>> thus want a new file with only the specified columns. I am sure there is >> an >>> elegant way of doing this but I am not sure how to convert my print >>> statement into something more dynamic. Any pointers would be appreciated. >>> >>> Regards >>> >>> -- >>> Gerhardus Geldenhuis >>> >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> To unsubscribe or change subscription options: >>> http://mail.python.org/mailman/listinfo/tutor >>> >> >> So you want to take 'column1' and get back 1?, 'column10' and get back 10? >> >> s = 'column1' >> i = int(s[6:]) >> >> This will only work if your strings all start with the text 'column' >> >> -- >> Joel Goldstick >> > > > > -- > Gerhardus Geldenhuis > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > End of Tutor Digest, Vol 98, Issue 58 > ************************************* From gerhardus.geldenhuis at gmail.com Mon Apr 23 19:42:35 2012 From: gerhardus.geldenhuis at gmail.com (Gerhardus Geldenhuis) Date: Mon, 23 Apr 2012 18:42:35 +0100 Subject: [Tutor] Converting a string into dictionary references In-Reply-To: <742783D1-E861-4059-AE70-E9703E4F7675@gmail.com> References: <742783D1-E861-4059-AE70-E9703E4F7675@gmail.com> Message-ID: Thanks! That does look helpfull, I will give it a go and see if I can get an alternative version working. Regards On 23 April 2012 17:40, Don Jennings wrote: > Remember, the keys for the dictionary in your example are simply strings. > It just so happens that those strings are in another file. Read the file > which contains the specified columns and split on the comma into variable > names for your output: > > > with open(spec_file, 'r') as f: > outcol1, outcol2, outcol3 = f.readline().split(',') > > # use variable names to access dictionary > print row[outcol1] + ',' + row[outcol2] + ',' + row[outcol3] > > > Now, if you are unsure how many columns will be in the file with specified > columns, that changes things slightly: > > > # get a list of the requested columns > outcols = [] > with open(spec_file, 'r') as f: > line = f.readline() > outcols.extend(line.split(',')) > > # later, use that list to do something with the output (I assume strings > for your data here) > print ','.join([row[outcol] for outcol in outcols]) > > Helpful? > > Take care, > Don > > > > Not quite, > > > > I have csvfile1: > > column1, column2, column3, ... column200 > > > > That is my raw data but I want to use only 5 columns for example in a > > specific application. > > I thus want a file with the following: > > column33,column1,column5 > > > > I then want to read the original csv file and write a new csv file with > the > > requested columns only. > > > > Does that make more sense? > > > > Regards > > > > On 23 April 2012 14:41, Joel Goldstick wrote: > > > >> On Mon, Apr 23, 2012 at 8:56 AM, Gerhardus Geldenhuis > >> wrote: > >>> Hi > >>> Appologies about the subject I could not think of a better description. > >>> > >>> I have this very simple function: > >>> > >>> def readcsvfile(filename): > >>> f = open(filename, 'ro') > >>> csvdata = csv.DictReader(f) > >>> for row in csvdata: > >>> print row["column3"]+','+row["column1"] > >>> > >>> I have another inputfile that will be comma separated list of values. > >>> Eg: > >>> column3,column4,column10 > >>> > >>> The idea is that I use this inputfile to tranform the original csv > file. > >> I > >>> thus want a new file with only the specified columns. I am sure there > is > >> an > >>> elegant way of doing this but I am not sure how to convert my print > >>> statement into something more dynamic. Any pointers would be > appreciated. > >>> > >>> Regards > >>> > >>> -- > >>> Gerhardus Geldenhuis > >>> > >>> _______________________________________________ > >>> Tutor maillist - Tutor at python.org > >>> To unsubscribe or change subscription options: > >>> http://mail.python.org/mailman/listinfo/tutor > >>> > >> > >> So you want to take 'column1' and get back 1?, 'column10' and get back > 10? > >> > >> s = 'column1' > >> i = int(s[6:]) > >> > >> This will only work if your strings all start with the text 'column' > >> > >> -- > >> Joel Goldstick > >> > > > > > > > > -- > > Gerhardus Geldenhuis > > -------------- next part -------------- > > An HTML attachment was scrubbed... > > URL: < > http://mail.python.org/pipermail/tutor/attachments/20120423/aa787769/attachment.html > > > > > > ------------------------------ > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > End of Tutor Digest, Vol 98, Issue 58 > > ************************************* > > -- Gerhardus Geldenhuis -------------- next part -------------- An HTML attachment was scrubbed... URL: From chnlion79 at gmail.com Tue Apr 24 05:00:30 2012 From: chnlion79 at gmail.com (Lion Chen) Date: Tue, 24 Apr 2012 11:00:30 +0800 Subject: [Tutor] why gtk.Entry does not give me right answers? In-Reply-To: <4F95705D.4080908@pearwood.info> References: <4F954DB7.4080000@gmail.com> <4F95705D.4080908@pearwood.info> Message-ID: <4F96174E.1020801@gmail.com> ? 2012?04?23? 23:08, Steven D'Aprano ??: > Lion Chen wrote: >> Hi, All, >> >> i am trying write a calculator, now normal calculation works ok. but if >> i enter long numbers, for example 333333333333333333 + 7, it gives me >> "333333333333333312"..... >> >> there are 18 "3"s, if the length is more than 17, the calculation will >> be wrong on Windows and Ubuntu. > You are losing precision by converting into a float. Watch: > >>>> n = 333333333333333333 >>>> n + 7 > 333333333333333340 >>>> int(float(n)) > 333333333333333312 >>>> int(float(n)+7) > 333333333333333312 > > Your integer value 333...333 requires 59 bits to store the entire number, but > Python floats are C doubles, which only have 52 bits available for the numeric > digits. (The other 12 bits encode the sign and exponent.) > > http://www.johndcook.com/blog/2009/04/06/anatomy-of-a-floating-point-number/ > > You cannot store 3333...333 exactly as a float. The two closest floats are: > > 333333333333333312.0 > 333333333333333376.0 > > so all numbers between them will be rounded up or down. > > Some possible solutions: > > * Don't try to mix infinite-precision integer arithmetic with finite-precision > float arithmetic. > > * Don't convert to float unless you really need to, e.g. if the string > contains a decimal point. > > * Use the decimal module instead of floats. You still have finite precision, > but you can choose how many *decimal* places to store instead of having a > fixed number of *binary* places. (But decimal is much slower.) > > > By the way, the code that you sent is unreadable. Please make sure that you > send plain text email, and that indentation is not lost. Without indentation, > it is impossible to understand your code. many thanks, Steve, i see, and i have solved it :) . and the codes in my thunderbird shows ok, so i thought it would be ok in yours, sorry for that.... Lion > > From isurveyor at vianet.net.au Tue Apr 24 09:57:58 2012 From: isurveyor at vianet.net.au (Ivor Surveyor) Date: Tue, 24 Apr 2012 15:57:58 +0800 Subject: [Tutor] Help with graphics please Message-ID: <3VcH3663xdzLxK@mail.python.org> I request help in locating the graphics module "graphics.py" I am new to both programming and Python. I have successfully down loaded Python 2.7.2 and WingIde 101 4.1. I am using Windows 7 as my operating system. I am reading Python programming by John Zelle supplemented by MIT lectures on computing science. I have reached the chapter on "Objects and Graphics." my problem is that I can not locate either the graphics module or graphics.py. the command "import graphics" elicits the response module unknown. I would be very appreciative of help in locating the file on the Internet. Naturally I will be pleased to purchase the file if necessary. regards, Ivor Surveyor isurveyor at vianet.net.au From ye.youqun at eisoo.com Tue Apr 24 10:11:05 2012 From: ye.youqun at eisoo.com (=?UTF-8?B?5Y+25L2R576k?=) Date: Tue, 24 Apr 2012 16:11:05 +0800 Subject: [Tutor] Fwd: The results of your email commands In-Reply-To: References: Message-ID: <4F966019.2070702@eisoo.com> Hi, all I have two block code as: Block 1: #...... pobj = subprocess.Popen (["passwd", user], stdout=subprocess.PIPE, stdin = subprocess.PIPE) password = password + "\n" pobj.stdin.write (password) pobj.stdin.write (password) #...... Block 2: #...... pobj = subprocess.Popen (["pdbedit", "-a", user], stdout=subprocess.PIPE, stdin =subprocess.PIPE) password = password + "\n" pobj.stdin.write (password) pobj.stdin.write (password) #...... The only difference is command to run, but code of Block 1 runs OK, and Block 2 can't write the password to "pdbedit". Is there any thing wrong with the code above or if something else cause Block 2 failed? Any suggestion ? From steve at pearwood.info Tue Apr 24 11:17:09 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 24 Apr 2012 19:17:09 +1000 Subject: [Tutor] Help with graphics please In-Reply-To: <3VcH3663xdzLxK@mail.python.org> References: <3VcH3663xdzLxK@mail.python.org> Message-ID: <20120424091709.GA19452@ando> On Tue, Apr 24, 2012 at 03:57:58PM +0800, Ivor Surveyor wrote: > > I request help in locating the graphics module "graphics.py" Have you tried searching for "Python programming by John Zelle graphics.py" on any of the major search engines, like Google, Yahoo or DuckDuckGo? That should always be your first stop for any question. I believe that this will give you the file you are after: http://mcsp.wartburg.edu/zelle/python/ > the command "import graphics" elicits the response module unknown. No it doesn't. If you're going to learn programming, you will need to be pedantic about reporting the *precise* error messages you get, and not paraphrase them. The error message you get is almost certainly something like this: Traceback (most recent call last): File "", line 1, in ImportError: No module named graphics (although the middle line is probably different). Now in this case I knew what you meant, it wasn't terribly difficult to work that out. But believe me, there are people who come here, or on other mailing lists and help forums, and give utterly undecipherable, incomplete, or even incorrect error messages, and thus send us on a wild goose chase trying to solve a problem that doesn't exist. Good luck and have fun! -- Steven From joel.goldstick at gmail.com Tue Apr 24 12:13:59 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Tue, 24 Apr 2012 06:13:59 -0400 Subject: [Tutor] Fwd: The results of your email commands In-Reply-To: <4F966019.2070702@eisoo.com> References: <4F966019.2070702@eisoo.com> Message-ID: On Tue, Apr 24, 2012 at 4:11 AM, ??? wrote: > Hi, all > > ? ?I have two block code as: > > Block 1: > ? ? ? ? ? ?#...... > ? ? ? ? ? ?pobj = subprocess.Popen (["passwd", user], > stdout=subprocess.PIPE, stdin = subprocess.PIPE) > ? ? ? ? ? ?password = password + "\n" > ? ? ? ? ? ?pobj.stdin.write (password) > ? ? ? ? ? ?pobj.stdin.write (password) > ? ? ? ? ? ?#...... > Block 2: > ? ? ? ? ? ?#...... > ? ? ? ? ? ?pobj = subprocess.Popen (["pdbedit", "-a", user], > stdout=subprocess.PIPE, stdin =subprocess.PIPE) > ? ? ? ? ? ?password = password + "\n" > ? ? ? ? ? ?pobj.stdin.write (password) > ? ? ? ? ? ?pobj.stdin.write (password) > ? ? ? ? ? ?#...... > > ? ? ? ?The only difference is command to run, but code of Block 1 runs OK, > and Block 2 can't write the password to "pdbedit". Is there any thing wrong > with the code above or if something else cause Block 2 failed? Any > suggestion ? > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor This isn't really a 'learning python' question. But I googled pdedit and found this: -a This option is used to add a user into the database. This com- mand needs a user name specified with the -u switch. When adding a new user, pdbedit will also ask for the password to be used. Example: pdbedit -a -u sorce new password: retype new password So it looks like if you use -a you also need -u -- Joel Goldstick From ye.youqun at eisoo.com Wed Apr 25 02:59:21 2012 From: ye.youqun at eisoo.com (=?UTF-8?B?5Y+25L2R576k?=) Date: Wed, 25 Apr 2012 08:59:21 +0800 Subject: [Tutor] Fwd: The results of your email commands In-Reply-To: References: <4F966019.2070702@eisoo.com> Message-ID: <4F974C69.8020600@eisoo.com> ? 2012-4-24 18:13, Joel Goldstick ??: > On Tue, Apr 24, 2012 at 4:11 AM, ??? wrote: >> Hi, all >> >> I have two block code as: >> >> Block 1: >> #...... >> pobj = subprocess.Popen (["passwd", user], >> stdout=subprocess.PIPE, stdin = subprocess.PIPE) >> password = password + "\n" >> pobj.stdin.write (password) >> pobj.stdin.write (password) >> #...... >> Block 2: >> #...... >> pobj = subprocess.Popen (["pdbedit", "-a", user], >> stdout=subprocess.PIPE, stdin =subprocess.PIPE) >> password = password + "\n" >> pobj.stdin.write (password) >> pobj.stdin.write (password) >> #...... >> >> The only difference is command to run, but code of Block 1 runs OK, >> and Block 2 can't write the password to "pdbedit". Is there any thing wrong >> with the code above or if something else cause Block 2 failed? Any >> suggestion ? >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > This isn't really a 'learning python' question. But I googled pdedit > and found this: Sorry for that, this is my first time to ask help to the community. > > -a This option is used to add a user into the database. This com- > mand needs a user name specified with the -u switch. When adding > a new user, pdbedit will also ask for the password to be used. > > Example: pdbedit -a -u sorce > new password: > retype new password Thanks for your patience and kindness! > So it looks like if you use -a you also need -u > > From isurveyor at vianet.net.au Wed Apr 25 05:54:36 2012 From: isurveyor at vianet.net.au (Ivor Surveyor) Date: Wed, 25 Apr 2012 11:54:36 +0800 Subject: [Tutor] Help with graphic file Message-ID: <3Vcnbn5zCDzMVD@mail.python.org> Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] Type "help", "copyright", "credits" or "license" for more information. Dear Steven D'Aprano I am most grateful for you directing me towards the file "graphics.py." I was able to download the file and inserted a copy into the directory containing Python. So far so good. I then run WIngIDE and typed "import python" into the editor followed by run in the Python shell. Below is a copy of the error message. It seems that files related to tkinter are not properly installed including Tcl. Can you please give me advice on how to correct this. Below I have copied the full details of the message from Python and below that the details of my system.\: >>>>>>>>> import graphics Traceback (most recent call last): File "C:\Program Files (x86)\Wing_IDLE_PYTHON\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 1, in # Used internally for debug sandbox under external interpreter File "C:\Program Files (x86)\graphics.py", line 168, in _root = tk.Tk() File "C:\Program Files (x86)\Lib\tkinter\__init__.py", line 1674, in __init__ self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use) _tkinter.TclError: Can't find a usable init.tcl in the following directories: {C:\Program Files (x86)\tcl\tcl8.5} {C:/Program Files (x86)/lib/tcl8.5} C:/lib/tcl8.5 C:/lib/tcl8.5 C:/library C:/library C:/tcl8.5.9/library C:/tcl8.5.9/library C:/Program Files (x86)/tcl/tcl8.5/init.tcl: version conflict for package "Tcl": have 8.5.9, need exactly 8.5.2 version conflict for package "Tcl": have 8.5.9, need exactly 8.5.2 while executing "package require -exact Tcl 8.5.2" (file "C:/Program Files (x86)/tcl/tcl8.5/init.tcl" line 20) invoked from within "source {C:/Program Files (x86)/tcl/tcl8.5/init.tcl}" ("uplevel" body line 1) invoked from within "uplevel #0 [list source $tclfile]" This probably means that Tcl wasn't installed properly. >>>>>> System Information report written at: 09/19/10 18:02:13 System Name: IVOR-PC [System Summary] Item Value OS Name Microsoft Windows 7 Professional Version 6.1.7600 Build 7600 Other OS Description Not Available OS Manufacturer Microsoft Corporation System Name IVOR-PC System Manufacturer MSI System Model MS-7636 System Type x64-based PC Processor Intel(R) Core(TM) i5 CPU 750 @ 2.67GHz, 2668 Mhz, 4 Core(s), 4 Logical Processor(s) BIOS Version/Date American Megatrends Inc. V1.3, 21/12/2009 SMBIOS Version 2.6 Windows Directory C:\Windows System Directory C:\Windows\system32 Boot Device \Device\HarddiskVolume1 Locale Australia Hardware Abstraction Layer Version = "6.1.7600.16385" User Name Ivor-PC\Ivor Time Zone W. Australia Standard Time Installed Physical Memory (RAM) 4.00 GB Total Physical Memory 3.96 GB Available Physical Memory 2.81 GB Total Virtual Memory 7.92 GB Available Virtual Memory 6.24 GB Page File Space 3.96 GB Page File C:\pagefile.sys Kind regards and thank you agian for assistance Ivor Surveyor isurveyor at vianet.net.au -------------- next part -------------- An HTML attachment was scrubbed... URL: From chnlion79 at gmail.com Wed Apr 25 06:41:30 2012 From: chnlion79 at gmail.com (Lion Chen) Date: Wed, 25 Apr 2012 12:41:30 +0800 Subject: [Tutor] gtk.TreeView displays all right on Windows, but can't see the values on Ubuntu Message-ID: <4F97807A.4010003@gmail.com> Hi, All, first thanks the people who gave helps to me, :) now i encountered another question... my first program LionCalculator, works ok on Windows, but there is a problem on Ubuntu. LionCalculator has a function that can store the previous calculation results to the gtk.ListStore((gobject.TYPE_STRING, gobject.TYPE_BOOLEAN, gobject.TYPE_STRING)) for i in xrange(12): self.results_store.append(["F%d" % (i+1), None, None]) when pressed F1--F12 or click the gtk.CellRendererRadio, the gtk.Entry will get the corresbonding values stored in ListStore. when i run the program on Windows, no problem, i can see everything that should display on the screen. but when i run it on Ubuntu, i can't see the "F1" -- "F12" in the ListStore, can't see the calculation results that should also display on ListStore, only the gtk.CellRendererRadio showed. i don't understand... and when i add "print ...get_store()[0][0]" and run it again, it print "F1"! strange... and when i press F1 or F2..., the result will copy to the entry, although it does not display in the TreeView, strange... the following are codes: #in class ResultsView...... def make_view(self): # make ListStore for storing results self.results_store = gtk.ListStore(gobject.TYPE_STRING, gobject.TYPE_BOOLEAN, gobject.TYPE_STRING) #to store 12 calculation results, the results_store[0][0] is "F1--F12" for i in xrange(12): self.results_store.append(["F%d" % (i+1), None, None]) self.results_view = gtk.TreeView(self.results_store) #f_renderer is for "F1" -- "F12" f_renderer = gtk.CellRendererText() f_renderer.set_property( 'editable', False ) f_renderer.set_property("size", 5) f_renderer.set_property("cell-background", "cyan") #when clicked bt_renderer, it will copy the corresbonding values to gtk.entry bt_renderer = gtk.CellRendererToggle() bt_renderer.set_property('activatable', True) bt_renderer.set_property("radio", True) bt_renderer.set_property("cell-background", "grey") bt_renderer.connect("toggled", self.ready_cp, self.results_store) #txt_renderer is for storing calculation results txt_renderer = gtk.CellRendererText() txt_renderer.set_property( 'editable', False ) txt_renderer.set_property("size", 5) txt_renderer.set_property("cell-background", "green") #i guess the problem is in the following, but i don't know where it exactly is, ok in Windows, can't show in Ubuntu... bt_column = gtk.TreeViewColumn("F1--F12") bt_column.pack_start(f_renderer, True) bt_column.pack_start(bt_renderer, False) bt_column.set_attributes(f_renderer, text=0) #set active to be clickable. and the bt_columen is #corresbonding to results_store columne 1 bt_column.add_attribute(bt_renderer, "active", 1) #and txt_column is corresbonding to the store column 2 txt_column = gtk.TreeViewColumn("Calculation Results ", txt_renderer, text=2) self.results_view.append_column(bt_column) self.results_view.append_column(txt_column) self.results_view.show() return self.results_view #in class LionCalc.... def __init__(self): ...... self.results_view = ResultsView() right_vbox.pack_start(self.results_view.make_view(), True, True, 0) win.show_all() could anybody give me help? thanks. -- Lion Chen From timomlists at gmail.com Wed Apr 25 09:11:32 2012 From: timomlists at gmail.com (Timo) Date: Wed, 25 Apr 2012 09:11:32 +0200 Subject: [Tutor] gtk.TreeView displays all right on Windows, but can't see the values on Ubuntu In-Reply-To: <4F97807A.4010003@gmail.com> References: <4F97807A.4010003@gmail.com> Message-ID: <4F97A3A4.4070207@gmail.com> Op 25-04-12 06:41, Lion Chen schreef: > Hi, All, Hi, please fix your formatting, the indentation is a big mess and makes it impossible to read. You should also ask your question on the PyGTK mailing list, not here. > first thanks the people who gave helps to me, :) > > now i encountered another question... > my first program LionCalculator, works ok on Windows, but there is a > problem on Ubuntu. > > LionCalculator has a function that can store the previous calculation > results to the > gtk.ListStore((gobject.TYPE_STRING, gobject.TYPE_BOOLEAN, > gobject.TYPE_STRING)) > > for i in xrange(12): > self.results_store.append(["F%d" % (i+1), None, None]) > > when pressed F1--F12 or click the gtk.CellRendererRadio, the gtk.Entry > will get the corresbonding values stored in ListStore. > > when i run the program on Windows, no problem, i can see everything that > should display on the screen. but when i run it on Ubuntu, i can't see > the "F1" -- "F12" in the ListStore, can't see the calculation results > that should also display on ListStore, only the gtk.CellRendererRadio > showed. > i don't understand... > > and when i add "print ...get_store()[0][0]" and run it again, it print > "F1"! strange... and when i press F1 or F2..., the result will copy to > the entry, > although it does not display in the TreeView, strange... > > the following are codes: > > #in class ResultsView...... > def make_view(self): > # make ListStore for storing results > self.results_store = gtk.ListStore(gobject.TYPE_STRING, > gobject.TYPE_BOOLEAN, > gobject.TYPE_STRING) > > #to store 12 calculation results, the results_store[0][0] is "F1--F12" > for i in xrange(12): > self.results_store.append(["F%d" % (i+1), None, None]) > > self.results_view = gtk.TreeView(self.results_store) > > #f_renderer is for "F1" -- "F12" > f_renderer = gtk.CellRendererText() > f_renderer.set_property( 'editable', False ) > f_renderer.set_property("size", 5) > f_renderer.set_property("cell-background", "cyan") > > #when clicked bt_renderer, it will copy the corresbonding values to > gtk.entry > bt_renderer = gtk.CellRendererToggle() > bt_renderer.set_property('activatable', True) > bt_renderer.set_property("radio", True) > bt_renderer.set_property("cell-background", "grey") > bt_renderer.connect("toggled", self.ready_cp, self.results_store) > > #txt_renderer is for storing calculation results > txt_renderer = gtk.CellRendererText() > txt_renderer.set_property( 'editable', False ) > txt_renderer.set_property("size", 5) > txt_renderer.set_property("cell-background", "green") > > #i guess the problem is in the following, but i don't know where it > exactly is, ok in Windows, can't show in Ubuntu... > bt_column = gtk.TreeViewColumn("F1--F12") > bt_column.pack_start(f_renderer, True) > bt_column.pack_start(bt_renderer, False) > bt_column.set_attributes(f_renderer, text=0) > #set active to be clickable. and the bt_columen is > #corresbonding to results_store columne 1 > bt_column.add_attribute(bt_renderer, "active", 1) > > #and txt_column is corresbonding to the store column 2 > txt_column = gtk.TreeViewColumn("Calculation Results ", txt_renderer, > text=2) > self.results_view.append_column(bt_column) > self.results_view.append_column(txt_column) > > self.results_view.show() > > return self.results_view > > #in class LionCalc.... > def __init__(self): > ...... > self.results_view = ResultsView() > right_vbox.pack_start(self.results_view.make_view(), True, True, 0) > > win.show_all() > > could anybody give me help? thanks. > From gerhardus.geldenhuis at gmail.com Wed Apr 25 11:36:16 2012 From: gerhardus.geldenhuis at gmail.com (Gerhardus Geldenhuis) Date: Wed, 25 Apr 2012 10:36:16 +0100 Subject: [Tutor] passing results between functions Message-ID: Hi I wrote two functions which does different manipulations on text files. To start out with I passed the filename as a parameter and each function opened the file and saved it. I then realized I would need to do that twice if I wanted to use both my functions on the same file. I the modified the functions to take the input as follows: myfunction(open(sys.argv[1]),'ro')) It still wasn't good enough so I modified the function to return data as follows: def myfunction returndata = [] # some code ... return ''.join(returndata) so now I can do myfunction(mysecondfunction(sys.argv[1],'ro')) or mysecondfunction(myfunction(sys.argv[1],'ro')) so my question is philosophical. Is that the pythonian way or is there a better/easier/more efficient way to pass data? To be honest I am still a bit stuck in how I did things when I programmed in Delphi years ago and trying to make the paradigm shift and understanding the data structures. Regards -- Gerhardus Geldenhuis -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Wed Apr 25 13:44:20 2012 From: d at davea.name (Dave Angel) Date: Wed, 25 Apr 2012 07:44:20 -0400 Subject: [Tutor] passing results between functions In-Reply-To: References: Message-ID: <4F97E394.6040300@davea.name> On 04/25/2012 05:36 AM, Gerhardus Geldenhuis wrote: > Hi > I wrote two functions which does different manipulations on text files. > > To start out with I passed the filename as a parameter and each function > opened the file and saved it. > > I then realized I would need to do that twice Do what twice? > if I wanted to use both my > functions on the same file. I the modified the functions to take the input > as follows: > myfunction(open(sys.argv[1]),'ro')) This is a syntax error. When posting code, please use copy/paste so we don't have to guess which part is just from your retyping. > It still wasn't good enough so I modified the function to return data as > follows: > > def myfunction This is another syntax error. Where are the parens, the arguments, or the colon? > returndata = [] Your email program destroyed the indentation here, or is this just another retyping error? > # some code > ... > return ''.join(returndata) > > so now I can do myfunction(mysecondfunction(sys.argv[1],'ro')) > or mysecondfunction(myfunction(sys.argv[1],'ro')) This won't work either, but guessing what's wrong would require that you actually post the function prototypes and return values. I infer that you return a single string from each function, but the functions take two parameters. Incidentally, in case you're planning to use the second parameter 'ro' as a mode for opening the file, I don't believe that 'o' is a valid mode value. > so my question is philosophical. Is that the pythonian way or is there a > better/easier/more efficient way to pass data? No clue till you actually post some code. > To be honest I am still a bit stuck in how I did things when I programmed > in Delphi years ago and trying to make the paradigm shift and understanding > the data structures. > > Regards > > -- DaveA From bala.biophysics at gmail.com Wed Apr 25 17:17:04 2012 From: bala.biophysics at gmail.com (Bala subramanian) Date: Wed, 25 Apr 2012 17:17:04 +0200 Subject: [Tutor] creating a regularly placed fields in a line Message-ID: Friends, I wrote a small piece of code (given below). The aim is to take each line in a file, split the fields, replace the first four fields and then write the new lines in a output file. The input and output are given in the attached file. The output contains fields which are irregularly placed depending up on the size of the field. I am thinking to fix the size of each field. Kindly provide me some way on how i can do the same or a better way to fix placement of fields. with open('tmp') as tp: for line in tp: line=line.split() p1=atm_type[line[0]];p2=atm_type[line[1]] p3=atm_type[line[2]];p4=atm_type[line[3]] new='\t'.join(line[4:10]) bond.write(' %s\t%s\t%s\t%s\t%s\n' % (p1,p2,p3,p4,new) ) -- C. Balasubramanian -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: test.output Type: application/octet-stream Size: 1025 bytes Desc: not available URL: From ramit.prasad at jpmorgan.com Wed Apr 25 17:57:03 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Wed, 25 Apr 2012 15:57:03 +0000 Subject: [Tutor] creating a regularly placed fields in a line In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF474092F9BFD@SCACMX008.exchad.jpmchase.net> > I wrote a small piece of code (given below). The aim is to take each line > in a file, split the fields, replace the first four fields and then write > the new lines in a output file. The input and output are given in the > attached file. The output contains fields which are irregularly placed > depending up on the size of the field. I am thinking to fix the size of > each field. Kindly provide me some way on how i can do the same or a > better way to fix placement of fields. > > with open('tmp') as tp: > for line in tp: > line=line.split() > p1=atm_type[line[0]];p2=atm_type[line[1]] > p3=atm_type[line[2]];p4=atm_type[line[3]] > new='\t'.join(line[4:10]) > bond.write(' %s\t%s\t%s\t%s\t%s\n' % (p1,p2,p3,p4,new) ) Taking a look at your output file leads me think that it is not really meant to be human readable. If it is only for a program to use, then I would just make it comma separated using the csv module. If you are intending to make it readable to humans, I would suggest looking at string formatting. It is better than tabbing since most clients show tabs a little differently and a tab may still cause irregular columns if you have a large difference in each row's column size. The formatting mini-language can be a little complex but luckily the guide is useful. http://docs.python.org/library/string.html#format-specification-mini-language The examples on that page are useful and I think what you want is quoted below. " Aligning the text and specifying a width: >>> '{:<30}'.format('left aligned') 'left aligned ' >>> '{:>30}'.format('right aligned') ' right aligned' >>> '{:^30}'.format('centered') ' centered ' >>> '{:*^30}'.format('centered') # use '*' as a fill char '***********centered***********' " Not really sure how to do the equivalent with % substitution. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From breamoreboy at yahoo.co.uk Wed Apr 25 18:58:32 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 25 Apr 2012 17:58:32 +0100 Subject: [Tutor] creating a regularly placed fields in a line In-Reply-To: <5B80DD153D7D744689F57F4FB69AF474092F9BFD@SCACMX008.exchad.jpmchase.net> References: <5B80DD153D7D744689F57F4FB69AF474092F9BFD@SCACMX008.exchad.jpmchase.net> Message-ID: On 25/04/2012 16:57, Prasad, Ramit wrote: > > Not really sure how to do the equivalent with % substitution. > > Ramit > See http://docs.python.org/library/stdtypes.html#string-formatting-operations -- Cheers. Mark Lawrence. From ramit.prasad at jpmorgan.com Wed Apr 25 19:15:20 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Wed, 25 Apr 2012 17:15:20 +0000 Subject: [Tutor] creating a regularly placed fields in a line In-Reply-To: References: <5B80DD153D7D744689F57F4FB69AF474092F9BFD@SCACMX008.exchad.jpmchase.net> Message-ID: <5B80DD153D7D744689F57F4FB69AF474092F9DA2@SCACMX008.exchad.jpmchase.net> > > > > Not really sure how to do the equivalent with % substitution. > > > > See > http://docs.python.org/library/stdtypes.html#string-formatting-operations > > Mark Lawrence. Thanks Mark. Based on that, I find .format more intuitive (especially for alignment) than % substitution. Useful to know both though, since lots of people swear by % substitution. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From alan.gauld at btinternet.com Wed Apr 25 20:12:22 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 25 Apr 2012 19:12:22 +0100 Subject: [Tutor] passing results between functions In-Reply-To: References: Message-ID: On 25/04/12 10:36, Gerhardus Geldenhuis wrote: > Hi > I wrote two functions which does different manipulations on text files. > > To start out with I passed the filename as a parameter and each function > opened the file and saved it. I assume you mean it did some processing on the file data and then wrote it back? > I then realized I would need to do that twice if I wanted to use both my > functions on the same file. I the modified the functions to take the > input as follows: > myfunction(open(sys.argv[1]),'ro')) You mean it took a file object and a string? > It still wasn't good enough so I modified the function to return data as > follows: > > def myfunction > returndata = [] > # some code > ... > return ''.join(returndata) So it returns a string. > so now I can do myfunction(mysecondfunction(sys.argv[1],'ro')) > or mysecondfunction(myfunction(sys.argv[1],'ro')) Thats inconsistent since to one occasion you pass two arguments but on the other only one - the return value of the first function. And since the first parameter is expecting a file object the string will cause an error. But if you fixed the inconsistent data issue then the principle is fine. > so my question is philosophical. Is that the pythonian way or is there a > better/easier/more efficient way to pass data? It depends what kind of data and what you mean by "pass". You could use objects to pass more complex types of data, or tuples to pass multiple values. Or you could write the values into a shared database. It just depends on what you want to do, whether the function needs to e thread-safe, how big the data is, etc. > To be honest I am still a bit stuck in how I did things when I > programmed in Delphi years ago and trying to make the paradigm shift and > understanding the data structures. Thee is virtually no difference between Delphi and Python in the way functions (and objects) work. I'm not sure what paradigmn shift you have in mind. Delphi can't return tuples, but other than that the options and styles are pretty similar. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Apr 25 20:32:28 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 25 Apr 2012 19:32:28 +0100 Subject: [Tutor] creating a regularly placed fields in a line In-Reply-To: References: Message-ID: On 25/04/12 16:17, Bala subramanian wrote: > placed depending up on the size of the field. I am thinking to fix the > size of each field. > with open('tmp') as tp: > for line in tp: >... > bond.write(' %s\t%s\t%s\t%s\t%s\n' % (p1,p2,p3,p4,new) ) Add your widths to the format string: bond.write(' %10s%20s%30s%10s%25s\n' % (p1,p2,p3,p4,new) ) adjust the lengths to suit. if you write the data in several places you can ensure consistency by defining the format string as a variable: fmt = ' %10s%20s%30s%10s%25s\n' bond.write( fmt % (p1,p2,p3,p4,new) ) hth, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From wayne at waynewerner.com Thu Apr 26 13:19:32 2012 From: wayne at waynewerner.com (Wayne Werner) Date: Thu, 26 Apr 2012 06:19:32 -0500 (CDT) Subject: [Tutor] creating a regularly placed fields in a line In-Reply-To: <5B80DD153D7D744689F57F4FB69AF474092F9DA2@SCACMX008.exchad.jpmchase.net> References: <5B80DD153D7D744689F57F4FB69AF474092F9BFD@SCACMX008.exchad.jpmchase.net> <5B80DD153D7D744689F57F4FB69AF474092F9DA2@SCACMX008.exchad.jpmchase.net> Message-ID: On Wed, 25 Apr 2012, Prasad, Ramit wrote: > Useful to > know both though, since lots of people swear by % substitution. And % formatting is slightly faster - if you end out doing tons of formatting and you find your script isn't fast enough, it's worth taking a look there. -Wayne From scarolan at gmail.com Thu Apr 26 21:24:38 2012 From: scarolan at gmail.com (Sean Carolan) Date: Thu, 26 Apr 2012 14:24:38 -0500 Subject: [Tutor] Python equivalent of "kill -0 PID" Message-ID: In bash you can do this to see if a process is running: [scarolan at kurobox:~/bin]$ kill -0 24275 [scarolan at kurobox:~/bin]$ echo $? 0 Is there a python equivalent? I tried using os.kill() but did not see any way to capture the output. From joel.goldstick at gmail.com Thu Apr 26 21:51:17 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Thu, 26 Apr 2012 15:51:17 -0400 Subject: [Tutor] Python equivalent of "kill -0 PID" In-Reply-To: References: Message-ID: On Thu, Apr 26, 2012 at 3:24 PM, Sean Carolan wrote: > In bash you can do this to see if a process is running: > > [scarolan at kurobox:~/bin]$ kill -0 24275 > [scarolan at kurobox:~/bin]$ echo $? > 0 > > Is there a python equivalent? ?I tried using os.kill() but did not see > any way to capture the output. > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor I don't know the answer to your question, but I googled this article: http://www.ibm.com/developerworks/aix/library/au-python/ It talks about various sys admin things you can do with python. It might get you started -- Joel Goldstick From mwalsh at mwalsh.org Thu Apr 26 22:29:20 2012 From: mwalsh at mwalsh.org (Martin Walsh) Date: Thu, 26 Apr 2012 15:29:20 -0500 Subject: [Tutor] Python equivalent of "kill -0 PID" In-Reply-To: References: Message-ID: <4F99B020.2020504@mwalsh.org> On 04/26/2012 02:24 PM, Sean Carolan wrote: > In bash you can do this to see if a process is running: > > [scarolan at kurobox:~/bin]$ kill -0 24275 > [scarolan at kurobox:~/bin]$ echo $? > 0 > > Is there a python equivalent? I tried using os.kill() but did not see > any way to capture the output. You might start with something like this ... # python2.x try: os.kill(24275, 0) except OSError, e: if e.errno != 3: # 3 = No such process raise # process is not running, do something else: # process is running, do something It would seem os.kill returns nothing if the signal is sent successfully, and will raise an exception if not. HTH! Marty From emailkgnow at gmail.com Fri Apr 27 06:08:35 2012 From: emailkgnow at gmail.com (Khalid Al-Ghamdi) Date: Fri, 27 Apr 2012 07:08:35 +0300 Subject: [Tutor] tkinter question Message-ID: hi everyone, I'm usting python 3.2 on windows, and I'm doing these GUI exercises using tkinter. I've created this simple window with two widgets (a label and a button) the button is supposed to exit the root window, but the problem is it doesn't seem to, for some reason. It looks like it is "trying to", but the window persists for some reason and becomes unresponsive. I'm NOT doing this in IDLE as i know there are issues with this. so is it an issue the Windows? or What? 1. import tkinter 2. top=tkinter.Tk() 3. 4. salam = tkinter.Label(top,text='salam') 5. salam.pack() 6. 7. quit= tkinter.Button(top, text='quit', command=top.quit,bg='red',fg= 'white') 8. * * 9. quit.pack(fill=tkinter.X) 10. 11. tkinter.mainloop() -------------- next part -------------- An HTML attachment was scrubbed... URL: From chare at labr.net Fri Apr 27 07:21:31 2012 From: chare at labr.net (Chris Hare) Date: Fri, 27 Apr 2012 00:21:31 -0500 Subject: [Tutor] PIL and converting an image to and from a string value Message-ID: <948D5E1E-23A7-46B9-B81C-BCF3EC233BFF@labr.net> Here is what I am trying to: the application user chooses an image file. I want to store the image data in a field in a sqlite database. My understanding from the reading I have done is that I have to convert the image data into a string , which I can then store in the database. Additionally, I need to be able to take the stored image data and convert it back to an image so I can display it in a canvas widget. I am using the python imaging library I think I have the following parts correct: image = Image.open("cover.jpg") image = image.resize((150,150),Image.ANTIALIAS) png = image.tostring("PNG") I am taking the image data from the file, resizing the image, and then using the PNG coder to force it into a PNG format image and converting it to a string. I am stuck however, in figuring out how to take the string data and converting it back to an image that I can put into the canvas widget. Either I am not finding a good explanation of how to do this or I am just not understanding what I am finding:-) Any ideas are appreciated! Thanks, Chris From isurveyor at vianet.net.au Fri Apr 27 08:49:11 2012 From: isurveyor at vianet.net.au (Ivor Surveyor) Date: Fri, 27 Apr 2012 14:49:11 +0800 Subject: [Tutor] virtualenv Message-ID: <3Vf5NR2YR2zMRk@mail.python.org> I recently asked the question how can I get graphic.py to work on my edition of Python which is 2.7.2 The problem was identified by Python tutor from my error messages as: "What that error is telling you is that you have a version 8.5.9 oftcl, but whatever you're trying to run is expecting _only_ 8.5.2 Sadly, probably, the way to "fix" this is by relaxing the requirements of the thing you're trying to run. Alternatively, look at virtualenv to set up an environment your code will work with." My next question is where do I obtain an appropriate version of virtualenv? My operating system is OS Name Microsoft Windows 7 Professional Version 6.1.7600 Build 7600 . I would appreciate any help, kind regards Ivor Surveyor isurveyor at vianet.net.au -------------- next part -------------- An HTML attachment was scrubbed... URL: From gerhardus.geldenhuis at gmail.com Fri Apr 27 14:58:54 2012 From: gerhardus.geldenhuis at gmail.com (Gerhardus Geldenhuis) Date: Fri, 27 Apr 2012 13:58:54 +0100 Subject: [Tutor] passing results between functions In-Reply-To: References: Message-ID: Thank you for all the replies. Having reread my question it is clear that it is not as well constructed as it should be. I will have a bit more of a think with regards to what I want to achieve and then if required rephrase my question. Best Regards On 25 April 2012 19:12, Alan Gauld wrote: > On 25/04/12 10:36, Gerhardus Geldenhuis wrote: > >> Hi >> I wrote two functions which does different manipulations on text files. >> >> To start out with I passed the filename as a parameter and each function >> opened the file and saved it. >> > > I assume you mean it did some processing on the file data and then wrote > it back? > > > I then realized I would need to do that twice if I wanted to use both my >> functions on the same file. I the modified the functions to take the >> input as follows: >> myfunction(open(sys.argv[1]),'**ro')) >> > > You mean it took a file object and a string? > > > It still wasn't good enough so I modified the function to return data as >> follows: >> >> def myfunction >> returndata = [] >> # some code >> ... >> return ''.join(returndata) >> > > So it returns a string. > > > so now I can do myfunction(mysecondfunction(**sys.argv[1],'ro')) >> or mysecondfunction(myfunction(**sys.argv[1],'ro')) >> > > Thats inconsistent since to one occasion you pass two arguments but on the > other only one - the return value of the first function. And since the > first parameter is expecting a file object the string will cause an error. > > But if you fixed the inconsistent data issue then the principle is fine. > > > so my question is philosophical. Is that the pythonian way or is there a >> better/easier/more efficient way to pass data? >> > > It depends what kind of data and what you mean by "pass". > You could use objects to pass more complex types of data, or tuples to > pass multiple values. Or you could write the values into a shared database. > It just depends on what you want to do, whether the function needs to e > thread-safe, how big the data is, etc. > > > To be honest I am still a bit stuck in how I did things when I >> programmed in Delphi years ago and trying to make the paradigm shift and >> understanding the data structures. >> > > Thee is virtually no difference between Delphi and Python in the way > functions (and objects) work. I'm not sure what paradigmn shift you have in > mind. Delphi can't return tuples, but other than that the options and > styles are pretty similar. > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -- Gerhardus Geldenhuis -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Fri Apr 27 16:02:27 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 27 Apr 2012 15:02:27 +0100 Subject: [Tutor] virtualenv In-Reply-To: <3Vf5NR2YR2zMRk@mail.python.org> References: <3Vf5NR2YR2zMRk@mail.python.org> Message-ID: On 27/04/2012 07:49, Ivor Surveyor wrote: > > I recently asked the question how can I get graphic.py to work on my > edition of Python which is 2.7.2 > The problem was identified by Python tutor from my error messages as: > > > "What that error is telling you is that you have a version 8.5.9 oftcl, > but whatever you're trying to run is expecting _only_ 8.5.2 > > Sadly, probably, the way to "fix" this is by relaxing the requirements > of the thing you're trying to run. Alternatively, look at virtualenv to > set up an environment your code will work with." > > My next question is where do I obtain an appropriate version of virtualenv? > > My operating system is > > OS Name Microsoft Windows 7 Professional > Version 6.1.7600 Build 7600 . > > I would appreciate any help, kind regards > > > Ivor Surveyor > isurveyor at vianet.net.au > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Google for python virtualenv windows and it's the first hit. -- Cheers. Mark Lawrence. From cranky.frankie at gmail.com Fri Apr 27 17:57:59 2012 From: cranky.frankie at gmail.com (Cranky Frankie) Date: Fri, 27 Apr 2012 11:57:59 -0400 Subject: [Tutor] running an imported function Message-ID: This is in 3.2.2. I wanted a function to clear the screen in IDLE. I have this in a clr.py file in a directory in my path: # Function to clear the IDLE screen by printing blank lines def clr(): '''Function to clear the IDLE screen by printing 50 lines.''' for i in range(1, 50): print() I can import it in IDLE no problem, but when I do this: >>> clr() I get Traceback (most recent call last): File "", line 1, in clr() TypeError: 'module' object is not callable Is there a way I can import clr.py and then run clr()? -- Frank L. "Cranky Frankie" Palmeri Risible Riding Raconteur & Writer ?The problem with quotes on the Internet is that it is often difficult to verify their authenticity.? - Abraham Lincoln From steve at pearwood.info Fri Apr 27 18:17:18 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 28 Apr 2012 02:17:18 +1000 Subject: [Tutor] running an imported function In-Reply-To: References: Message-ID: <4F9AC68E.50906@pearwood.info> Cranky Frankie wrote: > Is there a way I can import clr.py and then run clr()? The same way you import any other module and then call a function in that module. Don't be fooled by the function having the same name as the module. import clr # import the module clr.clr() # and call the fully-qualified name of the function Or if you prefer: from clr import clr # import only the function clr() By the way, this may be a simpler way of clearing the screen: def clr(): print("\n"*50) This is probably better, although it's not guaranteed to work for all terminal types: def clr(): print("\033[2J") -- Steven From chare at labr.net Fri Apr 27 17:53:20 2012 From: chare at labr.net (Chris Hare) Date: Fri, 27 Apr 2012 10:53:20 -0500 Subject: [Tutor] PIL and converting an image to and from a string value In-Reply-To: <948D5E1E-23A7-46B9-B81C-BCF3EC233BFF@labr.net> References: <948D5E1E-23A7-46B9-B81C-BCF3EC233BFF@labr.net> Message-ID: <270DD345-3EC4-4808-B6C5-9B3A7FF50975@labr.net> I got it figured out. On Apr 27, 2012, at 12:21 AM, Chris Hare wrote: > > Here is what I am trying to: > > the application user chooses an image file. I want to store the image data in a field in a sqlite database. My understanding from the reading I have done is that I have to convert the image data into a string , which I can then store in the database. Additionally, I need to be able to take the stored image data and convert it back to an image so I can display it in a canvas widget. I am using the python imaging library > > I think I have the following parts correct: > > image = Image.open("cover.jpg") > image = image.resize((150,150),Image.ANTIALIAS) > png = image.tostring("PNG") > > I am taking the image data from the file, resizing the image, and then using the PNG coder to force it into a PNG format image and converting it to a string. > > I am stuck however, in figuring out how to take the string data and converting it back to an image that I can put into the canvas widget. Either I am not finding a good explanation of how to do this or I am just not understanding what I am finding:-) > > Any ideas are appreciated! > > Thanks, > Chris > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From savtech138 at gmail.com Fri Apr 27 20:22:22 2012 From: savtech138 at gmail.com (Russell Smith) Date: Fri, 27 Apr 2012 11:22:22 -0700 Subject: [Tutor] PIL and converting an image to and from a string value In-Reply-To: <270DD345-3EC4-4808-B6C5-9B3A7FF50975@labr.net> References: <948D5E1E-23A7-46B9-B81C-BCF3EC233BFF@labr.net> <270DD345-3EC4-4808-B6C5-9B3A7FF50975@labr.net> Message-ID: What did you do? On Friday, April 27, 2012, Chris Hare wrote: > > I got it figured out. > > On Apr 27, 2012, at 12:21 AM, Chris Hare wrote: > > > > > Here is what I am trying to: > > > > the application user chooses an image file. I want to store the image > data in a field in a sqlite database. My understanding from the reading I > have done is that I have to convert the image data into a string , which I > can then store in the database. Additionally, I need to be able to take > the stored image data and convert it back to an image so I can display it > in a canvas widget. I am using the python imaging library > > > > I think I have the following parts correct: > > > > image = Image.open("cover.jpg") > > image = image.resize((150,150),Image.ANTIALIAS) > > png = image.tostring("PNG") > > > > I am taking the image data from the file, resizing the image, and then > using the PNG coder to force it into a PNG format image and converting it > to a string. > > > > I am stuck however, in figuring out how to take the string data and > converting it back to an image that I can put into the canvas widget. > Either I am not finding a good explanation of how to do this or I am just > not understanding what I am finding:-) > > > > Any ideas are appreciated! > > > > Thanks, > > Chris > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Fri Apr 27 20:54:24 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Fri, 27 Apr 2012 14:54:24 -0400 Subject: [Tutor] Is there a way I can print the output of help(module)? Message-ID: Its really nice how python displays help from the docstrings of modules. I'd like to save this info to a file, and I realize I've never come across how to do that. -- Joel Goldstick From steve at pearwood.info Fri Apr 27 21:03:07 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 28 Apr 2012 05:03:07 +1000 Subject: [Tutor] Is there a way I can print the output of help(module)? In-Reply-To: References: Message-ID: <4F9AED6B.7060600@pearwood.info> Joel Goldstick wrote: > Its really nice how python displays help from the docstrings of > modules. I'd like to save this info to a file, and I realize I've > never come across how to do that. At the command prompt (not the Python interactive interpreter!), run the pydoc command: pydoc math will display the documentation for help. pydoc -w math will write it to a file math.html. To do the same thing from the interactive interpreter, start with: import pydoc and go from there. -- Steven From joel.goldstick at gmail.com Fri Apr 27 21:11:59 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Fri, 27 Apr 2012 15:11:59 -0400 Subject: [Tutor] Is there a way I can print the output of help(module)? In-Reply-To: <4F9AED6B.7060600@pearwood.info> References: <4F9AED6B.7060600@pearwood.info> Message-ID: On Fri, Apr 27, 2012 at 3:03 PM, Steven D'Aprano wrote: > Joel Goldstick wrote: >> >> Its really nice how python displays help from the docstrings of >> modules. ?I'd like to save this info to a file, and I realize I've >> never come across how to do that. > > > At the command prompt (not the Python interactive interpreter!), run the > pydoc command: > > pydoc math > > will display the documentation for help. > > pydoc -w math > > will write it to a file math.html. > > > To do the same thing from the interactive interpreter, start with: > > import pydoc > > and go from there. > > > > -- > Steven > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Hey Steven, thanks. I guess I was a little lazy in my research. I just discovered pydocs before I read your response. Its great! This is great motivation to write concise and complete docstrings. -- Joel Goldstick From leamhall at gmail.com Fri Apr 27 21:20:11 2012 From: leamhall at gmail.com (Leam Hall) Date: Fri, 27 Apr 2012 15:20:11 -0400 Subject: [Tutor] Is there a way I can print the output of help(module)? In-Reply-To: References: <4F9AED6B.7060600@pearwood.info> Message-ID: <4F9AF16B.2040503@gmail.com> On 04/27/2012 03:11 PM, Joel Goldstick wrote: > Hey Steven, thanks. > > I guess I was a little lazy in my research. I just discovered pydocs > before I read your response. Its great! This is great motivation to > write concise and complete docstrings. > Joel, I am constantly amazed by all the things Python offers. Enjoy the language! Leam From alan.gauld at btinternet.com Sat Apr 28 01:54:38 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 28 Apr 2012 00:54:38 +0100 Subject: [Tutor] tkinter question In-Reply-To: References: Message-ID: On 27/04/12 05:08, Khalid Al-Ghamdi wrote: > I've created this simple window with two widgets (a label and a button) > the button is supposed to exit the root window, but the problem is it > doesn't seem to, > top=tkinter.Tk() > ... > tkinter.mainloop() try top.mainloop() I'm not sure if that makes a difference but it is usual to call mainloop() on the root widget, calling at the module level may do something strange... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From abasiemeka at gmail.com Sat Apr 28 03:06:17 2012 From: abasiemeka at gmail.com (Osemeka Osuagwu) Date: Sat, 28 Apr 2012 02:06:17 +0100 Subject: [Tutor] Pygame installation problems Message-ID: Hi, I started learning Python recently, having only very little programming experience. I installed Pygame and tried using >import pygame to test the installation and got the following error in return; Traceback (most recent call last): File "", line 1, in ImportError: No module named pygame Please does this mean I didn't install pygame correctly? How do I get it to work. Thanks, eMeka. -- *We have enough for our need but not enough for our greed.* -------------- next part -------------- An HTML attachment was scrubbed... URL: From savtech138 at gmail.com Sat Apr 28 03:41:18 2012 From: savtech138 at gmail.com (Russell Smith) Date: Fri, 27 Apr 2012 18:41:18 -0700 Subject: [Tutor] Pygame installation problems In-Reply-To: References: Message-ID: I would google 'pygame download' and look at the first hit. You are right to add the import but you need to download the files still. On Friday, April 27, 2012, Osemeka Osuagwu wrote: > Hi, > I started learning Python recently, having only very little programming > experience. I installed Pygame and tried using > > >import pygame > > to test the installation and got the following error in return; > > Traceback (most recent call last): > File "", line 1, in > ImportError: No module named pygame > > Please does this mean I didn't install pygame correctly? > How do I get it to work. > > Thanks, > > eMeka. > > > -- > *We have enough for our need but not enough for our greed.* > -------------- next part -------------- An HTML attachment was scrubbed... URL: From isurveyor at vianet.net.au Sat Apr 28 03:25:51 2012 From: isurveyor at vianet.net.au (Ivor Surveyor) Date: Sat, 28 Apr 2012 09:25:51 +0800 Subject: [Tutor] more help with vitualenv Message-ID: <3VfZZB6LM2zM45@mail.python.org> As suggested I visited the site virtualenv. However I could not find the files for download and to install on my machine. Could I please ask for further guidance on how to proceed? Ivor Surveyor isurveyor at vianet.net.au From savtech138 at gmail.com Sat Apr 28 03:51:00 2012 From: savtech138 at gmail.com (Russell Smith) Date: Fri, 27 Apr 2012 18:51:00 -0700 Subject: [Tutor] more help with vitualenv In-Reply-To: <3VfZZB6LM2zM45@mail.python.org> References: <3VfZZB6LM2zM45@mail.python.org> Message-ID: http://pypi.python.org/pypi/virtualenv/1.7.1.2 Read the page at the link above. You will find it. On Friday, April 27, 2012, Ivor Surveyor wrote: > > As suggested I visited the site virtualenv. However I could not find the > files for download and to install on my machine. > Could I please ask for further guidance on how to proceed? > > Ivor Surveyor > isurveyor at vianet.net.au > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From dineshbvadhia at hotmail.com Sat Apr 28 04:41:46 2012 From: dineshbvadhia at hotmail.com (Dinesh Vadhia) Date: Fri, 27 Apr 2012 19:41:46 -0700 Subject: [Tutor] (no subject) Message-ID: http://revistabuenosmuchachos.com/orndkty/247274.html -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sat Apr 28 06:46:29 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 28 Apr 2012 14:46:29 +1000 Subject: [Tutor] Pygame installation problems In-Reply-To: References: Message-ID: <4F9B7625.9080009@pearwood.info> Osemeka Osuagwu wrote: > Hi, > I started learning Python recently, having only very little programming > experience. I installed Pygame and tried using How did you install it? What operating system are you using? >> import pygame > > to test the installation and got the following error in return; > > Traceback (most recent call last): > File "", line 1, in > ImportError: No module named pygame > > Please does this mean I didn't install pygame correctly? Yes. -- Steven From steve at pearwood.info Sat Apr 28 06:58:56 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 28 Apr 2012 14:58:56 +1000 Subject: [Tutor] more help with vitualenv In-Reply-To: <3VfZZB6LM2zM45@mail.python.org> References: <3VfZZB6LM2zM45@mail.python.org> Message-ID: <4F9B7910.8040008@pearwood.info> Ivor Surveyor wrote: > > As suggested I visited the site virtualenv. However I could not find > the files for download and to install on my machine. > Could I please ask for further guidance on how to proceed? Which site did you go to? "virtualenv" is not a site, it is a name. Precision of language is your friend -- when asking for help, please be precise and accurate in your descriptions. When I google for "virtualenv", the very first link that comes up is this: http://pypi.python.org/pypi/virtualenv Is that the site you went to? If not, which site did you go to? On that site, there is a link "Downloads" almost at the top of the page, immediately under the title: virtualenv 1.7.1.2 Virtual Python Environment builder Downloads Clicking on the Downloads link takes you directly to the download area, where you can download a source tarball (.tar.gz file). Or if you prefer, there are other instructions for installing it. Do you have pip installed on your computer? If so, you can run pip install virtualenv from the command line (NOT the Python interactive interpreter) to automatically install virtualenv. Or if all else fails, the site above links directly to a single Python file which you can save to your hard drive. -- Steven From weij383 at hotmail.com Sat Apr 28 15:08:37 2012 From: weij383 at hotmail.com (Wei Juen Lo) Date: Sat, 28 Apr 2012 23:38:37 +1030 Subject: [Tutor] (no subject) Message-ID: here is my code for a calculator: def menu(): print "Welcome to calculator.py" print "your options are:" print " " print "1) Addition" print "2) Subtraction" print "3) Multiplication" print "4) Division" print "5) Quit calculator.py" print " " return input ("Choose your option: ") def add(a,b): print a, "+", b, "=", a + b def sub(a,b): print b, "-", a, "=", b - a def mul(a,b): print a, "*", b, "=", a * b def div(a,b): print a, "/", b, "=", a / b def main(): loop = 1 choice = 0 while loop == 1: choice = menu() if choice == 1: add(input("Add this: "),input("to this: ")) elif choice == 2: sub(input("Subtract this: "),input("from this: ")) elif choice == 3: mul(input("Multiply this: "),input("by this: ")) elif choice == 4: div(input("Divide this: "),input("by this: ")) elif choice == 5: loop = 0 print "Thank you for using calculator.py!" main() Few questions: why do i have to press enter for it to initialisewhy does it print the stuff in menu() again after doing the equationi am trying to understand classes if anyone has time to make all these functions go into a class calculator and have it still work and send me the code so i can have an example to refer to that would be great -------------- next part -------------- An HTML attachment was scrubbed... URL: From chare at labr.net Sat Apr 28 15:13:11 2012 From: chare at labr.net (Chris Hare) Date: Sat, 28 Apr 2012 08:13:11 -0500 Subject: [Tutor] PIL and converting an image to and from a string value In-Reply-To: References: <948D5E1E-23A7-46B9-B81C-BCF3EC233BFF@labr.net> <270DD345-3EC4-4808-B6C5-9B3A7FF50975@labr.net> Message-ID: <4E5CFCD4-1107-44A5-8BB7-A6848C64F310@labr.net> What I did: self.imageBuffer = StringIO.StringIO() image = Image.open(filename) image = image.resize((150,150),Image.ANTIALIAS) image.save(self.imageBuffer, format= 'PNG') self.imageBuffer.seek(0) image = Image.open(self.imageBuffer) So, that is how I got around the problem On Apr 27, 2012, at 1:22 PM, Russell Smith wrote: > What did you do? > > On Friday, April 27, 2012, Chris Hare wrote: > > I got it figured out. > > On Apr 27, 2012, at 12:21 AM, Chris Hare wrote: > > > > > Here is what I am trying to: > > > > the application user chooses an image file. I want to store the image data in a field in a sqlite database. My understanding from the reading I have done is that I have to convert the image data into a string , which I can then store in the database. Additionally, I need to be able to take the stored image data and convert it back to an image so I can display it in a canvas widget. I am using the python imaging library > > > > I think I have the following parts correct: > > > > image = Image.open("cover.jpg") > > image = image.resize((150,150),Image.ANTIALIAS) > > png = image.tostring("PNG") > > > > I am taking the image data from the file, resizing the image, and then using the PNG coder to force it into a PNG format image and converting it to a string. > > > > I am stuck however, in figuring out how to take the string data and converting it back to an image that I can put into the canvas widget. Either I am not finding a good explanation of how to do this or I am just not understanding what I am finding:-) > > > > Any ideas are appreciated! > > > > Thanks, > > Chris > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Apr 28 15:40:17 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 28 Apr 2012 14:40:17 +0100 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: On 28/04/12 14:08, Wei Juen Lo wrote: > def menu(): > > print "Welcome to calculator.py" > print "your options are:" > print " " > print "1) Addition" > print "2) Subtraction" > print "3) Multiplication" > print "4) Division" > print "5) Quit calculator.py" > print " " > return input ("Choose your option: ") > > def main(): > loop = 1 > choice = 0 > while loop == 1: > choice = menu() > if choice == 1: > add(input("Add this: "),input("to this: ")) > elif choice == 2: > sub(input("Subtract this: "),input("from this: ")) > elif choice == 3: > mul(input("Multiply this: "),input("by this: ")) > elif choice == 4: > div(input("Divide this: "),input("by this: ")) > elif choice == 5: > loop = 0 > Few questions: > > why do i have to press enter for it to initialise You don't, it goes straight into the menu loop. You have to press enter after typing input to tell python you have finished entering data. But the initialisation is the two lines before the while loop starts and you don't need to press enter for that. > why does it print the stuff in menu() again after doing the equation Because the first line inside the while loop is the call to the menu function: > while loop == 1: > choice = menu() Every time you finish a calculation, because loop is still 1 the program returns to the while and repeats the body of the loop. Starting with the call to menu() to get the next user selection. > i am trying to understand classes if anyone has time to make all these > functions go into a class calculator and have it still work and send me > the code so i can have an example to refer to that would be great There is absolutely no point in confusing yourself with classes if you don't understand the basics like the code above. Figure out how the basics work first before even beginning to worry about classes. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From chare at labr.net Sat Apr 28 15:15:53 2012 From: chare at labr.net (Chris Hare) Date: Sat, 28 Apr 2012 08:15:53 -0500 Subject: [Tutor] putting an image into a canvas object Message-ID: <147931BD-6EF9-4483-A63D-7FDC704F745D@labr.net> What I am trying to do is put an image on a canvas object, which I think is allowed. self.picture1 = Canvas(self.pictureFrame,width=150,height=150) self.imageBuffer = StringIO.StringIO() image = Image.open(filename) image = image.resize((150,150),Image.ANTIALIAS) image.save(self.imageBuffer, format= 'PNG') self.imageBuffer.seek(0) image = Image.open(self.imageBuffer) photo = PhotoImage(image) self.picture1.create_image(0, 0, image = photo ) However, this code results in the following exception:" Exception in Tkinter callback Traceback (most recent call last): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 1410, in __call__ return self.func(*args) File "z.py", line 803, in changePicture1 self.picture1.create_image(0, 0, image = photo ) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 2198, in create_image return self._create('image', args, kw) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 2189, in _create *(args + self._options(cnf, kw)))) TypeError: __str__ returned non-string (type instance) What did I do wrong? From abasiemeka at gmail.com Sat Apr 28 17:00:03 2012 From: abasiemeka at gmail.com (Osemeka Osuagwu) Date: Sat, 28 Apr 2012 16:00:03 +0100 Subject: [Tutor] Tutor Digest, Vol 98, Issue 70 In-Reply-To: References: Message-ID: I use 64bit Windows7 and Python 2.7.2 (upgraded from 2.6.6) I downloaded the windows binary from the pygame site (http://www.pygame.org/download.shtml) and ran it. During the installation I had to choose install directory, I left it at the default option (which created a new folder on my C: drive). On 4/28/12, 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. more help with vitualenv (Ivor Surveyor) > 2. Re: more help with vitualenv (Russell Smith) > 3. (no subject) (Dinesh Vadhia) > 4. Re: Pygame installation problems (Steven D'Aprano) > 5. Re: more help with vitualenv (Steven D'Aprano) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Sat, 28 Apr 2012 09:25:51 +0800 > From: Ivor Surveyor > To: tutor at python.org > Subject: [Tutor] more help with vitualenv > Message-ID: <3VfZZB6LM2zM45 at mail.python.org> > Content-Type: text/plain; charset="us-ascii"; format=flowed > > > As suggested I visited the site virtualenv. However I could not find > the files for download and to install on my machine. > Could I please ask for further guidance on how to proceed? > > Ivor Surveyor > isurveyor at vianet.net.au > > > > ------------------------------ > > Message: 2 > Date: Fri, 27 Apr 2012 18:51:00 -0700 > From: Russell Smith > To: Ivor Surveyor > Cc: "tutor at python.org" > Subject: Re: [Tutor] more help with vitualenv > Message-ID: > > Content-Type: text/plain; charset="iso-8859-1" > > http://pypi.python.org/pypi/virtualenv/1.7.1.2 > > Read the page at the link above. You will find it. > > On Friday, April 27, 2012, Ivor Surveyor wrote: > >> >> As suggested I visited the site virtualenv. However I could not find the >> files for download and to install on my machine. >> Could I please ask for further guidance on how to proceed? >> >> Ivor Surveyor >> isurveyor at vianet.net.au >> ______________________________**_________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/**mailman/listinfo/tutor >> > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > > > ------------------------------ > > Message: 3 > Date: Fri, 27 Apr 2012 19:41:46 -0700 > From: Dinesh Vadhia > To: , , > , , > , , , > , > Subject: [Tutor] (no subject) > Message-ID: > Content-Type: text/plain; charset="iso-8859-1" > > http://revistabuenosmuchachos.com/orndkty/247274.html > > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > > > ------------------------------ > > Message: 4 > Date: Sat, 28 Apr 2012 14:46:29 +1000 > From: Steven D'Aprano > To: tutor at python.org > Subject: Re: [Tutor] Pygame installation problems > Message-ID: <4F9B7625.9080009 at pearwood.info> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Osemeka Osuagwu wrote: >> Hi, >> I started learning Python recently, having only very little programming >> experience. I installed Pygame and tried using > > > How did you install it? > > What operating system are you using? > > >>> import pygame >> >> to test the installation and got the following error in return; >> >> Traceback (most recent call last): >> File "", line 1, in >> ImportError: No module named pygame >> >> Please does this mean I didn't install pygame correctly? > > Yes. > > > > -- > Steven > > > > ------------------------------ > > Message: 5 > Date: Sat, 28 Apr 2012 14:58:56 +1000 > From: Steven D'Aprano > To: tutor at python.org > Subject: Re: [Tutor] more help with vitualenv > Message-ID: <4F9B7910.8040008 at pearwood.info> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Ivor Surveyor wrote: >> >> As suggested I visited the site virtualenv. However I could not find >> the files for download and to install on my machine. >> Could I please ask for further guidance on how to proceed? > > Which site did you go to? "virtualenv" is not a site, it is a name. > Precision > of language is your friend -- when asking for help, please be precise and > accurate in your descriptions. > > When I google for "virtualenv", the very first link that comes up is this: > > http://pypi.python.org/pypi/virtualenv > > Is that the site you went to? If not, which site did you go to? > > On that site, there is a link "Downloads" almost at the top of the page, > immediately under the title: > > virtualenv 1.7.1.2 > Virtual Python Environment builder > Downloads > > > Clicking on the Downloads link takes you directly to the download area, > where > you can download a source tarball (.tar.gz file). > > > Or if you prefer, there are other instructions for installing it. Do you > have > pip installed on your computer? If so, you can run > > pip install virtualenv > > from the command line (NOT the Python interactive interpreter) to > automatically install virtualenv. > > Or if all else fails, the site above links directly to a single Python file > > which you can save to your hard drive. > > > > -- > Steven > > > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > End of Tutor Digest, Vol 98, Issue 70 > ************************************* > -- *We have enough for our need but not enough for our greed.* From d at davea.name Sat Apr 28 19:09:07 2012 From: d at davea.name (Dave Angel) Date: Sat, 28 Apr 2012 13:09:07 -0400 Subject: [Tutor] Tutor Digest, Vol 98, Issue 70 In-Reply-To: References: Message-ID: <4F9C2433.6000101@davea.name> On 04/28/2012 11:00 AM, Osemeka Osuagwu wrote: > I use 64bit Windows7 and Python 2.7.2 (upgraded from 2.6.6) > > I downloaded the windows binary from the pygame site > (http://www.pygame.org/download.shtml) and ran it. During the > installation I had to choose install directory, I left it at the > default option (which created a new folder on my C: drive). > > On 4/28/12, 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..." >> Like the man says, make a meaningful Subject for your message. If it's a reply to a previous one, you should reply to that particular message instead of the digest. But if you can't convince your email program to do that, at least fix the Subject line so it looks like a reply (Stick a Re: in front of the previous message's subject, if it doesn't already have one) Also, don't include a lot of nonsense that has nothing to do with your post. It's possible that something meaningful was in there, but we shouldn't have to hunt. So, back to the question you didn't ask. So pygame's install created a directory? it should be put into the existing python directory structure if you want python to be able to find it. -- DaveA From sntshkmr60 at gmail.com Sun Apr 29 00:48:49 2012 From: sntshkmr60 at gmail.com (Santosh Kumar) Date: Sun, 29 Apr 2012 04:18:49 +0530 Subject: [Tutor] Getting started with PyGTK [Receiving Error] Message-ID: System Information ---------------------------- Ubuntu 11.10 Python 2.7.2 Problem ------------ I think my Ubuntu has PyGTK and GTK both already installed. But however when I am importing "gtk" in Python interactive mode then I am getting the following warning: (.:4126): Gtk-WARNING **: Unable to locate theme engine in module_path: "pixmap", (.:4126): Gtk-WARNING **: Unable to locate theme engine in module_path: "pixmap", (.:4126): Gtk-WARNING **: Unable to locate theme engine in module_path: "pixmap", (.:4126): Gtk-WARNING **: Unable to locate theme engine in module_path: "pixmap", On the other side, importing "PyGTK" works well. What might be error? From alan.gauld at btinternet.com Sun Apr 29 01:23:05 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 29 Apr 2012 00:23:05 +0100 Subject: [Tutor] Getting started with PyGTK [Receiving Error] In-Reply-To: References: Message-ID: On 28/04/12 23:48, Santosh Kumar wrote: > System Information > ---------------------------- > Ubuntu 11.10 > Python 2.7.2 > > Problem > ------------ > > I think my Ubuntu has PyGTK and GTK both already installed. You should be able to confirm that by checking in Synaptic. > however when I am importing "gtk" in Python interactive mode then I am > getting the following warning: > > (.:4126): Gtk-WARNING **: Unable to locate theme engine in > module_path: "pixmap", > > On the other side, importing "PyGTK" works well. What might be error? What exactly does that mean? Do you mean yhou get no errors? Does it mean you can execute some sample code? The warnings above may not be serious, does gtk work in the sense of executing code? What happens if youi do help(gtk) ? However, Gtk is not a mainstream package for beginners to Python and not part of the standard library and that's what this list is focused on. You might get more detailed help on a pygtk forum, or maybe even a generic GTk forum since the error probably refers to some basic GTk feature. It certainly isn't a pure python issue. This page has some suggestions: http://www.pygtk.org/feedback.html -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From savtech138 at gmail.com Sun Apr 29 04:03:38 2012 From: savtech138 at gmail.com (Russell Smith) Date: Sat, 28 Apr 2012 19:03:38 -0700 Subject: [Tutor] Getting started with PyGTK [Receiving Error] In-Reply-To: References: Message-ID: Make sure you installed the theme engine 'pixmap' or whichever gtk package that has the theme engine you are missing. Google search for the gtk packages. Look here http://askubuntu.com/questions/66356/gdk-gtk-warnings-and-errors-from-the-command-lineand you will see a very similar problem with a solution which I bet will help you. Cheers On Saturday, April 28, 2012, Alan Gauld wrote: > On 28/04/12 23:48, Santosh Kumar wrote: > >> System Information >> ---------------------------- >> Ubuntu 11.10 >> Python 2.7.2 >> >> Problem >> ------------ >> >> I think my Ubuntu has PyGTK and GTK both already installed. >> > > You should be able to confirm that by checking in Synaptic. > > however when I am importing "gtk" in Python interactive mode then I am >> getting the following warning: >> >> (.:4126): Gtk-WARNING **: Unable to locate theme engine in >> module_path: "pixmap", >> >> On the other side, importing "PyGTK" works well. What might be error? >> > > > What exactly does that mean? Do you mean yhou get no errors? Does it mean > you can execute some sample code? > > The warnings above may not be serious, does gtk work in the sense of > executing code? What happens if youi do help(gtk) ? > > However, Gtk is not a mainstream package for beginners to Python and not > part of the standard library and that's what this list is focused on. You > might get more detailed help on a pygtk forum, or maybe even a generic GTk > forum since the error probably refers to some basic GTk feature. It > certainly isn't a pure python issue. > > This page has some suggestions: > > http://www.pygtk.org/feedback.**html > > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From russel at winder.org.uk Sun Apr 29 13:41:33 2012 From: russel at winder.org.uk (Russel Winder) Date: Sun, 29 Apr 2012 12:41:33 +0100 Subject: [Tutor] Getting started with PyGTK [Receiving Error] In-Reply-To: References: Message-ID: <1335699693.17704.4.camel@launcelot.winder.org.uk> Santosh, On Sun, 2012-04-29 at 04:18 +0530, Santosh Kumar wrote: > System Information > ---------------------------- > Ubuntu 11.10 > Python 2.7.2 > > Problem > ------------ > > I think my Ubuntu has PyGTK and GTK both already installed. But > however when I am importing "gtk" in Python interactive mode then I am > getting the following warning: > > (.:4126): Gtk-WARNING **: Unable to locate theme engine in > module_path: "pixmap", > > (.:4126): Gtk-WARNING **: Unable to locate theme engine in > module_path: "pixmap", > > (.:4126): Gtk-WARNING **: Unable to locate theme engine in > module_path: "pixmap", > > (.:4126): Gtk-WARNING **: Unable to locate theme engine in > module_path: "pixmap", > > On the other side, importing "PyGTK" works well. What might be error? This is an Ubuntu configuration error and nothing to do with Python or PyGTK. As Russell Smith notes you need to get Aptitude/Apt-Get/Synaptic/...whatever package manager you use... to ensure the pixmap engine is installed. Of course one has to ask why you are using that GTK engine, there are many other far better ones. It is also worth noting that PyGTK is effectively deprecated. PyGTK only works with GTK+2 it is not ported to GTK+3. Instead PyGObject is the way of working with GTK+3 from Python. http://readthedocs.org/docs/python-gtk-3-tutorial/en/latest/index.html -- Russel. ============================================================================= Dr Russel Winder t: +44 20 7585 2200 voip: sip:russel.winder at ekiga.net 41 Buckmaster Road m: +44 7770 465 077 xmpp: russel at winder.org.uk London SW11 1EN, UK w: www.russel.org.uk skype: russel_winder -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 198 bytes Desc: This is a digitally signed message part URL: From mmistroni at gmail.com Sun Apr 29 16:04:52 2012 From: mmistroni at gmail.com (Marco Mistroni) Date: Sun, 29 Apr 2012 15:04:52 +0100 Subject: [Tutor] VirutalEnv not working on Ubuntu server 9.10 Message-ID: HI all i have a VPS which is running Ubuntu server 9.10 i have downloaded virtualenv 1.4.2 and installed it in a tmp directory i have created a environment for using googlemaps.. i am able to download googlemaps package, but when i activate the environment , run python and type import googlemaps i receive the following error ImportError: no module caleld googlemaps ..BUt i have just imported it using pip install. here's output of doing pip install googlemaps Downloadign googlemaps-1.0.2 ... Running setup.py install for googlemaps Successfully installed googlemaps yet, when i type pytyon and start to import googlemaps all i receive is an error that the package does not exist what am i missing? w/kindest regards marco -------------- next part -------------- An HTML attachment was scrubbed... URL: From mmistroni at gmail.com Sun Apr 29 16:28:13 2012 From: mmistroni at gmail.com (Marco Mistroni) Date: Sun, 29 Apr 2012 15:28:13 +0100 Subject: [Tutor] VirutalEnv not working on Ubuntu server 9.10 / sorted Message-ID: Hello sorry to bother , found out hte problem. the imported packages work if i run python from the /bin directory of the virtualenv environment i have created w/kindest regards marco On Sun, Apr 29, 2012 at 3:04 PM, Marco Mistroni wrote: > HI all > i have a VPS which is running Ubuntu server 9.10 > > i have downloaded virtualenv 1.4.2 and installed it in a tmp directory > > i have created a environment for using googlemaps.. > > i am able to download googlemaps package, but when i activate the > environment , run python and type import googlemaps > i receive the following error > > ImportError: no module caleld googlemaps > > > ..BUt i have just imported it using pip install. here's output of doing > pip install googlemaps > > Downloadign googlemaps-1.0.2 > ... > > Running setup.py install for googlemaps > Successfully installed googlemaps > > yet, when i type pytyon and start to import googlemaps all i receive is > an error that the package does not exist > > what am i missing? > > w/kindest regards > marco > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Sun Apr 29 18:06:34 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sun, 29 Apr 2012 12:06:34 -0400 Subject: [Tutor] VirutalEnv not working on Ubuntu server 9.10 / sorted In-Reply-To: References: Message-ID: On Sun, Apr 29, 2012 at 10:28 AM, Marco Mistroni wrote: > Hello > ? sorry to bother , found out hte problem. the imported packages work if i > run python from the /bin directory of the virtualenv? environment i have > created > > w/kindest regards > ?marco > > On Sun, Apr 29, 2012 at 3:04 PM, Marco Mistroni wrote: >> >> HI all >> ?i have a VPS which is running Ubuntu server 9.10 >> >> i have downloaded virtualenv 1.4.2 and installed it in a tmp directory >> >> i have created a environment for using googlemaps.. >> >> i am able to download googlemaps package,? but when i activate the >> environment , run python? and type? import googlemaps >> i receive the following error >> >> ImportError: no module caleld googlemaps >> >> >> ..BUt i have just imported it using pip install. here's output of doing >> pip install googlemaps >> >> Downloadign googlemaps-1.0.2 >> ... >> >> Running setup.py install for googlemaps >> Successfully installed googlemaps >> >> yet, when i type pytyon? and start to import googlemaps all i receive is >> an error that the package does not exist >> >> what am i missing? >> >> w/kindest regards >> ?marco >> >> > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Did you know the current version is: virtualenv 1.7.1.2 They changed the default options so that site packages are not used by default -- Joel Goldstick From wprins at gmail.com Sun Apr 29 20:19:23 2012 From: wprins at gmail.com (Walter Prins) Date: Sun, 29 Apr 2012 19:19:23 +0100 Subject: [Tutor] Tutor Digest, Vol 98, Issue 70 In-Reply-To: References: Message-ID: Hi Osemeka, On 28 April 2012 16:00, Osemeka Osuagwu wrote: > I use 64bit Windows7 and Python 2.7.2 (upgraded from 2.6.6) > Do you use 64 bit Python 2.7.2 or 32 bit Python 2.7.2? > > I downloaded the windows binary from the pygame site > (http://www.pygame.org/download.shtml) and ran it. During the > installation I had to choose install directory, I left it at the > default option (which created a new folder on my C: drive). > Did you download and install the 32-bit or 64-bit version of Pygame? The links on the page you reference is the 32-bit versions. There are also some prerelease 64-bit binaries available elsewhere as mentioned on that page. Anyway, my spidey sense tells me that you're likely running a 64-bit version of Python and have installed the 32-bit version of Pygame. This won't work and may explain your current problem. To solve it, ensure the version of Python and PyGame matches each other in terms of being 32-bit or 64-bit as well as the version of Python targetted by Pygame. As a sidenote, please try and be neater in your posts. Useful subjects help, and the convention on this list is to bottom post, that is, comment/respond to a particular text below the relevant piece of quoted text. People may be inclined to skip over questions/posts which neglect to make some effort to be easy to read and comply with list ettiquette. Thanks, Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From shahviral.it at gmail.com Mon Apr 30 09:00:37 2012 From: shahviral.it at gmail.com (viral shah) Date: Mon, 30 Apr 2012 12:30:37 +0530 Subject: [Tutor] Fwd: help In-Reply-To: References: Message-ID: I want to print below matrix. can any one suggest me the method for the same 1 2 3 4 5 6 7 8 9 Thanks -- Viral Shah IT Department, E-mail : shahviral.it at gmail.com Mobile : (+91) 9722312220 -- Viral Shah IT Department, E-mail : shahviral.it at gmail.com Mobile : (+91) 9722312220 -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Apr 30 09:22:55 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 30 Apr 2012 08:22:55 +0100 Subject: [Tutor] Fwd: help In-Reply-To: References: Message-ID: On 30/04/12 08:00, viral shah wrote: > > > I want to print below matrix. > > can any one suggest me the method for the same > > 1 2 3 > 4 5 6 > 7 8 9 print ''' 1 2 3 4 5 6 7 8 9 ''' But I suspect you wanted more than that? But without some context I can't guess what. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From breamoreboy at yahoo.co.uk Mon Apr 30 09:27:47 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 30 Apr 2012 08:27:47 +0100 Subject: [Tutor] Fwd: help In-Reply-To: References: Message-ID: On 30/04/2012 08:00, viral shah wrote: > I want to print below matrix. > > can any one suggest me the method for the same > > 1 2 3 > 4 5 6 > 7 8 9 > > Thanks > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Quoting from c.l.p at 07:46 "In general, for homework questions, you should present your attempt at a solution, with specific questions where you are running into difficulty. Are you able to output anything using a python program? If not, you should take a look at one of the several excellent tutorials easily found by a web search. The official tutorial is at http://docs.python.org/py3k/tutorial/ and it might be enough for you to at least attempt a solution to your problem." -- Cheers. Mark Lawrence. From spawgi at gmail.com Mon Apr 30 09:34:04 2012 From: spawgi at gmail.com (spawgi at gmail.com) Date: Mon, 30 Apr 2012 13:04:04 +0530 Subject: [Tutor] Fwd: help In-Reply-To: References: Message-ID: What does your input look like? Please provide that information. Regards, - SWP On Mon, Apr 30, 2012 at 12:30 PM, viral shah wrote: > > > I want to print below matrix. > > can any one suggest me the method for the same > > 1 2 3 > 4 5 6 > 7 8 9 > > Thanks > > -- > Viral Shah > IT Department, > E-mail : shahviral.it at gmail.com > Mobile : (+91) 9722312220 > > > > > > > -- > Viral Shah > IT Department, > E-mail : shahviral.it at gmail.com > Mobile : (+91) 9722312220 > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- http://spawgi.wordpress.com We can do it and do it better. -------------- next part -------------- An HTML attachment was scrubbed... URL: From shahviral.it at gmail.com Mon Apr 30 11:50:21 2012 From: shahviral.it at gmail.com (viral shah) Date: Mon, 30 Apr 2012 15:20:21 +0530 Subject: [Tutor] Python Variable Addition Message-ID: Hi I'm new in the learning of python I want to make simple code for two variable addition Please help me in the following code *x = 12 print x y =20 print y z = x+y print 'Addition of above two numbers are : ' + int.z * when I run this same I got an error message : *AttributeError: type object 'int' has no attribute 'z' Please help me to solve the same error *-- Viral Shah IT Department, E-mail : shahviral.it at gmail.com Mobile : (+91) 9722312220 -------------- next part -------------- An HTML attachment was scrubbed... URL: From shukla.kapil at gmail.com Mon Apr 30 12:00:26 2012 From: shukla.kapil at gmail.com (=?utf-8?B?S2FwaWwgU2h1a2xhCiDgpJXgpKrgpL/gpLIg4KS24KWB4KSV4KWN4oCN4KSy4KS+?=) Date: Mon, 30 Apr 2012 10:00:26 +0000 Subject: [Tutor] Python Variable Addition In-Reply-To: References: Message-ID: <87191701-1335780026-cardhu_decombobulator_blackberry.rim.net-220256374-@b4.c5.bise3.blackberry> Viral You should be doing this "Addition of two numbers is" + str(x+y) + operator works on same datatypes and int being one of the built in objects in python does not have a method z U shld use str() or int() to do type conversion -Kapil ???? ??????? -----Original Message----- From: viral shah Sender: tutor-bounces+shukla.kapil=gmail.com at python.org Date: Mon, 30 Apr 2012 15:20:21 To: Subject: [Tutor] Python Variable Addition _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From d at davea.name Mon Apr 30 12:10:13 2012 From: d at davea.name (Dave Angel) Date: Mon, 30 Apr 2012 06:10:13 -0400 Subject: [Tutor] Python Variable Addition In-Reply-To: References: Message-ID: <4F9E6505.8090404@davea.name> On 04/30/2012 05:50 AM, viral shah wrote: > Hi > > I'm new in the learning of python > > I want to make simple code for two variable addition > > Please help me in the following code > > *x = 12 > print x > y =20 > print y > z = x+y > print 'Addition of above two numbers are : ' + int.z > * > when I run this same I got an error message : > > *AttributeError: type object 'int' has no attribute 'z' > > Please help me to solve the same error > > Welcome to Python tutor. Normally, the print statement accepts a list of items, separated by commas. Each item is implicitly converted to a string, and the results are sent to standard out, with a space between each item. So the most straightforward way to print z would be something like: print 'Addition of above two numbers are:', z Now, sometimes you want to combine two strings yourself, so you might use: print 'Addition of above two numbers are:' + str(z) Here we are using the str type as a conversion function. Note that we used parentheses, not the dot operator. And notice that since print only gets one item, it does not add a space. -- DaveA From anurag at grexit.com Mon Apr 30 12:38:35 2012 From: anurag at grexit.com (Anurag Maherchandani) Date: Mon, 30 Apr 2012 16:08:35 +0530 Subject: [Tutor] Imaplib Select Fails while connecting folder(**Labelname) of gmail Message-ID: I am using imaplib module for connecting to Gmail Imap, and i am getting the below mentioned error. I am using select command to connect Labelname is **LabelName I Get this Error: resp, data = self._imap.select("**LabelName") File "/usr/lib/python2.6/imaplib.py", line 642, in select typ, dat = self._simple_command(name, mailbox) File "/usr/lib/python2.6/imaplib.py", line 1060, in _simple_command return self._command_complete(name, self._command(name, *args)) File "/usr/lib/python2.6/imaplib.py", line 895, in _command_complete raise self.error('%s command error: %s %s' % (name, typ, data)) imaplib.error: SELECT command error: BAD ['Could not parse command'] whereas if the Labelname is ** LabelName It successfully connects. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Apr 30 19:36:10 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 30 Apr 2012 18:36:10 +0100 Subject: [Tutor] Python Variable Addition In-Reply-To: <87191701-1335780026-cardhu_decombobulator_blackberry.rim.net-220256374-@b4.c5.bise3.blackberry> References: <87191701-1335780026-cardhu_decombobulator_blackberry.rim.net-220256374-@b4.c5.bise3.blackberry> Message-ID: On 30/04/12 11:00, Kapil Shukla ???? ??????? wrote: > Viral > You should be doing this > > "Addition of two numbers is" + str(x+y) There is no need for str() since print implicitly calls string to convert objects to string format. Also the addition is not needed since print takes a comma separated list of arguments. So it would normally be: print 'Addition of above two numbers are : ', z > + operator works on same datatypes and Using addition on strings is quite expensive and there are usually better ways to do the same job. > int being one of the built in objects in python does not have a method z This however is true(ish - int is a type not strictly an object, except that everything in Python is an object, including types! :-) and it is the source of the original error message. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From breamoreboy at yahoo.co.uk Mon Apr 30 20:27:15 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 30 Apr 2012 19:27:15 +0100 Subject: [Tutor] Python Variable Addition In-Reply-To: References: <87191701-1335780026-cardhu_decombobulator_blackberry.rim.net-220256374-@b4.c5.bise3.blackberry> Message-ID: On 30/04/2012 18:36, Alan Gauld wrote: > On 30/04/12 11:00, Kapil Shukla ???? ??????? wrote: >> Viral >> You should be doing this >> >> "Addition of two numbers is" + str(x+y) > > There is no need for str() since print implicitly calls string to > convert objects to string format. Also the addition is not needed since > print takes a comma separated list of arguments. So it would normally be: > > print 'Addition of above two numbers are : ', z Except that you'll get two spaces after the colon :) > > >> + operator works on same datatypes and > > Using addition on strings is quite expensive and there are usually > better ways to do the same job. > > >> int being one of the built in objects in python does not have a method z > > This however is true(ish - int is a type not strictly an object, except > that everything in Python is an object, including types! :-) and it is > the source of the original error message. > -- Cheers. Mark Lawrence. From alan.gauld at btinternet.com Mon Apr 30 20:40:17 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 30 Apr 2012 19:40:17 +0100 Subject: [Tutor] Python Variable Addition In-Reply-To: References: <87191701-1335780026-cardhu_decombobulator_blackberry.rim.net-220256374-@b4.c5.bise3.blackberry> Message-ID: On 30/04/12 19:27, Mark Lawrence wrote: >> print 'Addition of above two numbers are : ', z > > Except that you'll get two spaces after the colon :) OK thats true, Try this: print 'Addition of above two numbers are :', z for one. :-) But if the number of spaces is critical string formatting is better still. And better than string addition. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From comer.duncan at gmail.com Mon Apr 30 23:25:45 2012 From: comer.duncan at gmail.com (Comer Duncan) Date: Mon, 30 Apr 2012 17:25:45 -0400 Subject: [Tutor] question about listing variables defined since session started Message-ID: Hi, I have a newbie type question. Say I have started a python (or ipython) session and have done some imports and have also defined some new variables since the session started. So, I have in my current namespace a bunch of things. Suppose I want to list just those variable names which have been defined since the session started but not include the names of the objects that who and whos will return. How to do that? In matlab, this is what the who returns, but in python I seem to always get a raft of things since I typically do import a bunch of things. Thanks for your suggestions. Comer From robert.sjoblom at gmail.com Mon Apr 30 23:35:17 2012 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Mon, 30 Apr 2012 23:35:17 +0200 Subject: [Tutor] question about listing variables defined since session started In-Reply-To: References: Message-ID: On 30 April 2012 23:25, Comer Duncan wrote: > Hi, > > I have a newbie type question. ?Say I have started a python (or > ipython) session and have done some imports and have also defined some > new variables since the session started. ?So, I have in my current > namespace a bunch of things. Suppose I ?want to list just those > variable ?names which have been defined since the session started but > not include the names of the objects that who and whos will return. > How to do that? Not entirely sure, but something like this might work (untested): for name in dir(): myvalue = eval(name) print name, "is", type(name), "and is equal to ", myvalue There's also global(), local() and vars(). -- best regards, Robert S.