From ross at ross.mayfirst.org Thu May 1 09:51:44 2008 From: ross at ross.mayfirst.org (Ross Glover) Date: Thu, 01 May 2008 03:51:44 -0400 Subject: [Tutor] put? Message-ID: <48197690.6050205@ross.mayfirst.org> Hi, I'm just learning python (as a first language) and I wrote this little snippet (cribbed from a website). I'm wondering what 'put' is and how it's used. I cannot seem to find much about it. > word = raw_input("enter your word >>") > put, get=os.popen4("dict -d wn " + (word)) > for lines in get.readlines(): > print lines thanks, ross -- If you know what you're doing, you must not be 'doing' a dissertation. From kent37 at tds.net Thu May 1 11:49:33 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 1 May 2008 05:49:33 -0400 Subject: [Tutor] put? In-Reply-To: <48197690.6050205@ross.mayfirst.org> References: <48197690.6050205@ross.mayfirst.org> Message-ID: <1c2a2c590805010249h438c5710tc98bd5caaf2138c8@mail.gmail.com> On Thu, May 1, 2008 at 3:51 AM, Ross Glover wrote: > Hi, I'm just learning python (as a first language) and I wrote this little > snippet (cribbed from a website). I'm wondering what 'put' is and how it's > used. I cannot seem to find much about it. > > > > word = raw_input("enter your word >>") > > put, get=os.popen4("dict -d wn " + (word)) > > for lines in get.readlines(): > > print lines put and get are variables that receive the result of the call to popen4(). The docs for popen4() are here: http://docs.python.org/lib/os-newstreams.html#os-newstreams It says popen4() "returns the file objects (child_stdin, child_stdout_and_stderr)", so put is linked to stdin for the child process. Kent From kriti_satija at yahoo.co.in Thu May 1 15:00:48 2008 From: kriti_satija at yahoo.co.in (Kriti Satija) Date: Thu, 1 May 2008 14:00:48 +0100 (BST) Subject: [Tutor] unsubscribtion Message-ID: <111202.92992.qm@web8515.mail.in.yahoo.com> Please unsubscribe my membership from python tutorlist. Bring your gang together. Do your thing. Find your favourite Yahoo! group at http://in.promos.yahoo.com/groups/ From nephish at gmail.com Thu May 1 15:13:30 2008 From: nephish at gmail.com (shawn bright) Date: Thu, 1 May 2008 08:13:30 -0500 Subject: [Tutor] send and receive HTTP POST In-Reply-To: <1c2a2c590804301205g6f37df39q6d9b925d8cdecc9d@mail.gmail.com> References: <384c93600804301113t2532b97epad03d9d3c1d69cb6@mail.gmail.com> <1c2a2c590804301205g6f37df39q6d9b925d8cdecc9d@mail.gmail.com> Message-ID: <384c93600805010613g447f3a91rdeedeac08179031c@mail.gmail.com> Thanks, sorry i was late getting back to you, but gmail thought this was spam. Go figure. Anyway, SOAPpy is doing great. Thanks shawn On Wed, Apr 30, 2008 at 2:05 PM, Kent Johnson wrote: > > POST /soap/SMS.asmx HTTP/1.1 > > Host: api.upsidewireless.com > > Content-Type: text/xml; charset=utf-8 > > Content-Length: length > > SOAPAction: "http://upsidewireless.com/webservice/sms/Send_Plain" > > It looks like you need SOAPpy: > http://diveintopython.org/soap_web_services/ > > Kent > From onyxtic at gmail.com Thu May 1 16:31:56 2008 From: onyxtic at gmail.com (Evans Anyokwu) Date: Thu, 1 May 2008 15:31:56 +0100 Subject: [Tutor] unsubscribtion In-Reply-To: <111202.92992.qm@web8515.mail.in.yahoo.com> References: <111202.92992.qm@web8515.mail.in.yahoo.com> Message-ID: Kriti, You can unsubscribe yourself without waiting for anyone to do it for you. Follow this link http://mail.python.org/mailman/listinfo/tutor Bye. Evans http://www.javawug.org On Thu, May 1, 2008 at 2:00 PM, Kriti Satija wrote: > Please unsubscribe my membership from python tutorlist. > > > Bring your gang together. Do your thing. Find your favourite Yahoo! > group at http://in.promos.yahoo.com/groups/ > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Thu May 1 16:34:39 2008 From: bgailer at gmail.com (bob gailer) Date: Thu, 01 May 2008 10:34:39 -0400 Subject: [Tutor] unsubscribtion In-Reply-To: <111202.92992.qm@web8515.mail.in.yahoo.com> References: <111202.92992.qm@web8515.mail.in.yahoo.com> Message-ID: <4819D4FF.1030408@gmail.com> Kriti Satija wrote: > Please unsubscribe my membership from python tutorlist. > > Only you can do that. Visit http://mail.python.org/mailman/listinfo/tutor -- Bob Gailer 919-636-4239 Chapel Hill, NC From alan.gauld at btinternet.com Thu May 1 19:43:20 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 1 May 2008 18:43:20 +0100 Subject: [Tutor] put? References: <48197690.6050205@ross.mayfirst.org> Message-ID: "Ross Glover" wrote > Hi, I'm just learning python (as a first language) and I wrote this > little snippet (cribbed from a website). I'm wondering what 'put' > is and how it's used. Hmmm. It sounds like you may be jumping in too deep too soon. Do you understand about files yet? Or variables? Are you comfortable with the concepts of stdin asnd stdout? If not you should probably stick to some of the more basic material until you understand those ideas. OTOH, if you are happy with those ideas: >> word = raw_input("enter your word >>") >> put, get=os.popen4("dict -d wn " + (word)) >> for lines in get.readlines(): >> print lines put and get are the return values from popen and correspond to stdin and stdout for the OS command inside popen(). get is the output of the command so the for loop prints the results of the command. Its a rather long-winded example IMHO. But it depends where you found it and what exactly it was illustrating! HTH -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From marc.tompkins at gmail.com Thu May 1 20:59:03 2008 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Thu, 1 May 2008 11:59:03 -0700 Subject: [Tutor] put? In-Reply-To: <48197690.6050205@ross.mayfirst.org> References: <48197690.6050205@ross.mayfirst.org> Message-ID: <40af687b0805011159t58daf481mca0b518c27e2ee3d@mail.gmail.com> On Thu, May 1, 2008 at 12:51 AM, Ross Glover wrote: > put, get=os.popen4("dict -d wn " + (word)) > > Something that can be a little confusing at first (and I haven't seen anybody mention it yet, so I thought I'd chime in) is that you can assign multiple variables at the same time. It can be a little jarring if you aren't used to it. So far you've probably only run into single assignments: x=5, dog=cat, etc. In contrast, this line runs a command that returns two values, and assigns those values to two variables called "put" and "get". If you weren't aware that multiple assignments were possible (and that this is what they look like), then this is a very confusing line of code indeed. Also - no offense to whoever put up the code you're learning from, but those variable names were poorly chosen! Since you're just starting out, you have the opportunity to learn good habits early. Don't use verbs as variable names! It is almost guaranteed to confuse the heck out of anybody who has to read your code later - maybe even yourself, if you don't look at it often. Variable naming conventions are a very contentious topic - you'll get fanatical supporters of "x" and "y", or Hungarian notation, or "VeryDescriptiveVariableName", or whatever, and I'm not going to make an endorsement... but I would make two hard and fast rules: - Don't use variable names that conflict with reserved words, e.g. don't create a list variable and name it "list". - Don't use variable names that SOUND like they might conflict with reserved words - like "put" and "get". -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From brnstrmrs at gmail.com Thu May 1 23:04:08 2008 From: brnstrmrs at gmail.com (Brain Stormer) Date: Thu, 1 May 2008 17:04:08 -0400 Subject: [Tutor] How to skip to next line in for loop Message-ID: <24bc7f6c0805011404j27dc2778s2a0f48f41d1a7347@mail.gmail.com> I have the following code: f = open('file.txt',r) for line in f.read(): if line == "3": line.next print line f.close() The file.txt looks like 1 2 3 4 5 I would like the code to output "4" but I don't know how to use the next. Are there any other way? Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Thu May 1 23:15:57 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 1 May 2008 17:15:57 -0400 Subject: [Tutor] How to skip to next line in for loop In-Reply-To: <24bc7f6c0805011404j27dc2778s2a0f48f41d1a7347@mail.gmail.com> References: <24bc7f6c0805011404j27dc2778s2a0f48f41d1a7347@mail.gmail.com> Message-ID: <1c2a2c590805011415j20f55565s48a06e6458d6da59@mail.gmail.com> On Thu, May 1, 2008 at 5:04 PM, Brain Stormer wrote: > I have the following code: > > f = open('file.txt',r) > for line in f.read(): > if line == "3": > line.next Try f.next() line is a string, it doesn't have a next() method. The file itself is iterable and has next(). Don't forget the parentheses! Kent > print line > f.close() > > The file.txt looks like > 1 > 2 > 3 > 4 > 5 > > I would like the code to output "4" > > but I don't know how to use the next. Are there any other way? > > Thanks > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From cuciferus at gmail.com Thu May 1 18:27:24 2008 From: cuciferus at gmail.com (ionut cucu) Date: Thu, 1 May 2008 19:27:24 +0300 Subject: [Tutor] unsubscribtion In-Reply-To: References: <111202.92992.qm@web8515.mail.in.yahoo.com> Message-ID: <20080501192724.10523cd8@cuci> Here's how to unsubscribe: First, ask your Internet Provider to mail you an Unsubscribing Kit. Then follow these directions. The kit will most likely be the standard no-fault type. Depending on requirements, System A and/or System B can be used. When operating System A, depress lever and a plastic dalkron unsubscriber will be dispensed through the slot immediately underneath. When you have fastened the adhesive lip, attach connection marked by the large "X" outlet hose. Twist the silver-coloured ring one inch below the connection point until you feel it lock. The kit is now ready for use. The Cin-Eliminator is activated by the small switch on the lip. When securing, twist the ring back to its initial condition, so that the two orange lines meet. Disconnect. Place the dalkron unsubscriber in the vacuum receptacle to the rear. Activate by pressing the blue button. The controls for System B are located on the opposite side. The red release switch places the Cin-Eliminator into position; it can be adjusted manually up or down by pressing the blue manual release button. The opening is self-adjusting. To secure after use, press the green button, which simultaneously activates the evaporator and returns the Cin-Eliminator to its storage position. You may log off if the green exit light is on over the evaporator. If the red light is illuminated, one of the Cin-Eliminator requirements has not been properly implemented. Press the "List Guy" call button on the right of the evaporator. He will secure all facilities from his control panel. To use the Auto-Unsub, first undress and place all your clothes in the clothes rack. Put on the velcro slippers located in the cabinet immediately below. Enter the shower, taking the entire kit with you. On the control panel to your upper right upon entering you will see a "Shower seal" button. Press to activate. A green light will then be illuminated immediately below. On the intensity knob, select the desired setting. Now depress the Auto-Unsub activation lever. Bathe normally. The Auto-Unsub will automatically go off after three minutes unless you activate the "Manual off" override switch by flipping it up. When you are ready to leave, press the blue "Shower seal" release button. The door will open and you may leave. Please remove the velcro slippers and place them in their container. If you prefer the ultrasonic log-off mode, press the indicated blue button. When the twin panels open, pull forward by rings A & B. The knob to the left, just below the blue light, has three settings, low, medium or high. For normal use, the medium setting is suggested. After these settings have been made, you can activate the device by switching to the "ON" position the clearly marked red switch. If during the unsubscribing operation you wish to change the settings, place the "manual off" override switch in the "OFF" position. You may now make the change and repeat the cycle. When the green exit light goes on, you may log off and have lunch. Please close the door behind you. From agent.krycek at gmail.com Fri May 2 00:02:15 2008 From: agent.krycek at gmail.com (Alex Krycek) Date: Thu, 1 May 2008 16:02:15 -0600 Subject: [Tutor] Problems sending POST data Message-ID: Hello all, I've been trying to send POST data to this library database with Python's urllib, but I can't get it to work. The website is http://catalog.denverlibrary.org/cgi-bin/cw_cgi?getLimitedTerms+2307(although the session expires after a short period of time. So it's better to first go to denverlibrary.org and then navigate to the advanced search page). This is the script that I used: ################################################################### import urllib queryString = "database=10&search1=%2F%2Fw&terms1=&bool1=and&search2=%2F%2Fn&terms2=&bool2=and&search3=%2F%2Ftw%2F&terms3=nanking&bool3=and&search4=%2F%2Fsd%2F&terms4=&bool4=and&search5=%2F%2Fed%2F&terms5=&spellcheck=false&keywords1=qdvds&keywords2=--none--&datelimit=%3E&year1=&year2=&limiter_count=3&branch=&Search=Search&Available=yes" url = " http://catalog.denverlibrary.org/cgi-bin/cw_cgi?customSearchFinish+17410" print urllib.urlopen(url, queryString).read() ################################################################### However, whenever I run the script I receive the page I was on (Advanced Search page) again. I'd like to get the page with the search results. This is what I got from livehttpheaders when I initiated a search from the website: ################################################################### http://catalog.denverlibrary.org/cgi-bin/cw_cgi?customSearchFinish+17410 POST /cgi-bin/cw_cgi?customSearchFinish+17410 HTTP/1.1 Host: catalog.denverlibrary.org User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9b5) Gecko/2008032620 Firefox/3.0b5 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip,deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive: 300 Connection: keep-alive Referer: http://catalog.denverlibrary.org/cgi-bin/cw_cgi?getLimitedTerms+17410 Cookie: __utma=109436176.390208191.1209600128.1209671991.1209676393.6; __utmz=109436176.1209600128.1.1.utmccn=(referral)|utmcsr= catalog.denverlibrary.org|utmcct=/cgi-bin/cw_cgi|utmcmd=referral; __utma=125080728.808666458.1209606982.1209606982.1209606982.1; __utmz=125080728.1209606982.1.1.utmccn=(referral)|utmcsr=denverlibrary.org|utmcct=/catalogs/index.html|utmcmd=referral; __utmc=109436176; __utmb=109436176 Content-Type: application/x-www-form-urlencoded Content-Length: 322 database=10&search1=%2F%2Fw&terms1=&bool1=and&search2=%2F%2Fn&terms2=&bool2=and&search3=%2F%2Ftw%2F&terms3=nanking&bool3=and&search4=%2F%2Fsd%2F&terms4=&bool4=and&search5=%2F%2Fed%2F&terms5=&spellcheck=false&keywords1=qdvds&keywords2=--none--&datelimit=%3E&year1=&year2=&limiter_count=3&branch=&Search=Search&Available=yes HTTP/1.x 302 Found Date: Thu, 01 May 2008 21:13:54 GMT Server: Apache/2.2.0 (Unix) DAV/2 mod_ssl/2.2.0 OpenSSL/0.9.8b PHP/5.1.6 JRun/4.0 Location: http://catalog.denverlibrary.org:80/cgi-bin/cw_cgi?resultsScreen+17410+1+1+0 Content-Length: 260 Keep-Alive: timeout=5, max=100 Connection: Keep-Alive Content-Type: text/html; charset=iso-8859-1 ################################################################### I'd appreciate any suggestions. Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Fri May 2 01:02:03 2008 From: bgailer at gmail.com (bob gailer) Date: Thu, 01 May 2008 19:02:03 -0400 Subject: [Tutor] put? In-Reply-To: <40af687b0805011159t58daf481mca0b518c27e2ee3d@mail.gmail.com> References: <48197690.6050205@ross.mayfirst.org> <40af687b0805011159t58daf481mca0b518c27e2ee3d@mail.gmail.com> Message-ID: <481A4BEB.7040402@gmail.com> Marc Tompkins wrote: > On Thu, May 1, 2008 at 12:51 AM, Ross Glover > wrote: > > put, get=os.popen4("dict -d wn " + (word)) > > Something that can be a little confusing at first (and I haven't seen > anybody mention it yet, so I thought I'd chime in) is that you can > assign multiple variables at the same time. It can be a little > jarring if you aren't used to it. So far you've probably only run > into single assignments: x=5, dog=cat, etc. > In contrast, this line runs a command that returns two values No No. Python does not have "commands" and can't therefore "run" them. A better way to express that is: on the right of the = is an expression which Python evaluates. > , and assigns those values to two variables called "put" and "get". > If you weren't aware that multiple assignments were possible (and that > this is what they look like), then this is a very confusing line of > code indeed. > > > Also - no offense to whoever put up the code you're learning from, but > those variable names were poorly chosen! Since you're just starting > out, you have the opportunity to learn good habits early. Don't use > verbs as variable names! It is almost guaranteed to confuse the heck > out of anybody who has to read your code later - maybe even yourself, > if you don't look at it often. > Variable naming conventions are a very contentious topic - you'll get > fanatical supporters of "x" and "y", or Hungarian notation, or > "VeryDescriptiveVariableName", or whatever, and I'm not going to make > an endorsement... but I would make two hard and fast rules: > - Don't use variable names that conflict with reserved words, e.g. > don't create a list variable and name it "list". > - Don't use variable names that SOUND like they might conflict with > reserved words - like "put" and "get". > > > > -- > www.fsrtechnologies.com > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Bob Gailer 919-636-4239 Chapel Hill, NC From bgailer at gmail.com Fri May 2 01:08:37 2008 From: bgailer at gmail.com (bob gailer) Date: Thu, 01 May 2008 19:08:37 -0400 Subject: [Tutor] How to skip to next line in for loop In-Reply-To: <24bc7f6c0805011404j27dc2778s2a0f48f41d1a7347@mail.gmail.com> References: <24bc7f6c0805011404j27dc2778s2a0f48f41d1a7347@mail.gmail.com> Message-ID: <481A4D75.6040302@gmail.com> Brain Stormer wrote: > I have the following code: > > f = open('file.txt',r) > for line in f.read(): That will read the entire file into a string, then access one character at a time from the string. If you want to work with lines: for line in f: > if line == "3": Assuming you adopt my approach, then each line will be a digit followed by \n (newline). So no line will == "3". Instead use: if line[:-1] == "3": > line.next Since next is a method it must be called, so that becomes: line.next() The rest is fine. > print line > f.close() > > The file.txt looks like > 1 > 2 > 3 > 4 > 5 > > I would like the code to output "4" > > but I don't know how to use the next. Are there any other way? -- Bob Gailer 919-636-4239 Chapel Hill, NC From bgailer at gmail.com Fri May 2 01:12:04 2008 From: bgailer at gmail.com (bob gailer) Date: Thu, 01 May 2008 19:12:04 -0400 Subject: [Tutor] unsubscribtion In-Reply-To: <20080501192724.10523cd8@cuci> References: <111202.92992.qm@web8515.mail.in.yahoo.com> <20080501192724.10523cd8@cuci> Message-ID: <481A4E44.50207@gmail.com> That sounds like irony. Somehow not suitable for this list or for someone seeking help as to how to unsubscribe. -- Bob Gailer 919-636-4239 Chapel Hill, NC From alan.gauld at btinternet.com Fri May 2 01:48:02 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 2 May 2008 00:48:02 +0100 Subject: [Tutor] How to skip to next line in for loop References: <24bc7f6c0805011404j27dc2778s2a0f48f41d1a7347@mail.gmail.com> Message-ID: "Brain Stormer" wrote > f = open('file.txt',r) > for line in f.read(): This reads the whole file inta a string then iterates over all the characters(not lines) in that string. Better to iterate over the file: for line in f: > if line == "3": > line.next this then becomes f.next() # next is a method not an attribute so needs the () to call it -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Fri May 2 01:51:19 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 2 May 2008 00:51:19 +0100 Subject: [Tutor] How to skip to next line in for loop References: <24bc7f6c0805011404j27dc2778s2a0f48f41d1a7347@mail.gmail.com> <481A4D75.6040302@gmail.com> Message-ID: "bob gailer" wrote >> if line == "3": > > Assuming you adopt my approach, then each line will be a digit > followed by \n (newline). So no line will == "3". Instead use: > > if line[:-1] == "3": or if line.rstrip() == "3" or even if line.startswith("3"): personally I prefer rstrip() over the -1 slice because it catches more potential junk. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Fri May 2 02:52:33 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 1 May 2008 20:52:33 -0400 Subject: [Tutor] Problems sending POST data In-Reply-To: References: Message-ID: <1c2a2c590805011752n7182dc0bt518d73ef6310fd2e@mail.gmail.com> On Thu, May 1, 2008 at 6:02 PM, Alex Krycek wrote: > Hello all, > > I've been trying to send POST data to this library database with Python's > urllib, but I can't get it to work. It looks like the library server wants to set a cookie in your browser and also responds with at redirect. I don't think urllib will handle either of those. Look at this page: http://personalpages.tds.net/~kent37/kk/00010.html for some tips on how to use urllib2 to handle cookies. Kent From ross at ross.mayfirst.org Fri May 2 05:42:53 2008 From: ross at ross.mayfirst.org (Ross Glover) Date: Thu, 01 May 2008 23:42:53 -0400 Subject: [Tutor] put? and files In-Reply-To: <40af687b0805011159t58daf481mca0b518c27e2ee3d@mail.gmail.com> References: <48197690.6050205@ross.mayfirst.org> <40af687b0805011159t58daf481mca0b518c27e2ee3d@mail.gmail.com> Message-ID: <481A8DBD.6060504@ross.mayfirst.org> Thanks all for your in[put]. It did take me a minute to figure out that 2 variables could get assigned using this method. Thanks to your help, I managed to cobble together a fully functional GUI based dictionary program (MY FIRST!). That said, it would seem that I do need to understand files better. Does anyone have a suggestion for a solid and detailed explanation? Either online or a book? What I want to do is write a program that parses text based on tags that I create, writes the text into separate files based on specified tags, i.e. each tag gets its own file. At least this is my starting goal. I've been working through the book Beginning Python, and I also went through AByteOfPython. Slowly it's beginning to make sense, but I would very much like to know what my next best step should be given the above mentioned goal. Text processing still eludes my understanding. Thanks again, ross -- If you know what you're doing, you must not be 'doing' a dissertation. From marc.tompkins at gmail.com Fri May 2 07:00:18 2008 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Thu, 1 May 2008 22:00:18 -0700 Subject: [Tutor] put? In-Reply-To: <481A4BEB.7040402@gmail.com> References: <48197690.6050205@ross.mayfirst.org> <40af687b0805011159t58daf481mca0b518c27e2ee3d@mail.gmail.com> <481A4BEB.7040402@gmail.com> Message-ID: <40af687b0805012200t2d414106ve80cad3c5a31bd7a@mail.gmail.com> On Thu, May 1, 2008 at 4:02 PM, bob gailer wrote: > Marc Tompkins wrote: > > > > In contrast, this line runs a command that returns two values > > > > No No. Python does not have "commands" and can't therefore "run" them. > > A better way to express that is: on the right of the = is an expression > which Python evaluates. a) Yes, of course, you're right, my semantics were all wrong. Serves me right for ranting before finishing my coffee. b) However, you're being a bit dogmatic, dontcha think? From the documentation: *popen*( command[, mode[, bufsize]]) Open a pipe to or from command. The return value is an open file object connected to the pipe, which can be read or written depending on whether mode is 'r' (default) or 'w'. The bufsizeargument has the same meaning as the corresponding argument to the built-in open() function. The exit status of the command (encoded in the format specified for wait()) is available as the return value of the close() method of the file object, except that when the exit status is zero (termination without errors), None is returned. Availability: Macintosh, Unix, Windows. The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. Changed in version 2.0: This function worked unreliably under Windows in earlier versions of Python. This was due to the use of the _popen() function from the libraries provided with Windows. Newer versions of Python do not use the broken implementation from the Windows libraries. Ease up, Bob. -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From rschroev_nospam_ml at fastmail.fm Fri May 2 09:55:56 2008 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Fri, 02 May 2008 09:55:56 +0200 Subject: [Tutor] How to skip to next line in for loop In-Reply-To: References: <24bc7f6c0805011404j27dc2778s2a0f48f41d1a7347@mail.gmail.com> Message-ID: Alan Gauld schreef: >> if line == "3": >> line.next > > this then becomes f.next() # next is a method not > an attribute so needs the () to call it Shouldn't it even be 'line = f.next()'? -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven From alan.gauld at btinternet.com Fri May 2 10:18:38 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 2 May 2008 09:18:38 +0100 Subject: [Tutor] put? and files References: <48197690.6050205@ross.mayfirst.org><40af687b0805011159t58daf481mca0b518c27e2ee3d@mail.gmail.com> <481A8DBD.6060504@ross.mayfirst.org> Message-ID: "Ross Glover" wrote > That said, it would seem that I do need to understand files better. > Does anyone have a suggestion for a solid and detailed explanation? > Either online or a book? Reading the Python tutorial section might be enough. If you understand the books you mention you should find the official tutorial easy enough. Or try my tutorial topic first for the basics. > I've been working through the book Beginning Python, and I also went > through AByteOfPython. Slowly it's beginning to make sense, but I > would very much like to know what my next best step should be given > the above mentioned goal. Text processing still eludes my > understanding. For text processing try the online version of David Mertz' book "Text Processing in Python" - try a Google search, I think its at gnossis.com or somesuch. The only caveat is that he is a fan of functional programming which can seem a tad strange if you aren't used to it. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Fri May 2 12:55:21 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 2 May 2008 06:55:21 -0400 Subject: [Tutor] How to skip to next line in for loop In-Reply-To: References: <24bc7f6c0805011404j27dc2778s2a0f48f41d1a7347@mail.gmail.com> Message-ID: <1c2a2c590805020355q7b6c8014q72f20c5d33d98265@mail.gmail.com> On Fri, May 2, 2008 at 3:55 AM, Roel Schroeven wrote: > Shouldn't it even be 'line = f.next()'? Wow, I think Brain Stormer should get a prize. I'm not sure what the prize is, but his short program has elicited incomplete and inaccurate answers from three of the top posters to this list! I *think* this is a complete answer: f = open('file.txt',r) for line in f: if line.rstrip() == "3": line = f.next() print line break # put this in if there is only one line you want to print f.close() ...awaiting any further corrections :-) Kent From kent37 at tds.net Fri May 2 13:23:15 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 2 May 2008 07:23:15 -0400 Subject: [Tutor] put? and files In-Reply-To: <481A8DBD.6060504@ross.mayfirst.org> References: <48197690.6050205@ross.mayfirst.org> <40af687b0805011159t58daf481mca0b518c27e2ee3d@mail.gmail.com> <481A8DBD.6060504@ross.mayfirst.org> Message-ID: <1c2a2c590805020423j74aa457bi417f07797980b816@mail.gmail.com> On Thu, May 1, 2008 at 11:42 PM, Ross Glover wrote: > Thanks all for your in[put]. It did take me a minute to figure out that 2 > variables could get assigned using this method. Thanks to your help, I > managed to cobble together a fully functional GUI based dictionary program > (MY FIRST!). > That said, it would seem that I do need to understand files better. Does > anyone have a suggestion for a solid and detailed explanation? Either > online or a book? I don't think you need to know more about files than you will get in any introductory book. The files chapter of Beginning Python should be fine. > What I want to do is write a program that parses text based on tags that I > create, writes the text into separate files based on specified tags, i.e. > each tag gets its own file. At least this is my starting goal. Text parsing varies widely. At the simple end, you can use string methods such as split(), strip() and slicing to extract the text you want. See the strings chapter of BP or http://docs.python.org/lib/string-methods.html The next level of complexity uses regular expressions to extract text. There is a bit of a learning curve to this, but regexes are a very powerful and useful tool that you can use outside of Python as well. They are helpful when your parser must recognize specific patterns. http://www.amk.ca/python/howto/regex/ For more complicated formats you will want a specialized parser. For example Python includes a parser for XML; BeautifulSoup is a popular third-party parser for HTML; pyparsing is a fairly easy-to-use library for building specialized parsers. You will want a specialized parser if your text format has many variations or if it allows nested patterns. If you give some examples of what you want to parse we can give more specific advice. Kent From brnstrmrs at gmail.com Fri May 2 16:05:37 2008 From: brnstrmrs at gmail.com (Brain Stormer) Date: Fri, 2 May 2008 10:05:37 -0400 Subject: [Tutor] How to skip to next line in for loop In-Reply-To: <1c2a2c590805020355q7b6c8014q72f20c5d33d98265@mail.gmail.com> References: <24bc7f6c0805011404j27dc2778s2a0f48f41d1a7347@mail.gmail.com> <1c2a2c590805020355q7b6c8014q72f20c5d33d98265@mail.gmail.com> Message-ID: <24bc7f6c0805020705j3fc55068q6cc1b5b77273b596@mail.gmail.com> Well, I was somewhat confused with all of the answers so I decided to go with my/following method. Kent's method has 4 fewer lines of code than mine and cleaner. Please correct me if I am fundamentally wrong. f=open('file.txt',r) for line in f.read().split(): if line == "3" position = True else: position = False if position == True print line position = False f.close() On Fri, May 2, 2008 at 6:55 AM, Kent Johnson wrote: > On Fri, May 2, 2008 at 3:55 AM, Roel Schroeven > wrote: > > > Shouldn't it even be 'line = f.next()'? > > Wow, I think Brain Stormer should get a prize. I'm not sure what the > prize is, but his short program has elicited incomplete and inaccurate > answers from three of the top posters to this list! I *think* this is > a complete answer: > > f = open('file.txt',r) > for line in f: > if line.rstrip() == "3": > line = f.next() > print line > break # put this in if there is only one line you want to print > f.close() > > ...awaiting any further corrections :-) > Kent > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Fri May 2 16:18:16 2008 From: bgailer at gmail.com (bob gailer) Date: Fri, 02 May 2008 10:18:16 -0400 Subject: [Tutor] How to skip to next line in for loop In-Reply-To: <24bc7f6c0805020705j3fc55068q6cc1b5b77273b596@mail.gmail.com> References: <24bc7f6c0805011404j27dc2778s2a0f48f41d1a7347@mail.gmail.com> <1c2a2c590805020355q7b6c8014q72f20c5d33d98265@mail.gmail.com> <24bc7f6c0805020705j3fc55068q6cc1b5b77273b596@mail.gmail.com> Message-ID: <481B22A8.1000906@gmail.com> Brain Stormer wrote: > Well, > I was somewhat confused with all of the answers so I decided to go > with my/following method. Kent's method has 4 fewer lines of code > than mine and cleaner. Please correct me if I am fundamentally wrong. > > f=open('file.txt',r) > > for line in f.read().split(): > if line == "3" > position = True > else: > position = False > if position == True > print line > position = False > f.close() > Yikes! That won't compile (missing : at end of if statements). After correcting, will print 3. How about this if you want less lines of code: f = open('file.txt',r).readlines() print f[[x+1 for x,line in enumerate(f) if line.rstrip() == "3"][0]] -- Bob Gailer 919-636-4239 Chapel Hill, NC From brnstrmrs at gmail.com Fri May 2 16:28:15 2008 From: brnstrmrs at gmail.com (Brain Stormer) Date: Fri, 2 May 2008 10:28:15 -0400 Subject: [Tutor] How to skip to next line in for loop In-Reply-To: <481B22A8.1000906@gmail.com> References: <24bc7f6c0805011404j27dc2778s2a0f48f41d1a7347@mail.gmail.com> <1c2a2c590805020355q7b6c8014q72f20c5d33d98265@mail.gmail.com> <24bc7f6c0805020705j3fc55068q6cc1b5b77273b596@mail.gmail.com> <481B22A8.1000906@gmail.com> Message-ID: <24bc7f6c0805020728y67ba6a11v62e606da22a87461@mail.gmail.com> You are correct. It is missing the ":" and it will print "3" On Fri, May 2, 2008 at 10:18 AM, bob gailer wrote: > Brain Stormer wrote: > > > Well, > > I was somewhat confused with all of the answers so I decided to go with > > my/following method. Kent's method has 4 fewer lines of code than mine and > > cleaner. Please correct me if I am fundamentally wrong. > > > > f=open('file.txt',r) > > > > for line in f.read().split(): > > if line == "3" > > position = True > > else: > > position = False > > if position == True > > print line > > position = False > > f.close() > > > > Yikes! That won't compile (missing : at end of if statements). After > correcting, will print 3. > > How about this if you want less lines of code: > > f = open('file.txt',r).readlines() > print f[[x+1 for x,line in enumerate(f) if line.rstrip() == "3"][0]] > > > -- > Bob Gailer > 919-636-4239 Chapel Hill, NC > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From brnstrmrs at gmail.com Fri May 2 16:34:23 2008 From: brnstrmrs at gmail.com (Brain Stormer) Date: Fri, 2 May 2008 10:34:23 -0400 Subject: [Tutor] How to skip to next line in for loop In-Reply-To: <24bc7f6c0805020728y67ba6a11v62e606da22a87461@mail.gmail.com> References: <24bc7f6c0805011404j27dc2778s2a0f48f41d1a7347@mail.gmail.com> <1c2a2c590805020355q7b6c8014q72f20c5d33d98265@mail.gmail.com> <24bc7f6c0805020705j3fc55068q6cc1b5b77273b596@mail.gmail.com> <481B22A8.1000906@gmail.com> <24bc7f6c0805020728y67ba6a11v62e606da22a87461@mail.gmail.com> Message-ID: <24bc7f6c0805020734r212c7ef1u47dd18ff19878ff1@mail.gmail.com> f=open('file.txt',r) position =False for line in f.read().split(): if position == True print line position = False if line == "3": position = True else: position = False f.close() On Fri, May 2, 2008 at 10:28 AM, Brain Stormer wrote: > You are correct. It is missing the ":" and it will print "3" > > On Fri, May 2, 2008 at 10:18 AM, bob gailer wrote: > > > Brain Stormer wrote: > > > > > Well, > > > I was somewhat confused with all of the answers so I decided to go > > > with my/following method. Kent's method has 4 fewer lines of code than > > > mine and cleaner. Please correct me if I am fundamentally wrong. > > > > > > f=open('file.txt',r) > > > > > > for line in f.read().split(): > > > if line == "3" > > > position = True > > > else: > > > position = False > > > if position == True > > > print line > > > position = False > > > f.close() > > > > > > Yikes! That won't compile (missing : at end of if statements). After > > correcting, will print 3. > > > > How about this if you want less lines of code: > > > > f = open('file.txt',r).readlines() > > print f[[x+1 for x,line in enumerate(f) if line.rstrip() == "3"][0]] > > > > > > -- > > Bob Gailer > > 919-636-4239 Chapel Hill, NC > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bryan.fodness at gmail.com Fri May 2 17:12:12 2008 From: bryan.fodness at gmail.com (Bryan Fodness) Date: Fri, 2 May 2008 11:12:12 -0400 Subject: [Tutor] best way to get external data Message-ID: I am trying to figure out the best way to get external data. Using the following data in a file 1 2 3 I have used, fi = open(infile, 'r') s = fi.readlines() fi.close() a = s[0] b = s[1] c = s[2] but, if I have, x = 1 y = 2 z = 3 I have used, for line in open(infile): i_line = line.split() if i_line[0] == 'x': a = i_line[2] elif i_line[0] == 'y': b = i_line[2] elif i_line[0] == 'z': c = i_line[2] I do have control over the creation of the data file. The second way is better in my mind, because it is independent of the ordering. If I have a long list of 'variable' = 'value', could this be better managed in a dictionary? Or, is there a better way? Thanks -- "The game of science can accurately be described as a never-ending insult to human intelligence." - Jo?o Magueijo -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Fri May 2 17:21:27 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 2 May 2008 11:21:27 -0400 Subject: [Tutor] How to skip to next line in for loop In-Reply-To: <24bc7f6c0805020734r212c7ef1u47dd18ff19878ff1@mail.gmail.com> References: <24bc7f6c0805011404j27dc2778s2a0f48f41d1a7347@mail.gmail.com> <1c2a2c590805020355q7b6c8014q72f20c5d33d98265@mail.gmail.com> <24bc7f6c0805020705j3fc55068q6cc1b5b77273b596@mail.gmail.com> <481B22A8.1000906@gmail.com> <24bc7f6c0805020728y67ba6a11v62e606da22a87461@mail.gmail.com> <24bc7f6c0805020734r212c7ef1u47dd18ff19878ff1@mail.gmail.com> Message-ID: <1c2a2c590805020821t7509bc2fofc0e7665e77f9ce0@mail.gmail.com> On Fri, May 2, 2008 at 10:34 AM, Brain Stormer wrote: > f=open('file.txt',r) > position =False > > for line in f.read().split(): Note that split() splits on any whitespace, not just line endings. In your case it doesn't much matter I guess. Kent From pythoninfo at dodgycauldron.com Fri May 2 17:33:56 2008 From: pythoninfo at dodgycauldron.com (Stephanie) Date: Fri, 2 May 2008 10:33:56 -0500 Subject: [Tutor] python -v command Message-ID: <315a79d00805020833g605a585aib83a36ed382e465d@mail.gmail.com> Hi, I'm at a very beginning level of Python knowledge, but I use several Python programs via the Macintosh Unix Terminal. I was trying to quickly see which version of Python I am running and typed in the command "python -v". That was obviously not the correct command to use. It installed several things and now I'm unable to run my Python programs. Can someone tell me if there there is a way to undo the python -v command? Any suggestions for how I can remedy the situation. I'm ready to crawl into a dark hole and hide - I feel very foolish! Thanks so much for putting up with a newbie's silly question. Here's the Terminal output in case that helps at all: admin$ python -v # installing zipimport hook import zipimport # builtin # installed zipimport hook # /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/site.pyc matches /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/site.py import site # precompiled from /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/site.pyc # /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/os.pyc matches /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/os.py import os # precompiled from /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/os.pyc import posix # builtin # /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/posixpath.pyc matches /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/posixpath.py import posixpath # precompiled from /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/posixpath.pyc # /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/stat.pyc matches /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/stat.py import stat # precompiled from /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/stat.pyc # /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/UserDict.pyc matches /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/UserDict.py import UserDict # precompiled from /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/UserDict.pyc # /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/copy_reg.pyc matches /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/copy_reg.py import copy_reg # precompiled from /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/copy_reg.pyc # /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/types.pyc matches /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/types.py import types # precompiled from /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/types.pyc # /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/warnings.pyc matches /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/warnings.py import warnings # precompiled from /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/warnings.pyc # /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/linecache.pyc matches /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/linecache.py import linecache # precompiled from /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/linecache.pyc import encodings # directory /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/encodings # /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/encodings/__init__.pyc matches /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/encodings/__init__.py import encodings # precompiled from /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/encodings/__init__.pyc # /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/codecs.pyc matches /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/codecs.py import codecs # precompiled from /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/codecs.pyc import _codecs # builtin # /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/encodings/aliases.pyc matches /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/encodings/aliases.py import encodings.aliases # precompiled from /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/encodings/aliases.pyc # /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/encodings/ascii.pyc matches /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/encodings/ascii.py import encodings.ascii # precompiled from /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/encodings/ascii.pyc Python 2.4.4 (#1, Oct 18 2006, 10:34:39) [GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin Type "help", "copyright", "credits" or "license" for more information. import readline # dynamically loaded from /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/lib-dynload/readline.so >>> -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Fri May 2 17:40:41 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 2 May 2008 11:40:41 -0400 Subject: [Tutor] best way to get external data In-Reply-To: References: Message-ID: <1c2a2c590805020840v2772f90dwb57bdee6df54b576@mail.gmail.com> On Fri, May 2, 2008 at 11:12 AM, Bryan Fodness wrote: > I am trying to figure out the best way to get external data. 1. Put the data in a Python module and import it 2. Put the data in a .ini file and read it with the ConfigParser module http://docs.python.org/lib/module-ConfigParser.html > If I have a long list of 'variable' = 'value', could this be better managed in a dictionary? Possibly. When you have a list of variables you are trying to create by name, a dictionary is definitely suggested. Kent From ptmcg at austin.rr.com Fri May 2 17:42:28 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Fri, 2 May 2008 10:42:28 -0500 Subject: [Tutor] How to skip to next line in for loop In-Reply-To: References: Message-ID: <003a01c8ac6b$207eacf0$6500a8c0@AWA2> Augghh! I can't stand it!!! If position is a boolean, then *why* must we test if it is equal to True?!!! It's a boolean! Just test it! For that matter, let's rename "position" to something a little more direct, "print_line" perhaps? Did you know that files are now iterators? If going through the file line by line, no need for read().split(), or readlines(), or anything else, just iterate over f: f=open('file.txt',r) print_line = False for line in f: if print_line: print line print_line = False if line == "3": print_line = True f.close() Is there only one line containing a "3" in this file? What if that were the 3rd line in a file containing 50 zillion lines? After printing the line after "3", this program iterates through the whole rest of the file, for nothing. Nothing! If you only want the first (or only) line after the line containing "3", then do: f=open('file.txt',r) print_line = False for line in f: if print_line: print line # found it, no need to read any further break if line == "3": print_line = True f.close() -- Paul From inthefridge at gmail.com Fri May 2 18:08:04 2008 From: inthefridge at gmail.com (Spencer Parker) Date: Fri, 2 May 2008 10:08:04 -0600 Subject: [Tutor] Regular expressions... Message-ID: I need to use a regular expression to get a couple of items for my python script. So far the script is running an 'ls' command to get a few items that I need I run an 'ls -sk /xen/domains2/machinename/disk.img' Output 2454112 /xen/domains2/machinename/disk.img Then I have it running an 'ls -lk /xen/domains2/machinename/disk.img output: -rw-r--r-- 1 root root 20980736 May 2 10:05 /xen/domains2/machinename/disk.img Then I take those two number and divide them using the the used amount by the actual size of the disk to get a percentage. I take all of that data and then stick it into a database. What I need to get is just the size numbers using regular expressions. I tried using an index, but since the disk images can up to 20 gig and be as low as 5 gig...the index changes. I also need to get the 'machinename' portion of the path as well to stick into the database. -- Spencer Parker _______________________________________________________ "if you can't go to heaven, may you at least die in Ireland." _______________________________________________________ -------------- next part -------------- An HTML attachment was scrubbed... URL: From malaclypse2 at gmail.com Fri May 2 18:13:33 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Fri, 2 May 2008 12:13:33 -0400 Subject: [Tutor] python -v command In-Reply-To: <315a79d00805020833g605a585aib83a36ed382e465d@mail.gmail.com> References: <315a79d00805020833g605a585aib83a36ed382e465d@mail.gmail.com> Message-ID: <16651e80805020913o6050fb3x9bb50dd3cfe8db77@mail.gmail.com> On Fri, May 2, 2008 at 11:33 AM, Stephanie wrote: > Hi, > I'm at a very beginning level of Python knowledge, but I use several Python > programs via the Macintosh Unix Terminal. I was trying to quickly see which > version of Python I am running and typed in the command "python -v". That > was obviously not the correct command to use. It installed several things > and now I'm unable to run my Python programs. > > Can someone tell me if there there is a way to undo the python -v command? > Any suggestions for how I can remedy the situation. 'python -v' just runs the python interpreter in verbose mode -- all those messages are about various libraries the interactive interpreter loads before it gives you the prompt. Running 'python -v' didn't (or at least should not) change anything in your environment. Can you show us what happens when you try to run some of your existing code that used to work? -- Jerry From kent37 at tds.net Fri May 2 18:16:57 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 2 May 2008 12:16:57 -0400 Subject: [Tutor] python -v command In-Reply-To: <315a79d00805020833g605a585aib83a36ed382e465d@mail.gmail.com> References: <315a79d00805020833g605a585aib83a36ed382e465d@mail.gmail.com> Message-ID: <1c2a2c590805020916x9d5b459p85b4788ef0339299@mail.gmail.com> On Fri, May 2, 2008 at 11:33 AM, Stephanie wrote: > Hi, > I'm at a very beginning level of Python knowledge, but I use several Python > programs via the Macintosh Unix Terminal. I was trying to quickly see which > version of Python I am running and typed in the command "python -v". That > was obviously not the correct command to use. It installed several things > and now I'm unable to run my Python programs. > > Can someone tell me if there there is a way to undo the python -v command? You have started python in verbose mode. It didn't actually install anything, it is showing you all the modules that are loaded when python starts up. At the end, notice that the prompt is >>>. That is the python interpreter prompt. Type control-D to exit the interpreter and get back to the shell prompt. Near the end, notice that it did also print the version - Python always does that when it runs interactively. You can also use the command python --version to print the version number and exit. Kent From kent37 at tds.net Fri May 2 18:18:40 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 2 May 2008 12:18:40 -0400 Subject: [Tutor] How to skip to next line in for loop In-Reply-To: <003a01c8ac6b$207eacf0$6500a8c0@AWA2> References: <003a01c8ac6b$207eacf0$6500a8c0@AWA2> Message-ID: <1c2a2c590805020918v454508ffkfad56c5ebea43627@mail.gmail.com> On Fri, May 2, 2008 at 11:42 AM, Paul McGuire wrote: > f=open('file.txt',r) > print_line = False > for line in f: > if print_line: > print line > print_line = False > if line == "3": Don't forget about the newline...(that makes four!) Kent From malaclypse2 at gmail.com Fri May 2 18:21:01 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Fri, 2 May 2008 12:21:01 -0400 Subject: [Tutor] Regular expressions... In-Reply-To: References: Message-ID: <16651e80805020921q1d6dacd8ydb42ef972c5ecbbf@mail.gmail.com> On Fri, May 2, 2008 at 12:08 PM, Spencer Parker wrote: > I need to use a regular expression to get a couple of items for my python > script. So far the script is running an 'ls' command to get a few items > that I need Why do you need to use regular expressions? This problem doesn't really seem to call for them. You should be able to just use the split method of strings. Here's an example: IDLE 1.2.2 >>> command1 = "2454112 /xen/domains2/machinename/disk.img" >>> command2 = "-rw-r--r-- 1 root root 20980736 May 2 10:05 /xen/domains2/machinename/disk.img" >>> command1.split() ['2454112', '/xen/domains2/machinename/disk.img'] >>> command2.split() ['-rw-r--r--', '1', 'root', 'root', '20980736', 'May', '2', '10:05', '/xen/domains2/machinename/disk.img'] >>> bytes_used = command1.split()[0] >>> bytes_actual = command2.split()[4] >>> print bytes_used 2454112 >>> print bytes_actual 20980736 >>> percent = float(bytes_used) / float(bytes_actual) >>> percent 0.11696977646542046 >>> -- Jerry From pythoninfo at dodgycauldron.com Fri May 2 18:21:31 2008 From: pythoninfo at dodgycauldron.com (Stephanie) Date: Fri, 2 May 2008 11:21:31 -0500 Subject: [Tutor] python -v command In-Reply-To: <1c2a2c590805020916x9d5b459p85b4788ef0339299@mail.gmail.com> References: <315a79d00805020833g605a585aib83a36ed382e465d@mail.gmail.com> <1c2a2c590805020916x9d5b459p85b4788ef0339299@mail.gmail.com> Message-ID: <315a79d00805020921w24e7e3f6jd12ec1e64a3df1b6@mail.gmail.com> Thank you to everyone for your help. I'm sorry to waste your time with such a silly question. I am now back up and running! I really appreciate your responses. On Fri, May 2, 2008 at 11:16 AM, Kent Johnson wrote: > On Fri, May 2, 2008 at 11:33 AM, Stephanie > wrote: > > Hi, > > I'm at a very beginning level of Python knowledge, but I use several > Python > > programs via the Macintosh Unix Terminal. I was trying to quickly see > which > > version of Python I am running and typed in the command "python -v". > That > > was obviously not the correct command to use. It installed several > things > > and now I'm unable to run my Python programs. > > > > Can someone tell me if there there is a way to undo the python -v > command? > > You have started python in verbose mode. It didn't actually install > anything, it is showing you all the modules that are loaded when > python starts up. > > At the end, notice that the prompt is >>>. That is the python > interpreter prompt. Type control-D to exit the interpreter and get > back to the shell prompt. > > Near the end, notice that it did also print the version - Python > always does that when it runs interactively. You can also use the > command > python --version > to print the version number and exit. > > Kent > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Fri May 2 18:23:46 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 2 May 2008 12:23:46 -0400 Subject: [Tutor] Regular expressions... In-Reply-To: References: Message-ID: <1c2a2c590805020923s2a07a457sd651a4e5b2f3dede@mail.gmail.com> On Fri, May 2, 2008 at 12:08 PM, Spencer Parker wrote: > I need to use a regular expression to get a couple of items for my python > script. So far the script is running an 'ls' command to get a few items > that I need > > I run an 'ls -sk /xen/domains2/machinename/disk.img' > > Output > > 2454112 /xen/domains2/machinename/disk.img Look at os.path.getsize(). You don't need to use ls to get this information. > What I need to get is just the size numbers using regular expressions. You could just use str.split() but getsize() is better. > I also need to get the 'machinename' > portion of the path as well to stick into the database. Don't you already know this? Where does the ls command come from? Anyway look at os.path.split() and os.path.dirname(). Kent From srilyk at gmail.com Fri May 2 18:55:59 2008 From: srilyk at gmail.com (W W) Date: Fri, 2 May 2008 11:55:59 -0500 Subject: [Tutor] Method question? Message-ID: <333efb450805020955i5b12c9acl2263184463adfe6a@mail.gmail.com> I'm playing around with pyGTK, and I have a question to see if I'm understanding things correctly. Is a method just a function inside a class? i.e. def myFunction(): print "This is a function" class myClass: def myMethod(): print "This is a method" and to call: myFunction() I tried to call the method via. myClass.myMethod() and x = myClass x.myMethod() but none of those were working... I'll take a look online, but am I correct that the only difference is that method is a function inside a class? Thanks, Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi From kent37 at tds.net Fri May 2 19:17:48 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 2 May 2008 13:17:48 -0400 Subject: [Tutor] Method question? In-Reply-To: <333efb450805020955i5b12c9acl2263184463adfe6a@mail.gmail.com> References: <333efb450805020955i5b12c9acl2263184463adfe6a@mail.gmail.com> Message-ID: <1c2a2c590805021017m5ec5ac4dldba4ed3a546f1fae@mail.gmail.com> On Fri, May 2, 2008 at 12:55 PM, W W wrote: > I'm playing around with pyGTK, and I have a question to see if I'm > understanding things correctly. > > Is a method just a function inside a class? Pretty much. It also has a required 'self' parameter which gets the value of the object on which the method is called. > > i.e. > > def myFunction(): > print "This is a function" > > class myClass: > def myMethod(): should be def myMethod(self): > print "This is a method" > > and to call: > > myFunction() > > I tried to call the method via. myClass.myMethod() and > x = myClass This just makes x an alias for the class object. Should be x = myClass() > x.myMethod() then this will work. Kent From inthefridge at gmail.com Fri May 2 19:38:49 2008 From: inthefridge at gmail.com (Spencer Parker) Date: Fri, 2 May 2008 11:38:49 -0600 Subject: [Tutor] Regular expressions... In-Reply-To: <1c2a2c590805020923s2a07a457sd651a4e5b2f3dede@mail.gmail.com> References: <1c2a2c590805020923s2a07a457sd651a4e5b2f3dede@mail.gmail.com> Message-ID: Well...it gives me the entire path...I am not running this script from the actual directory...I am running it from a secure user directory that only has certain access rights. During the os.path.dirname gives me the entire directory path...I just need to last part of it is all. out of '/xen/domains2/machinename/disk.img all I need is 'machinename' On Fri, May 2, 2008 at 10:23 AM, Kent Johnson wrote: > On Fri, May 2, 2008 at 12:08 PM, Spencer Parker > wrote: > > I need to use a regular expression to get a couple of items for my python > > script. So far the script is running an 'ls' command to get a few items > > that I need > > > > I run an 'ls -sk /xen/domains2/machinename/disk.img' > > > > Output > > > > 2454112 /xen/domains2/machinename/disk.img > > Look at os.path.getsize(). You don't need to use ls to get this > information. > > > What I need to get is just the size numbers using regular expressions. > > You could just use str.split() but getsize() is better. > > > I also need to get the 'machinename' > > portion of the path as well to stick into the database. > > Don't you already know this? Where does the ls command come from? > Anyway look at os.path.split() and os.path.dirname(). > > Kent > -- Spencer Parker _______________________________________________________ "if you can't go to heaven, may you at least die in Ireland." _______________________________________________________ -------------- next part -------------- An HTML attachment was scrubbed... URL: From titleistfour at gmail.com Fri May 2 19:46:06 2008 From: titleistfour at gmail.com (jay) Date: Fri, 2 May 2008 12:46:06 -0500 Subject: [Tutor] Regular expressions... In-Reply-To: References: <1c2a2c590805020923s2a07a457sd651a4e5b2f3dede@mail.gmail.com> Message-ID: <7c25bb490805021046o579fcdcaoe3630540424b0edc@mail.gmail.com> dir = '/xen/domains2/machinename/disk.img' a = dir.split('/')[3] is what I would use... On Fri, May 2, 2008 at 12:38 PM, Spencer Parker wrote: > Well...it gives me the entire path...I am not running this script from the > actual directory...I am running it from a secure user directory that only > has certain access rights. During the os.path.dirname gives me the entire > directory path...I just need to last part of it is all. out of > '/xen/domains2/machinename/disk.img all I need is 'machinename' > > On Fri, May 2, 2008 at 10:23 AM, Kent Johnson wrote: > > > On Fri, May 2, 2008 at 12:08 PM, Spencer Parker > > wrote: > > > I need to use a regular expression to get a couple of items for my > > python > > > script. So far the script is running an 'ls' command to get a few > > items > > > that I need > > > > > > I run an 'ls -sk /xen/domains2/machinename/disk.img' > > > > > > Output > > > > > > 2454112 /xen/domains2/machinename/disk.img > > > > Look at os.path.getsize(). You don't need to use ls to get this > > information. > > > > > What I need to get is just the size numbers using regular expressions. > > > > You could just use str.split() but getsize() is better. > > > > > I also need to get the 'machinename' > > > portion of the path as well to stick into the database. > > > > Don't you already know this? Where does the ls command come from? > > Anyway look at os.path.split() and os.path.dirname(). > > > > Kent > > > > > > -- > Spencer Parker > _______________________________________________________ > > "if you can't go to heaven, may you at least die in Ireland." > > _______________________________________________________ > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Fri May 2 20:16:26 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 2 May 2008 14:16:26 -0400 Subject: [Tutor] Regular expressions... In-Reply-To: References: <1c2a2c590805020923s2a07a457sd651a4e5b2f3dede@mail.gmail.com> Message-ID: <1c2a2c590805021116p54df4392n8ac2d09a9ecc77bf@mail.gmail.com> On Fri, May 2, 2008 at 1:38 PM, Spencer Parker wrote: > Well...it gives me the entire path...I am not running this script from the > actual directory...I am running it from a secure user directory that only > has certain access rights. During the os.path.dirname gives me the entire > directory path...I just need to last part of it is all. out of > '/xen/domains2/machinename/disk.img all I need is 'machinename' In [1]: import os In [2]: path = '/xen/domains2/machinename/disk.img' In [3]: os.path.basename(os.path.dirname(path)) Out[3]: 'machinename' Kent From srilyk at gmail.com Fri May 2 20:20:55 2008 From: srilyk at gmail.com (W W) Date: Fri, 2 May 2008 13:20:55 -0500 Subject: [Tutor] Method question? In-Reply-To: <1c2a2c590805021017m5ec5ac4dldba4ed3a546f1fae@mail.gmail.com> References: <333efb450805020955i5b12c9acl2263184463adfe6a@mail.gmail.com> <1c2a2c590805021017m5ec5ac4dldba4ed3a546f1fae@mail.gmail.com> Message-ID: <333efb450805021120o171f2978vc37fb81a20ba20f8@mail.gmail.com> On Fri, May 2, 2008 at 12:17 PM, Kent Johnson wrote: > This just makes x an alias for the class object. Should be > x = myClass() > > > x.myMethod() > > then this will work. Ah! Thank you! I knew/guessed the alias bit from my experience with C++, but I couldn't figure out exactly what I needed. I've seen the "self" reference before, but I never really understood it. Let me see if I understand correctly: class myClass(): creates a new "data type"(?), called myClass, and x = myClass() creates a variable with the type of "myClass", similar to foo = dict() and the method inside myClass defined as myMethod(self), can be called on the data type "myClass" like this: x.myMethod() is that fairly accurate? -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi From pylinuxian at gmail.com Fri May 2 20:31:13 2008 From: pylinuxian at gmail.com (Arthur) Date: Fri, 2 May 2008 18:31:13 +0000 Subject: [Tutor] Method question? In-Reply-To: <333efb450805021120o171f2978vc37fb81a20ba20f8@mail.gmail.com> References: <333efb450805020955i5b12c9acl2263184463adfe6a@mail.gmail.com> <1c2a2c590805021017m5ec5ac4dldba4ed3a546f1fae@mail.gmail.com> <333efb450805021120o171f2978vc37fb81a20ba20f8@mail.gmail.com> Message-ID: i had tough time understanding classes ... hope this helps : http://www2.lib.uchicago.edu/keith/courses/python/class/5/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Fri May 2 20:42:24 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 2 May 2008 14:42:24 -0400 Subject: [Tutor] Method question? In-Reply-To: <333efb450805021120o171f2978vc37fb81a20ba20f8@mail.gmail.com> References: <333efb450805020955i5b12c9acl2263184463adfe6a@mail.gmail.com> <1c2a2c590805021017m5ec5ac4dldba4ed3a546f1fae@mail.gmail.com> <333efb450805021120o171f2978vc37fb81a20ba20f8@mail.gmail.com> Message-ID: <1c2a2c590805021142t7b01341emec13eb7ae66ba0e5@mail.gmail.com> On Fri, May 2, 2008 at 2:20 PM, W W wrote: > I knew/guessed the alias bit from my experience with C++, but I > couldn't figure out exactly what I needed. I've seen the "self" > reference before, but I never really understood it. 'self' is roughly like 'this' in C++. Unlike C++, self must be explicit - it is listed as a method parameter and it must be used for attribute access. > Let me see if I > understand correctly: > > class myClass(): or, more idiomatic (class names start with upper case letters) and modern (inherit from object to create a new-style class): class MyClass(object): > > creates a new "data type"(?), called myClass, and > > x = myClass() > > creates a variable with the type of "myClass", similar to foo = dict() > > and the method inside myClass defined as myMethod(self), can be called > on the data type "myClass" like this: > > x.myMethod() > > is that fairly accurate? Yes. Kent From bgailer at gmail.com Fri May 2 20:49:02 2008 From: bgailer at gmail.com (bob gailer) Date: Fri, 02 May 2008 14:49:02 -0400 Subject: [Tutor] How to skip to next line in for loop In-Reply-To: <481B22A8.1000906@gmail.com> References: <24bc7f6c0805011404j27dc2778s2a0f48f41d1a7347@mail.gmail.com> <1c2a2c590805020355q7b6c8014q72f20c5d33d98265@mail.gmail.com> <24bc7f6c0805020705j3fc55068q6cc1b5b77273b596@mail.gmail.com> <481B22A8.1000906@gmail.com> Message-ID: <481B621E.8090000@gmail.com> bob gailer wrote: > Or even simplre > > f = open('file.txt',r).readlines() > print [f[x+1] for x, line in enumerate(f) if line.rstrip() == "3"][0] > -- Bob Gailer 919-636-4239 Chapel Hill, NC From srilyk at gmail.com Fri May 2 20:57:15 2008 From: srilyk at gmail.com (W W) Date: Fri, 2 May 2008 13:57:15 -0500 Subject: [Tutor] Method question? In-Reply-To: <1c2a2c590805021142t7b01341emec13eb7ae66ba0e5@mail.gmail.com> References: <333efb450805020955i5b12c9acl2263184463adfe6a@mail.gmail.com> <1c2a2c590805021017m5ec5ac4dldba4ed3a546f1fae@mail.gmail.com> <333efb450805021120o171f2978vc37fb81a20ba20f8@mail.gmail.com> <1c2a2c590805021142t7b01341emec13eb7ae66ba0e5@mail.gmail.com> Message-ID: <333efb450805021157y1cb1c927y8527c32461891d31@mail.gmail.com> I think I'm beginning to understand how classes/methods work now, I'm sure further understanding will come with practice. Thanks for the help and suggestions! -Wayne On Fri, May 2, 2008 at 1:42 PM, Kent Johnson wrote: > On Fri, May 2, 2008 at 2:20 PM, W W wrote: > > > I knew/guessed the alias bit from my experience with C++, but I > > couldn't figure out exactly what I needed. I've seen the "self" > > reference before, but I never really understood it. > > 'self' is roughly like 'this' in C++. Unlike C++, self must be > explicit - it is listed as a method parameter and it must be used for > attribute access. > > > > Let me see if I > > understand correctly: > > > > class myClass(): > > or, more idiomatic (class names start with upper case letters) and > modern (inherit from object to create a new-style class): > class MyClass(object): > > > > > creates a new "data type"(?), called myClass, and > > > > x = myClass() > > > > creates a variable with the type of "myClass", similar to foo = dict() > > > > and the method inside myClass defined as myMethod(self), can be called > > on the data type "myClass" like this: > > > > x.myMethod() > > > > is that fairly accurate? > > Yes. > > Kent > -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi From ross at ross.mayfirst.org Fri May 2 21:08:05 2008 From: ross at ross.mayfirst.org (Ross Glover) Date: Fri, 02 May 2008 15:08:05 -0400 Subject: [Tutor] put? and files In-Reply-To: <1c2a2c590805020423j74aa457bi417f07797980b816@mail.gmail.com> References: <48197690.6050205@ross.mayfirst.org> <40af687b0805011159t58daf481mca0b518c27e2ee3d@mail.gmail.com> <481A8DBD.6060504@ross.mayfirst.org> <1c2a2c590805020423j74aa457bi417f07797980b816@mail.gmail.com> Message-ID: <481B6695.90209@ross.mayfirst.org> > > If you give some examples of what you want to parse we can give more > specific advice. > > Kent > > I'm assuming this falls under the rubric of text parsing. Here's what I want to make: A way to create a set of user defined tags or markers that can be applied to any section of a text document. Then I want a function that will write to a file all of the tagged/marked text (that is text between tag_start and tag_end), preferably with a reference to the file from which it came. Ultimately, I want this to reside in a gui which allows the user to read the text, tag/mark various sections of interest, and then write all of those sections to files corresponding to the specified tags. I expect the files to be between 50k and 150k words. thanks, ross -- If you know what you're doing, you must not be 'doing' a dissertation. From kent37 at tds.net Fri May 2 21:16:48 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 2 May 2008 15:16:48 -0400 Subject: [Tutor] put? and files In-Reply-To: <481B6695.90209@ross.mayfirst.org> References: <48197690.6050205@ross.mayfirst.org> <40af687b0805011159t58daf481mca0b518c27e2ee3d@mail.gmail.com> <481A8DBD.6060504@ross.mayfirst.org> <1c2a2c590805020423j74aa457bi417f07797980b816@mail.gmail.com> <481B6695.90209@ross.mayfirst.org> Message-ID: <1c2a2c590805021216h6e1ceb44k667a04f460ab82f5@mail.gmail.com> On Fri, May 2, 2008 at 3:08 PM, Ross Glover wrote: > I'm assuming this falls under the rubric of text parsing. Here's what I > want to make: > A way to create a set of user defined tags or markers that can be applied > to any section of a text document. Then I want a function that will write > to a file all of the tagged/marked text (that is text between tag_start and > tag_end), preferably with a reference to the file from which it came. You could do that with just string find and slicing but I think it will be simpler with regular expressions. You can make a regex to match everything from 'tag_start' to 'tag_end' and use a group to pull out the stuff in between. Kent From aymchaos at yahoo.com Fri May 2 21:11:44 2008 From: aymchaos at yahoo.com (Mihai Iacob) Date: Fri, 2 May 2008 12:11:44 -0700 (PDT) Subject: [Tutor] Starting a .py file from Idle Message-ID: <662596.1360.qm@web32703.mail.mud.yahoo.com> Hello, Can anyone tell me how to start a program directly from the interpreter (i'm using IDLE). Usually i open a new window , write the lines of code and press F5 to run the program in the interpreter. The problem is that i need to to that directly from the interpreter. (I'm running windows). ____________________________________________________________________________________ Be a better friend, newshound, and know-it-all with Yahoo! Mobile. Try it now. http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ From pylinuxian at gmail.com Fri May 2 21:57:04 2008 From: pylinuxian at gmail.com (Arthur) Date: Fri, 2 May 2008 19:57:04 +0000 Subject: [Tutor] Starting a .py file from Idle In-Reply-To: <468262.72734.qm@web32701.mail.mud.yahoo.com> References: <468262.72734.qm@web32701.mail.mud.yahoo.com> Message-ID: i guess : START > RUN then type : python your_script.py arg_1 arg_2 -------------- next part -------------- An HTML attachment was scrubbed... URL: From pylinuxian at gmail.com Fri May 2 21:38:16 2008 From: pylinuxian at gmail.com (Arthur) Date: Fri, 2 May 2008 19:38:16 +0000 Subject: [Tutor] Starting a .py file from Idle In-Reply-To: References: <662596.1360.qm@web32703.mail.mud.yahoo.com> Message-ID: > On Fri, May 2, 2008 at 7:11 PM, Mihai Iacob wrote: > Hello, > > Can anyone tell me how to start a program directly > from the interpreter (i'm using IDLE). Usually i open > a new window , write the lines of code and press F5 to > run the program in the interpreter. > The problem is that i need to to that directly from > the interpreter. (I'm running windows). FILE > OPEN would open any text file & F5 would run any code in there. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri May 2 22:49:50 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 2 May 2008 21:49:50 +0100 Subject: [Tutor] python -v command References: <315a79d00805020833g605a585aib83a36ed382e465d@mail.gmail.com> Message-ID: "Stephanie" wrote > programs via the Macintosh Unix Terminal. I was trying to quickly > see which > version of Python I am running and typed in the command "python -v". uppercase: python -V Alan G. From alan.gauld at btinternet.com Fri May 2 22:53:56 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 2 May 2008 21:53:56 +0100 Subject: [Tutor] Starting a .py file from Idle References: <662596.1360.qm@web32703.mail.mud.yahoo.com> Message-ID: "Mihai Iacob" wrote > Can anyone tell me how to start a program directly > from the interpreter (i'm using IDLE). Usually i open > a new window , write the lines of code and press F5 to > run the program in the interpreter. You mean the results show up in the interactive shell window of IDLE? > The problem is that i need to to that directly from > the interpreter. (I'm running windows). Do you mean you want to run a program you have previously written inside IDLE? Or that you want to run a program outside of IDLE? Alan G From bgailer at gmail.com Fri May 2 23:42:14 2008 From: bgailer at gmail.com (bob gailer) Date: Fri, 02 May 2008 17:42:14 -0400 Subject: [Tutor] Starting a .py file from Idle In-Reply-To: <662596.1360.qm@web32703.mail.mud.yahoo.com> References: <662596.1360.qm@web32703.mail.mud.yahoo.com> Message-ID: <481B8AB6.40002@gmail.com> Mihai Iacob wrote: > Hello, > > Can anyone tell me how to start a program directly > from the interpreter (i'm using IDLE). Usually i open > a new window , write the lines of code and press F5 to > run the program in the interpreter. > The problem is that i need to to that directly from > the interpreter. Pray tell, why? Try >>> import program -- Bob Gailer 919-636-4239 Chapel Hill, NC From ruivaldo at gmail.com Sat May 3 00:33:01 2008 From: ruivaldo at gmail.com (rui) Date: Fri, 2 May 2008 19:33:01 -0300 Subject: [Tutor] best way to get external data In-Reply-To: References: Message-ID: PyYaml is an option too. [1] [1] - http://pyyaml.org/ It?s very readable and is converted to a Python native structure/object. On Fri, May 2, 2008 at 12:12 PM, Bryan Fodness wrote: > I am trying to figure out the best way to get external data. > > Using the following data in a file > > 1 > 2 > 3 > > I have used, > > fi = open(infile, 'r') > s = fi.readlines() > fi.close() > a = s[0] > b = s[1] > c = s[2] > > but, if I have, > > x = 1 > y = 2 > z = 3 > > I have used, > > for line in open(infile): > i_line = line.split() > if i_line[0] == 'x': > a = i_line[2] > elif i_line[0] == 'y': > b = i_line[2] > elif i_line[0] == 'z': > c = i_line[2] > > I do have control over the creation of the data file. The second way is > better in my mind, because it is independent of the ordering. > > If I have a long list of 'variable' = 'value', could this be better > managed in a dictionary? Or, is there a better way? > > Thanks > > > -- > "The game of science can accurately be described as a never-ending insult > to human intelligence." - Jo?o Magueijo > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Meu nome ? Valdo, Ruivaldo Neto. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ayadiimens at gmail.com Sun May 4 14:37:35 2008 From: ayadiimens at gmail.com (imen ayadi) Date: Sun, 4 May 2008 14:37:35 +0200 Subject: [Tutor] block in my application QT4/python2.5 Message-ID: <86b6dc890805040537r22e3682ejfb2656f749f1f54c@mail.gmail.com> Hello, I hope you can help me to find the solution. I use ERIC 4 as environment for python. I developed like a chat program, with a server and multi clients. First, it works when I executed it in DOS. But when I integrated the program in QT4 interface .py it always blocks. This is my interface server_code.py: # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'interf_s.ui' # # Created: Tue Apr 29 12:55:58 2008 # by: PyQt4 UI code generator 4.3.3 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui import socket, sys, threading import time import locale class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(QtCore.QSize(QtCore.QRect(0,0,610,600).size()).expandedTo(MainWindow.minimumSizeHint())) self.centralwidget = QtGui.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.gc = QtGui.QGroupBox(self.centralwidget) self.gc.setGeometry(QtCore.QRect(9,9,581,111)) self.gc.setObjectName("gc") self.adripes = QtGui.QLineEdit(self.gc) self.adripes.setGeometry(QtCore.QRect(110,30,301,20)) self.adripes.setObjectName("adripes") self.label = QtGui.QLabel(self.gc) self.label.setGeometry(QtCore.QRect(20,30,71,16)) self.label.setObjectName("label") self.label_2 = QtGui.QLabel(self.gc) self.label_2.setGeometry(QtCore.QRect(20,60,91,16)) self.label_2.setObjectName("label_2") self.nipes = QtGui.QLineEdit(self.gc) self.nipes.setGeometry(QtCore.QRect(110,60,301,20)) self.nipes.setObjectName("nipes") self.connectes = QtGui.QPushButton(self.gc) self.connectes.setGeometry(QtCore.QRect(470,70,91,23)) self.connectes.setObjectName("connectes") self.envoies = QtGui.QTextEdit(self.centralwidget) self.envoies.setGeometry(QtCore.QRect(10,150,256,271)) self.envoies.setObjectName("envoies") self.chates = QtGui.QLineEdit(self.centralwidget) self.chates.setGeometry(QtCore.QRect(10,450,256,31)) self.chates.setObjectName("chates") self.benves = QtGui.QPushButton(self.centralwidget) self.benves.setGeometry(QtCore.QRect(190,520,75,23)) self.benves.setObjectName("benves") self.gt = QtGui.QGroupBox(self.centralwidget) self.gt.setGeometry(QtCore.QRect(280,140,311,401)) self.gt.setObjectName("gt") self.tablees = QtGui.QTableWidget(self.gt) self.tablees.setGeometry(QtCore.QRect(20,40,281,181)) self.tablees.setObjectName("tablees") self.ajoues = QtGui.QPushButton(self.gt) self.ajoues.setGeometry(QtCore.QRect(210,280,75,23)) self.ajoues.setObjectName("ajoues") self.suppes = QtGui.QPushButton(self.gt) self.suppes.setGeometry(QtCore.QRect(210,330,75,23)) self.suppes.setObjectName("suppes") MainWindow.setCentralWidget(self.centralwidget) self.statusbar = QtGui.QStatusBar(MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.menubar = QtGui.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0,0,610,21)) self.menubar.setObjectName("menubar") MainWindow.setMenuBar(self.menubar) self.retranslateUi(MainWindow) QtCore.QObject.connect(self.ajoues,QtCore.SIGNAL("clicked()"),self.ajout) QtCore.QObject.connect(self.suppes,QtCore.SIGNAL("clicked()"),self.supprim) QtCore.QObject.connect(self.connectes,QtCore.SIGNAL("clicked()"),self.conec) QtCore.QObject.connect(self.benves,QtCore.SIGNAL("clicked()"),self.chat) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow", "MainWindow", None, QtGui.QApplication.UnicodeUTF8)) self.gc.setTitle(QtGui.QApplication.translate("MainWindow", "Connexion :", None, QtGui.QApplication.UnicodeUTF8)) self.label.setText(QtGui.QApplication.translate("MainWindow", "Adresse IP :", None, QtGui.QApplication.UnicodeUTF8)) self.label_2.setText(QtGui.QApplication.translate("MainWindow", "Numero de port :", None, QtGui.QApplication.UnicodeUTF8)) self.connectes.setText(QtGui.QApplication.translate("MainWindow", "Connexion", None, QtGui.QApplication.UnicodeUTF8)) self.envoies.setHtml(QtGui.QApplication.translate("MainWindow", "\n" "

", None, QtGui.QApplication.UnicodeUTF8)) self.benves.setText(QtGui.QApplication.translate("MainWindow", "Envoyer", None, QtGui.QApplication.UnicodeUTF8)) self.gt.setTitle(QtGui.QApplication.translate("MainWindow", "Gestion commandes :", None, QtGui.QApplication.UnicodeUTF8)) self.tablees.clear() self.tablees.setColumnCount(2) self.tablees.setRowCount(3) headerItem = QtGui.QTableWidgetItem() headerItem.setText(QtGui.QApplication.translate("MainWindow", "Commande 1", None, QtGui.QApplication.UnicodeUTF8)) self.tablees.setVerticalHeaderItem(0,headerItem) headerItem1 = QtGui.QTableWidgetItem() headerItem1.setText(QtGui.QApplication.translate("MainWindow", "Commande 2", None, QtGui.QApplication.UnicodeUTF8)) self.tablees.setVerticalHeaderItem(1,headerItem1) headerItem2 = QtGui.QTableWidgetItem() headerItem2.setText(QtGui.QApplication.translate("MainWindow", "Commande 3", None, QtGui.QApplication.UnicodeUTF8)) self.tablees.setVerticalHeaderItem(2,headerItem2) headerItem3 = QtGui.QTableWidgetItem() headerItem3.setText(QtGui.QApplication.translate("MainWindow", "Requ?te", None, QtGui.QApplication.UnicodeUTF8)) self.tablees.setHorizontalHeaderItem(0,headerItem3) headerItem4 = QtGui.QTableWidgetItem() headerItem4.setText(QtGui.QApplication.translate("MainWindow", "Reponse", None, QtGui.QApplication.UnicodeUTF8)) self.tablees.setHorizontalHeaderItem(1,headerItem4) item = QtGui.QTableWidgetItem() item.setText(QtGui.QApplication.translate("MainWindow", "$ GPSCON", None, QtGui.QApplication.UnicodeUTF8)) self.tablees.setItem(0,0,item) item1 = QtGui.QTableWidgetItem() item1.setText(QtGui.QApplication.translate("MainWindow", "Bonjour", None, QtGui.QApplication.UnicodeUTF8)) self.tablees.setItem(0,1,item1) item2 = QtGui.QTableWidgetItem() item2.setText(QtGui.QApplication.translate("MainWindow", "$ GPSNMUN", None, QtGui.QApplication.UnicodeUTF8)) self.tablees.setItem(1,0,item2) item3 = QtGui.QTableWidgetItem() item3.setText(QtGui.QApplication.translate("MainWindow", "OK", None, QtGui.QApplication.UnicodeUTF8)) self.tablees.setItem(1,1,item3) item4 = QtGui.QTableWidgetItem() item4.setText(QtGui.QApplication.translate("MainWindow", "$ GPSACP", None, QtGui.QApplication.UnicodeUTF8)) self.tablees.setItem(2,0,item4) item5 = QtGui.QTableWidgetItem() item5.setText(QtGui.QApplication.translate("MainWindow", "Hello", None, QtGui.QApplication.UnicodeUTF8)) self.tablees.setItem(2,1,item5) self.ajoues.setText(QtGui.QApplication.translate("MainWindow", "Ajouter", None, QtGui.QApplication.UnicodeUTF8)) self.suppes.setText(QtGui.QApplication.translate("MainWindow", "Supprimer", None, QtGui.QApplication.UnicodeUTF8)) def ajout(self): self.tablees.insertRow(3) def supprim(self): self.tablees.removeRow(3) def chat(self): rep = self.chates.text() self.envoies.append("Donnees Envoyees>"+rep) self.chates.clear() return rep #self.envoies.append("Deconnexion de ", self.client_address) def conec(self): HOST = self.adripes.text() PORT = int(self.nipes.text()) mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: mySocket.bind((HOST, PORT)) except socket.error: self.envoies.setText("La liaison du socket a l'adresse choisie a echoue.") sys.exit() while 1: self.envoies.append("Serveur pret en attente de requetes .") mySocket.listen(5) connexion, adresse = mySocket.accept() c= time.strftime('%A %c') client= "Connexion au port" + str(adresse[1]) + " a " + c self.envoies.append(client) donneesRecues = connexion.recv(8192) t=time.strftime("%H:%M:%S") self.envoies.append(" Donnees Recues " +t+ " > "+ donneesRecues) rep = self.chat() connexion.send(rep) if __name__ == "__main__": import sys app = QtGui.QApplication(sys.argv) MainWindow = QtGui.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_()) This interface should realise the communication between many clients according to the client adresse In a python forum someone proposed to me that code, But when I executed it an error message appear and indicate that "pythonw.exe encountered a problem and must close. Excuse us for the incurred ...." I have windowsXP.The code is: # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'interf_s.ui' # # Created: Tue Apr 29 12:55:58 2008 # by: PyQt4 UI code generator 4.3.3 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui from PyQt4.QtCore import * from PyQt4.QtGui import * import socket, sys, threading import time import locale class Thread(QThread): #lock = QReadWriteLock() def __init__(self, host, port): super(Thread, self).__init__() #self.socketId = socketId self.host = host self.port = port def run(self): HOST = self.host PORT = int(self.port) mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: mySocket.bind((HOST, PORT)) except socket.error: #self.envoies.setText("La liaison du socket a l'adresse choisie a echoue.") print "La liaison du socket a l'adresse choisie a echoue." sys.exit() while 1: #self.envoies.append("Serveur pret en attente de requetes .") print "Serveur pret en attente de requetes ." mySocket.listen(5) connexion, adresse = mySocket.accept() c= time.strftime('%A %c') client= "Connexion au port" + str(adresse[1]) + " a " + c #self.envoies.append(client) print client donneesRecues = connexion.recv(8192) t=time.strftime("%H:%M:%S") #self.envoies.append(" Donnees Recues " +t+ " > "+ donneesRecues) rep = " Donnees Recues " +t+ " > "+ donneesRecues print rep #rep = self.chat() connexion.send(rep) #"Donnees Envoyees>"+rep class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(QtCore.QSize(QtCore.QRect(0,0,610,600).size()).expandedTo(MainWindow.minimumSizeHint())) self.centralwidget = QtGui.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.gc = QtGui.QGroupBox(self.centralwidget) self.gc.setGeometry(QtCore.QRect(9,9,581,111)) self.gc.setObjectName("gc") self.adripes = QtGui.QLineEdit(self.gc) self.adripes.setGeometry(QtCore.QRect(110,30,301,20)) self.adripes.setObjectName("adripes") self.label = QtGui.QLabel(self.gc) self.label.setGeometry(QtCore.QRect(20,30,71,16)) self.label.setObjectName("label") self.label_2 = QtGui.QLabel(self.gc) self.label_2.setGeometry(QtCore.QRect(20,60,91,16)) self.label_2.setObjectName("label_2") self.nipes = QtGui.QLineEdit(self.gc) self.nipes.setGeometry(QtCore.QRect(110,60,301,20)) self.nipes.setObjectName("nipes") self.connectes = QtGui.QPushButton(self.gc) self.connectes.setGeometry(QtCore.QRect(470,70,91,23)) self.connectes.setObjectName("connectes") self.envoies = QtGui.QTextEdit(self.centralwidget) self.envoies.setGeometry(QtCore.QRect(10,150,256,271)) self.envoies.setObjectName("envoies") self.chates = QtGui.QLineEdit(self.centralwidget) self.chates.setGeometry(QtCore.QRect(10,450,256,31)) self.chates.setObjectName("chates") self.benves = QtGui.QPushButton(self.centralwidget) self.benves.setGeometry(QtCore.QRect(190,520,75,23)) self.benves.setObjectName("benves") self.gt = QtGui.QGroupBox(self.centralwidget) self.gt.setGeometry(QtCore.QRect(280,140,311,401)) self.gt.setObjectName("gt") self.tablees = QtGui.QTableWidget(self.gt) self.tablees.setGeometry(QtCore.QRect(20,40,281,181)) self.tablees.setObjectName("tablees") self.ajoues = QtGui.QPushButton(self.gt) self.ajoues.setGeometry(QtCore.QRect(210,280,75,23)) self.ajoues.setObjectName("ajoues") self.suppes = QtGui.QPushButton(self.gt) self.suppes.setGeometry(QtCore.QRect(210,330,75,23)) self.suppes.setObjectName("suppes") MainWindow.setCentralWidget(self.centralwidget) self.statusbar = QtGui.QStatusBar(MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.menubar = QtGui.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0,0,610,21)) self.menubar.setObjectName("menubar") MainWindow.setMenuBar(self.menubar) self.retranslateUi(MainWindow) QtCore.QObject.connect(self.ajoues,QtCore.SIGNAL("clicked()"),self.ajout) QtCore.QObject.connect(self.suppes,QtCore.SIGNAL("clicked()"),self.supprim) QtCore.QObject.connect(self.connectes,QtCore.SIGNAL("clicked()"),self.conec) QtCore.QObject.connect(self.benves,QtCore.SIGNAL("clicked()"),self.chat) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow", "MainWindow", None, QtGui.QApplication.UnicodeUTF8)) self.gc.setTitle(QtGui.QApplication.translate("MainWindow", "Connexion :", None, QtGui.QApplication.UnicodeUTF8)) self.label.setText(QtGui.QApplication.translate("MainWindow", "Adresse IP :", None, QtGui.QApplication.UnicodeUTF8)) self.label_2.setText(QtGui.QApplication.translate("MainWindow", "Numero de port :", None, QtGui.QApplication.UnicodeUTF8)) self.connectes.setText(QtGui.QApplication.translate("MainWindow", "Connexion", None, QtGui.QApplication.UnicodeUTF8)) self.envoies.setHtml(QtGui.QApplication.translate("MainWindow", "\n" "

", None, QtGui.QApplication.UnicodeUTF8)) self.benves.setText(QtGui.QApplication.translate("MainWindow", "Envoyer", None, QtGui.QApplication.UnicodeUTF8)) self.gt.setTitle(QtGui.QApplication.translate("MainWindow", "Gestion commandes :", None, QtGui.QApplication.UnicodeUTF8)) self.tablees.clear() self.tablees.setColumnCount(2) self.tablees.setRowCount(3) headerItem = QtGui.QTableWidgetItem() headerItem.setText(QtGui.QApplication.translate("MainWindow", "Commande 1", None, QtGui.QApplication.UnicodeUTF8)) self.tablees.setVerticalHeaderItem(0,headerItem) headerItem1 = QtGui.QTableWidgetItem() headerItem1.setText(QtGui.QApplication.translate("MainWindow", "Commande 2", None, QtGui.QApplication.UnicodeUTF8)) self.tablees.setVerticalHeaderItem(1,headerItem1) headerItem2 = QtGui.QTableWidgetItem() headerItem2.setText(QtGui.QApplication.translate("MainWindow", "Commande 3", None, QtGui.QApplication.UnicodeUTF8)) self.tablees.setVerticalHeaderItem(2,headerItem2) headerItem3 = QtGui.QTableWidgetItem() headerItem3.setText(QtGui.QApplication.translate("MainWindow", "Requ?te", None, QtGui.QApplication.UnicodeUTF8)) self.tablees.setHorizontalHeaderItem(0,headerItem3) headerItem4 = QtGui.QTableWidgetItem() headerItem4.setText(QtGui.QApplication.translate("MainWindow", "Reponse", None, QtGui.QApplication.UnicodeUTF8)) self.tablees.setHorizontalHeaderItem(1,headerItem4) item = QtGui.QTableWidgetItem() item.setText(QtGui.QApplication.translate("MainWindow", "$ GPSCON", None, QtGui.QApplication.UnicodeUTF8)) self.tablees.setItem(0,0,item) item1 = QtGui.QTableWidgetItem() item1.setText(QtGui.QApplication.translate("MainWindow", "Bonjour", None, QtGui.QApplication.UnicodeUTF8)) self.tablees.setItem(0,1,item1) item2 = QtGui.QTableWidgetItem() item2.setText(QtGui.QApplication.translate("MainWindow", "$ GPSNMUN", None, QtGui.QApplication.UnicodeUTF8)) self.tablees.setItem(1,0,item2) item3 = QtGui.QTableWidgetItem() item3.setText(QtGui.QApplication.translate("MainWindow", "OK", None, QtGui.QApplication.UnicodeUTF8)) self.tablees.setItem(1,1,item3) item4 = QtGui.QTableWidgetItem() item4.setText(QtGui.QApplication.translate("MainWindow", "$ GPSACP", None, QtGui.QApplication.UnicodeUTF8)) self.tablees.setItem(2,0,item4) item5 = QtGui.QTableWidgetItem() item5.setText(QtGui.QApplication.translate("MainWindow", "Hello", None, QtGui.QApplication.UnicodeUTF8)) self.tablees.setItem(2,1,item5) self.ajoues.setText(QtGui.QApplication.translate("MainWindow", "Ajouter", None, QtGui.QApplication.UnicodeUTF8)) self.suppes.setText(QtGui.QApplication.translate("MainWindow", "Supprimer", None, QtGui.QApplication.UnicodeUTF8)) def ajout(self): self.tablees.insertRow(3) def supprim(self): self.tablees.removeRow(3) def chat(self): rep = self.chates.text() self.envoies.append("Donnees Envoyees>"+rep) self.chates.clear() return rep #self.envoies.append("Deconnexion de ", self.client_address) def conec(self): HOST = self.adripes.text() PORT = int(self.nipes.text()) thread = Thread(HOST, PORT) QtCore.QObject.connect(thread, SIGNAL("finished()"), thread, SLOT("deleteLater()")) thread.start() if __name__ == "__main__": import sys app = QtGui.QApplication(sys.argv) MainWindow = QtGui.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_()) Thank you for reading my e_mail. I am waiting for your answer even if ... I accept any other solution or links to help me. I wonder if the client code should also be modified. -------------- next part -------------- An HTML attachment was scrubbed... URL: From quantrum75 at yahoo.com Mon May 5 01:07:42 2008 From: quantrum75 at yahoo.com (quantrum75) Date: Sun, 4 May 2008 16:07:42 -0700 (PDT) Subject: [Tutor] list and tuple question In-Reply-To: Message-ID: <104430.95181.qm@web31406.mail.mud.yahoo.com> An HTML attachment was scrubbed... URL: From quantrum75 at yahoo.com Mon May 5 01:29:08 2008 From: quantrum75 at yahoo.com (quantrum75) Date: Sun, 4 May 2008 16:29:08 -0700 (PDT) Subject: [Tutor] List and tuple question -resend Message-ID: <460150.52635.qm@web31403.mail.mud.yahoo.com> An HTML attachment was scrubbed... URL: From quantrum75 at yahoo.com Mon May 5 01:33:08 2008 From: quantrum75 at yahoo.com (quantrum75) Date: Sun, 4 May 2008 16:33:08 -0700 (PDT) Subject: [Tutor] List and tuple question -resend #2 Message-ID: <401782.10338.qm@web31405.mail.mud.yahoo.com> Sincerely sorry for spamming everybody. Dint know about yahoo's quirks regarding html attachments.. Hopefully this works. Hi everybody I have a simple newbie kind of questions. I have tried hard to solve it, but couldn't figure it out. The problem is, I want to make a tuple of tuples or a list of lists in a iterative fashion in the following format. For example, a=[[1,],[2,],[3,],[4,],[5,]] or a=((1,),(2,),(3,),(4,),(5,)) I need the comma since it is going into an excel sheet. I tried a=[] for i in range(5): a.append('['+str(i)+','+']') but it gives me, ['[0,]', '[1,]', '[2,]', '[3,]', '[4,]', '[5,]'] Which is no good since excel reads the whole thing inside the ' ' instead of the actual number. I know the solution is probably simple and I appreciate any help. Thanks Rama ____________________________________________________________________________________ Be a better friend, newshound, and know-it-all with Yahoo! Mobile. Try it now. http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ From alan.gauld at btinternet.com Mon May 5 01:42:28 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 5 May 2008 00:42:28 +0100 Subject: [Tutor] list and tuple question References: <104430.95181.qm@web31406.mail.mud.yahoo.com> Message-ID: "quantrum75" wrote in > Hi everybody Hi, I think the key to your question is here: > a=((1,),(2,),(3,),(4,),(5,)) > > I need the comma since it is going into an excel sheet. I think you are confused between tuples and comma separated strings - which is what you normally use to load data into Excel I think you probably want to look at the csv module which makes it easier to create properly foermatted comma separated values > a=[] > for i in range(5): > a.append('['+str(i)+','+']') This appends a string that looks like a list to a list. To create a list of lists you only need: a.append([i]) But that doesmn't show any commas - and neither should it since the comma is not part of the list/tuple for a single item, its only a syntactic trick to force Python to produce a tuple. >>> a = (1,) >>> a (1,) >>> print a[0] 1 So the comma is only part of the representation to show its actually a tuple not just a number in parentheses. > ['[0,]', '[1,]', '[2,]', '[3,]', '[4,]', '[5,]'] Which is what you told it to store. > Which is no good since excel reads the whole thing inside the ' > ' > instead of the actual number. How are you feeding the data to excel? Or to rephtrase that how is Excel 'reading' the data? That is fairly critical to solving your core problem. > I know th e solution is probably simple and I appreciate any > help. I think the solution lies in a different place to where you are looking. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From bhawsar.vaibhav at gmail.com Mon May 5 13:12:51 2008 From: bhawsar.vaibhav at gmail.com (Vaibhav.bhawsar) Date: Mon, 5 May 2008 07:12:51 -0400 Subject: [Tutor] threading: getting latest elements from list/dict Message-ID: <17d58cc40805050412l2cc0340cs2b84916d0af0760c@mail.gmail.com> Hello I have a thread updating a dictionary with new elements. How can I check for new elements as they are inserted into the dictionary by the thread? In general is it safe to read a dictionary or a list while it is being updated by a running thread? Does the dictionary or list have to be locked while reading? many questions! :) vaibhav -------------- next part -------------- An HTML attachment was scrubbed... URL: From bhawsar.vaibhav at gmail.com Mon May 5 13:23:54 2008 From: bhawsar.vaibhav at gmail.com (Vaibhav.bhawsar) Date: Mon, 5 May 2008 07:23:54 -0400 Subject: [Tutor] threading: getting latest elements from list/dict In-Reply-To: <17d58cc40805050412l2cc0340cs2b84916d0af0760c@mail.gmail.com> References: <17d58cc40805050412l2cc0340cs2b84916d0af0760c@mail.gmail.com> Message-ID: <17d58cc40805050423l167b0f94u29777121431c0896@mail.gmail.com> Hello I have a thread updating a dictionary with new elements. How can I check for new elements as they are inserted into the dictionary by the thread? In general is it safe to read a dictionary or a list while it is being updated by a running thread? Does the dictionary or list have to be locked while reading? many questions! :) vaibhav -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Mon May 5 13:33:46 2008 From: bgailer at gmail.com (bob gailer) Date: Mon, 05 May 2008 07:33:46 -0400 Subject: [Tutor] threading: getting latest elements from list/dict In-Reply-To: <17d58cc40805050423l167b0f94u29777121431c0896@mail.gmail.com> References: <17d58cc40805050412l2cc0340cs2b84916d0af0760c@mail.gmail.com> <17d58cc40805050423l167b0f94u29777121431c0896@mail.gmail.com> Message-ID: <481EF09A.6040504@gmail.com> Vaibhav.bhawsar wrote: > Hello > I have a thread updating a dictionary with new elements. How can I > check for new elements as they are inserted into the dictionary by the > thread? In general is it safe to read a dictionary or a list while it > is being updated by a running thread? Does the dictionary or list have > to be locked while reading? http://www.python.org/doc/faq/library/#what-kinds-of-global-value-mutation-are-thread-safe -- Bob Gailer 919-636-4239 Chapel Hill, NC From nomb85 at comcast.net Mon May 5 21:44:40 2008 From: nomb85 at comcast.net (Nathan McBride) Date: Mon, 05 May 2008 15:44:40 -0400 Subject: [Tutor] free loop device Message-ID: <481F63A8.4030707@comcast.net> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hey Guys, I have a program that uses the loop devices. However I originally was finding the free one with: 'losetup -f'. Which returns the next free loop device. :D However, I found that some of the other distros have a version of losetup that does not include that switch. So I am trying to work up another way to get the next device. What I'm figuring is doing 'losetup -a', parsing the returned data, and incrementing it by one... However I don't know how to accomplish this. An example 'losetup -a' would be like this: ?[root at localhost Desktop]# losetup -a /dev/loop0: [fd00]:11305639 (enc) /dev/loop1: [fd00]:11306533 (/home/nmcbride/Desktop/xxxxxxxxxxxxxxx.iso) Can anyone give me a hand? Thanks, Nate -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.7 (GNU/Linux) Comment: Using GnuPG with Fedora - http://enigmail.mozdev.org iD8DBQFIH2Oo/n+duykW6K8RAnCTAJ480KREx5udm22wFx3KbNQ08p6AeQCfcfoO IS+ZG3J8M1/oEjcHN/pLhU4= =5zQk -----END PGP SIGNATURE----- From inthefridge at gmail.com Tue May 6 00:05:04 2008 From: inthefridge at gmail.com (Spencer Parker) Date: Mon, 5 May 2008 16:05:04 -0600 Subject: [Tutor] Looking for something similar to du... Message-ID: I am wondering if there is a way to do something that du does in Linux. I have several disk images and I need a way to get the size used...not the size of the image. If you type in du and the disk image path it gives you this number. is there anyway to do this in python? -- Spencer Parker _______________________________________________________ "if you can't go to heaven, may you at least die in Ireland." _______________________________________________________ -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue May 6 02:21:21 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 6 May 2008 01:21:21 +0100 Subject: [Tutor] Looking for something similar to du... References: Message-ID: "Spencer Parker" wrote >I am wondering if there is a way to do something that du does in >Linux. I > have several disk images and I need a way to get the size used...not > the > size of the image. If you type in du and the disk image path it > gives you > this number. is there anyway to do this in python? Probably but I'm not totally clear what you are looking for. Can you explain what you mean by the diffrence between the size used versus the size of the image? Surely the size of the image is the space it uses? Or are you expanding compressed files? Can you give an example of the two measures so that we(I?) can better understand the distinction Meantime try looking at the os.walk function and the os.fstat function. That may be all you need. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From bgailer at gmail.com Tue May 6 02:32:56 2008 From: bgailer at gmail.com (bob gailer) Date: Mon, 05 May 2008 20:32:56 -0400 Subject: [Tutor] free loop device In-Reply-To: <481F63A8.4030707@comcast.net> References: <481F63A8.4030707@comcast.net> Message-ID: <481FA738.7090007@gmail.com> Nathan McBride wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Hey Guys, > > I have a program that uses the loop devices. However I originally was > finding the free one with: > 'losetup -f'. Which returns the next free loop device. :D However, I > found that some of the other distros > have a version of losetup that does not include that switch. So I am > trying to work up another way to get the > next device. > > What I'm figuring is doing 'losetup -a', parsing the returned data, and > incrementing it by one... > However I don't know how to accomplish this. An example 'losetup -a' > would be like this: > > ?[root at localhost Desktop]# losetup -a > /dev/loop0: [fd00]:11305639 (enc) > /dev/loop1: [fd00]:11306533 (/home/nmcbride/Desktop/xxxxxxxxxxxxxxx.iso) > > Can anyone give me a hand? > I for one have no idea how this relates to Python. If others do then they are likely to help you. -- Bob Gailer 919-636-4239 Chapel Hill, NC From marc.tompkins at gmail.com Tue May 6 02:57:38 2008 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Mon, 5 May 2008 17:57:38 -0700 Subject: [Tutor] Looking for something similar to du... In-Reply-To: References: Message-ID: <40af687b0805051757ka8fd24ascf2a362f07554dd9@mail.gmail.com> On Mon, May 5, 2008 at 5:21 PM, Alan Gauld wrote: > Probably but I'm not totally clear what you are looking for. > Can you explain what you mean by the diffrence between the size > used versus the size of the image? Surely the size of the image > is the space it uses? Or are you expanding compressed files? > Disk space is allocated in large units (in DOS/Windows they're called "clusters", *nixes call them "blocks"). A one-byte file still uses an entire cluster, whose size depends on the size of the disk and the number of chunks it can be divided into. So just knowing the size of the file is not quite enough information if you need to know how much room is left on the disk... If you use Windows, you can see this very easily - right-clicking on a JPEG file and selecting Properties, I get: Size: 35.1 KB (35,997 bytes) Size on disk: 48.0 KB (49,152 bytes) >From the os.stat() docs: > On some Unix systems (such as Linux), the following attributes may also be > available: st_blocks (number of blocks allocated for file), st_blksize(filesystem blocksize), > st_rdev (type of device if an inode device). st_flags (user defined flags > for file). > So apparently os.stat() can get this info from *nix, but not Windows... maybe behind the scenes, it runs du? -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From nomb85 at comcast.net Tue May 6 04:14:27 2008 From: nomb85 at comcast.net (Nathan McBride) Date: Mon, 05 May 2008 22:14:27 -0400 Subject: [Tutor] free loop device In-Reply-To: <481FA738.7090007@gmail.com> References: <481F63A8.4030707@comcast.net> <481FA738.7090007@gmail.com> Message-ID: <481FBF03.4090004@comcast.net> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Yup, I got some help in IRC. What I ended up doing was using regex to pull out each "/dev/loopX". Then took the X and fed it to max which in turn gave me the highest numbered loop device in use. After which I then just added 1 to X and added it to the end of "/dev/loop_". The only other thing I had to do was put a check in incase there were no used loop devices in which case then it defaults to "/dev/loop0". Works like a charm. :D Nate bob gailer wrote: > Nathan McBride wrote: >> -----BEGIN PGP SIGNED MESSAGE----- >> Hash: SHA1 >> >> Hey Guys, >> >> I have a program that uses the loop devices. However I originally was >> finding the free one with: >> 'losetup -f'. Which returns the next free loop device. :D However, I >> found that some of the other distros >> have a version of losetup that does not include that switch. So I am >> trying to work up another way to get the >> next device. >> >> What I'm figuring is doing 'losetup -a', parsing the returned data, and >> incrementing it by one... >> However I don't know how to accomplish this. An example 'losetup -a' >> would be like this: >> >> ?[root at localhost Desktop]# losetup -a >> /dev/loop0: [fd00]:11305639 (enc) >> /dev/loop1: [fd00]:11306533 (/home/nmcbride/Desktop/xxxxxxxxxxxxxxx.iso) >> >> Can anyone give me a hand? >> > > I for one have no idea how this relates to Python. If others do then they are likely to help you. > -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.7 (GNU/Linux) Comment: Using GnuPG with Fedora - http://enigmail.mozdev.org iD8DBQFIH78C/n+duykW6K8RAuE3AJoDu69W1D7dldLPxXpCfRGuoc++FQCgj2G3 4fG0aSw7fe/noi4hqesG9oA= =vas+ -----END PGP SIGNATURE----- From inthefridge at gmail.com Tue May 6 05:59:30 2008 From: inthefridge at gmail.com (Spencer Parker) Date: Mon, 5 May 2008 21:59:30 -0600 Subject: [Tutor] Looking for something similar to du... In-Reply-To: <40af687b0805051757ka8fd24ascf2a362f07554dd9@mail.gmail.com> References: <40af687b0805051757ka8fd24ascf2a362f07554dd9@mail.gmail.com> Message-ID: Mark is right...in that I don't want the actual size of the file itself...that I can get from another way in Python which i am already doing. I was mainly wondering if there was a way to do it and I was just missing something. I looked though stat() and that is basically what I wanted. I wasn't sure if that was actually it until Mark spelled it out for me. I do love using du...since I am learning..I just wanted make sure I wasn't missing anything...thank you guys as always... On Mon, May 5, 2008 at 6:57 PM, Marc Tompkins wrote: > On Mon, May 5, 2008 at 5:21 PM, Alan Gauld > wrote: > >> Probably but I'm not totally clear what you are looking for. >> Can you explain what you mean by the diffrence between the size >> used versus the size of the image? Surely the size of the image >> is the space it uses? Or are you expanding compressed files? >> > > Disk space is allocated in large units (in DOS/Windows they're called > "clusters", *nixes call them "blocks"). A one-byte file still uses an > entire cluster, whose size depends on the size of the disk and the number of > chunks it can be divided into. So just knowing the size of the file is not > quite enough information if you need to know how much room is left on the > disk... > > If you use Windows, you can see this very easily - right-clicking on a JPEG > file and selecting Properties, I get: > Size: 35.1 KB (35,997 bytes) > Size on disk: 48.0 KB (49,152 bytes) > > From the os.stat() docs: > >> On some Unix systems (such as Linux), the following attributes may also >> be available: st_blocks (number of blocks allocated for file), st_blksize(filesystem blocksize), >> st_rdev (type of device if an inode device). st_flags (user defined flags >> for file). >> > So apparently os.stat() can get this info from *nix, but not Windows... > maybe behind the scenes, it runs du? > -- > www.fsrtechnologies.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Spencer Parker _______________________________________________________ "if you can't go to heaven, may you at least die in Ireland." _______________________________________________________ -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue May 6 08:55:10 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 6 May 2008 07:55:10 +0100 Subject: [Tutor] Looking for something similar to du... References: <40af687b0805051757ka8fd24ascf2a362f07554dd9@mail.gmail.com> Message-ID: "Marc Tompkins" wrote >> Can you explain what you mean by the diffrence between the size >> used versus the size of the image? > Disk space is allocated in large units (in DOS/Windows they're > called > "clusters", *nixes call them "blocks"). Ah yes, indeed it is. And in a previous life I even used to care about such things! Nowadays I've gotten used to disk space being so cheap and plentiful I confess I'd forgotten all about the diffrences and their significance. Thanks for the reminder Marc. As to finding disk usage on Windows I found this snippet on an MSDN forum: ------------------ If you want the size of the file on disk when compressed or sparse then you have to use Platform/Invoke to call GetCompressedFileSize as I don't believe .NET exposes this method directly. Furthermore this doesn't give you the actual size on disk if it isn't compressed. For that I believe you'd have to determine how many clusters it takes up and multiply that by the cluster size. I don't believe there is any direct way in Windows to do that but WMI might provide a way. Nevertheless this is not what you'd want to use as it'll also contain unused bytes of data. --------------------- Which is rather scary... Alan G From marc.tompkins at gmail.com Tue May 6 09:17:23 2008 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Tue, 6 May 2008 00:17:23 -0700 Subject: [Tutor] Looking for something similar to du... In-Reply-To: References: <40af687b0805051757ka8fd24ascf2a362f07554dd9@mail.gmail.com> Message-ID: <40af687b0805060017n6bf2ada9p228d1643d6cba70a@mail.gmail.com> On Mon, May 5, 2008 at 11:55 PM, Alan Gauld wrote: > > As to finding disk usage on Windows I found this > snippet on an MSDN forum: > > ------------------ > If you want the size of the file on disk when compressed or sparse > then you have to use Platform/Invoke to call GetCompressedFileSize > as I don't believe .NET exposes this method directly. Furthermore > this doesn't give you the actual size on disk if it isn't compressed. > For that I believe you'd have to determine how many clusters it > takes up and multiply that by the cluster size. I don't believe > there is any direct way in Windows to do that but WMI might > provide a way. Nevertheless this is not what you'd want to > use as it'll also contain unused bytes of data. > --------------------- > > Which is rather scary... > Not really, just written by someone who 1) had something else in mind, or 2) is unclear on the concept. Because _of course_ this number will include unused bytes (not "of data", though, just "of disk space"). It's called slack space, I believe - all those extra bytes between the end of the file and the end of the last cluster allocated to the file. Even with FAT32, NTFS, and many highly-advanced file systems in the *nix world, it adds up to a surprisingly large proportion of most peoples' disk space. (More if you have lots of tiny files, less if you have lots of big files.) That being said, I've recently been buying 500GB hard drives for $100. (And yes, I'm sure there are even hotter deals out there. Don't rub it in if you've found one, though - it'll only make me miserable.) At 20 cents a gig, it's hard to work up any real anxiety over slack space. I'm curious - what does the OP do with this info? Does it have some deeper significance I don't know about, or is it just a cool statistic to track? -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From agoldgod at gmail.com Tue May 6 10:26:33 2008 From: agoldgod at gmail.com (goldgod a) Date: Tue, 6 May 2008 13:56:33 +0530 Subject: [Tutor] Redarding Random no display in WXPython Message-ID: <105c9ccc0805060126m3fdde924rd5e2031d3f17e22d@mail.gmail.com> Dear friends, I wish to display a random number in my GUI text box which is been developed in Wxpython.. Here i couln't refresh the GUI continuously.. Please help me out in this regard.. -- Thanks & Regards, goldgod -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue May 6 10:52:26 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 6 May 2008 09:52:26 +0100 Subject: [Tutor] Looking for something similar to du... References: <40af687b0805051757ka8fd24ascf2a362f07554dd9@mail.gmail.com> <40af687b0805060017n6bf2ada9p228d1643d6cba70a@mail.gmail.com> Message-ID: "Marc Tompkins" wrote >> As to finding disk usage on Windows I found this >> snippet on an MSDN forum: >> >> ------------------ > >....I don't believe >> there is any direct way in Windows to do that but WMI might >> provide a way. Nevertheless this is not what you'd want to >> >> Which is rather scary... >> > > Not really, just written by someone who 1) had something else in > mind, I just meant the fact that Microsoft didn't appear to provide an API function to find it directly was scary - especially since its something they report in Explorer as you noted earlier. > That being said, I've recently been buying 500GB hard > drives for $100. The cost of disk space is frighteningly cheap. I remember buying a Terabyte of storage for a mainframe about 20 years ago and it cost over $2 million. Now I can buy a Terabyte of NAS for $200! That's why I've stopped worrying about lost space due to block sizes! :-) Alan G. From alan.gauld at btinternet.com Tue May 6 10:53:37 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 6 May 2008 09:53:37 +0100 Subject: [Tutor] Redarding Random no display in WXPython References: <105c9ccc0805060126m3fdde924rd5e2031d3f17e22d@mail.gmail.com> Message-ID: "goldgod a" wrote > I wish to display a random number in my GUI text > box > which is been developed in Wxpython.. Here i couln't refresh the GUI > continuously.. Please help me out in this regard.. Look at the Timer object in wxPython. Set a timer event and in the event handler refresh the display then restart the timer. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Tue May 6 11:53:43 2008 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Tue, 6 May 2008 09:53:43 +0000 (GMT) Subject: [Tutor] Fw: Redarding Random no display in WXPython Message-ID: <398220.61634.qm@web86712.mail.ukl.yahoo.com> Sending onto list. ----- Forwarded Message ---- From: goldgod a To: Alan Gauld Sent: Tuesday, 6 May, 2008 10:21:01 AM Subject: Re: [Tutor] Redarding Random no display in WXPython Here i have given the coding buddy.. just help me out.. import wx,random class MyFrame(wx.Frame): def __init__(self, *args, **kwds): # begin wxGlade: MyFrame.__init__ kwds["style"] = wx.ICONIZE|wx.CAPTION|wx.MINIMIZE|wx.CLOSE_BOX|wx.MINIMIZE_BOX|wx.MAXIMIZE_BOX|wx.SYSTEM_MENU|wx.RESIZE_BORDER|wx.FRAME_TOOL_WINDOW|wx.CLIP_CHILDREN wx.Frame.__init__(self, *args, **kwds) self.Refresh() # Menu Bar self.frame_1_menubar = wx.MenuBar() self.SetMenuBar(self.frame_1_menubar) wxglade_tmp_menu = wx.Menu() wxglade_tmp_menu.Append(wx.NewId(), "Save", "", wx.ITEM_NORMAL) wxglade_tmp_menu.Append(wx.NewId(), "IP Detector", "", wx.ITEM_NORMAL) wxglade_tmp_menu.Append(wx.NewId(), "Properties", "", wx.ITEM_NORMAL) wxglade_tmp_menu.Append(wx.NewId(), "History", "", wx.ITEM_NORMAL) wxglade_tmp_menu.Append(wx.NewId(), "Exit", "", wx.ITEM_NORMAL) self.frame_1_menubar.Append(wxglade_tmp_menu, "RTL-Democos") wxglade_tmp_menu = wx.Menu() wxglade_tmp_menu.Append(wx.NewId(), "RTL-Democos Tool", "", wx.ITEM_NORMAL) wxglade_tmp_menu.Append(wx.NewId(), "AU-KBC", "", wx.ITEM_NORMAL) wxglade_tmp_menu.Append(wx.NewId(), "Contributors", "", wx.ITEM_NORMAL) self.frame_1_menubar.Append(wxglade_tmp_menu, "Help") # Menu Bar end self.frame_1_statusbar = self.CreateStatusBar(1, wx.ST_SIZEGRIP) self.label_1 = wx.StaticText(self, -1, "Current Temperature") self.text_ctrl_1 = wx.TextCtrl(self, -1, "", style=wx.TE_MULTILINE|wx.TE_CENTRE|wx.TE_LINEWRAP|wx.TE_WORDWRAP) self.text_ctrl_1.SetEditable ( False ) self.label_3 = wx.StaticText(self, -1, "Controller") self.radio_box_1 = wx.RadioBox(self, -1, "Mode Selection", choices=["Automatic", "Manual"], majorDimension=15, style=wx.RA_SPECIFY_COLS) self.radio_box_2 = wx.RadioBox(self, -1, "Manual", choices=["AC", "Heater", "Fan"], majorDimension=19, style=wx.RA_SPECIFY_COLS) self.label_2 = wx.StaticText(self, -1, "Recent Sensor Values") self.text_ctrl_2 = wx.TextCtrl(self, -1, "", style=wx.TE_PROCESS_ENTER|wx.TE_MULTILINE|wx.HSCROLL|wx.TE_LINEWRAP|wx.TE_WORDWRAP) self.text_ctrl_2.SetEditable ( False ) self.label_4 = wx.StaticText(self, -1, "Controller Status") self.text_ctrl_3 = wx.TextCtrl(self, -1, "", style=wx.TE_MULTILINE|wx.TE_LINEWRAP|wx.TE_WORDWRAP) self.text_ctrl_3.SetEditable ( False ) #self.Refresh() self.text_ctrl_1.AppendText(str(random.randrange(0,100))) self.text_ctrl_1.Refresh() self.text_ctrl_1.Update() ##self.PushStatusText() #self.desired_fifo = open('/dev/rtf4', 'w') self.__set_properties() self.__do_layout() def __set_properties(self): # begin wxGlade: MyFrame.__set_properties self.SetTitle("RTL_Democos") self.SetSize((340, 380)) self.SetBackgroundColour(wx.Colour(201, 255, 229)) self.frame_1_statusbar.SetStatusWidths([-1]) # statusbar fields frame_1_statusbar_fields = ["RTL-Democos - A Real Time Signal Monitoring Tool "] for i in range(len(frame_1_statusbar_fields)): self.frame_1_statusbar.SetStatusText(frame_1_statusbar_fields[i], i) self.label_1.SetMinSize((190, 37)) self.text_ctrl_1.SetMinSize((90, 37)) self.text_ctrl_1.SetBackgroundColour(wx.Colour(233, 255, 253)) self.label_3.SetMinSize((196, 27)) self.radio_box_1.SetMinSize((1360, 64)) self.radio_box_1.SetBackgroundColour(wx.Colour(201, 255, 229)) self.radio_box_1.SetSelection(0) self.radio_box_2.SetMinSize((1102, 54)) self.radio_box_2.SetBackgroundColour(wx.Colour(201, 255, 229)) self.radio_box_2.Enable(True) self.radio_box_2.SetSelection(0) self.label_2.SetMinSize((155, 27)) self.text_ctrl_2.SetMinSize((150, 100)) self.text_ctrl_2.SetBackgroundColour(wx.Colour(233, 255, 253)) self.label_4.SetMinSize((155, 27)) self.text_ctrl_3.SetMinSize((150, 100)) self.text_ctrl_3.SetBackgroundColour(wx.Colour(233, 255, 253)) # end wxGlade self.Refresh() def __do_layout(self): # begin wxGlade: MyFrame.__do_layout sizer_1 = wx.BoxSizer(wx.VERTICAL) sizer_2 = wx.BoxSizer(wx.VERTICAL) sizer_4 = wx.BoxSizer(wx.HORIZONTAL) sizer_8 = wx.BoxSizer(wx.VERTICAL) sizer_7 = wx.BoxSizer(wx.VERTICAL) sizer_3 = wx.BoxSizer(wx.HORIZONTAL) sizer_6 = wx.BoxSizer(wx.VERTICAL) sizer_5 = wx.BoxSizer(wx.VERTICAL) sizer_5.Add(self.label_1, 0, 0, 0) sizer_5.Add(self.text_ctrl_1, 0, 0, 0) sizer_3.Add(sizer_5, 1, wx.EXPAND, 0) sizer_6.Add(self.label_3, 0, 0, 0) sizer_6.Add(self.radio_box_1, 0, 0, 1) sizer_6.Add(self.radio_box_2, 0, 0, 0) sizer_3.Add(sizer_6, 1, wx.EXPAND, 0) sizer_2.Add(sizer_3, 1, wx.EXPAND, 0) sizer_7.Add(self.label_2, 0, 0, 0) sizer_7.Add(self.text_ctrl_2, 0, 0, 0) sizer_4.Add(sizer_7, 1, wx.EXPAND, 0) sizer_8.Add(self.label_4, 0, 0, 0) sizer_8.Add(self.text_ctrl_3, 0, 0, 0) sizer_4.Add(sizer_8, 1, wx.EXPAND, 0) sizer_2.Add(sizer_4, 1, wx.EXPAND, 0) sizer_1.Add(sizer_2, 1, wx.EXPAND, 0) self.SetSizer(sizer_1) self.Layout() self.Centre() ##def temp(): ## import random ## return random.randrange(0,100) ## print #while 1: #actual_fifo = open('/dev/mem', 'r') #alt_str = actual_fifo.read(4) #altitude = 0 #for foobar in range(3,-1,-1): # altitude = 256 * altitude + ord(alt_str[foobar]) #label_str = str(altitude) #self.text_ctrl_1.Clear() #label_str = str(altitude) #return label_str ##if __name__ == "__main__": ## app = wx.PySimpleApp(0) ## wx.InitAllImageHandlers() ## frame_1 =MyFrame(None, -1, "") ## app.SetTopWindow(frame_1) ## ##temp() ## frame_1.Show() ## s= True ## if s: ## s=False ## app.MainLoop() ## ##break ## else: ## s=True ## app.MainLoop() ## class MyApp(wx.App): def OnInit(self): frame_1 =MyFrame(None, -1, "") self.SetTopWindow(frame_1) frame_1.Show() return True while 1: app=MyApp(redirect=True) app.MainLoop() -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue May 6 11:58:37 2008 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Tue, 6 May 2008 09:58:37 +0000 (GMT) Subject: [Tutor] Redarding Random no display in WXPython Message-ID: <119481.11370.qm@web86701.mail.ukl.yahoo.com> Always use Reply All to send to the list as well. That way you get more likeliehood of a response. > Thanks Buddy.. and Is there any possibilities to display ma random number > in WxTextCtrl with out using Timer Object.. The GUI has to get refresh automatically.. The normal way to do an auto-update in a GUI is using a timer set to a short interval - say 200ms. However, looking at the code you sent I don't see you binding any events to any widgets. Do you have much experience of using wxPython or any other GUI toolkit? Do you understand event driven programming? If not I think you should drop Glade and write a few simple hand crafted wxPython applications first (maybe a currency convertor or somesuch) so that you are clear how GUIs and events work. Glade and its like are great for quickly drawing a GUI but they tend to hide how the underlying system works - but you do still need to understand that. If you do understand these topics then can you explain where your random number generation/display is supposed to fit into your code framework? It seems to me that it is sitting in a temp function that never gets called? HTH, Alan G -------------- next part -------------- An HTML attachment was scrubbed... URL: From rdm at rcblue.com Tue May 6 16:11:36 2008 From: rdm at rcblue.com (Dick Moores) Date: Tue, 06 May 2008 07:11:36 -0700 Subject: [Tutor] Cosmetic question about printing Message-ID: <20080506141157.B5DDF1E400A@bag.python.org> An HTML attachment was scrubbed... URL: From kent37 at tds.net Tue May 6 18:07:34 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 6 May 2008 12:07:34 -0400 Subject: [Tutor] Cosmetic question about printing In-Reply-To: <20080506141157.B5DDF1E400A@bag.python.org> References: <20080506141157.B5DDF1E400A@bag.python.org> Message-ID: <1c2a2c590805060907n5bbb5ab5tb0b3190790c51f83@mail.gmail.com> On Tue, May 6, 2008 at 10:11 AM, Dick Moores wrote: > > This script of mine, < http://py77.python.pastebin.com/f2fdcb99c>, has a function that prints the result--the difference in days, and weeks and days, between two dates. > > The function is > > def printResult(date1, date2, days1, weeks, days2): > print "\nThe difference between %s and %s is %d days" % (date1.strftime("%m/%d/%Y"), > date2.strftime("%m/%d/%Y"), days1) > print 37 * " ", > print "Or %d weeks and %d days" % (weeks, days2) > print ((len(str(weeks)) + len(str(days2))) + 57) * "=" > > An example output is: > > The difference between 05/06/2008 and 11/04/2008 is 182 days > Or 26 weeks and 0 days > ============================================================ > > Nicely right-justified, but that's not always the case: > > The difference between 07/04/1776 and 09/11/2001 is 82248 days > Or 11749 weeks and 5 days > =============================================================== > > Isn't there an easier way, something built into Python, that would do the job? > You can right-justify in a format operation. You will have to do it in two steps since the string you want to right-justify is itself the result of a format operation: line2 = "Or %d weeks and %d days" % (weeks, days2) print '%50s' % line2 Instead of 50 you probably want to use the length of the previous line. You can insert this into the format using * for the length: print %*s' % (len(line1), line2) Kent From rdm at rcblue.com Tue May 6 18:40:34 2008 From: rdm at rcblue.com (Dick Moores) Date: Tue, 06 May 2008 09:40:34 -0700 Subject: [Tutor] Cosmetic question about printing In-Reply-To: <1c2a2c590805060907n5bbb5ab5tb0b3190790c51f83@mail.gmail.co m> References: <20080506141157.B5DDF1E400A@bag.python.org> <1c2a2c590805060907n5bbb5ab5tb0b3190790c51f83@mail.gmail.com> Message-ID: <20080506164047.9EDE51E400A@bag.python.org> An HTML attachment was scrubbed... URL: From srilyk at gmail.com Tue May 6 18:54:43 2008 From: srilyk at gmail.com (W W) Date: Tue, 6 May 2008 11:54:43 -0500 Subject: [Tutor] Cosmetic question about printing In-Reply-To: <20080506164047.9EDE51E400A@bag.python.org> References: <20080506141157.B5DDF1E400A@bag.python.org> <1c2a2c590805060907n5bbb5ab5tb0b3190790c51f83@mail.gmail.com> <20080506164047.9EDE51E400A@bag.python.org> Message-ID: <333efb450805060954p462289d8g3a300d63565ed125@mail.gmail.com> On Tue, May 6, 2008 at 11:40 AM, Dick Moores wrote: > > > > > At 09:07 AM 5/6/2008, Kent Johnson wrote: > > You can right-justify in a format operation. You will have to do it in > two steps since the string you want to right-justify is itself the > result of a format operation: > line2 = "Or %d weeks and %d days" % (weeks, days2) > print '%50s' % line2 > > Instead of 50 you probably want to use the length of the previous > line. You can insert this into the format using * for the length: > print %*s' % (len(line1), line2) > print "This is a very very long line ending in %s" % "even more length" > print "A short %s" % "line" I think it would consist of line1 = "This is a very very long line ending in %s" % "even more length" line2 = "A short %s" % "line" print line1 print '%*s' % (len(line1), line2) In a function: >>> def foo(string1, string2): ... print string1 ... print '%*s' % (len(line1), line2) ... >>> foo(line1, line2) This is a very very long line ending in even more length A short line (as close as I can get it with non-monospace) -Wayne From robertk at bcgsc.ca Tue May 6 18:46:09 2008 From: robertk at bcgsc.ca (Robert Kirkpatrick) Date: Tue, 06 May 2008 09:46:09 -0700 Subject: [Tutor] put? Message-ID: Hey Alan! Is there a dict program for the MacOS flavour of *nix? That's a slick little bit of code but it doesn't work on my Mac: robertk01$ dict -bash: dict: command not found but it works fine when I ssh into a Linux box... > > OTOH, if you are happy with those ideas: > >>> word = raw_input("enter your word >>") >>> put, get=os.popen4("dict -d wn " + (word)) >>> for lines in get.readlines(): >>> print lines From rdm at rcblue.com Tue May 6 20:35:26 2008 From: rdm at rcblue.com (Dick Moores) Date: Tue, 06 May 2008 11:35:26 -0700 Subject: [Tutor] Cosmetic question about printing In-Reply-To: <333efb450805060954p462289d8g3a300d63565ed125@mail.gmail.co m> References: <20080506141157.B5DDF1E400A@bag.python.org> <1c2a2c590805060907n5bbb5ab5tb0b3190790c51f83@mail.gmail.com> <20080506164047.9EDE51E400A@bag.python.org> <333efb450805060954p462289d8g3a300d63565ed125@mail.gmail.com> Message-ID: <20080506183623.A25F71E4009@bag.python.org> An HTML attachment was scrubbed... URL: From steve at alchemy.com Tue May 6 01:55:30 2008 From: steve at alchemy.com (Steve Willoughby) Date: Mon, 5 May 2008 16:55:30 -0700 (PDT) Subject: [Tutor] Cosmetic question about printing In-Reply-To: <20080506183623.A25F71E4009@bag.python.org> References: <20080506141157.B5DDF1E400A@bag.python.org> <1c2a2c590805060907n5bbb5ab5tb0b3190790c51f83@mail.gmail.com> <20080506164047.9EDE51E400A@bag.python.org> <333efb450805060954p462289d8g3a300d63565ed125@mail.gmail.com> <20080506183623.A25F71E4009@bag.python.org> Message-ID: <52300.134.134.136.14.1210031730.squirrel@webmail.alchemy.com> On Tue, May 6, 2008 11:35, Dick Moores wrote: > Could someone just come right out and do it for me? I'm lost here. > That '*' is just too magical..  Where did you guys learn about > '%*s'? Does the '%s' still mean a string? Python's % operator (for string formatting) is derived from the C standard library function printf(), which also accepts the %*s notation. It's capable of a lot of powerful features you may not be aware of. See printf(3) for full details (you can google for printf if you don't have manpages on your system). In a nutshell, between the % and the s you can put the desired field width, like "%10s" which means to pad out the data in the string to be at least 10 characters, right-justifying the column. "%-10s" means to left justify it. If the string being printed is longer than that, it's just printed as-is, it's not truncated. But you can specify that if you like, too: "%10.10s" In place of either of those numbers, you can use "*" which just means "pick up the desired width from the next value in the tuple", which allows you to compute the width on the fly, which is what's being done here. Try this: def print_result(date1, date2, days1, weeks, days2): line1 = 'The difference between %s and %s is %d day%s' % ( date1.strftime('%m/%d/%Y'), date2.strftime('%m/%d/%Y'), days1, ('' if days1 == 1 else 's')) line2 = 'Or %d week%s and %d day%s' % ( weeks, ('' if weeks == 1 else 's'), days2, ('' if days2 == 1 else 's')) print line1 print '%*s' % (len(line1), line2) From kent37 at tds.net Tue May 6 21:09:19 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 6 May 2008 15:09:19 -0400 Subject: [Tutor] Cosmetic question about printing In-Reply-To: <20080506183623.A25F71E4009@bag.python.org> References: <20080506141157.B5DDF1E400A@bag.python.org> <1c2a2c590805060907n5bbb5ab5tb0b3190790c51f83@mail.gmail.com> <20080506164047.9EDE51E400A@bag.python.org> <333efb450805060954p462289d8g3a300d63565ed125@mail.gmail.com> <20080506183623.A25F71E4009@bag.python.org> Message-ID: <1c2a2c590805061209p66673481jcadab56513b8843a@mail.gmail.com> On Tue, May 6, 2008 at 2:35 PM, Dick Moores wrote: > I'm lost here. That '*' > is just too magical.. Where did you guys learn about '%*s'? http://docs.python.org/lib/typesseq-strings.html Item 4 - Minimum field width > Does the '%s' > still mean a string? Yes. Kent From marc.tompkins at gmail.com Tue May 6 23:37:59 2008 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Tue, 6 May 2008 14:37:59 -0700 Subject: [Tutor] put? In-Reply-To: References: Message-ID: <40af687b0805061437i64f4effbi1bdd29d52e60512a@mail.gmail.com> On Tue, May 6, 2008 at 9:46 AM, Robert Kirkpatrick wrote: > Hey Alan! Is there a dict program for the MacOS flavour of *nix? That's > a > slick little bit of code but it doesn't work on my Mac: > > robertk01$ dict > -bash: dict: command not found > > but it works fine when I ssh into a Linux box... > > Check this out: http://dictosx.sourceforge.net/ -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From rdm at rcblue.com Tue May 6 23:41:40 2008 From: rdm at rcblue.com (Dick Moores) Date: Tue, 06 May 2008 14:41:40 -0700 Subject: [Tutor] Cosmetic question about printing In-Reply-To: <1c2a2c590805061209p66673481jcadab56513b8843a@mail.gmail.co m> References: <20080506141157.B5DDF1E400A@bag.python.org> <1c2a2c590805060907n5bbb5ab5tb0b3190790c51f83@mail.gmail.com> <20080506164047.9EDE51E400A@bag.python.org> <333efb450805060954p462289d8g3a300d63565ed125@mail.gmail.com> <20080506183623.A25F71E4009@bag.python.org> <1c2a2c590805061209p66673481jcadab56513b8843a@mail.gmail.com> Message-ID: <20080506214513.3DEF21E4027@bag.python.org> An HTML attachment was scrubbed... URL: From rdm at rcblue.com Wed May 7 00:04:57 2008 From: rdm at rcblue.com (Dick Moores) Date: Tue, 06 May 2008 15:04:57 -0700 Subject: [Tutor] Cosmetic question about printing In-Reply-To: <52300.134.134.136.14.1210031730.squirrel@webmail.alchemy.c om> References: <20080506141157.B5DDF1E400A@bag.python.org> <1c2a2c590805060907n5bbb5ab5tb0b3190790c51f83@mail.gmail.com> <20080506164047.9EDE51E400A@bag.python.org> <333efb450805060954p462289d8g3a300d63565ed125@mail.gmail.com> <20080506183623.A25F71E4009@bag.python.org> <52300.134.134.136.14.1210031730.squirrel@webmail.alchemy.com> Message-ID: <20080506220524.D1FFF1E400A@bag.python.org> At 04:55 PM 5/5/2008, Steve Willoughby wrote: >On Tue, May 6, 2008 11:35, Dick Moores wrote: > > > Could someone just come right out and do it for me? I'm lost here. > > That '*' is just too magical..  Where did you guys learn about > > '%*s'? Does the '%s' still mean a string? > >Python's % operator (for string formatting) is derived from the C standard >library function printf(), which also accepts the %*s notation. It's >capable of a lot of powerful features you may not be aware of. See >printf(3) for full details (you can google for printf if you don't have >manpages on your system). > >In a nutshell, between the % and the s you can put the desired field >width, like "%10s" which means to pad out the data in the string to be at >least 10 characters, right-justifying the column. "%-10s" means to left >justify it. If the string being printed is longer than that, it's just >printed as-is, it's not truncated. But you can specify that if you like, >too: "%10.10s" > >In place of either of those numbers, you can use "*" which just means >"pick up the desired width from the next value in the tuple", which allows >you to compute the width on the fly, which is what's being done here. > >Try this: > >def print_result(date1, date2, days1, weeks, days2): > line1 = 'The difference between %s and %s is %d day%s' % ( > date1.strftime('%m/%d/%Y'), > date2.strftime('%m/%d/%Y'), > days1, ('' if days1 == 1 else 's')) > line2 = 'Or %d week%s and %d day%s' % ( > weeks, ('' if weeks == 1 else 's'), > days2, ('' if days2 == 1 else 's')) > > print line1 > print '%*s' % (len(line1), line2) I just found your reply in my Tutor mailbox, at the HEAD of the thread I started. By my time (U.S. PDT), you answered my 07:11 AM 5/6/2008 post at 04:55 PM 5/5/2008! Received: from 134.134.136.14 (SquirrelMail authenticated user steve) by webmail.alchemy.com with HTTP; Mon, 5 May 2008 16:55:30 -0700 (PDT) But I'm glad I noticed it. That's a very clear explanation of '%' and '*'. Thanks! You worked in a nice algorithm for pluralizing regular nouns. Thanks for that, too. Dick Moores From mwalsh at groktech.org Wed May 7 02:30:14 2008 From: mwalsh at groktech.org (Martin Walsh) Date: Tue, 06 May 2008 19:30:14 -0500 Subject: [Tutor] free loop device In-Reply-To: <481FBF03.4090004@comcast.net> References: <481F63A8.4030707@comcast.net> <481FA738.7090007@gmail.com> <481FBF03.4090004@comcast.net> Message-ID: <4820F816.4060200@groktech.org> Nathan McBride wrote: > Yup, I got some help in IRC. What I ended up doing was using regex to > pull out each "/dev/loopX". Then > took the X and fed it to max which in turn gave me the highest numbered > loop device in use. After which I > then just added 1 to X and added it to the end of "/dev/loop_". The > only other thing I had to do was put a > check in incase there were no used loop devices in which case then it > defaults to "/dev/loop0". One might also consider reimplementing 'losetup -f' in python, but after my own attempt I realize it might not be that practical, and is potentially dangerous I suppose -- if, like me, you don't fully understand the underlying system calls. I've attached my attempt for the sake of discussion only, and not as a solution -- perhaps someone with interest will correct any errors and make it usable. I would definitely appreciate it. Drifting off topic now... I copied most of the find_unused_loop_device implementation in util-linux/lomount.c[1]. The main points of interest, and potential doom due to my ignorance, are related to the fcntl.ioctl call: 1) the LOOP_GET_STATUS ioctl op const, isn't exposed in any of the typical python modules that I can find, and as such I'm worried that it's value is somehow platform dependent. 2) for a similar reason, I am passing a string of the largest allowed length as the 3rd arg to the fcntl.ioctl call on line 33, since the size of the returned data seems to be governed by a struct defined in loop.h, which needs dev_t from a kernel header. Whew. This seems to work fine on my ubuntu system, if sloppy. But, since I don't know, I tend to assume it could cause problems with stability or security. Anyway, thanks for the interesting question Nathan. Now I have some reading to do. :) Marty [1] http://www.google.com/codesearch?hl=en&q=show:3q3vE6vLdaY:0lRVP2J7BtU:j-QqODsRp3s&sa=N&ct=rd&cs_p=ftp://ftp.kernel.org/pub/linux/utils/util-linux/testing/util-linux-2.13-pre7.tar.gz&cs_f=util-linux-2.13-pre7/mount/lomount.c&start=1 -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: loop.txt URL: From kent37 at tds.net Wed May 7 02:41:37 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 6 May 2008 20:41:37 -0400 Subject: [Tutor] Cosmetic question about printing In-Reply-To: <20080506214513.3DEF21E4027@bag.python.org> References: <20080506141157.B5DDF1E400A@bag.python.org> <1c2a2c590805060907n5bbb5ab5tb0b3190790c51f83@mail.gmail.com> <20080506164047.9EDE51E400A@bag.python.org> <333efb450805060954p462289d8g3a300d63565ed125@mail.gmail.com> <20080506183623.A25F71E4009@bag.python.org> <1c2a2c590805061209p66673481jcadab56513b8843a@mail.gmail.com> <20080506214513.3DEF21E4027@bag.python.org> Message-ID: <1c2a2c590805061741p3f6c5a2am9a4c260bae417379@mail.gmail.com> On Tue, May 6, 2008 at 5:41 PM, Dick Moores wrote: > > The function is now: > > > def printResult(date1, date2, days1, weeks, days2): > print "\nThe difference between %s and %s is %d days" % (date1.strftime("%m/%d/%Y"), > date2.strftime("%m/%d/%Y"), days1) > line1 = "\nThe difference between %s and %s is %d days" % ((date1.strftime("%m/%d/%Y"), date2.strftime("%m/%d/%Y"), days1)) There is no need to compute this string twice, just use line1 = ... print line1 Kent From rdm at rcblue.com Wed May 7 02:54:01 2008 From: rdm at rcblue.com (Dick Moores) Date: Tue, 06 May 2008 17:54:01 -0700 Subject: [Tutor] Cosmetic question about printing In-Reply-To: <1c2a2c590805061741p3f6c5a2am9a4c260bae417379@mail.gmail.co m> References: <20080506141157.B5DDF1E400A@bag.python.org> <1c2a2c590805060907n5bbb5ab5tb0b3190790c51f83@mail.gmail.com> <20080506164047.9EDE51E400A@bag.python.org> <333efb450805060954p462289d8g3a300d63565ed125@mail.gmail.com> <20080506183623.A25F71E4009@bag.python.org> <1c2a2c590805061209p66673481jcadab56513b8843a@mail.gmail.com> <20080506214513.3DEF21E4027@bag.python.org> <1c2a2c590805061741p3f6c5a2am9a4c260bae417379@mail.gmail.com> Message-ID: <20080507005419.B45CC1E4002@bag.python.org> At 05:41 PM 5/6/2008, Kent Johnson wrote: >On Tue, May 6, 2008 at 5:41 PM, Dick Moores wrote: > > > > > The function is now: > > > > > > def printResult(date1, date2, days1, weeks, days2): > > print "\nThe difference between %s and %s is %d days" % > (date1.strftime("%m/%d/%Y"), > > date2.strftime("%m/%d/%Y"), days1) > > line1 = "\nThe difference between %s and %s is %d days" % > ((date1.strftime("%m/%d/%Y"), date2.strftime("%m/%d/%Y"), days1)) > >There is no need to compute this string twice, just use > line1 = ... > print line1 Oh, of course. Thanks for pointing that out. Dick From rdm at rcblue.com Wed May 7 02:54:01 2008 From: rdm at rcblue.com (Dick Moores) Date: Tue, 06 May 2008 17:54:01 -0700 Subject: [Tutor] Cosmetic question about printing In-Reply-To: <1c2a2c590805061741p3f6c5a2am9a4c260bae417379@mail.gmail.co m> References: <20080506141157.B5DDF1E400A@bag.python.org> <1c2a2c590805060907n5bbb5ab5tb0b3190790c51f83@mail.gmail.com> <20080506164047.9EDE51E400A@bag.python.org> <333efb450805060954p462289d8g3a300d63565ed125@mail.gmail.com> <20080506183623.A25F71E4009@bag.python.org> <1c2a2c590805061209p66673481jcadab56513b8843a@mail.gmail.com> <20080506214513.3DEF21E4027@bag.python.org> <1c2a2c590805061741p3f6c5a2am9a4c260bae417379@mail.gmail.com> Message-ID: <20080507005421.AD6D21E4016@bag.python.org> At 05:41 PM 5/6/2008, Kent Johnson wrote: >On Tue, May 6, 2008 at 5:41 PM, Dick Moores wrote: > > > > > The function is now: > > > > > > def printResult(date1, date2, days1, weeks, days2): > > print "\nThe difference between %s and %s is %d days" % > (date1.strftime("%m/%d/%Y"), > > date2.strftime("%m/%d/%Y"), days1) > > line1 = "\nThe difference between %s and %s is %d days" % > ((date1.strftime("%m/%d/%Y"), date2.strftime("%m/%d/%Y"), days1)) > >There is no need to compute this string twice, just use > line1 = ... > print line1 Oh, of course. Thanks for pointing that out. Dick From steve at alchemy.com Wed May 7 04:36:08 2008 From: steve at alchemy.com (Steve Willoughby) Date: Tue, 6 May 2008 19:36:08 -0700 Subject: [Tutor] Cosmetic question about printing In-Reply-To: <20080506220524.D1FFF1E400A@bag.python.org> References: <20080506141157.B5DDF1E400A@bag.python.org> <1c2a2c590805060907n5bbb5ab5tb0b3190790c51f83@mail.gmail.com> <20080506164047.9EDE51E400A@bag.python.org> <333efb450805060954p462289d8g3a300d63565ed125@mail.gmail.com> <20080506183623.A25F71E4009@bag.python.org> <52300.134.134.136.14.1210031730.squirrel@webmail.alchemy.com> <20080506220524.D1FFF1E400A@bag.python.org> Message-ID: <20080507023608.GA31019@dragon.alchemy.com> On Tue, May 06, 2008 at 03:04:57PM -0700, Dick Moores wrote: > I just found your reply in my Tutor mailbox, at the HEAD of the > thread I started. By my time (U.S. PDT), you answered my 07:11 AM > 5/6/2008 post at 04:55 PM 5/5/2008! Yeah, sorry about that. The clock on my system was off. Fixed now :) And glad to help. -- Steve Willoughby | Using billion-dollar satellites steve at alchemy.com | to hunt for Tupperware. From inthefridge at gmail.com Wed May 7 21:34:54 2008 From: inthefridge at gmail.com (Spencer Parker) Date: Wed, 7 May 2008 13:34:54 -0600 Subject: [Tutor] Excluding a directory in a script... Message-ID: I have a script that is just basically looking for a disk image in a directory...it lists all the directories in the main disk image directory then appends disk.img to the end to build the full file path. I have one directory that holds old images in it for deletion at a later date. This directory will never contain disk.img in there...it causes the script to error out since it didn't find that in there. How can I exclude this directory from being listed? -- Spencer Parker _______________________________________________________ "if you can't go to heaven, may you at least die in Ireland." _______________________________________________________ -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Wed May 7 21:57:09 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 7 May 2008 15:57:09 -0400 Subject: [Tutor] Excluding a directory in a script... In-Reply-To: References: Message-ID: <1c2a2c590805071257s6413132sde5ff854a6d9e51@mail.gmail.com> On Wed, May 7, 2008 at 3:34 PM, Spencer Parker wrote: > I have a script that is just basically looking for a disk image in a > directory. Please show us the script. Kent From kdsudac at yahoo.com Wed May 7 21:50:53 2008 From: kdsudac at yahoo.com (Keith Suda-Cederquist) Date: Wed, 7 May 2008 12:50:53 -0700 (PDT) Subject: [Tutor] Memory Leak? Message-ID: <107168.14558.qm@web54307.mail.re2.yahoo.com> Hi, I'm doing some image processing using PIL and SciPy. Individual images are 2000x2000 pixels with each pixel being 16 bits, so a single image is around 7 MB in size. I've noticed that while my code is running the amount of memory being used (as reported by Windows Task Manager) by Python gradually increases. It continues to increase if I re-run the same code again from within iPython (everytime I re-run the code the memory used increases by about 300 MB). So after re-running the code several times (while debugging and/or developing) I will eventually get a memory exception (). Does this mean I've somehow created a memory leak? From what I've read, in Python 2.X creating a memory leak is a hard thing to do. Perhaps I'm just doing a terrible job of coding and am constantly creating new things that take up memory??? My basic code structure is below. Anyone has any suggestions on how to improve the efficiency of my code or to debug this problem? Thank you in advance, Keith def function1(filename): image1=im2array(filename) #im2array is a function I wrote to open a tiff image as a scipy array #average the 2000x2000 2d array into a single 2000x1 1d array # perform some scaling on the 2000x1 1d array #take the FFT of the 2000x1 1d array result=[fftpeak, fftmaxamplitude] #output is just two float values return result filenames=['file1.tif','file2.tif',...] #about 40 image filenames in this list results=[] for ind in xrange(0,len(filenames): results.append(function1(filenames[ind])) --------------------------------- Be a better friend, newshound, and know-it-all with Yahoo! Mobile. Try it now. -------------- next part -------------- An HTML attachment was scrubbed... URL: From inthefridge at gmail.com Wed May 7 21:59:58 2008 From: inthefridge at gmail.com (Spencer Parker) Date: Wed, 7 May 2008 13:59:58 -0600 Subject: [Tutor] Excluding a directory in a script... In-Reply-To: <1c2a2c590805071257s6413132sde5ff854a6d9e51@mail.gmail.com> References: <1c2a2c590805071257s6413132sde5ff854a6d9e51@mail.gmail.com> Message-ID: here is the code: http://dpaste.com/48734/ On Wed, May 7, 2008 at 1:57 PM, Kent Johnson wrote: > On Wed, May 7, 2008 at 3:34 PM, Spencer Parker > wrote: > > I have a script that is just basically looking for a disk image in a > > directory. > > Please show us the script. > > Kent > -- Spencer Parker _______________________________________________________ "if you can't go to heaven, may you at least die in Ireland." _______________________________________________________ -------------- next part -------------- An HTML attachment was scrubbed... URL: From mlangford.cs03 at gtalumni.org Wed May 7 22:18:23 2008 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Wed, 7 May 2008 16:18:23 -0400 Subject: [Tutor] Memory Leak? In-Reply-To: <107168.14558.qm@web54307.mail.re2.yahoo.com> References: <107168.14558.qm@web54307.mail.re2.yahoo.com> Message-ID: <82b4f5810805071318r5779e585u3f7497013105d272@mail.gmail.com> You can always make a subclass of the classes you're thinking aren't being garbage collected and put a print statement in their __del__ functions to show you when they are. That will show you if/which objects aren't being deleted. Do you have any global variables? --Michael On Wed, May 7, 2008 at 3:50 PM, Keith Suda-Cederquist wrote: > Hi, > > I'm doing some image processing using PIL and SciPy. Individual images are > 2000x2000 pixels with each pixel being 16 bits, so a single image is around > 7 MB in size. > > I've noticed that while my code is running the amount of memory being used > (as reported by Windows Task Manager) by Python gradually increases. It > continues to increase if I re-run the same code again from within iPython > (everytime I re-run the code the memory used increases by about 300 MB). So > after re-running the code several times (while debugging and/or developing) > I will eventually get a memory exception (). > > Does this mean I've somehow created a memory leak? From what I've read, > in Python 2.X creating a memory leak is a hard thing to do. Perhaps I'm > just doing a terrible job of coding and am constantly creating new things > that take up memory??? > > My basic code structure is below. Anyone has any suggestions on how to > improve the efficiency of my code or to debug this problem? > > Thank you in advance, > Keith > > def function1(filename): > image1=im2array(filename) > #im2array is a function I wrote to open a tiff image as a scipy array > #average the 2000x2000 2d array into a single 2000x1 1d array > # perform some scaling on the 2000x1 1d array > #take the FFT of the 2000x1 1d array > result=[fftpeak, fftmaxamplitude] #output is just two float values > return result > > filenames=['file1.tif','file2.tif',...] #about 40 image filenames in this > list > > results=[] > for ind in xrange(0,len(filenames): > results.append(function1(filenames[ind])) > > > > > ------------------------------ > Be a better friend, newshound, and know-it-all with Yahoo! Mobile. Try it > now. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Michael Langford Phone: 404-386-0495 Consulting: http://www.RowdyLabs.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Wed May 7 22:23:26 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 7 May 2008 16:23:26 -0400 Subject: [Tutor] Excluding a directory in a script... In-Reply-To: References: Message-ID: <1c2a2c590805071323icd7d1b0yfa3e4c6d6bcdc371@mail.gmail.com> On Wed, May 7, 2008 at 3:34 PM, Spencer Parker wrote: > I have a script that is just basically looking for a disk image in a > directory...it lists all the directories in the main disk image directory > then appends disk.img to the end to build the full file path. I have one > directory that holds old images in it for deletion at a later date. This > directory will never contain disk.img in there...it causes the script to > error out since it didn't find that in there. How can I exclude this > directory from being listed? I guess you want something like path = sys.argv[1] + '/' + i + '/disk.img' if not os.path.isfile(path): continue Kent PS it helps to give the actual error as well as the code. From kent37 at tds.net Wed May 7 22:28:20 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 7 May 2008 16:28:20 -0400 Subject: [Tutor] Memory Leak? In-Reply-To: <107168.14558.qm@web54307.mail.re2.yahoo.com> References: <107168.14558.qm@web54307.mail.re2.yahoo.com> Message-ID: <1c2a2c590805071328g2cb80cb5i75cc64cf026dab78@mail.gmail.com> On Wed, May 7, 2008 at 3:50 PM, Keith Suda-Cederquist wrote: > Hi, > > I'm doing some image processing using PIL and SciPy. Individual images are > 2000x2000 pixels with each pixel being 16 bits, so a single image is around > 7 MB in size. > > I've noticed that while my code is running the amount of memory being used > (as reported by Windows Task Manager) by Python gradually increases. It > continues to increase if I re-run the same code again from within iPython > (everytime I re-run the code the memory used increases by about 300 MB). So > after re-running the code several times (while debugging and/or developing) > I will eventually get a memory exception (). 7 * 40 is close to 300 so I guess you are somehow not freeing the images. > def function1(filename): > image1=im2array(filename) > #im2array is a function I wrote to open a tiff image as a scipy array > #average the 2000x2000 2d array into a single 2000x1 1d array > # perform some scaling on the 2000x1 1d array > #take the FFT of the 2000x1 1d array > result=[fftpeak, fftmaxamplitude] #output is just two float values > return result > > filenames=['file1.tif','file2.tif',...] #about 40 image filenames in this > list This looks ok, I guess any problem is in im2array. > results=[] > for ind in xrange(0,len(filenames): > results.append(function1(filenames[ind])) This can be written much more simply with a list comprehension: results = [ function1(name) for name in filenames ] Kent From bgailer at gmail.com Wed May 7 23:08:00 2008 From: bgailer at gmail.com (bob gailer) Date: Wed, 07 May 2008 17:08:00 -0400 Subject: [Tutor] Excluding a directory in a script... In-Reply-To: References: <1c2a2c590805071257s6413132sde5ff854a6d9e51@mail.gmail.com> Message-ID: <48221A30.10202@gmail.com> Spencer Parker wrote: > here is the code: > http://dpaste.com/48734/ Please show us the traceback. -- Bob Gailer 919-636-4239 Chapel Hill, NC From cappy2112 at gmail.com Wed May 7 23:14:39 2008 From: cappy2112 at gmail.com (Tony Cappellini) Date: Wed, 7 May 2008 14:14:39 -0700 Subject: [Tutor] Memory Leak? Message-ID: <8249c4ac0805071414q354ea9e8ld69746cb8c390fff@mail.gmail.com> Message: 5 Date: Wed, 7 May 2008 16:18:23 -0400 From: "Michael Langford" Subject: Re: [Tutor] Memory Leak? To: "Keith Suda-Cederquist" Cc: Python Tutor List Message-ID: <82b4f5810805071318r5779e585u3f7497013105d272 at mail.gmail.com> Content-Type: text/plain; charset="iso-8859-1" >>You can always make a subclass of the classes you're thinking aren't being >>garbage collected and put a print statement in their __del__ functions to >>show you when they are. That will show you if/which objects aren't being >>deleted. Is this reliable or will this just confuse the issue? Python in a Nutshell states "While gc itself can automatically fix many leaks (as long as you avoid defining __del__ in your classes, since the existence of __del__ can block cyclic garbage collection), your program runs faster if it avoids creating cyclic garbage in the first place -------------- next part -------------- An HTML attachment was scrubbed... URL: From kdsudac at yahoo.com Thu May 8 00:03:37 2008 From: kdsudac at yahoo.com (Keith Suda-Cederquist) Date: Wed, 7 May 2008 15:03:37 -0700 (PDT) Subject: [Tutor] Memory Leak? In-Reply-To: <8249c4ac0805071414q354ea9e8ld69746cb8c390fff@mail.gmail.com> Message-ID: <776473.60306.qm@web54306.mail.re2.yahoo.com> So I started commenting things out until I isolated the problem. For some reason when I plot some of the data using pylab/matplotlib, then close the figure using pylab.close() the memory doesn't get cleared. (I left this part out of my psedo-code in my previous post--Sorry!). I followed the advice on this page: http://mail.python.org/pipermail/python-list/2006-December/417208.html and the problem is now gone. I'm a little confused about the whole memory situation now, but I guess I can move on. Are these generally known and accepted problems that people just work around? Can anyone suggest a better way for me to implement plotting using pylab/matplotlib in the future? Thanks, Keith Tony Cappellini wrote: Message: 5 Date: Wed, 7 May 2008 16:18:23 -0400 From: "Michael Langford" Subject: Re: [Tutor] Memory Leak? To: "Keith Suda-Cederquist" Cc: Python Tutor List Message-ID: <82b4f5810805071318r5779e585u3f7497013105d272 at mail.gmail.com> Content-Type: text/plain; charset="iso-8859-1" >>You can always make a subclass of the classes you're thinking aren't being >>garbage collected and put a print statement in their __del__ functions to >>show you when they are. That will show you if/which objects aren't being >>deleted. Is this reliable or will this just confuse the issue? Python in a Nutshell states "While gc itself can automatically fix many leaks (as long as you avoid defining __del__ in your classes, since the existence of __del__ can block cyclic garbage collection), your program runs faster if it avoids creating cyclic garbage in the first place _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor --------------------------------- Be a better friend, newshound, and know-it-all with Yahoo! Mobile. Try it now. -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Thu May 8 01:53:58 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 7 May 2008 19:53:58 -0400 Subject: [Tutor] Memory Leak? In-Reply-To: <776473.60306.qm@web54306.mail.re2.yahoo.com> References: <8249c4ac0805071414q354ea9e8ld69746cb8c390fff@mail.gmail.com> <776473.60306.qm@web54306.mail.re2.yahoo.com> Message-ID: <1c2a2c590805071653i6ad5db75pfeb2d4af4f8868e3@mail.gmail.com> On Wed, May 7, 2008 at 6:03 PM, Keith Suda-Cederquist wrote: > I followed the advice on this page: > http://mail.python.org/pipermail/python-list/2006-December/417208.html > and the problem is now gone. Which advice did you follow? There are quite a few suggestions on that page and the linked FAQ entry. > I'm a little confused about the whole memory situation now, but I guess I > can move on. Are these generally known and accepted problems that people > just work around? Judging from the FAQ they may be known. Kent From jeff at drinktomi.com Thu May 8 02:41:10 2008 From: jeff at drinktomi.com (Jeff Younker) Date: Wed, 7 May 2008 17:41:10 -0700 Subject: [Tutor] Memory Leak? In-Reply-To: <776473.60306.qm@web54306.mail.re2.yahoo.com> References: <776473.60306.qm@web54306.mail.re2.yahoo.com> Message-ID: > I followed the advice on this page: http://mail.python.org/pipermail/python-list/2006-December/417208.html > and the problem is now gone. There are two pieces of advice on that page. Which did you follow? - Jeff Younker - jeff at drinktomi.com - From eike.welk at gmx.net Thu May 8 13:52:21 2008 From: eike.welk at gmx.net (Eike Welk) Date: Thu, 08 May 2008 13:52:21 +0200 Subject: [Tutor] Memory Leak? In-Reply-To: <776473.60306.qm@web54306.mail.re2.yahoo.com> References: <776473.60306.qm@web54306.mail.re2.yahoo.com> Message-ID: <200805081352.22209.eike.welk@gmx.net> On Thursday 08 May 2008 00:03, Keith Suda-Cederquist wrote: > So I started commenting things out until I isolated the problem. > For some reason when I plot some of the data using > pylab/matplotlib, then close the figure using pylab.close() the > memory doesn't get cleared. (I left this part out of my psedo-code > in my previous post--Sorry!). I can reproduce this behavior with the QT-Agg backend on my computer too. However when I use a non-interactive backend, the problem goes away. Backends are explained here: http://matplotlib.sourceforge.net/backends.html Here's an example script. The memory usage remains constant. Without lines 1 and 2 however the memory usage increases continuously during the for loop. eike at bookxie:~> ipython Total number of aliases: 15 Python 2.5 (r25:51908, Jan 10 2008, 17:55:29) Type "copyright", "credits" or "license" for more information. IPython 0.7.2 -- An enhanced Interactive Python. ? -> Introduction to IPython's features. %magic -> Information about IPython's 'magic' % functions. help -> Python's own help system. object? -> Details about 'object'. ?object also works, ?? prints more. In [1]:import matplotlib In [2]:matplotlib.use('Agg') In [3]:import pylab as pl In [4]:for i in range(1000): .4.: pl.figure() .4.: pl.plot([1,2,3]) .4.: pl.close() .3.: < lines deleted > Out[4]:[] Out[4]: Out[4]:[] In [5]: Kind regards, Eke. From mlangford.cs03 at gtalumni.org Thu May 8 17:48:42 2008 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Thu, 8 May 2008 11:48:42 -0400 Subject: [Tutor] Memory Leak? In-Reply-To: <8249c4ac0805071414q354ea9e8ld69746cb8c390fff@mail.gmail.com> References: <8249c4ac0805071414q354ea9e8ld69746cb8c390fff@mail.gmail.com> Message-ID: <82b4f5810805080848h62d88be9jcef00d022f663489@mail.gmail.com> > > >>You can always make a subclass of the classes you're thinking aren't > being > >>garbage collected and put a print statement in their __del__ functions to > >>show you when they are. That will show you if/which objects aren't being > >>deleted. > > Is this reliable or will this just confuse the issue? > > Python in a Nutshell states "While gc itself can automatically fix many > leaks (as long as you avoid defining __del__ in your classes, since the > existence of __del__ can block cyclic garbage collection), your program runs > faster if it avoids creating cyclic garbage in the first place > > Yes is it reliable if you are intending to have non-cyclic data in the first place (which has no chance of no being gc-ed). This sounds like his use case. --Michael -- Michael Langford Phone: 404-386-0495 Consulting: http://www.RowdyLabs.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From lists at sandipb.net Thu May 8 17:40:29 2008 From: lists at sandipb.net (Sandip Bhattacharya) Date: Thu, 8 May 2008 21:10:29 +0530 Subject: [Tutor] Buffering in file.read() Message-ID: <20080508154029.GA7950@sandipb.net> Suppose I need to write a program which needs to parse lots of binary files. This requires multiple reads of small amounts of data. Obviously if I need to do this very often, I need to do some kind of buffering to reduce IO. My question is this - does Python have its own buffering while doing file.read()? In that case, I can stop worrying about writing my own buffering logic and just read like I desire. - Sandip -- Sandip Bhattacharya From dkuhlman at rexx.com Thu May 8 19:40:58 2008 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Thu, 8 May 2008 10:40:58 -0700 Subject: [Tutor] Buffering in file.read() In-Reply-To: <20080508154029.GA7950@sandipb.net> References: <20080508154029.GA7950@sandipb.net> Message-ID: <20080508174058.GA80995@cutter.rexx.com> On Thu, May 08, 2008 at 09:10:29PM +0530, Sandip Bhattacharya wrote: > > Suppose I need to > write a program which needs to parse lots of binary files. This requires > multiple reads of small amounts of data. Obviously if I need to do this > very often, I need to do some kind of buffering to reduce IO. > > My question is this - does Python have its own buffering while doing > file.read()? In that case, I can stop worrying about writing my own > buffering logic and just read like I desire. > Take a look at the optional "bufsize" argument to the "open" built-in function: "The optional bufsize argument specifies the file's desired buffer size: 0 means unbuffered, 1 means line buffered, any other positive value means use a buffer of (approximately) that size. A negative bufsize means to use the system default, which is usually line buffered for tty devices and fully buffered for other files. If omitted, the system default is used." -- http://docs.python.org/lib/built-in-funcs.html#l2h-54 Looks to me that the buffering is done for you, but that you can control it a bit. - Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From rdm at rcblue.com Thu May 8 19:51:46 2008 From: rdm at rcblue.com (Dick Moores) Date: Thu, 08 May 2008 10:51:46 -0700 Subject: [Tutor] regex newbie question Message-ID: <20080508175308.E5EE61E401C@bag.python.org> An HTML attachment was scrubbed... URL: From kent37 at tds.net Thu May 8 20:07:14 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 8 May 2008 14:07:14 -0400 Subject: [Tutor] Buffering in file.read() In-Reply-To: <20080508174058.GA80995@cutter.rexx.com> References: <20080508154029.GA7950@sandipb.net> <20080508174058.GA80995@cutter.rexx.com> Message-ID: <1c2a2c590805081107s162bdb7fqd10f46344270c9c2@mail.gmail.com> On Thu, May 8, 2008 at 1:40 PM, Dave Kuhlman wrote: > On Thu, May 08, 2008 at 09:10:29PM +0530, Sandip Bhattacharya wrote: > Take a look at the optional "bufsize" argument to the "open" built-in > function: > > "The optional bufsize argument specifies the file's desired buffer > size: 0 means unbuffered, 1 means line buffered, any other positive > value means use a buffer of (approximately) that size. A negative > bufsize means to use the system default, which is usually line > buffered for tty devices and fully buffered for other files. If > omitted, the system default is used." > > -- http://docs.python.org/lib/built-in-funcs.html#l2h-54 > > Looks to me that the buffering is done for you, but that you can > control it a bit. Footnote 2.3 says, "Specifying a buffer size currently has no effect on systems that don't have setvbuf(). The interface to specify the buffer size is not done using a method that calls setvbuf(), because that may dump core when called after any I/O has been performed, and there's no reliable way to determine whether this is the case." So whether that works will depend on what OS the OP is using. Presumably the underlying file system does at least block-level buffering but I can't say for sure... Kent From kent37 at tds.net Thu May 8 20:14:24 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 8 May 2008 14:14:24 -0400 Subject: [Tutor] regex newbie question In-Reply-To: <20080508175308.E5EE61E401C@bag.python.org> References: <20080508175308.E5EE61E401C@bag.python.org> Message-ID: <1c2a2c590805081114p41c5f1c2oec221b54d1a53986@mail.gmail.com> On Thu, May 8, 2008 at 1:51 PM, Dick Moores wrote: > > Could someone tell me what's wrong with this regex? > > ============================================== > lst = ["2/2/2", "3/3/45", "345/03/45", "4/4/2009", "4/4/12345", > "12/12/555", "12/12", "2/2", "2/12", "12/2"] > > regex = r"\b\d+/\d+/\d{2,4}\b|\b\d{1,2}/\d{1,2}\b" \b matches the boundary between word and non-word. \ is a non-word character so each number is a word and "2/2/2" will match against \b\d{1,2}/\d{1,2}\b. The regex only has to match some part of the string, not the whole string. If you want to match against the full string then use ^ and $ at beginning and end of the regex rather than \b. Kent From steve at alchemy.com Thu May 8 20:21:34 2008 From: steve at alchemy.com (Steve Willoughby) Date: Thu, 8 May 2008 11:21:34 -0700 (PDT) Subject: [Tutor] regex newbie question In-Reply-To: <20080508175308.E5EE61E401C@bag.python.org> References: <20080508175308.E5EE61E401C@bag.python.org> Message-ID: <51592.134.134.136.14.1210270894.squirrel@webmail.alchemy.com> On Thu, May 8, 2008 10:51, Dick Moores wrote: > > > Could someone tell me what's wrong with this regex?

The main thing is that you're forgetting that a RE matches anywhere in the string. \b\d+/\d+/\d{2,4}\b matches 4/4/2009 12/12/555 \b\d{1,2}/\d{1,2}\b matches 4/4/2009 4/4/12345 12/12/555 12/12 2/2 2/12 From rdm at rcblue.com Thu May 8 20:42:06 2008 From: rdm at rcblue.com (Dick Moores) Date: Thu, 08 May 2008 11:42:06 -0700 Subject: [Tutor] regex newbie question In-Reply-To: <1c2a2c590805081114p41c5f1c2oec221b54d1a53986@mail.gmail.co m> References: <20080508175308.E5EE61E401C@bag.python.org> <1c2a2c590805081114p41c5f1c2oec221b54d1a53986@mail.gmail.com> Message-ID: <20080508184232.D61221E400C@bag.python.org> An HTML attachment was scrubbed... URL: From steve at alchemy.com Thu May 8 20:46:59 2008 From: steve at alchemy.com (Steve Willoughby) Date: Thu, 8 May 2008 11:46:59 -0700 (PDT) Subject: [Tutor] regex newbie question In-Reply-To: <20080508184232.D61221E400C@bag.python.org> References: <20080508175308.E5EE61E401C@bag.python.org> <1c2a2c590805081114p41c5f1c2oec221b54d1a53986@mail.gmail.com> <20080508184232.D61221E400C@bag.python.org> Message-ID: <51882.134.134.136.14.1210272419.squirrel@webmail.alchemy.com> Be aware that \d{2,4} matches 2, 3 or 4 digits, which may be different than what you're looking for, since 1/12/234 would match On Thu, May 8, 2008 11:42, Dick Moores wrote: > > > At 11:14 AM 5/8/2008, Kent Johnson wrote:
>
On Thu, May 8, 2008 at 1:51 PM, > Dick Moores <rdm at rcblue.com> wrote:
> >
> >  Could someone tell me what's wrong with this regex?
> >
> >  ==============================================
> >  lst = ["2/2/2", "3/3/45", > "345/03/45", "4/4/2009", "4/4/12345",
> >         > "12/12/555", "12/12", "2/2", > "2/12", "12/2"]
> >
> >  regex = > r"\b\d+/\d+/\d{2,4}\b|\b\d{1,2}/\d{1,2}\b"

> \b matches the boundary between word and non-word. \ is a non-word
> character so each number is a word and "2/2/2" will match > against
> \b\d{1,2}/\d{1,2}\b. The regex only has to match some part of the
> string, not the whole string.

> If you want to match against the full string then use ^ and $ at
> beginning and end of the regex rather than \b.

> Changing to
> regex = r"^\d+/\d+/\d{2,4}$|^\d{1,2}/\d{1,2}$"

>
did the job, and I learned several important points.

> Thanks, Kent and Steve!

> Dick
> > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From rdm at rcblue.com Thu May 8 21:40:28 2008 From: rdm at rcblue.com (Dick Moores) Date: Thu, 08 May 2008 12:40:28 -0700 Subject: [Tutor] regex newbie question In-Reply-To: <51882.134.134.136.14.1210272419.squirrel@webmail.alchemy.c om> References: <20080508175308.E5EE61E401C@bag.python.org> <1c2a2c590805081114p41c5f1c2oec221b54d1a53986@mail.gmail.com> <20080508184232.D61221E400C@bag.python.org> <51882.134.134.136.14.1210272419.squirrel@webmail.alchemy.com> Message-ID: <20080508194125.1E6441E400C@bag.python.org> At 11:46 AM 5/8/2008, Steve Willoughby wrote: >Be aware that \d{2,4} matches 2, 3 or 4 digits, which may be >different than what you're looking for, since 1/12/234 would >match Yes, I wanted to permit that. In my script, mxDateTime turns 1/12/234 into 01/12/0234. So if a user wants to enter it, I'll let him. But here's a chance to ask: What regex would match 2-digit strings and 4-digit strings only? And another: What regex matches the "" string? Dick From timmichelsen at gmx-topmail.de Thu May 8 22:08:00 2008 From: timmichelsen at gmx-topmail.de (Tim Michelsen) Date: Thu, 08 May 2008 22:08:00 +0200 Subject: [Tutor] converting all files in a directory with subprocess Message-ID: Hello, I am working on a automatic documentation program to convert my txt2tags based documentations sources into HTMl files. I want to use txt2tags via command line. Here's my code: ##### #!/usr/bin/env python # -*- coding: utf-8 -*- import os import subprocess import fnmatch documentation_directory = './doc/' for file in os.listdir(documentation_directory): if fnmatch.fnmatch(file, '*.t2t'): print file subprocess.call('txt2tags', '-t html', '--toc') ##### END #### When I run the script it exits with the following error message: #### START OUTPUT #### python ./make_documentation.py index.t2t Traceback (most recent call last): File "./make_documentation.py", line 12, in subprocess.call('txt2tags', '-t html', '--toc') File "/usr/lib/python2.5/subprocess.py", line 444, in call return Popen(*popenargs, **kwargs).wait() File "/usr/lib/python2.5/subprocess.py", line 545, in __init__ raise TypeError("bufsize must be an integer") TypeError: bufsize must be an integer #### END OUTPUT #### I am stuck here. Why would the script not let txt2tags convert every file in my directory? like txt2tags -t html --toc THEFILE I already tried subprocess.call('txt2tags', '-t html', '--toc', file) But without success. I'd appreciate any pointer here. Thanks and regards, Timmie From mail at timgolden.me.uk Thu May 8 22:13:34 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 08 May 2008 21:13:34 +0100 Subject: [Tutor] converting all files in a directory with subprocess In-Reply-To: References: Message-ID: <48235EEE.60404@timgolden.me.uk> Tim Michelsen wrote: > Hello, > I am working on a automatic documentation program to convert my txt2tags > based documentations sources into HTMl files. I want to use txt2tags via > command line. > > Here's my code: > > ##### > > #!/usr/bin/env python > # -*- coding: utf-8 -*- > import os > import subprocess > import fnmatch > > documentation_directory = './doc/' > > for file in os.listdir(documentation_directory): > if fnmatch.fnmatch(file, '*.t2t'): > print file > subprocess.call('txt2tags', '-t html', '--toc') > > ##### END #### > > When I run the script it exits with the following error message: > > #### START OUTPUT #### > python ./make_documentation.py > index.t2t > Traceback (most recent call last): > File "./make_documentation.py", line 12, in > subprocess.call('txt2tags', '-t html', '--toc') > File "/usr/lib/python2.5/subprocess.py", line 444, in call > return Popen(*popenargs, **kwargs).wait() > File "/usr/lib/python2.5/subprocess.py", line 545, in __init__ > raise TypeError("bufsize must be an integer") > TypeError: bufsize must be an integer > #### END OUTPUT #### Whenever you're running subprocess.call and you see this error, say to yourself: "Have I passed the command line as one parameter in a list; or have I passed it as a series of parameters?" Because I can't remember the number of times I've made that mistake myself. Basically, subprocess.call expects either a string or a list of strings as the first param, and then the second one is the bufsize, an integer. And then there are others (check the params to subprocess.Popen). You're passing a string -- your second param -- as the second parameter, and it's not an integer. So you get a TypeError. Simple, no? TJG From steve at alchemy.com Thu May 8 22:30:39 2008 From: steve at alchemy.com (Steve Willoughby) Date: Thu, 8 May 2008 13:30:39 -0700 (PDT) Subject: [Tutor] regex newbie question In-Reply-To: <20080508194125.1E6441E400C@bag.python.org> References: <20080508175308.E5EE61E401C@bag.python.org> <1c2a2c590805081114p41c5f1c2oec221b54d1a53986@mail.gmail.com> <20080508184232.D61221E400C@bag.python.org> <51882.134.134.136.14.1210272419.squirrel@webmail.alchemy.com> <20080508194125.1E6441E400C@bag.python.org> Message-ID: <53155.134.134.136.14.1210278639.squirrel@webmail.alchemy.com> On Thu, May 8, 2008 12:40, Dick Moores wrote: > At 11:46 AM 5/8/2008, Steve Willoughby wrote: >>Be aware that \d{2,4} matches 2, 3 or 4 digits, which may be >>different than what you're looking for, since 1/12/234 would >>match > > Yes, I wanted to permit that. In my script, mxDateTime turns 1/12/234 > into 01/12/0234. So if a user wants to enter it, I'll let him. > > But here's a chance to ask: What regex would match 2-digit strings > and 4-digit strings only? ^\d\d(\d\d)?$ > And another: What regex matches the "" string? ^$ From eric at glodime.com Thu May 8 22:38:49 2008 From: eric at glodime.com (Eric Morey) Date: Thu, 08 May 2008 16:38:49 -0400 Subject: [Tutor] Tutorial indicating different output Message-ID: <1210279129.5244.23.camel@glodime-XI> Hello everyone, ?I have no prior experience with programing. I've just started with the Python tutorial at http://www.dickbaldwin.com/tocpyth.htm. On the section that describes ?decimal division on this page: http://www.dickbaldwin.com/python/Pyth0004.htm Figure 10 shows: >>> 2.0/5 # get decimal quotient 0.4 >>> 2/5.0 # do it again 0.4 >>> ? http://www.dickbaldwin.com/python/Pyth0004-fig10.htm Howerver, using the python shell in my terminal, I get: >>> 2.0/5 # get decimal quotient 0.40000000000000002 >>> 2/5.0 # do it again 0.40000000000000002 >>> I didn't worry too much about it and continued to move on. But I'm curious as to why there was a difference. Anyone know why? Eric... From rdm at rcblue.com Thu May 8 23:40:16 2008 From: rdm at rcblue.com (Dick Moores) Date: Thu, 08 May 2008 14:40:16 -0700 Subject: [Tutor] regex newbie question In-Reply-To: <53155.134.134.136.14.1210278639.squirrel@webmail.alchemy.c om> References: <20080508175308.E5EE61E401C@bag.python.org> <1c2a2c590805081114p41c5f1c2oec221b54d1a53986@mail.gmail.com> <20080508184232.D61221E400C@bag.python.org> <51882.134.134.136.14.1210272419.squirrel@webmail.alchemy.com> <20080508194125.1E6441E400C@bag.python.org> <53155.134.134.136.14.1210278639.squirrel@webmail.alchemy.com> Message-ID: <20080508214036.BD0DB1E4017@bag.python.org> At 01:30 PM 5/8/2008, Steve Willoughby wrote: >On Thu, May 8, 2008 12:40, Dick Moores wrote: > > But here's a chance to ask: What regex would match 2-digit strings > > and 4-digit strings only? > >^\d\d(\d\d)?$ Ah. And so ^\d\d(\d\d)?(\d\d)?$ matches all and only 2-, 4-, and 6-digit strings. Which makes me wonder if there's a regex for ALL and only strings of digits only, with an even number of digits. > > And another: What regex matches the "" string? > >^$ Oh, of course. Thanks, Dick From alan.gauld at btinternet.com Fri May 9 00:33:46 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 8 May 2008 23:33:46 +0100 Subject: [Tutor] Tutorial indicating different output References: <1210279129.5244.23.camel@glodime-XI> Message-ID: "Eric Morey" wrote > >>> 2.0/5 # get decimal quotient > 0.4 > >>> 2/5.0 # do it again > 0.4 > >>> > ? > http://www.dickbaldwin.com/python/Pyth0004-fig10.htm > > > Howerver, using the python shell in my terminal, I get: > >>> 2.0/5 # get decimal quotient > 0.40000000000000002 > >>> 2/5.0 # do it again > 0.40000000000000002 > >>> Looks like the author cheated a little. If you explicitly print the result: >>> print 2.0/5 # get decimal quotient 0.4 It should work as expected. Without the print Python uses a slightly different set of formatting rules for values. (print uses str() while evaluating uses repr(), but you don;t need to worry about that yet! :-) My advice to beginners is to always use print for consistent results even though it is more typing. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From steve at alchemy.com Fri May 9 01:32:54 2008 From: steve at alchemy.com (Steve Willoughby) Date: Thu, 8 May 2008 16:32:54 -0700 (PDT) Subject: [Tutor] regex newbie question In-Reply-To: <20080508214036.BD0DB1E4017@bag.python.org> References: <20080508175308.E5EE61E401C@bag.python.org> <1c2a2c590805081114p41c5f1c2oec221b54d1a53986@mail.gmail.com> <20080508184232.D61221E400C@bag.python.org> <51882.134.134.136.14.1210272419.squirrel@webmail.alchemy.com> <20080508194125.1E6441E400C@bag.python.org> <53155.134.134.136.14.1210278639.squirrel@webmail.alchemy.com> <20080508214036.BD0DB1E4017@bag.python.org> Message-ID: <58332.134.134.136.14.1210289574.squirrel@webmail.alchemy.com> On Thu, May 8, 2008 14:40, Dick Moores wrote: > At 01:30 PM 5/8/2008, Steve Willoughby wrote: >>On Thu, May 8, 2008 12:40, Dick Moores wrote: >> > But here's a chance to ask: What regex would match 2-digit strings >> > and 4-digit strings only? >> >>^\d\d(\d\d)?$ > > Ah. And so ^\d\d(\d\d)?(\d\d)?$ matches all and only 2-, 4-, and > 6-digit strings. Which makes me wonder if there's a regex for ALL > and only strings of digits only, with an even number of digits. That would be r'^\d\d(\d\d)*$' From steve at alchemy.com Fri May 9 01:34:26 2008 From: steve at alchemy.com (Steve Willoughby) Date: Thu, 8 May 2008 16:34:26 -0700 (PDT) Subject: [Tutor] regex newbie question In-Reply-To: <58332.134.134.136.14.1210289574.squirrel@webmail.alchemy.com> References: <20080508175308.E5EE61E401C@bag.python.org> <1c2a2c590805081114p41c5f1c2oec221b54d1a53986@mail.gmail.com> <20080508184232.D61221E400C@bag.python.org> <51882.134.134.136.14.1210272419.squirrel@webmail.alchemy.com> <20080508194125.1E6441E400C@bag.python.org> <53155.134.134.136.14.1210278639.squirrel@webmail.alchemy.com> <20080508214036.BD0DB1E4017@bag.python.org> <58332.134.134.136.14.1210289574.squirrel@webmail.alchemy.com> Message-ID: <58370.134.134.136.14.1210289666.squirrel@webmail.alchemy.com> On Thu, May 8, 2008 16:32, Steve Willoughby wrote: > On Thu, May 8, 2008 14:40, Dick Moores wrote: >> At 01:30 PM 5/8/2008, Steve Willoughby wrote: >>>On Thu, May 8, 2008 12:40, Dick Moores wrote: >>> > But here's a chance to ask: What regex would match 2-digit strings >>> > and 4-digit strings only? >>> >>>^\d\d(\d\d)?$ >> >> Ah. And so ^\d\d(\d\d)?(\d\d)?$ matches all and only 2-, 4-, and >> 6-digit strings. Which makes me wonder if there's a regex for ALL >> and only strings of digits only, with an even number of digits. > > That would be r'^\d\d(\d\d)*$' Or... r'^(\d\d)+$' From rdm at rcblue.com Fri May 9 02:33:54 2008 From: rdm at rcblue.com (Dick Moores) Date: Thu, 08 May 2008 17:33:54 -0700 Subject: [Tutor] How to catch this exception? Message-ID: <20080509003433.0246F1E401A@bag.python.org> An HTML attachment was scrubbed... URL: From rdm at rcblue.com Fri May 9 03:16:19 2008 From: rdm at rcblue.com (Dick Moores) Date: Thu, 08 May 2008 18:16:19 -0700 Subject: [Tutor] regex newbie question In-Reply-To: <58332.134.134.136.14.1210289574.squirrel@webmail.alchemy.c om> References: <20080508175308.E5EE61E401C@bag.python.org> <1c2a2c590805081114p41c5f1c2oec221b54d1a53986@mail.gmail.com> <20080508184232.D61221E400C@bag.python.org> <51882.134.134.136.14.1210272419.squirrel@webmail.alchemy.com> <20080508194125.1E6441E400C@bag.python.org> <53155.134.134.136.14.1210278639.squirrel@webmail.alchemy.com> <20080508214036.BD0DB1E4017@bag.python.org> <58332.134.134.136.14.1210289574.squirrel@webmail.alchemy.com> Message-ID: <20080509011631.5B17D1E400C@bag.python.org> At 04:32 PM 5/8/2008, Steve Willoughby wrote: >On Thu, May 8, 2008 14:40, Dick Moores wrote: > > At 01:30 PM 5/8/2008, Steve Willoughby wrote: > >>On Thu, May 8, 2008 12:40, Dick Moores wrote: > >> > But here's a chance to ask: What regex would match 2-digit strings > >> > and 4-digit strings only? > >> > >>^\d\d(\d\d)?$ > > > > Ah. And so ^\d\d(\d\d)?(\d\d)?$ matches all and only 2-, 4-, and > > 6-digit strings. Which makes me wonder if there's a regex for ALL > > and only strings of digits only, with an even number of digits. > >That would be r'^\d\d(\d\d)*$' OK! I bought RegexBuddy () today, which is a big help. However, it has a comment about your regex--I think it's saying you are wrong--tho it sure does the job for me with VALID 12 1234 123456 12345678 1234567890 1234567890112345678901 INVALID 1 123 12345 1234567 123456789 12345678901 123456789011234567890 in matching all the valids and none of the invalids. What say you? See Thanks very much, Dick From Nick.Treloar at education.nsw.gov.au Fri May 9 03:40:05 2008 From: Nick.Treloar at education.nsw.gov.au (Nick.Treloar at education.nsw.gov.au) Date: Fri, 9 May 2008 11:40:05 +1000 Subject: [Tutor] animations and movies Message-ID: <38336A03AE7EBF4C8ED36DBB759AF96C04CE2A77C9@EXCHMB-EVSB1.DETISP.LOCAL> hey just wondering if any one can point me in the right direction for coding animations and playing movies ________________________________ This message is intended for the addressee named and may contain privileged information or confidential information or both. If you are not the intended recipient please delete it and notify the sender. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at alchemy.com Fri May 9 05:55:37 2008 From: steve at alchemy.com (Steve Willoughby) Date: Thu, 08 May 2008 20:55:37 -0700 Subject: [Tutor] regex newbie question In-Reply-To: <20080509011631.5B17D1E400C@bag.python.org> References: <20080508175308.E5EE61E401C@bag.python.org> <1c2a2c590805081114p41c5f1c2oec221b54d1a53986@mail.gmail.com> <20080508184232.D61221E400C@bag.python.org> <51882.134.134.136.14.1210272419.squirrel@webmail.alchemy.com> <20080508194125.1E6441E400C@bag.python.org> <53155.134.134.136.14.1210278639.squirrel@webmail.alchemy.com> <20080508214036.BD0DB1E4017@bag.python.org> <58332.134.134.136.14.1210289574.squirrel@webmail.alchemy.com> <20080509011631.5B17D1E400C@bag.python.org> Message-ID: <4823CB39.2040803@alchemy.com> Dick Moores wrote: > At 04:32 PM 5/8/2008, Steve Willoughby wrote: >> On Thu, May 8, 2008 14:40, Dick Moores wrote: >> > At 01:30 PM 5/8/2008, Steve Willoughby wrote: >> >>On Thu, May 8, 2008 12:40, Dick Moores wrote: >> >> > But here's a chance to ask: What regex would match 2-digit strings >> >> > and 4-digit strings only? >> >> >> >>^\d\d(\d\d)?$ >> > >> > Ah. And so ^\d\d(\d\d)?(\d\d)?$ matches all and only 2-, 4-, and >> > 6-digit strings. Which makes me wonder if there's a regex for ALL >> > and only strings of digits only, with an even number of digits. >> >> That would be r'^\d\d(\d\d)*$' > > OK! > > I bought RegexBuddy () today, which is a big > help. However, it has a comment about your regex--I think it's saying > you are wrong--tho it sure does the job for me with No, the comment was warning you that something wouldn't work, but it's not what you were trying to do anyway. Sort of "If you were intending for this side effect to work in addition to matching even numbers of digits..." But that doesn't apply to your stated problem. > > VALID > 12 > 1234 > 123456 > 12345678 > 1234567890 > 1234567890112345678901 > INVALID > 1 > 123 > 12345 > 1234567 > 123456789 > 12345678901 > 123456789011234567890 > > in matching all the valids and none of the invalids. > > What say you? See > > > Thanks very much, > > Dick > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Fri May 9 06:26:15 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 9 May 2008 05:26:15 +0100 Subject: [Tutor] animations and movies References: <38336A03AE7EBF4C8ED36DBB759AF96C04CE2A77C9@EXCHMB-EVSB1.DETISP.LOCAL> Message-ID: wrote > hey just wondering if any one can point me in the > right direction for coding animations and playing movies ISTR a tool called blender that could do this. It was scripted in Python. Alan G From metolone+gmane at gmail.com Fri May 9 07:29:35 2008 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Thu, 8 May 2008 22:29:35 -0700 Subject: [Tutor] Tutorial indicating different output References: <1210279129.5244.23.camel@glodime-XI> Message-ID: "Eric Morey" wrote in message news:1210279129.5244.23.camel at glodime-XI... > Hello everyone, > > ?I have no prior experience with programing. I've just started with the > Python tutorial at http://www.dickbaldwin.com/tocpyth.htm. > On the section that describes ?decimal division on this page: > http://www.dickbaldwin.com/python/Pyth0004.htm > > Figure 10 shows: > > >>> 2.0/5 # get decimal quotient > 0.4 > >>> 2/5.0 # do it again > 0.4 > >>> > ? > http://www.dickbaldwin.com/python/Pyth0004-fig10.htm > > > Howerver, using the python shell in my terminal, I get: > >>> 2.0/5 # get decimal quotient > 0.40000000000000002 > >>> 2/5.0 # do it again > 0.40000000000000002 > >>> > > I didn't worry too much about it and continued to move on. But I'm > curious as to why there was a difference. Anyone know why? http://www.python.org/doc/faq/general/#why-are-floating-point-calculations-so-inaccurate -Mark From rdm at rcblue.com Fri May 9 11:42:30 2008 From: rdm at rcblue.com (Dick Moores) Date: Fri, 09 May 2008 02:42:30 -0700 Subject: [Tutor] How to catch this exception? In-Reply-To: <20080509003433.0246F1E401A@bag.python.org> References: <20080509003433.0246F1E401A@bag.python.org> Message-ID: <20080509094331.CACC91E400F@bag.python.org> An HTML attachment was scrubbed... URL: From bhaaluu at gmail.com Fri May 9 13:34:14 2008 From: bhaaluu at gmail.com (bhaaluu) Date: Fri, 9 May 2008 07:34:14 -0400 Subject: [Tutor] animations and movies In-Reply-To: <38336A03AE7EBF4C8ED36DBB759AF96C04CE2A77C9@EXCHMB-EVSB1.DETISP.LOCAL> References: <38336A03AE7EBF4C8ED36DBB759AF96C04CE2A77C9@EXCHMB-EVSB1.DETISP.LOCAL> Message-ID: http://pygame.org/news.html On Thu, May 8, 2008 at 9:40 PM, wrote: > hey just wondering if any one can point me in the right direction for coding > animations and playing movies > ________________________________ > This message is intended for the addressee named and may contain privileged > information or confidential information or both. If you are not the intended > recipient please delete it and notify the sender. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- b h a a l u u at g m a i l dot c o m Kid on Bus: What are you gonna do today, Napoleon? Napoleon Dynamite: Whatever I feel like I wanna do. Gosh! From mi.janssen at gmail.com Fri May 9 13:54:52 2008 From: mi.janssen at gmail.com (Michael Janssen) Date: Fri, 9 May 2008 13:54:52 +0200 Subject: [Tutor] regex newbie question In-Reply-To: <20080509011631.5B17D1E400C@bag.python.org> References: <20080508175308.E5EE61E401C@bag.python.org> <1c2a2c590805081114p41c5f1c2oec221b54d1a53986@mail.gmail.com> <20080508184232.D61221E400C@bag.python.org> <51882.134.134.136.14.1210272419.squirrel@webmail.alchemy.com> <20080508194125.1E6441E400C@bag.python.org> <53155.134.134.136.14.1210278639.squirrel@webmail.alchemy.com> <20080508214036.BD0DB1E4017@bag.python.org> <58332.134.134.136.14.1210289574.squirrel@webmail.alchemy.com> <20080509011631.5B17D1E400C@bag.python.org> Message-ID: <1ff2dfbf0805090454n6f8f9672yda5e071f2570a177@mail.gmail.com> On Fri, May 9, 2008 at 3:16 AM, Dick Moores wrote: > > At 04:32 PM 5/8/2008, Steve Willoughby wrote: >> >> That would be r'^\d\d(\d\d)*$' > > I bought RegexBuddy () today, which is a big > help. However, it has a comment about your regex The comment on http://www.rcblue.com/Regex/all_even_number_of_digits.htm is telling us, that the group only "captures" the last repetition. That's fine for the problem given, since we're not interessted in whatever the groups "captures". The group is solely used to enforce repetitions of two-digits-together. Since we're not interested in the group's submatch, we can ignore it beforehand: >>> mt = re.search(r'^\d\d(\d\d)*$', '1234') # capture (\d\d) >>> mt.group() # the full match '1234' >>> mt.group(1) # here is the captured submatch of group one '34' >>> mt = re.search(r'^\d\d(?:\d\d)*$', '1234') # non-grouping version, simply enforce two-digits, do not capture >>> mt.group() '1234' >>> mt.group(1) Traceback (most recent call last): File "", line 1, in ? IndexError: no such group the benefit of such a non-group is, that it's clear for the reader, that you're not intending to use the submatch later on and it keeps mt.group(*) clean. When I first saw the grouping versions, I've actually asked myself, hey, what you're gonna make with the group's match... regards Michael From bhawsar.vaibhav at gmail.com Fri May 9 15:36:31 2008 From: bhawsar.vaibhav at gmail.com (Vaibhav.bhawsar) Date: Fri, 9 May 2008 09:36:31 -0400 Subject: [Tutor] animations and movies In-Reply-To: References: <38336A03AE7EBF4C8ED36DBB759AF96C04CE2A77C9@EXCHMB-EVSB1.DETISP.LOCAL> Message-ID: <17d58cc40805090636l3ac1577fmff2fbcf4c0dadf86@mail.gmail.com> pyglet http://www.pyglet.org/ thats an option too On Fri, May 9, 2008 at 7:34 AM, bhaaluu wrote: > http://pygame.org/news.html > > On Thu, May 8, 2008 at 9:40 PM, > wrote: > > hey just wondering if any one can point me in the right direction for > coding > > animations and playing movies > > ________________________________ > > This message is intended for the addressee named and may contain > privileged > > information or confidential information or both. If you are not the > intended > > recipient please delete it and notify the sender. > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > -- > b h a a l u u at g m a i l dot c o m > Kid on Bus: What are you gonna do today, Napoleon? > Napoleon Dynamite: Whatever I feel like I wanna do. Gosh! > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Vaibhav Bhawsar -------------- next part -------------- An HTML attachment was scrubbed... URL: From bhaaluu at gmail.com Fri May 9 18:16:27 2008 From: bhaaluu at gmail.com (bhaaluu) Date: Fri, 9 May 2008 12:16:27 -0400 Subject: [Tutor] animations and movies In-Reply-To: <38336A03AE7EBF4C8ED36DBB759AF96C04CE2A77C9@EXCHMB-EVSB1.DETISP.LOCAL> References: <38336A03AE7EBF4C8ED36DBB759AF96C04CE2A77C9@EXCHMB-EVSB1.DETISP.LOCAL> Message-ID: On Thu, May 8, 2008 at 9:40 PM, wrote: > hey just wondering if any one can point me in the right direction for coding > animations and playing movies > ________________________________ > This message is intended for the addressee named and may contain privileged > information or confidential information or both. If you are not the intended > recipient please delete it and notify the sender. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > Here's a short pygame example that plays a video.mpg (MPEG 1 file): #!/usr/bin/python # movie.py import sys import pygame pygame.init() mov_name = "video.mpg" pygame.mouse.set_visible(False) pygame.mixer.quit() screen = pygame.display.set_mode((320, 240)) video = pygame.movie.Movie(mov_name) screen = pygame.display.set_mode(video.get_size()) video.play() while video.get_busy(): for event in pygame.event.get(): if event.type == pygame.QUIT: break Of course, you'll need a file called video.mpg for the script to work. -- b h a a l u u at g m a i l dot c o m Kid on Bus: What are you gonna do today, Napoleon? Napoleon Dynamite: Whatever I feel like I wanna do. Gosh! From bhaaluu at gmail.com Sat May 10 01:10:41 2008 From: bhaaluu at gmail.com (bhaaluu) Date: Fri, 9 May 2008 19:10:41 -0400 Subject: [Tutor] animations and movies In-Reply-To: <38336A03AE7EBF4C8ED36DBB759AF96C04CE2A77C9@EXCHMB-EVSB1.DETISP.LOCAL> References: <38336A03AE7EBF4C8ED36DBB759AF96C04CE2A77C9@EXCHMB-EVSB1.DETISP.LOCAL> Message-ID: On Thu, May 8, 2008 at 9:40 PM, Nick.Treloar at education.nsw.gov.au> wrote: > hey just wondering if any one can point me in the right direction for coding > animations and playing movies > ________________________________ > This message is intended for the addressee named and may contain privileged > information or confidential information or both. If you are not the intended > recipient please delete it and notify the sender. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > Here's an example of a pygame animation: http://www.cs.iupui.edu/~aharris/pygame/ch08/bounce.py The site has all sorts of other pygame examples on it. -- b h a a l u u at g m a i l dot c o m Kid on Bus: What are you gonna do today, Napoleon? Napoleon Dynamite: Whatever I feel like I wanna do. Gosh! From rdm at rcblue.com Sat May 10 15:36:53 2008 From: rdm at rcblue.com (Dick Moores) Date: Sat, 10 May 2008 06:36:53 -0700 Subject: [Tutor] Logging module Message-ID: <20080510133759.CAFC51E4011@bag.python.org> I don't understand how to use this. I've read and . I thought I'd try with a script that screws up: a = "qwerty" b = a*b But how to use the logging module to log the report of the screw up? Right now I don't care about the various levels. I just want to get something into a log file. Hellmann suggest this: import logging LOG_FILENAME = '/tmp/logging_example.out' logging.basicConfig(filename=LOG_FILENAME, level=logging.DEBUG,) logging.debug('This message should go to the log file') But where to put it? In my above script? Thanks, Dick Moores From mwalsh at groktech.org Sat May 10 23:03:20 2008 From: mwalsh at groktech.org (Martin Walsh) Date: Sat, 10 May 2008 16:03:20 -0500 Subject: [Tutor] Logging module Message-ID: <48260D98.70101@groktech.org> Dick Moores wrote: > But how to use the logging module to log the report of the screw up? > Right now I don't care about the various levels. I just want to get > something into a log file. > > Hellmann suggest this: > > import logging > LOG_FILENAME = '/tmp/logging_example.out' > logging.basicConfig(filename=LOG_FILENAME, level=logging.DEBUG,) > logging.debug('This message should go to the log file') > > But where to put it? In my above script? I usually wrap up code in a try except and use the logging.exception method, which is shorthand for logging.error(msg, exc_info=1), to include the traceback. Something like this: import logging LOG_FILENAME = '/tmp/logging_example.out' logging.basicConfig(filename=LOG_FILENAME, level=logging.DEBUG) def main(): a = "qwerty" b = a * b try: main() except: logging.exception('unknown') raise HTH, Marty From rdm at rcblue.com Sun May 11 02:08:18 2008 From: rdm at rcblue.com (Dick Moores) Date: Sat, 10 May 2008 17:08:18 -0700 Subject: [Tutor] Logging module In-Reply-To: <48260D98.70101@groktech.org> References: <48260D98.70101@groktech.org> Message-ID: <20080511000830.A08D91E4013@bag.python.org> At 02:03 PM 5/10/2008, Martin Walsh wrote: >Dick Moores wrote: > > But how to use the logging module to log the report of the screw up? > > Right now I don't care about the various levels. I just want to get > > something into a log file. > > > > Hellmann suggest this: > > > > import logging > > LOG_FILENAME = '/tmp/logging_example.out' > > logging.basicConfig(filename=LOG_FILENAME, level=logging.DEBUG,) > > logging.debug('This message should go to the log file') > > > > But where to put it? In my above script? > >I usually wrap up code in a try except and use the logging.exception >method, which is shorthand for logging.error(msg, exc_info=1), to >include the traceback. Something like this: > >import logging >LOG_FILENAME = '/tmp/logging_example.out' >logging.basicConfig(filename=LOG_FILENAME, level=logging.DEBUG) > >def main(): > a = "qwerty" > b = a * b > >try: > main() >except: > logging.exception('unknown') > raise Thank you! That gives me a good start. Dick From jatinder.singh2 at wipro.com Sun May 11 13:24:32 2008 From: jatinder.singh2 at wipro.com (root) Date: Sun, 11 May 2008 16:54:32 +0530 Subject: [Tutor] Tutor Digest, Vol 51, Issue 23 In-Reply-To: References: Message-ID: <1210505072.30416.16.camel@localhost.localdomain> Hi , I AM TRYING FOR A PYTHON PROGRAM THAT WILL CHECK WHETHER {- PHP AND MYSQL -} ARE INSTALLED ON lINUX OR NOT AND IF THEY ARE NOT INSTALLED THEN THE SCRIPT WILL TO INSTALL IT. for this I am doing import sys import os import commands import sys commands_hash = {} commands_hash['php'] = {} commands_hash['php']['title'] = "***********PHP**************" commands_hash['php']['value'] = "rpm -qa *php*" commands_hash['mysql'] = {} commands_hash['mysql']['title'] = "***********MYSQL**************" commands_hash['mysql']['value'] = "rpm -qa *mysql*" this is checking whether PHP and MYSQL are installed but PLEASE TELL ME HOW TO ENHANCE IT SO AS THE INSTALL IT IF NOT INSTALLED ALREADY. Thanks Jatinder Singh On Sun, 2008-05-11 at 12:00 +0200, 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. Logging module (Dick Moores) > 2. Re: Logging module (Martin Walsh) > 3. Re: Logging module (Dick Moores) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Sat, 10 May 2008 06:36:53 -0700 > From: Dick Moores > Subject: [Tutor] Logging module > To: Python Tutor List > Message-ID: <20080510133759.CAFC51E4011 at bag.python.org> > Content-Type: text/plain; charset="us-ascii"; format=flowed > > I don't understand how to use this. I've read > and > . > > I thought I'd try with a script that screws up: > > a = "qwerty" > b = a*b > > But how to use the logging module to log the report of the screw up? > Right now I don't care about the various levels. I just want to get > something into a log file. > > Hellmann suggest this: > > import logging > LOG_FILENAME = '/tmp/logging_example.out' > logging.basicConfig(filename=LOG_FILENAME, level=logging.DEBUG,) > logging.debug('This message should go to the log file') > > But where to put it? In my above script? > > Thanks, > > Dick Moores > > > > > ------------------------------ > > Message: 2 > Date: Sat, 10 May 2008 16:03:20 -0500 > From: Martin Walsh > Subject: Re: [Tutor] Logging module > To: "tutor at python.org" > Message-ID: <48260D98.70101 at groktech.org> > Content-Type: text/plain; charset=ISO-8859-1 > > Dick Moores wrote: > > But how to use the logging module to log the report of the screw up? > > Right now I don't care about the various levels. I just want to get > > something into a log file. > > > > Hellmann suggest this: > > > > import logging > > LOG_FILENAME = '/tmp/logging_example.out' > > logging.basicConfig(filename=LOG_FILENAME, level=logging.DEBUG,) > > logging.debug('This message should go to the log file') > > > > But where to put it? In my above script? > > I usually wrap up code in a try except and use the logging.exception > method, which is shorthand for logging.error(msg, exc_info=1), to > include the traceback. Something like this: > > import logging > LOG_FILENAME = '/tmp/logging_example.out' > logging.basicConfig(filename=LOG_FILENAME, level=logging.DEBUG) > > def main(): > a = "qwerty" > b = a * b > > try: > main() > except: > logging.exception('unknown') > raise > > HTH, > Marty > > > > ------------------------------ > > Message: 3 > Date: Sat, 10 May 2008 17:08:18 -0700 > From: Dick Moores > Subject: Re: [Tutor] Logging module > To: "tutor at python.org" > Message-ID: <20080511000830.A08D91E4013 at bag.python.org> > Content-Type: text/plain; charset="us-ascii"; format=flowed > > At 02:03 PM 5/10/2008, Martin Walsh wrote: > >Dick Moores wrote: > > > But how to use the logging module to log the report of the screw up? > > > Right now I don't care about the various levels. I just want to get > > > something into a log file. > > > > > > Hellmann suggest this: > > > > > > import logging > > > LOG_FILENAME = '/tmp/logging_example.out' > > > logging.basicConfig(filename=LOG_FILENAME, level=logging.DEBUG,) > > > logging.debug('This message should go to the log file') > > > > > > But where to put it? In my above script? > > > >I usually wrap up code in a try except and use the logging.exception > >method, which is shorthand for logging.error(msg, exc_info=1), to > >include the traceback. Something like this: > > > >import logging > >LOG_FILENAME = '/tmp/logging_example.out' > >logging.basicConfig(filename=LOG_FILENAME, level=logging.DEBUG) > > > >def main(): > > a = "qwerty" > > b = a * b > > > >try: > > main() > >except: > > logging.exception('unknown') > > raise > > Thank you! That gives me a good start. > > Dick > > > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > End of Tutor Digest, Vol 51, Issue 23 > ************************************* Please do not print this email unless it is absolutely necessary. The information contained in this electronic message and any attachments to this message are intended for the exclusive use of the addressee(s) and may contain proprietary, confidential or privileged information. If you are not the intended recipient, you should not disseminate, distribute or copy this e-mail. Please notify the sender immediately and destroy all copies of this message and any attachments. WARNING: Computer viruses can be transmitted via email. The recipient should check this email and any attachments for the presence of viruses. The company accepts no liability for any damage caused by any virus transmitted by this email. www.wipro.com From =?UTF-8?Q?=22=18=E0=A4=B6=E0=A4=82=E0=A4=A4=E0=A4=A8=E0=A5=82_?= Sun May 11 13:37:13 2008 From: =?UTF-8?Q?=22=18=E0=A4=B6=E0=A4=82=E0=A4=A4=E0=A4=A8=E0=A5=82_?= (=?UTF-8?Q?=22=18=E0=A4=B6=E0=A4=82=E0=A4=A4=E0=A4=A8=E0=A5=82_?=) Date: Sun, 11 May 2008 17:07:13 +0530 Subject: [Tutor] Tutor Digest, Vol 51, Issue 23 In-Reply-To: <1210505072.30416.16.camel@localhost.localdomain> References: <1210505072.30416.16.camel@localhost.localdomain> Message-ID: <0F25FF6A-1EC0-4AE1-B883-5E98243D6445@gmail.com> Hi Jatinder, Please turn off caps lock. On 11-May-08, at 4:54 PM, root wrote: > Hi , > I AM TRYING FOR A PYTHON PROGRAM THAT WILL CHECK WHETHER {- PHP AND > MYSQL -} ARE INSTALLED ON lINUX OR NOT AND IF THEY ARE NOT INSTALLED > THEN THE SCRIPT WILL TO INSTALL IT. > > for this I am doing > > import sys > import os > import commands > import sys > > > commands_hash = {} > commands_hash['php'] = {} > commands_hash['php']['title'] = "***********PHP**************" > commands_hash['php']['value'] = "rpm -qa *php*" > commands_hash['mysql'] = {} > commands_hash['mysql']['title'] = "***********MYSQL**************" > commands_hash['mysql']['value'] = "rpm -qa *mysql*" > > > this is checking whether PHP and MYSQL are installed but PLEASE TELL > ME > HOW TO ENHANCE IT SO AS THE INSTALL IT IF NOT INSTALLED ALREADY. Please check '-i' and '-U' options of rpm command. regards, shantanoo From jatinder.singh2 at wipro.com Sun May 11 13:51:26 2008 From: jatinder.singh2 at wipro.com (root) Date: Sun, 11 May 2008 17:21:26 +0530 Subject: [Tutor] checking and installing dependent softwares In-Reply-To: <0F25FF6A-1EC0-4AE1-B883-5E98243D6445@gmail.com> References: <1210505072.30416.16.camel@localhost.localdomain> <0F25FF6A-1EC0-4AE1-B883-5E98243D6445@gmail.com> Message-ID: <1210506686.30416.32.camel@localhost.localdomain> Hi , i am trying for a python script that is to check the php5 and mysql softwares.If the php5 and mysql softwares are not installed, the should provide a way to list down / install the software. please guide me to do this.- for this I am doing import sys import os import commands import sys commands_hash = {} commands_hash['php'] = {} commands_hash['php']['title'] = "*********PHP**************" commands_hash['php']['value'] = "rpm -qa *php*" commands_hash['mysql'] = {} commands_hash['mysql']['title'] ="********MYSQL**************" commands_hash['mysql']['value'] = "rpm -qa *mysql*" this is checking whether PHP and MYSQL are installed but how to enhance it so as to install them. Thanks Jatinder Singh On Sun, 2008-05-11 at 17:07 +0530, "????? ????? (Shantanoo Mahajan)" wrote: > Hi Jatinder, > Please turn off caps lock. > On 11-May-08, at 4:54 PM, root wrote: > > > Hi , > > I AM TRYING FOR A PYTHON PROGRAM THAT WILL CHECK WHETHER {- PHP AND > > MYSQL -} ARE INSTALLED ON lINUX OR NOT AND IF THEY ARE NOT INSTALLED > > THEN THE SCRIPT WILL TO INSTALL IT. > > > > for this I am doing > > > > import sys > > import os > > import commands > > import sys > > > > > > commands_hash = {} > > commands_hash['php'] = {} > > commands_hash['php']['title'] = "***********PHP**************" > > commands_hash['php']['value'] = "rpm -qa *php*" > > commands_hash['mysql'] = {} > > commands_hash['mysql']['title'] = "***********MYSQL**************" > > commands_hash['mysql']['value'] = "rpm -qa *mysql*" > > > > > > this is checking whether PHP and MYSQL are installed but PLEASE TELL > > ME > > HOW TO ENHANCE IT SO AS THE INSTALL IT IF NOT INSTALLED ALREADY. > > Please check '-i' and '-U' options of rpm command. > > regards, > shantanoo Please do not print this email unless it is absolutely necessary. The information contained in this electronic message and any attachments to this message are intended for the exclusive use of the addressee(s) and may contain proprietary, confidential or privileged information. If you are not the intended recipient, you should not disseminate, distribute or copy this e-mail. Please notify the sender immediately and destroy all copies of this message and any attachments. WARNING: Computer viruses can be transmitted via email. The recipient should check this email and any attachments for the presence of viruses. The company accepts no liability for any damage caused by any virus transmitted by this email. www.wipro.com From gloomdemon at gmail.com Mon May 12 14:51:27 2008 From: gloomdemon at gmail.com (Gloom Demon) Date: Mon, 12 May 2008 15:51:27 +0300 Subject: [Tutor] Using Python for accurate calculations Message-ID: <38446940805120551i19f323aexdac46847576e7f62@mail.gmail.com> Hello I am working on a function which is going to calculate correlation between two given sets of numbers. Example: x=[10.0, 10.8, 11.3, 10.0, 10.1, 11.1, 11.3, 10.2, 13.5, 12.3, 14.5, 11.0, 12.0, 11.8, 13.4, 11.4, 12.0, 15.6, 13.0, 12.1] y=[0.70, 0.73, 0.75, 0.70, 0.65, 0.65, 0.70, 0.61, 0.70, 0.63, 0.70, 0.65, 0.72, 0.69, 0.78, 0.70, 0.60, 0.85, 0.80, 0.75] However Python stores these numbers like this: >>> x [10.0, 10.800000000000001, 11.300000000000001, 10.0, 10.1, 11.1, 11.300000000000001, 10.199999999999999, 13.5, 12.300000000000001, 14.5, 11.0, 12.0, 11.800000000000001, 13.4, 11.4, 12.0, 15.6, 13.0, 12.1] >>> y [0.69999999999999996, 0.72999999999999998, 0.75, 0.69999999999999996, 0.65000000000000002, 0.65000000000000002, 0.69999999999999996, 0.60999999999999999, 0.69999999999999996, 0.63, 0.69999999999999996, 0.65000000000000002, 0.71999999999999997, 0.68999999999999995, 0.78000000000000003, 0.69999999999999996, 0.59999999999999998, 0.84999999999999998, 0.80000000000000004, 0.75] The extra digits added by Python are adding error probability to my calculations. Is there a way to overcome this? Thank You :-) -------------- next part -------------- An HTML attachment was scrubbed... URL: From dkuhlman at rexx.com Mon May 12 17:57:46 2008 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Mon, 12 May 2008 15:57:46 +0000 (UTC) Subject: [Tutor] Buffering in file.read() References: <20080508154029.GA7950@sandipb.net> <20080508174058.GA80995@cutter.rexx.com> <1c2a2c590805081107s162bdb7fqd10f46344270c9c2@mail.gmail.com> Message-ID: Kent Johnson tds.net> writes: > > Footnote 2.3 says, "Specifying a buffer size currently has no effect > on systems that don't have setvbuf(). The interface to specify the > buffer size is not done using a method that calls setvbuf(), because > that may dump core when called after any I/O has been performed, and > there's no reliable way to determine whether this is the case." > > So whether that works will depend on what OS the OP is using. And so, the next question is: Which OS's support setvbuf()? I'm on Ubuntu GNU/Linux. I do the following and I see: ~ [6] cd /usr/include/ /usr/include [7] grep setvbuf *.h stdio.h:/* The possibilities for the third argument to `setvbuf'. */ stdio.h:extern int setvbuf (FILE *__restrict __stream, char *__restrict __buf, So, some versions of Linux apparently have it. And, for MS Windows, you might look here: http://msdn.microsoft.com/en-us/library/86cebhfs(VS.80).aspx So, MS Windows seems to support it. - Dave From bgailer at gmail.com Mon May 12 18:46:21 2008 From: bgailer at gmail.com (bob gailer) Date: Mon, 12 May 2008 12:46:21 -0400 Subject: [Tutor] Using Python for accurate calculations In-Reply-To: <38446940805120551i19f323aexdac46847576e7f62@mail.gmail.com> References: <38446940805120551i19f323aexdac46847576e7f62@mail.gmail.com> Message-ID: <4828745D.9090104@gmail.com> Gloom Demon wrote: > Hello > > I am working on a function which is going to calculate correlation > between two given sets of numbers. > > Example: > x=[10.0, 10.8, 11.3, 10.0, 10.1, 11.1, 11.3, 10.2, 13.5, 12.3, 14.5, > 11.0, 12.0, 11.8, 13.4, 11.4, 12.0, 15.6, 13.0, 12.1] > y=[0.70, 0.73, 0.75, 0.70, 0.65, 0.65, 0.70, 0.61, 0.70, 0.63, 0.70, > 0.65, 0.72, 0.69, 0.78, 0.70, 0.60, 0.85, 0.80, 0.75] > > > However Python stores these numbers like this: > >>> x > [10.0, 10.800000000000001, 11.300000000000001, 10.0, 10.1, 11.1, > 11.300000000000001, 10.199999999999999, 13.5, 12.300000000000001, > 14.5, 11.0, 12.0, 11.800000000000001, 13.4, 11.4, 12.0, 15.6, 13.0, 12.1] > >>> y > [0.69999999999999996, 0.72999999999999998, 0.75, 0.69999999999999996, > 0.65000000000000002, 0.65000000000000002, 0.69999999999999996, > 0.60999999999999999, 0.69999999999999996, 0.63, 0.69999999999999996, > 0.65000000000000002, 0.71999999999999997, 0.68999999999999995, > 0.78000000000000003, 0.69999999999999996, 0.59999999999999998, > 0.84999999999999998, 0.80000000000000004, 0.75] > > The extra > digits added by Python are adding error probability to my calculations. Is there a way to overcome this? See http://docs.python.org/tut/node16.html. -- Bob Gailer 919-636-4239 Chapel Hill, NC From muchanek at gmail.com Mon May 12 18:51:12 2008 From: muchanek at gmail.com (kinuthia muchane) Date: Mon, 12 May 2008 19:51:12 +0300 Subject: [Tutor] Else Clause In A Loop In-Reply-To: References: Message-ID: <1210611072.5842.39.camel@www.kinuthia.com> Hi, I learnt that a loop can have an else clause. And that this clause executes when the loop TERMINATES. In a while loop when the condition becomes false, and in a for loop when a sequence is exhausted. When I write the following code it seems to work: for n in [1,2,3,4,5]: print 'we are in the loop',n else: print 'we are now EXITING the loop',n which results in: we are in the loop 1 we are in the loop 2 we are in the loop 3 we are in the loop 4 we are in the loop 5 we are now EXITING the loop 5 Or: n = 1 while n <= 5: print 'we are in the loop',n n += 1 else: print 'we are now EXITING the loop',n ...which gives: we are in the loop 1 we are in the loop 2 we are in the loop 3 we are in the loop 4 we are in the loop 5 we are now EXITING the loop 6 (it spills over here!) This has served to confuse me more. Would someone please kindly explain how all this fits into the code below which searches (and finds!) for prime numbers... def prime(): number = int(raw_input("Enter a number :")) for i in range(2,number): for j in range(2,i): if i%j == 0: break else: print "is a prime number", i prime() ...especially in the instance when number is 2 in the first for statement, for then we will have for j range(2,2)! Or what is going on?? Thanks, Kinuthia... From bgailer at gmail.com Mon May 12 19:16:24 2008 From: bgailer at gmail.com (bob gailer) Date: Mon, 12 May 2008 13:16:24 -0400 Subject: [Tutor] Using Python for accurate calculations In-Reply-To: <38446940805120551i19f323aexdac46847576e7f62@mail.gmail.com> References: <38446940805120551i19f323aexdac46847576e7f62@mail.gmail.com> Message-ID: <48287B68.3040609@gmail.com> Gloom Demon wrote: > Hello > > I am working on a function which is going to calculate correlation > between two given sets of numbers. > > Example: > x=[10.0, 10.8, 11.3, 10.0, 10.1, 11.1, 11.3, 10.2, 13.5, 12.3, 14.5, > 11.0, 12.0, 11.8, 13.4, 11.4, 12.0, 15.6, 13.0, 12.1] > y=[0.70, 0.73, 0.75, 0.70, 0.65, 0.65, 0.70, 0.61, 0.70, 0.63, 0.70, > 0.65, 0.72, 0.69, 0.78, 0.70, 0.60, 0.85, 0.80, 0.75] > > > However Python stores these numbers like this: > >>> x > [10.0, 10.800000000000001, 11.300000000000001, 10.0, 10.1, 11.1, > 11.300000000000001, 10.199999999999999, 13.5, 12.300000000000001, > 14.5, 11.0, 12.0, 11.800000000000001, 13.4, 11.4, 12.0, 15.6, 13.0, 12.1] > >>> y > [0.69999999999999996, 0.72999999999999998, 0.75, 0.69999999999999996, > 0.65000000000000002, 0.65000000000000002, 0.69999999999999996, > 0.60999999999999999, 0.69999999999999996, 0.63, 0.69999999999999996, > 0.65000000000000002, 0.71999999999999997, 0.68999999999999995, > 0.78000000000000003, 0.69999999999999996, 0.59999999999999998, > 0.84999999999999998, 0.80000000000000004, 0.75] > > The extra > digits added by Python are adding error probability to my calculations. Is there a way to overcome this? Also consider using the decimal module http://docs.python.org/lib/module-decimal.html -- Bob Gailer 919-636-4239 Chapel Hill, NC From john.ertl at navy.mil Mon May 12 20:00:59 2008 From: john.ertl at navy.mil (Ertl, John C CIV 63134) Date: Mon, 12 May 2008 11:00:59 -0700 Subject: [Tutor] how to return an error from a CGI Message-ID: <5061A819-D9DA-46C6-BAFC-1E01544002F4@mimectl> Classification: UNCLASSIFIED Caveat (s): FOUO All, I have been writing simple cgi scripts for a long time but have never worried about the error codes. Now I have been asked to return a specific error and I have no idea how to do this. I do not even know if I should be returning an HTTP or URL error. If I understand correctly, I am supposed to return something similar to say a 500 error. I think this is a HTTP error and I tried a few things but no luck. Thanks for the ideas. John Ertl Meteorologist FNMOC 7 Grace Hopper Ave. Monterey, CA 93943 (831) 656-5704 john.ertl at navy.mil Classification: UNCLASSIFIED Caveat (s): FOUO -------------- next part -------------- An HTML attachment was scrubbed... URL: From sruiz at canterburyschool.org Mon May 12 20:08:54 2008 From: sruiz at canterburyschool.org (=?ISO-8859-1?Q?=22Sim=F3n_A=2E_Ruiz=22?=) Date: Mon, 12 May 2008 14:08:54 -0400 Subject: [Tutor] Else Clause In A Loop In-Reply-To: <1210611072.5842.39.camel@www.kinuthia.com> References: <1210611072.5842.39.camel@www.kinuthia.com> Message-ID: <482887B6.7000302@canterburyschool.org> I'll try my hand at this: The outside for loop is looking through every number up to the variable "number". For each of those numbers, it checks to see if any number between 2 and i is divisible into i. If it finds anything, we know it's not a prime, and so it breaks out of that second loop without completing it, which means the else block isn't executed. If it can't find anything that i is divisible by, then that inside for loop finishes without breaking, we know that i is a prime number, and the "else" clause is executed. range(2,2) is is an empty list, so the loops ends uneventfully without doing anything and the else clause is executed. I'm not an expert, and this seems to me to be what's happening there. Sim?n kinuthia muchane wrote: > Hi, > > I learnt that a loop can have an else clause. And that this clause > executes when the loop TERMINATES. In a while loop when the condition > becomes false, and in a for loop when a sequence is exhausted. When I > write the following code it seems to work: > > for n in [1,2,3,4,5]: > print 'we are in the loop',n > else: > print 'we are now EXITING the loop',n > > which results in: > > we are in the loop 1 > we are in the loop 2 > we are in the loop 3 > we are in the loop 4 > we are in the loop 5 > we are now EXITING the loop 5 > > Or: > > n = 1 > while n <= 5: > print 'we are in the loop',n > n += 1 > else: > print 'we are now EXITING the loop',n > > ...which gives: > > we are in the loop 1 > we are in the loop 2 > we are in the loop 3 > we are in the loop 4 > we are in the loop 5 > we are now EXITING the loop 6 (it spills over here!) > > This has served to confuse me more. Would someone please kindly explain > how all this fits into the code below which searches (and finds!) for > prime numbers... > > > def prime(): > number = int(raw_input("Enter a number :")) > for i in range(2,number): > for j in range(2,i): > if i%j == 0: > break > else: > print "is a prime number", i > prime() > > ...especially in the instance when number is 2 in the first for > statement, for then we will have for j range(2,2)! Or what is going > on?? > > Thanks, > Kinuthia... > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From muchanek at gmail.com Mon May 12 22:11:42 2008 From: muchanek at gmail.com (kinuthia muchane) Date: Mon, 12 May 2008 23:11:42 +0300 Subject: [Tutor] Else Clause In A Loop In-Reply-To: <482887B6.7000302@canterburyschool.org> References: <1210611072.5842.39.camel@www.kinuthia.com> <482887B6.7000302@canterburyschool.org> Message-ID: <1210623102.5853.53.camel@www.kinuthia.com> On Mon, 2008-05-12 at 14:08 -0400, "Sim?n A. Ruiz" wrote: > I'll try my hand at this: > > The outside for loop is looking through every number up to the variable > "number". No quarrel here. > > For each of those numbers, it checks to see if any number between 2 and > i is divisible into i. If it finds anything, we know it's not a prime, > and so it breaks out of that second loop without completing it, which > means the else block isn't executed. This is where I am getting lost. When the variable 'number' is 3, it means that in that instance the inner 'for' statement will be 'for j in range(2,3)', hmmm which means that we will be dividing each element by 2 in the first 'for' statement and checking whether it is true , no? But 2%2 is zero, so, in my warped logic, the inner 'for' loop should break and the else clause will not execute! > > If it can't find anything that i is divisible by, then that inside for > loop finishes without breaking, we know that i is a prime number, and > the "else" clause is executed. This is where it gets even more interesting for me. Wont 'i' in one instance be 8, so at that particular moment there will be a 7 in the inner 'for' loop which will be divisible by one of our 'prime' numbers ie 7?! I know I am wrong but for some reason I cannot see the light! :-) > > range(2,2) is is an empty list, so the loops ends uneventfully without > doing anything and the else clause is executed. > > I'm not an expert, and this seems to me to be what's happening there. > > Sim?n All the same, thanks... > > kinuthia muchane wrote: > > Hi, > > > > I learnt that a loop can have an else clause. And that this clause > > executes when the loop TERMINATES. In a while loop when the condition > > becomes false, and in a for loop when a sequence is exhausted. When I > > write the following code it seems to work: > > > > for n in [1,2,3,4,5]: > > print 'we are in the loop',n > > else: > > print 'we are now EXITING the loop',n > > > > which results in: > > > > we are in the loop 1 > > we are in the loop 2 > > we are in the loop 3 > > we are in the loop 4 > > we are in the loop 5 > > we are now EXITING the loop 5 > > > > Or: > > > > n = 1 > > while n <= 5: > > print 'we are in the loop',n > > n += 1 > > else: > > print 'we are now EXITING the loop',n > > > > ...which gives: > > > > we are in the loop 1 > > we are in the loop 2 > > we are in the loop 3 > > we are in the loop 4 > > we are in the loop 5 > > we are now EXITING the loop 6 (it spills over here!) > > > > This has served to confuse me more. Would someone please kindly explain > > how all this fits into the code below which searches (and finds!) for > > prime numbers... > > > > > > def prime(): > > number = int(raw_input("Enter a number :")) > > for i in range(2,number): > > for j in range(2,i): > > if i%j == 0: > > break > > else: > > print i, "is a prime number" > > prime() > > > > ...especially in the instance when number is 2 in the first for > > statement, for then we will have for j in range(2,2)! Or what is going > > on?? > > > > Thanks, > > Kinuthia... > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor From dyoo at csmail.wpi.edu Mon May 12 21:49:50 2008 From: dyoo at csmail.wpi.edu (Danny Yoo) Date: Mon, 12 May 2008 15:49:50 -0400 (EDT) Subject: [Tutor] how to return an error from a CGI Message-ID: Hi John, It's been a long time! I believe you may be looking for the Status Code stuff that web servers use to tell browsers that something special is happening. See Section 3.3.1.3 in: http://www.unix.com.ua/orelly/linux/cgi/ch03_03.htm for an example done in Perl; the code should be easy to translate to Python. The idea is to print out a "Status" header at the beginning, so that the web server knows that it should send out a response with that particular status code type. The status codes are also specified as constants in: http://www.python.org/doc/lib/module-httplib.html near the bottom of that documentation. Wikipedia also catalogs the status codes that you can use: http://en.wikipedia.org/wiki/List_of_HTTP_status_codes From alan.gauld at btinternet.com Tue May 13 00:52:40 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 12 May 2008 23:52:40 +0100 Subject: [Tutor] Else Clause In A Loop References: <1210611072.5842.39.camel@www.kinuthia.com> Message-ID: "kinuthia muchane" wrote > This has served to confuse me more. Would someone please kindly > explain > how all this fits into the code below which searches (and finds!) > for > prime numbers... It doesn't find prime numbers very well. It only finds the primes *below* the one entered. So... > def prime(): > number = int(raw_input("Enter a number :")) > for i in range(2,number): > for j in range(2,i): > if i%j == 0: > break > else: > print "is a prime number", i > > prime() > > ...especially in the instance when number is 2 in the first for > statement, for then we will have for j range(2,2)! When number is 2 it doesnm't print anything. Which as you point out is as you would expect since the first range() will be empty. For number=3 the first range has one element so it enters the second loop with an empty list so goes straight to the else clause. I'm not a sure what you are confused about? The code is not very elegant or effective but it does what you have described in your experiments. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Tue May 13 01:01:36 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 13 May 2008 00:01:36 +0100 Subject: [Tutor] Using Python for accurate calculations References: <38446940805120551i19f323aexdac46847576e7f62@mail.gmail.com> Message-ID: "Gloom Demon" wrote > I am working on a function which is going to calculate correlation > between two given sets of numbers. > > Example: > x=[10.0, 10.8, 11.3, 10.0, 10.1, 11.1, 11.3, 10.2, 13.5, 12.3, 14.5, > 11.0, > y=[0.70, 0.73, 0.75, 0.70, 0.65, 0.65, 0.70, 0.61, 0.70, 0.63, 0.70, > 0.65, > > However Python stores these numbers like this: >>>> x > [10.0, 10.800000000000001, 11.300000000000001, 10.0, 10.1, 11.1, > The extra digits added by Python are adding error probability The digits aren't really added by Python they are just the nearest equivalent to your decimal numbers in binary. It will happen in any computer program that uses standard float types (even a pocket calculator!) This is one reason not to use floats for finance calculations! There are several ways around it. 1) Multiply up your numbers to integer values - in your case multiplying by 100 (or 1000) would work. - Easy with a list comprehension. 2) Use the decimal module for fixed decimals. (BCD if you like) 3) Set limits and work within +/- delta of your final values. Much depends on whether the errors are affecting the results or only the display of the results. The display can be fixed via formatted printing, the actual values will need options 1-3. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From afinn at alumni.purdue.edu Tue May 13 02:03:44 2008 From: afinn at alumni.purdue.edu (Downbound) Date: Mon, 12 May 2008 17:03:44 -0700 (PDT) Subject: [Tutor] pyUSB linux + unknown device Message-ID: <17198596.post@talk.nabble.com> I'm trying to make an interface between my weather station and my linux server however the only output the weather station has is USB. Further, there are only windows drivers for this Honeywell weather station. Thus, I'm trying to use Python and pyUSB to interface. I THINK i've gotten pretty close. It appears the device is identifying as an Unknown Product by Tenx Technology, Inc. on USB 1.10. I can gleen all the information about the device that you can get from 'configurations' but I'm stuck on the next step. . Reading. Now, I'm betting the device simply is dumping packets just like the serial device would on all other weather stations I've encountered. However, I'm not SURE. I've pasted my code below but I'm getting this error: "usb.USBError: error submitting URB: Device or resource busy" Anyone have any thoughts or suggestions on where I should go from here. . This is my first shot at PyUSB if you hadn't noticed. import re, sys, usb, string class DeviceDescriptor: def __init__(self): 1 def getDevice(self): buses = usb.busses() for bus in buses: for device in bus.devices: if hex(device.idVendor)[2:] == '1130': print 'Device Found: %s:%s'%(hex(device.idVendor),hex(device.idProduct)) return device print 'FAILED TO FIND THE WEATHER STATION!' return None class main: def __init__(self): self.device_descriptor = DeviceDescriptor() self.device = self.device_descriptor.getDevice() self.handle = self.device.open() def close(self): self.handle.releaseInterface() def getDataPacket(self, bytesToGet): #self.handle.bulkWrite(1,"v"+(7)*"Z",1000) return self.handle.interruptRead(0x81,3,1000) if __name__ == "__main__": data = main() print data.getDataPacket(10) -- View this message in context: http://www.nabble.com/pyUSB-linux-%2B-unknown-device-tp17198596p17198596.html Sent from the Python - tutor mailing list archive at Nabble.com. From twomol at hotmail.com Tue May 13 03:37:32 2008 From: twomol at hotmail.com (tuyun) Date: Tue, 13 May 2008 01:37:32 +0000 Subject: [Tutor] How to make a python binding for a c library? Message-ID: Hi I have a library written in C, I want to make a python binding for it. But I dont know how to get started. Is there any guide or document? Is "Python/C API Reference Manual" the right doc I need to study first? Thanks in advance Twomol _________________________________________________________________ ???MSN??????????????????? http://mobile.msn.com.cn/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From rdm at rcblue.com Tue May 13 08:22:00 2008 From: rdm at rcblue.com (Dick Moores) Date: Mon, 12 May 2008 23:22:00 -0700 Subject: [Tutor] a replace function using re module Message-ID: <20080513062415.A29F21E4002@bag.python.org> An HTML attachment was scrubbed... URL: From metolone+gmane at gmail.com Tue May 13 08:31:56 2008 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Mon, 12 May 2008 23:31:56 -0700 Subject: [Tutor] How to make a python binding for a c library? References: Message-ID: "tuyun" wrote in message news:BAY108-W54DF95D77BED99541362E2CDCF0 at phx.gbl... > Hi > I have a library written in C, I want to make a python binding for it. > But I dont know how to get started. > Is there any guide or document? > Is "Python/C API Reference Manual" the right doc I need to study first? Check out the ctypes library. It comes with Python 2.5, but can be installed for older versions. Here's an example that calls the Win32 function Beep() from kernel32.dll: import ctypes ctypes.windll.kernel32.Beep(440,1000) This is a simplistic example that works for simple DLL functions that take integers and return integers. If your APIs deal with pointers and read/write buffers it is somewhat more complicated, but still easier to write your bindings in Python than using the Python C APIs. -Mark From jjhartley at gmail.com Tue May 13 13:06:28 2008 From: jjhartley at gmail.com (James Hartley) Date: Tue, 13 May 2008 04:06:28 -0700 Subject: [Tutor] sorting dictionary keys? Message-ID: I suspect this is a brain-dead question... Given the following code, output is as expected: $ cat test.py d = { 'a' : 1, 'd' : 2, 'b' : 3, 'c' : 0 } for i in d.keys(): print "%s\t%s" % (i, d[i]) $ python test.py a 1 c 0 b 3 d 2 $ But if the keys are sorted, I get an error: $ cat test1.py d = { 'a' : 1, 'd' : 2, 'b' : 3, 'c' : 0 } for i in d.keys().sort(): print "%s\t%s" % (i, d[i]) $ python test1.py Traceback (most recent call last): File "test.py", line 3, in for i in d.keys().sort(): TypeError: 'NoneType' object is not iterable $ What is the correct manner to iterate through sorted dictionary keys? Thanks. Jim From k.mugund at yahoo.com Tue May 13 13:32:59 2008 From: k.mugund at yahoo.com (Mugund K) Date: Tue, 13 May 2008 04:32:59 -0700 (PDT) Subject: [Tutor] sorting dictionary keys? In-Reply-To: Message-ID: <387452.96929.qm@web45713.mail.sp1.yahoo.com> An HTML attachment was scrubbed... URL: From kent37 at tds.net Tue May 13 13:40:30 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 13 May 2008 07:40:30 -0400 Subject: [Tutor] sorting dictionary keys? In-Reply-To: References: Message-ID: <1c2a2c590805130440vfbc9e20x698045ee061ac7f7@mail.gmail.com> On Tue, May 13, 2008 at 7:06 AM, James Hartley wrote: > But if the keys are sorted, I get an error: > $ cat test1.py > d = { 'a' : 1, 'd' : 2, 'b' : 3, 'c' : 0 } > > for i in d.keys().sort(): > print "%s\t%s" % (i, d[i]) > $ python test1.py > Traceback (most recent call last): > File "test.py", line 3, in > for i in d.keys().sort(): for i in sorted(d.keys()): or simply for i in sorted(d): since iterating a dict gives its keys. The problem is that the inplace sort() returns None. d.keys() is a (new) list containing the keys d.keys().sort() gets the list of keys and sorts it, but the value of the expression is None, so you are essentially writing for i in None: which gives the TypeError you see. The builtin function sorted() takes any iterable as an argument and *returns* a sorted sequence so you can use it in an expression. Kent From norman at khine.net Tue May 13 13:58:11 2008 From: norman at khine.net (Norman Khine) Date: Tue, 13 May 2008 13:58:11 +0200 Subject: [Tutor] sorting dictionary keys? In-Reply-To: References: Message-ID: <48298253.5070901@khine.net> how about this >>> d = { 'a' : 1, 'd' : 2, 'b' : 3, 'c' : 0 } >>> for i in sorted(set(d)): ... print "%s\t%s" % (i, d[i]) ... a 1 b 3 c 0 d 2 James Hartley wrote: > I suspect this is a brain-dead question... > > Given the following code, output is as expected: > > $ cat test.py > d = { 'a' : 1, 'd' : 2, 'b' : 3, 'c' : 0 } > > for i in d.keys(): > print "%s\t%s" % (i, d[i]) > $ python test.py > a 1 > c 0 > b 3 > d 2 > $ > > But if the keys are sorted, I get an error: > $ cat test1.py > d = { 'a' : 1, 'd' : 2, 'b' : 3, 'c' : 0 } > > for i in d.keys().sort(): > print "%s\t%s" % (i, d[i]) > $ python test1.py > Traceback (most recent call last): > File "test.py", line 3, in > for i in d.keys().sort(): > TypeError: 'NoneType' object is not iterable > $ > > What is the correct manner to iterate through sorted dictionary keys? > > Thanks. > > Jim > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Tue May 13 14:25:12 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 13 May 2008 08:25:12 -0400 Subject: [Tutor] sorting dictionary keys? In-Reply-To: <387452.96929.qm@web45713.mail.sp1.yahoo.com> References: <387452.96929.qm@web45713.mail.sp1.yahoo.com> Message-ID: <1c2a2c590805130525g2faf7d2cv1c5558c7574e5e4a@mail.gmail.com> On Tue, May 13, 2008 at 7:32 AM, Mugund K wrote: > > A quick but ugly [brain-dead :-) ]fix would be sorting keys seperately, > >>> temp = d.keys() > >>> temp.sort() > >>> for i in temp: Not so ugly; before sorted() was introduced (Python 2.4) that would be the way to do it. Kent From kent37 at tds.net Tue May 13 14:28:04 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 13 May 2008 08:28:04 -0400 Subject: [Tutor] sorting dictionary keys? In-Reply-To: <48298253.5070901@khine.net> References: <48298253.5070901@khine.net> Message-ID: <1c2a2c590805130528m56dac63sc3b0b13e2e5f75c0@mail.gmail.com> On Tue, May 13, 2008 at 7:58 AM, Norman Khine wrote: > how about this > > > >>> d = { 'a' : 1, 'd' : 2, 'b' : 3, 'c' : 0 } > >>> for i in sorted(set(d)): > ... print "%s\t%s" % (i, d[i]) The set() is not needed. Also to iterate over key, value pairs in order by key you can use this: for k, v in sorted(d.items()): print '%s\t%s' (k, v) Kent From sruiz at canterburyschool.org Tue May 13 17:09:20 2008 From: sruiz at canterburyschool.org (=?UTF-8?B?IlNpbcOzbiBBLiBSdWl6Ig==?=) Date: Tue, 13 May 2008 11:09:20 -0400 Subject: [Tutor] Else Clause In A Loop In-Reply-To: <1210623102.5853.53.camel@www.kinuthia.com> References: <1210611072.5842.39.camel@www.kinuthia.com> <482887B6.7000302@canterburyschool.org> <1210623102.5853.53.camel@www.kinuthia.com> Message-ID: <4829AF20.9080308@canterburyschool.org> kinuthia muchane wrote: > On Mon, 2008-05-12 at 14:08 -0400, "Sim?n A. Ruiz" wrote: >> For each of those numbers, it checks to see if any number between 2 and >> i is divisible into i. If it finds anything, we know it's not a prime, >> and so it breaks out of that second loop without completing it, which >> means the else block isn't executed. > > This is where I am getting lost. When the variable 'number' is 3, it > means that in that instance the inner 'for' statement will be 'for j in > range(2,3)', hmmm which means that we will be dividing each element by 2 > in the first 'for' statement and checking whether it is true , no? But > 2%2 is zero, so, in my warped logic, the inner 'for' loop should break > and the else clause will not execute! When i is 3, then we'll only check (2 % 3 == 0) which is False, so the loop ends unbroken and runs the else clause letting us know that 3 is indeed a prime number. Never will we check (2 % 2 == 0). When i is 2, range(2,2) returns [], so the loop ends unbroken (without starting) and runs the else clause. >> If it can't find anything that i is divisible by, then that inside for >> loop finishes without breaking, we know that i is a prime number, and >> the "else" clause is executed. > > This is where it gets even more interesting for me. Wont 'i' in one > instance be 8, so at that particular moment there will be a 7 in the > inner 'for' loop which will be divisible by one of our 'prime' numbers > ie 7?! I know I am wrong but for some reason I cannot see the light! :-) Don't worry about it, you're doing fine. Remember, when you're most confused you're most ready to learn something. :-D Ok, so when i is 8, we check: is (8 % 2 == 0)? True. Break! So, we've broken out of the inner loop and thus ignore the else statement. We know 8 is not a prime number. Now, for a prime. When i is 7, we check: is (7 % 2 == 0)? False. Next! is (7 % 3 == 0)? False. Next! is (7 % 4 == 0)? False. Next! is (7 % 5 == 0)? False. Next! is (7 % 6 == 0)? False. Next! So, we've finished the inner loop without breaking, so we now run the else clause: is a prime number 7 Does this help at all? Hope this finds you all having a beautiful day! Sim?n From andreas at kostyrka.org Tue May 13 19:19:31 2008 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Tue, 13 May 2008 19:19:31 +0200 Subject: [Tutor] How to make a python binding for a c library? In-Reply-To: References: Message-ID: <1210699172.7472.8.camel@andi-lap.lan> Am Montag, den 12.05.2008, 23:31 -0700 schrieb Mark Tolonen: > "tuyun" wrote in message > news:BAY108-W54DF95D77BED99541362E2CDCF0 at phx.gbl... > > Hi > > I have a library written in C, I want to make a python binding for it. > > But I dont know how to get started. > > Is there any guide or document? > > Is "Python/C API Reference Manual" the right doc I need to study first? > > Check out the ctypes library. It comes with Python 2.5, but can be > installed for older versions. > > Here's an example that calls the Win32 function Beep() from kernel32.dll: > > import ctypes > ctypes.windll.kernel32.Beep(440,1000) > > This is a simplistic example that works for simple DLL functions that take > integers and return integers. If your APIs deal with pointers and > read/write buffers it is somewhat more complicated, but still easier to > write your bindings in Python than using the Python C APIs. Alternativly you might consider using something like cython. Andreas > > -Mark > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil URL: From alan.gauld at btinternet.com Tue May 13 19:56:26 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 13 May 2008 18:56:26 +0100 Subject: [Tutor] How to make a python binding for a c library? References: Message-ID: "tuyun" wrote > I have a library written in C, I want to > make a python binding for it. If on Windows and a DLL then ctypes is probably the best bet. If a simple object file on *nix then you might try SWIG, the basic tutorial there is quite good. There are lots of HowTo articles on this topic however so you should find plenty explanation for doing it from the ground up. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From mlangford.cs03 at gtalumni.org Tue May 13 21:59:34 2008 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Tue, 13 May 2008 15:59:34 -0400 Subject: [Tutor] pyUSB linux + unknown device In-Reply-To: <17198596.post@talk.nabble.com> References: <17198596.post@talk.nabble.com> Message-ID: <82b4f5810805131259x794c998cn23bcf8dc8becb0cc@mail.gmail.com> This should get you started. You're need to go to figure out your data format, and you're going to need to go through the data, most likely with a snooper. http://www.nabble.com/Using-pyusb-td16164343.html --Michael On Mon, May 12, 2008 at 8:03 PM, Downbound wrote: > > I'm trying to make an interface between my weather station and my linux > server however the only output the weather station has is USB. Further, > there are only windows drivers for this Honeywell weather station. Thus, > I'm > trying to use Python and pyUSB to interface. I THINK i've gotten pretty > close. It appears the device is identifying as an Unknown Product by Tenx > Technology, Inc. on USB 1.10. I can gleen all the information about the > device that you can get from 'configurations' but I'm stuck on the next > step. . Reading. Now, I'm betting the device simply is dumping packets > just > like the serial device would on all other weather stations I've > encountered. > However, I'm not SURE. I've pasted my code below but I'm getting this > error: > "usb.USBError: error submitting URB: Device or resource busy" > > Anyone have any thoughts or suggestions on where I should go from here. . > This is my first shot at PyUSB if you hadn't noticed. > > import re, sys, usb, string > > class DeviceDescriptor: > def __init__(self): > 1 > > def getDevice(self): > buses = usb.busses() > for bus in buses: > for device in bus.devices: > if hex(device.idVendor)[2:] == '1130': > print 'Device Found: > %s:%s'%(hex(device.idVendor),hex(device.idProduct)) > return device > print 'FAILED TO FIND THE WEATHER STATION!' > return None > > class main: > > def __init__(self): > self.device_descriptor = DeviceDescriptor() > self.device = self.device_descriptor.getDevice() > self.handle = self.device.open() > > def close(self): > self.handle.releaseInterface() > > def getDataPacket(self, bytesToGet): > #self.handle.bulkWrite(1,"v"+(7)*"Z",1000) > return self.handle.interruptRead(0x81,3,1000) > > > if __name__ == "__main__": > data = main() > print data.getDataPacket(10) > -- > View this message in context: > http://www.nabble.com/pyUSB-linux-%2B-unknown-device-tp17198596p17198596.html > Sent from the Python - tutor mailing list archive at Nabble.com. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Michael Langford Phone: 404-386-0495 Consulting: http://www.RowdyLabs.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From kdsudac at yahoo.com Wed May 14 02:31:35 2008 From: kdsudac at yahoo.com (Keith Suda-Cederquist) Date: Tue, 13 May 2008 17:31:35 -0700 (PDT) Subject: [Tutor] Memory Leak? In-Reply-To: Message-ID: <20039.77936.qm@web54302.mail.re2.yahoo.com> Sorry for not responding sooner. I took the advice to add these two lines to my code: import matplotlib matplotlib.use('Agg') -Keith Jeff Younker wrote: > I followed the advice on this page: http://mail.python.org/pipermail/python-list/2006-December/417208.html > and the problem is now gone. There are two pieces of advice on that page. Which did you follow? - Jeff Younker - jeff at drinktomi.com - -------------- next part -------------- An HTML attachment was scrubbed... URL: From Nick.Treloar at education.nsw.gov.au Wed May 14 02:34:48 2008 From: Nick.Treloar at education.nsw.gov.au (Nick.Treloar at education.nsw.gov.au) Date: Wed, 14 May 2008 10:34:48 +1000 Subject: [Tutor] (no subject) Message-ID: <38336A03AE7EBF4C8ED36DBB759AF96C04CE2A77CA@EXCHMB-EVSB1.DETISP.LOCAL> hey guys i was wondering if there was a way for me to destroy a window that is playing a movie,. once the movie is finished ________________________________ This message is intended for the addressee named and may contain privileged information or confidential information or both. If you are not the intended recipient please delete it and notify the sender. -------------- next part -------------- An HTML attachment was scrubbed... URL: From chester_lab at fltg.net Wed May 14 02:10:57 2008 From: chester_lab at fltg.net (FT) Date: Tue, 13 May 2008 20:10:57 -0400 Subject: [Tutor] Sorting Dictionary Keys Message-ID: <003d01c8b557$01496ab0$0201a8c0@brucetower> Jim, OK, use the example below for sorting dictionary keys and placing them in a list. Note that an error will happen if the format on the print statement does not correspond to the type of sort. #THIS SORTS A DICTIONARY BY USING SET THEORY AND DIC ITEMS! import random dic = {} print "Randomizing!" for i in range(20): dic[ random.randrange(100)] = random.randrange(100, 1000) print "Dic:" j=0 list=[] for k,i in dic.items(): print "K=%d I=%d" % (k,i) list.append("K=%d I=%d" % (k,i)) j+=1 j=0 print "Sorted Dic By Set:" print "Num: Old, Sorted" for k in sorted(set(dic)): print "(%d) %s | K=%d I=%d" % (j+1, list[j], k,dic[k]) j+=1 j=0 print "Sorted Dic By Items:" print "Num: Old, Sorted" for k,i in sorted(dic.items()): print "(%d) %s | K=%d I=%d" % (j+1, list[j], k,i) j+=1 --- On Tue, 5/13/08, James Hartley wrote: From: James Hartley Subject: [Tutor] sorting dictionary keys? To: tutor at python.org Date: Tuesday, May 13, 2008, 11:06 AM I suspect this is a brain-dead question... Given the following code, output is as expected: $ cat test.py d = { 'a' : 1, 'd' : 2, 'b' : 3, 'c' : 0 } for i in d.keys(): print "%s\t%s" % (i, d[i]) $ python test.py a 1 c 0 b 3 d 2 $ But if the keys are sorted, I get an error: $ cat test1.py d = { 'a' : 1, 'd' : 2, 'b' : 3, 'c' : 0 } for i in d.keys().sort(): print "%s\t%s" % (i, d[i]) $ python test1.py Traceback (most recent call last): File "test.py", line 3, in for i in d.keys().sort(): TypeError: 'NoneType' object is not iterable $ What is the correct manner to iterate through sorted dictionary keys? Thanks. Jim From kent37 at tds.net Wed May 14 02:44:58 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 13 May 2008 20:44:58 -0400 Subject: [Tutor] (no subject) In-Reply-To: <38336A03AE7EBF4C8ED36DBB759AF96C04CE2A77CA@EXCHMB-EVSB1.DETISP.LOCAL> References: <38336A03AE7EBF4C8ED36DBB759AF96C04CE2A77CA@EXCHMB-EVSB1.DETISP.LOCAL> Message-ID: <1c2a2c590805131744i17fe183av932adca7a5fe0cfb@mail.gmail.com> On Tue, May 13, 2008 at 8:34 PM, wrote: > > > hey guys i was wondering if there was a way for me to destroy a window that > is playing a movie,. once the movie is finished Perhaps. Would you care to give some more details? Perhaps some code? Kent From Nick.Treloar at education.nsw.gov.au Wed May 14 03:07:58 2008 From: Nick.Treloar at education.nsw.gov.au (Nick.Treloar at education.nsw.gov.au) Date: Wed, 14 May 2008 11:07:58 +1000 Subject: [Tutor] destroying a window once a movie has stoped playing Message-ID: <38336A03AE7EBF4C8ED36DBB759AF96C04CE2A77CB@EXCHMB-EVSB1.DETISP.LOCAL> def movieu(self): mov_name = "video.mpg" pygame.mixer.quit() screen = pygame.display.set_mode((320, 240)) video = pygame.movie.Movie(mov_name) screen = pygame.display.set_mode(video.get_size()) video.play() while video.get_busy(): for event in pygame.event.get(): if event.type == pygame.QUIT: break this is the peice of code i am using to run a movie in my scissors paper rock game so when rock beats scissors a movie will play. i can get the movie to play but i would like to no if i can make the window destroy once the movie has stoped ________________________________ This message is intended for the addressee named and may contain privileged information or confidential information or both. If you are not the intended recipient please delete it and notify the sender. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed May 14 06:26:12 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 14 May 2008 05:26:12 +0100 Subject: [Tutor] (no subject) References: <38336A03AE7EBF4C8ED36DBB759AF96C04CE2A77CA@EXCHMB-EVSB1.DETISP.LOCAL> <1c2a2c590805131744i17fe183av932adca7a5fe0cfb@mail.gmail.com> Message-ID: "Kent Johnson" wrote in message news:1c2a2c590805131744i17fe183av932adca7a5fe0cfb at mail.gmail.com... > On Tue, May 13, 2008 at 8:34 PM, > wrote: >> >> >> hey guys i was wondering if there was a way for me to destroy a >> window that >> is playing a movie,. once the movie is finished > > Perhaps. Would you care to give some more details? Perhaps some > code? And the OS and application used to play the movie would help too! Alan G. From muchanek at gmail.com Wed May 14 08:47:18 2008 From: muchanek at gmail.com (kinuthia muchane) Date: Wed, 14 May 2008 09:47:18 +0300 Subject: [Tutor] Else Clause In A Loop In-Reply-To: <4829AF20.9080308@canterburyschool.org> References: <1210611072.5842.39.camel@www.kinuthia.com> <482887B6.7000302@canterburyschool.org> <1210623102.5853.53.camel@www.kinuthia.com> <4829AF20.9080308@canterburyschool.org> Message-ID: <1210747638.5801.11.camel@www.kinuthia.com> On Tue, 2008-05-13 at 11:09 -0400, "Sim?n A. Ruiz" wrote: > kinuthia muchane wrote: > > On Mon, 2008-05-12 at 14:08 -0400, "Sim?n A. Ruiz" wrote: > >> For each of those numbers, it checks to see if any number between 2 and > >> i is divisible into i. If it finds anything, we know it's not a prime, > >> and so it breaks out of that second loop without completing it, which > >> means the else block isn't executed. > > > > This is where I am getting lost. When the variable 'number' is 3, it > > means that in that instance the inner 'for' statement will be 'for j in > > range(2,3)', hmmm which means that we will be dividing each element by 2 > > in the first 'for' statement and checking whether it is true , no? But > > 2%2 is zero, so, in my warped logic, the inner 'for' loop should break > > and the else clause will not execute! > > When i is 3, then we'll only check (2 % 3 == 0) which is False, so the > loop ends unbroken and runs the else clause letting us know that 3 is > indeed a prime number. Shouldn't we be checking for (3%2 == 0) instead of (2%3 == 0)? > > Never will we check (2 % 2 == 0). > > When i is 2, range(2,2) returns [], so the loop ends unbroken (without > starting) and runs the else clause. > > >> If it can't find anything that i is divisible by, then that inside for > >> loop finishes without breaking, we know that i is a prime number, and > >> the "else" clause is executed. > > > > This is where it gets even more interesting for me. Wont 'i' in one > > instance be 8, so at that particular moment there will be a 7 in the > > inner 'for' loop which will be divisible by one of our 'prime' numbers > > ie 7?! I know I am wrong but for some reason I cannot see the light! :-) > > Don't worry about it, you're doing fine. > > Remember, when you're most confused you're most ready to learn > something. :-D > > Ok, so when i is 8, we check: > is (8 % 2 == 0)? True. Break! > So, we've broken out of the inner loop and thus ignore the else > statement. We know 8 is not a prime number. > > Now, for a prime. When i is 7, we check: > is (7 % 2 == 0)? False. Next! > is (7 % 3 == 0)? False. Next! > is (7 % 4 == 0)? False. Next! > is (7 % 5 == 0)? False. Next! > is (7 % 6 == 0)? False. Next! > So, we've finished the inner loop without breaking, so we now run the > else clause: > is a prime number 7 > > > Does this help at all? It was crystal clear! Thanks Simon (I didn't know how to put the accent mark over the 'o', though), the confusion is gone. ;) > > Hope this finds you all having a beautiful day! > > Sim?n From mobiledreamers at gmail.com Wed May 14 09:45:33 2008 From: mobiledreamers at gmail.com (Mark) Date: Wed, 14 May 2008 00:45:33 -0700 Subject: [Tutor] Help with class.self variables Message-ID: <482A989D.8090108@gmail.com> An HTML attachment was scrubbed... URL: From jdmccla at regence.com Wed May 14 13:09:41 2008 From: jdmccla at regence.com (James D Mcclatchey) Date: Wed, 14 May 2008 04:09:41 -0700 Subject: [Tutor] James D Mcclatchey is out of the office. Message-ID: I will be out of the office starting 05/14/2008 and will not return until 05/19/2008. I will respond to your message when I return. ***IMPORTANT NOTICE: This communication, including any attachment, contains information that may be confidential or privileged, and is intended solely for the entity or individual to whom it is addressed. If you are not the intended recipient, you should delete this message and are hereby notified that any disclosure, copying, or distribution of this message is strictly prohibited. Nothing in this email, including any attachment, is intended to be a legally binding signature.*** From kent37 at tds.net Wed May 14 14:16:33 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 14 May 2008 08:16:33 -0400 Subject: [Tutor] Help with class.self variables In-Reply-To: <482A989D.8090108@gmail.com> References: <482A989D.8090108@gmail.com> Message-ID: <1c2a2c590805140516l39e974fbpe8a45b7cc1dd3adc@mail.gmail.com> On Wed, May 14, 2008 at 3:45 AM, Mark wrote: > i want to set the keys of the user row as the keys of User self > but i m not sure how to do it > > for i in self._user.keys(): > self[i]=self._user[i] Should be setattr(self, i, self._user[i]) > You can do something like > > self.update(_user) Should be self.__dict__.update(self._user) You should probably consider an existing object-relation mapper such as SQLAlchemy, SQLObject or Django ORM rather than rolling your own. Kent From bhaaluu at gmail.com Wed May 14 14:23:27 2008 From: bhaaluu at gmail.com (bhaaluu) Date: Wed, 14 May 2008 08:23:27 -0400 Subject: [Tutor] destroying a window once a movie has stoped playing In-Reply-To: <38336A03AE7EBF4C8ED36DBB759AF96C04CE2A77CB@EXCHMB-EVSB1.DETISP.LOCAL> References: <38336A03AE7EBF4C8ED36DBB759AF96C04CE2A77CB@EXCHMB-EVSB1.DETISP.LOCAL> Message-ID: On Tue, May 13, 2008 at 9:07 PM, wrote: > > > def movieu(self): > mov_name = "video.mpg" > pygame.mixer.quit() > screen = pygame.display.set_mode((320, 240)) > video = pygame.movie.Movie(mov_name) > screen = pygame.display.set_mode(video.get_size()) > video.play() > while video.get_busy(): > for event in pygame.event.get(): > if event.type == pygame.QUIT: > break > > this is the peice of code i am using to run a movie in my scissors paper > rock game so when rock beats scissors a movie will play. i can get the movie > to play but i would like to no if i can make the window destroy once the > movie has stoped > ________________________________ > This message is intended for the addressee named and may contain privileged > information or confidential information or both. If you are not the intended > recipient please delete it and notify the sender. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Hey Nick, You may have better luck asking pygame-specific questions on the pygame mailing list? Pygame maintains an active mailing list. You can email the list at pygame-users at seul.org To get on or off the mailing list, send an email message to majordomo at seul.org with a simple command in the body. Some examples; (note, no subject is needed). If subscribing or unsubscribing, there's no need to enter any extra email address information. Just use the commands like they are below, the email address you mail from is the address mail will go to (or stop going to). (from: http://pygame.org/wiki/info) I think the Tutor list mainly helps with "business type" scripting such as accessing a database, opening, writing, reading, closing files, working with lists, dictionaries, tuples, and so forth? The pygame list is specific to pygame, and the gurus there can answer any pygame question you ask them! Happy Programming! -- b h a a l u u at g m a i l dot c o m Kid on Bus: What are you gonna do today, Napoleon? Napoleon Dynamite: Whatever I feel like I wanna do. Gosh! From sruiz at canterburyschool.org Wed May 14 16:11:42 2008 From: sruiz at canterburyschool.org (=?UTF-8?B?IlNpbcOzbiBBLiBSdWl6Ig==?=) Date: Wed, 14 May 2008 10:11:42 -0400 Subject: [Tutor] Else Clause In A Loop In-Reply-To: <1210747638.5801.11.camel@www.kinuthia.com> References: <1210611072.5842.39.camel@www.kinuthia.com> <482887B6.7000302@canterburyschool.org> <1210623102.5853.53.camel@www.kinuthia.com> <4829AF20.9080308@canterburyschool.org> <1210747638.5801.11.camel@www.kinuthia.com> Message-ID: <482AF31E.1090103@canterburyschool.org> kinuthia muchane wrote: > On Tue, 2008-05-13 at 11:09 -0400, "Sim?n A. Ruiz" wrote: >> When i is 3, then we'll only check (2 % 3 == 0) which is False, so the >> loop ends unbroken and runs the else clause letting us know that 3 is >> indeed a prime number. > > Shouldn't we be checking for (3%2 == 0) instead of (2%3 == 0)? Absolutely right. My mistake. >> Does this help at all? > > It was crystal clear! Thanks Simon (I didn't know how to put the accent > mark over the 'o', though), the confusion is gone. ;) Awesome. Glad I could be of help. :-D Sim?n From jjcrump at myuw.net Wed May 14 21:02:20 2008 From: jjcrump at myuw.net (Jon Crump) Date: Wed, 14 May 2008 12:02:20 -0700 (PDT) Subject: [Tutor] basic lists and loops question Message-ID: Something basic about lists and loops that I'm not getting here. I've got a long list of dictionaries that looks like this: lst = [{'placename': u'Stow, Lincolnshire', 'long-name': u'Stow, Lincolnshire.', 'end': datetime.date(1216, 9, 28), 'start': datetime.date(1216, 9, 26)}, {'placename': u'Lincoln, Lincolnshire', 'long-name': u'Lincoln, Lincolnshire.', 'end': datetime.date(1216, 9, 30), 'start': datetime.date(1216, 9, 28)}, {'placename': u'Lincoln, Lincolnshire', 'long-name': u'Lincoln, Lincolnshire.', 'end': datetime.date(1216, 10, 2), 'start': datetime.date(1216, 10, 1)}, {'placename': u'Grimsby, Lincolnshire', 'long-name': u'Grimsby, Lincolnshire.', 'end': datetime.date(1216, 10, 4), 'start': datetime.date(1216, 10, 3)}, {'placename': u'Louth, Lincolnshire', 'long-name': u'Louth, Lincolnshire.', 'end': datetime.date(1216, 10, 4), 'start': datetime.date(1216, 10, 4)} ] I have a function that searches through them to find pairs of dictionaries that satisfy certain criteria. When the nested loops find such a pair, I need to merge them. So far so good. This works: def events(data): evts = [] for x in lst: for y in lst: if (x['placename'] == y['placename']) and (x['end'].month + 1 == y['start'].month) and (y['start'] - x['end'] == datetime.timedelta(1)): evts.append({'placename': x['placename'], 'long-name': x['long-name'], 'start': x['start'], 'end': y['end']}) evts.append(x) return evts for x in events(lst): print x But then I need to delete the two original dictionaries that I merged. If I do del x, I get an error "local variable 'x' referenced before assignment" I've also tried decorating the processed dictionaries in the if loop thus: x['processed'] = True y['processed'] = True Then when I call events() I get back the merged dict and the decorated dicts: {'placename': u'Lincoln, Lincolnshire', 'end': datetime.date(1216, 10, 2), 'start': datetime.date(1216, 9, 28), 'long-name': u'Lincoln, Lincolnshire.'} {'placename': u'Lincoln, Lincolnshire', 'processed': True, 'end': datetime.date(1216, 9, 30), 'start': datetime.date(1216, 9, 28), 'long-name': u'Lincoln, Lincolnshire.'} {'placename': u'Lincoln, Lincolnshire', 'processed': True, 'end': datetime.date(1216, 10, 2), 'start': datetime.date(1216, 10, 1), 'long-name': u'Lincoln, Lincolnshire.'} But if I try to call events() thus: for x in events(lst): if x['processed'] == True: print x I get a KeyError. Could someone explain what's going on here? Thanks, Jon From bgailer at gmail.com Wed May 14 23:12:54 2008 From: bgailer at gmail.com (bob gailer) Date: Wed, 14 May 2008 17:12:54 -0400 Subject: [Tutor] basic lists and loops question In-Reply-To: References: Message-ID: <482B55D6.5040409@gmail.com> Jon Crump wrote: > Something basic about lists and loops that I'm not getting here. I've > got a long list of dictionaries that looks like this: > > lst = [{'placename': u'Stow, Lincolnshire', 'long-name': u'Stow, > Lincolnshire.', 'end': datetime.date(1216, 9, 28), 'start': > datetime.date(1216, 9, 26)}, > {'placename': u'Lincoln, Lincolnshire', 'long-name': u'Lincoln, > Lincolnshire.', 'end': datetime.date(1216, 9, 30), 'start': > datetime.date(1216, 9, 28)}, > {'placename': u'Lincoln, Lincolnshire', 'long-name': u'Lincoln, > Lincolnshire.', 'end': datetime.date(1216, 10, 2), 'start': > datetime.date(1216, 10, 1)}, > {'placename': u'Grimsby, Lincolnshire', 'long-name': u'Grimsby, > Lincolnshire.', 'end': datetime.date(1216, 10, 4), 'start': > datetime.date(1216, 10, 3)}, > {'placename': u'Louth, Lincolnshire', 'long-name': u'Louth, > Lincolnshire.', 'end': datetime.date(1216, 10, 4), 'start': > datetime.date(1216, 10, 4)} > ] > > I have a function that searches through them to find pairs of > dictionaries that satisfy certain criteria. When the nested loops find > such a pair, I need to merge them. So far so good. This works: > > def events(data): > evts = [] > for x in lst: > for y in lst: > if (x['placename'] == y['placename']) and (x['end'].month + 1 == > y['start'].month) and (y['start'] - x['end'] == datetime.timedelta(1)): > evts.append({'placename': x['placename'], 'long-name': > x['long-name'], 'start': x['start'], 'end': y['end']}) > evts.append(x) > return evts > > for x in events(lst): > print x > > But then I need to delete the two original dictionaries that I merged. > If I do del x, I get an error "local variable 'x' referenced before > assignment" Try lst.remove(x) > > I've also tried decorating the processed dictionaries in the if loop > thus: > x['processed'] = True > y['processed'] = True > > Then when I call events() I get back the merged dict and the decorated > dicts: > > {'placename': u'Lincoln, Lincolnshire', 'end': datetime.date(1216, 10, > 2), 'start': datetime.date(1216, 9, 28), 'long-name': u'Lincoln, > Lincolnshire.'} > {'placename': u'Lincoln, Lincolnshire', 'processed': True, 'end': > datetime.date(1216, 9, 30), 'start': datetime.date(1216, 9, 28), > 'long-name': u'Lincoln, Lincolnshire.'} > {'placename': u'Lincoln, Lincolnshire', 'processed': True, 'end': > datetime.date(1216, 10, 2), 'start': datetime.date(1216, 10, 1), > 'long-name': u'Lincoln, Lincolnshire.'} > > But if I try to call events() thus: > > for x in events(lst): > if x['processed'] == True: > print x > > I get a KeyError. Sounds like the key 'processed' is created by the assignment x['processed'] = True. So those dictionaries that have not experienced this assignment have no such key. You should instead use: if 'processed' in x: Also if x['processed'] == True: can be expressed if x['processed']: > HTH -- Bob Gailer 919-636-4239 Chapel Hill, NC From kent37 at tds.net Wed May 14 23:31:04 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 14 May 2008 17:31:04 -0400 Subject: [Tutor] basic lists and loops question In-Reply-To: References: Message-ID: <1c2a2c590805141431o37535a29u98889cf70d6dff34@mail.gmail.com> On Wed, May 14, 2008 at 3:02 PM, Jon Crump wrote: > Something basic about lists and loops that I'm not getting here. > I have a function that searches through them to find pairs of dictionaries > that satisfy certain criteria. When the nested loops find such a pair, I > need to merge them. So far so good. This works: > > def events(data): > evts = [] > for x in lst: > for y in lst: > if (x['placename'] == y['placename']) and (x['end'].month + 1 == > y['start'].month) and (y['start'] - x['end'] == datetime.timedelta(1)): > evts.append({'placename': x['placename'], 'long-name': > x['long-name'], 'start': x['start'], 'end': y['end']}) > evts.append(x) > return evts > > for x in events(lst): > print x > > But then I need to delete the two original dictionaries that I merged. If I > do del x, I get an error "local variable 'x' referenced before assignment" Not sure why you got that error but it general it is not a good idea to delete items from a container you are iterating; the results can be unpredictable. > > I've also tried decorating the processed dictionaries in the if loop thus: > x['processed'] = True > y['processed'] = True > > Then when I call events() I get back the merged dict and the decorated > dicts: > > {'placename': u'Lincoln, Lincolnshire', 'end': datetime.date(1216, 10, 2), > 'start': datetime.date(1216, 9, 28), 'long-name': u'Lincoln, Lincolnshire.'} > {'placename': u'Lincoln, Lincolnshire', 'processed': True, 'end': > datetime.date(1216, 9, 30), 'start': datetime.date(1216, 9, 28), > 'long-name': u'Lincoln, Lincolnshire.'} > {'placename': u'Lincoln, Lincolnshire', 'processed': True, 'end': > datetime.date(1216, 10, 2), 'start': datetime.date(1216, 10, 1), > 'long-name': u'Lincoln, Lincolnshire.'} > > But if I try to call events() thus: > > for x in events(lst): > if x['processed'] == True: > print x > > I get a KeyError. The problem is that not every dict has the 'processed' key. Try if x.get('processed') == True: or just if x.get('processed'): x.get() will return None (instead of raising KeyError) if the key is not present. Kent From jjcrump at myuw.net Thu May 15 00:03:49 2008 From: jjcrump at myuw.net (Jon Crump) Date: Wed, 14 May 2008 15:03:49 -0700 (PDT) Subject: [Tutor] basic lists and loops question In-Reply-To: <482B55D6.5040409@gmail.com> References: <482B55D6.5040409@gmail.com> Message-ID: Bob, and Kent, Many thanks! > Sounds like the key 'processed' is created by the assignment x['processed'] = > True. So those dictionaries that have not experienced this assignment have no > such key. You should instead use: if 'processed' in x: Doh! Now that WAS obvious > Try lst.remove(x) Now this was odd. My trusty guide "Learning Python" (Lutz & Ascher) 2nd Ed. for python 2.3 says nothing about remove(). This must be 2.4 or 2.5 yes? this now has the desired effect (remains to be seen if it works for all instances): def events(data): evts = [] for x in data: for y in data: if (x['placename'] == y['placename']) and (x['end'].month + 1 == y['start'].month) and (y['start'] - x['end'] == datetime.timedelta(1)): x['end'] = y['end'] data.remove(x) evts.append(x) return evts I understand about removing elements from a container you're iterating. Is data.remove(x) problematic in this context? From kent37 at tds.net Thu May 15 03:06:30 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 14 May 2008 21:06:30 -0400 Subject: [Tutor] basic lists and loops question In-Reply-To: References: <482B55D6.5040409@gmail.com> Message-ID: <1c2a2c590805141806o3867fc35ia1cfc1b6a52ba471@mail.gmail.com> On Wed, May 14, 2008 at 6:03 PM, Jon Crump wrote: > def events(data): > evts = [] > for x in data: > for y in data: > if (x['placename'] == y['placename']) and (x['end'].month + 1 == > y['start'].month) and (y['start'] - x['end'] == datetime.timedelta(1)): > x['end'] = y['end'] > data.remove(x) > evts.append(x) > return evts > > I understand about removing elements from a container you're iterating. Is > data.remove(x) problematic in this context? Yes. It can cause the iteration to skip elements ofthe list. Better to post-process the list with a list comprehension: evts = [ evt for evt in evts if 'processed' not in evt ] Kent From kent37 at tds.net Thu May 15 03:30:58 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 14 May 2008 21:30:58 -0400 Subject: [Tutor] basic lists and loops question In-Reply-To: <1c2a2c590805141806o3867fc35ia1cfc1b6a52ba471@mail.gmail.com> References: <482B55D6.5040409@gmail.com> <1c2a2c590805141806o3867fc35ia1cfc1b6a52ba471@mail.gmail.com> Message-ID: <1c2a2c590805141830s6f0d26f0u5aa41fecde5598c9@mail.gmail.com> On Wed, May 14, 2008 at 9:06 PM, Kent Johnson wrote: >> I understand about removing elements from a container you're iterating. Is >> data.remove(x) problematic in this context? > > Yes. It can cause the iteration to skip elements of the list. For example: In [1]: l=range(5) In [2]: for i in l: ...: print i ...: if i==2: ...: l.remove(i) ...: ...: 0 1 2 4 Notice how 3 is skipped. Don't do this! Kent From jjcrump at myuw.net Thu May 15 04:25:43 2008 From: jjcrump at myuw.net (Jon Crump) Date: Wed, 14 May 2008 19:25:43 -0700 (PDT) Subject: [Tutor] basic lists and loops question In-Reply-To: <1c2a2c590805141806o3867fc35ia1cfc1b6a52ba471@mail.gmail.com> References: <482B55D6.5040409@gmail.com> <1c2a2c590805141806o3867fc35ia1cfc1b6a52ba471@mail.gmail.com> Message-ID: Kent, On Wed, 14 May 2008, Kent Johnson wrote: >> I understand about removing elements from a container you're iterating. Is >> data.remove(x) problematic in this context? > > Yes. It can cause the iteration to skip elements ofthe list. Better to > post-process the list with a list comprehension: > evts = [ evt for evt in evts if 'processed' not in evt ] Thanks very much. This became clear when I applied the .remove(x) solution to the whole list: very strange results. Altering x in the y loop also had unforseen effects. I finally decorated every dictionary acted upon so I could check everything that was going on. the appended merged dict got a "merged" key and the two dictionaries that were merged each got a "processed" key, then I post processed the list to remove the 'processed' dictionaries **whew**. Thanks for clarifying AND saving me from error. Jon From kpsingh at gmail.com Thu May 15 07:58:14 2008 From: kpsingh at gmail.com (Kamal) Date: Wed, 14 May 2008 22:58:14 -0700 Subject: [Tutor] looking for ways to get diff between two txt files Message-ID: <333eea650805142258q42aae345ta89a558331ba94ec@mail.gmail.com> Hi, I would really appreciate if someone help to find a way to calculate delta (diff) between two similar text files. I have looked at difflib and found related script at this site http://www.java2s.com/Code/Python/Utility/Printfilediffsincontextunifiedorndiffformats.htm Is there a simple way to just get delta between two files? e.g. I have below two files and the delta between these two files is in diff_output.txt file1.txt hello world file2.txt hello world hello python diff_output.txt hello python -- Thanks, Kamal From gtxy20 at gmail.com Thu May 15 08:40:24 2008 From: gtxy20 at gmail.com (GTXY20) Date: Thu, 15 May 2008 02:40:24 -0400 Subject: [Tutor] Iterate through dictionary values and remove item Message-ID: <39cb7e5d0805142340v1ce25d79n2d9f90db0b5fb18e@mail.gmail.com> Hello all, I have dictionary like the following: d={(1,23A):[a,b,c,d], (1,24A):[b,c,d], (2,23A):[a,b], (2,24A):[a,b,c,d]} I would like to iterate through the dictionary such that if it finds the value 'a' in the values of the key that it would remove the value 'b' from the values list. In addition if it finds 'a' in the values list I would like it to take the first item from the key tuple k[0] and and then look through the dictionary for that k[0] value and then remove 'b' from its value list even if 'a' is not present in that list. So at the end I would like my dictionary to end with: d={(1,23A):[a,c,d], (1,24A):[c,d], (2,23A):[a], (2,24A):[a,c,d]} Initally I did the following: for k,v in d.items(): u=k[0] b=k[1] if 'a' in v: for k,v in d.items(): if k[0] == u: for values in v: if values == 'b': v.remove(values) However this will be a very big dictionary and it ended up running for a very long time - in fact I had to kill the process. Can anyone suggest an alternate method to do this? Thanks in advance for any suggestions. G. From wtfwhoami at gmail.com Thu May 15 09:00:04 2008 From: wtfwhoami at gmail.com (Guess?!?) Date: Thu, 15 May 2008 00:00:04 -0700 Subject: [Tutor] Random module error Message-ID: <8c64f3990805150000s46cd9247w51d5ddeb6f49af67@mail.gmail.com> Hello All, I am importing module "random" and it is giving me this error below AttributeError: 'module' object has no attribute 'randrange' What could be the reason for this? When I chk API ..random module has a function randrange ...... >>> from TurtleWorld import * Traceback (most recent call last): File "", line 1, in File "C:\Python25\swampy.1.1\TurtleWorld.py", line 1, in from World import * File "C:\Python25\swampy.1.1\World.py", line 29, in import random File "C:\Python25\random.py", line 4, in i = random.randrange(10,50) AttributeError: 'module' object has no attribute 'randrange' >>> -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Thu May 15 12:49:28 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 15 May 2008 06:49:28 -0400 Subject: [Tutor] looking for ways to get diff between two txt files In-Reply-To: <333eea650805142258q42aae345ta89a558331ba94ec@mail.gmail.com> References: <333eea650805142258q42aae345ta89a558331ba94ec@mail.gmail.com> Message-ID: <1c2a2c590805150349l23b07511x1532f3868105864a@mail.gmail.com> On Thu, May 15, 2008 at 1:58 AM, Kamal wrote: > Hi, > > I would really appreciate if someone help to find a way to calculate > delta (diff) between two similar text files. This example would be pretty easy to modify to do what you want: http://personalpages.tds.net/~kent37/blog/arch_m1_2004_06.html#e47 Kent From bgailer at gmail.com Thu May 15 13:01:12 2008 From: bgailer at gmail.com (bob gailer) Date: Thu, 15 May 2008 07:01:12 -0400 Subject: [Tutor] Iterate through dictionary values and remove item In-Reply-To: <39cb7e5d0805142340v1ce25d79n2d9f90db0b5fb18e@mail.gmail.com> References: <39cb7e5d0805142340v1ce25d79n2d9f90db0b5fb18e@mail.gmail.com> Message-ID: <482C17F8.7050200@gmail.com> GTXY20 wrote: > Hello all, > > I have dictionary like the following: > > d={(1,23A):[a,b,c,d], (1,24A):[b,c,d], (2,23A):[a,b], (2,24A):[a,b,c,d]} > > I would like to iterate through the dictionary such that if it finds > the value 'a' in the values of the key that it would remove the value > 'b' from the values list. In addition if it finds 'a' in the values > list I would like it to take the first item from the key tuple k[0] > and and then look through the dictionary for that k[0] value and then > remove 'b' from its value list even if 'a' is not present in that > list. So at the end I would like my dictionary to end with: > > d={(1,23A):[a,c,d], (1,24A):[c,d], (2,23A):[a], (2,24A):[a,c,d]} > > Initally I did the following: > > for k,v in d.items(): > u=k[0] > b=k[1] > if 'a' in v: > for k,v in d.items(): > if k[0] == u: > for values in v: > if values == 'b': > v.remove(values) > > However this will be a very big dictionary and it ended up running for > a very long time - in fact I had to kill the process. > > Can anyone suggest an alternate method to do this? > > Thanks in advance for any suggestions. > Your code sure looks weird! d={(1,23A):[a,c,d], (1,24A):[c,d], (2,23A):[a], (2,24A):[a,c,d]} That gives a syntax error at the first A. And the rest of the code lacks indentation. Your code does not match your specification. You said "... if it finds the value 'a' in the values of the key...." but you test if 'a' in v: Please fix these issues and repost. -- Bob Gailer 919-636-4239 Chapel Hill, NC From kent37 at tds.net Thu May 15 13:57:55 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 15 May 2008 07:57:55 -0400 Subject: [Tutor] Iterate through dictionary values and remove item In-Reply-To: <39cb7e5d0805142340v1ce25d79n2d9f90db0b5fb18e@mail.gmail.com> References: <39cb7e5d0805142340v1ce25d79n2d9f90db0b5fb18e@mail.gmail.com> Message-ID: <1c2a2c590805150457u36f8b8e2r92a92b2eb6760d95@mail.gmail.com> On Thu, May 15, 2008 at 2:40 AM, GTXY20 wrote: > Hello all, > > I have dictionary like the following: > > d={(1,23A):[a,b,c,d], (1,24A):[b,c,d], (2,23A):[a,b], (2,24A):[a,b,c,d]} > > I would like to iterate through the dictionary such that if it finds > the value 'a' in the values of the key that it would remove the value > 'b' from the values list. In addition if it finds 'a' in the values > list I would like it to take the first item from the key tuple k[0] > and and then look through the dictionary for that k[0] value and then > remove 'b' from its value list even if 'a' is not present in that > list. So at the end I would like my dictionary to end with: > > d={(1,23A):[a,c,d], (1,24A):[c,d], (2,23A):[a], (2,24A):[a,c,d]} > > Initally I did the following: > > for k,v in d.items(): > u=k[0] > b=k[1] > if 'a' in v: > for k,v in d.items(): > if k[0] == u: > for values in v: > if values == 'b': > v.remove(values) > > However this will be a very big dictionary and it ended up running for > a very long time - in fact I had to kill the process. The main problem is the nested loops. Every time you find an 'a' you search the whole dict for items starting with matching keys. There are some smaller problems as well - you could use d.iteritems() instead of d.items() to avoid creating intermediate lists, and there are better ways to remove 'b' from v. The first thing I would do is reduce this to two passes over the dict - the first pass can find the keys, the second to delete 'b' from the list. For example, toRemove=set(k[0] for k, v in d.iteritems() if 'b' in v) for k,v in d.iteritems(): if k[0] in toRemove: try: v.remove('b') except ValueError: pass If this is too slow, consider splitting up your keys - make a two-level dict so you can find all the keys starting with a particular value by a dict lookup instead of search. Kent From kent37 at tds.net Thu May 15 14:00:00 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 15 May 2008 08:00:00 -0400 Subject: [Tutor] Random module error In-Reply-To: <8c64f3990805150000s46cd9247w51d5ddeb6f49af67@mail.gmail.com> References: <8c64f3990805150000s46cd9247w51d5ddeb6f49af67@mail.gmail.com> Message-ID: <1c2a2c590805150500o52d63b7fgb814dcf8aab8bf94@mail.gmail.com> On Thu, May 15, 2008 at 3:00 AM, Guess?!? wrote: > Hello All, > > I am importing module "random" and it is giving me this error > below AttributeError: 'module' object has no attribute 'randrange' You have named your program random.py. The import finds your program rather than the random module. Rename your program and delete the associated .pyc file and it will work. Kent From diegotrazzi at gmail.com Thu May 15 14:10:40 2008 From: diegotrazzi at gmail.com (Diego Trazzi) Date: Thu, 15 May 2008 13:10:40 +0100 Subject: [Tutor] Freeze utility Message-ID: <10a7c87f0805150510t2e39bb7eo8b39a699165a94e9@mail.gmail.com> Can you recommended any good freeze utility for python to create linux standalone executables, other than the freeze.py ? this script doen't seems to include my .gif images... Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From jatinder.singh2 at wipro.com Thu May 15 17:22:22 2008 From: jatinder.singh2 at wipro.com (root) Date: Thu, 15 May 2008 20:52:22 +0530 Subject: [Tutor] (no subject) Message-ID: <1210864942.2319.8.camel@localhost.localdomain> hi ,i am working to replace three lines in a httpd.conf file using regular expression.i am able to change only one among them but while replacing other i am not geeting good idea to replace all the three lines just in a single script ,,my script is like #!usr/bin/python import sys import os import re import string def replace_file(file,search,replace): cregex=re.compile(search) for current_line in file: if cregex.search(current_line): current_line=re.sub(search,replace,current_line) print current_line else: print current_line def main(): file =open("/root/Desktop/httpd.conf").readlines() replace_file(file,'User apache ' , 'User myuser ') #replace_file(file,'Group apache','Group myuser') #replace_file(file,DirectoryIndex\ index.html\ index.html.var,DirectoryIndex\ index.html\ index.html.var\ login.html) if __name__ == '__main__': main() I am running this command to save the output in a temp file then replacing with original httpd.conf. can I do this in a single python script that'll change three lines and there should not any need to replace it.that is the change should directly save to the source file......?????????? any help will be appreciated.Thanks Please do not print this email unless it is absolutely necessary. The information contained in this electronic message and any attachments to this message are intended for the exclusive use of the addressee(s) and may contain proprietary, confidential or privileged information. If you are not the intended recipient, you should not disseminate, distribute or copy this e-mail. Please notify the sender immediately and destroy all copies of this message and any attachments. WARNING: Computer viruses can be transmitted via email. The recipient should check this email and any attachments for the presence of viruses. The company accepts no liability for any damage caused by any virus transmitted by this email. www.wipro.com From kent37 at tds.net Thu May 15 17:51:58 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 15 May 2008 11:51:58 -0400 Subject: [Tutor] (no subject) In-Reply-To: <1210864942.2319.8.camel@localhost.localdomain> References: <1210864942.2319.8.camel@localhost.localdomain> Message-ID: <1c2a2c590805150851m7b0ba5c1jc702b6060bdf71f9@mail.gmail.com> On Thu, May 15, 2008 at 11:22 AM, root wrote: > hi ,i am working to replace three lines in a httpd.conf file using > regular expression You don't need regex for this, you are replacing plain strings. I would read the entire file, change the strings and write it out again. For example, path = "/root/Desktop/httpd.conf" f = open(path) data = f.read() f.close() for search, replace in [ ('User apache ' , 'User myuser '), ('Group apache','Group myuser'), ('DirectoryIndex\ index.html\ index.html.var','DirectoryIndex\ index.html\ index.html.var\ login.html') ]: data.replace(search, replace) f = open(path, 'w') f.write(data) f.close() This replaces the file in place, if you want to make a backup it will be a little more complex. A few other notes: - don't use 'file' as a variable name, it shadows the builtin file() function - I'm not sure what the \ in your search string are for but they are interpreted as escape characters. If you want a literal \ in the string you have to use two \\ or prefix the string with r to make a raw string. Kent From gtxy20 at gmail.com Thu May 15 18:58:03 2008 From: gtxy20 at gmail.com (GTXY20) Date: Thu, 15 May 2008 12:58:03 -0400 Subject: [Tutor] Iterate through dictionary values and remove item In-Reply-To: <1c2a2c590805150457u36f8b8e2r92a92b2eb6760d95@mail.gmail.com> References: <39cb7e5d0805142340v1ce25d79n2d9f90db0b5fb18e@mail.gmail.com> <1c2a2c590805150457u36f8b8e2r92a92b2eb6760d95@mail.gmail.com> Message-ID: <39cb7e5d0805150958l9e4b393n4a0df18005c72ea2@mail.gmail.com> Hi Kent and Bob, Bob sorry about the previous code snippet (was late) - I had previously been trying to accomplish with the following: for k,v in d.items(): u=k[0] b=k[1] if 'a' in v: for k,v in d.items(): if k[0] == u: for vals in v: if vals == 'b': v.remove('b') this as mentioned was not performing very well at all. Kent, I incorporated your suggestion: toRemove=set(k[0] for k, v in d.iteritems() if 'b' in v) for k,v in d.iteritems(): if k[0] in toRemove: try: v.remove('b') except ValueError: pass and the speed and result improved very dramatically. I suspect that I need to get a better handle on the difference between items() and iteritems() and what situations would call for them respectively. Having said that, Kent I am not 100 percent sure of what you menat when you mention a two-level dict. Can you give me a very brief example? Thank you so much for your feedback. G. On Thu, May 15, 2008 at 7:57 AM, Kent Johnson wrote: > On Thu, May 15, 2008 at 2:40 AM, GTXY20 wrote: > > Hello all, > > > > I have dictionary like the following: > > > > d={(1,23A):[a,b,c,d], (1,24A):[b,c,d], (2,23A):[a,b], (2,24A):[a,b,c,d]} > > > > I would like to iterate through the dictionary such that if it finds > > the value 'a' in the values of the key that it would remove the value > > 'b' from the values list. In addition if it finds 'a' in the values > > list I would like it to take the first item from the key tuple k[0] > > and and then look through the dictionary for that k[0] value and then > > remove 'b' from its value list even if 'a' is not present in that > > list. So at the end I would like my dictionary to end with: > > > > d={(1,23A):[a,c,d], (1,24A):[c,d], (2,23A):[a], (2,24A):[a,c,d]} > > > > Initally I did the following: > > > > for k,v in d.items(): > > u=k[0] > > b=k[1] > > if 'a' in v: > > for k,v in d.items(): > > if k[0] == u: > > for values in v: > > if values == 'b': > > v.remove(values) > > > > However this will be a very big dictionary and it ended up running for > > a very long time - in fact I had to kill the process. > > The main problem is the nested loops. Every time you find an 'a' you > search the whole dict for items starting with matching keys. There > are some smaller problems as well - you could use d.iteritems() > instead of d.items() to avoid creating intermediate lists, and there > are better ways to remove 'b' from v. > > The first thing I would do is reduce this to two passes over the dict > - the first pass can find the keys, the second to delete 'b' from the > list. For example, > toRemove=set(k[0] for k, v in d.iteritems() if 'b' in v) > for k,v in d.iteritems(): > if k[0] in toRemove: > try: > v.remove('b') > except ValueError: > pass > > If this is too slow, consider splitting up your keys - make a > two-level dict so you can find all the keys starting with a particular > value by a dict lookup instead of search. > > Kent > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Thu May 15 19:26:27 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 15 May 2008 13:26:27 -0400 Subject: [Tutor] Iterate through dictionary values and remove item In-Reply-To: <39cb7e5d0805150958l9e4b393n4a0df18005c72ea2@mail.gmail.com> References: <39cb7e5d0805142340v1ce25d79n2d9f90db0b5fb18e@mail.gmail.com> <1c2a2c590805150457u36f8b8e2r92a92b2eb6760d95@mail.gmail.com> <39cb7e5d0805150958l9e4b393n4a0df18005c72ea2@mail.gmail.com> Message-ID: <1c2a2c590805151026s79c7bfccne522b73beff56a09@mail.gmail.com> On Thu, May 15, 2008 at 12:58 PM, GTXY20 wrote: > I suspect that I need > to get a better handle on the difference between items() and iteritems() and > what situations would call for them respectively. items() returns a list, iteritems() returns an iterator. If you don't actually need an explicit list, iteritems() saves the cost of creating it. > Having said that, Kent I am not 100 percent sure of what you menat when you > mention a two-level dict. Can you give me a very brief example? Your dict d would look like this: d={ 1: {23A:[a,b,c,d], 24A:[b,c,d]}, 2: {23A:[a,b], 24A:[a,b,c,d]} } The top level would just use the first element of the current key; the value would be another dict whose keys are the second element of the current key. This makes it easy to find all the values whose first key element is '1', for example. (You could also have the second element be a list of tuples, that might be better if you just need to iterate over it.) Kent From timmichelsen at gmx-topmail.de Thu May 15 20:10:05 2008 From: timmichelsen at gmx-topmail.de (Tim Michelsen) Date: Thu, 15 May 2008 20:10:05 +0200 Subject: [Tutor] Open a directory in the default file manager Message-ID: Hello, is there any function/module that allows me to open a directory in the default file manager of a operating system? Here I a piece of code how to open a URL in the default webbrowser: http://www.python.org/doc/lib/module-webbrowser.html import webbrowser myurl = 'http://www.python.org' webbrowser.open_new_tab(myurl) I just wanna do the same with a directory. The function should open Explorer on Windows, Nautilus on Gnome, Thunar onn XFCE4, ... Thanks for your help in advance. Regards, Timmie From enganar at yahoo.com Thu May 15 19:50:51 2008 From: enganar at yahoo.com (Gillian) Date: Thu, 15 May 2008 13:50:51 -0400 (EDT) Subject: [Tutor] Guido van Robot help Message-ID: <962137.62828.qm@web36502.mail.mud.yahoo.com> Hi, Would anyone be able to offer assistance re: using Guido van Robot to perform pattern recognition (as in it "sees" a particular pattern (like a 3x5 grid depiction of the letter "A") and responds accordingly)? In my example, Guido recognizes a specific letter by placing down an appropriate amount of beepers. A = 1 beeper, B = 2, etc. I'm able to create separate definitions to recognize specific letters, but my difficulty arises when I try to make a program so robust that it should be able to recognize any letter of the alphabet no matter what order they would be in. Thanks, Jill __________________________________________________________________ Looking for the perfect gift? Give the gift of Flickr! http://www.flickr.com/gift/ From wtfwhoami at gmail.com Thu May 15 21:48:33 2008 From: wtfwhoami at gmail.com (Guess?!?) Date: Thu, 15 May 2008 12:48:33 -0700 Subject: [Tutor] Random module error In-Reply-To: <1c2a2c590805150500o52d63b7fgb814dcf8aab8bf94@mail.gmail.com> References: <8c64f3990805150000s46cd9247w51d5ddeb6f49af67@mail.gmail.com> <1c2a2c590805150500o52d63b7fgb814dcf8aab8bf94@mail.gmail.com> Message-ID: <8c64f3990805151248y2526becbm9713c917808fa38b@mail.gmail.com> Hello Kent, I dont have any program with name random.py. I am using swampy API ( http://allendowney.com/swampy/install.html) As instructed by author, I do following steps 1> unzip/extract the folder into Python directory 2> go to the swampy directory 3> and invoke python command to start interpreter 4> as soon as I write from TurtleWorld import * I get that error ..... I checked inside the folder ...there is no random.py and i checked TurtleWorld.py ....there is only reference to standard module "random" Thnks G On Thu, May 15, 2008 at 5:00 AM, Kent Johnson wrote: > On Thu, May 15, 2008 at 3:00 AM, Guess?!? wrote: > > Hello All, > > > > I am importing module "random" and it is giving me this error > > below AttributeError: 'module' object has no attribute 'randrange' > > You have named your program random.py. The import finds your program > rather than the random module. Rename your program and delete the > associated .pyc file and it will work. > > Kent > -------------- next part -------------- An HTML attachment was scrubbed... URL: From christopher.henk at allisontransmission.com Thu May 15 22:18:26 2008 From: christopher.henk at allisontransmission.com (christopher.henk at allisontransmission.com) Date: Thu, 15 May 2008 16:18:26 -0400 Subject: [Tutor] Random module error In-Reply-To: <8c64f3990805151248y2526becbm9713c917808fa38b@mail.gmail.com> Message-ID: Your original post showed this traceback: Traceback (most recent call last): File "", line 1, in File "C:\Python25\swampy.1.1\TurtleWorld.py", line 1, in from World import * File "C:\Python25\swampy.1.1\World.py", line 29, in import random File "C:\Python25\random.py", line 4, in i = random.randrange(10,50) AttributeError: 'module' object has no attribute 'randrange' Which would suggest that the file World.py imported a file called random.py from the directory C:\Python25\random.py The random module that comes with python is typically stored in the directory C:\Python25\Lib and never contains the line: i = random.randrange(10,50) So I would look for a .py or .pyc file in your Python25 folder called random and remove it like Kent said. Hope that works. Chris "Guess?!?" Sent by: tutor-bounces at python.org 05/15/2008 03:48 PM To "Kent Johnson" cc tutor at python.org Subject Re: [Tutor] Random module error Hello Kent, I dont have any program with name random.py. I am using swampy API ( http://allendowney.com/swampy/install.html) As instructed by author, I do following steps 1> unzip/extract the folder into Python directory 2> go to the swampy directory 3> and invoke python command to start interpreter 4> as soon as I write from TurtleWorld import * I get that error ..... I checked inside the folder ...there is no random.py and i checked TurtleWorld.py ....there is only reference to standard module "random" Thnks G On Thu, May 15, 2008 at 5:00 AM, Kent Johnson wrote: On Thu, May 15, 2008 at 3:00 AM, Guess?!? wrote: > Hello All, > > I am importing module "random" and it is giving me this error > below AttributeError: 'module' object has no attribute 'randrange' You have named your program random.py. The import finds your program rather than the random module. Rename your program and delete the associated .pyc file and it will work. Kent _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From wtfwhoami at gmail.com Thu May 15 22:43:11 2008 From: wtfwhoami at gmail.com (Guess?!?) Date: Thu, 15 May 2008 13:43:11 -0700 Subject: [Tutor] Random module error In-Reply-To: References: <8c64f3990805151248y2526becbm9713c917808fa38b@mail.gmail.com> Message-ID: <8c64f3990805151343rf5822b0xf5b6217c47e4683f@mail.gmail.com> Got it fixed ...Thanks Kent and Chris. I might have created a prog and named it random and later deleted it but pyc was still sitting at the bottom ....I purged it and I am back on learning curve .... ... ~G On Thu, May 15, 2008 at 1:18 PM, wrote: > > Your original post showed this traceback: > Traceback (most recent call last): > File "", line 1, in > File "C:\Python25\swampy.1.1\TurtleWorld.py", line 1, in > from World import * > File "C:\Python25\swampy.1.1\World.py", line 29, in > import random > File "C:\Python25\random.py", line 4, in > i = random.randrange(10,50) > AttributeError: 'module' object has no attribute 'randrange' > > > Which would suggest that the file World.py imported a file called random.py > from the directory C:\Python25\random.py > The random module that comes with python is typically stored in the > directory C:\Python25\Lib > and never contains the line: i = random.randrange(10,50) > > So I would look for a .py or .pyc file in your Python25 folder called > random and remove it like Kent said. > > Hope that works. > > Chris > > > > *"Guess?!?" * > Sent by: tutor-bounces at python.org > > 05/15/2008 03:48 PM > To > "Kent Johnson" > cc > tutor at python.org Subject > Re: [Tutor] Random module error > > > > > Hello Kent, > > I dont have any program with name random.py. I am using swampy API (* > http://allendowney.com/swampy/install.html* > ) > As instructed by author, I do following steps > > 1> unzip/extract the folder into Python directory > 2> go to the swampy directory > 3> and invoke python command to start interpreter > 4> as soon as I write from TurtleWorld import * > > I get that error ..... I checked inside the folder ...there is no random.py > and > i checked TurtleWorld.py ....there is only reference to standard module > "random" > > Thnks > G > > > > > > On Thu, May 15, 2008 at 5:00 AM, Kent Johnson <*kent37 at tds.net*> > wrote: > On Thu, May 15, 2008 at 3:00 AM, Guess?!? <*wtfwhoami at gmail.com*> > wrote: > > Hello All, > > > > I am importing module "random" and it is giving me this error > > below AttributeError: 'module' object has no attribute 'randrange' > > You have named your program random.py. The import finds your program > rather than the random module. Rename your program and delete the > associated .pyc file and it will work. > > Kent > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From simon_ecc at yahoo.co.uk Fri May 16 14:16:10 2008 From: simon_ecc at yahoo.co.uk (ppaarrkk) Date: Fri, 16 May 2008 05:16:10 -0700 (PDT) Subject: [Tutor] Getting started with Python Message-ID: <17273337.post@talk.nabble.com> I can't. >>> import file.py is all very well if the interpreter knows where file.py is. I want to do this : >>> import /directory1/directory2/file.py Is this not possible ? -- View this message in context: http://www.nabble.com/Getting-started-with-Python-tp17273337p17273337.html Sent from the Python - tutor mailing list archive at Nabble.com. From moishyyehuda at gmail.com Fri May 16 17:20:47 2008 From: moishyyehuda at gmail.com (Moishy Gluck) Date: Fri, 16 May 2008 11:20:47 -0400 Subject: [Tutor] Getting started with Python In-Reply-To: <187d38240805160820t40ae617bo77503198306dcc05@mail.gmail.com> References: <17273337.post@talk.nabble.com> <187d38240805160820t40ae617bo77503198306dcc05@mail.gmail.com> Message-ID: <187d38240805160820n59834bebx2955b4c7386b0247@mail.gmail.com> On Fri, May 16, 2008 at 11:20 AM, Moishy Gluck wrote: > You need to place a "__init__.py" file in a directory you want to reference > in an import statement. > > I don't believe the content of the file is important but you can place code > in the file that will affect how files are imported. > > The import syntax is a such. > > import directory1.directory2.file.py > > Place "__init__.py" in both "directory1" and "directory2" > > Good luck simon. > > > On Fri, May 16, 2008 at 8:16 AM, ppaarrkk wrote: > >> >> I can't. >> >> >> >>> import file.py >> >> >> is all very well if the interpreter knows where file.py is. >> >> >> I want to do this : >> >> >>> import /directory1/directory2/file.py >> >> >> Is this not possible ? >> >> -- >> View this message in context: >> http://www.nabble.com/Getting-started-with-Python-tp17273337p17273337.html >> Sent from the Python - tutor mailing list archive at Nabble.com. >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From titleistfour at gmail.com Fri May 16 17:44:04 2008 From: titleistfour at gmail.com (jay) Date: Fri, 16 May 2008 10:44:04 -0500 Subject: [Tutor] Getting started with Python In-Reply-To: <187d38240805160820n59834bebx2955b4c7386b0247@mail.gmail.com> References: <17273337.post@talk.nabble.com> <187d38240805160820t40ae617bo77503198306dcc05@mail.gmail.com> <187d38240805160820n59834bebx2955b4c7386b0247@mail.gmail.com> Message-ID: <7c25bb490805160844k20392910i607fa17992411261@mail.gmail.com> Have you tried this ? import sys sys.path.append('/directory1/directory2') import file.py j On Fri, May 16, 2008 at 10:20 AM, Moishy Gluck wrote: > > > On Fri, May 16, 2008 at 11:20 AM, Moishy Gluck > wrote: > >> You need to place a "__init__.py" file in a directory you want to >> reference in an import statement. >> >> I don't believe the content of the file is important but you can place >> code in the file that will affect how files are imported. >> >> The import syntax is a such. >> >> import directory1.directory2.file.py >> >> Place "__init__.py" in both "directory1" and "directory2" >> >> Good luck simon. >> >> >> On Fri, May 16, 2008 at 8:16 AM, ppaarrkk wrote: >> >>> >>> I can't. >>> >>> >>> >>> import file.py >>> >>> >>> is all very well if the interpreter knows where file.py is. >>> >>> >>> I want to do this : >>> >>> >>> import /directory1/directory2/file.py >>> >>> >>> Is this not possible ? >>> >>> -- >>> View this message in context: >>> http://www.nabble.com/Getting-started-with-Python-tp17273337p17273337.html >>> Sent from the Python - tutor mailing list archive at Nabble.com. >>> >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> http://mail.python.org/mailman/listinfo/tutor >>> >> >> > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From thomas.pani at gmail.com Fri May 16 17:55:58 2008 From: thomas.pani at gmail.com (Thomas Pani) Date: Fri, 16 May 2008 17:55:58 +0200 Subject: [Tutor] Open a directory in the default file manager In-Reply-To: References: Message-ID: <482DAE8E.2090308@gmail.com> Tim Michelsen wrote: > Hello, > is there any function/module that allows me to open a directory in the > default file manager of a operating system? On Windows you can use os.startfile(). On "pure" Unices there's no such thing as filetype associations However, if you use a desktop environment, you can spawn xdg-open (from xdg-utils) from Python. This will autodetect gnome, kde and xfce and use their tools (gnome-open, kfmclient, exo-open). I think on OS X/Darwin there's a similar utility called `open'. You can use sys.platform to determine which system you're running on. thomas From Mike.Hansen at atmel.com Fri May 16 17:57:45 2008 From: Mike.Hansen at atmel.com (Hansen, Mike) Date: Fri, 16 May 2008 09:57:45 -0600 Subject: [Tutor] Getting started with Python In-Reply-To: <7c25bb490805160844k20392910i607fa17992411261@mail.gmail.com> References: <17273337.post@talk.nabble.com><187d38240805160820t40ae617bo77503198306dcc05@mail.gmail.com><187d38240805160820n59834bebx2955b4c7386b0247@mail.gmail.com> <7c25bb490805160844k20392910i607fa17992411261@mail.gmail.com> Message-ID: <7941B2693F32294AAF16C26B679A258D023D0C19@csomb01.corp.atmel.com> Isn't it import file not import file.py or has that changed in recent versions? Mike ________________________________ From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of jay Sent: Friday, May 16, 2008 9:44 AM To: tutor at python.org Subject: Re: [Tutor] Getting started with Python Have you tried this ? import sys sys.path.append('/directory1/directory2') import file.py j On Fri, May 16, 2008 at 10:20 AM, Moishy Gluck wrote: On Fri, May 16, 2008 at 11:20 AM, Moishy Gluck wrote: You need to place a "__init__.py" file in a directory you want to reference in an import statement. I don't believe the content of the file is important but you can place code in the file that will affect how files are imported. The import syntax is a such. import directory1.directory2.file.py Place "__init__.py" in both "directory1" and "directory2" Good luck simon. On Fri, May 16, 2008 at 8:16 AM, ppaarrkk wrote: I can't. >>> import file.py is all very well if the interpreter knows where file.py is. I want to do this : >>> import /directory1/directory2/file.py Is this not possible ? -- View this message in context: http://www.nabble.com/Getting-started-with-Python-tp17273337p17273337.ht ml Sent from the Python - tutor mailing list archive at Nabble.com. _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From titleistfour at gmail.com Fri May 16 18:02:44 2008 From: titleistfour at gmail.com (jay) Date: Fri, 16 May 2008 11:02:44 -0500 Subject: [Tutor] Getting started with Python In-Reply-To: <7941B2693F32294AAF16C26B679A258D023D0C19@csomb01.corp.atmel.com> References: <17273337.post@talk.nabble.com> <187d38240805160820t40ae617bo77503198306dcc05@mail.gmail.com> <187d38240805160820n59834bebx2955b4c7386b0247@mail.gmail.com> <7c25bb490805160844k20392910i607fa17992411261@mail.gmail.com> <7941B2693F32294AAF16C26B679A258D023D0C19@csomb01.corp.atmel.com> Message-ID: <7c25bb490805160902t5e46523ck5f31b38c89c266f6@mail.gmail.com> Your right, typo :-) On Fri, May 16, 2008 at 10:57 AM, Hansen, Mike wrote: > Isn't it > > import file > > not > > import file.py > > or has that changed in recent versions? > > Mike > > ------------------------------ > *From:* tutor-bounces at python.org [mailto:tutor-bounces at python.org] *On > Behalf Of *jay > *Sent:* Friday, May 16, 2008 9:44 AM > *To:* tutor at python.org > *Subject:* Re: [Tutor] Getting started with Python > > Have you tried this ? > > import sys > sys.path.append('/directory1/directory2') > import file.py > > j > > On Fri, May 16, 2008 at 10:20 AM, Moishy Gluck > wrote: > >> >> >> On Fri, May 16, 2008 at 11:20 AM, Moishy Gluck >> wrote: >> >>> You need to place a "__init__.py" file in a directory you want to >>> reference in an import statement. >>> >>> I don't believe the content of the file is important but you can place >>> code in the file that will affect how files are imported. >>> >>> The import syntax is a such. >>> >>> import directory1.directory2.file.py >>> >>> Place "__init__.py" in both "directory1" and "directory2" >>> >>> Good luck simon. >>> >>> >>> On Fri, May 16, 2008 at 8:16 AM, ppaarrkk wrote: >>> >>>> >>>> I can't. >>>> >>>> >>>> >>> import file.py >>>> >>>> >>>> is all very well if the interpreter knows where file.py is. >>>> >>>> >>>> I want to do this : >>>> >>>> >>> import /directory1/directory2/file.py >>>> >>>> >>>> Is this not possible ? >>>> >>>> -- >>>> View this message in context: >>>> http://www.nabble.com/Getting-started-with-Python-tp17273337p17273337.html >>>> Sent from the Python - tutor mailing list archive at Nabble.com. >>>> >>>> _______________________________________________ >>>> Tutor maillist - Tutor at python.org >>>> http://mail.python.org/mailman/listinfo/tutor >>>> >>> >>> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.c.miller at gmail.com Fri May 16 23:43:19 2008 From: joel.c.miller at gmail.com (Joel Miller) Date: Fri, 16 May 2008 14:43:19 -0700 Subject: [Tutor] quickly pulling marbles out of urns Message-ID: <13c8f3270805161443k51e2994bj3485acc6438f57e3@mail.gmail.com> I'm looking for a faster way to do the following problem: I have an urn with many different colors of marbles in it. I pull one out and note the color. I do not replace it. For the programming of this, I actually know how many are yellow, green, etc. So the way the code works right now is: import math ... randindex = math.randint(1,number_of_marbles) for color in colors: if randindex<=marble_count[color]: #we've found what color it will be break else: #try next color randindex -= marble_count[color] marble_count[color] -= 1 number_of_marbles -= 1 return color Unfortunately, I have hundreds of thousands of colors, so it spends a while on this loop. And I have to keep choosing marbles many times at different points of the code. Is there a quicker way to do this? Thanks, Joel From adam.clarridge at gmail.com Sat May 17 00:59:50 2008 From: adam.clarridge at gmail.com (Adam Clarridge) Date: Fri, 16 May 2008 18:59:50 -0400 Subject: [Tutor] Dictionaries or Numpy? Message-ID: <495f2c630805161559w60b6ebbck19f07cb539ecd9a0@mail.gmail.com> Hi, I'm writing an AI for a board game called Blokus, and I believe that the quality of the program is going to greatly depend on the efficiency of the algorithm I use to generate legal moves and rate them. I know sort of how I'm going to do this legal move generation, and I know it is going to require lots of accesses to an array of some kind which will represent the game board. I'm fairly new to Python, and I am not sure whether it would be faster for me to use a Dictionary data type to represent the board (advantages: indices can be strings or tuples, and the dictionary can store different types of data as well, so programming would be easier) or the Numpy array type (don't know much about this, but I have heard Numpy is faster). So is Numpy faster for simple array accesses? That would be valuable and I'd deal with having an integer-indexed integer array if I had to. Code might look something like this: for playable_corner in all_playable_corners: for piece in all_available_pieces: for each_square in piece: # if square is not in a legal position, don't add to list of legal moves So that if statement would be accessing the board array many many times. I guess my question is: Is there any way to test Dictionary access time vs. Numpy array access time? Thanks, Adam From john at fouhy.net Sat May 17 02:08:15 2008 From: john at fouhy.net (John Fouhy) Date: Sat, 17 May 2008 12:08:15 +1200 Subject: [Tutor] Dictionaries or Numpy? In-Reply-To: <495f2c630805161559w60b6ebbck19f07cb539ecd9a0@mail.gmail.com> References: <495f2c630805161559w60b6ebbck19f07cb539ecd9a0@mail.gmail.com> Message-ID: <5e58f2e40805161708y5a2b27e8wc5bc179974d8c35e@mail.gmail.com> On 17/05/2008, Adam Clarridge wrote: > I'm fairly new to Python, and I am not sure whether it would be faster > for me to use a Dictionary data type to represent the board > (advantages: indices can be strings or tuples, and the dictionary can > store different types of data as well, so programming would be easier) > or the Numpy array type (don't know much about this, but I have heard > Numpy is faster). Hi Adam, I believe a general rule of programming is: don't optimize until you know you need to. I would advise using dictionaries for simplicity. If the program turns out slower than you would like, you can use profiling tools to figure out where in the code it is spending most of its time. If this turns out to involve dictionary lookups, you could then look at changing to Numpy (hint: you could use the timeit module to benchmark dictionary access against Numpy arrays). If your program design is good, the change should be too hard. http://en.wikipedia.org/wiki/Optimization_(computer_science)#When_to_optimize -- John. From pine508 at hotmail.com Sat May 17 06:09:03 2008 From: pine508 at hotmail.com (Che M) Date: Sat, 17 May 2008 00:09:03 -0400 Subject: [Tutor] datetime syntax error for May 8th and 9th 2008?? Message-ID: Am I missing something? Why does May 7th and other dates work but I'm getting "invalid token" for May 8th and 9th? (I have not tested many other dates of the year in this way) This is from a freshly begun IDLE session: IDLE 1.2 >>> import datetime >>> datetime.datetime(2008,05,07) datetime.datetime(2008, 5, 7, 0, 0) >>> datetime.datetime(2008, 05, 08) SyntaxError: invalid token >>> datetime.datetime(2008, 05, 09) SyntaxError: invalid token Is this a glitch in the Matrix? Che _________________________________________________________________ E-mail for the greater good. Join the i?m Initiative from Microsoft. http://im.live.com/Messenger/IM/Join/Default.aspx?source=EML_WL_ GreaterGood -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Sat May 17 06:15:23 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 17 May 2008 00:15:23 -0400 Subject: [Tutor] quickly pulling marbles out of urns In-Reply-To: <13c8f3270805161443k51e2994bj3485acc6438f57e3@mail.gmail.com> References: <13c8f3270805161443k51e2994bj3485acc6438f57e3@mail.gmail.com> Message-ID: <1c2a2c590805162115tce8e705j5723bf0917291c5e@mail.gmail.com> On Fri, May 16, 2008 at 5:43 PM, Joel Miller wrote: > I'm looking for a faster way to do the following problem: > > I have an urn with many different colors of marbles in it. I pull one > out and note the color. I do not replace it. You probably know, this is called sampling without replacement. If you can put all the 'marbles' in a list, here is a promising approach: http://groups.google.com/group/comp.lang.python/browse_thread/thread/dff9425afdb744e5/6b9a84329c0815d4?lnk=raot This is probably worth looking at too though I can't understand it at this hour: http://safari.oreilly.com/0596007973/pythoncook2-CHP-18-SECT-4 Kent From pine508 at hotmail.com Sat May 17 06:18:39 2008 From: pine508 at hotmail.com (Che M) Date: Sat, 17 May 2008 00:18:39 -0400 Subject: [Tutor] datetime syntax error for May 8th and 9th 2008?? Message-ID: From: pine508 at hotmail.com To: tutor at python.org Subject: datetime syntax error for May 8th and 9th 2008?? Date: Sat, 17 May 2008 00:09:03 -0400 Am I missing something? Why does May 7th and other dates work but I'm getting "invalid token" for May 8th and 9th? (I have not tested many other dates of the year in this way) This is from a freshly begun IDLE session: IDLE 1.2 >>> import datetime >>> datetime.datetime(2008,05,07) datetime.datetime(2008, 5, 7, 0, 0) >>> datetime.datetime(2008, 05, 08) SyntaxError: invalid token >>> datetime.datetime(2008, 05, 09) SyntaxError: invalid token After trying it a bit more, I see that writing it this way works: >>> datetime.datetime(2008,05,8) datetime.datetime(2008, 5, 8, 0, 0) So, then, why can one not use YYYY-MM-DD with these two dates and must instead switch to YYYY-MM-D? I have a feeling the explanation will be interesting and somehow make sense, though right now it seems odd. _________________________________________________________________ Keep your kids safer online with Windows Live Family Safety. http://www.windowslive.com/family_safety/overview.html?ocid=TXT_TAGLM_WL_Refresh_family_safety_052008 -------------- next part -------------- An HTML attachment was scrubbed... URL: From john at fouhy.net Sat May 17 06:29:50 2008 From: john at fouhy.net (John Fouhy) Date: Sat, 17 May 2008 16:29:50 +1200 Subject: [Tutor] datetime syntax error for May 8th and 9th 2008?? In-Reply-To: References: Message-ID: <5e58f2e40805162129s1a8638e0q340bd21289d5b995@mail.gmail.com> On 17/05/2008, Che M wrote: > >>> datetime.datetime(2008, 05, 08) > SyntaxError: invalid token It's simpler than that... Try this: >>> x = 08 File "", line 1 x = 08 ^ SyntaxError: invalid token >>> x = 010 >>> x 8 Basically, python interprets integer literals starting with 0 as octal numbers. It's an old convention from C (or earlier?). It doesn't affect strings, so int('010') == 10 (unless you use eval). HTH! -- John. From john at fouhy.net Sat May 17 06:51:14 2008 From: john at fouhy.net (John Fouhy) Date: Sat, 17 May 2008 16:51:14 +1200 Subject: [Tutor] quickly pulling marbles out of urns In-Reply-To: <13c8f3270805161443k51e2994bj3485acc6438f57e3@mail.gmail.com> References: <13c8f3270805161443k51e2994bj3485acc6438f57e3@mail.gmail.com> Message-ID: <5e58f2e40805162151x292f6365vb564fe2f683cee2c@mail.gmail.com> On 17/05/2008, Joel Miller wrote: > I have an urn with many different colors of marbles in it. I pull one > out and note the color. I do not replace it. Kent's suggest seems simplest: represent the marbles as a list of integers, where marbles[i] is the integer corresponding to marble i's colour. If that doesn't work (too many marbles?), maybe some kind of binary tree approach? e.g. a MarbleColour class which stores - the colour - the number of marbles with this colour - the number of marbles in the left subtree - the number of marbles in the right subtree where either subtree could be None (and thus have 0 marbles). Set the binary tree up initially so it's balanced by marble weight (if the marble colours are all approximately the same size at the start, you could approximate this by just filling in colours from the top in any order). Then you can randomly generate a colour by generating a random int in (0,1) and comparing with the proportions in the node. Then you just have to update the weights for the colour you choose and all nodes above it. Should be log_2(n) to pick one colour and n.log_2(n) to pick colours until you run out. -- John. From wescpy at gmail.com Sat May 17 08:38:42 2008 From: wescpy at gmail.com (wesley chun) Date: Fri, 16 May 2008 23:38:42 -0700 Subject: [Tutor] datetime syntax error for May 8th and 9th 2008?? In-Reply-To: <5e58f2e40805162129s1a8638e0q340bd21289d5b995@mail.gmail.com> References: <5e58f2e40805162129s1a8638e0q340bd21289d5b995@mail.gmail.com> Message-ID: <78b3a9580805162338r5cca9f63h2e8b829266dd2e00@mail.gmail.com> On Fri, May 16, 2008 at 9:29 PM, John Fouhy wrote: > On 17/05/2008, Che M wrote: >> >>> datetime.datetime(2008, 05, 08) >> SyntaxError: invalid token > > It's simpler than that... Try this: > >>>> x = 08 > File "", line 1 > x = 08 > ^ > SyntaxError: invalid token >>>> x = 010 >>>> x > 8 > > Basically, python interprets integer literals starting with 0 as octal > numbers. It's an old convention from C (or earlier?). It doesn't > affect strings, so int('010') == 10 (unless you use eval). che, john is correct. any leading zero (0) of an integer number will be translated as base 8 or octal, which counts by 8's: 00, 01, 02, 03, 04, 05, 06, 07, 10 (decimal/base 10: 8*1+0=8), 11 (decimal: 8*1+1=9), 12 (decimal: 8*1+2=10), 13 (decimal 8+3=11), 14, 15, 16, 17 (decimal: 15), 20 (decimal: 8*2+0=16), 21 (decimal: 8*2+1=17), etc... the problem with "08" is that because you're counting by 8s, a value of "08" is invalid because the digits "8" and "9" are not part of the octal "alphabet" or character set. that is why "07" works but not "08". as an FYI, because of this confusion, starting with Python 3.0, octal numbers will require a lowercase "o" (in the same manner as hexadecimal/base 16 numbers require an "x") after leading 0, i.e., 0o7, 0o16, etc. (Oo8 is still an invalid octal number.) hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From ricaraoz at gmail.com Fri May 16 15:01:36 2008 From: ricaraoz at gmail.com (Ricardo Araoz) Date: Fri, 16 May 2008 10:01:36 -0300 Subject: [Tutor] Iterate through dictionary values and remove item In-Reply-To: <1c2a2c590805151026s79c7bfccne522b73beff56a09@mail.gmail.com> References: <39cb7e5d0805142340v1ce25d79n2d9f90db0b5fb18e@mail.gmail.com> <1c2a2c590805150457u36f8b8e2r92a92b2eb6760d95@mail.gmail.com> <39cb7e5d0805150958l9e4b393n4a0df18005c72ea2@mail.gmail.com> <1c2a2c590805151026s79c7bfccne522b73beff56a09@mail.gmail.com> Message-ID: <482D85B0.6060904@gmail.com> Kent Johnson wrote: > On Thu, May 15, 2008 at 12:58 PM, GTXY20 wrote: >> I suspect that I need >> to get a better handle on the difference between items() and iteritems() and >> what situations would call for them respectively. > > items() returns a list, iteritems() returns an iterator. If you don't > actually need an explicit list, iteritems() saves the cost of creating > it. > >> Having said that, Kent I am not 100 percent sure of what you menat when you >> mention a two-level dict. Can you give me a very brief example? > > Your dict d would look like this: > d={ > 1: {23A:[a,b,c,d], 24A:[b,c,d]}, > 2: {23A:[a,b], 24A:[a,b,c,d]} > } > Lads... >>> d={ ... 1: {23A:[a,b,c,d], 24A:[b,c,d]}, ... 2: {23A:[a,b], 24A:[a,b,c,d]} ... } File "", line 2 1: {23A:[a,b,c,d], 24A:[b,c,d]}, ^ SyntaxError: invalid syntax >>> Let's get a proper syntax for our data before attempting to process it. From adam.clarridge at gmail.com Sat May 17 18:12:10 2008 From: adam.clarridge at gmail.com (Adam Clarridge) Date: Sat, 17 May 2008 12:12:10 -0400 Subject: [Tutor] Dictionaries or Numpy? In-Reply-To: <5e58f2e40805161708y5a2b27e8wc5bc179974d8c35e@mail.gmail.com> References: <495f2c630805161559w60b6ebbck19f07cb539ecd9a0@mail.gmail.com> <5e58f2e40805161708y5a2b27e8wc5bc179974d8c35e@mail.gmail.com> Message-ID: <495f2c630805170912x238a093apb585a6a581f255cc@mail.gmail.com> On 5/16/08, John Fouhy wrote: > > On 17/05/2008, Adam Clarridge wrote: > > I'm fairly new to Python, and I am not sure whether it would be faster > > for me to use a Dictionary data type to represent the board > > (advantages: indices can be strings or tuples, and the dictionary can > > store different types of data as well, so programming would be easier) > > or the Numpy array type (don't know much about this, but I have heard > > Numpy is faster). > > > Hi Adam, > > I believe a general rule of programming is: don't optimize until you > know you need to. I would advise using dictionaries for simplicity. > If the program turns out slower than you would like, you can use > profiling tools to figure out where in the code it is spending most of > its time. If this turns out to involve dictionary lookups, you could > then look at changing to Numpy (hint: you could use the timeit module > to benchmark dictionary access against Numpy arrays). If your program > design is good, the change should be too hard. > > > http://en.wikipedia.org/wiki/Optimization_(computer_science)#When_to_optimize > > -- > > John. Thanks for the insight - I guess I was sort of overlooking that general principle, good to be reminded. The timeit module seems like exactly what I would want later on, too. Thanks again! Adam -------------- next part -------------- An HTML attachment was scrubbed... URL: From katcipis at inf.ufsc.br Sat May 17 20:18:38 2008 From: katcipis at inf.ufsc.br (Tiago Katcipis) Date: Sat, 17 May 2008 15:18:38 -0300 Subject: [Tutor] Best way to define comparison Message-ID: <60a9403b0805171118obf21958yc09280aecfab1f92@mail.gmail.com> Im writing a class on python and i want to implement the == and != operators on it. I have read about __cmp__ and about __eq__ for == and __ne__ for ! =. My question is... who is the better to use? and if there is no better what are the advantages and disvantages of them. Some articles talk about using cmp, and others about the eq...its a little confusing :-( -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Sat May 17 21:30:46 2008 From: bgailer at gmail.com (bob gailer) Date: Sat, 17 May 2008 15:30:46 -0400 Subject: [Tutor] Best way to define comparison In-Reply-To: <60a9403b0805171118obf21958yc09280aecfab1f92@mail.gmail.com> References: <60a9403b0805171118obf21958yc09280aecfab1f92@mail.gmail.com> Message-ID: <482F3266.90105@gmail.com> Tiago Katcipis wrote: > Im writing a class on python and i want to implement the == and != > operators on it. I have read about __cmp__ and about __eq__ for == and > __ne__ for ! =. My question is... who is the better to use? and if > there is no better what are the advantages and disvantages of them. > Some articles talk about using cmp, and others about the eq...its a > little confusing :-( AFAIK either approach is OK. No advantages. (Other than writing one method vs 2). -- Bob Gailer 919-636-4239 Chapel Hill, NC From kent37 at tds.net Sun May 18 00:40:22 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 17 May 2008 18:40:22 -0400 Subject: [Tutor] Best way to define comparison In-Reply-To: <60a9403b0805171118obf21958yc09280aecfab1f92@mail.gmail.com> References: <60a9403b0805171118obf21958yc09280aecfab1f92@mail.gmail.com> Message-ID: <1c2a2c590805171540w79c79d2dhe3e5a75f201bf8a7@mail.gmail.com> On Sat, May 17, 2008 at 2:18 PM, Tiago Katcipis wrote: > Im writing a class on python and i want to implement the == and != operators > on it. I have read about __cmp__ and about __eq__ for == and __ne__ for ! =. > My question is... who is the better to use? Use __cmp__() if it meets your needs - you just have to define one method and you get all comparisons. The other special methods - "rich comparisons" - were introduced in Python 2.1 to allow additional flexibility when __cmp__() is not adequate. http://www.amk.ca/python/2.1/index.html#SECTION000500000000000000000 Kent From kent37 at tds.net Sun May 18 01:36:47 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 17 May 2008 19:36:47 -0400 Subject: [Tutor] Best way to define comparison In-Reply-To: <60a9403b0805171604h408783e7x4fe2d14ff4d2ee6d@mail.gmail.com> References: <60a9403b0805171118obf21958yc09280aecfab1f92@mail.gmail.com> <1c2a2c590805171540w79c79d2dhe3e5a75f201bf8a7@mail.gmail.com> <60a9403b0805171604h408783e7x4fe2d14ff4d2ee6d@mail.gmail.com> Message-ID: <1c2a2c590805171636m79c6620dr6aacfa5ec8fe297e@mail.gmail.com> On Sat, May 17, 2008 at 7:04 PM, Tiago Katcipis wrote: > ive been reading and really seens to be better to use cmp... i will not have > to write a method to every single operator. But when python compare > objects...like in Sets or Lists...to check for membership etc, it uses cmp > ou eq? It uses __eq__() if it is defined, otherwise __cmp__() http://docs.python.org/ref/customization.html Kent PS Please use Reply All to reply to the list From katcipis at inf.ufsc.br Sun May 18 04:29:58 2008 From: katcipis at inf.ufsc.br (Tiago Katcipis) Date: Sat, 17 May 2008 23:29:58 -0300 Subject: [Tutor] Best way to define comparison In-Reply-To: <1c2a2c590805171636m79c6620dr6aacfa5ec8fe297e@mail.gmail.com> References: <60a9403b0805171118obf21958yc09280aecfab1f92@mail.gmail.com> <1c2a2c590805171540w79c79d2dhe3e5a75f201bf8a7@mail.gmail.com> <60a9403b0805171604h408783e7x4fe2d14ff4d2ee6d@mail.gmail.com> <1c2a2c590805171636m79c6620dr6aacfa5ec8fe297e@mail.gmail.com> Message-ID: <60a9403b0805171929l5fd3af95ic658a35394fddb3f@mail.gmail.com> ops im sorry..i didnt noticed that reply just replyed to you..i thought it would go to the list. Thanks for the help best regards On Sat, May 17, 2008 at 8:36 PM, Kent Johnson wrote: > On Sat, May 17, 2008 at 7:04 PM, Tiago Katcipis > wrote: > > ive been reading and really seens to be better to use cmp... i will not > have > > to write a method to every single operator. But when python compare > > objects...like in Sets or Lists...to check for membership etc, it uses > cmp > > ou eq? > > It uses __eq__() if it is defined, otherwise __cmp__() > http://docs.python.org/ref/customization.html > > Kent > > PS Please use Reply All to reply to the list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From wcyeee at gmail.com Mon May 19 09:27:06 2008 From: wcyeee at gmail.com (wcyee) Date: Mon, 19 May 2008 03:27:06 -0400 Subject: [Tutor] Calling super in __init__ Message-ID: Hi - I wrote a custom exception class as follows: class CustomError(Exception): def __init__(self, msg): super(CustomError, self).__init__(self, msg) But this doesn't work as expected: try: raise CustomError('something bad') except CustomError, err: print err.message err.message is a blank string. I fixed this eventually by rewriting the call to the super constructor: class CustomError(Exception): def __init__(self, msg): Exception.__init__(self, msg) Now everything works, but I'm not sure I understand why super(...).__init__(...) behaves differently from Exception.__init__(...). According to the documentation, "super() only works with new-style classes". Is the problem that Exception is an "old style" class (I'm still learning what this means)? If so, how can I tell when I'm up against an "old style" class when using python? Why does super() fail silently, if this is the case? Thanks in advance for any pointers or help in understanding this! -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Mon May 19 12:40:42 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 19 May 2008 06:40:42 -0400 Subject: [Tutor] Calling super in __init__ In-Reply-To: References: Message-ID: <1c2a2c590805190340i6b1981e2qc7331379e73e8964@mail.gmail.com> On Mon, May 19, 2008 at 3:27 AM, wcyee wrote: > Hi - I wrote a custom exception class as follows: > > class CustomError(Exception): > def __init__(self, msg): > super(CustomError, self).__init__(self, msg) Should be super(CustomError, self).__init__(msg) i.e. don't repeat 'self'. > According to the documentation, "super() only works with new-style classes". > Is the problem that Exception is an "old style" class (I'm still learning > what this means)? No > If so, how can I tell when I'm up against an "old style" > class when using python? The type of a new-style class is 'type' (unless it has a custom metaclass). The type of an old-style class is 'classobj': In [20]: type(Exception) Out[20]: In [21]: class Foo: pass ....: In [22]: type(Foo) Out[22]: New-style classes have a __getattribute__() special method which is missing in old-style classes, so another way to tell is to look for __getattribute__. Kent From ptmcg at austin.rr.com Mon May 19 14:43:02 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 19 May 2008 07:43:02 -0500 Subject: [Tutor] Calling super in __init__ In-Reply-To: References: Message-ID: <003b01c8b9ad$e09a52b0$0321a8c0@AWA2> >>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Hi - I wrote a custom exception class as follows: class CustomError(Exception): def __init__(self, msg): super(CustomError, self).__init__(self, msg) But this doesn't work as expected: >>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Correct use of super would be: class CustomError(Exception): def __init__(self, msg): super(CustomError, self).__init__(msg) (Don't add self as an argument.) Exception became a new-style class in Python 2.5. -- Paul From chester_lab at fltg.net Mon May 19 20:03:47 2008 From: chester_lab at fltg.net (FT) Date: Mon, 19 May 2008 14:03:47 -0400 Subject: [Tutor] Pythoncom Tutorial Message-ID: <001b01c8b9db$068c6620$0201a8c0@brucetower> Hi! I noticed that when wanting to learn Pythoncom there is no real good accessible tutorial for it. Does anyone know where a good structured tutorial exists for the Com utilities so I can write my own screen reader program? When trying to understand all the needed variables and such for the windows commands and variables it gets confusing. I want to learn how to get the objects and its methods so I can use a python program to read and verbalize the objects as you focus on them and such. The only explanations I found either have the descriptions scattered and no examples or structure on how to use any of the com stuff. How to use the Makepy and when not to use it. How to get the objects and its list of methods to be able to work with it for screen reading purposes. Thanks in advance. Bruce From cbc at unc.edu Mon May 19 21:24:56 2008 From: cbc at unc.edu (Chris Calloway) Date: Mon, 19 May 2008 15:24:56 -0400 Subject: [Tutor] Python and Plone Boot Camps in Chapel Hill, NC Message-ID: <4831D408.30209@unc.edu> Triangle (NC) Zope and Python Users Group (TriZPUG) is proud to open registration for our fourth annual ultra-low cost Plone and Python training camps, BootCampArama 2008: http://trizpug.org/boot-camp/2008/ Registration is now open for: PyCamp: Python Boot Camp, August 4 - 8 Plone Boot Camp: Customizing Plone, July 28 - August 1 Advanced Plone Boot Camp: Plone 3 Techniques, August 4 - 8 All of these take place on the campus of the University of North Carolina at Chapel Hill in state of the art high tech classrooms, with free mass transit, low-cost accommodations with free wireless, and convenient dining options. Plone Boot Camp is taught by Joel Burton, twice chair of the Plone Foundation. Joel has logged more the 200 days at the head of Plone classrooms on four continents. See plonebootcamps.com for dozens of testimonials from Joel's students. PyCamp is taught by Chris Calloway, facilitator for TriZPUG and application analyst for the Southeast Coastal Ocean Observing System. Chris has developed PyCamp for over 1500 hours on behalf of Python user groups. Early bird registration runs through June 30. So register today! PyCamp is TriZPUG's Python Boot Camp, which takes a programmer familiar with basic programming concepts to the status of Python developer with one week of training. If you have previous scripting or programming experience and want to step into Python programming as quickly and painlessly as possible, this boot camp is for you. PyCamp is also the perfect follow-on to Plone Boot Camp: Customizing Plone the previous week. At Plone Boot Camp: Customizing Plone you will learn the essentials you need to build your Plone site and deploy it. This course is the most popular in the Plone world--for a good reason: it teaches you practical skills in a friendly, hands-on format. This bootcamp is aimed at: * people with HTML or web design experience * people with some or no Python experience * people with some or no Zope/Plone experience It covers using Plone, customizing, and deploying Plone sites. At Advanced Plone Boot Camp: Plone 3 Techniques you will learn to build a site using the best practices of Plone 3 as well as advance your skills in scripting and developing for Plone. The course covers the new technologies in Plone 3.0 and 3.1 intended for site integrators and developers: our new portlet infrastructure, viewlets, versioning, and a friendly introduction to Zope 3 component architecture. Now, updated for Plone 3.1! The course is intended for people who have experience with the basics of Plone site development and HTML/CSS. It will cover what you need to know to take advantage of these new technologies in Plone 3. For more information contact: info at trizpug.org From timmichelsen at gmx-topmail.de Mon May 19 21:36:30 2008 From: timmichelsen at gmx-topmail.de (Tim Michelsen) Date: Mon, 19 May 2008 21:36:30 +0200 Subject: [Tutor] Open a directory in the default file manager In-Reply-To: <482DAE8E.2090308@gmail.com> References: <482DAE8E.2090308@gmail.com> Message-ID: Hi! > > is there any function/module that allows me to open a directory in the > > default file manager of a operating system? > > On Windows you can use os.startfile(). > On "pure" Unices there's no such thing as filetype associations > However, if you use a desktop environment, you can spawn xdg-open (from > xdg-utils) from Python. This will autodetect gnome, kde and xfce and use > their tools (gnome-open, kfmclient, exo-open). > I think on OS X/Darwin there's a similar utility called `open'. > > You can use sys.platform to determine which system you're running on. I wasn't able to start explorer with os.startfile() I then used subprocess.call(['explorer', my_directory]) And it works. Kind regards, Timmie From timmichelsen at gmx-topmail.de Mon May 19 21:38:19 2008 From: timmichelsen at gmx-topmail.de (Tim Michelsen) Date: Mon, 19 May 2008 21:38:19 +0200 Subject: [Tutor] converting all files in a directory with subprocess In-Reply-To: <48235EEE.60404@timgolden.me.uk> References: <48235EEE.60404@timgolden.me.uk> Message-ID: Hello, just for the records: below is some code that works ### convert all t2t docs in a directory. #!/usr/bin/env python # -*- coding: utf-8 -*- import os import subprocess import fnmatch documentation_directory = './doc/' for file in os.listdir(documentation_directory): if fnmatch.fnmatch(file, '*.t2t'): ### assemble file name filepath = documentation_directory+file ### run txt2tags #subprocess.call(['txt2tags', '--target=html', '--toc', documentation_directory+file]) subprocess.call(['txt2tags', '--target=html', '--toc', filepath]) From Mike.Hansen at atmel.com Mon May 19 21:44:48 2008 From: Mike.Hansen at atmel.com (Hansen, Mike) Date: Mon, 19 May 2008 13:44:48 -0600 Subject: [Tutor] Pythoncom Tutorial In-Reply-To: <001b01c8b9db$068c6620$0201a8c0@brucetower> References: <001b01c8b9db$068c6620$0201a8c0@brucetower> Message-ID: <7941B2693F32294AAF16C26B679A258D0242A9D8@csomb01.corp.atmel.com> > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of FT > Sent: Monday, May 19, 2008 12:04 PM > To: Tutor Python ORG > Subject: [Tutor] Pythoncom Tutorial > > > Hi! > > I noticed that when wanting to learn Pythoncom there is > no real good > accessible tutorial for it. > Does anyone know where a good structured tutorial exists > for the Com > utilities so I can write my own screen reader program? > > When trying to understand all the needed variables and > such for the > windows commands and variables it gets confusing. I want to > learn how to get > the objects and its methods so I can use a python program to read and > verbalize the objects as you focus on them and such. The only > explanations I > found either have the descriptions scattered and no examples > or structure on > how to use any of the com stuff. > > How to use the Makepy and when not to use it. How to get > the objects and > its list of methods to be able to work with it for screen > reading purposes. > > Thanks in advance. > > Bruce > Python Programming on Win32 might help. There's also a couple of articles on OnLamp. http://www.oreilly.com/catalog/9781565926219/index.html Mike From collinsjames9 at gmail.com Mon May 19 21:06:31 2008 From: collinsjames9 at gmail.com (james collins) Date: Mon, 19 May 2008 15:06:31 -0400 Subject: [Tutor] env variable Message-ID: <0F91EE97-481E-4F6C-88CD-6DC36382B5E3@gmail.com> just wondering how to set up my env variable? can't import scripts because my IDLE MacPython 2.5, can't find the module scripts. i created the file with textwrangler and stored them in my home folder in a folder i called python, on a macbook pro running mac os 10.5.2 From srilyk at gmail.com Mon May 19 23:28:47 2008 From: srilyk at gmail.com (W W) Date: Mon, 19 May 2008 16:28:47 -0500 Subject: [Tutor] timed functions? Timeouts? Message-ID: <333efb450805191428u42872d06p1d94e575ef670659@mail.gmail.com> Hi, I'm having trouble finding any information (or if it's possible) on this particular topic. Specifically, there's a feature in javascript that I want to emulate. this is an example I pulled from a webmonkey tutorial -------------------------- function writeTime() { // get a date object var today = new Date(); // ask the object for some information var hours = today.getHours(); var minutes = today.getMinutes(); var seconds = today.getSeconds(); // fixTime makes the minutes and seconds look right // it just sticks a zero in front of numbers less than 10 minutes = fixTime(minutes); seconds = fixTime(seconds); // put together the time string and write it out var the_time = hours + ":" + minutes + ":" + seconds; window.document.the_form.the_text.value = the_time; // run this function again in half a second the_timeout= setTimeout('writeTime();',500); } function fixTime(the_time) { if (the_time <10) { the_time = "0" + the_time; } return the_time; } --------------- The specific bit I'm looking at is this line the_timeout = setTimeout('writeTime();',500); basically it calls the function again in 500ms, but rather than pausing, I guess it spawns a new thread? I'm not really sure. >From the little experience I have in JS it appears that multiple "timers" can be running at a time, all the code "in between" the timeouts will execute, and when the timeout is finished it will execute whatever the command is (in this case, 'writeTime();'). So I'm trying to find out a pythonic equivalent (if there is one). So far Googling for "python timeout" gives me no helpful results, and "python threading" gives me some examples that are close to what I think I'm looking for. Now, when I look at that example and try to translate the timeout to what I think is going on "behind the scenes" I'm pretty sure it spawns a thread that does something similar to this: 1 import time 2 3 def timer(end, exe): 4 start = time.time() 5 while True: 6 now = time.time() 7 if (now - start) >= end: 8 break 9 exe() 10 11 def execute_this(): 12 for x in range(1, 10): 13 print x 14 15 timer(5, execute_this) Am I correct? Is there a python built-in for this? Where should I go to learn more? Is there anything "wrong" with using a function like this? Thanks in advance, Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi From marilyn at deliberate.com Mon May 19 23:21:16 2008 From: marilyn at deliberate.com (Marilyn Davis) Date: Mon, 19 May 2008 14:21:16 -0700 (PDT) Subject: [Tutor] New Style Classes, __getitem__ and iteration Message-ID: <48750.66.218.47.125.1211232076.squirrel@mail.tigertech.net> Hi Tutors and Tutees, I've been teaching Python quite a while and a brilliant student asked a question that made me realize a big hole in my understanding. I think it is really magical that, when I define __getitem__ on classic classes, the built-in iterator uses it. But, when I make the same class as a new style class, I lose this behavior. I didn't realize that something was lost in defining a new style class. Maybe it's something else that I'm missing. Thank you for your insights. Marilyn p.s. Here's some code that demonstrates my confusion: #!/usr/bin/env python class Circle: def __init__(self, data, times): """Put the 'data' in a circle that goes around 'times' times.""" self.data = data self.times = times def __getitem__(self, i): """circle[i] --> Circle.__getitem__(circle, i).""" l_self = len(self) if i >= self.times * l_self: raise IndexError, \ "Error raised: Circle object only goes around %d times"\ % self.times return self.data[i % l_self] def __len__(self): return len(self.data) class NewCircle(list): def __init__(self, data, times): list.__init__(self, data) self.times = times def __getitem__(self, i): l_self = len(self) if i >= self.times * l_self: raise IndexError, \ "Error raised: NewCircle object only goes around %d times"\ % self.times return list.__getitem__(self, i % l_self) def main(): circle = Circle("around", 3) print sorted(circle) new_circle = NewCircle("around", 3) print sorted(new_circle) main() """ OUTPUT: $ ./circle_question.py ['a', 'a', 'a', 'd', 'd', 'd', 'n', 'n', 'n', 'o', 'o', 'o', 'r', 'r', 'r', 'u', 'u', 'u'] ['a', 'd', 'n', 'o', 'r', 'u'] $ """ From wescpy at gmail.com Tue May 20 00:09:33 2008 From: wescpy at gmail.com (wesley chun) Date: Mon, 19 May 2008 15:09:33 -0700 Subject: [Tutor] New Style Classes, __getitem__ and iteration In-Reply-To: <48750.66.218.47.125.1211232076.squirrel@mail.tigertech.net> References: <48750.66.218.47.125.1211232076.squirrel@mail.tigertech.net> Message-ID: <78b3a9580805191509y5417f107h3091f5f051da0378@mail.gmail.com> > I think it is really magical that, when I define __getitem__ on classic > classes, the built-in iterator uses it. > > But, when I make the same class as a new style class, I lose this behavior. > > I didn't realize that something was lost in defining a new style class. > Maybe it's something else that I'm missing. marilyn, the problem isn't related to you using a new-style class. if you ported the classic class directly, it works just fine: class Circle2(object): def __init__(self, data, times): """Put the 'data' in a circle that goes around 'times' times.""" self.data = data self.times = times def __getitem__(self, i): """circle[i] --> Circle.__getitem__(circle, i).""" l_self = len(self) print 'i, self.times, l_self:', i, self.times, l_self if i >= self.times * l_self: raise IndexError, \ "Error raised: Circle object only goes around %d times"\ % self.times return self.data[i % l_self] def __len__(self): return len(self.data) $ ./circle_question.py ['a', 'a', 'a', 'd', 'd', 'd', 'n', 'n', 'n', 'o', 'o', 'o', 'r', 'r', 'r', 'u', 'u', 'u'] to really start to debug your code, change the call from sorted() to list(), as in: circle = Circle2("around", 3) print list(circle) the output will change to: $ ./circle_question.py ['a', 'r', 'o', 'u', 'n', 'd', 'a', 'r', 'o', 'u', 'n', 'd', 'a', 'r', 'o', 'u', 'n', 'd'] when you call sorted() or list() on your object, it attempts to build a new list consisting of the return values of each getitem() call. the difference is that with your original class, it doesn't "end" until the count has surpassed the number of times you want it (3) and the number of elements total (6), meaning it stops when you go beyond 18. i put in a tiny print statement in the __getitem__() code in all 3 classes. in the original classic class and my port to new-style classes, that print statement told me everything i just said above. the thing that is different about your new-style class is that it subclasses list. in your class that derives from list, it did not execute your __getitem__() method even once. that clues me in on my belief that the reason why it doesn't work is because it is *already* a list. calling list() or sorted() on it attempts to create a new list, but since the original data structure is a list, it merely just copies all of its references without using getitem(). without looking at the source code, i can't confirm this. can anyone else "finish the sentence i started?" hope this partially helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From kent37 at tds.net Tue May 20 01:29:15 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 19 May 2008 19:29:15 -0400 Subject: [Tutor] New Style Classes, __getitem__ and iteration In-Reply-To: <48750.66.218.47.125.1211232076.squirrel@mail.tigertech.net> References: <48750.66.218.47.125.1211232076.squirrel@mail.tigertech.net> Message-ID: <1c2a2c590805191629y631fb6acsefed8d71b4a93ac4@mail.gmail.com> On Mon, May 19, 2008 at 5:21 PM, Marilyn Davis wrote: > Hi Tutors and Tutees, > > I've been teaching Python quite a while and a brilliant student asked a > question that made me realize a big hole in my understanding. > > I think it is really magical that, when I define __getitem__ on classic > classes, the built-in iterator uses it. > > But, when I make the same class as a new style class, I lose this behavior. There are a couple of possible explanations, I'm not sure which is right without looking into the implementation of sorted(). Wesley may be right, that sorted() sees that its argument is a list and uses a lower-level access than __getitem__() to copy the list for sorting. In general, list operations are not implemented in terms of __getitem__(). In other words, you can't subclass list(), override __getitem__() and expect to change how all list operations work. __getitem__() is not a bottleneck procedure. It's also possible that sorted() just expects a sequence and uses the iterator protocol to access the values of its argument. This is certainly the case with your Circle class. This class doesn't define an __iter__() method so Python uses the older iteration protocol based on __getitem__(). With NewCircle, even if sorted() is accessing it with an iterator, your __getitem__() will not be called because list implements __iter__() so iteration will use the modern iteration protocol. ------------------ OK, I looked at the source a bit. builtin_sorted(), in bltinmodule.c, calls PySequence_List() to create a list to sort. PySequence_List(), in abstract.c, creates a new list, then calls _PyList_Extend() to add the new items. _PyList_Extend(), in listobject.c, calls listextend() which is the implementation of list.extend() listextend() is clearly optimized for lists and tuples. I didn't dig farther than that. For other data types it iterates over the argument. A good discussion of the iterator protocol is here: http://www.python.org/doc/2.2.3/whatsnew/node4.html Kent From alan.gauld at btinternet.com Tue May 20 02:00:49 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 20 May 2008 01:00:49 +0100 Subject: [Tutor] Pythoncom Tutorial References: <001b01c8b9db$068c6620$0201a8c0@brucetower> Message-ID: "FT" wrote > I noticed that when wanting to learn Pythoncom there is no real > good > accessible tutorial for it. > Does anyone know where a good structured tutorial exists for the > Com > utilities so I can write my own screen reader program? Assuming you mean Pythonwin, the libraries for accessing the Windows API that come as part of winall then the best tutorial is the one in Mark Hammond's book "Python Progeramming on Win32" But it helps if you have a basic understanding of COM generally, for example using it from within VBScript. Also familiarity with the vanilla Windows API documentation helps and that is not really part of the Pytthon access library. You should find plenty of tutorials on the raw API on the net. > the objects and its methods so I can use a python program to read > and > verbalize the objects as you focus on them and such. The only > explanations I > found either have the descriptions scattered and no examples or > structure on > how to use any of the com stuff. You might find ctypes is better for that kind of thing. COM is better when you want to remotely control another application but for interceprting low level Windows messages ctypes seems like a better approach - although I confess to not having tried it! -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld > > How to use the Makepy and when not to use it. How to get the > objects and > its list of methods to be able to work with it for screen reading > purposes. > > Thanks in advance. > > Bruce > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Tue May 20 02:07:18 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 20 May 2008 01:07:18 +0100 Subject: [Tutor] converting all files in a directory with subprocess References: <48235EEE.60404@timgolden.me.uk> Message-ID: "Tim Michelsen" wrote in > below is some code that works > > ### convert all t2t docs in a directory. > for file in os.listdir(documentation_directory): > if fnmatch.fnmatch(file, '*.t2t'): You might be able to do this more succinctly using the glob.glob() function... Just a thought, Alan G. From alan.gauld at btinternet.com Tue May 20 02:04:59 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 20 May 2008 01:04:59 +0100 Subject: [Tutor] env variable References: <0F91EE97-481E-4F6C-88CD-6DC36382B5E3@gmail.com> Message-ID: "james collins" wrote > just wondering how to set up my env variable? > can't import scripts because my IDLE MacPython 2.5, can't find the > module scripts. You should try setting your PYTHONPATH environment vaqriable in your bash shell. .profile or .login are the two files that you can use and I've forgotten which is recommended for environment variables. Both work but one can get called multiple times if I remember correctly. > i created the file with textwrangler and stored them in my home > folder in a folder i called python, on a macbook pro running mac os > 10.5.2 In bash the line should look like: export PYTHONPATH=~/python HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Tue May 20 02:12:42 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 20 May 2008 01:12:42 +0100 Subject: [Tutor] timed functions? Timeouts? References: <333efb450805191428u42872d06p1d94e575ef670659@mail.gmail.com> Message-ID: "W W" wrote > The specific bit I'm looking at is this line > > the_timeout = setTimeout('writeTime();',500); > > basically it calls the function again in 500ms, but rather than > pausing, I guess it spawns a new thread? I'm not really sure. You might be able to use select() for this. Or if in a GUI environment just create a timer. Or create a thread and use sleep() within the thread. Just some ideas at 01:10am. So they are probably mince! Night all, Alan G From kent37 at tds.net Tue May 20 03:23:58 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 19 May 2008 21:23:58 -0400 Subject: [Tutor] timed functions? Timeouts? In-Reply-To: <333efb450805191428u42872d06p1d94e575ef670659@mail.gmail.com> References: <333efb450805191428u42872d06p1d94e575ef670659@mail.gmail.com> Message-ID: <1c2a2c590805191823w54ec0fc3gc5127ee77ad4bd2b@mail.gmail.com> On Mon, May 19, 2008 at 5:28 PM, W W wrote: > Now, when I look at that example and try to translate the timeout to > what I think is going on "behind the scenes" I'm pretty sure it spawns > a thread that does something similar to this: > > 1 import time > 2 > 3 def timer(end, exe): > 4 start = time.time() > 5 while True: > 6 now = time.time() > 7 if (now - start) >= end: > 8 break > 9 exe() > 10 > 11 def execute_this(): > 12 for x in range(1, 10): > 13 print x > 14 > 15 timer(5, execute_this) > > Am I correct? Is there a python built-in for this? Where should I go > to learn more? Is there anything "wrong" with using a function like > this? You are pretty much on the right track but you should put a time.sleep() in your loop or it will chew up all available CPU time. Even better, figure out how long you need to sleep. The sched module in the standard library might help though it doesn't seem to do any threading. Also look at these recipes: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496800 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/114644 Kent From chester_lab at fltg.net Tue May 20 03:43:40 2008 From: chester_lab at fltg.net (FT) Date: Mon, 19 May 2008 21:43:40 -0400 Subject: [Tutor] Pythoncom Tutorial References: <001b01c8b9db$068c6620$0201a8c0@brucetower> <7941B2693F32294AAF16C26B679A258D0242A9D8@csomb01.corp.atmel.com> Message-ID: <003c01c8ba1a$f7722c70$0201a8c0@brucetower> > Hi! > > I noticed that when wanting to learn Pythoncom there is > no real good > accessible tutorial for it. > Does anyone know where a good structured tutorial exists > for the Com > utilities so I can write my own screen reader program? > Python Programming on Win32 might help. There's also a couple of articles on OnLamp. http://www.oreilly.com/catalog/9781565926219/index.html Mike Hi! A book is nice if you can see to read it. Still searching for the best way to go on this. It was suggested to go to the API of windowes or ctypes. I confress that I have not used ctypes when just hoping to find a python format to get such things as the focus information when jumping from window to window. Or tag along saying what is going on at the moment and location you are in. The name fo the object, and the variable or data info at the moment in time... Bruce From srilyk at gmail.com Tue May 20 05:23:17 2008 From: srilyk at gmail.com (W W) Date: Mon, 19 May 2008 22:23:17 -0500 Subject: [Tutor] timed functions? Timeouts? In-Reply-To: <1c2a2c590805191823w54ec0fc3gc5127ee77ad4bd2b@mail.gmail.com> References: <333efb450805191428u42872d06p1d94e575ef670659@mail.gmail.com> <1c2a2c590805191823w54ec0fc3gc5127ee77ad4bd2b@mail.gmail.com> Message-ID: <333efb450805192023oca201fbvb1334f3a98affc9b@mail.gmail.com> Those examples are really helpful and I'm pretty sure they'll do what I need, I'll just have to play with them a little more. I do have a question about one of the examples though! Specifically this part: 4 class Operation(threading._Timer): 5 def __init__(self, *args, **kwargs): 6 threading._Timer.__init__(self, *args, **kwargs) 7 self.setDaemon(True) So in trying to understand the class definition, I found this: "In Python, the ancestor of a class is simply listed in parentheses immediately after the class name." So does that mean that Operation is similar or the same as say: Operation = threading._Timer? Then I'm a little confused by the * and ** - they look just like the pointer and pointer to a pointer in C++, but do they perform the same function in python? TIA, Wayne On Mon, May 19, 2008 at 8:23 PM, Kent Johnson wrote: > On Mon, May 19, 2008 at 5:28 PM, W W wrote: >> Now, when I look at that example and try to translate the timeout to >> what I think is going on "behind the scenes" I'm pretty sure it spawns >> a thread that does something similar to this: >> >> 1 import time >> 2 >> 3 def timer(end, exe): >> 4 start = time.time() >> 5 while True: >> 6 now = time.time() >> 7 if (now - start) >= end: >> 8 break >> 9 exe() >> 10 >> 11 def execute_this(): >> 12 for x in range(1, 10): >> 13 print x >> 14 >> 15 timer(5, execute_this) >> >> Am I correct? Is there a python built-in for this? Where should I go >> to learn more? Is there anything "wrong" with using a function like >> this? > > You are pretty much on the right track but you should put a > time.sleep() in your loop or it will chew up all available CPU time. > Even better, figure out how long you need to sleep. > > The sched module in the standard library might help though it doesn't > seem to do any threading. Also look at these recipes: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496800 > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/114644 > > Kent > -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi From wcyeee at gmail.com Tue May 20 07:17:28 2008 From: wcyeee at gmail.com (wcyee) Date: Tue, 20 May 2008 01:17:28 -0400 Subject: [Tutor] Calling super in __init__ In-Reply-To: <003b01c8b9ad$e09a52b0$0321a8c0@AWA2> References: <003b01c8b9ad$e09a52b0$0321a8c0@AWA2> Message-ID: Kent and Paul, Thanks very much for your help! On Mon, May 19, 2008 at 8:43 AM, Paul McGuire wrote: > >>>>>>>>>>>>>>>>>>>>>>>>>>>>>> > Hi - I wrote a custom exception class as follows: > > class CustomError(Exception): > def __init__(self, msg): > super(CustomError, self).__init__(self, msg) > > But this doesn't work as expected: > >>>>>>>>>>>>>>>>>>>>>>>>>>>>>> > > Correct use of super would be: > > class CustomError(Exception): > def __init__(self, msg): > super(CustomError, self).__init__(msg) > > (Don't add self as an argument.) > > Exception became a new-style class in Python 2.5. > > -- Paul > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From pine508 at hotmail.com Tue May 20 09:01:50 2008 From: pine508 at hotmail.com (Che M) Date: Tue, 20 May 2008 03:01:50 -0400 Subject: [Tutor] datetime syntax error for May 8th and 9th 2008?? In-Reply-To: <78b3a9580805162338r5cca9f63h2e8b829266dd2e00@mail.gmail.com> References: <5e58f2e40805162129s1a8638e0q340bd21289d5b995@mail.gmail.com> <78b3a9580805162338r5cca9f63h2e8b829266dd2e00@mail.gmail.com> Message-ID: > Date: Fri, 16 May 2008 23:38:42 -0700 > From: wescpy at gmail.com > To: pine508 at hotmail.com; john at fouhy.net > Subject: Re: [Tutor] datetime syntax error for May 8th and 9th 2008?? > CC: tutor at python.org > > On Fri, May 16, 2008 at 9:29 PM, John Fouhy wrote: > > On 17/05/2008, Che M wrote: > >> >>> datetime.datetime(2008, 05, 08) > >> SyntaxError: invalid token > > > > It's simpler than that... Try this: > > > >>>> x = 08 > > File "", line 1 > > x = 08 > > ^ > > SyntaxError: invalid token > >>>> x = 010 > >>>> x > > 8 > > > > Basically, python interprets integer literals starting with 0 as octal > > numbers. It's an old convention from C (or earlier?). It doesn't > > affect strings, so int('010') == 10 (unless you use eval). > > > che, > > john is correct. any leading zero (0) of an integer number will be > translated as base 8 or octal, which counts by 8's: > > 00, 01, 02, 03, 04, 05, 06, 07, 10 (decimal/base 10: 8*1+0=8), > 11 (decimal: 8*1+1=9), 12 (decimal: 8*1+2=10), 13 (decimal 8+3=11), > 14, 15, 16, 17 (decimal: 15), 20 (decimal: 8*2+0=16), 21 (decimal: > 8*2+1=17), etc... > > the problem with "08" is that because you're counting by 8s, a value > of "08" is invalid because the digits "8" and "9" are not part of the > octal "alphabet" or character set. that is why "07" works but not > "08". > > as an FYI, because of this confusion, starting with Python 3.0, octal > numbers will require a lowercase "o" (in the same manner as > hexadecimal/base 16 numbers require an "x") after leading 0, i.e., > 0o7, 0o16, etc. (Oo8 is still an invalid octal number.) > > hope this helps! > -- wesley > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Thank you, Wesley, that is helpful and interesting. Best regards, Che _________________________________________________________________ E-mail for the greater good. Join the i?m Initiative from Microsoft. http://im.live.com/Messenger/IM/Join/Default.aspx?source=EML_WL_ GreaterGood -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue May 20 11:42:01 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 20 May 2008 10:42:01 +0100 Subject: [Tutor] Pythoncom Tutorial References: <001b01c8b9db$068c6620$0201a8c0@brucetower><7941B2693F32294AAF16C26B679A258D0242A9D8@csomb01.corp.atmel.com> <003c01c8ba1a$f7722c70$0201a8c0@brucetower> Message-ID: "FT" wrote > A book is nice if you can see to read it. Still searching for the > best > way to go on this. It was suggested to go to the API of windowes or > ctypes. > I confress that I have not used ctypes when just hoping to find a > python > format to get such things as the focus information when jumping from > window ctypes is a Python solution to accessing the windows API. It avoids COM which is an extra layer of complexity. You can also use the pythonwin package without COM and access the API that way but there is little to choose between pythonwin and ctypes inthat case and ctypes seems to be a bit more powerful with the low level APIs. At least that's my impression. I doubt if you will find a high level Python solution to very platform specific things like grabbing focus, screen scraping etc You will need to get your hands dirty and use the Win32 API functions I think. Alan G From kent37 at tds.net Tue May 20 14:18:06 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 20 May 2008 08:18:06 -0400 Subject: [Tutor] timed functions? Timeouts? In-Reply-To: <333efb450805192023oca201fbvb1334f3a98affc9b@mail.gmail.com> References: <333efb450805191428u42872d06p1d94e575ef670659@mail.gmail.com> <1c2a2c590805191823w54ec0fc3gc5127ee77ad4bd2b@mail.gmail.com> <333efb450805192023oca201fbvb1334f3a98affc9b@mail.gmail.com> Message-ID: <1c2a2c590805200518q1e7b09e9g856ad1fdc2384c3d@mail.gmail.com> On Mon, May 19, 2008 at 11:23 PM, W W wrote: > Those examples are really helpful and I'm pretty sure they'll do what > I need, I'll just have to play with them a little more. > > I do have a question about one of the examples though! > > Specifically this part: > > 4 class Operation(threading._Timer): > 5 def __init__(self, *args, **kwargs): > 6 threading._Timer.__init__(self, *args, **kwargs) > 7 self.setDaemon(True) > > So in trying to understand the class definition, I found this: > > "In Python, the ancestor of a class is simply listed in parentheses > immediately after the class name." > > So does that mean that Operation is similar or the same as say: > > Operation = threading._Timer? No. class Operation(threading._Timer) creates a new class called Operation that inherits from threading._Timer. I.e. threading._Timer is the base class, or superclass, of Operation. Operation = threading._Timer this just makes the name Operation be an alias for threading._Timer; it doesn't create a new class. > Then I'm a little confused by the * and ** - they look just like the > pointer and pointer to a pointer in C++, but do they perform the same > function in python? No, these are not pointers, they allow passing arbitrary lists and dicts of arguments. I don't know of a good writeup of this syntax; here are some pointers: http://bytes.com/forum/thread25464.html Kent From listas.condhor at gmail.com Tue May 20 17:26:51 2008 From: listas.condhor at gmail.com (Laureano Arcanio) Date: Tue, 20 May 2008 12:26:51 -0300 Subject: [Tutor] listing classes Message-ID: <759f137c0805200826t29f4e397nb59d2ce12ccf3c47@mail.gmail.com> Hi All, I need to have a listing of all classes defined inside a class body, something like this: class A(object): class B(object): pass class C(object): pass(object): and i need to get the classes to instantiate them.. something like this. classes =[A,B] Any ideas ? do i need meta classes or something ? Thanks in advice. -------------- next part -------------- An HTML attachment was scrubbed... URL: From thomas.pani at gmail.com Tue May 20 18:47:28 2008 From: thomas.pani at gmail.com (Thomas Pani) Date: Tue, 20 May 2008 18:47:28 +0200 Subject: [Tutor] listing classes In-Reply-To: <759f137c0805200826t29f4e397nb59d2ce12ccf3c47@mail.gmail.com> References: <759f137c0805200826t29f4e397nb59d2ce12ccf3c47@mail.gmail.com> Message-ID: <483300A0.8070509@gmail.com> Hi, dir(A) will essentially give you what you want (and a little more) If you're only interested in classes, you can do something like: import types [ name for name in dir(A) if type(eval('A.'+name)) == types.ClassType ] Thomas Laureano Arcanio wrote: > Hi All, > > I need to have a listing of all classes defined inside a class body, > something like this: > > class A(object): > class B(object): > pass > class C(object): > pass(object): > > and i need to get the classes to instantiate them.. something like this. > > classes =[A,B] > > Any ideas ? do i need meta classes or something ? > > Thanks in advice. > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From python at bdurham.com Tue May 20 18:59:31 2008 From: python at bdurham.com (python at bdurham.com) Date: Tue, 20 May 2008 12:59:31 -0400 Subject: [Tutor] listing classes In-Reply-To: <483300A0.8070509@gmail.com> References: <759f137c0805200826t29f4e397nb59d2ce12ccf3c47@mail.gmail.com> <483300A0.8070509@gmail.com> Message-ID: <1211302771.24360.1254178455@webmail.messagingengine.com> Thomas, > import types > [ name for name in dir(A) if type(eval('A.'+name)) == types.ClassType ] The == types.ClassType doesn't seem to pick out the classes. Also, I think you should be returning eval( name ) vs. name so that the OP gets a list of objects vs. names? (My take on what the poster wanted). Malcolm From kent37 at tds.net Tue May 20 19:48:03 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 20 May 2008 13:48:03 -0400 Subject: [Tutor] listing classes In-Reply-To: <483300A0.8070509@gmail.com> References: <759f137c0805200826t29f4e397nb59d2ce12ccf3c47@mail.gmail.com> <483300A0.8070509@gmail.com> Message-ID: <1c2a2c590805201048q15dd20d3y8c50c9887fa51a7b@mail.gmail.com> On Tue, May 20, 2008 at 12:47 PM, Thomas Pani wrote: > Hi, > > dir(A) will essentially give you what you want (and a little more) > > If you're only interested in classes, you can do something like: > > import types > [ name for name in dir(A) if type(eval('A.'+name)) == types.ClassType ] There is no need to use eval() here. Python has powerful introspection capabilities - use getattr() to get a named attribute of an object. For example: In [1]: class A: ...: class B: ...: pass ...: class C: ...: pass In [2]: dir(A) Out[2]: ['B', 'C', '__doc__', '__module__'] In [3]: type(A.B) Out[3]: In [4]: type(A) Out[4]: In [5]: [ name for name in dir(A) if type(getattr(A, name))==type(A) ] Out[5]: ['B', 'C'] Note: types.ClassObj is the type of old-style classes. The OP used new-style classes which are of type type. Using type(A) for the comparison means it will work with either kind of classes as long as they are the same. You could also use inspect.isclass() to decide if it is a class. Kent From kent37 at tds.net Tue May 20 20:04:21 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 20 May 2008 14:04:21 -0400 Subject: [Tutor] Fwd: timed functions? Timeouts? In-Reply-To: <333efb450805200931o3d83d397mcd76d0c8dc84aad@mail.gmail.com> References: <333efb450805191428u42872d06p1d94e575ef670659@mail.gmail.com> <1c2a2c590805191823w54ec0fc3gc5127ee77ad4bd2b@mail.gmail.com> <333efb450805192023oca201fbvb1334f3a98affc9b@mail.gmail.com> <1c2a2c590805200518q1e7b09e9g856ad1fdc2384c3d@mail.gmail.com> <333efb450805200931o3d83d397mcd76d0c8dc84aad@mail.gmail.com> Message-ID: <1c2a2c590805201104v74bbd31bqa316891f88b28584@mail.gmail.com> Forwarding to the list. ---------- Forwarded message ---------- From: W W Date: Tue, May 20, 2008 at 12:31 PM Subject: Re: [Tutor] timed functions? Timeouts? To: Kent Johnson On Tue, May 20, 2008 at 7:18 AM, Kent Johnson wrote: >> Then I'm a little confused by the * and ** - they look just like the >> pointer and pointer to a pointer in C++, but do they perform the same >> function in python? > > No, these are not pointers, they allow passing arbitrary lists and > dicts of arguments. I don't know of a good writeup of this syntax; > here are some pointers: > http://bytes.com/forum/thread25464.html Ahhh, now I see (I think). Here's what I've discovered. The * unpacks the list into a tuple, creating a "new" variable that as far as I can tell, dies when the function ends. ** creates a copy of the dictionary, rather than passing the actual dictionary, so it's possible to operate on it, leaving the original dict intact. Neither value is actually considered an argument: >>> def SomeFunction(**foo): ... print foo ... >>> mydict = {'abc':123} >>> SomeFunction(mydict) Traceback (most recent call last): File "", line 1, in TypeError: SomeFunction() takes exactly 0 arguments (1 given) >>> SomeFunction(**mydict) {'abc': 123} ---- Using a list without * doesn't create an error at all, instead it yields results I didn't expect: >>> def SomeFunction(*foo): ... print foo ... >>> mylist = ['a', 'b', 'c'] >>> SomeFunction(mylist) (['a', 'b', 'c'],) ---- Specifically, it doesn't unpack the list, it just packs the list into a tuple. With a little more experimentation I've discovered that you can manually enter data, instead of using a list: >>> def another_function(*foo): ... print foo ... >>> another_function('hello', 'spork', 1,2,3) ('hello', 'spork', 1, 2, 3) Now I just have to figure out exactly how thread/threading uses these tuples! Thanks again! -Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi From alan.gauld at btinternet.com Tue May 20 20:10:27 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 20 May 2008 19:10:27 +0100 Subject: [Tutor] listing classes References: <759f137c0805200826t29f4e397nb59d2ce12ccf3c47@mail.gmail.com> Message-ID: "Laureano Arcanio" wrote > I need to have a listing of all classes defined inside a class body, > something like this: > > class A(object): > class B(object): > pass > class C(object): > pass(object): Others have answered but I'm curious why you would want to have such a structure. Defining nested classes is a fairly unusual construct only used under fairly specific conditions. It also limits reuse opportunities and flexibility quite a bit. Is there any reason why you can't just define the classes individually and put them in a list or dictionary? That would be much simpler. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Tue May 20 20:12:08 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 20 May 2008 19:12:08 +0100 Subject: [Tutor] timed functions? Timeouts? References: <333efb450805191428u42872d06p1d94e575ef670659@mail.gmail.com><1c2a2c590805191823w54ec0fc3gc5127ee77ad4bd2b@mail.gmail.com><333efb450805192023oca201fbvb1334f3a98affc9b@mail.gmail.com> <1c2a2c590805200518q1e7b09e9g856ad1fdc2384c3d@mail.gmail.com> Message-ID: "Kent Johnson" wrote >> Then I'm a little confused by the * and ** - they look just like >> the >> pointer and pointer to a pointer in C++, but do they perform the >> same >> function in python? > > No, these are not pointers, they allow passing arbitrary lists and > dicts of arguments. I don't know of a good writeup of this syntax; Soince you (the OP) seem to know some C the */** parameters are somewhat similar to varargs in C. (as used in functions like printf) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From moishyyehuda at gmail.com Tue May 20 23:33:38 2008 From: moishyyehuda at gmail.com (Moishy Gluck) Date: Tue, 20 May 2008 17:33:38 -0400 Subject: [Tutor] timed functions? Timeouts? In-Reply-To: References: <333efb450805191428u42872d06p1d94e575ef670659@mail.gmail.com> <1c2a2c590805191823w54ec0fc3gc5127ee77ad4bd2b@mail.gmail.com> <333efb450805192023oca201fbvb1334f3a98affc9b@mail.gmail.com> <1c2a2c590805200518q1e7b09e9g856ad1fdc2384c3d@mail.gmail.com> Message-ID: <187d38240805201433j3fd4269cxb374fb1c9e244822@mail.gmail.com> #A single " * " accepts arbitrary amount of unnamed parameters. Two " ** " accepts an arbitrary amount of unnamed parameters. # Using asterisk. def FuncOne(*list, **dict): for color in list: print color print "" for [color, value] in dict.items(): print color.ljust(5), ":", value # Not using asterisk. def FuncTwo(list, dict): for color in list: print color print "" for [color, value] in dict.items(): print color.ljust(5), ":", value #A single " * " turns a list into unnamed parameters. Two " ** " dictionary in named parameters. colors = ["red", "green", "blue"] rgbValues = {"red": "ff0000", "green": "00ff00", "blue": "0000ff", } print "FuncOne:\n" # Using asterisk. FuncOne(*colors, **rgbValues) print "\n\nFuncTwo:\n" # Not using asterisk. FuncTwo(colors, rgbValues) --------------- outputs to: FuncOne: red green blue blue : 0000ff green : 00ff00 red : ff0000 FuncTwo: red green blue blue : 0000ff green : 00ff00 red : ff0000 On Tue, May 20, 2008 at 2:12 PM, Alan Gauld wrote: > > "Kent Johnson" wrote > > Then I'm a little confused by the * and ** - they look just like the >>> pointer and pointer to a pointer in C++, but do they perform the same >>> function in python? >>> >> >> No, these are not pointers, they allow passing arbitrary lists and >> dicts of arguments. I don't know of a good writeup of this syntax; >> > > Soince you (the OP) seem to know some C the */** parameters > are somewhat similar to varargs in C. (as used in functions like > printf) > > HTH, > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From cappy2112 at gmail.com Wed May 21 01:34:07 2008 From: cappy2112 at gmail.com (Tony Cappellini) Date: Tue, 20 May 2008 16:34:07 -0700 Subject: [Tutor] Re Open a directory in the default file manager Message-ID: <8249c4ac0805201634xde3c9f9ue41705253daa9be4@mail.gmail.com> Message: 2 Date: Thu, 15 May 2008 20:10:05 +0200 From: Tim Michelsen Subject: [Tutor] Open a directory in the default file manager To: tutor at python.org Message-ID: Content-Type: text/plain; charset=ISO-8859-15; format=flowed Hello, >>is there any function/module that allows me to open a directory in the >>default file manager of a operating system? The os module gives you file & directory management functions, but not a graphical file manager. The os module also has many functions for spawning other processes This doesn't open a File Manager- per se, it opens a platform independent File Browser, and from it you can do some limited functions that a file manager would. Try EasyDialogs (On Windows you need to install it first, it's part of the Mac python distribution, but is not for Windows. EasyDialogs.AskFolder also EasyDialogs.AskFileForOpen -------------- next part -------------- An HTML attachment was scrubbed... URL: From cappy2112 at gmail.com Wed May 21 01:42:26 2008 From: cappy2112 at gmail.com (Tony Cappellini) Date: Tue, 20 May 2008 16:42:26 -0700 Subject: [Tutor] Tutor Open a directory in the default file manager Message-ID: <8249c4ac0805201642n57ebad04r579474f39051ae9d@mail.gmail.com> *Tim Michelsen* timmichelsen at gmx-topmail.de *Mon May 19 21:36:30 CEST 2008* - Previous message: [Tutor] Open a directory in the default file manager - Next message: [Tutor] Getting started with Python - *Messages sorted by:* [ date ] [ thread ] [ subject ] [ author ] ** >>I wasn't able to start explorer with os.startfile() You need to use it like this os.startfile('file.txt') but it will launch the application associated with .TXT files- which could be anything on Windows. It wont launch Explorer unless you have Explorer associated with that extension. -------------- next part -------------- An HTML attachment was scrubbed... URL: From dkuhlman at rexx.com Wed May 21 02:01:26 2008 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Tue, 20 May 2008 17:01:26 -0700 Subject: [Tutor] listing classes In-Reply-To: <1c2a2c590805201048q15dd20d3y8c50c9887fa51a7b@mail.gmail.com> References: <759f137c0805200826t29f4e397nb59d2ce12ccf3c47@mail.gmail.com> <483300A0.8070509@gmail.com> <1c2a2c590805201048q15dd20d3y8c50c9887fa51a7b@mail.gmail.com> Message-ID: <20080521000126.GA59289@cutter.rexx.com> On Tue, May 20, 2008 at 01:48:03PM -0400, Kent Johnson wrote: > > Note: types.ClassObj is the type of old-style classes. The OP used > new-style classes which are of type type. Using type(A) for the > comparison means it will work with either kind of classes as long as > they are the same. You could also use inspect.isclass() to decide if > it is a class. Using the inspect module sounds like a good suggestion to me. I'm wondering why we don't use the inspect module all the way. Here is a bit of code: import inspect # Import the module containing the classes we want to list. import test_inspect_data def test(): outer_classes = inspect.getmembers(test_inspect_data, inspect.isclass) print outer_classes for name, class_ in outer_classes: inner_classes = inspect.getmembers(class_, inspect.isclass) print inner_classes if __name__ == '__main__': test() Which prints out: [('A', )] [('B', ), ('C', ), ('__class__', )] - Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From carroll at tjc.com Wed May 21 10:25:22 2008 From: carroll at tjc.com (Terry Carroll) Date: Wed, 21 May 2008 01:25:22 -0700 (PDT) Subject: [Tutor] Little problem with math module In-Reply-To: Message-ID: > "Tiago Katcipis" wrote > > > def newton_divergente(x): > > return math.pow(x, 1.0/3.0) > > > > but when x = -20 it returns this error > > > > return math.pow(x, 1.0/3.0) > > ValueError: math domain error > > > > but why is that? is it impossible to calculate -20 ^ (1/3) ? Can I chime in late on this one? I'm catching up on some old email. It's already been pointed out that a negative number cannot be raised to a fractional power. But as long as you're only looking to calculate roots you should be able to calculate them unless the number is negative *and* the root is even. For example, you cannot (without getting into complex numbers) take the square root (an even root) of -8. But the cube root (an odd root) of -8 is -2. N**1/x is equal to -(-N**1/x), as long as the constraints above are met. Relying on this, you can easily write an "nthroot" routine that calculates the non-complex nth root of a number, unless the number is negative and the root-number is even: def nthroot(x, n): """returns the non-complex nth root of x""" if x > 0: return x**(1.0/n) elif n%2 == 1: return -(-x)**(1.0/n) else: raise ValueError, "even root cannot be calculated for negative number" For example: >>> nthroot(100, 2) 10.0 >>> nthroot(8, 3) 2.0 >>> nthroot(-8, 3) -2.0 >>> nthroot(-8, 2) # this is a no-no; negative number & even root Traceback (most recent call last): File "", line 1, in File "nthroots.py", line 8, in nthroot raise ValueError, "even root cannot be calculated for negative number" ValueError: even root cannot be calculated for negative number >>> Now, if you *are* willing to get into complex numbers, i.e., numbers with an imaginary component, you should be aware that there's no such thing as *the* Nth root of a number. Instead there are N Nth roots, evenly spaced in a circle centered on 0+0i. For example, the number 16 has two square roots, at 4 and -4; or more completely 4+0i and -4+0i. But it has 4 4th roots. Obviously it has 2 and -2 (2+0i and -2+0i); but it also has 0+2i and 0-2i: (0+2i)*(0+2i)*(0+2i)*(0+2i) = -4 * -4 = 16 (0-2i)*(0-2i)*(0-2i)*(0-2i) = 4 * 4 = 16 The following (barely-tested) routine should calculate all the Nth roots of a given x, even when x is negative and N is even: def nthroots(x, n): """returns a list of all nth roots of x""" from math import pi, cos, sin roots = [] if x >=1: startangle = 0 else: startangle = pi/2 firstroot = abs(x)**(1.0/n) for i in range(0, n): angle = (i*(2*pi)/n)+startangle root = complex(firstroot*cos(angle), firstroot*sin(angle)) roots.append(root) return roots Example: >>> nthroots(16,4) [(2+0j), (1.2246063538223773e-016+2j), (-2+2.4492127076447545e-016j), (-3.6738190614671318e-016-2j)] Apart from precision issues, those are 2+0j, 0+2j, -2+0j and 0-2j. From faheem at atlantiscomputing.com Wed May 21 11:35:21 2008 From: faheem at atlantiscomputing.com (Faheem) Date: Wed, 21 May 2008 15:05:21 +0530 Subject: [Tutor] String Replacement question Message-ID: <20080521150521.604437d8@atlantiscomputing.com> Hi all, How do I replace the same value multiple times without repeating the same variable name/value repeatedly? for ex. some = 'thing' print '%s %s %s %s' % (some,some,some,some) in this case, my question is how do i replace "% (some,some,some)" with something more concise? thanks in advance, Faheem From wolfram.kraus at fen-net.de Wed May 21 12:11:28 2008 From: wolfram.kraus at fen-net.de (Wolfram Kraus) Date: Wed, 21 May 2008 12:11:28 +0200 Subject: [Tutor] String Replacement question In-Reply-To: <20080521150521.604437d8@atlantiscomputing.com> References: <20080521150521.604437d8@atlantiscomputing.com> Message-ID: Am 21.05.2008 11:35, Faheem schrieb: > Hi all, > How do I replace the same value multiple times without repeating the > same variable name/value repeatedly? > for ex. > > some = 'thing' > print '%s %s %s %s' % (some,some,some,some) > > in this case, my question is how do i replace "% (some,some,some)" with > something more concise? > > thanks in advance, > Faheem Hi! Two possible solutions: print "%s %s %s %s" % (tuple([some]*4)) print " ".join([some for x in range(4)]) HTH, Wolfram From b.qadir at ugrad.unimelb.edu.au Wed May 21 11:35:01 2008 From: b.qadir at ugrad.unimelb.edu.au (Binish Huma Qadir) Date: Wed, 21 May 2008 19:35:01 +1000 (EST) Subject: [Tutor] python investment scheme assistance Message-ID: <3049.59.101.135.171.1211362501.squirrel@webmail.student.unimelb.edu.au> Hi, I'm doing a Investment implementation project where i need to use the following data: http://app.lms.unimelb.edu.au/bbcswebdav/courses/600151_2008_1/datasets/finance/asx_large.csv I've been instructed to design an investment scheme in python. The investment scheme i have chosen is based on investing in 3companies with the highest dividend yield and lowest debt equity ratio. The problem is that i dont know how to set up a python code that gives me the top 3 companies with the above characterisics. Your help would be much appreciated. Thank you very much for your time. Regards, Binish From kent37 at tds.net Wed May 21 12:36:30 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 21 May 2008 06:36:30 -0400 Subject: [Tutor] String Replacement question In-Reply-To: <20080521150521.604437d8@atlantiscomputing.com> References: <20080521150521.604437d8@atlantiscomputing.com> Message-ID: <1c2a2c590805210336h71fdc349r803b7ba076cb5f88@mail.gmail.com> On Wed, May 21, 2008 at 5:35 AM, Faheem wrote: > Hi all, > How do I replace the same value multiple times without repeating the > same variable name/value repeatedly? > for ex. > > some = 'thing' > print '%s %s %s %s' % (some,some,some,some) You can use named parameters, which moves the repetition to the format string: In [24]: print '%(some)s %(some)s %(some)s %(some)s' % (dict(some=some)) thing thing thing thing With multiple values, a common trick is to pass vars() or locals() as the dict, giving the format access to all defined variables: In [27]: a=1 In [28]: b=2 In [29]: print '%(a)s %(b)s' % vars() 1 2 If you literally need to repeat as in your example, you could do this: In [26]: print '%s %s %s %s' % (4*(some,)) thing thing thing thing Kent From moishyyehuda at gmail.com Wed May 21 13:04:16 2008 From: moishyyehuda at gmail.com (Moishy Gluck) Date: Wed, 21 May 2008 07:04:16 -0400 Subject: [Tutor] String Replacement question In-Reply-To: <1c2a2c590805210336h71fdc349r803b7ba076cb5f88@mail.gmail.com> References: <20080521150521.604437d8@atlantiscomputing.com> <1c2a2c590805210336h71fdc349r803b7ba076cb5f88@mail.gmail.com> Message-ID: <187d38240805210404r1a6877edp610c1ef3372e44a0@mail.gmail.com> Some other solutions might be >>> animal = 'cat' >>> " ".join((animal, ) * 4) 'cat cat cat cat' >>> animal = 'cat' >>> print " ".join((animal, ) * 4) cat cat cat cat >>>#If you need the string injected into another string >>> print "My %s's name is ginger." % (" ".join((animal,) * 4)) My cat cat cat cat's name is ginger. >>> On Wed, May 21, 2008 at 6:36 AM, Kent Johnson wrote: > On Wed, May 21, 2008 at 5:35 AM, Faheem > wrote: > > Hi all, > > How do I replace the same value multiple times without repeating the > > same variable name/value repeatedly? > > for ex. > > > > some = 'thing' > > print '%s %s %s %s' % (some,some,some,some) > > You can use named parameters, which moves the repetition to the format > string: > > In [24]: print '%(some)s %(some)s %(some)s %(some)s' % (dict(some=some)) > thing thing thing thing > > With multiple values, a common trick is to pass vars() or locals() as > the dict, giving the format access to all defined variables: > > In [27]: a=1 > > In [28]: b=2 > > In [29]: print '%(a)s %(b)s' % vars() > 1 2 > > If you literally need to repeat as in your example, you could do this: > > In [26]: print '%s %s %s %s' % (4*(some,)) > thing thing thing thing > > Kent > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Wed May 21 14:45:10 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 21 May 2008 08:45:10 -0400 Subject: [Tutor] python investment scheme assistance In-Reply-To: <3049.59.101.135.171.1211362501.squirrel@webmail.student.unimelb.edu.au> References: <3049.59.101.135.171.1211362501.squirrel@webmail.student.unimelb.edu.au> Message-ID: <1c2a2c590805210545g4a4c188cu70aca0f4c406508@mail.gmail.com> On Wed, May 21, 2008 at 5:35 AM, Binish Huma Qadir wrote: > Hi, > > I'm doing a Investment implementation project where i need to use the > following data: > http://app.lms.unimelb.edu.au/bbcswebdav/courses/600151_2008_1/datasets/finance/asx_large.csv > > I've been instructed to design an investment scheme in python. > The investment scheme i have chosen is based on investing in 3companies > with the highest dividend yield and lowest debt equity ratio. This sounds like a homework problem; we try to avoid doing homework. We will help you with specific questions. Do you know how to read the file? Maybe you could start with a program that just reads and prints the csv file. The csv module can help with that. Then compute and print the measures you need; finally pick out the top three. Try to write some code and ask here when you have trouble. Kent From muchanek at gmail.com Wed May 21 15:42:11 2008 From: muchanek at gmail.com (Kinuthia Muchane) Date: Wed, 21 May 2008 16:42:11 +0300 Subject: [Tutor] String Replacement Question Message-ID: <483426B3.5080309@gmail.com> >>> st = "String" >>> print "%s " %st*3 String String String >>> Does this help? Kinuthia... ----------------------------- Message: 6 Date: Wed, 21 May 2008 15:05:21 +0530 From: Faheem Subject: [Tutor] String Replacement question To: tutor at python.org Message-ID: <20080521150521.604437d8 at atlantiscomputing.com> Content-Type: text/plain; charset=US-ASCII Hi all, How do I replace the same value multiple times without repeating the same variable name/value repeatedly? for ex. some = 'thing' print '%s %s %s %s' % (some,some,some,some) in this case, my question is how do i replace "% (some,some,some)" with something more concise? thanks in advance, Faheem From moishyyehuda at gmail.com Wed May 21 16:29:41 2008 From: moishyyehuda at gmail.com (Moishy Gluck) Date: Wed, 21 May 2008 10:29:41 -0400 Subject: [Tutor] String Replacement Question In-Reply-To: <187d38240805210729h5b9838bfj93d775676cc94efe@mail.gmail.com> References: <483426B3.5080309@gmail.com> <187d38240805210729h5b9838bfj93d775676cc94efe@mail.gmail.com> Message-ID: <187d38240805210729r29f225bbyae313adb3f3423b5@mail.gmail.com> On Wed, May 21, 2008 at 10:29 AM, Moishy Gluck wrote: > >>> "%s " %st*3 > 'String String String ' > ^ > If you look closely at the end of the string there is an extra space. > > >>> " ".join((st, )*3) > 'String String String' > ^ > No extra space. > > > On Wed, May 21, 2008 at 9:42 AM, Kinuthia Muchane > wrote: > >> st = "String" >>>>> print "%s " %st*3 >>>>> >>>> String String String >> >>> >>>>> >> Does this help? >> >> Kinuthia... >> >> ----------------------------- >> >> Message: 6 >> Date: Wed, 21 May 2008 15:05:21 +0530 >> From: Faheem >> Subject: [Tutor] String Replacement question >> To: tutor at python.org >> Message-ID: <20080521150521.604437d8 at atlantiscomputing.com> >> Content-Type: text/plain; charset=US-ASCII >> >> Hi all, >> How do I replace the same value multiple times without repeating the >> same variable name/value repeatedly? >> for ex. >> >> some = 'thing' >> print '%s %s %s %s' % (some,some,some,some) >> >> in this case, my question is how do i replace "% (some,some,some)" with >> something more concise? >> >> thanks in advance, >> Faheem >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jatinder.singh2 at wipro.com Wed May 21 16:51:02 2008 From: jatinder.singh2 at wipro.com (jatinder Singh) Date: Wed, 21 May 2008 20:21:02 +0530 Subject: [Tutor] changin two lines in a single python script In-Reply-To: References: Message-ID: <1211381479.10205.13.camel@wipro.com> Hi . I am trying to change two lines in a single file (etc/php.ini) but my script is not doing this in one time .Please hav a look import re import sys import os def re_new(pat, rep, s): print re.sub(pat, rep, s) _stext_1 = 'memory_limit...M' #first word to search _rtext_1 = 'memory_limit = 512M ;' #to be replaced with first word _stext_2 = 'upload_max_filesize.*M' #Second word _rtext_2 = 'upload_max_filesize = 9M ;' #to replace with second word s = open("/home/ccuser/temp1.txt").readlines() for record in s: re_new(_stext_1,_rtext_1,record) #if found first then replaceit re_new(_stext_2,_rtext_2,record) #else if found second then replace that Will you please help me to correct this script so as to both of the changes occure at a singlr time Thanks for past, now and future Jatin On Wed, 2008-05-21 at 16:29 +0200, tutor-request at python.org wrote: > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request at python.org > > You can reach the person managing the list at > tutor-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. Re: String Replacement question (Wolfram Kraus) > 2. python investment scheme assistance (Binish Huma Qadir) > 3. Re: String Replacement question (Kent Johnson) > 4. Re: String Replacement question (Moishy Gluck) > 5. Re: python investment scheme assistance (Kent Johnson) > 6. String Replacement Question (Kinuthia Muchane) > 7. Re: String Replacement Question (Moishy Gluck) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Wed, 21 May 2008 12:11:28 +0200 > From: Wolfram Kraus > Subject: Re: [Tutor] String Replacement question > To: tutor at python.org > Message-ID: > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Am 21.05.2008 11:35, Faheem schrieb: > > Hi all, > > How do I replace the same value multiple times without repeating the > > same variable name/value repeatedly? > > for ex. > > > > some = 'thing' > > print '%s %s %s %s' % (some,some,some,some) > > > > in this case, my question is how do i replace "% (some,some,some)" with > > something more concise? > > > > thanks in advance, > > Faheem > > Hi! > > Two possible solutions: > > print "%s %s %s %s" % (tuple([some]*4)) > > print " ".join([some for x in range(4)]) > > HTH, > Wolfram > > > > ------------------------------ > > Message: 2 > Date: Wed, 21 May 2008 19:35:01 +1000 (EST) > From: Binish Huma Qadir > Subject: [Tutor] python investment scheme assistance > To: tutor at python.org > Message-ID: > <3049.59.101.135.171.1211362501.squirrel at webmail.student.unimelb.edu.au> > > Content-Type: text/plain; charset=UTF-8 > > Hi, > > I'm doing a Investment implementation project where i need to use the > following data: > http://app.lms.unimelb.edu.au/bbcswebdav/courses/600151_2008_1/datasets/finance/asx_large.csv > > I've been instructed to design an investment scheme in python. > The investment scheme i have chosen is based on investing in 3companies > with the highest dividend yield and lowest debt equity ratio. > > The problem is that i dont know how to set up a python code that gives me > the top 3 companies with the above characterisics. > > Your help would be much appreciated. > Thank you very much for your time. > Regards, > Binish > > > > ------------------------------ > > Message: 3 > Date: Wed, 21 May 2008 06:36:30 -0400 > From: "Kent Johnson" > Subject: Re: [Tutor] String Replacement question > To: Faheem > Cc: tutor at python.org > Message-ID: > <1c2a2c590805210336h71fdc349r803b7ba076cb5f88 at mail.gmail.com> > Content-Type: text/plain; charset=ISO-8859-1 > > On Wed, May 21, 2008 at 5:35 AM, Faheem wrote: > > Hi all, > > How do I replace the same value multiple times without repeating the > > same variable name/value repeatedly? > > for ex. > > > > some = 'thing' > > print '%s %s %s %s' % (some,some,some,some) > > You can use named parameters, which moves the repetition to the format string: > > In [24]: print '%(some)s %(some)s %(some)s %(some)s' % (dict(some=some)) > thing thing thing thing > > With multiple values, a common trick is to pass vars() or locals() as > the dict, giving the format access to all defined variables: > > In [27]: a=1 > > In [28]: b=2 > > In [29]: print '%(a)s %(b)s' % vars() > 1 2 > > If you literally need to repeat as in your example, you could do this: > > In [26]: print '%s %s %s %s' % (4*(some,)) > thing thing thing thing > > Kent > > > ------------------------------ > > Message: 4 > Date: Wed, 21 May 2008 07:04:16 -0400 > From: "Moishy Gluck" > Subject: Re: [Tutor] String Replacement question > To: tutor at python.org > Message-ID: > <187d38240805210404r1a6877edp610c1ef3372e44a0 at mail.gmail.com> > Content-Type: text/plain; charset="iso-8859-1" > > Some other solutions might be > > >>> animal = 'cat' > >>> " ".join((animal, ) * 4) > 'cat cat cat cat' > >>> animal = 'cat' > >>> print " ".join((animal, ) * 4) > cat cat cat cat > >>>#If you need the string injected into another string > >>> print "My %s's name is ginger." % (" ".join((animal,) * 4)) > My cat cat cat cat's name is ginger. > >>> > > On Wed, May 21, 2008 at 6:36 AM, Kent Johnson wrote: > > > On Wed, May 21, 2008 at 5:35 AM, Faheem > > wrote: > > > Hi all, > > > How do I replace the same value multiple times without repeating the > > > same variable name/value repeatedly? > > > for ex. > > > > > > some = 'thing' > > > print '%s %s %s %s' % (some,some,some,some) > > > > You can use named parameters, which moves the repetition to the format > > string: > > > > In [24]: print '%(some)s %(some)s %(some)s %(some)s' % (dict(some=some)) > > thing thing thing thing > > > > With multiple values, a common trick is to pass vars() or locals() as > > the dict, giving the format access to all defined variables: > > > > In [27]: a=1 > > > > In [28]: b=2 > > > > In [29]: print '%(a)s %(b)s' % vars() > > 1 2 > > > > If you literally need to repeat as in your example, you could do this: > > > > In [26]: print '%s %s %s %s' % (4*(some,)) > > thing thing thing thing > > > > Kent > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > > ------------------------------ > > Message: 5 > Date: Wed, 21 May 2008 08:45:10 -0400 > From: "Kent Johnson" > Subject: Re: [Tutor] python investment scheme assistance > To: "Binish Huma Qadir" > Cc: tutor at python.org > Message-ID: > <1c2a2c590805210545g4a4c188cu70aca0f4c406508 at mail.gmail.com> > Content-Type: text/plain; charset=ISO-8859-1 > > On Wed, May 21, 2008 at 5:35 AM, Binish Huma Qadir > wrote: > > Hi, > > > > I'm doing a Investment implementation project where i need to use the > > following data: > > http://app.lms.unimelb.edu.au/bbcswebdav/courses/600151_2008_1/datasets/finance/asx_large.csv > > > > I've been instructed to design an investment scheme in python. > > The investment scheme i have chosen is based on investing in 3companies > > with the highest dividend yield and lowest debt equity ratio. > > This sounds like a homework problem; we try to avoid doing homework. > We will help you with specific questions. > > Do you know how to read the file? Maybe you could start with a program > that just reads and prints the csv file. The csv module can help with > that. Then compute and print the measures you need; finally pick out > the top three. > > Try to write some code and ask here when you have trouble. > > Kent > > > ------------------------------ > > Message: 6 > Date: Wed, 21 May 2008 16:42:11 +0300 > From: Kinuthia Muchane > Subject: [Tutor] String Replacement Question > To: tutor at python.org > Message-ID: <483426B3.5080309 at gmail.com> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > >>> st = "String" > >>> print "%s " %st*3 > String String String > >>> > > Does this help? > > Kinuthia... > > ----------------------------- > > Message: 6 > Date: Wed, 21 May 2008 15:05:21 +0530 > From: Faheem > Subject: [Tutor] String Replacement question > To: tutor at python.org > Message-ID: <20080521150521.604437d8 at atlantiscomputing.com> > Content-Type: text/plain; charset=US-ASCII > > Hi all, > How do I replace the same value multiple times without repeating the > same variable name/value repeatedly? > for ex. > > some = 'thing' > print '%s %s %s %s' % (some,some,some,some) > > in this case, my question is how do i replace "% (some,some,some)" with > something more concise? > > thanks in advance, > Faheem > > > > ------------------------------ > > Message: 7 > Date: Wed, 21 May 2008 10:29:41 -0400 > From: "Moishy Gluck" > Subject: Re: [Tutor] String Replacement Question > To: tutor at python.org > Message-ID: > <187d38240805210729r29f225bbyae313adb3f3423b5 at mail.gmail.com> > Content-Type: text/plain; charset="iso-8859-1" > > On Wed, May 21, 2008 at 10:29 AM, Moishy Gluck > wrote: > > > >>> "%s " %st*3 > > 'String String String ' > > ^ > > If you look closely at the end of the string there is an extra space. > > > > >>> " ".join((st, )*3) > > 'String String String' > > ^ > > No extra space. > > > > > > On Wed, May 21, 2008 at 9:42 AM, Kinuthia Muchane > > wrote: > > > >> st = "String" > >>>>> print "%s " %st*3 > >>>>> > >>>> String String String > >> > >>> > >>>>> > >> Does this help? > >> > >> Kinuthia... > >> > >> ----------------------------- > >> > >> Message: 6 > >> Date: Wed, 21 May 2008 15:05:21 +0530 > >> From: Faheem > >> Subject: [Tutor] String Replacement question > >> To: tutor at python.org > >> Message-ID: <20080521150521.604437d8 at atlantiscomputing.com> > >> Content-Type: text/plain; charset=US-ASCII > >> > >> Hi all, > >> How do I replace the same value multiple times without repeating the > >> same variable name/value repeatedly? > >> for ex. > >> > >> some = 'thing' > >> print '%s %s %s %s' % (some,some,some,some) > >> > >> in this case, my question is how do i replace "% (some,some,some)" with > >> something more concise? > >> > >> thanks in advance, > >> Faheem > >> > >> _______________________________________________ > >> Tutor maillist - Tutor at python.org > >> http://mail.python.org/mailman/listinfo/tutor > >> > > > > > -------------- 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 51, Issue 44 > ************************************* -- Kind Regards Jatinder Singh Project Trainee Wipro Technologies Greater Noida Please do not print this email unless it is absolutely necessary. The information contained in this electronic message and any attachments to this message are intended for the exclusive use of the addressee(s) and may contain proprietary, confidential or privileged information. If you are not the intended recipient, you should not disseminate, distribute or copy this e-mail. Please notify the sender immediately and destroy all copies of this message and any attachments. WARNING: Computer viruses can be transmitted via email. The recipient should check this email and any attachments for the presence of viruses. The company accepts no liability for any damage caused by any virus transmitted by this email. www.wipro.com From muchanek at gmail.com Wed May 21 16:59:05 2008 From: muchanek at gmail.com (Kinuthia Muchane) Date: Wed, 21 May 2008 17:59:05 +0300 Subject: [Tutor] String Replacement Question In-Reply-To: <187d38240805210729h5b9838bfj93d775676cc94efe@mail.gmail.com> References: <483426B3.5080309@gmail.com> <187d38240805210729h5b9838bfj93d775676cc94efe@mail.gmail.com> Message-ID: <483438B9.60303@gmail.com> Moishy Gluck wrote: > >>> "%s " %st*3 > 'String String String ' > ^ > If you look closely at the end of the string there is an extra space. > > >>> " ".join((st, )*3) > 'String String String' > ^ > No extra space. Ah...Okay! > > On Wed, May 21, 2008 at 9:42 AM, Kinuthia Muchane > wrote: > > st = "String" > print "%s " %st*3 > > String String String > > > > Does this help? > > Kinuthia... From girzel at gmail.com Wed May 21 14:27:40 2008 From: girzel at gmail.com (Eric Abrahamsen) Date: Wed, 21 May 2008 20:27:40 +0800 Subject: [Tutor] syntax question Message-ID: <34CE1020-04D9-4133-AB3C-D90F5F78E915@gmail.com> Hi all, This is a syntax that I've seen on occasion in other people's code: theme = (VALID_THEMES[0], theme) [ theme in VALID_THEMES ] I have no idea how this works, or how to go about looking it up. Can someone enlighten me as to what's happening here? Many thanks, Eric From listas.condhor at gmail.com Wed May 21 17:58:43 2008 From: listas.condhor at gmail.com (Laureano Arcanio) Date: Wed, 21 May 2008 12:58:43 -0300 Subject: [Tutor] listing classes In-Reply-To: <20080521000126.GA59289@cutter.rexx.com> References: <759f137c0805200826t29f4e397nb59d2ce12ccf3c47@mail.gmail.com> <483300A0.8070509@gmail.com> <1c2a2c590805201048q15dd20d3y8c50c9887fa51a7b@mail.gmail.com> <20080521000126.GA59289@cutter.rexx.com> Message-ID: <759f137c0805210858g52272e4ei3005e2fb6b056990@mail.gmail.com> well it's true, using list it's scalable too. But It's doesn't looks friendly to the user to write the document. Syntacticly looks nice to keep some of the original structure of the html ( I mind, put the thags inside the document, and so on ). I'll making some test this days to see what i get, and i keep on mind your suggestions. Thanks for all your feedback ! -------------- next part -------------- An HTML attachment was scrubbed... URL: From moishyyehuda at gmail.com Wed May 21 18:00:40 2008 From: moishyyehuda at gmail.com (Moishy Gluck) Date: Wed, 21 May 2008 12:00:40 -0400 Subject: [Tutor] Fwd: syntax question In-Reply-To: <187d38240805210900q15520d7ckf5a1f17d853cb9fd@mail.gmail.com> References: <34CE1020-04D9-4133-AB3C-D90F5F78E915@gmail.com> <187d38240805210900q15520d7ckf5a1f17d853cb9fd@mail.gmail.com> Message-ID: <187d38240805210900x41f381f4mc4af81ff9258f5c9@mail.gmail.com> ---------- Forwarded message ---------- From: Moishy Gluck Date: Wed, May 21, 2008 at 12:00 PM Subject: Re: [Tutor] syntax question To: Eric Abrahamsen You appear to be referring to list comprehension. Here is a link to list comprehension is the python docs. http://docs.python.org/tut/node7.html#SECTION007140000000000000000 [index for index in iterable] Some examples would be: colors = ["red", "green", "blue"] hexValues = {"red": "ff0000", "green": "00ff00", "blue": "0000ff"} #Get hexadecimal values of each color. print [hexValues[color] for color in colors] #Get a copy of the same list. print [color for color in colors] #Get the length of each member. print [len(color) for color in colors] #add optional if statment. print [color for color in colors if len(color) > 3] The output would be: ['ff0000', '00ff00', '0000ff'] ['red', 'green', 'blue'] [3, 5, 4] ['green', 'blue'] On Wed, May 21, 2008 at 8:27 AM, Eric Abrahamsen wrote: > Hi all, > > This is a syntax that I've seen on occasion in other people's code: > > theme = (VALID_THEMES[0], theme) [ theme in VALID_THEMES ] > > I have no idea how this works, or how to go about looking it up. Can > someone enlighten me as to what's happening here? > > Many thanks, > Eric > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Wed May 21 18:10:50 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 21 May 2008 12:10:50 -0400 Subject: [Tutor] syntax question In-Reply-To: <34CE1020-04D9-4133-AB3C-D90F5F78E915@gmail.com> References: <34CE1020-04D9-4133-AB3C-D90F5F78E915@gmail.com> Message-ID: <1c2a2c590805210910p282099f2k98e5d33fd4062cec@mail.gmail.com> On Wed, May 21, 2008 at 8:27 AM, Eric Abrahamsen wrote: > Hi all, > > This is a syntax that I've seen on occasion in other people's code: > > theme = (VALID_THEMES[0], theme) [ theme in VALID_THEMES ] > > I have no idea how this works, or how to go about looking it up. This is one way to implement a conditional expression in Python < 2.5. In general, the expression (A, B)[bool(C)] has the value A if bool(C) is false and B if bool(C) is true. The boolean value is either 0 or 1. It is used as an index into the tuple to select the desired value. In Python 2.5 this can be written with the condition expression B if C else A or to use your example theme = theme if (theme in VALID_THEMES) else VALID_THEMES[0] Kent From jeff at drinktomi.com Wed May 21 18:39:07 2008 From: jeff at drinktomi.com (Jeff Younker) Date: Wed, 21 May 2008 09:39:07 -0700 Subject: [Tutor] String Replacement Question In-Reply-To: <483426B3.5080309@gmail.com> References: <483426B3.5080309@gmail.com> Message-ID: <64E53ECE-ED8B-4E38-9745-9C4BE39DC330@drinktomi.com> On May 21, 2008, at 6:42 AM, Kinuthia Muchane wrote: >>>> st = "String" >>>> print "%s " %st*3 > String String String >>>> > > Does this help? Another approach is to use dictionaries for string replacement. >>> subst = {'some': 'thing'} >>> print "%(some)s%(some)s%(some)s" % subst thingthingthing -jeff From carlos.hanson at gmail.com Wed May 21 19:15:17 2008 From: carlos.hanson at gmail.com (Carlos Hanson) Date: Wed, 21 May 2008 10:15:17 -0700 Subject: [Tutor] String Replacement Question In-Reply-To: <64E53ECE-ED8B-4E38-9745-9C4BE39DC330@drinktomi.com> References: <483426B3.5080309@gmail.com> <64E53ECE-ED8B-4E38-9745-9C4BE39DC330@drinktomi.com> Message-ID: On Wed, May 21, 2008 at 9:39 AM, Jeff Younker wrote: > On May 21, 2008, at 6:42 AM, Kinuthia Muchane wrote: > >>>>> st = "String" >>>>> print "%s " %st*3 >> >> String String String >>>>> >> >> Does this help? > > Another approach is to use dictionaries for string > replacement. > >>>> subst = {'some': 'thing'} >>>> print "%(some)s%(some)s%(some)s" % subst > thingthingthing > As an alternate to repeating the formated string: --> print '%(some)s'*3 % subst thingthingthing (forgot to reply all) -- Carlos Hanson From carlos.hanson at gmail.com Wed May 21 19:17:14 2008 From: carlos.hanson at gmail.com (Carlos Hanson) Date: Wed, 21 May 2008 10:17:14 -0700 Subject: [Tutor] syntax question In-Reply-To: <34CE1020-04D9-4133-AB3C-D90F5F78E915@gmail.com> References: <34CE1020-04D9-4133-AB3C-D90F5F78E915@gmail.com> Message-ID: On Wed, May 21, 2008 at 5:27 AM, Eric Abrahamsen wrote: > Hi all, > > This is a syntax that I've seen on occasion in other people's code: > > theme = (VALID_THEMES[0], theme) [ theme in VALID_THEMES ] > > I have no idea how this works, or how to go about looking it up. Can someone > enlighten me as to what's happening here? > > Many thanks, > Eric First, I looked at the code to see what I easily understood: - VALID_THEMES is a list of type something, since it has an index applied to it:VALID_THEMES[0] - theme is a type something that is in the list: theme in VALID_THEMES Next, I started playing with it based on what I knew using string as the theme type: --> VALID_THEMES = ['sun', 'moon', 'earth'] --> theme1 = 'moon' --> theme2 = 'mars' --> print (VALID_THEMES[0], theme1) ('sun', 'moon') --> print (VALID_THEMES[0], theme2) ('sun', 'mars') --> [theme1 in VALID_THEMES] [True] --> [theme2 in VALID_THEMES] [False] --> (VALID_THEMES[0], theme1)[theme1 in VALID_THEMES] 'moon' --> (VALID_THEMES[0], theme2)[theme2 in VALID_THEMES] 'sun' So what just happened? First, we created a tuple of the first VALID_THEME and a variable theme. Then we tested the variable theme to see if it was a VALID_THEME. The combination of the two always gives us a valid theme. The test if [theme in VALID_THEMES] becomes an index to the tuple: --> (VALID_THEMES[0], theme1)[1] 'moon' --> (VALID_THEMES[0], theme1)[0] 'sun' But we got [True] and [False]: --> True == 1 True --> False == 0 True So in words, the code returns the default theme which is the first in the list of valid themes unless the chosen theme is also in the list of valid themes. My suggestion is to play with code in the interpreter that you don't understand. -- Carlos Hanson From bgailer at gmail.com Wed May 21 19:31:45 2008 From: bgailer at gmail.com (bob gailer) Date: Wed, 21 May 2008 13:31:45 -0400 Subject: [Tutor] changin two lines in a single python script In-Reply-To: <1211381479.10205.13.camel@wipro.com> References: <1211381479.10205.13.camel@wipro.com> Message-ID: <48345C81.3080908@gmail.com> 1) When starting a new topic start a new email rather than replying to another unrelated post. 2) jatinder Singh wrote: > Hi . > > I am trying to change two lines in a single file (etc/php.ini) but my > script is not doing this in one time .Please hav a look > > import re > import sys > import os > > def re_new(pat, rep, s): > print re.sub(pat, rep, s) > > _stext_1 = 'memory_limit...M' #first word to search > _rtext_1 = 'memory_limit = 512M ;' #to be replaced with first word > _stext_2 = 'upload_max_filesize.*M' #Second word > _rtext_2 = 'upload_max_filesize = 9M ;' #to replace with second > word > s = open("/home/ccuser/temp1.txt").readlines() > for record in s: > re_new(_stext_1,_rtext_1,record) #if found first then replaceit > re_new(_stext_2,_rtext_2,record) #else if found second then > replace that > > Will you please help me to correct this script so as to both of the > changes occure at a singlr time > > Thanks for past, now and future > > Jatin > > > On Wed, 2008-05-21 at 16:29 +0200, tutor-request at python.org wrote: > >> Send Tutor mailing list submissions to >> tutor at python.org >> >> To subscribe or unsubscribe via the World Wide Web, visit >> http://mail.python.org/mailman/listinfo/tutor >> or, via email, send a message with subject or body 'help' to >> tutor-request at python.org >> >> You can reach the person managing the list at >> tutor-owner at python.org >> >> When replying, please edit your Subject line so it is more specific >> than "Re: Contents of Tutor digest..." >> >> >> Today's Topics: >> >> 1. Re: String Replacement question (Wolfram Kraus) >> 2. python investment scheme assistance (Binish Huma Qadir) >> 3. Re: String Replacement question (Kent Johnson) >> 4. Re: String Replacement question (Moishy Gluck) >> 5. Re: python investment scheme assistance (Kent Johnson) >> 6. String Replacement Question (Kinuthia Muchane) >> 7. Re: String Replacement Question (Moishy Gluck) >> >> >> ---------------------------------------------------------------------- >> >> Message: 1 >> Date: Wed, 21 May 2008 12:11:28 +0200 >> From: Wolfram Kraus >> Subject: Re: [Tutor] String Replacement question >> To: tutor at python.org >> Message-ID: >> Content-Type: text/plain; charset=ISO-8859-1; format=flowed >> >> Am 21.05.2008 11:35, Faheem schrieb: >> >>> Hi all, >>> How do I replace the same value multiple times without repeating the >>> same variable name/value repeatedly? >>> for ex. >>> >>> some = 'thing' >>> print '%s %s %s %s' % (some,some,some,some) >>> >>> in this case, my question is how do i replace "% (some,some,some)" with >>> something more concise? >>> >>> thanks in advance, >>> Faheem >>> >> Hi! >> >> Two possible solutions: >> >> print "%s %s %s %s" % (tuple([some]*4)) >> >> print " ".join([some for x in range(4)]) >> >> HTH, >> Wolfram >> >> >> >> ------------------------------ >> >> Message: 2 >> Date: Wed, 21 May 2008 19:35:01 +1000 (EST) >> From: Binish Huma Qadir >> Subject: [Tutor] python investment scheme assistance >> To: tutor at python.org >> Message-ID: >> <3049.59.101.135.171.1211362501.squirrel at webmail.student.unimelb.edu.au> >> >> Content-Type: text/plain; charset=UTF-8 >> >> Hi, >> >> I'm doing a Investment implementation project where i need to use the >> following data: >> http://app.lms.unimelb.edu.au/bbcswebdav/courses/600151_2008_1/datasets/finance/asx_large.csv >> >> I've been instructed to design an investment scheme in python. >> The investment scheme i have chosen is based on investing in 3companies >> with the highest dividend yield and lowest debt equity ratio. >> >> The problem is that i dont know how to set up a python code that gives me >> the top 3 companies with the above characterisics. >> >> Your help would be much appreciated. >> Thank you very much for your time. >> Regards, >> Binish >> >> >> >> ------------------------------ >> >> Message: 3 >> Date: Wed, 21 May 2008 06:36:30 -0400 >> From: "Kent Johnson" >> Subject: Re: [Tutor] String Replacement question >> To: Faheem >> Cc: tutor at python.org >> Message-ID: >> <1c2a2c590805210336h71fdc349r803b7ba076cb5f88 at mail.gmail.com> >> Content-Type: text/plain; charset=ISO-8859-1 >> >> On Wed, May 21, 2008 at 5:35 AM, Faheem wrote: >> >>> Hi all, >>> How do I replace the same value multiple times without repeating the >>> same variable name/value repeatedly? >>> for ex. >>> >>> some = 'thing' >>> print '%s %s %s %s' % (some,some,some,some) >>> >> You can use named parameters, which moves the repetition to the format string: >> >> In [24]: print '%(some)s %(some)s %(some)s %(some)s' % (dict(some=some)) >> thing thing thing thing >> >> With multiple values, a common trick is to pass vars() or locals() as >> the dict, giving the format access to all defined variables: >> >> In [27]: a=1 >> >> In [28]: b=2 >> >> In [29]: print '%(a)s %(b)s' % vars() >> 1 2 >> >> If you literally need to repeat as in your example, you could do this: >> >> In [26]: print '%s %s %s %s' % (4*(some,)) >> thing thing thing thing >> >> Kent >> >> >> ------------------------------ >> >> Message: 4 >> Date: Wed, 21 May 2008 07:04:16 -0400 >> From: "Moishy Gluck" >> Subject: Re: [Tutor] String Replacement question >> To: tutor at python.org >> Message-ID: >> <187d38240805210404r1a6877edp610c1ef3372e44a0 at mail.gmail.com> >> Content-Type: text/plain; charset="iso-8859-1" >> >> Some other solutions might be >> >> >>>>> animal = 'cat' >>>>> " ".join((animal, ) * 4) >>>>> >> 'cat cat cat cat' >> >>>>> animal = 'cat' >>>>> print " ".join((animal, ) * 4) >>>>> >> cat cat cat cat >> >>>>> #If you need the string injected into another string >>>>> print "My %s's name is ginger." % (" ".join((animal,) * 4)) >>>>> >> My cat cat cat cat's name is ginger. >> >> On Wed, May 21, 2008 at 6:36 AM, Kent Johnson wrote: >> >> >>> On Wed, May 21, 2008 at 5:35 AM, Faheem >>> wrote: >>> >>>> Hi all, >>>> How do I replace the same value multiple times without repeating the >>>> same variable name/value repeatedly? >>>> for ex. >>>> >>>> some = 'thing' >>>> print '%s %s %s %s' % (some,some,some,some) >>>> >>> You can use named parameters, which moves the repetition to the format >>> string: >>> >>> In [24]: print '%(some)s %(some)s %(some)s %(some)s' % (dict(some=some)) >>> thing thing thing thing >>> >>> With multiple values, a common trick is to pass vars() or locals() as >>> the dict, giving the format access to all defined variables: >>> >>> In [27]: a=1 >>> >>> In [28]: b=2 >>> >>> In [29]: print '%(a)s %(b)s' % vars() >>> 1 2 >>> >>> If you literally need to repeat as in your example, you could do this: >>> >>> In [26]: print '%s %s %s %s' % (4*(some,)) >>> thing thing thing thing >>> >>> Kent >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> http://mail.python.org/mailman/listinfo/tutor >>> >>> >> -------------- next part -------------- >> An HTML attachment was scrubbed... >> URL: >> >> ------------------------------ >> >> Message: 5 >> Date: Wed, 21 May 2008 08:45:10 -0400 >> From: "Kent Johnson" >> Subject: Re: [Tutor] python investment scheme assistance >> To: "Binish Huma Qadir" >> Cc: tutor at python.org >> Message-ID: >> <1c2a2c590805210545g4a4c188cu70aca0f4c406508 at mail.gmail.com> >> Content-Type: text/plain; charset=ISO-8859-1 >> >> On Wed, May 21, 2008 at 5:35 AM, Binish Huma Qadir >> wrote: >> >>> Hi, >>> >>> I'm doing a Investment implementation project where i need to use the >>> following data: >>> http://app.lms.unimelb.edu.au/bbcswebdav/courses/600151_2008_1/datasets/finance/asx_large.csv >>> >>> I've been instructed to design an investment scheme in python. >>> The investment scheme i have chosen is based on investing in 3companies >>> with the highest dividend yield and lowest debt equity ratio. >>> >> This sounds like a homework problem; we try to avoid doing homework. >> We will help you with specific questions. >> >> Do you know how to read the file? Maybe you could start with a program >> that just reads and prints the csv file. The csv module can help with >> that. Then compute and print the measures you need; finally pick out >> the top three. >> >> Try to write some code and ask here when you have trouble. >> >> Kent >> >> >> ------------------------------ >> >> Message: 6 >> Date: Wed, 21 May 2008 16:42:11 +0300 >> From: Kinuthia Muchane >> Subject: [Tutor] String Replacement Question >> To: tutor at python.org >> Message-ID: <483426B3.5080309 at gmail.com> >> Content-Type: text/plain; charset=ISO-8859-1; format=flowed >> >> >>>>> st = "String" >>>>> print "%s " %st*3 >>>>> >> String String String >> >> Does this help? >> >> Kinuthia... >> >> ----------------------------- >> >> Message: 6 >> Date: Wed, 21 May 2008 15:05:21 +0530 >> From: Faheem >> Subject: [Tutor] String Replacement question >> To: tutor at python.org >> Message-ID: <20080521150521.604437d8 at atlantiscomputing.com> >> Content-Type: text/plain; charset=US-ASCII >> >> Hi all, >> How do I replace the same value multiple times without repeating the >> same variable name/value repeatedly? >> for ex. >> >> some = 'thing' >> print '%s %s %s %s' % (some,some,some,some) >> >> in this case, my question is how do i replace "% (some,some,some)" with >> something more concise? >> >> thanks in advance, >> Faheem >> >> >> >> ------------------------------ >> >> Message: 7 >> Date: Wed, 21 May 2008 10:29:41 -0400 >> From: "Moishy Gluck" >> Subject: Re: [Tutor] String Replacement Question >> To: tutor at python.org >> Message-ID: >> <187d38240805210729r29f225bbyae313adb3f3423b5 at mail.gmail.com> >> Content-Type: text/plain; charset="iso-8859-1" >> >> On Wed, May 21, 2008 at 10:29 AM, Moishy Gluck >> wrote: >> >> >>>>>> "%s " %st*3 >>>>>> >>> 'String String String ' >>> ^ >>> If you look closely at the end of the string there is an extra space. >>> >>> >>>>>> " ".join((st, )*3) >>>>>> >>> 'String String String' >>> ^ >>> No extra space. >>> >>> >>> On Wed, May 21, 2008 at 9:42 AM, Kinuthia Muchane >>> wrote: >>> >>> >>>> st = "String" >>>> >>>>>>> print "%s " %st*3 >>>>>>> >>>>>>> >>>>>> String String String >>>>>> >>>> Does this help? >>>> >>>> Kinuthia... >>>> >>>> ----------------------------- >>>> >>>> Message: 6 >>>> Date: Wed, 21 May 2008 15:05:21 +0530 >>>> From: Faheem >>>> Subject: [Tutor] String Replacement question >>>> To: tutor at python.org >>>> Message-ID: <20080521150521.604437d8 at atlantiscomputing.com> >>>> Content-Type: text/plain; charset=US-ASCII >>>> >>>> Hi all, >>>> How do I replace the same value multiple times without repeating the >>>> same variable name/value repeatedly? >>>> for ex. >>>> >>>> some = 'thing' >>>> print '%s %s %s %s' % (some,some,some,some) >>>> >>>> in this case, my question is how do i replace "% (some,some,some)" with >>>> something more concise? >>>> >>>> thanks in advance, >>>> Faheem >>>> >>>> _______________________________________________ >>>> Tutor maillist - Tutor at python.org >>>> http://mail.python.org/mailman/listinfo/tutor >>>> >>>> >>> >> -------------- 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 51, Issue 44 >> ************************************* >> -- Bob Gailer 919-636-4239 Chapel Hill, NC From bgailer at gmail.com Wed May 21 19:32:01 2008 From: bgailer at gmail.com (bob gailer) Date: Wed, 21 May 2008 13:32:01 -0400 Subject: [Tutor] changin two lines in a single python script In-Reply-To: <1211381479.10205.13.camel@wipro.com> References: <1211381479.10205.13.camel@wipro.com> Message-ID: <48345C91.9070603@gmail.com> 1) When starting a new topic start a new email rather than replying to another unrelated post. 2) jatinder Singh wrote: > Hi . > > I am trying to change two lines in a single file (etc/php.ini) but my > script is not doing this in one time .Please hav a look > > import re > import sys > import os > > def re_new(pat, rep, s): > print re.sub(pat, rep, s) > > _stext_1 = 'memory_limit...M' #first word to search > _rtext_1 = 'memory_limit = 512M ;' #to be replaced with first word > _stext_2 = 'upload_max_filesize.*M' #Second word > _rtext_2 = 'upload_max_filesize = 9M ;' #to replace with second > word > s = open("/home/ccuser/temp1.txt").readlines() > for record in s: > re_new(_stext_1,_rtext_1,record) #if found first then replaceit > re_new(_stext_2,_rtext_2,record) #else if found second then > replace that > > Will you please help me to correct this script so as to both of the > changes occure at a singlr time > > Thanks for past, now and future > > Jatin > > > On Wed, 2008-05-21 at 16:29 +0200, tutor-request at python.org wrote: > >> Send Tutor mailing list submissions to >> tutor at python.org >> >> To subscribe or unsubscribe via the World Wide Web, visit >> http://mail.python.org/mailman/listinfo/tutor >> or, via email, send a message with subject or body 'help' to >> tutor-request at python.org >> >> You can reach the person managing the list at >> tutor-owner at python.org >> >> When replying, please edit your Subject line so it is more specific >> than "Re: Contents of Tutor digest..." >> >> >> Today's Topics: >> >> 1. Re: String Replacement question (Wolfram Kraus) >> 2. python investment scheme assistance (Binish Huma Qadir) >> 3. Re: String Replacement question (Kent Johnson) >> 4. Re: String Replacement question (Moishy Gluck) >> 5. Re: python investment scheme assistance (Kent Johnson) >> 6. String Replacement Question (Kinuthia Muchane) >> 7. Re: String Replacement Question (Moishy Gluck) >> >> >> ---------------------------------------------------------------------- >> >> Message: 1 >> Date: Wed, 21 May 2008 12:11:28 +0200 >> From: Wolfram Kraus >> Subject: Re: [Tutor] String Replacement question >> To: tutor at python.org >> Message-ID: >> Content-Type: text/plain; charset=ISO-8859-1; format=flowed >> >> Am 21.05.2008 11:35, Faheem schrieb: >> >>> Hi all, >>> How do I replace the same value multiple times without repeating the >>> same variable name/value repeatedly? >>> for ex. >>> >>> some = 'thing' >>> print '%s %s %s %s' % (some,some,some,some) >>> >>> in this case, my question is how do i replace "% (some,some,some)" with >>> something more concise? >>> >>> thanks in advance, >>> Faheem >>> >> Hi! >> >> Two possible solutions: >> >> print "%s %s %s %s" % (tuple([some]*4)) >> >> print " ".join([some for x in range(4)]) >> >> HTH, >> Wolfram >> >> >> >> ------------------------------ >> >> Message: 2 >> Date: Wed, 21 May 2008 19:35:01 +1000 (EST) >> From: Binish Huma Qadir >> Subject: [Tutor] python investment scheme assistance >> To: tutor at python.org >> Message-ID: >> <3049.59.101.135.171.1211362501.squirrel at webmail.student.unimelb.edu.au> >> >> Content-Type: text/plain; charset=UTF-8 >> >> Hi, >> >> I'm doing a Investment implementation project where i need to use the >> following data: >> http://app.lms.unimelb.edu.au/bbcswebdav/courses/600151_2008_1/datasets/finance/asx_large.csv >> >> I've been instructed to design an investment scheme in python. >> The investment scheme i have chosen is based on investing in 3companies >> with the highest dividend yield and lowest debt equity ratio. >> >> The problem is that i dont know how to set up a python code that gives me >> the top 3 companies with the above characterisics. >> >> Your help would be much appreciated. >> Thank you very much for your time. >> Regards, >> Binish >> >> >> >> ------------------------------ >> >> Message: 3 >> Date: Wed, 21 May 2008 06:36:30 -0400 >> From: "Kent Johnson" >> Subject: Re: [Tutor] String Replacement question >> To: Faheem >> Cc: tutor at python.org >> Message-ID: >> <1c2a2c590805210336h71fdc349r803b7ba076cb5f88 at mail.gmail.com> >> Content-Type: text/plain; charset=ISO-8859-1 >> >> On Wed, May 21, 2008 at 5:35 AM, Faheem wrote: >> >>> Hi all, >>> How do I replace the same value multiple times without repeating the >>> same variable name/value repeatedly? >>> for ex. >>> >>> some = 'thing' >>> print '%s %s %s %s' % (some,some,some,some) >>> >> You can use named parameters, which moves the repetition to the format string: >> >> In [24]: print '%(some)s %(some)s %(some)s %(some)s' % (dict(some=some)) >> thing thing thing thing >> >> With multiple values, a common trick is to pass vars() or locals() as >> the dict, giving the format access to all defined variables: >> >> In [27]: a=1 >> >> In [28]: b=2 >> >> In [29]: print '%(a)s %(b)s' % vars() >> 1 2 >> >> If you literally need to repeat as in your example, you could do this: >> >> In [26]: print '%s %s %s %s' % (4*(some,)) >> thing thing thing thing >> >> Kent >> >> >> ------------------------------ >> >> Message: 4 >> Date: Wed, 21 May 2008 07:04:16 -0400 >> From: "Moishy Gluck" >> Subject: Re: [Tutor] String Replacement question >> To: tutor at python.org >> Message-ID: >> <187d38240805210404r1a6877edp610c1ef3372e44a0 at mail.gmail.com> >> Content-Type: text/plain; charset="iso-8859-1" >> >> Some other solutions might be >> >> >>>>> animal = 'cat' >>>>> " ".join((animal, ) * 4) >>>>> >> 'cat cat cat cat' >> >>>>> animal = 'cat' >>>>> print " ".join((animal, ) * 4) >>>>> >> cat cat cat cat >> >>>>> #If you need the string injected into another string >>>>> print "My %s's name is ginger." % (" ".join((animal,) * 4)) >>>>> >> My cat cat cat cat's name is ginger. >> >> On Wed, May 21, 2008 at 6:36 AM, Kent Johnson wrote: >> >> >>> On Wed, May 21, 2008 at 5:35 AM, Faheem >>> wrote: >>> >>>> Hi all, >>>> How do I replace the same value multiple times without repeating the >>>> same variable name/value repeatedly? >>>> for ex. >>>> >>>> some = 'thing' >>>> print '%s %s %s %s' % (some,some,some,some) >>>> >>> You can use named parameters, which moves the repetition to the format >>> string: >>> >>> In [24]: print '%(some)s %(some)s %(some)s %(some)s' % (dict(some=some)) >>> thing thing thing thing >>> >>> With multiple values, a common trick is to pass vars() or locals() as >>> the dict, giving the format access to all defined variables: >>> >>> In [27]: a=1 >>> >>> In [28]: b=2 >>> >>> In [29]: print '%(a)s %(b)s' % vars() >>> 1 2 >>> >>> If you literally need to repeat as in your example, you could do this: >>> >>> In [26]: print '%s %s %s %s' % (4*(some,)) >>> thing thing thing thing >>> >>> Kent >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> http://mail.python.org/mailman/listinfo/tutor >>> >>> >> -------------- next part -------------- >> An HTML attachment was scrubbed... >> URL: >> >> ------------------------------ >> >> Message: 5 >> Date: Wed, 21 May 2008 08:45:10 -0400 >> From: "Kent Johnson" >> Subject: Re: [Tutor] python investment scheme assistance >> To: "Binish Huma Qadir" >> Cc: tutor at python.org >> Message-ID: >> <1c2a2c590805210545g4a4c188cu70aca0f4c406508 at mail.gmail.com> >> Content-Type: text/plain; charset=ISO-8859-1 >> >> On Wed, May 21, 2008 at 5:35 AM, Binish Huma Qadir >> wrote: >> >>> Hi, >>> >>> I'm doing a Investment implementation project where i need to use the >>> following data: >>> http://app.lms.unimelb.edu.au/bbcswebdav/courses/600151_2008_1/datasets/finance/asx_large.csv >>> >>> I've been instructed to design an investment scheme in python. >>> The investment scheme i have chosen is based on investing in 3companies >>> with the highest dividend yield and lowest debt equity ratio. >>> >> This sounds like a homework problem; we try to avoid doing homework. >> We will help you with specific questions. >> >> Do you know how to read the file? Maybe you could start with a program >> that just reads and prints the csv file. The csv module can help with >> that. Then compute and print the measures you need; finally pick out >> the top three. >> >> Try to write some code and ask here when you have trouble. >> >> Kent >> >> >> ------------------------------ >> >> Message: 6 >> Date: Wed, 21 May 2008 16:42:11 +0300 >> From: Kinuthia Muchane >> Subject: [Tutor] String Replacement Question >> To: tutor at python.org >> Message-ID: <483426B3.5080309 at gmail.com> >> Content-Type: text/plain; charset=ISO-8859-1; format=flowed >> >> >>>>> st = "String" >>>>> print "%s " %st*3 >>>>> >> String String String >> >> Does this help? >> >> Kinuthia... >> >> ----------------------------- >> >> Message: 6 >> Date: Wed, 21 May 2008 15:05:21 +0530 >> From: Faheem >> Subject: [Tutor] String Replacement question >> To: tutor at python.org >> Message-ID: <20080521150521.604437d8 at atlantiscomputing.com> >> Content-Type: text/plain; charset=US-ASCII >> >> Hi all, >> How do I replace the same value multiple times without repeating the >> same variable name/value repeatedly? >> for ex. >> >> some = 'thing' >> print '%s %s %s %s' % (some,some,some,some) >> >> in this case, my question is how do i replace "% (some,some,some)" with >> something more concise? >> >> thanks in advance, >> Faheem >> >> >> >> ------------------------------ >> >> Message: 7 >> Date: Wed, 21 May 2008 10:29:41 -0400 >> From: "Moishy Gluck" >> Subject: Re: [Tutor] String Replacement Question >> To: tutor at python.org >> Message-ID: >> <187d38240805210729r29f225bbyae313adb3f3423b5 at mail.gmail.com> >> Content-Type: text/plain; charset="iso-8859-1" >> >> On Wed, May 21, 2008 at 10:29 AM, Moishy Gluck >> wrote: >> >> >>>>>> "%s " %st*3 >>>>>> >>> 'String String String ' >>> ^ >>> If you look closely at the end of the string there is an extra space. >>> >>> >>>>>> " ".join((st, )*3) >>>>>> >>> 'String String String' >>> ^ >>> No extra space. >>> >>> >>> On Wed, May 21, 2008 at 9:42 AM, Kinuthia Muchane >>> wrote: >>> >>> >>>> st = "String" >>>> >>>>>>> print "%s " %st*3 >>>>>>> >>>>>>> >>>>>> String String String >>>>>> >>>> Does this help? >>>> >>>> Kinuthia... >>>> >>>> ----------------------------- >>>> >>>> Message: 6 >>>> Date: Wed, 21 May 2008 15:05:21 +0530 >>>> From: Faheem >>>> Subject: [Tutor] String Replacement question >>>> To: tutor at python.org >>>> Message-ID: <20080521150521.604437d8 at atlantiscomputing.com> >>>> Content-Type: text/plain; charset=US-ASCII >>>> >>>> Hi all, >>>> How do I replace the same value multiple times without repeating the >>>> same variable name/value repeatedly? >>>> for ex. >>>> >>>> some = 'thing' >>>> print '%s %s %s %s' % (some,some,some,some) >>>> >>>> in this case, my question is how do i replace "% (some,some,some)" with >>>> something more concise? >>>> >>>> thanks in advance, >>>> Faheem >>>> >>>> _______________________________________________ >>>> Tutor maillist - Tutor at python.org >>>> http://mail.python.org/mailman/listinfo/tutor >>>> >>>> >>> >> -------------- 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 51, Issue 44 >> ************************************* >> -- Bob Gailer 919-636-4239 Chapel Hill, NC From bgailer at gmail.com Wed May 21 19:35:07 2008 From: bgailer at gmail.com (bob gailer) Date: Wed, 21 May 2008 13:35:07 -0400 Subject: [Tutor] changing two lines in a single python script Message-ID: <48345D4B.2040801@gmail.com> 1) When starting a new topic start a new email rather than replying to another unrelated post. jatinder Singh wrote: > Hi . > > I am trying to change two lines in a single file (etc/php.ini) but my > script is not doing this in one time . What does "in one time" mean? What IS the script doing? > Please hav a look > > import re > import sys > import os > > def re_new(pat, rep, s): > print re.sub(pat, rep, s) > It appears that you are using stdout to write the altered file. True? > > _stext_1 = 'memory_limit...M' #first word to search > _rtext_1 = 'memory_limit = 512M ;' #to be replaced with first word > _stext_2 = 'upload_max_filesize.*M' #Second word > _rtext_2 = 'upload_max_filesize = 9M ;' #to replace with second > word > s = open("/home/ccuser/temp1.txt").readlines() > for record in s: > re_new(_stext_1,_rtext_1,record) #if found first then replaceit > re_new(_stext_2,_rtext_2,record) #else if found second then > replace that > > Will you please help me to correct this script so as to both of the > changes occure at a singlr time > > Thanks for past, now and future > > Jatin -- Bob Gailer 919-636-4239 Chapel Hill, NC From kent37 at tds.net Wed May 21 19:36:33 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 21 May 2008 13:36:33 -0400 Subject: [Tutor] Fwd: syntax question In-Reply-To: <187d38240805210900x41f381f4mc4af81ff9258f5c9@mail.gmail.com> References: <34CE1020-04D9-4133-AB3C-D90F5F78E915@gmail.com> <187d38240805210900q15520d7ckf5a1f17d853cb9fd@mail.gmail.com> <187d38240805210900x41f381f4mc4af81ff9258f5c9@mail.gmail.com> Message-ID: <1c2a2c590805211036m221f1b7qb0b793bf2406c473@mail.gmail.com> On Wed, May 21, 2008 at 12:00 PM, Moishy Gluck wrote: > You appear to be referring to list comprehension. No, it is not a list comp. See my separate reply. Kent From amit.kumar.iitr at gmail.com Wed May 21 20:11:53 2008 From: amit.kumar.iitr at gmail.com (Amit Kumar) Date: Wed, 21 May 2008 23:41:53 +0530 Subject: [Tutor] Supported platform Message-ID: Can I get list of supported platform by python? can I install python on AS/400 and HP-Unix? Regards Amit -------------- next part -------------- An HTML attachment was scrubbed... URL: From tktucker at gmail.com Wed May 21 20:31:28 2008 From: tktucker at gmail.com (Tom Tucker) Date: Wed, 21 May 2008 14:31:28 -0400 Subject: [Tutor] Supported platform In-Reply-To: References: Message-ID: <2a278ffe0805211131m3fc21dc4w8e384181ac69c78a@mail.gmail.com> I would check the docs on the www.python.org website. >From the main page.... "Python runs on Windows, Linux/Unix, Mac OS X, OS/2, Amiga, Palm Handhelds, and Nokia mobile phones. Python has also been ported to the Java and .NET virtual machines." On Wed, May 21, 2008 at 2:11 PM, Amit Kumar wrote: > Can I get list of supported platform by python? > > can I install python on AS/400 and HP-Unix? > > Regards > Amit > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Wed May 21 19:16:07 2008 From: bgailer at gmail.com (bob gailer) Date: Wed, 21 May 2008 13:16:07 -0400 Subject: [Tutor] String Replacement question In-Reply-To: <20080521150521.604437d8@atlantiscomputing.com> References: <20080521150521.604437d8@atlantiscomputing.com> Message-ID: <483458D7.8020901@gmail.com> Faheem wrote: > Hi all, > How do I replace the same value multiple times without repeating the > same variable name/value repeatedly? > for ex. > > some = 'thing' > print '%s %s %s %s' % (some,some,some,some) > > in this case, my question is how do i replace "% (some,some,some)" with > something more concise? > > The tersest I can offer is: print '%s %s %s %s' % ((some,)*4) -- Bob Gailer 919-636-4239 Chapel Hill, NC From malaclypse2 at gmail.com Wed May 21 20:40:23 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Wed, 21 May 2008 14:40:23 -0400 Subject: [Tutor] Supported platform In-Reply-To: References: Message-ID: <16651e80805211140p6b502bfcm9b09432b38ef0a1b@mail.gmail.com> On Wed, May 21, 2008 at 2:11 PM, Amit Kumar wrote: > Can I get list of supported platform by python? > > can I install python on AS/400 and HP-Unix? I don't know of any sort of official list of supported platforms. Activestate claims to have a python distribution for HPUX: http://www.activestate.com/Products/activepython/features.plex There appears to be an os/400 python package here: http://www.iseriespython.com/ -- Jerry From kent37 at tds.net Wed May 21 20:55:13 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 21 May 2008 14:55:13 -0400 Subject: [Tutor] Supported platform In-Reply-To: <16651e80805211140p6b502bfcm9b09432b38ef0a1b@mail.gmail.com> References: <16651e80805211140p6b502bfcm9b09432b38ef0a1b@mail.gmail.com> Message-ID: <1c2a2c590805211155x5ce1bd0bqd0354a26547481fb@mail.gmail.com> > On Wed, May 21, 2008 at 2:11 PM, Amit Kumar wrote: >> Can I get list of supported platform by python? See http://www.python.org/download/ http://www.python.org/download/other for a partial list. Kent From srilyk at gmail.com Wed May 21 18:59:22 2008 From: srilyk at gmail.com (W W) Date: Wed, 21 May 2008 11:59:22 -0500 Subject: [Tutor] File access times Message-ID: <333efb450805210959g6e6ca30aq292e5b1c234caf41@mail.gmail.com> I've just made an interesting observation, and I'm curious if anyone knows any more about it. 1 import time 2 3 start = time.time() 4 f = open("test.txt") 5 f.close() 6 end = time.time() 7 print end - start 8 9 10 start = time.time() 11 f = open("/home/wayne/python_files/test/test.txt") 12 f.close() 13 end = time.time() 14 print end - start As you can see, the open/timing dialogs are precisely the same, yet as I've run it, I get these results: ------------ 2.59876251221e-05 1.8835067749e-05 ------------ 3.38554382324e-05 1.90734863281e-05 ------------ 2.8133392334e-05 1.90734863281e-05 ------------ However, when I switch the order, so the full path is first, I get similar results. Granted, .000028 vs .000019 (seconds?) isn't terribly long, but it *is* a discrepancy, and I find it even more puzzling that the second access is faster, regardless of how detailed the path is. Could it be that the file is stored in RAM and "remembered" even though it's been closed? Just curious, Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi From listas.condhor at gmail.com Wed May 21 22:55:33 2008 From: listas.condhor at gmail.com (Laureano Arcanio) Date: Wed, 21 May 2008 17:55:33 -0300 Subject: [Tutor] listing classes In-Reply-To: <759f137c0805210858g52272e4ei3005e2fb6b056990@mail.gmail.com> References: <759f137c0805200826t29f4e397nb59d2ce12ccf3c47@mail.gmail.com> <483300A0.8070509@gmail.com> <1c2a2c590805201048q15dd20d3y8c50c9887fa51a7b@mail.gmail.com> <20080521000126.GA59289@cutter.rexx.com> <759f137c0805210858g52272e4ei3005e2fb6b056990@mail.gmail.com> Message-ID: <759f137c0805211355gcaca232m4455167afc635812@mail.gmail.com> Finally, i decide to make this: from metatag import MetaTag from htmltools import TagHTML class Structure(object): class A(TagHTML): pass class B(TagHTML): pass def get(self): __all__ = dir(self) classes = filter(lambda k: type(getattr(self, k)) == type(TagHTML) , __all__) methods = filter(lambda k: str(type(getattr(self, k))) == "" , __all__) return classes, methods So i can Lis Methods and Classes, and then use setattr or whatever needed. There is a think left, i can't jus compare this: if type(somethingA) == type(somthingB): I transform type() to a string and then compare them.. (like in the code below) Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From listas.condhor at gmail.com Wed May 21 23:01:51 2008 From: listas.condhor at gmail.com (Laureano Arcanio) Date: Wed, 21 May 2008 18:01:51 -0300 Subject: [Tutor] listing classes In-Reply-To: <759f137c0805211355gcaca232m4455167afc635812@mail.gmail.com> References: <759f137c0805200826t29f4e397nb59d2ce12ccf3c47@mail.gmail.com> <483300A0.8070509@gmail.com> <1c2a2c590805201048q15dd20d3y8c50c9887fa51a7b@mail.gmail.com> <20080521000126.GA59289@cutter.rexx.com> <759f137c0805210858g52272e4ei3005e2fb6b056990@mail.gmail.com> <759f137c0805211355gcaca232m4455167afc635812@mail.gmail.com> Message-ID: <759f137c0805211401n5b893cc3ldafa8e16bb48a6d8@mail.gmail.com> sorry this is not true: There is a think left, i can't jus compare this: if type(somethingA) == type(somthingB): I transform type() to a string and then compare them.. (like in the code below) Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Thu May 22 00:36:14 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 21 May 2008 18:36:14 -0400 Subject: [Tutor] File access times In-Reply-To: <333efb450805210959g6e6ca30aq292e5b1c234caf41@mail.gmail.com> References: <333efb450805210959g6e6ca30aq292e5b1c234caf41@mail.gmail.com> Message-ID: <1c2a2c590805211536s3c7a5698ma6b1f05195662f37@mail.gmail.com> On Wed, May 21, 2008 at 12:59 PM, W W wrote: > Could it be > that the file is stored in RAM and "remembered" even though it's been > closed? Yes, the OS caches file and directory data so the second open is faster. Kent From listas.condhor at gmail.com Thu May 22 01:45:40 2008 From: listas.condhor at gmail.com (Laureano Arcanio) Date: Wed, 21 May 2008 20:45:40 -0300 Subject: [Tutor] listing classes In-Reply-To: <759f137c0805211401n5b893cc3ldafa8e16bb48a6d8@mail.gmail.com> References: <759f137c0805200826t29f4e397nb59d2ce12ccf3c47@mail.gmail.com> <483300A0.8070509@gmail.com> <1c2a2c590805201048q15dd20d3y8c50c9887fa51a7b@mail.gmail.com> <20080521000126.GA59289@cutter.rexx.com> <759f137c0805210858g52272e4ei3005e2fb6b056990@mail.gmail.com> <759f137c0805211355gcaca232m4455167afc635812@mail.gmail.com> <759f137c0805211401n5b893cc3ldafa8e16bb48a6d8@mail.gmail.com> Message-ID: <759f137c0805211645y4cf863ebu246413d8c925d7e6@mail.gmail.com> I'm using the dir() function, but this give me an alphabetic ordered list, is there any way to do the same but getting an appearance ordered list ?. -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Thu May 22 02:47:19 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 21 May 2008 20:47:19 -0400 Subject: [Tutor] listing classes In-Reply-To: <759f137c0805211645y4cf863ebu246413d8c925d7e6@mail.gmail.com> References: <759f137c0805200826t29f4e397nb59d2ce12ccf3c47@mail.gmail.com> <483300A0.8070509@gmail.com> <1c2a2c590805201048q15dd20d3y8c50c9887fa51a7b@mail.gmail.com> <20080521000126.GA59289@cutter.rexx.com> <759f137c0805210858g52272e4ei3005e2fb6b056990@mail.gmail.com> <759f137c0805211355gcaca232m4455167afc635812@mail.gmail.com> <759f137c0805211401n5b893cc3ldafa8e16bb48a6d8@mail.gmail.com> <759f137c0805211645y4cf863ebu246413d8c925d7e6@mail.gmail.com> Message-ID: <1c2a2c590805211747u27fad136n6646e564dcf28008@mail.gmail.com> On Wed, May 21, 2008 at 7:45 PM, Laureano Arcanio wrote: > > I'm using the dir() function, but this give me an alphabetic ordered list, > is there any way to do the same but getting an appearance ordered list ?. Not easily. Attributes are stored in a dict; dicts don't preserve order. You would have to make a custom metaclass that remembered the order. What is it you are trying to accomplish? Kent From carroll at tjc.com Thu May 22 07:29:36 2008 From: carroll at tjc.com (Terry Carroll) Date: Wed, 21 May 2008 22:29:36 -0700 (PDT) Subject: [Tutor] Little problem with math module In-Reply-To: Message-ID: On Wed, 21 May 2008, Terry Carroll wrote: > The following (barely-tested) routine should calculate all the Nth roots > of a given x, even when x is negative and N is even: I realize I'm probably talking to myself here, but for the benefit of the archives, I found a more elegant approach after reading http://everything2.com/node/1309141. The following routine instead uses the formula at the end of the page (although I must admit I needed to read the entire page very carefully before I actually understood it): def nthroots(x,n): """returns a list of all nth roots of x; see http://everything2.com/node/1309141 """ from math import atan2, pi from cmath import exp i = 0+1j z=complex(x) # express the cartesian (x+yi) complex number z # as polar (modulus R & argument theta) R = abs(z) theta = atan2(z.imag, z.real) coef = R**(1.0/n) return [coef * exp(i*(theta/n + 2*pi*k/n)) for k in range(0,n)] I'm not sure it's faster than the method from the prior email, but it certainly seems a bit less ham-handed. It could probably be sped up, at the cost of some obfuscation, by pulling a few more things out of the list comprehension, e.g., X = i*theta/n Y = (0+2j)*pi/n return [coeff * exp(X + Y*k) for k in range(0,n)] From kent37 at tds.net Thu May 22 12:07:39 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 22 May 2008 06:07:39 -0400 Subject: [Tutor] Fwd: listing classes In-Reply-To: <759f137c0805211941s2eef77dfqf0335d4e5a8ec11@mail.gmail.com> References: <759f137c0805200826t29f4e397nb59d2ce12ccf3c47@mail.gmail.com> <483300A0.8070509@gmail.com> <1c2a2c590805201048q15dd20d3y8c50c9887fa51a7b@mail.gmail.com> <20080521000126.GA59289@cutter.rexx.com> <759f137c0805210858g52272e4ei3005e2fb6b056990@mail.gmail.com> <759f137c0805211355gcaca232m4455167afc635812@mail.gmail.com> <759f137c0805211401n5b893cc3ldafa8e16bb48a6d8@mail.gmail.com> <759f137c0805211645y4cf863ebu246413d8c925d7e6@mail.gmail.com> <1c2a2c590805211747u27fad136n6646e564dcf28008@mail.gmail.com> <759f137c0805211941s2eef77dfqf0335d4e5a8ec11@mail.gmail.com> Message-ID: <1c2a2c590805220307w6e74e219w8cd84c6c07d833eb@mail.gmail.com> Forwarding to the list. ---------- Forwarded message ---------- From: Laureano Arcanio Date: Wed, May 21, 2008 at 10:41 PM Subject: Re: [Tutor] listing classes To: Kent Johnson I'm building a light html serialize tool, it's going to be used to build templates on the fly for ToscaWidgets. I have it already working, but i'm traying to make a "user friendly" way to declare Tags and Documents. ( that with some other facilities ) So the idea of the class containing classes, it's just with that end. Syntactic sugar let's say. The problem comes because i need to keep the order of the HTML tags, and as you say dict doesn't work like that.. I've working on this metaclass, and then extend list with it, but i have the same problem, the dct comes in a dict... class MetaHTML(type): def __new__(meta, name , bases, dct): # Deletes methods and attributes containing "_" items = [] for key, value in dct.items(): if '_' in key: dct.pop(key) items = [tag() for tag in dct.values()] def __init__(self, items=items): self.extend(items) dct.update({'__slots__':[], '__init__':__init__}) return type.__new__(meta,name,bases,dct) class HTML(list): __metaclass__ = MetaHTML I'm write this metaclass inspired in the WidgetsList that comes shipped with toscawidgets. I can do definitely the same using a list and just doing: document = [A(), B()] But it's not so nice. Any suggestion ? Thanks From ricaraoz at gmail.com Wed May 21 15:53:22 2008 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Wed, 21 May 2008 10:53:22 -0300 Subject: [Tutor] String Replacement question In-Reply-To: <20080521150521.604437d8@atlantiscomputing.com> References: <20080521150521.604437d8@atlantiscomputing.com> Message-ID: <48342952.9030706@bigfoot.com> Faheem wrote: > Hi all, > How do I replace the same value multiple times without repeating the > same variable name/value repeatedly? > for ex. > > some = 'thing' > print '%s %s %s %s' % (some,some,some,some) > > in this case, my question is how do i replace "% (some,some,some)" with > something more concise? > print '%s %s %s %s' % ((some,) * 4) HTH From srilyk at gmail.com Thu May 22 13:38:32 2008 From: srilyk at gmail.com (W W) Date: Thu, 22 May 2008 06:38:32 -0500 Subject: [Tutor] Fwd: listing classes In-Reply-To: <1c2a2c590805220307w6e74e219w8cd84c6c07d833eb@mail.gmail.com> References: <759f137c0805200826t29f4e397nb59d2ce12ccf3c47@mail.gmail.com> <1c2a2c590805201048q15dd20d3y8c50c9887fa51a7b@mail.gmail.com> <20080521000126.GA59289@cutter.rexx.com> <759f137c0805210858g52272e4ei3005e2fb6b056990@mail.gmail.com> <759f137c0805211355gcaca232m4455167afc635812@mail.gmail.com> <759f137c0805211401n5b893cc3ldafa8e16bb48a6d8@mail.gmail.com> <759f137c0805211645y4cf863ebu246413d8c925d7e6@mail.gmail.com> <1c2a2c590805211747u27fad136n6646e564dcf28008@mail.gmail.com> <759f137c0805211941s2eef77dfqf0335d4e5a8ec11@mail.gmail.com> <1c2a2c590805220307w6e74e219w8cd84c6c07d833eb@mail.gmail.com> Message-ID: <333efb450805220438kf48c9fao698a864ee7b935ad@mail.gmail.com> I don't know if this is the best solution, but what I usually do is create a list that matches the key: mydict = {} mylist = [] for x in range(1, 10): key = raw_input("Enter the key: ") mydict[key] = value mylist.append(key) You just have to change it to read from a file/hard code all the tags or what not. HTH, Wayne On Thu, May 22, 2008 at 5:07 AM, Kent Johnson wrote: > Forwarding to the list. > > > ---------- Forwarded message ---------- > From: Laureano Arcanio > Date: Wed, May 21, 2008 at 10:41 PM > Subject: Re: [Tutor] listing classes > To: Kent Johnson > > > I'm building a light html serialize tool, it's going to be used to > build templates on the fly for ToscaWidgets. I have it already > working, but i'm traying to make a "user friendly" way to declare Tags > and Documents. ( that with some other facilities ) > > So the idea of the class containing classes, it's just with that end. > Syntactic sugar let's say. > > The problem comes because i need to keep the order of the HTML tags, > and as you say dict doesn't work like that.. I've working on this > metaclass, and then extend list with it, but i have the same problem, > the dct comes in a dict... > > class MetaHTML(type): > def __new__(meta, name , bases, dct): > # Deletes methods and attributes containing "_" > items = [] > for key, value in dct.items(): > if '_' in key: > dct.pop(key) > > items = [tag() for tag in dct.values()] > > def __init__(self, items=items): > self.extend(items) > dct.update({'__slots__':[], '__init__':__init__}) > return type.__new__(meta,name,bases,dct) > > class HTML(list): > __metaclass__ = MetaHTML > > > I'm write this metaclass inspired in the WidgetsList that comes > shipped with toscawidgets. > > I can do definitely the same using a list and just doing: > > document = [A(), > B()] > > But it's not so nice. > > Any suggestion ? > > Thanks > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi From kent37 at tds.net Thu May 22 14:37:02 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 22 May 2008 08:37:02 -0400 Subject: [Tutor] listing classes In-Reply-To: <759f137c0805211941s2eef77dfqf0335d4e5a8ec11@mail.gmail.com> References: <759f137c0805200826t29f4e397nb59d2ce12ccf3c47@mail.gmail.com> <483300A0.8070509@gmail.com> <1c2a2c590805201048q15dd20d3y8c50c9887fa51a7b@mail.gmail.com> <20080521000126.GA59289@cutter.rexx.com> <759f137c0805210858g52272e4ei3005e2fb6b056990@mail.gmail.com> <759f137c0805211355gcaca232m4455167afc635812@mail.gmail.com> <759f137c0805211401n5b893cc3ldafa8e16bb48a6d8@mail.gmail.com> <759f137c0805211645y4cf863ebu246413d8c925d7e6@mail.gmail.com> <1c2a2c590805211747u27fad136n6646e564dcf28008@mail.gmail.com> <759f137c0805211941s2eef77dfqf0335d4e5a8ec11@mail.gmail.com> Message-ID: <1c2a2c590805220537g10f5d765nd7f5d69f06452336@mail.gmail.com> On Wed, May 21, 2008 at 10:41 PM, Laureano Arcanio wrote: > The problem comes because i need to keep the order of the HTML tags, and as > you say dict doesn't work like that.. I've working on this metaclass, and > then extend list with it, but i have the same problem, the dct comes in a > dict... > > class MetaHTML(type): > def __new__(meta, name , bases, dct): > # Deletes methods and attributes containing "_" > items = [] > for key, value in dct.items(): > if '_' in key: > dct.pop(key) > > items = [tag() for tag in dct.values()] > > def __init__(self, items=items): > self.extend(items) > dct.update({'__slots__':[], '__init__':__init__}) > return type.__new__(meta,name,bases,dct) > > class HTML(list): > __metaclass__ = MetaHTML The *nested* classes need a metaclass that keeps track of order. At the point of creation of the nested class object, you can add the object to a list. I think you can do this with a metaclass... Kent From gtxy20 at gmail.com Thu May 22 18:14:56 2008 From: gtxy20 at gmail.com (GTXY20) Date: Thu, 22 May 2008 12:14:56 -0400 Subject: [Tutor] Randomize SSN value in field Message-ID: <39cb7e5d0805220914m39a5c517w654163da4e813d1a@mail.gmail.com> Hello all, I will be dealing with an address list where I might have the following: Name SSN John 111111111 John 111111111 Jane 222222222 Jill 333333333 What I need to do is parse the address list and then create a unique random unidentifiable value for the SSN field like so: Name SSNrandomvalue John 1a1b1c1d1 John 1a1b1c1d1 Jane 2a2b2c2d2 Jill 3a3b3c3d3 The unique random value does not have to follow this convention but it needs to be unique so that I can relate it back to the original SSN when needed. As opposed to using the random module I was thinking that it would be better to use either sha or md5. Just curious as to thoughts on the correct approach. Thank you in advance. G. -------------- next part -------------- An HTML attachment was scrubbed... URL: From taserian at gmail.com Thu May 22 19:17:58 2008 From: taserian at gmail.com (taserian) Date: Thu, 22 May 2008 13:17:58 -0400 Subject: [Tutor] Randomize SSN value in field In-Reply-To: <39cb7e5d0805220914m39a5c517w654163da4e813d1a@mail.gmail.com> References: <39cb7e5d0805220914m39a5c517w654163da4e813d1a@mail.gmail.com> Message-ID: <70dbc4d40805221017o7d051487y508b6bd98e73c38f@mail.gmail.com> On Thu, May 22, 2008 at 12:14 PM, GTXY20 wrote: > Hello all, > > I will be dealing with an address list where I might have the following: > > Name SSN > John 111111111 > John 111111111 > Jane 222222222 > Jill 333333333 > > What I need to do is parse the address list and then create a unique random > unidentifiable value for the SSN field like so: > > Name SSNrandomvalue > John 1a1b1c1d1 > John 1a1b1c1d1 > Jane 2a2b2c2d2 > Jill 3a3b3c3d3 > > The unique random value does not have to follow this convention but it needs > to be unique so that I can relate it back to the original SSN when needed. > As opposed to using the random module I was thinking that it would be better > to use either sha or md5. Just curious as to thoughts on the correct > approach. > > Thank you in advance. > > G. Both SHA and MD5 are intended to be one-way functions, such that you can't recover what you provide as an argument. For example (taken from http://www.python.org/doc/current/lib/module-hashlib.html) : >>> hashlib.sha224("Nobody inspects the spammish repetition").hexdigest() 'a4337bc45a8fc544c03f52dc550cd6e1e87021bc896588bd79e901e2' There's no way to take the value 'a4337...' and return "Nobody insp..", because there are potentially infinite strings that have to map into the available 224-bit space that sha224 provides. If you want to be able to recover the SSN, you should probably look at cryptography. Here's a link that might interest you: http://www.amk.ca/python/code/crypto.html Tony R. aka Taser From srilyk at gmail.com Thu May 22 19:20:07 2008 From: srilyk at gmail.com (W W) Date: Thu, 22 May 2008 12:20:07 -0500 Subject: [Tutor] Randomize SSN value in field In-Reply-To: <39cb7e5d0805220914m39a5c517w654163da4e813d1a@mail.gmail.com> References: <39cb7e5d0805220914m39a5c517w654163da4e813d1a@mail.gmail.com> Message-ID: <333efb450805221020t22693422iaf70ccf62941d9ef@mail.gmail.com> Oops! Maybe it works better with reply to all: You're looking for a completely random 9 digit number that you can't derive the name from? I don't know that anything would really be more or less secure than simply using random. >>> import random >>> random.randrange(100000000,999999999) 988559585 >>> random.randrange(100000000,999999999) 905877832 >>> random.randrange(100000000,999999999) Just for kicks and giggles, I've tried and at least 35,000 records came up with no repeats. Of course you'd want to check that, and the easiest way is using a dict/hashtable. I'm checking to see if out of 500,000 records I can generate a repeated value, though. Is there any particular reason you're worried about using random to generate the fake SSN? At least, one that you can share with us? ------- I went ahead and wrote a program to generate 500,000 random SSNs, and I got a total of 132 repeats (assuming my code works how I wanted it to). If I'm correct in my math, that's about a .0003% chance of repeat, using the same system. Also just FYI, it took about 23 seconds to generate all 500,000. if you would like to see my code, just ask! HTH, Wayne On Thu, May 22, 2008 at 11:14 AM, GTXY20 wrote: > Hello all, > > I will be dealing with an address list where I might have the following: > > Name SSN > John 111111111 > John 111111111 > Jane 222222222 > Jill 333333333 > > What I need to do is parse the address list and then create a unique random > unidentifiable value for the SSN field like so: > > Name SSNrandomvalue > John 1a1b1c1d1 > John 1a1b1c1d1 > Jane 2a2b2c2d2 > Jill 3a3b3c3d3 > > The unique random value does not have to follow this convention but it needs > to be unique so that I can relate it back to the original SSN when needed. > As opposed to using the random module I was thinking that it would be better > to use either sha or md5. Just curious as to thoughts on the correct > approach. > > Thank you in advance. > > G. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi From srilyk at gmail.com Thu May 22 19:26:18 2008 From: srilyk at gmail.com (W W) Date: Thu, 22 May 2008 12:26:18 -0500 Subject: [Tutor] Randomize SSN value in field In-Reply-To: <70dbc4d40805221017o7d051487y508b6bd98e73c38f@mail.gmail.com> References: <39cb7e5d0805220914m39a5c517w654163da4e813d1a@mail.gmail.com> <70dbc4d40805221017o7d051487y508b6bd98e73c38f@mail.gmail.com> Message-ID: <333efb450805221026r57ad66d3wfa70317d47e336ea@mail.gmail.com> On Thu, May 22, 2008 at 12:17 PM, taserian wrote: > so that I can relate it back to the original SSN when needed. Oh! Oops! I didn't clearly understand this sentence the first time. Yes, you want to learn about cryptography. Google for Bruce Schneier - one of the world's foremost crypto experts. PGP is a form of cryptography. Basically, using something like PGP should suit your needs, though if you're worried about the security of the SSN, there are various other concerns to take into account. HTH, Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi From kent37 at tds.net Thu May 22 19:39:04 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 22 May 2008 13:39:04 -0400 Subject: [Tutor] Randomize SSN value in field In-Reply-To: <39cb7e5d0805220914m39a5c517w654163da4e813d1a@mail.gmail.com> References: <39cb7e5d0805220914m39a5c517w654163da4e813d1a@mail.gmail.com> Message-ID: <1c2a2c590805221039x1345db94h5756d4958596da1d@mail.gmail.com> On Thu, May 22, 2008 at 12:14 PM, GTXY20 wrote: > Hello all, > > I will be dealing with an address list where I might have the following: > > Name SSN > John 111111111 > John 111111111 > Jane 222222222 > Jill 333333333 > > What I need to do is parse the address list and then create a unique random > unidentifiable value for the SSN field > The unique random value does not have to follow this convention but it needs > to be unique so that I can relate it back to the original SSN when needed. > As opposed to using the random module I was thinking that it would be better > to use either sha or md5. Just curious as to thoughts on the correct > approach. How are you relating back to the SSN? Are you keeping a cross-reference? If so, you might just assign sequence numbers for the unidentifiable value. If you want the key itself to be convertable back to the SSN (which wouldn't work with random values) you will need some cryptography. If you want a unique key that won't collide with other keys then sha or md5 is a better bet than random. Kent From gtxy20 at gmail.com Thu May 22 19:56:22 2008 From: gtxy20 at gmail.com (GTXY20) Date: Thu, 22 May 2008 13:56:22 -0400 Subject: [Tutor] Randomize SSN value in field In-Reply-To: <1c2a2c590805221039x1345db94h5756d4958596da1d@mail.gmail.com> References: <39cb7e5d0805220914m39a5c517w654163da4e813d1a@mail.gmail.com> <1c2a2c590805221039x1345db94h5756d4958596da1d@mail.gmail.com> Message-ID: <39cb7e5d0805221056l7674a592m68333a1c11e4cdad@mail.gmail.com> Thanks all; Basically I will be given an address list of about 50 million address lines - this will boil down to approximately 15 million unique people in the list using SSN as the reference for the primary key. I was concerned that by using random I would eventually have duplicate values for different SSN's. After assigning the unique reference for the SSN I need to then forward the address file (complete 50 million records) to a larger group for analysis and assign the unique reference in place of the SSN. I will take a look at the various options I have with sha and md5 along with the information regarding cryptography to see what i can come up with. Alternatively I guess I could parse the address list and build a dictionary where the key is the SSN and the value starts at 1 and is incremented as I add addtional SSN keys to the dictionary. I would hold onto this dictionary for reference as information is fed back to me. With respect to a potentially large dictionary object can you suggest efficient ways of handling memory when working with large dictionary objects? As always your help much appreciated. G. On Thu, May 22, 2008 at 1:39 PM, Kent Johnson wrote: > On Thu, May 22, 2008 at 12:14 PM, GTXY20 wrote: > > Hello all, > > > > I will be dealing with an address list where I might have the following: > > > > Name SSN > > John 111111111 > > John 111111111 > > Jane 222222222 > > Jill 333333333 > > > > What I need to do is parse the address list and then create a unique > random > > unidentifiable value for the SSN field > > > The unique random value does not have to follow this convention but it > needs > > to be unique so that I can relate it back to the original SSN when > needed. > > As opposed to using the random module I was thinking that it would be > better > > to use either sha or md5. Just curious as to thoughts on the correct > > approach. > > How are you relating back to the SSN? Are you keeping a > cross-reference? If so, you might just assign sequence numbers for the > unidentifiable value. If you want the key itself to be convertable > back to the SSN (which wouldn't work with random values) you will need > some cryptography. If you want a unique key that won't collide with > other keys then sha or md5 is a better bet than random. > > Kent > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Thu May 22 20:07:49 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 22 May 2008 14:07:49 -0400 Subject: [Tutor] Randomize SSN value in field In-Reply-To: <39cb7e5d0805221056l7674a592m68333a1c11e4cdad@mail.gmail.com> References: <39cb7e5d0805220914m39a5c517w654163da4e813d1a@mail.gmail.com> <1c2a2c590805221039x1345db94h5756d4958596da1d@mail.gmail.com> <39cb7e5d0805221056l7674a592m68333a1c11e4cdad@mail.gmail.com> Message-ID: <1c2a2c590805221107l1cf5eaf1l7caabddcc5904068@mail.gmail.com> On Thu, May 22, 2008 at 1:56 PM, GTXY20 wrote: > With respect to a potentially large dictionary object can you suggest > efficient ways of handling memory when working with large dictionary > objects? Consider using a database. The public value can just be the primary key of the SSN in a database table. Kent From wescpy at gmail.com Thu May 22 20:25:48 2008 From: wescpy at gmail.com (wesley chun) Date: Thu, 22 May 2008 11:25:48 -0700 Subject: [Tutor] String Replacement question In-Reply-To: <1c2a2c590805210336h71fdc349r803b7ba076cb5f88@mail.gmail.com> References: <20080521150521.604437d8@atlantiscomputing.com> <1c2a2c590805210336h71fdc349r803b7ba076cb5f88@mail.gmail.com> Message-ID: <78b3a9580805221125u3832ddc0laac30ecb5cef4cb9@mail.gmail.com> > > some = 'thing' > > print '%s %s %s %s' % (some,some,some,some) > > You can use named parameters, which moves the repetition to the format string: > > In [24]: print '%(some)s %(some)s %(some)s %(some)s' % (dict(some=some)) > thing thing thing thing > > With multiple values, a common trick is to pass vars() or locals() as > the dict, giving the format access to all defined variables: > > In [27]: a=1 > In [28]: b=2 > In [29]: print '%(a)s %(b)s' % vars() > 1 2 everyone has clever solutions on the repeating, but as kent has shown in his example above, i think a dictionary form of the string format operator is the best solution. once you have the dictionary, you can add many more repetitions in your format string without touching the dictionary argument on the RHS, unlike using the tuple solution where you would have to update a multiplier. it's also works better if you have multiply-repeated variables... you don't have to create another variable on the right along with a multiplier. somewhere you just have to add it to the dict just once. cheers, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From dineshbvadhia at hotmail.com Thu May 22 23:53:41 2008 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Thu, 22 May 2008 14:53:41 -0700 Subject: [Tutor] Equivalent 'case' statement Message-ID: Is there an equivalent to the C/C++ 'case' (or 'switch') statement in Python? Dinesh -------------- next part -------------- An HTML attachment was scrubbed... URL: From inhahe at gmail.com Fri May 23 01:15:39 2008 From: inhahe at gmail.com (inhahe) Date: Thu, 22 May 2008 19:15:39 -0400 Subject: [Tutor] Equivalent 'case' statement In-Reply-To: References: Message-ID: no, but you can a) use elifs if c==1: do this elif c==2: do this elif c==3: do this b) make a dictionary of functions (this is faster) def case1: do this def case2: do that def case3: do the other cases = {1: case2, 2: case2, 3:case3} cases[c]() if your functions are one expression you could use lambdas cases = { 1: lambda: x*2 2: lambda: y**2 3: lambda: sys.stdout.write("hi\n") } cases[c]() your functions and lambdas can also take parameters of course On Thu, May 22, 2008 at 5:53 PM, Dinesh B Vadhia wrote: > Is there an equivalent to the C/C++ 'case' (or 'switch') statement in > Python? > > Dinesh > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From alan.gauld at btinternet.com Fri May 23 01:25:23 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 23 May 2008 00:25:23 +0100 Subject: [Tutor] Equivalent 'case' statement References: Message-ID: "Dinesh B Vadhia" wrote > Is there an equivalent to the C/C++ 'case' (or 'switch') statement > in Python? No, just if/elif However you can often achieve similar results with a dictionary: def func1(v): return v def func2(v): return v*2 switch = { 'val1': func1, # use a function for each value 'val2': func2, 'val3': lambda v: "this is three!" } # or use lambda if preferred val = raw_input("Value? (val1,val2,val3)") print switch.[val](val) ### which is equivalent to: if val == 'val1': print func1(val) elif val == 'val2': print func2(val) elif val == 'val3': print "this is three" HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From inhahe at gmail.com Fri May 23 01:25:55 2008 From: inhahe at gmail.com (inhahe) Date: Thu, 22 May 2008 19:25:55 -0400 Subject: [Tutor] Equivalent 'case' statement In-Reply-To: References: Message-ID: > > cases = { > 1: lambda: x*2 > 2: lambda: y**2 > 3: lambda: sys.stdout.write("hi\n") > } > i forgot the commas. cases = { 1: lambda: x*2, 2: lambda: y**2, 3: lambda: sys.stdout.write("hi\n") } > > your functions and lambdas can also take parameters of course > lambda a, b: a*b From jasonbconner at gmail.com Fri May 23 02:41:38 2008 From: jasonbconner at gmail.com (Jason Conner) Date: Fri, 23 May 2008 12:41:38 +1200 Subject: [Tutor] Reading only a few specific lines of a file Message-ID: Hey guys, Very new to programming Python, and I'm running up against a problem. I am building a program that will take a text file, search for a string in that text file. Once it finds the string its looking for, I want to put the next five lines of text into a variable. Here's what I have so far: def loadItem(self, objectToLoad): x = 0 wordList = [] fobj = file() fobj.open("itemconfig.txt", 'rU') for line in fobj.readline(): if line == objectToLoad: while x != 5 for word in line.split(): wordList.append(word) x += 1 thing = item(wordList[0], wordList[1], wordList[2], wordList[3], wordList[4]) itemList.append(thing) This, however, highlights my problem. "if line == objectToLoad:" ceases to be true on the second iteration, as it reads in another line. Is there a better way to do this, or should I just parse the whole document, and look for the strings I want to find? -------------- next part -------------- An HTML attachment was scrubbed... URL: From john at fouhy.net Fri May 23 03:03:11 2008 From: john at fouhy.net (John Fouhy) Date: Fri, 23 May 2008 13:03:11 +1200 Subject: [Tutor] Reading only a few specific lines of a file In-Reply-To: References: Message-ID: <5e58f2e40805221803mdac5dcdib9cfe4b5d8125670@mail.gmail.com> On 23/05/2008, Jason Conner wrote: Hi Jason, > def loadItem(self, objectToLoad): > x = 0 > wordList = [] > fobj = file() > fobj.open("itemconfig.txt", 'rU') > > for line in fobj.readline(): In recent pythons, you can write this better as: for line in fobj: Once you've done this, you can use .next() to advance the iterator. e.g.: for line in fobj: if line == objectToLoad: wordList.append(line) wordList.append(fobj.next()) This will save the line that matched and the line following it. Note that this means you won't check the second line --- you can maybe visualise this with a simpler example: >>> a = [] >>> nums = iter(range(10)) >>> for i in nums: ... a.append((i, nums.next())) ... >>> a [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)] -- John. From faheem at atlantiscomputing.com Fri May 23 06:10:02 2008 From: faheem at atlantiscomputing.com (Faheem) Date: Fri, 23 May 2008 09:40:02 +0530 Subject: [Tutor] String Replacement question Message-ID: <20080523094002.7611a729@atlantiscomputing.com> Hey All, Thanks.. That was quick. Good to know there is a mailing list like this one. Thanks to everyone and all the replies. Faheem From muchanek at gmail.com Fri May 23 12:32:05 2008 From: muchanek at gmail.com (Kinuthia Muchane) Date: Fri, 23 May 2008 13:32:05 +0300 Subject: [Tutor] Tutor Digest, Vol 51, Issue 51 In-Reply-To: References: Message-ID: <48369D25.8020301@gmail.com> tutor-request at python.org wrote: > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request at python.org > > You can reach the person managing the list at > tutor-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. Re: Equivalent 'case' statement (Alan Gauld) > 2. Re: Equivalent 'case' statement (inhahe) > 3. Reading only a few specific lines of a file (Jason Conner) > 4. Re: Reading only a few specific lines of a file (John Fouhy) > 5. Re: String Replacement question (Faheem) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Fri, 23 May 2008 00:25:23 +0100 > From: "Alan Gauld" > Subject: Re: [Tutor] Equivalent 'case' statement > To: tutor at python.org > Message-ID: > Content-Type: text/plain; format=flowed; charset="iso-8859-1"; > reply-type=original > > > "Dinesh B Vadhia" wrote > >> Is there an equivalent to the C/C++ 'case' (or 'switch') statement >> in Python? > > No, just if/elif > > However you can often achieve similar results with a dictionary: > > def func1(v): return v > > def func2(v): return v*2 > > > switch = { 'val1': func1, # use a function for each value > 'val2': func2, > 'val3': lambda v: "this is three!" } # or use > lambda if preferred > > val = raw_input("Value? (val1,val2,val3)") > Something small here. This > print switch.[val](val) should be: print switch[val](val) > > > ### which is equivalent to: > > if val == 'val1': print func1(val) > elif val == 'val2': print func2(val) > elif val == 'val3': print "this is three" > > HTH, > From kent37 at tds.net Fri May 23 12:48:02 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 23 May 2008 06:48:02 -0400 Subject: [Tutor] changin two lines in a single python script In-Reply-To: <1211381479.10205.13.camel@wipro.com> References: <1211381479.10205.13.camel@wipro.com> Message-ID: <1c2a2c590805230348w399ffd9am84356eb0efe2f0cf@mail.gmail.com> On Wed, May 21, 2008 at 10:51 AM, jatinder Singh wrote: > Hi . > > I am trying to change two lines in a single file (etc/php.ini) but my > script is not doing this in one time . See my answer to your almost identical question last week about modifying httpd.conf. Kent PS Please don't include the entire archive when you post. From alan.gauld at btinternet.com Fri May 23 12:49:37 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 23 May 2008 11:49:37 +0100 Subject: [Tutor] Reading only a few specific lines of a file References: Message-ID: "Jason Conner" wrote > building a program that will take a text file, search for a string > in that > text file. Once it finds the string its looking for, I want to put > the next > five lines of text into a variable. Here's what I have so far: > > def loadItem(self, objectToLoad): > x = 0 > wordList = [] > fobj = file() This does nothing. file() is just an alias for open() > fobj.open("itemconfig.txt", 'rU') > > for line in fobj.readline(): And you can iterate over the file itself so this could become: for line in file(("itemconfig.txt", 'rU'): > if line == objectToLoad: > while x != 5 > for word in line.split(): > wordList.append(word) > x += 1 This isn't quite what you said above in that you didn't mention storing the individual words... > > thing = item(wordList[0], wordList[1], wordList[2], wordList[3], > wordList[4]) But this could just be: thing = line.split[:5] # use slicing to get first 4 items > itemList.append(thing) or even make it all one line here... Now to get the next 4 lines as well set a flag/counter. say linecount. Set it to 0 at the top then linecount = 0 for line in file("itemconfig.txt", 'rU'): if line == objectToLoad or linecount > 0: if linecount == 0: linecount = 5 # set linecount on first line itemList.append(line.split()[:5]) linecount -= 1 HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From muchanek at gmail.com Fri May 23 13:59:45 2008 From: muchanek at gmail.com (Kinuthia Muchane) Date: Fri, 23 May 2008 14:59:45 +0300 Subject: [Tutor] Equivalent 'case' Statement In-Reply-To: References: Message-ID: <4836B1B1.9090504@gmail.com> Hi, I messed in earlier message, my apologies. > Message: 1 > Date: Fri, 23 May 2008 00:25:23 +0100 > From: "Alan Gauld" > Subject: Re: [Tutor] Equivalent 'case' statement > To: tutor at python.org > Message-ID: > Content-Type: text/plain; format=flowed; charset="iso-8859-1"; > reply-type=original > > > "Dinesh B Vadhia" wrote > >> Is there an equivalent to the C/C++ 'case' (or 'switch') statement >> in Python? > > No, just if/elif > > However you can often achieve similar results with a dictionary: > > def func1(v): return v > > def func2(v): return v*2 > > > switch = { 'val1': func1, # use a function for each value > 'val2': func2, > 'val3': lambda v: "this is three!" } # or use > lambda if preferred > > val = raw_input("Value? (val1,val2,val3)") > This: > print switch.[val](val) should be: print switch[val](val) > > > ### which is equivalent to: > > if val == 'val1': print func1(val) > elif val == 'val2': print func2(val) > elif val == 'val3': print "this is three" > > HTH, > From dnr at freemail.lt Fri May 23 17:23:12 2008 From: dnr at freemail.lt (dnr) Date: Fri, 23 May 2008 18:23:12 +0300 Subject: [Tutor] Decompyle and python 2.4 (2.5) Message-ID: <2DC0EDC4735F445C96BE8E992C36B3FF@in.telecom.lt> Hello, are there any volunteer who'd like to do some good for the python community? To be short - Decompyle package currently only supports python versions prior to 2.4. After small tuning it seems to support 2.4 and 2.5....partly Some tuning is required in parser.py which maps disassembled opcodes back to python syntax. details at: http://www.netzond.com/decompyle-vs-python-24-25/ please, don't be shy and express your opinion on this subject. -------------- next part -------------- An HTML attachment was scrubbed... URL: From marilyn at deliberate.com Fri May 23 18:22:34 2008 From: marilyn at deliberate.com (Marilyn Davis) Date: Fri, 23 May 2008 09:22:34 -0700 (PDT) Subject: [Tutor] Reading only a few specific lines of a file Message-ID: <55894.66.218.47.125.1211559754.squirrel@mail.tigertech.net> (I'm sorry for the duplicate, Alan.) On Fri, May 23, 2008 3:49 am, Alan Gauld wrote: > "Jason Conner" wrote > > >> building a program that will take a text file, search for a string in >> that text file. Once it finds the string its looking for, I want to put >> the next five lines of text into a variable. Here's what I have so far: >> >> def loadItem(self, objectToLoad): x = 0 wordList = [] fobj = file() > > This does nothing. file() is just an alias for open() > > > >> fobj.open("itemconfig.txt", 'rU') >> >> for line in fobj.readline(): > > And you can iterate over the file itself so this could become: > > > for line in file(("itemconfig.txt", 'rU'): > > >> if line == objectToLoad: while x != 5 for word in line.split(): >> wordList.append(word) x += 1 > > This isn't quite what you said above in that you didn't mention > storing the individual words... > >> >> thing = item(wordList[0], wordList[1], wordList[2], wordList[3], >> wordList[4]) > > But this could just be: > > > thing = line.split[:5] # use slicing to get first 4 items > >> itemList.append(thing) > > or even make it all one line here... > > Now to get the next 4 lines as well set a flag/counter. say linecount. > Set it to 0 at the top then > > > linecount = 0 for line in file("itemconfig.txt", 'rU'): if line == > objectToLoad or linecount > 0: if linecount == 0: linecount = 5 # set > linecount on first line itemList.append(line.split()[:5]) > linecount -= 1 I always go for readability. So I like "for x in range(5):" to go 5 times. I'm not sure what we should be doing 5 times either. Similarly, for readability, I choose the if/elif/else form of switch replacement. Also, I don't like to see the obfuscated forms of the conditional operator. Heck, I'm not even crazy about the Python conditional in 2.5. I like to say "The point of a programming language is to communicate with other engineers (in a language that also the computer understands)." I hope you like these thoughts. Marilyn Davis > > > HTH, > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Fri May 23 18:59:54 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 23 May 2008 17:59:54 +0100 Subject: [Tutor] Decompyle and python 2.4 (2.5) References: <2DC0EDC4735F445C96BE8E992C36B3FF@in.telecom.lt> Message-ID: "dnr" wrote > are there any volunteer who'd like to do some good for the python > community? > To be short - Decompyle package currently only supports python > versions prior to 2.4. These sort of requests are probably better targetted at the main comp.lang.python list rather than a list for beginners. > Some tuning is required in parser.py ... > details at: http://www.netzond.com/decompyle-vs-python-24-25/ > > please, don't be shy and express your opinion on this subject. Since you seem to have figured out what needs doing, why not try it yourself? -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Fri May 23 19:06:17 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 23 May 2008 18:06:17 +0100 Subject: [Tutor] Reading only a few specific lines of a file References: <55894.66.218.47.125.1211559754.squirrel@mail.tigertech.net> Message-ID: "Marilyn Davis" wrote > (I'm sorry for the duplicate, Alan.) I didn't see a duplicate! ;-) >> linecount = 0 >> for line in file("itemconfig.txt", 'rU'): >> if line == objectToLoad or linecount > 0: >> if linecount == 0: linecount = 5 >> itemList.append(line.split()[:5]) >> linecount -= 1 > > I always go for readability. So I like "for x in range(5):" to go 5 > times. I'm not sure what we should be doing 5 times either. You could use a nested for loop but that would involve the use of an iterator.next() function which I didn't want to confuse the issue with, although John has pointed it out now anyway. Since the outer for loop is doing the next() call for us it didn't seem necessary. > Similarly, for readability, I choose the if/elif/else form of switch > replacement. Are you referring to the other thread? There is no switch here. > Also, I don't like to see the obfuscated forms of the conditional > operator. Heck, I'm not even crazy about the Python conditional in > 2.5. Similarly there is no conditional statements here? Again are you refering to the other recent thread? > I like to say "The point of a programming language is to communicate > with > other engineers (in a language that also the computer understands)." I agree. :-) Alan G. From marilyn at deliberate.com Fri May 23 19:30:47 2008 From: marilyn at deliberate.com (Marilyn Davis) Date: Fri, 23 May 2008 10:30:47 -0700 (PDT) Subject: [Tutor] Readability, in general: was Re: Reading only a few specific lines of a file In-Reply-To: References: <55894.66.218.47.125.1211559754.squirrel@mail.tigertech.net> Message-ID: <42302.66.218.47.125.1211563847.squirrel@mail.tigertech.net> On Fri, May 23, 2008 10:06 am, Alan Gauld wrote: > "Marilyn Davis" wrote > > >> (I'm sorry for the duplicate, Alan.) >> > > I didn't see a duplicate! ;-) > > >>> linecount = 0 for line in file("itemconfig.txt", 'rU'): if line == >>> objectToLoad or linecount > 0: if linecount == 0: linecount = 5 >>> itemList.append(line.split()[:5]) >>> linecount -= 1 >> >> I always go for readability. So I like "for x in range(5):" to go 5 >> times. I'm not sure what we should be doing 5 times either. > > You could use a nested for loop but that would involve the use > of an iterator.next() function which I didn't want to confuse the issue > with, although John has pointed it out now anyway. Since the outer for > loop is doing the next() call for us it didn't seem necessary. > >> Similarly, for readability, I choose the if/elif/else form of switch >> replacement. > > Are you referring to the other thread? > There is no switch here. > > >> Also, I don't like to see the obfuscated forms of the conditional >> operator. Heck, I'm not even crazy about the Python conditional in 2.5. >> > > Similarly there is no conditional statements here? Again are > you refering to the other recent thread? Yes, I am referring to other threads. I have time, right now, to read and learn. Maybe I should have said the same thing in each thread. I'm sorry. Marilyn > >> I like to say "The point of a programming language is to communicate >> with other engineers (in a language that also the computer understands)." >> > > I agree. :-) > > > Alan G. > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From kent37 at tds.net Fri May 23 20:38:36 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 23 May 2008 14:38:36 -0400 Subject: [Tutor] Fwd: syntax question In-Reply-To: <187d38240805231125k4ab2a716x4f9ebdbfef8fb791@mail.gmail.com> References: <34CE1020-04D9-4133-AB3C-D90F5F78E915@gmail.com> <187d38240805210900q15520d7ckf5a1f17d853cb9fd@mail.gmail.com> <187d38240805210900x41f381f4mc4af81ff9258f5c9@mail.gmail.com> <1c2a2c590805211036m221f1b7qb0b793bf2406c473@mail.gmail.com> <187d38240805231125k4ab2a716x4f9ebdbfef8fb791@mail.gmail.com> Message-ID: <1c2a2c590805231138u6c1d3df7v55d0ae7c5406d2d5@mail.gmail.com> On Fri, May 23, 2008 at 2:25 PM, Moishy Gluck wrote: > I came in python around 2.5. So I've been using "Boolean and 1 or 2". For Python 2.5 you should use the new syntax 1 if Boolean or 2 It doesn't have the problems of the unofficial syntax you quote. Kent From yxi at bcm.edu Fri May 23 23:22:23 2008 From: yxi at bcm.edu (Yuanxin Xi) Date: Fri, 23 May 2008 16:22:23 -0500 Subject: [Tutor] python 2D list Message-ID: <4837358F.4090601@bcm.edu> I'm a Python newbie and still exploring, just surprised to see this 2D list assignment while debugging. >>> a = [[0] *3] *4 >>> a [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]] >>> a[1][2] = 1 >>> a [[0, 0, 1], [0, 0, 1], [0, 0, 1], [0, 0, 1]] why is that a[0][2] a[1][2] a[2][2] a[3][2] are all assigned to 1 instead of only a[1][2] = 1? This is a little confusing and inconsistent with almost all other languages. Could anyone please help explain the assignment mechanism here? Thanks From srilyk at gmail.com Sat May 24 01:33:22 2008 From: srilyk at gmail.com (W W) Date: Fri, 23 May 2008 18:33:22 -0500 Subject: [Tutor] Fwd: python 2D list In-Reply-To: <333efb450805231630t5aa2a13by157c16d5be80273e@mail.gmail.com> References: <4837358F.4090601@bcm.edu> <333efb450805231630t5aa2a13by157c16d5be80273e@mail.gmail.com> Message-ID: <333efb450805231633r40b58869l1baa6b67a92b3f3@mail.gmail.com> Oops! Forgot to "Reply to All" ---------------- I'm not sure but take a look at this: >>> a = [[0]*3]*4 >>> a [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]] >>> a[1] [0, 0, 0] >>> a[0][0] = 4 >>> a [[4, 0, 0], [4, 0, 0], [4, 0, 0], [4, 0, 0]] >>> b = [[0,0,0],[0,0,0],[0,0,0]] >>> b [[0, 0, 0], [0, 0, 0], [0, 0, 0]] >>> b[0][0] = 4 >>> b [[4, 0, 0], [0, 0, 0], [0, 0, 0]] I think, if I'm not mistaken, that one part of your initialisation only creates 3 aliases, similar to something like this: list = [0, 0, 0] list = [list, list, list] and further testing supports this hypothesis: >>> list = [4400, 60, 70] >>> list = [list, list, list] >>> list [[4400, 60, 70], [4400, 60, 70], [4400, 60, 70]] >>> list[0][1] = 'foo' >>> list [[4400, 'foo', 70], [4400, 'foo', 70], [4400, 'foo', 70]] HTH, Wayne On Fri, May 23, 2008 at 4:22 PM, Yuanxin Xi wrote: > I'm a Python newbie and still exploring, just surprised to see this 2D list > assignment while debugging. > >>>> a = [[0] *3] *4 >>>> a > [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]] >>>> a[1][2] = 1 >>>> a > [[0, 0, 1], [0, 0, 1], [0, 0, 1], [0, 0, 1]] > > why is that a[0][2] a[1][2] a[2][2] a[3][2] are all assigned to 1 instead of > only a[1][2] = 1? This is a little confusing and inconsistent with almost > all other languages. Could anyone please help explain the assignment > mechanism here? Thanks > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi From alan.gauld at btinternet.com Sat May 24 01:50:30 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 24 May 2008 00:50:30 +0100 Subject: [Tutor] python 2D list References: <4837358F.4090601@bcm.edu> Message-ID: "Yuanxin Xi" wrote > I'm a Python newbie and still exploring, just surprised to see this > 2D list assignment while debugging. > > >>> a = [[0] *3] *4 This creates a list with 3 zeros then creates a second list with 4 references to the first list. Remember that in Python all variables are references. > >>> a[1][2] = 1 > >>> a > [[0, 0, 1], [0, 0, 1], [0, 0, 1], [0, 0, 1]] > > why is that a[0][2] a[1][2] a[2][2] a[3][2] are all assigned to 1 Because your list is 4 references to the same list. You changed the underlying list so all references reflect the change. > This is a little confusing and inconsistent with almost all other > languages. Could anyone please help Its not inconsistent with, say C/C++ if you think of a C array of pointers. Something like (My C is rusty!) void main() { int *ia = {0,0,0}; int **ipa = {ia,ia,ia}; ipa[1][2] = 1; } HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From inhahe at gmail.com Sat May 24 01:52:22 2008 From: inhahe at gmail.com (inhahe) Date: Fri, 23 May 2008 19:52:22 -0400 Subject: [Tutor] __getattr__ can't be a staticmethod? Message-ID: why doesn't this work? >>> class a: ... @staticmethod ... def __getattr__(attr): ... return "I am a dork" ... >>> f = a() >>> f.hi Traceback (most recent call last): File "", line 1, in TypeError: 'staticmethod' object is not callable From kent37 at tds.net Sat May 24 04:34:47 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 23 May 2008 22:34:47 -0400 Subject: [Tutor] python 2D list In-Reply-To: <4837358F.4090601@bcm.edu> References: <4837358F.4090601@bcm.edu> Message-ID: <1c2a2c590805231934t18f05e71j2c8750702faab81c@mail.gmail.com> On Fri, May 23, 2008 at 5:22 PM, Yuanxin Xi wrote: > I'm a Python newbie and still exploring, just surprised to see this 2D list > assignment while debugging. http://www.python.org/doc/faq/programming/#how-do-i-create-a-multidimensional-list Kent From kent37 at tds.net Sat May 24 04:47:01 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 23 May 2008 22:47:01 -0400 Subject: [Tutor] __getattr__ can't be a staticmethod? In-Reply-To: References: Message-ID: <1c2a2c590805231947i59fa64eck5c4f798d277a3663@mail.gmail.com> On Fri, May 23, 2008 at 7:52 PM, inhahe wrote: > why doesn't this work? > >>>> class a: > ... @staticmethod > ... def __getattr__(attr): > ... return "I am a dork" > ... >>>> f = a() >>>> f.hi > Traceback (most recent call last): > File "", line 1, in > TypeError: 'staticmethod' object is not callable I don't know why you are getting that specific error, but what are you trying to do? This code doesn't make sense. __getattr__() is the hook for getting attributes of an object; staticmethods aren't associated with any object. What attributes do you want to get? Kent From dineshbvadhia at hotmail.com Sat May 24 12:36:48 2008 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Sat, 24 May 2008 03:36:48 -0700 Subject: [Tutor] Equivalent 'case' statement References: Message-ID: The dictionary of functions was the way to go and does perform much faster than if/elif's. Thank-you! ----- Original Message ----- From: inhahe To: Dinesh B Vadhia Cc: tutor at python.org Sent: Thursday, May 22, 2008 4:15 PM Subject: Re: [Tutor] Equivalent 'case' statement no, but you can a) use elifs if c==1: do this elif c==2: do this elif c==3: do this b) make a dictionary of functions (this is faster) def case1: do this def case2: do that def case3: do the other cases = {1: case2, 2: case2, 3:case3} cases[c]() if your functions are one expression you could use lambdas cases = { 1: lambda: x*2 2: lambda: y**2 3: lambda: sys.stdout.write("hi\n") } cases[c]() your functions and lambdas can also take parameters of course On Thu, May 22, 2008 at 5:53 PM, Dinesh B Vadhia wrote: > Is there an equivalent to the C/C++ 'case' (or 'switch') statement in > Python? > > Dinesh > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Sat May 24 14:02:22 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 24 May 2008 08:02:22 -0400 Subject: [Tutor] __getattr__ can't be a staticmethod? In-Reply-To: <1c2a2c590805240501s72a4b915ke99904021eb930a6@mail.gmail.com> References: <1c2a2c590805231947i59fa64eck5c4f798d277a3663@mail.gmail.com> <1c2a2c590805240501s72a4b915ke99904021eb930a6@mail.gmail.com> Message-ID: <1c2a2c590805240502t6e74cdb4o4119f455ce263b38@mail.gmail.com> On Sat, May 24, 2008 at 2:45 AM, inhahe wrote: > On Fri, May 23, 2008 at 10:47 PM, Kent Johnson wrote: >> On Fri, May 23, 2008 at 7:52 PM, inhahe wrote: >>> why doesn't this work? >>> >>>>>> class a: >>> ... @staticmethod >>> ... def __getattr__(attr): >>> ... return "I am a dork" >>> ... >>>>>> f = a() >>>>>> f.hi >>> Traceback (most recent call last): >>> File "", line 1, in >>> TypeError: 'staticmethod' object is not callable >> > I wanted to set getattr on a class. I don't need an object. I'm not > really getting anything > specific to the class or an object of it. i'm using it because f.hi() > is easier than f('hi')(). In your example, f is an instance and normal getattr would do what you want. For example: class a: def __getattr__(self, attr): return "I am a dork" f = a() print f.hi prints "I am a dork" If you want to be able to ask for a.hi then you need a metaclass - you have to define __getattr__() in the class of a, which is its metaclass: class meta(type): def __getattr__(self, attr): return "I am a dork" class b(object): __metaclass__ = meta print b.hi Kent From dnr at freemail.lt Sat May 24 18:00:47 2008 From: dnr at freemail.lt (dnr) Date: Sat, 24 May 2008 19:00:47 +0300 Subject: [Tutor] Decompyle and python 2.4 (2.5) In-Reply-To: References: <2DC0EDC4735F445C96BE8E992C36B3FF@in.telecom.lt> Message-ID: <7ACB5EA26F464F2CAEE935A320F52EB1@dongndm> sadly I don't speak this language(java is my religion) - it will take weeks for me to dig into the code. Personaly I don't have an interest anymore in revealing what's behind the *.pyc curtains because I got what I wanted. Still, assuming the fact that 90% of work is allready done and there's so few left in having what thousands of people were looking for, I feel my conscience-stricken. nevermind, I'll repost this at lang.python >> are there any volunteer who'd like to do some good for the python >> community? >> To be short - Decompyle package currently only supports python >> versions prior to 2.4. > > These sort of requests are probably better targetted at > the main comp.lang.python list rather than a list for beginners. > >> Some tuning is required in parser.py ... >> details at: http://www.netzond.com/decompyle-vs-python-24-25/ >> >> please, don't be shy and express your opinion on this subject. > > Since you seem to have figured out what needs doing, why > not try it yourself? From jasonbconner at gmail.com Sun May 25 01:09:13 2008 From: jasonbconner at gmail.com (Jason Conner) Date: Sun, 25 May 2008 11:09:13 +1200 Subject: [Tutor] Reading only a few specific lines of a file In-Reply-To: References: <55894.66.218.47.125.1211559754.squirrel@mail.tigertech.net> Message-ID: Hey guys, I went with a combination of the above, though I tried several different solutions. Here's what I ended up with: def loadItem(self, objectToLoad): wordList = [] fobj = open('/home/jason.conner/Documents/Python/objectconfig.txt', 'r') for line in fobj: if line == objectToLoad: wordList.append(line) for i in range(5): wordList.append(fobj.next()) Though it did take me a few minutes to figure out that I needed to include the \n in the objectToLoad variable to get it to work in its present form, it works great. Thanks for all your help! -------------- next part -------------- An HTML attachment was scrubbed... URL: From eric at ericabrahamsen.net Sun May 25 12:30:28 2008 From: eric at ericabrahamsen.net (Eric Abrahamsen) Date: Sun, 25 May 2008 18:30:28 +0800 Subject: [Tutor] get/set attributes Message-ID: <6BB36E8B-51BC-4472-A88B-EDD55FC40DD4@ericabrahamsen.net> Hello, I'm trying to create a Dummy class of objects, something that will return an empty string for any attribute. I'm making a very simple CMS with Cherrypy/Sqlalchemy/Cheetah, and I have an HTML form template that I use for editing/creating objects to save to the database. I'm using just one form template, and I want to either pass an object from the database to the template (for editing existing objects), or a Dummy object which outputs empty strings for all the HTML form fields, creating a blank form. Additionally, I'd like to be able to pass keyword arguments to the Dummy() initialization which get turned into attributes, so I can output various default values for the form fields. What I've got so far handles non-existent attributes fine, but using keywords to create attributes isn't working (attributes thus set still output an empty string), and I'm not sure why. Here's the class: class Dummy(object): def __init__(self,**atts): for k,v in atts.items(): self.k = v def __repr__(self): return '' def __getattr__(self, attr): return '' >>> dum = Dummy(name='John') >>> dum >>> dum.nationality '' >>> dum.name '' __getattr__ says it only comes into play when an attribute is NOT found, so I must be doing something wrong in the __init__ method... Thanks in advance, Eric From kent37 at tds.net Sun May 25 14:59:40 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 25 May 2008 08:59:40 -0400 Subject: [Tutor] Reading only a few specific lines of a file In-Reply-To: References: <55894.66.218.47.125.1211559754.squirrel@mail.tigertech.net> Message-ID: <1c2a2c590805250559h342e75abp47de00f30f5defca@mail.gmail.com> On Sat, May 24, 2008 at 7:09 PM, Jason Conner wrote: > def loadItem(self, objectToLoad): > wordList = [] > fobj = open('/home/jason.conner/Documents/Python/objectconfig.txt', 'r') > > for line in fobj: > if line == objectToLoad: > wordList.append(line) > for i in range(5): > wordList.append(fobj.next()) > > Though it did take me a few minutes to figure out that I needed to include > the \n in the objectToLoad variable to get it to work in its present form, > it works great. Thanks for all your help! Yes, the lines you get from iterating the file contain the trailing newlines. A simple fix (which strips *all* whitespace from both ends of the line) is to say line = line.strip() You can be more restrictive if you want, for example line = line.rstrip('\r\n') will strip only carriage returns and line feeds from the end (right side) of line. Note that wordList will also include newlines in its entries. You might want to use some variation of wordList.append(fobj.next().strip()) Kent From kent37 at tds.net Sun May 25 15:03:07 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 25 May 2008 09:03:07 -0400 Subject: [Tutor] get/set attributes In-Reply-To: <6BB36E8B-51BC-4472-A88B-EDD55FC40DD4@ericabrahamsen.net> References: <6BB36E8B-51BC-4472-A88B-EDD55FC40DD4@ericabrahamsen.net> Message-ID: <1c2a2c590805250603q18e72e20l3e7a0fb2c3c8e8f3@mail.gmail.com> On Sun, May 25, 2008 at 6:30 AM, Eric Abrahamsen wrote: > What I've got so far handles non-existent attributes fine, but using > keywords to create attributes isn't working (attributes thus set still > output an empty string), and I'm not sure why. Here's the class: > > class Dummy(object): > def __init__(self,**atts): > for k,v in atts.items(): > self.k = v This creates an attribute named k; it does not create an attribute whose name is the *value* of k. For that you need setattr: setattr(self, k, v) There is a shortcut that replaces the entire loop: self.__dict__.update(atts) Kent From alan.gauld at btinternet.com Sun May 25 16:55:16 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 25 May 2008 15:55:16 +0100 Subject: [Tutor] get/set attributes References: <6BB36E8B-51BC-4472-A88B-EDD55FC40DD4@ericabrahamsen.net> Message-ID: "Eric Abrahamsen" wrote > return an empty string for any attribute. I'm making a very simple > CMS with Cherrypy/Sqlalchemy/Cheetah, Those are the components of TurboGears. You might save a lot of bother by using TG instead of trying to write all the glue code yourself. Form handling for one would come for free, as would logins, help pages etc etc. OTOH maybe you are doing this as a learning exercise in which case have at it! :-) -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From eric at ericabrahamsen.net Sun May 25 18:52:24 2008 From: eric at ericabrahamsen.net (Eric Abrahamsen) Date: Mon, 26 May 2008 00:52:24 +0800 Subject: [Tutor] get/set attributes In-Reply-To: References: <6BB36E8B-51BC-4472-A88B-EDD55FC40DD4@ericabrahamsen.net> Message-ID: <4BB3EEDF-2AF5-4A7C-B6AD-9875176AEE1C@ericabrahamsen.net> > This creates an attribute named k; it does not create an attribute > whose name is the *value* of k. For that you need setattr: > setattr(self, k, v) > > There is a shortcut that replaces the entire loop: > self.__dict__.update(atts) Thanks Kent, that explains a lot about how things work. >> return an empty string for any attribute. I'm making a very simple >> CMS with Cherrypy/Sqlalchemy/Cheetah, > > Those are the components of TurboGears. > You might save a lot of bother by using TG instead of trying to > write all the glue code yourself. Form handling for one would > come for free, as would logins, help pages etc etc. > > OTOH maybe you are doing this as a learning exercise in > which case have at it! :-) I am doing this as a learning exercise, though I hadn't realized those are precisely TG's components. I'm actually coming at this from Django, and wanted to approach things at a lower level (every time a friend asks me to make a website for them I use it as an excuse to learn some new framework components). I wasn't really missing Django until I got to the 'CMS backend' stage of things ? forms for models, validation, etc. I'll stick through the learning exercise, but it will be *very* nice to return to a full framework package... Eric > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From kent37 at tds.net Sun May 25 21:32:32 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 25 May 2008 15:32:32 -0400 Subject: [Tutor] Reading only a few specific lines of a file In-Reply-To: <670cc5db0805251120k6dcbce06s45332786a9d7ac31@mail.gmail.com> References: <55894.66.218.47.125.1211559754.squirrel@mail.tigertech.net> <1c2a2c590805250559h342e75abp47de00f30f5defca@mail.gmail.com> <670cc5db0805251120k6dcbce06s45332786a9d7ac31@mail.gmail.com> Message-ID: <1c2a2c590805251232j4844e46dm63669be824b8ece4@mail.gmail.com> Forwarding to the list with my reply... On Sun, May 25, 2008 at 2:20 PM, Chester wrote: > Python uses \n as the newline character (which is a UNIX/Linux newline > character). I see you have Python for Windows installed and running it on > the Windows OS. The file objectconfig.txt has the Windows newline character > \r\n at the end of each physical line, which confuses the Python parser. I > think you need to look at the linesep function of the os module; that is, > use os.linesep (check how to use it) and you should be good. ;) Umm...no. \n does double-duty, in a way. It is the linefeed character, and it represents a newline. On Unix-like OSes such as Unix, Linux and MacOS X the newline character is a single linefeed so there is no difference between these two meanings. Windows uses two characters - carriage return + line feed - to represent a newline. When you read a text file in Python on Windows, the CRLF pairs are converted to a single LF char, or \n. So in this sense \n does represent a newline in a portable fashion. Note that this has nothing to do with the Python *parser*, which reads Python source files. It is the Python runtime that makes the translation. One every platform, when you read lines from a file using "for line in f", f.readline() or f.readlines(), the newline character is included in the returned line. This is the source of the OP's problem, not any confusion on the part of the parser or the runtime. Kent PS Please use Reply All to reply to the list. From wxpythoner at gmail.com Sun May 25 22:03:39 2008 From: wxpythoner at gmail.com (Chester) Date: Sun, 25 May 2008 22:03:39 +0200 Subject: [Tutor] Reading only a few specific lines of a file In-Reply-To: <1c2a2c590805251232j4844e46dm63669be824b8ece4@mail.gmail.com> References: <55894.66.218.47.125.1211559754.squirrel@mail.tigertech.net> <1c2a2c590805250559h342e75abp47de00f30f5defca@mail.gmail.com> <670cc5db0805251120k6dcbce06s45332786a9d7ac31@mail.gmail.com> <1c2a2c590805251232j4844e46dm63669be824b8ece4@mail.gmail.com> Message-ID: <670cc5db0805251303p23dc1e2ar31ebf8a4582b2abb@mail.gmail.com> I don't know then. Just hack your way through and tell us how did you manage to do it. ;) On Sun, May 25, 2008 at 9:32 PM, Kent Johnson wrote: > Forwarding to the list with my reply... > > On Sun, May 25, 2008 at 2:20 PM, Chester wrote: > > Python uses \n as the newline character (which is a UNIX/Linux newline > > character). I see you have Python for Windows installed and running it on > > the Windows OS. The file objectconfig.txt has the Windows newline > character > > \r\n at the end of each physical line, which confuses the Python parser. > I > > think you need to look at the linesep function of the os module; that is, > > use os.linesep (check how to use it) and you should be good. ;) > > Umm...no. > > \n does double-duty, in a way. It is the linefeed character, and it > represents a newline. > > On Unix-like OSes such as Unix, Linux and MacOS X the newline > character is a single linefeed so there is no difference between these > two meanings. > > Windows uses two characters - carriage return + line feed - to > represent a newline. When you read a text file in Python on Windows, > the CRLF pairs are converted to a single LF char, or \n. So in this > sense \n does represent a newline in a portable fashion. > > Note that this has nothing to do with the Python *parser*, which reads > Python source files. It is the Python runtime that makes the > translation. > > One every platform, when you read lines from a file using "for line in > f", f.readline() or f.readlines(), the newline character is included > in the returned line. This is the source of the OP's problem, not any > confusion on the part of the parser or the runtime. > > Kent > > PS Please use Reply All to reply to the list. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From zmanji at gmail.com Sun May 25 22:52:38 2008 From: zmanji at gmail.com (Zameer Manji) Date: Sun, 25 May 2008 16:52:38 -0400 Subject: [Tutor] How to get a string from a DOM Text node ? Message-ID: <4839D196.9090100@gmail.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA512 I'm trying to extract some information from the following xml file: http://pastebin.ca/1029125 This is the code that I have so far: import xml.dom.minidom file = "Music.xml" doc = xml.dom.minidom.parse(file) plist = doc.childNodes[1] dict = plist.childNodes[1] #dict contains App version and stuff, as well as tracks and playlist. tdict = dict.childNodes[21] #dict which contains dicts for each track, those dicts contain the info print tdict.childNodes[1] print tdict.childNodes[1].toxml() print tdict.childNodes[2] This code prints out the following: 42 The problem is that the Text node that is printed out is blank, when it should be 42. What do I need to do so I can get tdict.childNodes[2] to become a string being "42" ? -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.7 (MingW32) iQEcBAEBCgAGBQJIOdGWAAoJEA759sZQuQ1B6l8H/2i5FTlsSHPMzlc5ch2/DLiY 0yS1VWNQNuVh40WfK0SVFgsmFxNJ0IFQ+kkJsQPH/mcxQHbP+8iuzKiMuZIpIgUY Gx/DwfIUzg60W0cCe9gfguvnR/rOXFk/5PuoktWHe9/8bb1BoV+RAFyc9mEWzRzJ K6+/Rb7ISvQ/ptZ13PNgmX3UkLZU+qIFqlZZ+9rDld4iuyc+toqhdf4nUm7Bemen XivPf4H/n8OpckYeYKXuKyotacsIZQQraAJevSeiV/EWWrkgHyslktnRwIGVJlmJ CC8fgKE7DUVrI1PFBa2W48xlTOcpLtg9beB86J5cjNlsbVkSMC+gMiVVAGPooZc= =yPBg -----END PGP SIGNATURE----- -------------- next part -------------- A non-text attachment was scrubbed... Name: 0x50B90D41.asc Type: application/pgp-keys Size: 1724 bytes Desc: not available URL: From moishyyehuda at gmail.com Sun May 25 23:54:49 2008 From: moishyyehuda at gmail.com (Moishy Gluck) Date: Sun, 25 May 2008 17:54:49 -0400 Subject: [Tutor] Fwd: How to get a string from a DOM Text node ? In-Reply-To: <187d38240805251454q7114532et3e1aa4860f3e1663@mail.gmail.com> References: <4839D196.9090100@gmail.com> <187d38240805251454q7114532et3e1aa4860f3e1663@mail.gmail.com> Message-ID: <187d38240805251454t5c9fd2c1s64b7679b959986ca@mail.gmail.com> ---------- Forwarded message ---------- From: Moishy Gluck Date: Sun, May 25, 2008 at 5:54 PM Subject: Re: [Tutor] How to get a string from a DOM Text node ? To: Zameer Manji xml does not allow text in a node. So you kneed to place a node inside the node. Like such 42 xml is also case sensitive. So the T in Text must be capital. If you do not want to edit your xml file this will get you what you want. print tdict.childNodes[1].firstChild print tdict.childNodes[1].firstChild.nodeValue will output 42 The xml turns white space into a text node. So the whitespace between "42" and " ... " got parsed into a text node. Which is "tdict.childNodes[2]". " ... " Would be the value of "tdict.childNodes[3]". On Sun, May 25, 2008 at 4:52 PM, Zameer Manji wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA512 > > I'm trying to extract some information from the following xml file: > http://pastebin.ca/1029125 > > This is the code that I have so far: > > import xml.dom.minidom > file = "Music.xml" > doc = xml.dom.minidom.parse(file) > > plist = doc.childNodes[1] > > dict = plist.childNodes[1] #dict contains App version and stuff, as well > as tracks and playlist. > > tdict = dict.childNodes[21] #dict which contains dicts for each track, > those dicts contain the info > > print tdict.childNodes[1] > print tdict.childNodes[1].toxml() > print tdict.childNodes[2] > > This code prints out the following: > > > 42 > "> > > The problem is that the Text node that is printed out is blank, when it > should be 42. What do I need to do so I can get tdict.childNodes[2] to > become a string being "42" ? > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.4.7 (MingW32) > > iQEcBAEBCgAGBQJIOdGWAAoJEA759sZQuQ1B6l8H/2i5FTlsSHPMzlc5ch2/DLiY > 0yS1VWNQNuVh40WfK0SVFgsmFxNJ0IFQ+kkJsQPH/mcxQHbP+8iuzKiMuZIpIgUY > Gx/DwfIUzg60W0cCe9gfguvnR/rOXFk/5PuoktWHe9/8bb1BoV+RAFyc9mEWzRzJ > K6+/Rb7ISvQ/ptZ13PNgmX3UkLZU+qIFqlZZ+9rDld4iuyc+toqhdf4nUm7Bemen > XivPf4H/n8OpckYeYKXuKyotacsIZQQraAJevSeiV/EWWrkgHyslktnRwIGVJlmJ > CC8fgKE7DUVrI1PFBa2W48xlTOcpLtg9beB86J5cjNlsbVkSMC+gMiVVAGPooZc= > =yPBg > -----END PGP SIGNATURE----- > > -----BEGIN PGP PUBLIC KEY BLOCK----- > Version: GnuPG v1.4.7 (MingW32) > > mQELBEM2+ggBCAC0L91VmTkAiJ20R652OR9kBjeJyirFBiG1/hPOVbMih9qp5VWh > a+iHzhmn90fl4gQpo4na1MW6mkTfYeD5ZJxKpS5YCZ7hAl54LJACAMcAaYqKgsMM > DaPZVtM6rKkE5DbKlny8G8OC8vP0cz2pQ7ONkPYTOtBx6PxeMDGmckunRgbbEI7r > 2Yv0BIP7GbfG59sxa12N+ekvOUFE7lrzsOUyLy+kANgpFBqaPABaP3qvV5NFWIba > DbU6jGja7cvz7NCnb/sZt7Jlw8ueJW41szN8z58n3E0HXYPqR+6FOexHsimAu9f+ > 7dl0JSxliXvD1JeXyDlZ7SMsbwQjQECREG/lAAYptC5aYW1lZXIgTWFuamkgKE5l > dyBNYWluIEtleSkgPHptYW5qaUBnbWFpbC5jb20+iQE2BBMBAgAgBQJDNvoIAhsD > BgsJCAcDAgQVAggDBBYCAwECHgECF4AACgkQDvn2xlC5DUHy/wf8Caj2qmsl/zUa > KdTHwlSHue9hIiiVwC1D7GkX7KPznhJH7jUQYOT1Q2KeyT9jMgbVHCjImmvgpKjS > 8JZ1p7DD5QzzE8vYlSGew+Axaav9TiRqTEhCPdm7ZbpJbocc6OVRlraQD1P5SRvB > LenTfIypOEK1gJzBCZW/2eSbawbcyWGEHNieNrGIumta2sHKYwP94E/dAZerJ8+z > DRd//G2kWOrT8bkRHoXBsmYhnlWtnXihRCYLIU6seJnl8pb0+7qOu2Z5tmK0lG4Q > slFabrAhPkInm3g+r4OHDASWG/yE4p96ReyTgkh7/JU8gjdWYnSY8bB5OOcHg4Eg > +CVceqRIxrkBCwRDNvpQAQgA1BfAHGqZ8qn06iScKMkxTqBZYQV9u4mYloIS6lE8 > vgzMDYeR2xAohttpDydgLY6AvJlEIlrv5B4McNXY/ove5+DnuVX8f+k5OCZYDuif > ZOeamcqhOM2Z+26qlRWdOud0jf0rHDc6fO/RqgCY3ERCGxKsK5XOxHReHIRkPu9H > fDT2LLUBaqZw99vOoMbbl2hdDDed4q5ZzYx1Jrue5frY358QAAzKNcEOjOCzmqGL > brFXmm5itW3hOK45ykGBYZHYkbsypjWXiLjm2UL1TEOWMNRvyCYLsjqAsMUhc2vv > KW7wubn9tm3d2+WvZPNDJ7zH1fGfpjB1m23mQ5AdglAhoQAGKYkBHwQYAQIACQUC > Qzb6UAIbDAAKCRAO+fbGULkNQbBGB/9QSvgxboVYpKjRFWMUIblLUSFxKfojNic9 > uocndJxmO5NtLsncXdNuuhm9dwAdwcUfCpNMq1k/2MA6WGB2pSr01PTAYl+zs360 > 7Rel5jf0IgKv967FoXLa2N/p7ek3o6EmuE3OevIJ+qnpOEjmAVy1DQvR64GMT1Nu > JrXizLbakJTuE/QoFY1X4sJIuMrz5eAggs/fTyYPRuXFqjkitPGZ81NeQpZ6HTYa > WZvDV2Vr006w0ZFY9/ttGuq43htv8+3zJDid1stX3BNXuYipN9gOy6ilgPlVD3B9 > yRp6m8h7Rc6EoWHqUM418d4PIJmulcUa4c4dAl16N6LsLnVidnhj > =wMDx > -----END PGP PUBLIC KEY BLOCK----- > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon May 26 00:06:16 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 25 May 2008 23:06:16 +0100 Subject: [Tutor] get/set attributes References: <6BB36E8B-51BC-4472-A88B-EDD55FC40DD4@ericabrahamsen.net> <4BB3EEDF-2AF5-4A7C-B6AD-9875176AEE1C@ericabrahamsen.net> Message-ID: "Eric Abrahamsen" wrote > >> CMS with Cherrypy/Sqlalchemy/Cheetah, > > > > Those are the components of TurboGears. > I am doing this as a learning exercise, though I hadn't realized > those are precisely TG's components. TG tries to use a set of "best practice" components and glue them together into a framework. It started off using Kid/CherryPy/SQLObject then acquired Alchemy as an alternative ORM and has now adopted Cheeetah for templating so you can mix n' match by setting your config options to select your favourite components, but the upper level framework stuff works fairly transparently - obviously the templating syntax depends on the engine you use and the ORM layer is restricted to whatever features your chosen mapper supports but the translation to python code is pretty seamless and portable. I like the concept of TG but there are a few niggles with it. I'm just learning Django at the moment so can't really make any proper comparisons yet. Alan G. From alan.gauld at btinternet.com Mon May 26 00:10:19 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 25 May 2008 23:10:19 +0100 Subject: [Tutor] How to get a string from a DOM Text node ? References: <4839D196.9090100@gmail.com> Message-ID: "Zameer Manji" wrote in > > I'm trying to extract some information from the following xml file: > http://pastebin.ca/1029125 > > This is the code that I have so far: > > import xml.dom.minidom > This code prints out the following: > > > 42 > "> > > The problem is that the Text node that is printed out is blank, when > it > should be 42. What do I need to do so I can get tdict.childNodes[2] > to I may be off base here; I only used DOM once. I usually use ElementTree for parsing XML(and only rarely do that!). But isn't there a data or content field on the tag object that you have to use? Just a vague memory and too late/lazy to look it up! It might be a clue till somebody who really knows minidom replies! Alan G. From midnightjulia at gmail.com Mon May 26 01:51:45 2008 From: midnightjulia at gmail.com (Julia) Date: Mon, 26 May 2008 01:51:45 +0200 Subject: [Tutor] What lib should I use? Message-ID: Hi! I need to write a program what can do two things: 1) get data from the website 2) send information from a textfield (e.g. like a google search) Any tips on what lib I should use and any good tutorial covering it? Thanks! /MJ -------------- next part -------------- An HTML attachment was scrubbed... URL: From mwalsh at groktech.org Mon May 26 02:04:23 2008 From: mwalsh at groktech.org (Martin Walsh) Date: Sun, 25 May 2008 19:04:23 -0500 Subject: [Tutor] How to get a string from a DOM Text node ? In-Reply-To: <4839D196.9090100@gmail.com> References: <4839D196.9090100@gmail.com> Message-ID: <4839FE87.7060001@groktech.org> Zameer Manji wrote: > I'm trying to extract some information from the following xml file: > http://pastebin.ca/1029125 > > file = "Music.xml" > dict = plist.childNodes[1] #dict contains App version and stuff, as well You really should try to avoid rebinding built-in names, like dict and file, this is just asking for trouble. > The problem is that the Text node that is printed out is blank, when it > should be 42. What do I need to do so I can get tdict.childNodes[2] to > become a string being "42" ? I have not used minidom at all really, but here is an example using BeautifulSoup, perhaps you'll find it helpful: from BeautifulSoup import BeautifulStoneSoup class MusicSoup(BeautifulStoneSoup): NESTABLE_TAGS = { 'dict': [], 'array': [] } bsoup = MusicSoup(file('Music.xml')) print bsoup.dict.dict.key.string # 42 print bsoup.dict.dict.key.findNextSibling('key').string # 183 ... or ... tracks = bsoup.dict.dict.findChildren('key', recursive=False) print tracks for track in tracks: print track details = track.findNextSibling('dict') HTH, Marty From alan.gauld at btinternet.com Mon May 26 02:11:22 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 26 May 2008 01:11:22 +0100 Subject: [Tutor] What lib should I use? References: Message-ID: "Julia" wrote > I need to write a program what can do two things: > > 1) get data from the website > 2) send information from a textfield (e.g. like a google search) There are lots of web frameworks for Python that you could use. The most basic is the standard cgi module in the standard library. Moving up frfrom there something like CherryPy is a good bet. But for what you describe vanilla cgi is fine. Read the docs and topic guide on the Python web site. http://wiki.python.org/moin/CgiScripts HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From pythonnutter at gmail.com Mon May 26 02:37:27 2008 From: pythonnutter at gmail.com (python nutter) Date: Mon, 26 May 2008 10:37:27 +1000 Subject: [Tutor] What lib should I use? In-Reply-To: References: Message-ID: On Mon, 26 May 2008 01:51:45 +0200, "Julia" said: > Hi! > > I need to write a program what can do two things: > > 1) get data from the website > 2) send information from a textfield (e.g. like a google search) Sounds like you are web scraping or wanting to make a web spider. Check out a) urllib b) urllib2 c) beautifulsoup a + b are built-ins. c you have to download and install from http://www.crummy.com/software/BeautifulSoup/ Cheers, Python Nutter -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Mon May 26 03:06:16 2008 From: bgailer at gmail.com (bob gailer) Date: Sun, 25 May 2008 21:06:16 -0400 Subject: [Tutor] What lib should I use? In-Reply-To: References: Message-ID: <483A0D08.9000901@gmail.com> Julia wrote: > > I need to write a program what can do two things: > > 1) get data from the website > 2) send information from a textfield (e.g. like a google search) I presume you want to automatically submit a form? For both see http://docs.python.org/lib/node577.html Forms are submitted by either GET or POST. Examine the HTML of the form to see which. -- Bob Gailer 919-636-4239 Chapel Hill, NC From srilyk at gmail.com Mon May 26 03:45:12 2008 From: srilyk at gmail.com (W W) Date: Sun, 25 May 2008 20:45:12 -0500 Subject: [Tutor] What lib should I use? In-Reply-To: <483A0D08.9000901@gmail.com> References: <483A0D08.9000901@gmail.com> Message-ID: <333efb450805251845n7e346d15t5791a9ba68c30484@mail.gmail.com> However, something to note is that Google prohibits web scraping, at least via urllib. If you try to GET or POST (I can't remember off the top of my head), Google will not return the actual search. HTH, Wayne On Sun, May 25, 2008 at 8:06 PM, bob gailer wrote: > Julia wrote: >> >> I need to write a program what can do two things: >> >> 1) get data from the website >> 2) send information from a textfield (e.g. like a google search) > > I presume you want to automatically submit a form? > > For both see > > http://docs.python.org/lib/node577.html > Forms are submitted by either GET or POST. Examine the HTML of the form to > see which. > > -- > Bob Gailer > 919-636-4239 Chapel Hill, NC > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi From midnightjulia at gmail.com Mon May 26 11:59:34 2008 From: midnightjulia at gmail.com (Julia) Date: Mon, 26 May 2008 11:59:34 +0200 Subject: [Tutor] What lib should I use? In-Reply-To: <333efb450805251845n7e346d15t5791a9ba68c30484@mail.gmail.com> References: <483A0D08.9000901@gmail.com> <333efb450805251845n7e346d15t5791a9ba68c30484@mail.gmail.com> Message-ID: Some of you are fairly close to what I intend with the code. I've written a program to solve a specific type of problems earlier. Now I wanted to take it to the next level and have it fetch the problem by itself and then submit the answer. I thought that would be kind of cool :) Thanks for the answers... I'll take a look at urllib, urllib2 as well as beautifulsoup and cherrypy (I like the name) /J On Mon, May 26, 2008 at 3:45 AM, W W wrote: > However, something to note is that Google prohibits web scraping, at > least via urllib. > > If you try to GET or POST (I can't remember off the top of my head), > Google will not return the actual search. > > HTH, > Wayne > > On Sun, May 25, 2008 at 8:06 PM, bob gailer wrote: > > Julia wrote: > >> > >> I need to write a program what can do two things: > >> > >> 1) get data from the website > >> 2) send information from a textfield (e.g. like a google search) > > > > I presume you want to automatically submit a form? > > > > For both see > > > > http://docs.python.org/lib/node577.html > > Forms are submitted by either GET or POST. Examine the HTML of the form > to > > see which. > > > > -- > > Bob Gailer > > 919-636-4239 Chapel Hill, NC > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > -- > To be considered stupid and to be told so is more painful than being > called gluttonous, mendacious, violent, lascivious, lazy, cowardly: > every weakness, every vice, has found its defenders, its rhetoric, its > ennoblement and exaltation, but stupidity hasn't. - Primo Levi > -------------- next part -------------- An HTML attachment was scrubbed... URL: From inhahe at gmail.com Mon May 26 12:06:42 2008 From: inhahe at gmail.com (inhahe) Date: Mon, 26 May 2008 06:06:42 -0400 Subject: [Tutor] help on StringIO Message-ID: Can someone explain to me how to use StringIO? Python 2.5.2 Stackless 3.1b3 060516 (release25-maint, Apr 2 2008, 19:04:14) [MS C v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import StringIO >>> s = StringIO.StringIO() >>> s.write('hi') >>> print s.read() >>> Is this a bug? From Matthias.Sommer at wincor-nixdorf.com Mon May 26 12:53:09 2008 From: Matthias.Sommer at wincor-nixdorf.com (Sommer, Matthias) Date: Mon, 26 May 2008 12:53:09 +0200 Subject: [Tutor] Promlem positioning the cursor by mouse in Idle Message-ID: <71FCE9DC9D0EA6478F8C44B757BC8A2D1D25D9@deexsi20.wincor-nixdorf.com> Hello, after asking already in some other places without getting helpful answers, I'll try to bother you: I use Idle under Windows and it workes to my pleasure. Now I tried under Linux and I have the problem, that I cannot position the cursor by clicking somewhere in the text. This happens under Mandriva (2008) and under Arch Linux (Arch 64, normal Arch and FaunOS). It does work under Xandros (on the eee pc). From the german python newsgroup I have reports that it is working in Ubuntu and Suse. So I don't think it's a Linux problem but a problem of Idle (or TK?) not working correctly for some distros. Can anyone give me a hint where I can look to get it working? Mit freundlichen Gr??en Matthias Sommer Entwicklung - Firmware/Elektronik ______________________________________________ Wincor Nixdorf Technology GmbH Am Vogelherd 67 D - 98693 Ilmenau, Germany Tel.: +49 (0) 36 77 862-194 Fax: +49 (0) 36 77 862-199 E-Mail: matthias.sommer at wincor-nixdorf.com www.wincor-nixdorf.com -- Wincor Nixdorf Technology GmbH Sitz der Gesellschaft: Paderborn Registergericht Paderborn HRB 3523 Gesch?ftsf?hrer: Eckard Heidloff, J?rgen Wilde, Wolfgang Keller Steuernummer: 339/5884/0020 - Ust-ID Nr.: DE243233085 Diese E-Mail enth?lt vertrauliche Informationen. Wenn Sie nicht der richtige Adressat sind oder diese E-Mail irrt?mlich erhalten haben, informieren Sie bitte sofort den Absender und vernichten Sie diese E-Mail. Das unerlaubte Kopieren sowie die unbefugte Weitergabe dieser E-Mail ist nicht gestattet. This e-mail may contain confidential information. If you are not the intended recipient (or have received this e-mail in error) please notify the sender immediately and destroy this e-mail. Any unauthorised copying, disclosure or distribution of the material in this e-mail is strictly forbidden. -------------- next part -------------- An HTML attachment was scrubbed... URL: From srilyk at gmail.com Mon May 26 14:20:56 2008 From: srilyk at gmail.com (W W) Date: Mon, 26 May 2008 07:20:56 -0500 Subject: [Tutor] Fwd: help on StringIO In-Reply-To: <333efb450805260518l5f5bea35hc788cd3dd17dc704@mail.gmail.com> References: <333efb450805260518l5f5bea35hc788cd3dd17dc704@mail.gmail.com> Message-ID: <333efb450805260520g89e8ec0t7481042d4526ef48@mail.gmail.com> ---------- Forwarded message ---------- From: W W Date: Mon, May 26, 2008 at 7:18 AM Subject: Re: [Tutor] help on StringIO To: inhahe On Mon, May 26, 2008 at 5:06 AM, inhahe wrote: > Can someone explain to me how to use StringIO? >>>> import StringIO >>>> s = StringIO.StringIO() >>>> s.write('hi') >>>> print s.read() > >>>> > > Is this a bug? >From what I read in the docs, .read() usually reads from the current position. So basically you're inputting 'hi' and the cursor is at the end: 'hi_' So when you read from the _ the only thing that's left is a blank string ''. Instead, try this: >>> import StringIO >>> s = StringIO.StringIO() >>> s.write('hi') >>> print s.getvalue() hi >>> s.read() '' >>> As you can see, s.read() works just the same, but s.getvalue() will get the actual value, regardless of your position in the "file". (I could be completely off with the read bit, so if anyone knows better, feel free to correct) Look here for more help: http://docs.python.org/lib/module-StringIO.html HTH, Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi From alan.gauld at btinternet.com Mon May 26 14:28:39 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 26 May 2008 13:28:39 +0100 Subject: [Tutor] What lib should I use? References: <483A0D08.9000901@gmail.com><333efb450805251845n7e346d15t5791a9ba68c30484@mail.gmail.com> Message-ID: "Julia" wrote > I've written a program to solve a specific type of problems earlier. > Now I > wanted to take it to the next level and have it fetch the problem by > itself > and then submit the answer. I thought that would be kind of cool :) If you want to simulate a web browser then the urllib/BeautifulSoup stuff is the right approach. If you want to catch a browser form submission at the server then CherryPy is a good framework. Alan G From alan.gauld at btinternet.com Mon May 26 14:32:44 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 26 May 2008 13:32:44 +0100 Subject: [Tutor] Promlem positioning the cursor by mouse in Idle References: <71FCE9DC9D0EA6478F8C44B757BC8A2D1D25D9@deexsi20.wincor-nixdorf.com> Message-ID: "Sommer, Matthias" wrote > I use Idle under ...Linux and I have the problem, that I cannot > position the cursor by clicking somewhere in the text. > This happens under Mandriva (2008) and under Arch > Linux (Arch 64, normal Arch and FaunOS). I've usd Idle on earlier Mandriva distros without problems. Also on Suse and Red Hat > It does work under Xandros (on the eee pc). Yep, works there for me too. Can you try writing a short Tkinter app with a Text widget and see if that works? That would help narrow it down to see if it is a Tkinter problem? Alan G. From alan.gauld at btinternet.com Mon May 26 18:16:50 2008 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Mon, 26 May 2008 16:16:50 +0000 (GMT) Subject: [Tutor] Promlem positioning the cursor by mouse in Idle Message-ID: <108677.63835.qm@web86707.mail.ukl.yahoo.com> CCing the list >>Can you try writing a short Tkinter app with a Text widget > >never done so, I prefer wxPython, from Tkinter import * top = Tk() Text(top).pack() top.mainloop() Should do it... Alan G. From kent37 at tds.net Mon May 26 18:33:40 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 26 May 2008 12:33:40 -0400 Subject: [Tutor] help on StringIO In-Reply-To: References: Message-ID: <1c2a2c590805260933l10277dd9q13df3fb59e4d5ace@mail.gmail.com> On Mon, May 26, 2008 at 6:06 AM, inhahe wrote: > Can someone explain to me how to use StringIO? > > Python 2.5.2 Stackless 3.1b3 060516 (release25-maint, Apr 2 2008, 19:04:14) [MS > C v.1310 32 bit (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. >>>> import StringIO >>>> s = StringIO.StringIO() >>>> s.write('hi') >>>> print s.read() Just like when writing to a real file, if you want to read back what you just wrote, you have to seek first: In [1]: import StringIO In [2]: s=StringIO.StringIO() In [3]: s.write('hi') In [4]: s.seek(0) In [5]: s.read() Out[5]: 'hi' But for the common use of StringIO where you want to write to a file-like object and retrieve what is written, just use getvalue(). Kent From ulrichhzn at gmail.com Mon May 26 21:45:31 2008 From: ulrichhzn at gmail.com (Ulrich) Date: Mon, 26 May 2008 21:45:31 +0200 Subject: [Tutor] Gasp Message-ID: <1211831131.9850.4.camel@atom> Hello, I am following the tutorial "How to think like a Computer Scientist" to learn Python and on Chapter 4 - Conditionals one of the exercises is to import some things from "gasp". However this is what I get when I try importing from the gasp module. Python 2.5.2 (r252:60911, Apr 21 2008, 11:12:42) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from gasp import * Traceback (most recent call last): File "", line 1, in ImportError: No module named gasp >>> How can I overcome this obstacle to continue the course? Thanks in advance. From kent37 at tds.net Mon May 26 22:07:37 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 26 May 2008 16:07:37 -0400 Subject: [Tutor] Gasp In-Reply-To: <1211831131.9850.4.camel@atom> References: <1211831131.9850.4.camel@atom> Message-ID: <1c2a2c590805261307i756f9bedr94091ff35705d7d7@mail.gmail.com> On Mon, May 26, 2008 at 3:45 PM, Ulrich wrote: > Hello, > > I am following the tutorial "How to think like a Computer Scientist" to > learn Python and on Chapter 4 - Conditionals one of the exercises is to > import some things from "gasp". That is not a standard module. Does it tell you where to get it? Perhaps they mean this: https://launchpad.net/gasp Kent From kent37 at tds.net Mon May 26 22:45:32 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 26 May 2008 16:45:32 -0400 Subject: [Tutor] help on StringIO In-Reply-To: References: <1c2a2c590805260933l10277dd9q13df3fb59e4d5ace@mail.gmail.com> Message-ID: <1c2a2c590805261345l6dddb0e1l6b0e25cad98f8a35@mail.gmail.com> On Mon, May 26, 2008 at 12:53 PM, inhahe wrote: > I guess that makes sense, but it seems a lot more useful to have a > function that only reads what's been written since the last time you > read. That way reading from a file that's growing would be > transparent--the same as reading it as if it were already full size. > It seems with this read function if you were copying a file, because > the file might be growing you'd have to do this: > while 1: > p = f1.tell() > f2.write(f1.read(4096)) > f1.seek(p+4096) > otherwise your copy process would quit as soon as any new data is > written, because the file position would jump to the end of the file. You are confusing reading and writing a single file using a single file handle, and reading from one file and writing to another. > > and getvalue just returns the entire contents of the buffer. >>>> s.write('hi') >>>> s.getvalue() > 'hi' >>>> s.write('hi') >>>> s.getvalue() > 'hihi' > > so i'd be getting redundant data. > > What i'm wondering about specifically is WSGI. it's supposed to > return a file-like object, wsgi.input, for reading the http request. > and if you read beyond what's currently received, it's supposed to > block until more is received. so are we actually supposed to read > from wsgi.input by doing this? > > while 1: > p = wsgi.input.tell() > processe(wsgi.input.read(4096)) > wsgi.input.seek(p+4096) # otherwise the next time something is > added to wsgi.input your reading will return nothing No, just read from the input. > and even then i suppose the WSGI server had better not write anything > to the stream before it's all read up otherwise it'll overwrite to > some position in the middle of the stream (wherever the current > position is). this makes no sense to me. how is this done? (and > where's the file class that works in a way that makes sense?) Can you show an example of why you need this? Kent PS Please use Reply All to reply to the list. From wescpy at gmail.com Mon May 26 23:32:07 2008 From: wescpy at gmail.com (wesley chun) Date: Mon, 26 May 2008 14:32:07 -0700 Subject: [Tutor] Gasp In-Reply-To: <1c2a2c590805261307i756f9bedr94091ff35705d7d7@mail.gmail.com> References: <1211831131.9850.4.camel@atom> <1c2a2c590805261307i756f9bedr94091ff35705d7d7@mail.gmail.com> Message-ID: <78b3a9580805261432o28f66c45x8dd83cb940d4f99b@mail.gmail.com> >> I am following the tutorial "How to think like a Computer Scientist" to >> learn Python and on Chapter 4 - Conditionals one of the exercises is to >> import some things from "gasp". > > That is not a standard module. Does it tell you where to get it? > Perhaps they mean this: > https://launchpad.net/gasp hi, and welcome to Python! for the other beginners who do not know which tutorial/book you're talking about, here is the link: http://openbookproject.net/thinkCSpy in Appendix A, you will find directions on how to install GASP: http://openbookproject.net/thinkCSpy/app_a.xhtml#auto1 Note that the reference to GASP is only available in the 2nd ed of HtTLaCS... you will not find a reference to it in the 1st ed: http://www.greenteapress.com/thinkpython/thinkCSpy/html/ best of luck! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From wescpy at gmail.com Mon May 26 23:34:08 2008 From: wescpy at gmail.com (wesley chun) Date: Mon, 26 May 2008 14:34:08 -0700 Subject: [Tutor] Gasp In-Reply-To: <78b3a9580805261432o28f66c45x8dd83cb940d4f99b@mail.gmail.com> References: <1211831131.9850.4.camel@atom> <1c2a2c590805261307i756f9bedr94091ff35705d7d7@mail.gmail.com> <78b3a9580805261432o28f66c45x8dd83cb940d4f99b@mail.gmail.com> Message-ID: <78b3a9580805261434p28810867q3f3ebe620dbe4e27@mail.gmail.com> > in Appendix A, you will find directions on how to install GASP: > http://openbookproject.net/thinkCSpy/app_a.xhtml#auto1 i should also add that Appendix B serves as an entire reference to GASP: http://www.openbookproject.net/thinkCSpy/app_b.xhtml From alan.gauld at btinternet.com Tue May 27 00:33:41 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 26 May 2008 23:33:41 +0100 Subject: [Tutor] help on StringIO References: <1c2a2c590805260933l10277dd9q13df3fb59e4d5ace@mail.gmail.com> <1c2a2c590805261345l6dddb0e1l6b0e25cad98f8a35@mail.gmail.com> Message-ID: > On Mon, May 26, 2008 at 12:53 PM, inhahe wrote: >> I guess that makes sense, but it seems a lot more useful to have a >> function that only reads what's been written since the last time >> you >> read. The file model in Python (and most programming languages) is based on the early tape drive model. You have a magnetic head that can read or write at the current point on the tape. You have to rewind the tape if you want to playback what you just recorded. If you do that, then read it you will be ready to record the next section. Yes you do need to store the starting point each time so that you can seek back to it (rewind), but it all works very logically if you bear in mind the original tape model. >> That way reading from a file that's growing would be >> transparent--the same as reading it as if it were already full >> size. But you would need two record heads and an infinitely long tape player (or triple loop buffer mechanism but thats getting technical! :-). The model may be outdated - that's why we use databases - but that is how the model works. >> It seems with this read function if you were copying a file, >> because >> the file might be growing you'd have to do this: Copying a file is no problem because you are reading from one file and writing to another. It would only be a problem if you tried to read back what you had just copied between each write. (Sometimes we do that - its often called validated write - and it slows down the copy process precisely because of all the to-ing and fro-ing involved) >> otherwise your copy process would quit as soon as any new data is >> written, because the file position would jump to the end of the >> file. The file position is always at the end of the file when writing. You add data in sequence, that's why they are called sequential files. >> What i'm wondering about specifically is WSGI. it's supposed to >> return a file-like object, wsgi.input, for reading the http >> request. >> and if you read beyond what's currently received, it's supposed to >> block until more is received. Which is what you'd want. It reads whatever is on the tape but if it reaches the end it stops and waits for more data to arrive. >> and even then i suppose the WSGI server had better not write >> anything >> to the stream before it's all read up otherwise it'll overwrite to >> some position in the middle of the stream I know little or nothing about WSGI specifics but streams in general will always write to the end of the buffer. The fact that the buffer behaves like a file-like-object implies that you can read input as if it were a file but the arriving data will continuously be dumped at the end. I don't think that should cause a problem. Its a difference between a data steam and a normal file. You can't rewind a stream. It looks like WSGI has two modes operating at once. A data stream model for receiving the data and a file-like model for reading that data out. >> where's the file class that works in a way that makes sense?) Files work like a tape recorder. Once you understand the underlying sequential model they do make sense. They just might not be they way you would want them to be! (NB There are other file models in computing, such as ISAM etc which work differently, but sequential is by far the dominant model and the one used in Python) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From dkuhlman at rexx.com Tue May 27 02:02:51 2008 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Mon, 26 May 2008 17:02:51 -0700 Subject: [Tutor] How to get a string from a DOM Text node ? In-Reply-To: References: <4839D196.9090100@gmail.com> Message-ID: <20080527000251.GA37937@cutter.rexx.com> On Sun, May 25, 2008 at 11:10:19PM +0100, Alan Gauld wrote: > > "Zameer Manji" wrote in > > > >The problem is that the Text node that is printed out is blank, when > >it > >should be 42. What do I need to do so I can get tdict.childNodes[2] > >to > > I may be off base here; I only used DOM once. I usually use > ElementTree for parsing XML(and only rarely do that!). But isn't there > a data or content field on the tag object that you have to use? > I second Alan's suggestion that you use ElementTree instead of minidom. It's in the Python 2.5 standard library now. And, you can find documentation here: http://effbot.org/zone/element-index.htm But, if you do stick with minidom, then I believe that you want something like this: if node.nodeType == node.TEXT_NODE: print 'characters: "%s"' % (node.data, ) - Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From Matthias.Sommer at wincor-nixdorf.com Tue May 27 09:18:59 2008 From: Matthias.Sommer at wincor-nixdorf.com (Sommer, Matthias) Date: Tue, 27 May 2008 09:18:59 +0200 Subject: [Tutor] Promlem positioning the cursor by mouse in Idle In-Reply-To: <108677.63835.qm@web86707.mail.ukl.yahoo.com> References: <108677.63835.qm@web86707.mail.ukl.yahoo.com> Message-ID: <71FCE9DC9D0EA6478F8C44B757BC8A2D1D2676@deexsi20.wincor-nixdorf.com> Hello, I just tested, and there it works... =B-O Strange... Mit freundlichen Gr??en Matthias Sommer Entwicklung - Firmware/Elektronik ______________________________________________ Wincor Nixdorf Technology GmbH Am Vogelherd 67 D - 98693 Ilmenau, Germany Tel.: +49 (0) 36 77 862-194 Fax: +49 (0) 36 77 862-199 E-Mail: matthias.sommer at wincor-nixdorf.com www.wincor-nixdorf.com -----Original Message----- From: ALAN GAULD [mailto:alan.gauld at btinternet.com] Sent: Monday, May 26, 2008 6:17 PM To: Sommer, Matthias Cc: tutor at python.org Subject: Re: [Tutor] Promlem positioning the cursor by mouse in Idle CCing the list >>Can you try writing a short Tkinter app with a Text widget > >never done so, I prefer wxPython, from Tkinter import * top = Tk() Text(top).pack() top.mainloop() Should do it... Alan G. -- Wincor Nixdorf Technology GmbH Sitz der Gesellschaft: Paderborn Registergericht Paderborn HRB 3523 Gesch?ftsf?hrer: Eckard Heidloff, J?rgen Wilde, Wolfgang Keller Steuernummer: 339/5884/0020 - Ust-ID Nr.: DE243233085 Diese E-Mail enth?lt vertrauliche Informationen. Wenn Sie nicht der richtige Adressat sind oder diese E-Mail irrt?mlich erhalten haben, informieren Sie bitte sofort den Absender und vernichten Sie diese E-Mail. Das unerlaubte Kopieren sowie die unbefugte Weitergabe dieser E-Mail ist nicht gestattet. This e-mail may contain confidential information. If you are not the intended recipient (or have received this e-mail in error) please notify the sender immediately and destroy this e-mail. Any unauthorised copying, disclosure or distribution of the material in this e-mail is strictly forbidden. From alan.gauld at btinternet.com Tue May 27 10:16:26 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 27 May 2008 09:16:26 +0100 Subject: [Tutor] Promlem positioning the cursor by mouse in Idle References: <108677.63835.qm@web86707.mail.ukl.yahoo.com> <71FCE9DC9D0EA6478F8C44B757BC8A2D1D2676@deexsi20.wincor-nixdorf.com> Message-ID: "Sommer, Matthias" wrote >>Can you try writing a short Tkinter app with a Text widget >I just tested, and there it works... =B-O > Strange... Very strange, I'm at a loss. Hopefully some of our Linux experts will have a suggestion. Alan G From muchanek at gmail.com Tue May 27 11:01:19 2008 From: muchanek at gmail.com (kinuthia muchane) Date: Tue, 27 May 2008 12:01:19 +0300 Subject: [Tutor] help on StringIO In-Reply-To: References: Message-ID: <1211878879.5827.13.camel@www.kinuthia.com> > ---------------------------------------------------------------------- > > Message: 1 > Date: Mon, 26 May 2008 06:06:42 -0400 > From: inhahe > Subject: [Tutor] help on StringIO > To: tutor at python.org > Message-ID: > > Content-Type: text/plain; charset=ISO-8859-1 > > Can someone explain to me how to use StringIO? > > Python 2.5.2 Stackless 3.1b3 060516 (release25-maint, Apr 2 2008, 19:04:14) [MS > C v.1310 32 bit (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> import StringIO > >>> s = StringIO.StringIO() > >>> s.write('hi') > >>> print s.read() > > >>> > > Is this a bug? > When you use the write method you move the cursor to the end of the word, just as Kent says. You can use the tell() method which returns your current position in the file-like object to confirm this: >>> import StringIO >>> s = StringIO.StringIO() >>> s.write('hi') >>> s.tell() 2 From muchanek at gmail.com Tue May 27 11:50:30 2008 From: muchanek at gmail.com (kinuthia muchane) Date: Tue, 27 May 2008 12:50:30 +0300 Subject: [Tutor] & syntax Message-ID: <1211881830.5827.25.camel@www.kinuthia.com> Hi, >>> 2&1 0 >>> 3&1 1 >>> 4&1 0 >>> 5&1 1 >>> 99&1 1 >>> 100&1 0 >>> 100&2 0 Would someone kindly explain to me what is going on here. All I can see is even numbers return a '0' and odds a '1'. I also know all even numbers in binary end in a zero. I had thought '&' was another way of writing the 'and' operator, seems I was wrong. Thanks! Kinuthia... From srilyk at gmail.com Tue May 27 12:48:01 2008 From: srilyk at gmail.com (W W) Date: Tue, 27 May 2008 05:48:01 -0500 Subject: [Tutor] & syntax In-Reply-To: <1211881830.5827.25.camel@www.kinuthia.com> References: <1211881830.5827.25.camel@www.kinuthia.com> Message-ID: <333efb450805270348u5566accam41ded730cb9cbc7a@mail.gmail.com> On Tue, May 27, 2008 at 4:50 AM, kinuthia muchane wrote: > Hi, >>>> 2&1 > 0 >>>> 3&1 > 1 >>>> 4&1 > 0 >>>> 5&1 > 1 >>>> 99&1 > 1 >>>> 100&1 > 0 >>>> 100&2 > 0 > > Would someone kindly explain to me what is going on here. All I can see > is even numbers return a '0' and odds a '1'. I also know all even > numbers in binary end in a zero. I had thought '&' was another way of > writing the 'and' operator, seems I was wrong. A quick Google search divulged the information that this is the bitwise AND operator. For more info: http://en.wikipedia.org/wiki/Bitwise_operation HTH, Wayne From muchanek at gmail.com Tue May 27 15:23:52 2008 From: muchanek at gmail.com (kinuthia muchane) Date: Tue, 27 May 2008 16:23:52 +0300 Subject: [Tutor] & syntax In-Reply-To: <333efb450805270348u5566accam41ded730cb9cbc7a@mail.gmail.com> References: <1211881830.5827.25.camel@www.kinuthia.com> <333efb450805270348u5566accam41ded730cb9cbc7a@mail.gmail.com> Message-ID: <1211894632.5827.29.camel@www.kinuthia.com> On Tue, 2008-05-27 at 05:48 -0500, W W wrote: > On Tue, May 27, 2008 at 4:50 AM, kinuthia muchane wrote: > > Hi, > >>>> 2&1 > > 0 > >>>> 3&1 > > 1 > >>>> 4&1 > > 0 > >>>> 5&1 > > 1 > >>>> 99&1 > > 1 > >>>> 100&1 > > 0 > >>>> 100&2 > > 0 > > > > Would someone kindly explain to me what is going on here. All I can see > > is even numbers return a '0' and odds a '1'. I also know all even > > numbers in binary end in a zero. I had thought '&' was another way of > > writing the 'and' operator, seems I was wrong. > > A quick Google search divulged the information that this is the > bitwise AND operator. > > For more info: > http://en.wikipedia.org/wiki/Bitwise_operation Thanks W W, this link was exactly what I wanted. > > HTH, > Wayne From alan.gauld at btinternet.com Tue May 27 18:55:36 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 27 May 2008 17:55:36 +0100 Subject: [Tutor] & syntax References: <1211881830.5827.25.camel@www.kinuthia.com> Message-ID: "kinuthia muchane" wrote >>>> 2&1 > 0 >>>> 3&1 > 1 > > Would someone kindly explain to me what is going on here. All I can > see > is even numbers return a '0' and odds a '1'. I also know all even > numbers in binary end in a zero. I had thought '&' was another way > of > writing the 'and' operator, seems I was wrong. This is a bitwise AND, ie it operates on each of the binary bits independanly. OTOH The logical AND operator treats the value *as a whole* as a boolean (true/false) value and operates on that value. You can read about bitwise operators and how and why they are used in my tutorial in the Using the OS topic, about half way through. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From cuciferus at gmail.com Tue May 27 21:57:05 2008 From: cuciferus at gmail.com (ionut cucu) Date: Tue, 27 May 2008 22:57:05 +0300 Subject: [Tutor] local service descovery Message-ID: <20080527225705.701f3d58@cuci> Hello world! I'm trying to run a mpd client (http://mpd.wikia.com/wiki/What_MPD_Is_and_Is_Not) and thought, for the users convenience to do a local discovery. But I'm not sure how to `do it. Therefore my question is : what lib should I use in order to discover a local server(I was thinking as much as one hoop would suffice) ? Thanks in advance! From nswitanek at stanford.edu Tue May 27 22:54:16 2008 From: nswitanek at stanford.edu (Switanek, Nick) Date: Tue, 27 May 2008 13:54:16 -0700 Subject: [Tutor] 180MB Message-ID: <21EB45BA6A0A4844B97D46A7721CFDF205D4EC64@gsb-exchmb02.stanford.edu> I'm running windows XP. Judging from the Add/Remove programs interface, it appears that many python packages I've installed over the years are each taking up right around 180MB. This includes pyreadline, winpdb, pywordnet, numarray, numpy, and many others besides. It seems an uncanny coincidence that each package would be within a few MB of the next. Any insight into whether there is something wrong here, and if so, what I've done? Thanks, Nick -------------- next part -------------- An HTML attachment was scrubbed... URL: From christopher.henk at allisontransmission.com Tue May 27 23:25:09 2008 From: christopher.henk at allisontransmission.com (christopher.henk at allisontransmission.com) Date: Tue, 27 May 2008 17:25:09 -0400 Subject: [Tutor] 180MB In-Reply-To: <21EB45BA6A0A4844B97D46A7721CFDF205D4EC64@gsb-exchmb02.stanford.edu> Message-ID: Looking at my system, it looks like you 180MB is for all your python packages together, not each one. I get 68.67MB under my add/remove which is the size of my Python folder. Chris "Switanek, Nick" Sent by: tutor-bounces at python.org 05/27/2008 04:54 PM To cc Subject [Tutor] 180MB I?m running windows XP. Judging from the Add/Remove programs interface, it appears that many python packages I?ve installed over the years are each taking up right around 180MB. This includes pyreadline, winpdb, pywordnet, numarray, numpy, and many others besides. It seems an uncanny coincidence that each package would be within a few MB of the next. Any insight into whether there is something wrong here, and if so, what I?ve done? Thanks, Nick _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From zmanji at gmail.com Wed May 28 02:35:15 2008 From: zmanji at gmail.com (Zameer Manji) Date: Tue, 27 May 2008 20:35:15 -0400 Subject: [Tutor] Simple Python Projects ? Message-ID: <483CA8C3.4090809@gmail.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA512 Are there any simple python projects out there that have well documented code and are recommended for new users to read and modify ? I have created a few small programs on my own, but I feel that I will learn more now if I attempt to understand code that I have not written and then attempt to modify it. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.7 (MingW32) iQEcBAEBCgAGBQJIPKjDAAoJEA759sZQuQ1BiuUH/04DqroYaNJzusHnAnD0S3Ub rLQUzQHs3Tzt3BvxdJgSnYnDXPe32Ml48c3uxDoe13uI1MUxA44xp/GIM3gkktMh s3IKZqKnYNgE+vmaP3sgTfkLbvs4mPK+SJX7Xk2LZRkBNuxmS6EZhFJ/Iqx6Jjuh 6qIAKVo26TB9+wFpNzaWOX8FyXKR5MuaQO+IwA/Yb3K4AsOxJddF9sMyQOE2kcfX de1RjRxDy0cRtrQkHM0/L+pHIL8i/0T9G4DUnd4Ak3OqEyCnydsfUssn94iuQfMG Sh98N7SAIPRRcse42XWXSI+bwMFVT2vhBrW/KlRW7deT0+3zR3ePuUNsn4eDqUU= =rq24 -----END PGP SIGNATURE----- -------------- next part -------------- A non-text attachment was scrubbed... Name: 0x50B90D41.asc Type: application/pgp-keys Size: 1724 bytes Desc: not available URL: From alan.gauld at btinternet.com Wed May 28 03:06:48 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 28 May 2008 02:06:48 +0100 Subject: [Tutor] Simple Python Projects ? References: <483CA8C3.4090809@gmail.com> Message-ID: "Zameer Manji" wrote > Are there any simple python projects out there that have well > documented > code and are recommended for new users to read and modify ? Depends on what you count as well documented! You can try a search on Sourceforge with lanuage=python. Try fixing some of the reported bugs - bug fixing is a great way to learn things to avoid in your own code! Or you could just try reading and playing with the samples that come with Python. There are some simple code beautifier scripts that could be easily enhanced and are not too hard. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Wed May 28 10:11:03 2008 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Wed, 28 May 2008 08:11:03 +0000 (GMT) Subject: [Tutor] Simple Python Projects ? Message-ID: <498807.12317.qm@web86702.mail.ukl.yahoo.com> > > Or you could just try reading and playing with the samples > > that come with Python. There are some simple code beautifier > > scripts that could be easily enhanced and are not too hard. > This looks very interesting to look at, on a windows installation of > Python where would they be located ? Look in the Tools directory. I'd start with the scrips subdirectory or possibly the webchecker or versioncheck sub folders. There are about 100 files in Tools which should be enough to keep you busy for a while! :-) Alan g From midnightjulia at gmail.com Wed May 28 11:40:02 2008 From: midnightjulia at gmail.com (Julia) Date: Wed, 28 May 2008 11:40:02 +0200 Subject: [Tutor] Simple Python Projects ? Message-ID: I would recommend PyGame.org. While you'll have to learn to use the PyGame library - there are alot of easy tutorials and open source projects. /MJ > Are there any simple python projects out there that have well documented > code and are recommended for new users to read and modify ? > > I have created a few small programs on my own, but I feel that I will > learn more now if I attempt to understand code that I have not written > and then attempt to modify it. -------------- next part -------------- An HTML attachment was scrubbed... URL: From qsqgeekyogdty at tiscali.co.uk Wed May 28 16:14:38 2008 From: qsqgeekyogdty at tiscali.co.uk (qsqgeekyogdty at tiscali.co.uk) Date: Wed, 28 May 2008 15:14:38 +0100 (GMT+01:00) Subject: [Tutor] (no subject) Message-ID: <33144189.1211984078011.JavaMail.root@ps38> Hello, (Sorry if this message gets double posted) I have been looking at using Beautifulsoup python module to make changes to some static html files a total of 167 files, but being a newb in programming was wondering first how to open, read/process the file, then write it, close it and then open the next file thus creating the loop. Can someone post me a simple example of doing this loop for a given directory. Thanks David ________________________ What can Tiscali do for you? http://www.tiscali.co.uk/services From qsqgeekyogdty at tiscali.co.uk Wed May 28 15:50:48 2008 From: qsqgeekyogdty at tiscali.co.uk (qsqgeekyogdty at tiscali.co.uk) Date: Wed, 28 May 2008 14:50:48 +0100 (GMT+01:00) Subject: [Tutor] Example of modifying files in directory Message-ID: <24089762.1211982648941.JavaMail.root@ps38> Hello, I have been looking at using Beautifulsoup python module to make changes to some static html files a total of 167 files, but being a newb in programming was wondering first how to open, read/process the file, then write it, close it and then open the next file thus creating the loop. Can someone post me a simple example of doing this loop for a given directory. Thanks David ________________________ What can Tiscali do for you? http://www.tiscali.co.uk/services From michael at yavarsity.com Wed May 28 16:23:26 2008 From: michael at yavarsity.com (Michael yaV) Date: Wed, 28 May 2008 10:23:26 -0400 Subject: [Tutor] I am a web designer wanting to learn Python Message-ID: <1A7D745C-92F7-4381-9008-1494CB4D6C39@yavarsity.com> Where should I begin/go to learn how to create web apps using Python? I would like to create a dynamic "content managed" website and I have chosen Python as my language of choice. Can anybody show me, a Mac user, where I, a programming beginner, can find tutorials for using Python for web apps? Thank you for any help. Michael From rdm at rcblue.com Wed May 28 16:58:19 2008 From: rdm at rcblue.com (Dick Moores) Date: Wed, 28 May 2008 07:58:19 -0700 Subject: [Tutor] A video introducing Ulipad, an IDE mainly for Python Message-ID: <20080528145832.798C61E400B@bag.python.org> I've been using Ulipad, a free IDE mainly for Python, and written in wxPython, for a couple of years, and think it's terrific. Now another user, Kelie Feng, has made an 8-minute video showing it off. The visual clarity of the video is remarkable. You can download it (Introducing_Ulipad_2008-05-22.avi), and a codec (tscc.exe) that may be necessary for your player, from . Dick Moores From alan.gauld at btinternet.com Wed May 28 17:17:06 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 28 May 2008 16:17:06 +0100 Subject: [Tutor] I am a web designer wanting to learn Python References: <1A7D745C-92F7-4381-9008-1494CB4D6C39@yavarsity.com> Message-ID: "Michael yaV" wrote > Where should I begin/go to learn how to create web apps using > Python? I would like to create a dynamic "content managed" website > and I have chosen Python as my language of choice. Can anybody show > me, a Mac user, where I, a programming beginner, can find tutorials > for using Python for web apps? If you expect to write several apps you should choose a Web Framework. The two most poular are TurboGears and Django. Both have websites, search Google... To use either you will need a good knowledge of Python programming in a non Web way, for that try the standard list of tutorials for either non-programmers or programmers from another language. http://wiki.python.org/moin/BeginnersGuide/NonProgrammers http://wiki.python.org/moin/BeginnersGuide/Programmers Then you can read about the fundamentals of web programming in the Web Topic Guide area of the Python web site http://wiki.python.org/moin/WebProgramming If you do go for a Web Framework you might also like the ShowMeDo website which has short video tutorials showing how to set up and create yur first web site. They definitely do Django and I think they might do TG too. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From sazelton at nd.edu Wed May 28 17:29:59 2008 From: sazelton at nd.edu (Sean Azelton) Date: Wed, 28 May 2008 11:29:59 -0400 Subject: [Tutor] A video introducing Ulipad, an IDE mainly for Python In-Reply-To: <69C3FA99EE2BAC4A81B9F63331B68F660ADFBA252E@ICE-MBX-1.ice.nd.edu> References: <69C3FA99EE2BAC4A81B9F63331B68F660ADFBA252E@ICE-MBX-1.ice.nd.edu> Message-ID: For those looking for the codec and not running Windows, you can find it here for Mac OS X as well http://www.techsmith.com/download/codecs.asp On Wed, May 28, 2008 at 11:01 AM, Dick Moores wrote: > I've been using Ulipad, a free IDE mainly for Python, and written in > wxPython, for a couple of years, and think it's terrific. Now another > user, Kelie Feng, has made an 8-minute video showing it off. The > visual clarity of the video is remarkable. You can download it > (Introducing_Ulipad_2008-05-22.avi), and a codec (tscc.exe) that may > be necessary for your player, from . > > Dick Moores > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Sean Azelton Systems Engineer : University of Notre Dame Notre Dame, IN http://www.linkedin.com/in/azelton From wescpy at gmail.com Wed May 28 20:04:33 2008 From: wescpy at gmail.com (wesley chun) Date: Wed, 28 May 2008 11:04:33 -0700 Subject: [Tutor] I am a web designer wanting to learn Python In-Reply-To: References: <1A7D745C-92F7-4381-9008-1494CB4D6C39@yavarsity.com> Message-ID: <78b3a9580805281104l632bcc55tff8f6e61e59c9950@mail.gmail.com> > > Where should I begin/go to learn how to create web apps using Python? I > would like to create a dynamic "content managed" website and I have chosen > Python as my language of choice. Can anybody show me, a Mac user, where I, > a programming beginner, can find tutorials for using Python for web apps? hi, and welcome to Python! out of curiosity, how did you arrive at the conclusion that you should use Python? > If you expect to write several apps you should choose a Web Framework. > The two most poular are TurboGears and Django. Both have websites, > search Google... you *could*, or we can just say http://djangoproject.com and http://turbogears.org if you are new to Python, i would suggest Django over TurboGears, not that Django is "better than" TG, but because those who favor TG are usually already familiar with Python, esp. the best-of-breed components of which it serves as the "glue", i.e. SQLObject/SQLAlchemy, CherryPy, MochiKit, Genshi/Kid. Django is an "all-in-one" package and requires "less overhead" if you're new to Python. on a related note, if you're interested solely in creating, running, managing, developing, and/or supporting a "content managed" site, i.e. run by a "content management system" (or CMS), you may also wish to look at Plone -- http://plone.org ... this is its speciality. all 3 of these frameworks have documentation as well as video clips on "how easy it is to use them" on their websites. if you're looking for reading, we can also recommend some books for you, but it will depend on your previous/current programming experience. best of luck! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From kent37 at tds.net Wed May 28 20:50:57 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 28 May 2008 14:50:57 -0400 Subject: [Tutor] Example of modifying files in directory In-Reply-To: <24089762.1211982648941.JavaMail.root@ps38> References: <24089762.1211982648941.JavaMail.root@ps38> Message-ID: <1c2a2c590805281150i482bfaf4if76f427c442c7274@mail.gmail.com> On Wed, May 28, 2008 at 9:50 AM, qsqgeekyogdty at tiscali.co.uk wrote: > Hello, > I have been looking at using Beautifulsoup python module to make > changes to some static html files a total of 167 files, but being a > newb in programming was wondering first how to open, read/process the > file, then write it, close it and then open the next file thus creating > the loop. I guess this is the simplest possible loop to do something to each file in a directory. You would call processDir() with the path to the directory to process. Define a function doSomethingWith() that takes the file contents as an argument and returns the new file contents. import os def processDir(dirpath): for name in os.listdir(dirpath): filepath = os.path.join(dirpath, name) f = open(filepath) data = f.read() f.close() data = doSomethingTo(data) f = open(filepath, 'w') f.write(data) f.close() This modifies files in place so you should have a backup. It assumes everything in the dir is a file; if not you need to check in the loop. HTH, Kent From michael at yavarsity.com Wed May 28 21:14:16 2008 From: michael at yavarsity.com (Michael yaV) Date: Wed, 28 May 2008 15:14:16 -0400 Subject: [Tutor] I am a web designer wanting to learn Python In-Reply-To: <78b3a9580805281104l632bcc55tff8f6e61e59c9950@mail.gmail.com> References: <1A7D745C-92F7-4381-9008-1494CB4D6C39@yavarsity.com> <78b3a9580805281104l632bcc55tff8f6e61e59c9950@mail.gmail.com> Message-ID: Wesley, I have been wanting to learn a language for the last 10 years, I am now just getting around to it. I did some research on languages, because I decided if I was going learn one, I wanted to learn something that I could use for many different applications (web being one). Python seemed to offer all I was looking for, plus, I have been told, it is rather easy to learn. Why? Michael On May 28, 2008, at 2:04 PM, wesley chun wrote: >>> Where should I begin/go to learn how to create web apps using >>> Python? I >> would like to create a dynamic "content managed" website and I >> have chosen >> Python as my language of choice. Can anybody show me, a Mac user, >> where I, >> a programming beginner, can find tutorials for using Python for >> web apps? > > > hi, and welcome to Python! > > out of curiosity, how did you arrive at the conclusion that you should > use Python? > > >> If you expect to write several apps you should choose a Web >> Framework. >> The two most poular are TurboGears and Django. Both have websites, >> search Google... > > you *could*, or we can just say http://djangoproject.com and > http://turbogears.org > > if you are new to Python, i would suggest Django over TurboGears, not > that Django is "better than" TG, but because those who favor TG are > usually already familiar with Python, esp. the best-of-breed > components of which it serves as the "glue", i.e. > SQLObject/SQLAlchemy, CherryPy, MochiKit, Genshi/Kid. Django is an > "all-in-one" package and requires "less overhead" if you're new to > Python. > > on a related note, if you're interested solely in creating, running, > managing, developing, and/or supporting a "content managed" site, i.e. > run by a "content management system" (or CMS), you may also wish to > look at Plone -- http://plone.org ... this is its speciality. > > all 3 of these frameworks have documentation as well as video clips on > "how easy it is to use them" on their websites. > > if you're looking for reading, we can also recommend some books for > you, but it will depend on your previous/current programming > experience. > > best of luck! > -- wesley > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > "Core Python Programming", Prentice Hall, (c)2007,2001 > http://corepython.com > > wesley.j.chun :: wescpy-at-gmail.com > python training and technical consulting > cyberweb.consulting : silicon valley, ca > http://cyberwebconsulting.com > From wescpy at gmail.com Wed May 28 21:50:55 2008 From: wescpy at gmail.com (wesley chun) Date: Wed, 28 May 2008 12:50:55 -0700 Subject: [Tutor] I am a web designer wanting to learn Python In-Reply-To: References: <1A7D745C-92F7-4381-9008-1494CB4D6C39@yavarsity.com> <78b3a9580805281104l632bcc55tff8f6e61e59c9950@mail.gmail.com> Message-ID: <78b3a9580805281250o5b4f4890s359fa35ca02774f8@mail.gmail.com> > I have been wanting to learn a language for the last 10 years, I am now > just getting around to it. I did some research on languages, because I > decided if I was going learn one, I wanted to learn something that I could > use for many different applications (web being one). Python seemed to offer > all I was looking for, plus, I have been told, it is rather easy to learn. > Why? the community is interested in knowing how new members came to the Python family. :-) sounds like you're new to programming. there are few good books on this subject: - Python Programming: An Introduction to Computer Science (John Zelle) - Python Programming for the Absolute Beginner (Michael Dawson) - Python For Dummies (Stef and Aahz Maruch) - How To Think Like a Computer Scientist (Allen Downey, Jeffrey Elkner, Chris Meyers) - Introduction to Computing and Programming in Python (Mark Guzdial) - Learn to Program Using Python (Alan Gauld) - Python: Visual QuickStart Guide (Chris Fehily) there are also some great online tutorials: - Python.org tutorial http://docs.python.org/tut - Instant Hacking http://www.hetland.org/python/instant-hacking.php - How to Think Like a Computer Scientst http://openbookproject.net/thinkCSpy/ - Learning to Program http://www.freenetpages.co.uk/hp/alan.gauld/ here is a link to a more comprehsnvie list of Python-related tutorials: - Python Tutorials http://awaretek.com/tutorials.html cheers, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From michael at yavarsity.com Wed May 28 22:05:53 2008 From: michael at yavarsity.com (Michael yaV) Date: Wed, 28 May 2008 16:05:53 -0400 Subject: [Tutor] I am a web designer wanting to learn Python In-Reply-To: <78b3a9580805281250o5b4f4890s359fa35ca02774f8@mail.gmail.com> References: <1A7D745C-92F7-4381-9008-1494CB4D6C39@yavarsity.com> <78b3a9580805281104l632bcc55tff8f6e61e59c9950@mail.gmail.com> <78b3a9580805281250o5b4f4890s359fa35ca02774f8@mail.gmail.com> Message-ID: <27D77075-5747-4E7D-8409-17E722ABA6EE@yavarsity.com> Thanks... I have my-work-cut-out-for-me. Michael On May 28, 2008, at 3:50 PM, wesley chun wrote: >> I have been wanting to learn a language for the last 10 years, I am >> now >> just getting around to it. I did some research on languages, >> because I >> decided if I was going learn one, I wanted to learn something that >> I could >> use for many different applications (web being one). Python seemed >> to offer >> all I was looking for, plus, I have been told, it is rather easy to >> learn. >> Why? > > the community is interested in knowing how new members came to the > Python family. :-) > > sounds like you're new to programming. there are few good books on > this subject: > - Python Programming: An Introduction to Computer Science (John Zelle) > - Python Programming for the Absolute Beginner (Michael Dawson) > - Python For Dummies (Stef and Aahz Maruch) > - How To Think Like a Computer Scientist (Allen Downey, Jeffrey > Elkner, Chris Meyers) > - Introduction to Computing and Programming in Python (Mark Guzdial) > - Learn to Program Using Python (Alan Gauld) > - Python: Visual QuickStart Guide (Chris Fehily) > > there are also some great online tutorials: > - Python.org tutorial http://docs.python.org/tut > - Instant Hacking http://www.hetland.org/python/instant-hacking.php > - How to Think Like a Computer Scientst http://openbookproject.net/thinkCSpy/ > - Learning to Program http://www.freenetpages.co.uk/hp/alan.gauld/ > > here is a link to a more comprehsnvie list of Python-related > tutorials: > - Python Tutorials http://awaretek.com/tutorials.html > > cheers, > -- wesley > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > "Core Python Programming", Prentice Hall, (c)2007,2001 > http://corepython.com > > wesley.j.chun :: wescpy-at-gmail.com > python training and technical consulting > cyberweb.consulting : silicon valley, ca > http://cyberwebconsulting.com > From bgailer at gmail.com Wed May 28 22:40:44 2008 From: bgailer at gmail.com (bob gailer) Date: Wed, 28 May 2008 16:40:44 -0400 Subject: [Tutor] A video introducing Ulipad, an IDE mainly for Python In-Reply-To: <20080528145832.798C61E400B@bag.python.org> References: <20080528145832.798C61E400B@bag.python.org> Message-ID: <483DC34C.9050308@gmail.com> Dick Moores wrote: > I've been using Ulipad, a free IDE mainly for Python, and written in > wxPython, for a couple of years, and think it's terrific. Thanks - IUlipad has some nice features, but I'd miss the debugging in PythonWin. -- Bob Gailer 919-636-4239 Chapel Hill, NC From chombee at nerdshack.com Wed May 28 22:41:36 2008 From: chombee at nerdshack.com (chombee) Date: Wed, 28 May 2008 21:41:36 +0100 Subject: [Tutor] 'Right' way to implement mixins in Python? Message-ID: <1212007297.17536.12.camel@marley> I'm writing an event-driven GUI framework. I have several independent units of functionality such as Draggable, Highlightable, etc. Although these units of functionality are independent of each other, they do all depend on a certain base implementation that they work with. I want widget objects to be able to select different combinations of these capabilities at will. So mixins seemed like the way to go. It seemed to me that the most natural way to implement mixins in Python is to use multiple inheritance with new-style classes. But I certainly confused myself a lot trying to do it. I think I have come up with the solution, although its late and this is pretty rushed, but I thought it would put it out there for comment. Is this the right thing to do? The lessons I learned are that, when implementing mixins using multiple inheritance: * Mixin classes should not derive from any base class (except object) * But they may assume that the classes they will be mixed in with do derive from a certain base class, so they may assume the base class is there. Here's some code showing the approach that seems to work for me: class Base(object): """Base class for mixer classes. All mixin classes require the classes they are mixed in with to be instances of this class (or a subclass).""" def __init__(self,b): self.b = b # Mixin classes assume this attribute will be present class MixinBPlusOne(object): """A mixin class that implements the print_b_plus_one method.""" def __init__(self): print 'MixinBPlusOne initialising' def print_b_plus_one(self): print self.b+1 class MixinBMinusOne(object): """A mixin class that implements the print_b_minus_one method.""" def __init__(self): print 'MixinBMinusOne initialising' def print_b_minus_one(self): print self.b-1 class Mixer(Base,MixinBPlusOne,MixinBMinusOne): """A mixer class (class that inherits some mixins), this will work because it also inherits Base, which the mixins expect.""" def __init__(self,b): # I feel like I should be using super here because # I'm using new-style classes and multiple # inheritance, but the argument list of # Base.__init__ differs from those of the Mixin # classes, and this seems to work anyway. Base.__init__(self,b) MixinBPlusOne.__init__(self) MixinBMinusOne.__init__(self) class BrokenMixer(MixinBPlusOne,MixinBMinusOne): """This will not work because it does not inherit Base, which the mixins expect it to do.""" pass m = Mixer(9) m.print_b_plus_one() m.print_b_minus_one() m = BrokenMixer(9) m.print_b_plus_one() # It'll crash here. It outputs this, the result I expected: MixinBPlusOne initialising MixinBMinusOne initialising 10 8 From cappy2112 at gmail.com Wed May 28 20:24:32 2008 From: cappy2112 at gmail.com (Tony Cappellini) Date: Wed, 28 May 2008 11:24:32 -0700 Subject: [Tutor] Python Programming for the Absolute Beginner-OT Message-ID: <8249c4ac0805281124k24217d8cy432844449e609c90@mail.gmail.com> A bit OT, but still within the realm of beginning Python... My co-worker whom has just started learning Python, bought this book in used condition. http://www.courseptr.com/ptr_detail.cfm?group=Programming&subcat=Other&isbn=978%2D1%2D59863%2D112%2D8 Unfortunately it came without the CD, and the publisher does not have a link for downloading the sources. If you have this book AND the CD, please reply to me OFF-LIST. I would like to get a copy of the files on the CD for my co-worker. Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu May 29 00:30:53 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 28 May 2008 23:30:53 +0100 Subject: [Tutor] 'Right' way to implement mixins in Python? References: <1212007297.17536.12.camel@marley> Message-ID: "chombee" wrote > I'm writing an event-driven GUI framework. I have several > independent > units of functionality such as Draggable, Highlightable, etc. > Although > these units of functionality are independent of each other, they do > all > depend on a certain base implementation that they work with. That's a bad thing in a mixin. Mixins should be as independant as possible from any other classes. Unfortunately thats not always possible so you should try to create an abstract superclass/interface and use that in your mixins. You can then subclass the mixin and replace the abstract class with the local concrete manifestation. It means one extra level of inheritance because you wind up with an abstract mixin plus the localised mixin. > widget objects to be able to select different combinations of these > capabilities at will. So mixins seemed like the way to go. Sounds a fair approach. So long as you are aware of the extra coomplexities asociated with maintaining very wide multi-inheritance heirarchies. > It seemed to me that the most natural way to implement mixins in > Python > is to use multiple inheritance with new-style classes. But I > certainly > confused myself a lot trying to do it. Mixins are normally done using MI. I''m interested in your experiences. Did new style classes specifically add problems(I've only done mixins in old style classes in Python, I've mainly used mixins in Lisp) > The lessons I learned are that, when implementing mixins using > multiple > inheritance: > > * Mixin classes should not derive from any base class (except > object) > * But they may assume that the classes they will be mixed in with do > derive from a certain base class, so they may assume the base class > is > there. Yes to both, regardless of language. As I said above you can make the mixins slightly more generally reusable by creating abstact mixins with explicit dependancy on an abstact interface. But better still is to avoid dependencies as much as possible where mixins are concerned. Instead build a protocol in the class framework outside the mixins and let them coerce the dependencies to suit the mixin interfaces. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From rdm at rcblue.com Thu May 29 00:32:47 2008 From: rdm at rcblue.com (Dick Moores) Date: Wed, 28 May 2008 15:32:47 -0700 Subject: [Tutor] A video introducing Ulipad, an IDE mainly for Python In-Reply-To: <483DC34C.9050308@gmail.com> References: <20080528145832.798C61E400B@bag.python.org> <483DC34C.9050308@gmail.com> Message-ID: <20080528223302.438031E4003@bag.python.org> At 01:40 PM 5/28/2008, bob gailer wrote: >Dick Moores wrote: >>I've been using Ulipad, a free IDE mainly for Python, and written >>in wxPython, for a couple of years, and think it's terrific. > >Thanks - IUlipad has some nice features, but I'd miss the debugging >in PythonWin. Hey, Ulipad has WinPdb. Dick Moores From chombee at nerdshack.com Thu May 29 01:20:32 2008 From: chombee at nerdshack.com (chombee) Date: Thu, 29 May 2008 00:20:32 +0100 Subject: [Tutor] 'Right' way to implement mixins in Python? In-Reply-To: References: <1212007297.17536.12.camel@marley> Message-ID: <1212016832.18164.13.camel@tig> Thanks Alan. Well, it looks like I've worked it out as far as small example programs go, hope I can get it working in my actual codebase now. On Wed, 2008-05-28 at 23:30 +0100, Alan Gauld wrote: > > It seemed to me that the most natural way to implement mixins in > > Python > > is to use multiple inheritance with new-style classes. But I > > certainly > > confused myself a lot trying to do it. > > Mixins are normally done using MI. I''m interested in your > experiences. > Did new style classes specifically add problems(I've only done mixins > in old style classes in Python, I've mainly used mixins in Lisp) The reason I started using new-style classes was that I had a diamond shape in my class inheritance hierarchy. All my mixin classes inherited from a single base class, and then all my widget classes multiple-inherited from selections of mixin classes. (I realise this is wrong now, but that's how I had it.) So to get the method resolution order working right with this diamond formation, I needed new-style classes. And with this diamond formation, to prevent the __init__ method of the base class being called many times when a widget class inherits many mixin classes, you have to use super() instead of explicit calls to all the parent __init__ methods. Then you run into a problem when the parameters taken the by __init__ methods of the mixins do not match each other or the paramaters taken by the __init__ method of the base class. If a multiple-inheriting widget class has in its class ancestry a number of different __init__ methods with different parameter lists, how can it call them all with a single use of super? So then you have to use *args and **kwargs in the __init__ method of _every_ class instead of specifying the parameters normally, and this has a disadvantage, that the checking of the parameter lists that Python would normally do is circumvented and you end up having to reimplement it yourself. By this time I was pretty put off by this approach, and was getting TypeErrors in my implementation, and decided not to push forward with it. Basically, I think that super in Python is a total mess, very tricky and unwieldy. To be avoided. And also, I think multiple inheritance is tricky and to be used minimally, avoiding diamond formations or worse. I understand now why Java does not allow multiple inheritance. But it all stemmed from my initial mistake, of having all the mixin classes inherit from a common base class. Take away that and you get rid of the diamond inheritance formation, you no longer need to use super, in fact, I probably don't need to use new-style classes at all. That's an entire days work summed up, trying to refactor my codebase to use mixins. From kent37 at tds.net Thu May 29 02:11:46 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 28 May 2008 20:11:46 -0400 Subject: [Tutor] 'Right' way to implement mixins in Python? In-Reply-To: References: <1212007297.17536.12.camel@marley> Message-ID: <1c2a2c590805281711x598f4045y30fc55689c52f12@mail.gmail.com> On Wed, May 28, 2008 at 6:30 PM, Alan Gauld wrote: > Mixins should be as independant > as possible from any other classes. Unfortunately thats not > always possible so you should try to create an abstract > superclass/interface and use that in your mixins. You can then > subclass the mixin and replace the abstract class with the local > concrete manifestation. It means one extra level of inheritance because > you wind up with an abstract mixin plus the localised mixin. I don't understand what you mean by this. Python doesn't really have abstract classes and interfaces. And how is this different than requiring the mixins to be used with only subclasses of a certain concrete class? > Instead build a protocol in the class framework outside the mixins > and let them coerce the dependencies to suit the mixin interfaces. Can you explain? I don't know what this means. Thanks, Kent From astroultraman at gmail.com Thu May 29 02:43:01 2008 From: astroultraman at gmail.com (Robert William Hanks) Date: Thu, 29 May 2008 01:43:01 +0100 Subject: [Tutor] why? Message-ID: <6be1291e0805281743l2b82818dg955173d95b1f25ac@mail.gmail.com> Need ti find out whem a number o this form i**3+j**3+1 is acube. tryed a simple brute force code but, why this not work? def iscube(n): cubed_root = n**(1/3.0) if round(cubed_root)**3 == n: return True else: return False for i in range(1,10000000): for j in range(1,10000000): soma= i**3 +j**3 +1 if isCube(soma): print i print j print soma -------------- next part -------------- An HTML attachment was scrubbed... URL: From john at fouhy.net Thu May 29 02:51:39 2008 From: john at fouhy.net (John Fouhy) Date: Thu, 29 May 2008 12:51:39 +1200 Subject: [Tutor] why? In-Reply-To: <6be1291e0805281743l2b82818dg955173d95b1f25ac@mail.gmail.com> References: <6be1291e0805281743l2b82818dg955173d95b1f25ac@mail.gmail.com> Message-ID: <5e58f2e40805281751t127f4a46q5325b1f465145ec2@mail.gmail.com> On 29/05/2008, Robert William Hanks wrote: > > Need ti find out whem a number o this form i**3+j**3+1 is acube. > tryed a simple brute force code but, why this not work? [deleted code] Why doesn't this work? What problems are you having? -- John. From bgailer at gmail.com Thu May 29 03:12:55 2008 From: bgailer at gmail.com (bob gailer) Date: Wed, 28 May 2008 21:12:55 -0400 Subject: [Tutor] why? In-Reply-To: <6be1291e0805281743l2b82818dg955173d95b1f25ac@mail.gmail.com> References: <6be1291e0805281743l2b82818dg955173d95b1f25ac@mail.gmail.com> Message-ID: <483E0317.3050106@gmail.com> Robert William Hanks wrote: > > Need ti find out whem a number o this form i**3+j**3+1 is acube. > tryed a simple brute force code but, why this not work? > > def iscube(n): > cubed_root = n**(1/3.0) > if round(cubed_root)**3 == n: > return True > else: > return False > > for i in range(1,10000000): > for j in range(1,10000000): > soma= i**3 +j**3 +1 > if isCube(soma): > print i > print j > print soma > > Always report the specific problem. Saying "why this not work?" does not help. What happens when you run this program? When I do I get: File "J:\pipelines\cubed.py", line 11, in if isCube(soma): NameError: name 'isCube' is not defined When I examine the program I'm not surprised to get that exception. -- Bob Gailer 919-636-4239 Chapel Hill, NC From bgailer at gmail.com Thu May 29 03:32:56 2008 From: bgailer at gmail.com (bob gailer) Date: Wed, 28 May 2008 21:32:56 -0400 Subject: [Tutor] why? In-Reply-To: <6be1291e0805281743l2b82818dg955173d95b1f25ac@mail.gmail.com> References: <6be1291e0805281743l2b82818dg955173d95b1f25ac@mail.gmail.com> Message-ID: <483E07C8.9010902@gmail.com> Robert William Hanks wrote: > > Need ti find out whem a number o this form i**3+j**3+1 is acube. > tryed a simple brute force code but, why this not work? > > def iscube(n): > cubed_root = n**(1/3.0) > if round(cubed_root)**3 == n: > return True > else: > return False > > for i in range(1,10000000): > for j in range(1,10000000): > soma= i**3 +j**3 +1 > if isCube(soma): > print i > print j > print soma > Assuming you fixed the problem, do you know of any cases for which i**3 +j**3 +1 is a cube? Also note this program will run for a LONG time. You can shorten the run time: for i in range(1,10000000): for j in range(j,10000000): # test each combination once soma = i**3 +j**3 +1 cubed_root = soma**(0.333) # function call and division take extra time and there is no need for either if abs(cubed_root - round(cubed_root)) < .01: # this is a guess at close enough, and cheaper than cubing? print i print j print soma -- Bob Gailer 919-636-4239 Chapel Hill, NC From kent37 at tds.net Thu May 29 03:58:11 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 28 May 2008 21:58:11 -0400 Subject: [Tutor] why? In-Reply-To: <6be1291e0805281743l2b82818dg955173d95b1f25ac@mail.gmail.com> References: <6be1291e0805281743l2b82818dg955173d95b1f25ac@mail.gmail.com> Message-ID: <1c2a2c590805281858l227fcefbs6b0449432f2daa31@mail.gmail.com> On Wed, May 28, 2008 at 8:43 PM, Robert William Hanks wrote: > > Need ti find out whem a number o this form i**3+j**3+1 is acube. > tryed a simple brute force code but, why this not work? > > def iscube(n): > cubed_root = n**(1/3.0) > if round(cubed_root)**3 == n: > return True > else: > return False > > for i in range(1,10000000): > for j in range(1,10000000): > soma= i**3 +j**3 +1 > if isCube(soma): > print i > print j > print soma Let's see. The inner loop will run 10000000 * 10000000 = 100000000000000 times. That's a pretty big number. Suppose each iteration of the loop takes 1 microsecond. (That seems optimistic but not too much - on my computer iscube(27) takes about 1.3 microseconds.) Then the entire program will complete in 10000000 * 10000000 / 1000000 / 60 / 60 / 24 / 365 = 3 years. Other than that it look OK to me... Looks like you need either a better algorithm or a faster computer! Kent From python at bdurham.com Thu May 29 04:52:13 2008 From: python at bdurham.com (python at bdurham.com) Date: Wed, 28 May 2008 22:52:13 -0400 Subject: [Tutor] I am a web designer wanting to learn Python In-Reply-To: <78b3a9580805281250o5b4f4890s359fa35ca02774f8@mail.gmail.com> References: <1A7D745C-92F7-4381-9008-1494CB4D6C39@yavarsity.com> <78b3a9580805281104l632bcc55tff8f6e61e59c9950@mail.gmail.com> <78b3a9580805281250o5b4f4890s359fa35ca02774f8@mail.gmail.com> Message-ID: <1212029533.11901.1255606851@webmail.messagingengine.com> Wesley, Don't be so modest - your "Core Python Programming" (by Wesley Chun) is also a great book for those looking to learn Python. Malcolm From wescpy at gmail.com Thu May 29 09:07:31 2008 From: wescpy at gmail.com (wesley chun) Date: Thu, 29 May 2008 00:07:31 -0700 Subject: [Tutor] I am a web designer wanting to learn Python In-Reply-To: <1212029533.11901.1255606851@webmail.messagingengine.com> References: <1A7D745C-92F7-4381-9008-1494CB4D6C39@yavarsity.com> <78b3a9580805281104l632bcc55tff8f6e61e59c9950@mail.gmail.com> <78b3a9580805281250o5b4f4890s359fa35ca02774f8@mail.gmail.com> <1212029533.11901.1255606851@webmail.messagingengine.com> Message-ID: <78b3a9580805290007h16abe874ja2323814b242cae6@mail.gmail.com> > Don't be so modest - your "Core Python Programming" (by Wesley Chun) is > also a great book for those looking to learn Python. malcolm, thanks for the kudos... really appreciate it. however, the reason why i didn't bring it up is because the target audience of my book is (generally) a technical person who already has some programming experience and wants/needs to learn Python as quickly and as comprehensively as possible. i don't really recommend my book for those who are completely new to programming as i think there are others who do a better job, hence all the recommendations in my previous message. (ironically, i've developed an entire training course for people who are absolute beginners to programming [with Python being the implementation language], but can't figure out the best and most effective way to advertise/market the course... maybe one day!) once michael comes up to speed, however, he's welcome to read "Core Python Programming" to fill in any gaps in his Python skills. :-) in closing, let me take one more cat out of the bag... i've been helping 2 fine gentlemen in developing a book on Django... yes, that Python web framework. we are wrapping it up, and it should be on the store shelves this fall. more info at the book's website at http://withdjango.com/ ... it is complementary to the reference book out there but is geared towards developing Django *applications*. look for it soon! best wishes, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From astroultraman at gmail.com Thu May 29 10:01:42 2008 From: astroultraman at gmail.com (Robert William Hanks) Date: Thu, 29 May 2008 09:01:42 +0100 Subject: [Tutor] why? In-Reply-To: <1c2a2c590805281858l227fcefbs6b0449432f2daa31@mail.gmail.com> References: <6be1291e0805281743l2b82818dg955173d95b1f25ac@mail.gmail.com> <1c2a2c590805281858l227fcefbs6b0449432f2daa31@mail.gmail.com> Message-ID: <6be1291e0805290101m3bfd88car65c1b68f71de766@mail.gmail.com> hi, i do not need a fancy elegant code, know this one is ugly and take to much time(i will for now use ctrl+c to break) my problem is that the result are wrong, just test one of the reults printed by this code, and you will see tha the results are wrong. Maybe something i do not understand is happenig wen python round the the cubed root. is this code wrong? On 5/29/08, Kent Johnson wrote: > On Wed, May 28, 2008 at 8:43 PM, Robert William Hanks > wrote: > > > > Need ti find out whem a number o this form i**3+j**3+1 is acube. > > tryed a simple brute force code but, why this not work? > > > > def iscube(n): > > cubed_root = n**(1/3.0) > > if round(cubed_root)**3 == n: > > return True > > else: > > return False > > > > for i in range(1,10000000): > > for j in range(1,10000000): > > soma= i**3 +j**3 +1 > > if isCube(soma): > > print i > > print j > > print soma > > Let's see. The inner loop will run 10000000 * 10000000 = > 100000000000000 times. That's a pretty big number. Suppose each > iteration of the loop takes 1 microsecond. (That seems optimistic but > not too much - on my computer iscube(27) takes about 1.3 > microseconds.) Then the entire program will complete in 10000000 * > 10000000 / 1000000 / 60 / 60 / 24 / 365 = 3 years. Other than that it > look OK to me... > > Looks like you need either a better algorithm or a faster computer! > > Kent > -------------- next part -------------- An HTML attachment was scrubbed... URL: From qsqgeekyogdty at tiscali.co.uk Thu May 29 10:17:40 2008 From: qsqgeekyogdty at tiscali.co.uk (qsqgeekyogdty at tiscali.co.uk) Date: Thu, 29 May 2008 09:17:40 +0100 (GMT+01:00) Subject: [Tutor] Modifying files in a directory. Message-ID: <25264616.1212049060519.JavaMail.root@ps25> Hi, >From my previous post, I have tis so far: [code] import os from BeautifulSoup import BeautifulSoup rootdir='/home/david/test' def upDateTable(line): soup = BeautifulSoup(''.join(file)) return line for subdir, dirs, files in os.walk(rootdir): for file in files: f=open(file, 'r') lines=f.readlines() f.close() f=open(file, 'w') for line in lines: newline=upDateTable(line) f.write(newline) f.close() [/code] In each html file I have this table, which I want to modify: [code]
PV Clad Analysis
200
$79.99
[/code] So the table has a class="tbl_left_inside" and I want to update the $79.99 so that the price is reduced by 15% And I want to add a new Buy Now! Thanks David ________________________ What can Tiscali do for you? http://www.tiscali.co.uk/services From wxpythoner at gmail.com Thu May 29 11:05:09 2008 From: wxpythoner at gmail.com (Chester) Date: Thu, 29 May 2008 11:05:09 +0200 Subject: [Tutor] Modifying files in a directory. In-Reply-To: <25264616.1212049060519.JavaMail.root@ps25> References: <25264616.1212049060519.JavaMail.root@ps25> Message-ID: <670cc5db0805290205x7e5205fbpfd8b079578c672c7@mail.gmail.com> please correct this from BeautifulSoup import BeautifulSoup to be from BeautifulSoup import BeautifulStoneSoup On Thu, May 29, 2008 at 10:17 AM, qsqgeekyogdty at tiscali.co.uk < qsqgeekyogdty at tiscali.co.uk> wrote: > Hi, > >From my previous post, I have tis so far: > > [code] > import os > from BeautifulSoup import BeautifulSoup > > > rootdir='/home/david/test' > > def upDateTable(line): > soup = BeautifulSoup(''.join(file)) > > > return line > > for subdir, dirs, files in os.walk(rootdir): > for file in files: > f=open(file, 'r') > lines=f.readlines() > f.close() > f=open(file, 'w') > for line in lines: > newline=upDateTable(line) > f.write(newline) > f.close() > > [/code] > > In each html file I have this table, which I want to modify: > > [code] > > > > > > > > > > >
PV Clad Analysis
200
$79.99
> > [/code] > > So the table has a class="tbl_left_inside" and I want to update the > $79.99 so that the price is reduced by 15% > > And I want to add a new Buy Now! > > > Thanks > David > > > > ________________________ > What can Tiscali do for you? http://www.tiscali.co.uk/services > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From cfuller at thinkingplanet.net Thu May 29 04:25:20 2008 From: cfuller at thinkingplanet.net (Chris Fuller) Date: Wed, 28 May 2008 21:25:20 -0500 Subject: [Tutor] why? In-Reply-To: <483E07C8.9010902@gmail.com> References: <6be1291e0805281743l2b82818dg955173d95b1f25ac@mail.gmail.com> <483E07C8.9010902@gmail.com> Message-ID: <200805282125.20542.cfuller@thinkingplanet.net> On Wednesday 28 May 2008 20:32, bob gailer wrote: > Robert William Hanks wrote: > > Need ti find out whem a number o this form i**3+j**3+1 is acube. > > tryed a simple brute force code but, why this not work? > > > > def iscube(n): > > cubed_root = n**(1/3.0) > > if round(cubed_root)**3 == n: > > return True > > else: > > return False > > > > for i in range(1,10000000): > > for j in range(1,10000000): > > soma= i**3 +j**3 +1 > > if isCube(soma): > > print i > > print j > > print soma > > Assuming you fixed the problem, do you know of any cases for which i**3 > +j**3 +1 is a cube? > > Also note this program will run for a LONG time. > > You can shorten the run time: > > for i in range(1,10000000): > for j in range(j,10000000): # test each combination once > soma = i**3 +j**3 +1 > cubed_root = soma**(0.333) # function call and division take > extra time and there is no need for either > if abs(cubed_root - round(cubed_root)) < .01: # this is a > guess at close enough, and cheaper than cubing? > print i > print j > print soma Actually, another flaw is the isCube (or iscube) function. This will produce false cubes, due to the rounding and floating point approximations. If you turn the problem around, and iterate through all n**3, and then iterate through all i,j less than n, and find all the i,j such that i**3+j**3+1==n**3, the run time will be much, much less for any given n, and eliminates the approximations. Cheers From qsqgeekyogdty at tiscali.co.uk Thu May 29 12:07:46 2008 From: qsqgeekyogdty at tiscali.co.uk (qsqgeekyogdty at tiscali.co.uk) Date: Thu, 29 May 2008 11:07:46 +0100 (GMT+01:00) Subject: [Tutor] Modifying files in a directory. Message-ID: <23627165.1212055666039.JavaMail.root@ps27> ok, but looking at the docs isn't BeautifulStoneSoup an XML parser or am I missing something? David ________________________ Guard against online ID theft - http://www.tiscali.co.uk/spyguard -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Thu May 29 12:15:16 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 29 May 2008 06:15:16 -0400 Subject: [Tutor] why? In-Reply-To: <6be1291e0805281743l2b82818dg955173d95b1f25ac@mail.gmail.com> References: <6be1291e0805281743l2b82818dg955173d95b1f25ac@mail.gmail.com> Message-ID: <1c2a2c590805290315r3698cbckaf5314458eca83@mail.gmail.com> On Wed, May 28, 2008 at 8:43 PM, Robert William Hanks wrote: > > Need ti find out whem a number o this form i**3+j**3+1 is acube. > tryed a simple brute force code but, why this not work? > > def iscube(n): > cubed_root = n**(1/3.0) > if round(cubed_root)**3 == n: Try if int(round(cubed_root)) ** 3 == n so the cube is done with integer arithmetic instead of floating point. Kent From kent37 at tds.net Thu May 29 12:25:43 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 29 May 2008 06:25:43 -0400 Subject: [Tutor] Modifying files in a directory. In-Reply-To: <25264616.1212049060519.JavaMail.root@ps25> References: <25264616.1212049060519.JavaMail.root@ps25> Message-ID: <1c2a2c590805290325o5a533a88q70002e2c57daee44@mail.gmail.com> On Thu, May 29, 2008 at 4:17 AM, qsqgeekyogdty at tiscali.co.uk wrote: > Hi, > >From my previous post, I have tis so far: > > [code] > import os > from BeautifulSoup import BeautifulSoup > > > rootdir='/home/david/test' > > def upDateTable(line): > soup = BeautifulSoup(''.join(file)) > > > return line Notice you are not using or changing line at all here. BS will work best for this if you pass it the entire contents of the file, not a line at a time as you are doing. To figure out the exact commands you need to give BS, it is very helpful to experiment on the command line. Kent From kent37 at tds.net Thu May 29 12:27:32 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 29 May 2008 06:27:32 -0400 Subject: [Tutor] Modifying files in a directory. In-Reply-To: <670cc5db0805290205x7e5205fbpfd8b079578c672c7@mail.gmail.com> References: <25264616.1212049060519.JavaMail.root@ps25> <670cc5db0805290205x7e5205fbpfd8b079578c672c7@mail.gmail.com> Message-ID: <1c2a2c590805290327g3ba277fet27cb7f2450b60a1a@mail.gmail.com> On Thu, May 29, 2008 at 5:05 AM, Chester wrote: > please correct this > from BeautifulSoup import BeautifulSoup > to be > from BeautifulSoup import BeautifulStoneSoup Why? BSS is for parsing XML. Kent From bgailer at gmail.com Thu May 29 13:51:57 2008 From: bgailer at gmail.com (bob gailer) Date: Thu, 29 May 2008 07:51:57 -0400 Subject: [Tutor] why? In-Reply-To: <6be1291e0805290101m3bfd88car65c1b68f71de766@mail.gmail.com> References: <6be1291e0805281743l2b82818dg955173d95b1f25ac@mail.gmail.com> <1c2a2c590805281858l227fcefbs6b0449432f2daa31@mail.gmail.com> <6be1291e0805290101m3bfd88car65c1b68f71de766@mail.gmail.com> Message-ID: <483E98DD.7030408@gmail.com> Did you see my comments and questions? Please fix the spelling error (iscube vs isCube). And tell us what results you are expecting, and what results you are getting. Nunbers rather than "wrong"! Otherwise we can't help -- Bob Gailer 919-636-4239 Chapel Hill, NC From kent37 at tds.net Thu May 29 14:27:31 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 29 May 2008 08:27:31 -0400 Subject: [Tutor] why? In-Reply-To: <1c2a2c590805290315r3698cbckaf5314458eca83@mail.gmail.com> References: <6be1291e0805281743l2b82818dg955173d95b1f25ac@mail.gmail.com> <1c2a2c590805290315r3698cbckaf5314458eca83@mail.gmail.com> Message-ID: <1c2a2c590805290527v47787034q716fcc8fdc7d39de@mail.gmail.com> On Thu, May 29, 2008 at 6:15 AM, Kent Johnson wrote: > if int(round(cubed_root)) ** 3 == n > so the cube is done with integer arithmetic instead of floating point. Compare: In [1]: 550919 ** 3 Out[1]: 167210386801801559L In [2]: 550919.0 ** 3 Out[2]: 1.6721038680180157e+017 The cubes you are working with are too large to be represented accurately with floating point numbers. Kent From qsqgeekyogdty at tiscali.co.uk Thu May 29 14:42:36 2008 From: qsqgeekyogdty at tiscali.co.uk (qsqgeekyogdty at tiscali.co.uk) Date: Thu, 29 May 2008 13:42:36 +0100 (GMT+01:00) Subject: [Tutor] Modifying files in a directory. Message-ID: <1142742.1212064956391.JavaMail.root@ps34.mc.tiscali.sys> Hi Yes I did notice I don't pass anything in the upDateTable ;) My problem is having to understand how to actually do this recursively On the command line seems simple and I get: >>> from BeautifulSoup import BeautifulSoup >>> path = '/home/david/test/stack.html' >>> path '/home/david/test/stack.html' >>> html = open(path, 'r') >>> html >>> soup = BeautifulSoup(html) >>> ord_tbl_price = soup.find('td', {'class': 'order_tbl_price'}) >>> ord_tbl_price From $32.66 >>> So now, how do I reduce the price by 15% and write it back to the document? Thanks David ________________________ Guard against online ID theft - http://www.tiscali.co.uk/spyguard From ptmcg at austin.rr.com Thu May 29 16:03:21 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Thu, 29 May 2008 09:03:21 -0500 Subject: [Tutor] why? In-Reply-To: References: Message-ID: <00a901c8c194$c16d1050$6500a8c0@AWA2> Here is a solution for your problem that will compute the values up to (5000,5000) in about 16 seconds: upperlimit = 5000 cube = {} for i in xrange(1,upperlimit): cube[i] = i*i*i cubes = set(cube.itervalues()) for i in xrange(upperlimit, int(upperlimit*1.26)): cubes.add(i*i*i) pairs = [(i,j) for i in range(1, upperlimit) for j in range(i, upperlimit) if cube[i] + cube[j] + 1 in cubes] for i,j in pairs: print i, j, print int(round((cube[i] + cube[j] + 1) ** (0.33333333333))), print cube[i] + cube[j] + 1 This program prints: 6 8 9 729 71 138 144 2985984 135 138 172 5088448 236 1207 1210 1771561000 242 720 729 387420489 372 426 505 128787625 426 486 577 192100033 566 823 904 738763264 575 2292 2304 12230590464 791 812 1010 1030301000 1938 2820 3097 29704593673 2676 3230 3753 52861038777 Since this smacks of homework, I'm guessing that your teacher will notice a number of non-beginner Python techniques, and may suspect that you didn't write this yourself. Here are some suggestions on how to change this program, or at least understand it better so you can pass it off as your own: 1. Convert the list comprehension calculation of pairs back into a nested for loop. 2. Explain why I used xrange instead of range. 3. Explain the purpose of the variables cube and cubes. 4. Explain why I computed the set of cubes up to upperlimit*1.26 (this was not a number I just picked out of the air). 5. If this takes 16 seconds to run on my computer with an upperlimit of 5000, estimate how long this will it take to run up to your original upperlimit of 10000000. -- Paul From srilyk at gmail.com Thu May 29 17:46:23 2008 From: srilyk at gmail.com (W W) Date: Thu, 29 May 2008 10:46:23 -0500 Subject: [Tutor] Best way to store space locations? Message-ID: <333efb450805290846hccd410dpd7bbe2f28d289ad@mail.gmail.com> For kicks and giggles/exercise, I'm creating a program that will decrypt a simple cypher (i.e. cesar cypher/rot13, or a=1, b=2, c=3), right now I've got my letter count, but I foresee a slight issue: dealing with spaces. For instance: "The quick brown fox jumps over the lazy dog" will give this data: (encoded as rot13) Gur dhvpx oebja sbk whzcf bire gur ynml qbt [(8, ' '), (4, 'b'), (3, 'r'), (2, 'u'), (2, 'h'), (2, 'g'), (2, 'e'), (1, 'z'), (1, 'y'), (1, 'x'), (1, 'w'), (1, 'v'), (1, 't'), (1, 's'), (1, 'q'), (1, 'p'), (1, 'o'), (1, 'n'), (1, 'm'), (1, 'l'), (1, 'k'), (1, 'j'), (1, 'i'), (1, 'f'), (1, 'd'), (1, 'c'), (1, 'a')] The specific part I'm looking at is the location of spaces... what would be the best way to keep the distribution? I have a few options that I know of: 1) Store the locations of spaces in a list or a tuple in the dictionary. This seems horribly complex and perhaps slow(ish)? 2) When the program figures out the most likely key, I could have it reiterate over the original string, replacing letters. This also seems like it would be slow... actually, now that I think of it, perhaps this is the best method? Once the program creates the dictionary to convert values, I could have it loop something similar to this: for letter in mystring: if letter = ' ': newstring += letter else: newstring += cypher_key(letter) Would that be the optimal conversion? TIA, Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi From alan.gauld at btinternet.com Thu May 29 19:13:22 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 29 May 2008 18:13:22 +0100 Subject: [Tutor] 'Right' way to implement mixins in Python? References: <1212007297.17536.12.camel@marley> <1c2a2c590805281711x598f4045y30fc55689c52f12@mail.gmail.com> Message-ID: "Kent Johnson" wrote >> Mixins should be as independant >> as possible from any other classes. Unfortunately thats not >> always possible so you should try to create an abstract >> superclass/interface and use that in your mixins. You can then >> subclass the mixin and replace the abstract class with the local >> concrete manifestation. It means one extra level of inheritance >> because >> you wind up with an abstract mixin plus the localised mixin. > > I don't understand what you mean by this. Umm, no not my clearest prose ever is it! :-) I'll try to rephrase it later, unfortunately I'm serving on a jury this week so reading tutor is evenings only... and I'm going out tonight! Alahn G. From srilyk at gmail.com Thu May 29 19:35:19 2008 From: srilyk at gmail.com (W W) Date: Thu, 29 May 2008 12:35:19 -0500 Subject: [Tutor] Stripping punctuation Message-ID: <333efb450805291035g500ad85fr8bfc146f366854bd@mail.gmail.com> Is there a faster way to strip punctuation from a string than this? from string import ascii_letters def strip_punctuation(mystring): newstring = '' for x in mystring: if x in ascii_letters: newstring += x else: pass return newstring In my decryption program I realized I need to strip all the punctuation, and that's the first thing I came up with. I couldn't find a built-in function in the time it took to roll my own. TIA, Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi From kent37 at tds.net Thu May 29 19:59:21 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 29 May 2008 13:59:21 -0400 Subject: [Tutor] Stripping punctuation In-Reply-To: <333efb450805291035g500ad85fr8bfc146f366854bd@mail.gmail.com> References: <333efb450805291035g500ad85fr8bfc146f366854bd@mail.gmail.com> Message-ID: <1c2a2c590805291059l6132af3ao38f683d3a957fcce@mail.gmail.com> On Thu, May 29, 2008 at 1:35 PM, W W wrote: > Is there a faster way to strip punctuation from a string than this? def strip_punctuation(my_string): return ''.join(c for c in my_string if c in ascii_letters) or use str.translate(): http://docs.python.org/lib/string-methods.html#l2h-268 Kent From clajo04 at mac.com Thu May 29 20:45:53 2008 From: clajo04 at mac.com (John Clark) Date: Thu, 29 May 2008 14:45:53 -0400 Subject: [Tutor] NYC Python User Group Meeting Announcement.... Message-ID: <00b601c8c1bc$3a6a0c20$af3e2460$@com> Greetings! The next New York City Python Users Group meeting is planned for June 17th, 6:30pm at Daylife Inc. at 444 Broadway (between Howard St. and Grand St.) on the 5th Floor. We welcome all those in the NYC area who are interested in Python to attend. More information can be found on the users group wiki page: http://www.nycpython.org Hope to see you there! -John Clark From chombee at nerdshack.com Thu May 29 22:57:18 2008 From: chombee at nerdshack.com (chombee) Date: Thu, 29 May 2008 21:57:18 +0100 Subject: [Tutor] 'Right' way to implement mixins in Python? In-Reply-To: References: <1212007297.17536.12.camel@marley> Message-ID: <1212094638.15939.5.camel@tig> On Wed, 2008-05-28 at 23:30 +0100, Alan Gauld wrote: > > The lessons I learned are that, when implementing mixins using > > multiple > > inheritance: > > > > * Mixin classes should not derive from any base class (except > > object) > > * But they may assume that the classes they will be mixed in with do > > derive from a certain base class, so they may assume the base class > > is > > there. > > Yes to both, regardless of language. As I said above you can make the > mixins slightly more generally reusable by creating abstact mixins > with explicit dependancy on an abstact interface. But better still is > to > avoid dependencies as much as possible where mixins are concerned. > Instead build a protocol in the class framework outside the mixins > and let them coerce the dependencies to suit the mixin interfaces. Yeah I'd like to see how this dependency on an abstract interface is implemented in Python also. The way I implemented my mixins, as I said, the mixins did not inherit from anything but they assume that a certain base class will be in the inheritance of any class they are mixed in to, I just explained this in the module docstring. But it's less than ideal. Even straight after writing that docstring, I started a new module and started writing classes that used the mixins, and immediately forgot to inherit from the base class that the mixins expect. I suppose I could get the __init__ methods of the mixins to look for the base class and complain if it's not there. What I tried to do in the first place when the mixins themselves actually inherited their common base class was better, because classes using the mixins didn't need to remember to inherit that class themselves, but that ran into all sorts of implementation problems as I've explained. Depending on an abstract interface might be better but I'm not sure how it would work. From ross at ross.mayfirst.org Thu May 29 23:17:23 2008 From: ross at ross.mayfirst.org (Ross Glover) Date: Thu, 29 May 2008 17:17:23 -0400 Subject: [Tutor] Working Script...but! Message-ID: <483F1D63.4080108@ross.mayfirst.org> Hi all, I've worked out this script to do what I want generally. However, I'm pretty sure that even though it works, I haven't utilized the advantages of python. This is more or less my first program. What I would like to know is what parts of this script you think could or should be functions in their own right. Also, I'm trying to figure out if I should be creating this as a class. I know that I still need to create some exception handling and stuff, but I want to get these functions as well articulated as possible. I hope it's okay that I submitted this much script. Thanks for any suggestions, Ross #!/usr/bin/env python # Filename: read_tags.py import os import re file_name = raw_input("Name of file to read: ") read_path = "/home/ross/Desktop/%s.txt" % file_name read_file = file(read_path, "r") search_file = read_file.read() def write_file(string_to_write): '''This function writes a string to a specified file using append and taking data from the string given it.''' if string_to_write != []: write_to_filename = raw_input("Name of file to write: ") path_input = raw_input("Path to file: ") if path_input == "": default_path = "/home/ross/Desktop/" write_to_path = default_path + "%s.txt" % write_to_filename write_to_file = file(write_to_path, "a") for items in string_to_write: write_to_file.write(items + '\n') continue print "File %s written!" % path_input else: write_to_path = path_input+ "%s" % write_to_filename write_to_file = file(write_to_path, "a") for items in string_to_write: write_to_file.write(items + '\n') print "File %s written!" % write_to_path else: print "There is nothing to write." def search_text(): if search_file != False: tag_to_search = raw_input("Name the theme: ") rawstr = "(?<=).*(?=<%s>)|(?<=).*[\\n]+[\S\s[<%s>]+?]*(?=<%s>)" % (tag_to_search, tag_to_search, tag_to_search, tag_to_search, tag_to_search) search_result = re.findall(rawstr, search_file) write_file(search_result) #print search_result return search_result else: print "File is empty!" -- If you know what you're doing, you must not be 'doing' a dissertation. From ulrichhzn at gmail.com Thu May 29 23:21:12 2008 From: ulrichhzn at gmail.com (Ulrich) Date: Thu, 29 May 2008 23:21:12 +0200 Subject: [Tutor] slope(x1, y1, x2, y2)??? Message-ID: <1212096072.10765.2.camel@atom> Hello again all and sorry for the bother but I'm having a bit of trouble here. Still busy with the "How to Think Like a Computer Scientist" book and am at chapter 5 busy with unit testing. I'm having problems with the exercise #3 on http://openbookproject.net//thinkCSpy/ch05.xhtml#auto9 . I have absolutely no clue how to get all my values to return "OK" in the unit test. Any help would be appreciated, I do not want to continue the courses if I don't understand something. Thanks! From kent37 at tds.net Thu May 29 23:29:45 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 29 May 2008 17:29:45 -0400 Subject: [Tutor] 'Right' way to implement mixins in Python? In-Reply-To: <1212094638.15939.5.camel@tig> References: <1212007297.17536.12.camel@marley> <1212094638.15939.5.camel@tig> Message-ID: <1c2a2c590805291429j670d9c4dqc51398edbf9e531f@mail.gmail.com> On Thu, May 29, 2008 at 4:57 PM, chombee wrote: > Yeah I'd like to see how this dependency on an abstract interface is > implemented in Python also. Python doesn't really have a concept of abstract interface, it uses duck typing instead. > I suppose I could get the __init__ methods of the mixins to look for the > base class and complain if it's not there. I think you could just put assert isinstance(self, RequiredBaseClass), "Missing required base class" in the mixin's __init__() method. Kent From alan.gauld at btinternet.com Fri May 30 01:27:50 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 30 May 2008 00:27:50 +0100 Subject: [Tutor] Stripping punctuation References: <333efb450805291035g500ad85fr8bfc146f366854bd@mail.gmail.com> Message-ID: "W W" wrote > Is there a faster way to strip punctuation from a string than this? Yes > from string import ascii_letters > > def strip_punctuation(mystring): > newstring = '' > for x in mystring: > if x in ascii_letters: > newstring += x This is very slow since it creates a new string with each addition, it doesn't just append a character at the end as you might think! It would be faster to add the chars to a list then use string join() at the end. But see below... > else: > pass The else/pass is redundant you could remove it. However, it's much easier to do a replacement operation and especially using a regex of all the non ascii characters - or whatever you define to be punctuation... That way you can do a single operation on the entire string which will all be coded in optimised C rather than clunking through, letter by letter in Python. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Fri May 30 01:40:15 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 30 May 2008 00:40:15 +0100 Subject: [Tutor] 'Right' way to implement mixins in Python? References: <1212007297.17536.12.camel@marley> <1c2a2c590805281711x598f4045y30fc55689c52f12@mail.gmail.com> Message-ID: "Alan Gauld" wrote > "Kent Johnson" wrote >>> Mixins should be as independant... >> I don't understand what you mean by this. OK, I'll try to rephrase what I said last time. But its gone midnight so it will be brief... Basically all I meant was that rather than making the mixin inherit from some specific problem-domain superclass it would be better to extract out the dependency interface into a separate asbstract class, C say, (ie one not intended to be instantiated) which can be packaged with the mixins and therefore enhance reuse across projects. In the specific project using the mixins there is still a need to pass in a project specific subclass (or in Python C-like) object which can be done either by inheriting from C - which reverses the dependency - or by simply using a C-like set of operations. By moving the dependency from an ingheritance relationship to a delegation rtelationship based on a parameterised class (at the init level) we provide a mechanism whereby multiple projects can reuse the mixin while putting the onus on sublassing within the project rather than within the mixin. This works on the theory that project specific code is much less likely to be generic than mixin code. So instead of class MyMixin(ProjectSpecificSuperclass): pass we move to class C(object): # define interface here class MyMixin(object): def __init__(self,c = C) def someMethod(self): #uses self.c here Now using projects can either subclass C and pass that into the Mixin constructor or just create C-like classes and pass those in. I hope thats at least slightly clearer! It wasn't intended to be profound, it was just badly expressed! -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Fri May 30 01:42:57 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 29 May 2008 19:42:57 -0400 Subject: [Tutor] slope(x1, y1, x2, y2)??? In-Reply-To: <1212096072.10765.2.camel@atom> References: <1212096072.10765.2.camel@atom> Message-ID: <1c2a2c590805291642i39ec332fm3866f011aeab4944@mail.gmail.com> On Thu, May 29, 2008 at 5:21 PM, Ulrich wrote: > I'm having problems with the exercise #3 on > http://openbookproject.net//thinkCSpy/ch05.xhtml#auto9 . I have > absolutely no clue how to get all my values to return "OK" in the unit > test. What are you having trouble with? Is it the geometry? This might help: http://en.wikipedia.org/wiki/Slope You will have to convert the arguments to floats to get some of the answers right. Kent From mwalsh at groktech.org Fri May 30 04:06:26 2008 From: mwalsh at groktech.org (Martin Walsh) Date: Thu, 29 May 2008 21:06:26 -0500 Subject: [Tutor] Modifying files in a directory. In-Reply-To: <1142742.1212064956391.JavaMail.root@ps34.mc.tiscali.sys> References: <1142742.1212064956391.JavaMail.root@ps34.mc.tiscali.sys> Message-ID: <483F6122.80005@groktech.org> qsqgeekyogdty at tiscali.co.uk wrote: >.>> soup = BeautifulSoup(html) >.>> ord_tbl_price = soup.find('td', {'class': 'order_tbl_price'}) >.>> ord_tbl_price > $32.66 > > So now, how do I reduce the price by 15% and write it back to the > document? Not sure if this is the right way, but it seems to work for me, YMMV: html = """\ From $32.66""" soup = BeautifulSoup(html) otp = soup.find('td', {'class': 'order_tbl_price'}) price = float(otp.contents[1].lstrip(' $')) otp.contents[1].replaceWith('$%0.2f' % (price * 0.85)) print soup.renderContents() """ From$27.76 """ I'll second Kent's suggestion to experiment on the command line, and go one further -- download and install the ipython interpreter[1]. It offers tab-completion of methods and attributes of an object (for example, type yourobject.), easy access to doc-strings with a single ?, the source code (when available) with ??, and much much more[2]. It's a real time saver, even if you don't use the fancier features it beats dir()/help() hands down. [1] http://ipython.scipy.org/moin/ [2] http://ipython.scipy.org/doc/manual/node4.html HTH, Marty From rduenasp at gmail.com Fri May 30 05:26:44 2008 From: rduenasp at gmail.com (=?ISO-8859-1?Q?Ricardo_Due=F1as_Parada?=) Date: Thu, 29 May 2008 22:26:44 -0500 Subject: [Tutor] Running shell command Message-ID: <559102030805292026j1297a89fy77e1e2cdf38fff46@mail.gmail.com> Hello list, I'm new in python, and I have a question about a program I am writing. I want ton make an application that shows me a system variable, and when it changes, but I am having a trouble when I try to run the command. The command is smartctl on the hdd, and it can be only accesed by su. When I run the command os.system in python, obviously he asks me for the password, and the program stops until I wirte it. . Is there any way to write the password from the python script?, or what do you recommend me? Thanks in advance, _Ricardo -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri May 30 09:21:09 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 30 May 2008 08:21:09 +0100 Subject: [Tutor] Running shell command References: <559102030805292026j1297a89fy77e1e2cdf38fff46@mail.gmail.com> Message-ID: "Ricardo Due?as Parada" wrote > When I run the command os.system in python, obviously he asks me for > the > password, and the program stops until I wirte it. . Is there any way > to > write the password from the python script?, or what do you recommend > me? os.system is a very basic way of running a program. You should use the newer subprocess module and the Popen() class. There are examples in the documentation. Also, basic usage is described in my Using the OS topic in my tutorial. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From qsqgeekyogdty at tiscali.co.uk Fri May 30 10:28:27 2008 From: qsqgeekyogdty at tiscali.co.uk (qsqgeekyogdty at tiscali.co.uk) Date: Fri, 30 May 2008 09:28:27 +0100 (GMT+01:00) Subject: [Tutor] Modifying files in a directory. Message-ID: <9855478.1212136107418.JavaMail.root@ps37.mc.tiscali.sys> Hello, Thanks for the replies, I have now installed ipython and will take the time to explore each object further. But I have one more question. On each page I have several From $32.66 each with different price. so, changing the code to use the findAll, returns a list: >>> otp = soup.findAll('td', {'class': 'order_tbl_price'}) >>> otp [From $32.66, $79.99, $39.99, 1 Full Pack - $65.95 ] >>> >>> >>> price = float(otp.contents[1].lstrip(' $')) Traceback (most recent call last): File "", line 1, in AttributeError: 'ResultSet' object has no attribute 'contents' >>> Even if I do a limit=1 as >>> otp = soup.findAll('td', {'class': 'order_tbl_price'}, limit=1) >>> otp [From $32.66] >>> price = float(otp.contents[1].lstrip(' $')) Traceback (most recent call last): File "", line 1, in AttributeError: 'ResultSet' object has no attribute 'contents' then, i thought I would loop through this list: >>> for x in otp: ... print x ... From$23.60 $79.99 $39.99 1 Blister Pack - $65.95 >>> And here I get stuck as to how to modify all the prices? Thanks in advance for any suggestions. David ________________________ Guard against online ID theft - http://www.tiscali.co.uk/spyguard From kent37 at tds.net Fri May 30 13:09:35 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 30 May 2008 07:09:35 -0400 Subject: [Tutor] Modifying files in a directory. In-Reply-To: <9855478.1212136107418.JavaMail.root@ps37.mc.tiscali.sys> References: <9855478.1212136107418.JavaMail.root@ps37.mc.tiscali.sys> Message-ID: <1c2a2c590805300409l1e84e1c5mad112ee702cc4c99@mail.gmail.com> On Fri, May 30, 2008 at 4:28 AM, qsqgeekyogdty at tiscali.co.uk wrote: > then, i thought I would loop through this list: > >>>> for x in otp: > ... print x > ... > >From$23.60 > $79.99 > $39.99 > class="order_table_price_small">1 Blister Pack - $65.95 > >>>> > > And here I get stuck as to how to modify all the prices? Just put the modification code inside the loop. It sounds like you might benefit from working through a basic Python tutorial, they will all cover loops and files. Many are listed here: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers Kent From qsqgeekyogdty at tiscali.co.uk Fri May 30 13:52:40 2008 From: qsqgeekyogdty at tiscali.co.uk (qsqgeekyogdty at tiscali.co.uk) Date: Fri, 30 May 2008 12:52:40 +0100 (GMT+01:00) Subject: [Tutor] Modifying files in a directory. Message-ID: <5052957.1212148360486.JavaMail.root@ps36.mc.tiscali.sys> Yes I do need to learn the basics of programming ;) This was the first I did, was to put the modification code into the loop, but had this error: >>> for x in otp: ... price = float(x.contents[1].lstrip(' $')) ... x.contents[1].replaceWith('$%0.2f' % (price * 0.85)) ... Traceback (most recent call last): File "", line 2, in IndexError: list index out of range Then I was thinking I need to extract the actual 'cell' with the price and then modify it. So looked at using actual_price = re.compile('[0-9]*(\.[0-9]*|$)') to find the text with the price. But then was getting too confused and maybe there is a simpler way, which I cannot see. Thanks David Guard your email - http://www.tiscali.co.uk/products/securemail/ ____________________________________________________ From kent37 at tds.net Fri May 30 14:43:35 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 30 May 2008 08:43:35 -0400 Subject: [Tutor] Modifying files in a directory. In-Reply-To: <5052957.1212148360486.JavaMail.root@ps36.mc.tiscali.sys> References: <5052957.1212148360486.JavaMail.root@ps36.mc.tiscali.sys> Message-ID: <1c2a2c590805300543h71fa8ba1nbfcc3f6025cdb0d6@mail.gmail.com> On Fri, May 30, 2008 at 7:52 AM, qsqgeekyogdty at tiscali.co.uk wrote: > Yes I do need to learn the basics of programming ;) > > This was the first I did, was to put the modification code into the > loop, but had this error: > >>>> for x in otp: > ... price = float(x.contents[1].lstrip(' $')) > ... x.contents[1].replaceWith('$%0.2f' % (price * 0.85)) > ... > Traceback (most recent call last): > File "", line 2, in > IndexError: list index out of range Your cells do not have the same structure, some have no , some have a before the price, the price may be inside a or not...you will have to write your program to deal with this variation. I guess your loop failed on the first that doesn't have a . If you print x in the loop that would help you figure out which one is the problem. Kent From lupin at orcon.net.nz Fri May 30 15:36:53 2008 From: lupin at orcon.net.nz (Brett Wilkins) Date: Sat, 31 May 2008 01:36:53 +1200 Subject: [Tutor] Running shell command In-Reply-To: References: <559102030805292026j1297a89fy77e1e2cdf38fff46@mail.gmail.com> Message-ID: Just as a side point, wouldn't the easiest way be to run the script under sudo? It's safer imho than putting the sudo password in programmatically... Cheers --Brett On 30/05/2008, at 7:21 PM, Alan Gauld wrote: > "Ricardo Due?as Parada" wrote > >> When I run the command os.system in python, obviously he asks me >> for the >> password, and the program stops until I wirte it. . Is there any >> way to >> write the password from the python script?, or what do you >> recommend me? > > os.system is a very basic way of running a program. > > You should use the newer subprocess module and the Popen() class. > There are examples in the documentation. > > Also, basic usage is described in my Using the OS topic in my > tutorial. > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From qsqgeekyogdty at tiscali.co.uk Fri May 30 15:46:44 2008 From: qsqgeekyogdty at tiscali.co.uk (qsqgeekyogdty at tiscali.co.uk) Date: Fri, 30 May 2008 14:46:44 +0100 (GMT+01:00) Subject: [Tutor] Modifying files in a directory. Message-ID: <24626822.1212155204522.JavaMail.root@ps29> OK I see, >>> for x in otp: ... print x ... From$23.60 $79.99 $39.99 1 Blister Pack - $65.95 So I will need to use the Remove elements in my code. Thanks for all your help. David Guard your email - http://www.tiscali.co.uk/products/securemail/ ____________________________________________________ From alan.gauld at btinternet.com Fri May 30 19:30:37 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 30 May 2008 18:30:37 +0100 Subject: [Tutor] Running shell command References: <559102030805292026j1297a89fy77e1e2cdf38fff46@mail.gmail.com> Message-ID: "Brett Wilkins" wrote > Just as a side point, wouldn't the easiest way be to run the script > under sudo? > It's safer imho than putting the sudo password in > programmatically... Yes, but he is (presumably) already using sudo within os.system. He wants to avoid putting in the password so he must take the security risks associated with that approach. Caveat emptor as they say! Alan G From rduenasp at gmail.com Fri May 30 19:52:27 2008 From: rduenasp at gmail.com (=?ISO-8859-1?Q?Ricardo_Due=F1as_Parada?=) Date: Fri, 30 May 2008 12:52:27 -0500 Subject: [Tutor] Running shell command In-Reply-To: References: <559102030805292026j1297a89fy77e1e2cdf38fff46@mail.gmail.com> Message-ID: <559102030805301052p10df7458r724f8e810b3c8e3a@mail.gmail.com> Thanks for your answers. How can I make that action more secure? Is there any way for running the program from a regular user (non su) without having the password within the code? _Ricardo 2008/5/30 Alan Gauld : > > "Brett Wilkins" wrote > >> Just as a side point, wouldn't the easiest way be to run the script under >> sudo? >> It's safer imho than putting the sudo password in programmatically... >> > > Yes, but he is (presumably) already using sudo within os.system. > He wants to avoid putting in the password so he must take the > security risks associated with that approach. > > Caveat emptor as they say! > > Alan G > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From teresav at vtnnv.com Fri May 30 18:54:50 2008 From: teresav at vtnnv.com (Teresa Von Hazmburg) Date: Fri, 30 May 2008 09:54:50 -0700 Subject: [Tutor] Error in executing: cmd. Message-ID: <200805301654.m4UGsn7G021746@johnny5.vtnnv.com> Hello, I am new to programming. I have a shapefile of county parcel data containing over 600,000 polygons. Using python, I am trying to query the shapefile and write the results out to separate shapefiles. I put a print command so I can watch the procedure. I execute the script and watch what is printed to the screen. Everything looks ok and then I leave the office and let the process run over night. But I come back in the morning to find this error message: Executing (Script14_1): Script14 Start Time: Thu May 29 16:39:32 2008 Running script Script14... Error in script Script14. Error in executing: cmd.exe /C N:\VTN\AI9\Scripts\python\RNZ9ET~K.PY "#" Failed to execute (Script14_1). End Time: Thu May 29 20:23:41 2008 (Elapsed Time: 3 hours 44 minutes 9 seconds Can anyone tell me what is wrong? Thank you. 2727 S. Rainbow Blvd. Las Vegas, NV 89146-5148 Phone: (702) 253-2434 Fax: (702) 362-2597 Web: vtnnv.com -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: image/jpeg Size: 1821 bytes Desc: not available URL: From srilyk at gmail.com Fri May 30 20:06:19 2008 From: srilyk at gmail.com (W W) Date: Fri, 30 May 2008 13:06:19 -0500 Subject: [Tutor] Fwd: Running shell command In-Reply-To: <333efb450805301105o56a61f1dq4a78a69034fcd4c@mail.gmail.com> References: <559102030805292026j1297a89fy77e1e2cdf38fff46@mail.gmail.com> <559102030805301052p10df7458r724f8e810b3c8e3a@mail.gmail.com> <333efb450805301105o56a61f1dq4a78a69034fcd4c@mail.gmail.com> Message-ID: <333efb450805301106g19e95cbfp2a5aff13870a016e@mail.gmail.com> Curse my forgetting to reply to all! ---------- Forwarded message ---------- From: W W Date: Fri, May 30, 2008 at 1:05 PM Subject: Re: [Tutor] Running shell command To: Ricardo Due?as Parada On Fri, May 30, 2008 at 12:52 PM, Ricardo Due?as Parada wrote: > Thanks for your answers. > > How can I make that action more secure? Is there any way for running > the program from a regular user (non su) without having the password > within the code? > > _Ricardo What type of system are you running? Ubuntu? Suse? Redhat? Or some Unix variety? Most *nix variants have a sudo, which allows non-root users to run commands as another user, most often a super-user (su). Assuming you have root access, you could easily set up a specific user account that has access to the smartctl command and nothing else (above that of a regular user), which would basically allow for a more secure method of running the script. google sudo or sudoers, or type "man sudo" or "man sudoers" at the command line for more help. HTH, Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi From srilyk at gmail.com Fri May 30 20:11:36 2008 From: srilyk at gmail.com (W W) Date: Fri, 30 May 2008 13:11:36 -0500 Subject: [Tutor] Error in executing: cmd. In-Reply-To: <200805301654.m4UGsn7G021746@johnny5.vtnnv.com> References: <200805301654.m4UGsn7G021746@johnny5.vtnnv.com> Message-ID: <333efb450805301111q5c31acccj6ce817ccde0aeabc@mail.gmail.com> I'm not certain, but it appears the file RNZ9ET~K.PY may not exist, or access is in some other way restricted. It's obviously running for a long time, about 3.75 hours. Is the RNZ*.PY file in some way generated by your original script? -Wayne On Fri, May 30, 2008 at 11:54 AM, Teresa Von Hazmburg wrote: > Hello, > > > > I am new to programming. > > I have a shapefile of county parcel data containing over 600,000 polygons. > > Using python, I am trying to query the shapefile and write the results out > > to separate shapefiles. > > I put a print command so I can watch the procedure. > > I execute the script and watch what is printed to the screen. > > Everything looks ok and then I leave the office and let the process run over > night. > > But I come back in the morning to find this error message: > > > > Executing (Script14_1): Script14 > > Start Time: Thu May 29 16:39:32 2008 > > Running script Script14... > > Error in script Script14. > > Error in executing: cmd.exe /C N:\VTN\AI9\Scripts\python\RNZ9ET~K.PY "#" > > > > Failed to execute (Script14_1). > > End Time: Thu May 29 20:23:41 2008 (Elapsed Time: 3 hours 44 minutes 9 > seconds > > > > Can anyone tell me what is wrong? > > > > Thank you. > > > > 2727 S. Rainbow Blvd. > > Las Vegas, NV 89146-5148 > > Phone: (702) 253-2434 > > Fax: (702) 362-2597 > > Web: vtnnv.com > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi From rduenasp at gmail.com Fri May 30 20:13:07 2008 From: rduenasp at gmail.com (=?ISO-8859-1?Q?Ricardo_Due=F1as_Parada?=) Date: Fri, 30 May 2008 13:13:07 -0500 Subject: [Tutor] Fwd: Running shell command In-Reply-To: <333efb450805301106g19e95cbfp2a5aff13870a016e@mail.gmail.com> References: <559102030805292026j1297a89fy77e1e2cdf38fff46@mail.gmail.com> <559102030805301052p10df7458r724f8e810b3c8e3a@mail.gmail.com> <333efb450805301105o56a61f1dq4a78a69034fcd4c@mail.gmail.com> <333efb450805301106g19e95cbfp2a5aff13870a016e@mail.gmail.com> Message-ID: <559102030805301113y33f1958cj9a818c3f14520e88@mail.gmail.com> I?m running Fedora 8, in this case the command is su -c 'command'. I also think it's better to allow a specific user to use smartctl. I will do that. Thank?s, it was really helpfull. _Ricardo 2008/5/30 W W : > Curse my forgetting to reply to all! > > ---------- Forwarded message ---------- > From: W W > Date: Fri, May 30, 2008 at 1:05 PM > Subject: Re: [Tutor] Running shell command > To: Ricardo Due?as Parada > > > On Fri, May 30, 2008 at 12:52 PM, Ricardo Due?as Parada > wrote: > > Thanks for your answers. > > > > How can I make that action more secure? Is there any way for running > > the program from a regular user (non su) without having the password > > within the code? > > > > _Ricardo > > What type of system are you running? Ubuntu? Suse? Redhat? Or some Unix > variety? > > Most *nix variants have a sudo, which allows non-root users to run > commands as another user, most often a super-user (su). > > Assuming you have root access, you could easily set up a specific user > account that has access to the smartctl command and nothing else > (above that of a regular user), which would basically allow for a more > secure method of running the script. > > google sudo or sudoers, or type "man sudo" or "man sudoers" at the > command line for more help. > > HTH, > Wayne > > > > -- > To be considered stupid and to be told so is more painful than being > called gluttonous, mendacious, violent, lascivious, lazy, cowardly: > every weakness, every vice, has found its defenders, its rhetoric, its > ennoblement and exaltation, but stupidity hasn't. - Primo Levi > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Fri May 30 20:27:27 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 30 May 2008 14:27:27 -0400 Subject: [Tutor] Error in executing: cmd. In-Reply-To: <200805301654.m4UGsn7G021746@johnny5.vtnnv.com> References: <200805301654.m4UGsn7G021746@johnny5.vtnnv.com> Message-ID: <1c2a2c590805301127h683ebc80y8a053dea25dad4b3@mail.gmail.com> On Fri, May 30, 2008 at 12:54 PM, Teresa Von Hazmburg wrote: > Can anyone tell me what is wrong? You haven't given us much to work with. Can you show us the script? Is RNZ9ET~K.PY the script you are running, or do you call it from your script? If it is something you are callling, can you run the failing command on the command line? Kent From kent37 at tds.net Fri May 30 21:24:03 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 30 May 2008 15:24:03 -0400 Subject: [Tutor] Error in executing: cmd. In-Reply-To: <200805301834.m4UIYMui013371@johnny5.vtnnv.com> References: <1c2a2c590805301127h683ebc80y8a053dea25dad4b3@mail.gmail.com> <200805301834.m4UIYMui013371@johnny5.vtnnv.com> Message-ID: <1c2a2c590805301224v5b56437ds8496468fe5579b6d@mail.gmail.com> On Fri, May 30, 2008 at 2:34 PM, Teresa Von Hazmburg wrote: > Hello and thank you for replying. > > As I mentioned I am new to python but I am also new this website/service. Welcome! > I guess I am not following protocol/etiquette with regards to requesting > service. Well, the more details you can give about the problem, the more likely we are to be able to help. That's not specific to this list. > Here are more details about my problem: > > > > I am using Windows XP, and intel processor. > > > > The python script I am running (see attached file) is accessing ArcGIS (the > GIS software from ESRI). I didn't get an attachment... > > > > I expect the process to take more than 3 hours because I need to process by > querying the entire shapefile of over 600,000 polygons into smaller > shapefiles. > > > > The script I am running does not call any other script so I did not > understand why it should even be looking for a script named RNZ9ET~K.PY OK. I don't know either! Kent PS Please use Reply All to reply to the list. > > > > The problem may not be with python but with the software I am trying to > access with python. I thought I would try your tutoring service first and > then I will contact the software developers. From teresav at vtnnv.com Fri May 30 22:14:06 2008 From: teresav at vtnnv.com (Teresa Von Hazmburg) Date: Fri, 30 May 2008 13:14:06 -0700 Subject: [Tutor] Error in executing: cmd. In-Reply-To: <1c2a2c590805301224v5b56437ds8496468fe5579b6d@mail.gmail.com> Message-ID: <200805302014.m4UKE5Qu003260@johnny5.vtnnv.com> Here are the files I was referring to in my last email Thank you all for your patience. -----Original Message----- From: kent3737 at gmail.com [mailto:kent3737 at gmail.com] On Behalf Of Kent Johnson Sent: Friday, May 30, 2008 12:24 PM To: Teresa Von Hazmburg Cc: Python Tutor List Subject: Re: [Tutor] Error in executing: cmd. On Fri, May 30, 2008 at 2:34 PM, Teresa Von Hazmburg wrote: > Hello and thank you for replying. > > As I mentioned I am new to python but I am also new this website/service. Welcome! > I guess I am not following protocol/etiquette with regards to requesting > service. Well, the more details you can give about the problem, the more likely we are to be able to help. That's not specific to this list. > Here are more details about my problem: > > > > I am using Windows XP, and intel processor. > > > > The python script I am running (see attached file) is accessing ArcGIS (the > GIS software from ESRI). I didn't get an attachment... > > > > I expect the process to take more than 3 hours because I need to process by > querying the entire shapefile of over 600,000 polygons into smaller > shapefiles. > > > > The script I am running does not call any other script so I did not > understand why it should even be looking for a script named RNZ9ET~K.PY OK. I don't know either! Kent PS Please use Reply All to reply to the list. > > > > The problem may not be with python but with the software I am trying to > access with python. I thought I would try your tutoring service first and > then I will contact the software developers. -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: read_libpcl2sections.py URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: parcel2.txt URL: From alan.gauld at btinternet.com Sat May 31 02:24:09 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 31 May 2008 01:24:09 +0100 Subject: [Tutor] Error in executing: cmd. References: <1c2a2c590805301224v5b56437ds8496468fe5579b6d@mail.gmail.com> <200805302014.m4UKE5Qu003260@johnny5.vtnnv.com> Message-ID: "Teresa Von Hazmburg" wrote > Here are the files I was referring to in my last email I don't really know the cause of your specific error but here are some comments that will tidy the code somewhat and might change the behaviour too. ######################### #Open/read textfile file = open (myfile, "r") Best to avoid using file as a variable name sionce its a built in name that is an alias for open. Using it as variable will likely confuse things for readers. file.seek(0) No need for the seek() here, you are already at the beginning, remove it. print file.readlines() file.seek(0) readlist = file.readlines() #print readlist file.seek(0) Reverse the order to store the value first then print the value That will save 2 more seek() calls. #listlength = len(readlist) #bksec_list = [] for line in file.readlines(): But in fact you didn't even need those readlines at all. Here you can just iterate over te file: for line in file: print "book = " + line[0:3] + " and section = " + line[3:5] book = line[0:3] section = line[3:5] Again if you do the assignments first then the print you avoid repeating the slice action. and avoid a maintenance problem since you can just print the actual variable values. bksecFolder = gismoFolder + "d" + book + "\\d" + book + section bkFolder = gismoFolder + "d" + book Again do the assignmment first then use it in the bksecFolder assignment. In other words reverse the order and use the variable. You can probably speed it up even more by using string formatting rather than addition which tends to be fairly slow in Python. out_shp = bksecFolder + "\\parcel_p.shp" strSel = "\"PARCEL\" LIKE '" + book + section + "%'" I would consider printing the strSel value since that is what you feed to Select_Analysis which appears to be the thing that does the work. This is the most likely source of errors! #print "querying section " + book + "-" + section #print out_shp gp.Select_analysis(in_parcel_shp, out_shp, strSel) print "Process finished" # added to allow inspection of screen print "PROCESS COMPLETE" Only one print needed. choice = raw_input('Type q to end :') # if choice == 'q' : # print ' ' The last if statement is redundant, lose it. Those changes will trim the code, make it easier to read and faster to execute. And will show us what the selection string actually looks like. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From bryan.fodness at gmail.com Sat May 31 21:43:17 2008 From: bryan.fodness at gmail.com (Bryan Fodness) Date: Sat, 31 May 2008 15:43:17 -0400 Subject: [Tutor] reading a string into an array Message-ID: I am trying to read a long string of values separated by a backslash into an array of known size. Here is my attempt, from numpy import * ay, ax = 384, 512 a = zeros([ay, ax]) for line in open('out.out'): data = line.split('\\') k = 0 for i in range(ay): for j in range(ax): a[i, j] = data[k] k+=1 but, I receive the following error. Traceback (most recent call last): File "C:/Users/bryan/Desktop/dose_array.py", line 13, in a[i, j] = data[k] ValueError: setting an array element with a sequence. -- "The game of science can accurately be described as a never-ending insult to human intelligence." - Jo?o Magueijo -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Sat May 31 23:11:21 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 31 May 2008 17:11:21 -0400 Subject: [Tutor] reading a string into an array In-Reply-To: References: Message-ID: <1c2a2c590805311411i18d85bd4ka76a53bed8663f0c@mail.gmail.com> On Sat, May 31, 2008 at 3:43 PM, Bryan Fodness wrote: > I am trying to read a long string of values separated by a backslash into an > array of known size. > > Here is my attempt, > > from numpy import * > ay, ax = 384, 512 > a = zeros([ay, ax]) > for line in open('out.out'): > data = line.split('\\') Are you trying to accumulate all the lines into data? If so you should use data = [] for line in open('out.out'): data.extend(line.split('\\')) > k = 0 > for i in range(ay): > for j in range(ax): > a[i, j] = data[k] > k+=1 > but, I receive the following error. > > Traceback (most recent call last): > File "C:/Users/bryan/Desktop/dose_array.py", line 13, in > a[i, j] = data[k] > ValueError: setting an array element with a sequence. I think this is because data is a list of strings, not numbers. Change my line above to data.extend(int(i) for i in line.split('\\')) But you don't have to create your array by copying every item. It is numpy, after all! I think this will work: data = [] for line in open('out.out'): data.extend(int(i) for i in line.split('\\')) a = array(data) a.shape = (384, 512) Kent