From wkgogogo at gmail.com Mon Sep 1 05:39:24 2008 From: wkgogogo at gmail.com (=?GB2312?B?zfXn5g==?=) Date: Mon, 1 Sep 2008 11:39:24 +0800 Subject: [Tutor] monitor subprocess and get it's output during execution Message-ID: <7a88e77d0808312039tc4eb37bic796c37c413abb0e@mail.gmail.com> Hi, I have a python program needs to do some download task from file server to local disk regularly. I intend to call robocopy.exe (a download tool in windows) do the real download job. --Below codes works: DownloadArgs = " \\servername\Sourcepath d:\destinationPath *.bin" os.system("robocopy.exe" +" "+ "DownloadArgs") But the problem is : 1.Program halt until this robocopy download complete. As the download will last 2~3hours, I want to do and display something while downloading. Such as display a ">" each 10 seconds while downloading. 2.robocopy's output display in console. I want to hide robocopy's output, meanwhile get latest output each 10 secends then display only a portion of it. --Then I use: p = subprocess.Popen(["robocopy.exe" +" " + "DownloadArgs"],Shell = True,stdout = PIPE) p.communicate() This can hide robocopy's output, but still can't display the download process is going. --Then I use: print "Download begin ..." p = subprocess.Popen(["robocopy.exe" +" " + "DownloadArgs"],Shell = True,stdout = PIPE) while not str(p.poll()).isdigit(): print ">", time.sleep(10) #don't know how to grab output and display portion of it print "Download complete with retval (%d) "% (p.poll()) This will make robocopy never terminate, and display ">>>>>>" forever. Any suggestion is welcome. Thanks in advance. Regards, Colin -------------- next part -------------- An HTML attachment was scrubbed... URL: From agoldgod at gmail.com Mon Sep 1 10:03:15 2008 From: agoldgod at gmail.com (goldgod a) Date: Mon, 1 Sep 2008 13:33:15 +0530 Subject: [Tutor] Tramline implementation Message-ID: <105c9ccc0809010103p7684935ci50ecf89d2c7e0bf0@mail.gmail.com> hi, I want to implement a tramline python library. I created a virtual host in apache and created a python(cgi) file with simple uploading concepts.Tramline is not interacting with apache. I tried get examples but they given for plone and zope. Is any idea or examples available. -- Thanks & Regards, goldgod -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Mon Sep 1 13:22:09 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 1 Sep 2008 07:22:09 -0400 Subject: [Tutor] Tramline implementation In-Reply-To: <105c9ccc0809010103p7684935ci50ecf89d2c7e0bf0@mail.gmail.com> References: <105c9ccc0809010103p7684935ci50ecf89d2c7e0bf0@mail.gmail.com> Message-ID: <1c2a2c590809010422g5355571qb35c0b4b4a4ce48a@mail.gmail.com> On Mon, Sep 1, 2008 at 4:03 AM, goldgod a wrote: > > hi, > I want to implement a tramline python library. I created a virtual > host in apache and created a python(cgi) file with simple uploading > concepts.Tramline is not interacting with apache. I tried get examples but > they given for plone and zope. Is any idea or examples available. I'm not sure what your problem is. Do you mean that your cgi is never being called by Apache? You have to configure apache for this to happen. Check the Apache docs or google 'python cgi apache' Kent From kent37 at tds.net Mon Sep 1 13:30:33 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 1 Sep 2008 07:30:33 -0400 Subject: [Tutor] monitor subprocess and get it's output during execution In-Reply-To: <7a88e77d0808312039tc4eb37bic796c37c413abb0e@mail.gmail.com> References: <7a88e77d0808312039tc4eb37bic796c37c413abb0e@mail.gmail.com> Message-ID: <1c2a2c590809010430h5f0676aeyabac1033bfe36e57@mail.gmail.com> On Sun, Aug 31, 2008 at 11:39 PM, ?? wrote: > --Then I use: > print "Download begin ..." > p = subprocess.Popen(["robocopy.exe" +" " + "DownloadArgs"],Shell = > True,stdout = PIPE) > while not str(p.poll()).isdigit(): > print ">", > time.sleep(10) > #don't know how to grab output and display portion of it > print "Download complete with retval (%d) "% (p.poll()) > > This will make robocopy never terminate, and display ">>>>>>" forever. I am not an expert in Popen, but I think in this example robocopy is blocked trying to output. Here is how to read the robocopy output: p = subprocess.Popen(["robocopy.exe" +" " + "DownloadArgs"],Shell = True,stdout = PIPE) while True: line = p.stdout.readline() if not line: break print line Kent From roadierich at googlemail.com Mon Sep 1 13:59:36 2008 From: roadierich at googlemail.com (Richard Lovely) Date: Mon, 1 Sep 2008 12:59:36 +0100 Subject: [Tutor] Concatenation vs formatting Message-ID: Just a couple of quick questions: What differences are there in efficency (i.e. time and memory) between string concatenation ("foo" + "bar") and printf style formatting ("%s%s" % ("foo","bar")). Is there any place where one is better than the other, and any places where either should be avoided? (I tend to program entirely using formatting.) Thanks -- Richard "Roadie Rich" Lovely, part of the JNP|UK Famile www.theJNP.com From sierra_mtnview at sbcglobal.net Mon Sep 1 16:17:11 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 01 Sep 2008 07:17:11 -0700 Subject: [Tutor] How Compute # of Days between Two Dates? Message-ID: <48BBF967.1080903@sbcglobal.net> An HTML attachment was scrubbed... URL: From allison.william at gmail.com Mon Sep 1 16:34:29 2008 From: allison.william at gmail.com (William Allison) Date: Mon, 01 Sep 2008 10:34:29 -0400 Subject: [Tutor] How Compute # of Days between Two Dates? In-Reply-To: <48BBF967.1080903@sbcglobal.net> References: <48BBF967.1080903@sbcglobal.net> Message-ID: <48BBFD75.4060905@gmail.com> Wayne Watson wrote: > That's the question in Subject. For example, the difference between 08/29/2008 > and 09/03/2008 is +5. The difference between 02/28/2008 and 03/03/2008 is 4, > leap year--extra day in Feb. I'm really only interested in years between, say, > 1990 and 2050. In other words not some really strange period of time well > outside our current era of history. I've used the datetime module to do something similar. Python 2.5.2 (r252:60911, Feb 22 2008, 07:57:53) [GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import datetime >>> today = datetime.date.today() >>> print today 2008-09-01 >>> last_year = datetime.date(2007, 9, 1) >>> print today - last_year 366 days, 0:00:00 >>> HTH, Will From greg at thewhittiers.com Mon Sep 1 16:41:30 2008 From: greg at thewhittiers.com (greg whittier) Date: Mon, 1 Sep 2008 10:41:30 -0400 Subject: [Tutor] How Compute # of Days between Two Dates? In-Reply-To: <48BBF967.1080903@sbcglobal.net> References: <48BBF967.1080903@sbcglobal.net> Message-ID: On Mon, Sep 1, 2008 at 10:17 AM, Wayne Watson wrote: > That's the question in Subject. For example, the difference between > 08/29/2008 and 09/03/2008 is +5. The difference between 02/28/2008 and > 03/03/2008 is 4, leap year--extra day in Feb. I'm really only interested in > years between, say, 1990 and 2050. In other words not some really strange > period of time well outside our current era of history. You want the datetime module. >>> from datetime import datetime >>> datetime(2008,03,03) - datetime(2008,2,28) datetime.timedelta(4) From bgailer at gmail.com Mon Sep 1 19:51:19 2008 From: bgailer at gmail.com (bob gailer) Date: Mon, 01 Sep 2008 13:51:19 -0400 Subject: [Tutor] Concatenation vs formatting In-Reply-To: References: Message-ID: <48BC2B97.50107@gmail.com> Richard Lovely wrote: > Just a couple of quick questions: > What differences are there in efficency (i.e. time and memory) between > string concatenation ("foo" + "bar") and printf style formatting > ("%s%s" % ("foo","bar")). > Is there any place where one is better than the othe concatenation should be more efficient as formatting takes 4 more bytecodes than concatenation, one of which is binary_format which will take more execution time. However unless your application does many of those it is not worth the effort to choose one over the other. I almost always favor formatting as it is so much easier to read, maintain and extend. -- Bob Gailer Chapel Hill NC 919-636-4239 When we take the time to be aware of our feelings and needs we have more satisfying interatctions with others. Nonviolent Communication provides tools for this awareness. As a coach and trainer I can assist you in learning this process. What is YOUR biggest relationship challenge? From sierra_mtnview at sbcglobal.net Tue Sep 2 02:07:37 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 01 Sep 2008 17:07:37 -0700 Subject: [Tutor] Responding to Tutor Posts, Reply-To Message-ID: <48BC83C9.1010503@sbcglobal.net> An HTML attachment was scrubbed... URL: From srilyk at gmail.com Tue Sep 2 02:14:58 2008 From: srilyk at gmail.com (W W) Date: Mon, 1 Sep 2008 19:14:58 -0500 Subject: [Tutor] Responding to Tutor Posts, Reply-To In-Reply-To: <48BC83C9.1010503@sbcglobal.net> References: <48BC83C9.1010503@sbcglobal.net> Message-ID: <333efb450809011714r281cb6cpca24bd7fcd597434@mail.gmail.com> On Mon, Sep 1, 2008 at 7:07 PM, Wayne Watson wrote: > When I reply to a response to my post, it seems to go back to the > respondent. I'd like it to just go back to the list. I'm using Seamonkey > (Mozilla). I can do a reply-all but that sends it to the respondent and the > list. It seems as though other lists have a Reply-To, which sends the post > to the list. Did I set something up wrong when I subscribed? > The list takes care of not sending it to your other recipients. (As you may have noticed you failed to get two copies of this e-mail) The list is just setup that the "reply-to" address isn't "tutor at python.org" If you're like any of us, you'll find that once or twice you'll fail to send your email by reply-to-all. Usually we'll just forward the response to the list with our replies. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From john at fouhy.net Tue Sep 2 02:15:17 2008 From: john at fouhy.net (John Fouhy) Date: Tue, 2 Sep 2008 12:15:17 +1200 Subject: [Tutor] Concatenation vs formatting In-Reply-To: References: Message-ID: <5e58f2e40809011715l7edc6e74r5661ec9fdab570f5@mail.gmail.com> 2008/9/1 Richard Lovely : > Just a couple of quick questions: > What differences are there in efficency (i.e. time and memory) between > string concatenation ("foo" + "bar") and printf style formatting > ("%s%s" % ("foo","bar")). The timeit module may provide some insight: Morpork:~ repton$ python -m timeit '"foo" + "bar"' 10000000 loops, best of 3: 0.0587 usec per loop Morpork:~ repton$ python -m timeit '"%s%s" % ("foo", "bar")' 1000000 loops, best of 3: 0.474 usec per loop Morpork:~ repton$ python -m timeit '"".join(["foo", "bar"])' 1000000 loops, best of 3: 0.579 usec per loop So, from one perspective, using string formatting (for this particular example) is about 8 times slower. OTOH, from another perspective, it's less than half a millisecond different. So, like Bob said, unless you're really doing a whole lot of this, go for whatever makes for the clearest or most maintainable code. (and don't forget ''.join if you're doing a lot of concatenation) -- John. From alan.gauld at btinternet.com Tue Sep 2 02:17:18 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 2 Sep 2008 01:17:18 +0100 Subject: [Tutor] Responding to Tutor Posts, Reply-To References: <48BC83C9.1010503@sbcglobal.net> Message-ID: "Wayne Watson" wrote > When I reply to a response to my post, it seems to go back > to the respondent. I'd like it to just go back to the list. > ...Did I set something up wrong when I subscribed? This has been a point of hot debate since the list was founded. Some of us like the reply going to the sender others want it to go to the list. Its not an error in your set up its deliberately set that way in the admin settings for the group. It's a philosphical debate whether the mail comes from the poster with the list server acting as a relay or whether it comes from the server itself. Provided you pay attention to the headers in your mails the Reply/ReplyAll will work as expected. Alan G From sierra_mtnview at sbcglobal.net Tue Sep 2 02:03:34 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 01 Sep 2008 17:03:34 -0700 Subject: [Tutor] How Compute # of Days between Two Dates? In-Reply-To: References: <48BBF967.1080903@sbcglobal.net> Message-ID: <48BC82D6.9010200@sbcglobal.net> An HTML attachment was scrubbed... URL: From john at fouhy.net Tue Sep 2 03:15:24 2008 From: john at fouhy.net (John Fouhy) Date: Tue, 2 Sep 2008 13:15:24 +1200 Subject: [Tutor] How Compute # of Days between Two Dates? In-Reply-To: <48BC82D6.9010200@sbcglobal.net> References: <48BBF967.1080903@sbcglobal.net> <48BC82D6.9010200@sbcglobal.net> Message-ID: <5e58f2e40809011815t2169d28cnd815b69e72840caa@mail.gmail.com> 2008/9/2 Wayne Watson : > How do I just get the current time? The following gives me 00:00:00. > > import datetime > > dt = datetime.time() datetime.datetime.today() will give you "now" as a datetime. You can then extract a time object from it: >>> datetime.datetime.today() datetime.datetime(2008, 9, 2, 13, 17, 13, 345793) >>> datetime.datetime.today().time() datetime.time(13, 17, 15, 786378) -- John. From wkgogogo at gmail.com Tue Sep 2 05:13:46 2008 From: wkgogogo at gmail.com (Colin.Wang) Date: Tue, 2 Sep 2008 11:13:46 +0800 Subject: [Tutor] monitor subprocess and get it's output during execution In-Reply-To: <1c2a2c590809010430h5f0676aeyabac1033bfe36e57@mail.gmail.com> References: <7a88e77d0808312039tc4eb37bic796c37c413abb0e@mail.gmail.com> <1c2a2c590809010430h5f0676aeyabac1033bfe36e57@mail.gmail.com> Message-ID: <7a88e77d0809012013r68878398rde01c645acf3b7fc@mail.gmail.com> 2008/9/1 Kent Johnson > On Sun, Aug 31, 2008 at 11:39 PM, ?? wrote: > > > --Then I use: > > print "Download begin ..." > > p = subprocess.Popen(["robocopy.exe" +" " + "DownloadArgs"],Shell = > > True,stdout = PIPE) > > while not str(p.poll()).isdigit(): > > print ">", > > time.sleep(10) > > #don't know how to grab output and display portion of it > > print "Download complete with retval (%d) "% (p.poll()) > > > > This will make robocopy never terminate, and display ">>>>>>" forever. > > I am not an expert in Popen, but I think in this example robocopy is > blocked trying to output. Here is how to read the robocopy output: > > p = subprocess.Popen(["robocopy.exe" +" " + "DownloadArgs"],Shell = > True,stdout = PIPE) > while True: > line = p.stdout.readline() > if not line: break > print line > > Kent Thanks Kent. Your code works, and robocopy process exit when download complete. When I try: p = subprocess.Popen(["robocopy.exe" +" " + "DownloadArgs"],Shell = True,stdout = PIPE) while True: line = p.stdout.readline() if not line: break time.sleep(5) ### new added print ">", then robocopy download will never complete. It seems, when call sleep() here, the subprocess will sleep too. Is that the cause? Thanks again. When subprocess running, how can I print some character on console window on a period of time? (Used to tell user the subprocess is still running) -------------- next part -------------- An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Tue Sep 2 05:27:21 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 01 Sep 2008 20:27:21 -0700 Subject: [Tutor] Checking for a Valid Date Message-ID: <48BCB299.8040206@sbcglobal.net> An HTML attachment was scrubbed... URL: From john at fouhy.net Tue Sep 2 06:25:35 2008 From: john at fouhy.net (John Fouhy) Date: Tue, 2 Sep 2008 16:25:35 +1200 Subject: [Tutor] Checking for a Valid Date In-Reply-To: <48BCB299.8040206@sbcglobal.net> References: <48BCB299.8040206@sbcglobal.net> Message-ID: <5e58f2e40809012125s33632ac3m3a19bc9a4a86b7e3@mail.gmail.com> 2008/9/2 Wayne Watson : > Is there some method or function that checks whether a date is valid. For > example, these are not valid (yyyy/mm/dd format here for reference.): [...] > Perhaps a Try is useful with some function? Yup. Have a look at time.strptime. Don't be afraid to look through the standard library documentation. If you're doing stuff with times and dates, reading through the time and datetime modules would be very helpful. (generally you will want to use datetime. The time module is at a lower level, although it is still the place to go for docs on strptime/strftime format strings) -- John. From agoldgod at gmail.com Tue Sep 2 10:00:47 2008 From: agoldgod at gmail.com (goldgod a) Date: Tue, 2 Sep 2008 13:30:47 +0530 Subject: [Tutor] Tramline implementation In-Reply-To: <1c2a2c590809010422g5355571qb35c0b4b4a4ce48a@mail.gmail.com> References: <105c9ccc0809010103p7684935ci50ecf89d2c7e0bf0@mail.gmail.com> <1c2a2c590809010422g5355571qb35c0b4b4a4ce48a@mail.gmail.com> Message-ID: <105c9ccc0809020100k2937c583hedd0974aa95ce620@mail.gmail.com> hi, I'm not sure what your problem is. Do you mean that your cgi is never > being called by Apache? You have to configure apache for this to > happen. Check the Apache docs or google 'python cgi apache'. I created a simple upload file using python-cgi. It's working with apache. I want to implement tramline support with that file. Tramline will work with apache and we can transfer the large file. I added the virtual host also but the tamline is not working. The same problem I am facing while implement it in PLONE/ZOPE. Any idea. I checked the apache log no more error over there, but apache is working fine. Any Idea to implement the same in cgi,plone or zope. Any body used it before. -- Thanks & Regards, goldgod -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Tue Sep 2 12:44:04 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 2 Sep 2008 06:44:04 -0400 Subject: [Tutor] monitor subprocess and get it's output during execution In-Reply-To: <7a88e77d0809012013r68878398rde01c645acf3b7fc@mail.gmail.com> References: <7a88e77d0808312039tc4eb37bic796c37c413abb0e@mail.gmail.com> <1c2a2c590809010430h5f0676aeyabac1033bfe36e57@mail.gmail.com> <7a88e77d0809012013r68878398rde01c645acf3b7fc@mail.gmail.com> Message-ID: <1c2a2c590809020344w3528c106p67818d4f8e76e087@mail.gmail.com> 2008/9/1 Colin. Wang : > When I try: > p = subprocess.Popen(["robocopy.exe" +" " + "DownloadArgs"],Shell = > True,stdout = PIPE) > while True: > line = p.stdout.readline() > if not line: break > time.sleep(5) ### new added > print ">", > > then robocopy download will never complete. > It seems, when call sleep() here, the subprocess will sleep too. > Is that the cause? Thanks again. I think robocopy is blocked waiting to output; it can only output one line every 5 seconds. Perhaps it times out. If you captured stderr you might see error messages. > When subprocess running, how can I print some character on console window on > a period of time? (Used to tell user the subprocess is still running) You might be able to do this by doing a non-blocking read() of the robocopy output but I don't know how to do that. Another option would be to have a second timer thread that every five seconds looks to see if the robocopy process is still running. The process that is reading robocopy output could reset the timer when it gets some output. This recipe is a starting point: http://code.activestate.com/recipes/464959/ Kent From kent37 at tds.net Tue Sep 2 13:10:52 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 2 Sep 2008 07:10:52 -0400 Subject: [Tutor] Tramline implementation In-Reply-To: <105c9ccc0809020100k2937c583hedd0974aa95ce620@mail.gmail.com> References: <105c9ccc0809010103p7684935ci50ecf89d2c7e0bf0@mail.gmail.com> <1c2a2c590809010422g5355571qb35c0b4b4a4ce48a@mail.gmail.com> <105c9ccc0809020100k2937c583hedd0974aa95ce620@mail.gmail.com> Message-ID: <1c2a2c590809020410u73d76e4cy313bd8f359653008@mail.gmail.com> On Tue, Sep 2, 2008 at 4:00 AM, goldgod a wrote: > I created a simple upload file using python-cgi. It's working with apache. I > want to implement tramline support with that file. Tramline will work with > apache and we can transfer the large file. I added the virtual host also > but the tamline is not working. The same problem I am facing while implement > it in PLONE/ZOPE. Any idea. I checked the apache log no more error over > there, but apache is working fine. Any Idea to implement the same in > cgi,plone or zope. Any body used it before. Tramline is installed into Apache as a mod_python filter. To use Tramline from a plain CGI you would have to emulate the mod_python filter protocol. I don't understand why you want to integrate Tramline with a cgi. Tramline is open source, public domain Python code, you can just re-use parts of it if you want to. Kent From adrian.greyling at gmail.com Tue Sep 2 18:09:07 2008 From: adrian.greyling at gmail.com (Adrian Greyling) Date: Tue, 2 Sep 2008 12:09:07 -0400 Subject: [Tutor] Is this a "Class" problem? In-Reply-To: <1c2a2c590808291431h2887b538pb50e4cc1b3ef975d@mail.gmail.com> References: <866c750d0808180913g29a3e83bocfa36c6448235024@mail.gmail.com> <5452EC5C-254A-4FA5-B749-6B6A8E073191@drinktomi.com> <866c750d0808290919o64571516k89c95bf2b9c01cc@mail.gmail.com> <1c2a2c590808291431h2887b538pb50e4cc1b3ef975d@mail.gmail.com> Message-ID: <866c750d0809020909y2f60a588o64c8c8efd6bf16aa@mail.gmail.com> I appreciate the feedback! I'll check out the pubsub module and see how that works out and I'll subscribe to the wxPython group too! Thanks again! On Fri, Aug 29, 2008 at 5:31 PM, Kent Johnson wrote: > On Fri, Aug 29, 2008 at 12:19 PM, Adrian Greyling > wrote: > > > Here's where I get fuzzy... Let's say I've got a "frame_1" object > > that opens a new "frame_2" object. As you've suggested above, I'll use > "m" > > to create an instance of a frame object. Now frame_2 opens a "dialog_1'" > > which asks for information that is sent back to 'frame_2'. How do I > > reference 'frame_2' in this case? Especially when frame_2 hasn't been > > closed and has just been waiting behind dialog_1 until dialog_1 closes. > > When I try to reference it again as "m = frame_2(self)" from a new > function > > definition, aren't I creating a brand new frame_2 object that has "blank" > > attributes, so to speak? > > Generally the way this works is something like: > - frame 2 creates dialog box > - frame 2 shows dialog box and waits for the dialog box to be dismissed > - frame 2 gets result from dialog box > > There are several examples of this in the wx demo, see > MultiChoiceDialog, SingleChoiceDialog, TextEntryDialog. If you are > writing your own custom dialog, make a method that allows the client > code to retrieve the user data from it. > > Kent > -------------- next part -------------- An HTML attachment was scrubbed... URL: From gslindstrom at gmail.com Wed Sep 3 05:05:15 2008 From: gslindstrom at gmail.com (Greg Lindstrom) Date: Tue, 2 Sep 2008 22:05:15 -0500 Subject: [Tutor] pyArkansas on October 4th Message-ID: We are pleased to announce that pyArkansas will be held on the campus of University of Central Arkansas (www.uca.edu) on October 4th. Scheduled classes in the morning include Python 101 taught by Dr. Bernard Chen (incoming faculty at UCA but having taught the course at Georgia State University), "Python 201" taught by Jeff Rush (Dallas Python Users Group) and Python for Unix/Linux Administration (Noah Gift teaching on his -- and Jeremy Jones' -- newly released OReilly title). The afternoon features talks and a panel discussion along with lots of great give aways and swag. Due to limitations of physical space we must close registration at 100 participants (in honor of my first OS, SunOS, we may go to 110). Check out our wiki at http://pycamp.python.org/Arkansas/HomePage. There's no registration fee, so if you're in the area stop on by...we are looking forward to a great day. Greg Lindstrom Python Artists of Arkansas (PyAR^2) -------------- next part -------------- An HTML attachment was scrubbed... URL: From david.johnson.ca at me.com Wed Sep 3 13:42:37 2008 From: david.johnson.ca at me.com (David Johnson) Date: Wed, 03 Sep 2008 12:42:37 +0100 Subject: [Tutor] Beginner issue with Tkinter Listbox Message-ID: <768F293C-F767-4BA3-BEB4-CC782C281E64@me.com> I have just started learning Python and have moved on to learning about Tkinter. This is likely to be a very easy question but I have no idea what is happening here. I am trying to set up a GUI, separated into several frames. In a lower frame I have added a Listbox. I want the first item in the Listbox to be highlighted when the programme starts up. Before adding the ".selection_set" method, the GUI looked just fine. I used the propagate method to fix the frame dimensions in my original programme. However, as soon as call the method: ListboxName.selection_set(0), the lower frame (containing the Listbox), ends up on the top row, covering the orginal top frame. I tried a very small bit of code to replicate the basic elements and the same happens (see code below): I am working using a mac and XCode, (cocoa-python project). Just as an additional point, I have diccovered that running the same programme through Terminal actually does just fine and displays the windows I want without a problem. Thanks in advance for any help with this Dave Here's the experiment: from Tkinter import * class Application(): def __init__(self, master): frame1 = Frame(master) frame1.grid() frame2 = Frame(master) frame2.grid() bttn = Button(frame1) bttn.grid() list = Listbox(frame2) list.grid() list.insert(END,"What's happening") list.selection_set(0) root = Tk() app = Application(root) root.mainloop() -------------- next part -------------- An HTML attachment was scrubbed... URL: From webmaster at monzell.com Wed Sep 3 21:44:54 2008 From: webmaster at monzell.com (Rilindo Foster) Date: Wed, 3 Sep 2008 15:44:54 -0400 Subject: [Tutor] TypeError: unsubscriptable object Message-ID: <0E3AE720-DF46-4700-A0C1-F5FFE8A5C886@monzell.com> Hi! Long time reader, first time poster (I think). I am trying to do a comparison on a particular list item. The list in question comes in this pair: TotalStoreSales = Revenues + "," + Orders TotalStoreSales = TotalStoreSales.split(",") At this point, it has two values, both strings. Then I attempt to do a comparison like so: if (float(TotalStoreSales[0]) > 0): (does stuff) I know that it is converting into a float - that I verified. At any event, it keeps returning with this: Traceback (most recent call last): File "./getMivaStoreTransactions.py", line 143, in ? TotalSales = TotalSales + getStoreStats(d[0],AllSales) File "./getMivaStoreTransactions.py", line 120, in getStoreStats if (float(TotalStoreSales[0]) > 0): TypeError: unsubscriptable object Maybe I am missing something someplace. Help? - Rilindo From kent37 at tds.net Wed Sep 3 22:37:36 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 3 Sep 2008 16:37:36 -0400 Subject: [Tutor] TypeError: unsubscriptable object In-Reply-To: <0E3AE720-DF46-4700-A0C1-F5FFE8A5C886@monzell.com> References: <0E3AE720-DF46-4700-A0C1-F5FFE8A5C886@monzell.com> Message-ID: <1c2a2c590809031337ie42b2a8g4098360e692eecf4@mail.gmail.com> On Wed, Sep 3, 2008 at 3:44 PM, Rilindo Foster wrote: > Hi! Long time reader, first time poster (I think). > > I am trying to do a comparison on a particular list item. The list in > question comes in this pair: > > TotalStoreSales = Revenues + "," + Orders > TotalStoreSales = TotalStoreSales.split(",") These two lines could be just TotalStoreSales = [Revenues, Orders] > At this point, it has two values, both strings. > > Then I attempt to do a comparison like so: > > if (float(TotalStoreSales[0]) > 0): > (does stuff) > > I know that it is converting into a float - that I verified. > > At any event, it keeps returning with this: > > Traceback (most recent call last): > File "./getMivaStoreTransactions.py", line 143, in ? > TotalSales = TotalSales + getStoreStats(d[0],AllSales) > File "./getMivaStoreTransactions.py", line 120, in getStoreStats > if (float(TotalStoreSales[0]) > 0): > TypeError: unsubscriptable object > > Maybe I am missing something someplace. Help? Is anything else happening between these two snippets? Try putting print type(TotalStoreSales), TotalStoreSales before the if statement. Kent From webmaster at monzell.com Wed Sep 3 22:51:30 2008 From: webmaster at monzell.com (Rilindo Foster) Date: Wed, 3 Sep 2008 16:51:30 -0400 Subject: [Tutor] TypeError: unsubscriptable object In-Reply-To: <1c2a2c590809031337ie42b2a8g4098360e692eecf4@mail.gmail.com> References: <0E3AE720-DF46-4700-A0C1-F5FFE8A5C886@monzell.com> <1c2a2c590809031337ie42b2a8g4098360e692eecf4@mail.gmail.com> Message-ID: As it turns out, I messed up. TotalStoreSales was returning as a integer, not a list. Which lead me to other issues with the script in question. Doh! Sorry about that and thanks! On Sep 3, 2008, at 4:37 PM, Kent Johnson wrote: > On Wed, Sep 3, 2008 at 3:44 PM, Rilindo Foster > wrote: >> Hi! Long time reader, first time poster (I think). >> >> I am trying to do a comparison on a particular list item. The list in >> question comes in this pair: >> >> TotalStoreSales = Revenues + "," + Orders >> TotalStoreSales = TotalStoreSales.split(",") > > These two lines could be just > TotalStoreSales = [Revenues, Orders] > >> At this point, it has two values, both strings. >> >> Then I attempt to do a comparison like so: >> >> if (float(TotalStoreSales[0]) > 0): >> (does stuff) >> >> I know that it is converting into a float - that I verified. >> >> At any event, it keeps returning with this: >> >> Traceback (most recent call last): >> File "./getMivaStoreTransactions.py", line 143, in ? >> TotalSales = TotalSales + getStoreStats(d[0],AllSales) >> File "./getMivaStoreTransactions.py", line 120, in getStoreStats >> if (float(TotalStoreSales[0]) > 0): >> TypeError: unsubscriptable object >> >> Maybe I am missing something someplace. Help? > > Is anything else happening between these two snippets? Try putting > print type(TotalStoreSales), TotalStoreSales > before the if statement. > > Kent -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Sep 3 22:59:14 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 03 Sep 2008 21:59:14 +0100 Subject: [Tutor] TypeError: unsubscriptable object In-Reply-To: <0E3AE720-DF46-4700-A0C1-F5FFE8A5C886@monzell.com> References: <0E3AE720-DF46-4700-A0C1-F5FFE8A5C886@monzell.com> Message-ID: <48BEFAA2.50708@btinternet.com> Rilindo Foster wrote: > The list in > question comes in this pair: > > TotalStoreSales = Revenues + "," + Orders > TotalStoreSales = TotalStoreSales.split(",") i Rilindo :-) Why not just TotalStoreSales = [Revenues, Orders] > At this point, it has two values, both strings. Did you try a print statement just to check it is a list here? > Then I attempt to do a comparison like so: > > if (float(TotalStoreSales[0]) > 0): > TypeError: unsubscriptable object Normally means the "list" isn't HTH, Alan G. From alan.gauld at btinternet.com Wed Sep 3 22:59:14 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 03 Sep 2008 21:59:14 +0100 Subject: [Tutor] TypeError: unsubscriptable object In-Reply-To: <0E3AE720-DF46-4700-A0C1-F5FFE8A5C886@monzell.com> References: <0E3AE720-DF46-4700-A0C1-F5FFE8A5C886@monzell.com> Message-ID: <48BEFAA2.50708@btinternet.com> Rilindo Foster wrote: > The list in > question comes in this pair: > > TotalStoreSales = Revenues + "," + Orders > TotalStoreSales = TotalStoreSales.split(",") i Rilindo :-) Why not just TotalStoreSales = [Revenues, Orders] > At this point, it has two values, both strings. Did you try a print statement just to check it is a list here? > Then I attempt to do a comparison like so: > > if (float(TotalStoreSales[0]) > 0): > TypeError: unsubscriptable object Normally means the "list" isn't HTH, Alan G. From cappy2112 at gmail.com Thu Sep 4 07:00:02 2008 From: cappy2112 at gmail.com (Tony Cappellini) Date: Wed, 3 Sep 2008 22:00:02 -0700 Subject: [Tutor] cmd module Message-ID: <8249c4ac0809032200u3cfec8ffv67f3efd6150a0950@mail.gmail.com> I was just reading the PYMOTW article on the cmd module, and trying the examples. http://www.doughellmann.com/PyMOTW/cmd/cmd.html Scroll down to Auto-Completion. Does the tab key work for anyone running Windows ? Is this an OS specific feature? I see the bash prompts in the article, tab does something different when running on Linux. I'm running Windows XP - when I run this example, tab only moves the cursor over, not the auto completion. From alan.gauld at btinternet.com Thu Sep 4 08:47:24 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 04 Sep 2008 07:47:24 +0100 Subject: [Tutor] cmd module In-Reply-To: <8249c4ac0809032200u3cfec8ffv67f3efd6150a0950@mail.gmail.com> References: <8249c4ac0809032200u3cfec8ffv67f3efd6150a0950@mail.gmail.com> Message-ID: <48BF847C.50508@btinternet.com> Tony Cappellini wrote: > Scroll down to Auto-Completion. > > Does the tab key work for anyone running Windows ? > Is this an OS specific feature? I've not read the article but I suspect it requires a GNU library to be included which seems to be standaard on *nix but not on XP. > I'm running Windows XP - when I run this example, tab only moves the > cursor over, not the auto completion. You can get the XP CMD prompt to do most of the Linux/bash like things, including autocompletion, but its not turned on by default. If you run HELP CMD at a CMD prompt you can read the long description of the ptions and how to enable them. This is very worth while if you use the cMD prompt regularly IMHO! HTH Alan G From alan.gauld at btinternet.com Thu Sep 4 08:47:24 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 04 Sep 2008 07:47:24 +0100 Subject: [Tutor] cmd module In-Reply-To: <8249c4ac0809032200u3cfec8ffv67f3efd6150a0950@mail.gmail.com> References: <8249c4ac0809032200u3cfec8ffv67f3efd6150a0950@mail.gmail.com> Message-ID: <48BF847C.50508@btinternet.com> Tony Cappellini wrote: > Scroll down to Auto-Completion. > > Does the tab key work for anyone running Windows ? > Is this an OS specific feature? I've not read the article but I suspect it requires a GNU library to be included which seems to be standaard on *nix but not on XP. > I'm running Windows XP - when I run this example, tab only moves the > cursor over, not the auto completion. You can get the XP CMD prompt to do most of the Linux/bash like things, including autocompletion, but its not turned on by default. If you run HELP CMD at a CMD prompt you can read the long description of the ptions and how to enable them. This is very worth while if you use the cMD prompt regularly IMHO! HTH Alan G From kent37 at tds.net Thu Sep 4 12:27:21 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 4 Sep 2008 06:27:21 -0400 Subject: [Tutor] cmd module In-Reply-To: <8249c4ac0809032200u3cfec8ffv67f3efd6150a0950@mail.gmail.com> References: <8249c4ac0809032200u3cfec8ffv67f3efd6150a0950@mail.gmail.com> Message-ID: <1c2a2c590809040327i264cc0xc3a06b71659141bb@mail.gmail.com> On Thu, Sep 4, 2008 at 1:00 AM, Tony Cappellini wrote: > I was just reading the PYMOTW article on the cmd module, and trying > the examples. > > http://www.doughellmann.com/PyMOTW/cmd/cmd.html > > Scroll down to Auto-Completion. > > Does the tab key work for anyone running Windows ? > Is this an OS specific feature? The command completion uses the Python readline library which, according to the docs, is only available on Unix. Kent From mwalsh at mwalsh.org Thu Sep 4 13:30:41 2008 From: mwalsh at mwalsh.org (Martin Walsh) Date: Thu, 04 Sep 2008 06:30:41 -0500 Subject: [Tutor] cmd module In-Reply-To: <1c2a2c590809040327i264cc0xc3a06b71659141bb@mail.gmail.com> References: <8249c4ac0809032200u3cfec8ffv67f3efd6150a0950@mail.gmail.com> <1c2a2c590809040327i264cc0xc3a06b71659141bb@mail.gmail.com> Message-ID: <48BFC6E1.5020902@mwalsh.org> Kent Johnson wrote: > On Thu, Sep 4, 2008 at 1:00 AM, Tony Cappellini wrote: >> I was just reading the PYMOTW article on the cmd module, and trying >> the examples. >> >> http://www.doughellmann.com/PyMOTW/cmd/cmd.html >> >> Scroll down to Auto-Completion. >> >> Does the tab key work for anyone running Windows ? >> Is this an OS specific feature? > > The command completion uses the Python readline library which, > according to the docs, is only available on Unix. There is pyreadline for windows, based on the installation instructions it might take a little effort to get it to work with the cmd module -- I've never tried. http://ipython.scipy.org/moin/PyReadline/Intro HTH, Marty From alan.gauld at btinternet.com Thu Sep 4 15:39:38 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 4 Sep 2008 14:39:38 +0100 Subject: [Tutor] Beginner issue with Tkinter Listbox References: <768F293C-F767-4BA3-BEB4-CC782C281E64@me.com> Message-ID: "David Johnson" wrote > However, as soon as call the method: ListboxName.selection_set(0), > the lower frame (containing the Listbox), ends up on the top row, > covering the orginal top frame. > I am working using a mac and XCode, (cocoa-python project). Just as > an additional point, I have diccovered that running the same > programme > through Terminal actually does just fine and displays the windows I > want without a problem. It works fine for me on Windows XP too. So that pretty much points the finger at the Mac environment. Either in XCode or maybe in the Cocoa version of Tkinter. I haven't got my Mac to hand but maybe some other XCode user could comment on what happens for them? One question, when it runs in Terminal does it come up with the Apple GUI style or the traditional X windows look? And same in XCode? It could be that XCode is picking up a different Tk library version. One for Cocoa and the other the traditional X windows version. Just a thought... Alan G. From bermanrl at embarqmail.com Thu Sep 4 15:59:11 2008 From: bermanrl at embarqmail.com (Robert Berman) Date: Thu, 04 Sep 2008 09:59:11 -0400 Subject: [Tutor] Need help with Factorial algorithm using Python Message-ID: <48BFE9AF.4000309@embarqmail.com> An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: factor.py Type: text/x-python Size: 1019 bytes Desc: not available URL: From rabidpoobear at gmail.com Thu Sep 4 16:39:29 2008 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 4 Sep 2008 09:39:29 -0500 Subject: [Tutor] Fwd: Need help with Factorial algorithm using Python In-Reply-To: References: <48BFE9AF.4000309@embarqmail.com> Message-ID: Oops, accidentally replied off list. ---------- Forwarded message ---------- From: Luke Paireepinart Date: Thu, Sep 4, 2008 at 9:39 AM Subject: Re: [Tutor] Need help with Factorial algorithm using Python To: Robert Berman On Thu, Sep 4, 2008 at 8:59 AM, Robert Berman wrote: > I am using both the THINK PYTHON text and the Challenge-You website to > learn Python. I am doing reasonably well and certainly enjoy the available > challenges. > > I am currently attempting to work a challenge known as the 'Zeros of a > Factorial' challenge located at > http://www.challenge-you.com/challenge?id=484. The actual challenge is as > follows: "It can easily be seen that 6! = 720 and has exactly one trailing > zero. What is the lowest integer, x, such that x! has 7^20 trailing zeros?" > > It does not, on the surface, appear to be a frontal lobe breaker. Design an > algorithm to build factorials; count the number of trailing zeros, and the > first time we hit it, we have the lowest integer. To test, I computed > factorials for 50,000--12,499 trailing zeros,100,000 trailing zeros--24,999, > 150,000 trailing zeros 37,498, and finally 200,000 trailing zeros of 49,998. > > Obviously, running a test on 1000000 would take some time and would not > even be close to the required number of trailing zeros. > > I need to know if I am even close with my approach to a workable algorithm > Sort of, but you're just guessing-checking or brute-forcing, which is not a really elegant algorithm. It will eventually come up with the right answer, though. You could also do a binary-search of sorts. Like, double the number, check the factorial. If it has too few trailing zeroes, double it again. Once you get above the target trailing zeroes, use 1.5 of the previous amount (instead of doubling). If you have too many zeroes still, use 1.25 of the previous amount. Otherwise use 1.75. That should converge fairly quickly on the correct answer. > and whatever suggestions you might have to speed up the process so that it > would not take hours until it found the correct integer. Any and all > suggestions as well as more efficient ways to code the algorithm will be > most appreciated. > Take a look at the code I've attached. It will search through all the factorials from 0 to 1000 that are multiples of 5. See if you can see the pattern in the number of zeroes. See hint below if you want. Once you figure out the pattern, you can just extrapolate from the 7**20 trailing zeroes what the actual factorial number is, then you can check it and make sure it's correct. I wrote a recursive factorial in case you're interested in seeing it. It's in the code. Hits the maximum recursion depth at factorial(1000). Oh, I also used a different strategy than you to count the zeroes. I just used a regex, because that made the most sense to me at the time. If any of my code doesn't make sense, let me know. Figuring out the pattern is better than a smarter guess-and-check, because you can go straight from a number of trailing zeroes directly to the source factorial. (hint: they are consecutive in groups of 5, and sometimes they skip one trailing zero, and sometimes two, between groups of 5. Try iterating over all the numbers between each gap and figure out which one creates the missing trailing zeroes, and study all these values.) You could probably look this stuff up online, but I thought it'd be more fun to try to come up with an algorithm on your own. (I didn't look this up either, so there might be a point at which the factorial pattern I am talking about breaks down, but I don't think there should be.) -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: factorial.py URL: From sierra_mtnview at sbcglobal.net Thu Sep 4 20:00:47 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Thu, 04 Sep 2008 11:00:47 -0700 Subject: [Tutor] Message 'list' object has no attribute 'strptime ? Message-ID: <48C0224F.7030602@sbcglobal.net> An HTML attachment was scrubbed... URL: From greg at thewhittiers.com Thu Sep 4 20:19:15 2008 From: greg at thewhittiers.com (greg whittier) Date: Thu, 4 Sep 2008 14:19:15 -0400 Subject: [Tutor] Message 'list' object has no attribute 'strptime ? In-Reply-To: <48C0224F.7030602@sbcglobal.net> References: <48C0224F.7030602@sbcglobal.net> Message-ID: On Thu, Sep 4, 2008 at 2:00 PM, Wayne Watson wrote: > The line > x = time.strptime(fmt_time, "%H %M %S") > with fmt_time = "11 12 40" > in function produces the msg: > Traceback (most recent call last): > File > "C:\Sandia_Meteors\Improved_Sentinel\Sentinel_Playground\Utility_Dev\SU_DateTimeAdjust.py", > line 209, in ? > if not verify_time(bump_time): > File > "C:\Sandia_Meteors\Improved_Sentinel\Sentinel_Playground\Utility_Dev\SU_DateTimeAdjust.py", > line 69, in verify_time > x = time.strptime(fmt_time, "%H %M %S") > AttributeError: 'list' object has no attribute 'strptime' > It looks like time is getting set to a list somewhere. Look at the code to figure out just what's in "time" at that point. You also might try a "print time" before that line or check it's value with a debugger. -------------- next part -------------- An HTML attachment was scrubbed... URL: From cfuller084 at thinkingplanet.net Thu Sep 4 18:03:39 2008 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Thu, 4 Sep 2008 11:03:39 -0500 Subject: [Tutor] Fwd: Need help with Factorial algorithm using Python In-Reply-To: References: <48BFE9AF.4000309@embarqmail.com> Message-ID: <200809041103.40007.cfuller084@thinkingplanet.net> The point of a lot of these challenges is to be smart with your math as well as your code. A brute force approach isn't going to work very well, especially in this case. An integer with 7^20 trailing zeros isn't even going to fit in your RAM. An observation: every trailing zero implies a factor of ten, which in primes is two and five. So the final number will have at least 7^20 twos and fives in its prime factorization. Exploiting this fact in a clever way is probably one way to solve this problem. Cheers From dcroxton at oxenstierna.homelinux.net Thu Sep 4 21:00:10 2008 From: dcroxton at oxenstierna.homelinux.net (Derek Croxton) Date: Thu, 04 Sep 2008 15:00:10 -0400 Subject: [Tutor] Python and HSQL Message-ID: Is there a way to connect to an HSQL database via Python? After some googling, the only way I can find is to use jython and connect via jdbc. I don't want to use jython, so I'm hoping there is another way. -- Sincerely, Derek From bermanrl at embarqmail.com Thu Sep 4 22:04:52 2008 From: bermanrl at embarqmail.com (Robert Berman) Date: Thu, 04 Sep 2008 16:04:52 -0400 Subject: [Tutor] Need help with Factorial algorithm using Python In-Reply-To: References: <48BFE9AF.4000309@embarqmail.com> Message-ID: <48C03F64.7070703@embarqmail.com> An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Thu Sep 4 22:05:35 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Thu, 04 Sep 2008 13:05:35 -0700 Subject: [Tutor] Message 'list' object has no attribute 'strptime ? In-Reply-To: <48C0224F.7030602@sbcglobal.net> References: <48C0224F.7030602@sbcglobal.net> Message-ID: <48C03F8F.9000609@sbcglobal.net> An HTML attachment was scrubbed... URL: From greg at thewhittiers.com Thu Sep 4 22:20:25 2008 From: greg at thewhittiers.com (greg whittier) Date: Thu, 4 Sep 2008 16:20:25 -0400 Subject: [Tutor] Message 'list' object has no attribute 'strptime ? In-Reply-To: <48C03F8F.9000609@sbcglobal.net> References: <48C0224F.7030602@sbcglobal.net> <48C03F8F.9000609@sbcglobal.net> Message-ID: On Thu, Sep 4, 2008 at 4:05 PM, Wayne Watson wrote: > Further info. If I put > y = time.strptime("11 01 05", "%H %M %S") > both in the function and in the main body. Only the line above in the > function produces an error message. > > Here's a simple program that creates the problem. > > import datetime > > def verify_time(in_time): > time = in_time.split(":") > in_time.split(":") produces a list > if len(time) <> 3: > print > print "Invalid format. Try again. hh:mm:ss, hh is 24 hour time." > return False > y = time.strptime("11 01 05", "%H %M %S") > a list object does not have a strptime method -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Thu Sep 4 22:29:58 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 4 Sep 2008 16:29:58 -0400 Subject: [Tutor] Python and HSQL In-Reply-To: References: Message-ID: <1c2a2c590809041329w4b6be03aid5d44d4d5792fecd@mail.gmail.com> On Thu, Sep 4, 2008 at 3:00 PM, Derek Croxton wrote: > Is there a way to connect to an HSQL database via Python? After some > googling, the only way I can find is to use jython and connect via jdbc. > I don't want to use jython, so I'm hoping there is another way. HSQL can talk HTTP so I guess at least in theory it is possible. I don't see any docs for the HTTP protocol though. Anyway Jython is not so bad :-) Kent From kent37 at tds.net Thu Sep 4 22:33:06 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 4 Sep 2008 16:33:06 -0400 Subject: [Tutor] Message 'list' object has no attribute 'strptime ? In-Reply-To: <48C03F8F.9000609@sbcglobal.net> References: <48C0224F.7030602@sbcglobal.net> <48C03F8F.9000609@sbcglobal.net> Message-ID: <1c2a2c590809041333r15432664qfbcb878dbad3adad@mail.gmail.com> On Thu, Sep 4, 2008 at 4:05 PM, Wayne Watson wrote: > Further info. If I put > y = time.strptime("11 01 05", "%H %M %S") > both in the function and in the main body. Only the line above in the > function produces an error message. > > Here's a simple program that creates the problem. > > import datetime > > def verify_time(in_time): > time = in_time.split(":") Like greg suspected...time is now a list. Kent From christopher.henk at allisontransmission.com Thu Sep 4 22:25:41 2008 From: christopher.henk at allisontransmission.com (christopher.henk at allisontransmission.com) Date: Thu, 4 Sep 2008 16:25:41 -0400 Subject: [Tutor] Message 'list' object has no attribute 'strptime ? In-Reply-To: <48C03F8F.9000609@sbcglobal.net> Message-ID: It looks to me that your variable: time = in_time.split(":") is hiding the time module. Chris Wayne Watson Sent by: tutor-bounces+christopher.henk=allisontransmission.com at python.org 09/04/2008 04:05 PM To "tutor at python.org" cc Subject Re: [Tutor] Message 'list' object has no attribute 'strptime ? Further info. If I put y = time.strptime("11 01 05", "%H %M %S") both in the function and in the main body. Only the line above in the function produces an error message. Here's a simple program that creates the problem. import datetime def verify_time(in_time): time = in_time.split(":") if len(time) <> 3: print print "Invalid format. Try again. hh:mm:ss, hh is 24 hour time." return False y = time.strptime("11 01 05", "%H %M %S") print y, "Yes, y" hour,minute,second = time fmt_time = hour+" "+minute+" "+second print "FMT TIME:", fmt_time x = time.strptime(fmt_time, "%H %M %S") print "fmt time:", fmt_time try: time.strptime(fmt_time, "%H %M %S") nhour = int(hour) nminute = int(minute) nsecond = int(second) except: print print "Invalid date values or format (hh:mm:ss): ", in_time print "Valid examples: 15:55:02, 8:20:5" print "Invalid examples: 14: 2:33, 7:11: 4, 11::7" return False return True y = time.strptime("11 01 05", "%H %M %S") atime = "11:12:13" print verify_time(atime) Wayne Watson wrote: The line x = time.strptime(fmt_time, "%H %M %S") with fmt_time = "11 12 40" in function produces the msg: Traceback (most recent call last): File "C:\Sandia_Meteors\Improved_Sentinel\Sentinel_Playground\Utility_Dev\SU_DateTimeAdjust.py", line 209, in ? if not verify_time(bump_time): File "C:\Sandia_Meteors\Improved_Sentinel\Sentinel_Playground\Utility_Dev\SU_DateTimeAdjust.py", line 69, in verify_time x = time.strptime(fmt_time, "%H %M %S") AttributeError: 'list' object has no attribute 'strptime' However, in another function the line x = time.strptime(fmt_date, "%m %d %Y") with fmt_date = "10 02 2008" works just fine. Does my format string in strptime for time have a problem? If I use the shell to set fmt_time and x = time.strptime(fmt_time, ..., I have no trouble. -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet Interesting government experience prior their candidacy: Abraham Lincoln: 2 years; George Washington: 0 years; Dwight Eisenhower: 0 years; James Buchanan: 29 years* Barack Obama: 11 years; John McCain: 26 years * Not a particularly good president at all Web Page: _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet Interesting government experience prior their candidacy: Abraham Lincoln: 2 years; George Washington: 0 years; Dwight Eisenhower: 0 years; James Buchanan: 29 years* Barack Obama: 11 years; John McCain: 26 years * Not a particularly good president at all Web Page: _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From inthefridge at gmail.com Thu Sep 4 22:56:32 2008 From: inthefridge at gmail.com (Spencer Parker) Date: Thu, 4 Sep 2008 14:56:32 -0600 Subject: [Tutor] Help with checking for a data type Message-ID: I have a script that is taking a directory list, the script then splits the name up by the hyphens in the name. The first part of the name should be a number, but it isn't always a number. Is there a way to say: if its a number then post this data....if not discard? -- Spencer Parker -------------- next part -------------- An HTML attachment was scrubbed... URL: From christopher.henk at allisontransmission.com Thu Sep 4 23:21:12 2008 From: christopher.henk at allisontransmission.com (christopher.henk at allisontransmission.com) Date: Thu, 4 Sep 2008 17:21:12 -0400 Subject: [Tutor] Help with checking for a data type In-Reply-To: Message-ID: try and convert the first value in the split list to a int (or float), if that works then post the value. if it throws an exception (ValueError) then catch that and pass, or do whatever else needs doing with the listing. def postData(inputData): fields=inputData.split("-") try: numberfield=int(fields[0]) #do whatever voodoo needed print "%s posted" %inputData except ValueError: print "%s not posted" %inputData pass #move on to other fields inputValue=["12-Foo-Fee","Bla-Ble-blu"] for entry in inputValue: postData(entry) "Spencer Parker" Sent by: tutor-bounces+christopher.henk=allisontransmission.com at python.org 09/04/2008 04:56 PM To tutor at python.org cc Subject [Tutor] Help with checking for a data type I have a script that is taking a directory list, the script then splits the name up by the hyphens in the name. The first part of the name should be a number, but it isn't always a number. Is there a way to say: if its a number then post this data....if not discard? -- Spencer Parker _______________________________________________ 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 Thu Sep 4 23:26:07 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 4 Sep 2008 17:26:07 -0400 Subject: [Tutor] Help with checking for a data type In-Reply-To: References: Message-ID: <1c2a2c590809041426x770f2115g3a55d1d8b59f288a@mail.gmail.com> On Thu, Sep 4, 2008 at 4:56 PM, Spencer Parker wrote: > I have a script that is taking a directory list, the script then splits the > name up by the hyphens in the name. The first part of the name should be a > number, but it isn't always a number. Is there a way to say: if its a > number then post this data....if not discard? Tthe isdigit() method of a string provides a simple test. It will return true if each character is a digit. if first_part.isdigit(): # post data If you want to allow things like '-300' or '1.234' then you can try to convert to an int or float. Failure will raise a ValueError. try: float(first_part) # post data except ValueError: pass Kent From inthefridge at gmail.com Thu Sep 4 23:30:21 2008 From: inthefridge at gmail.com (Spencer Parker) Date: Thu, 4 Sep 2008 15:30:21 -0600 Subject: [Tutor] Help with checking for a data type In-Reply-To: <1c2a2c590809041426x770f2115g3a55d1d8b59f288a@mail.gmail.com> References: <1c2a2c590809041426x770f2115g3a55d1d8b59f288a@mail.gmail.com> Message-ID: Those worked for me...thanks again!!! On Thu, Sep 4, 2008 at 3:26 PM, Kent Johnson wrote: > On Thu, Sep 4, 2008 at 4:56 PM, Spencer Parker > wrote: > > I have a script that is taking a directory list, the script then splits > the > > name up by the hyphens in the name. The first part of the name should be > a > > number, but it isn't always a number. Is there a way to say: if its a > > number then post this data....if not discard? > > Tthe isdigit() method of a string provides a simple test. It will > return true if each character is a digit. > if first_part.isdigit(): > # post data > > If you want to allow things like '-300' or '1.234' then you can try to > convert to an int or float. Failure will raise a ValueError. > try: > float(first_part) > # post data > except ValueError: > pass > > Kent > -- Spencer Parker -------------- next part -------------- An HTML attachment was scrubbed... URL: From roybayot at gmail.com Fri Sep 5 03:00:43 2008 From: roybayot at gmail.com (Roy Khristopher Bayot) Date: Fri, 5 Sep 2008 09:00:43 +0800 Subject: [Tutor] how do you make this a better code? Message-ID: <5e6459540809041800v10c25acr6d42a4a63c12a837@mail.gmail.com> Hi. Good day. I am new to Python but I have had experience with C/C++ and Matlab. I've been reading How to Think Like a Computer Scientist and skimmed Core Python to learn. Now I havent done the exercises because I wanted to get down to the project I'm doing in my spare time. The project involves taking pictures. I found a program called gphoto2 that can do what i need. But it was in command line. And i wanted to access it with a program. So I made a class that calls gphoto2 to control a camera. Here's the code. class CamHandle(object): def __init__(self): import os w = os.system('gphoto2 --auto-detect > CamHandleLog.txt') test = os.system('gphoto2 --capture-image >> CamHandleLog.txt') def captureImage(self): import os x = os.system('gphoto2 --capture-image >> CamHandleLog.txt') def getAllImages(self): import os y = os.system('gphoto2 --get-all-files >> CamHandleLog.txt') def deleteAllImages(self): import os z = os.system('gphoto2 -DR >> CamHandleLog.txt') Now when I import the file to the interpreter and instantiate the class, it works. Each function works. I havent done any error handling or exception handling yet but it works for now. However, I am bothered with the import statements in each function. Correct me if I am wrong but each "import os" statement only exists in each method. Is there a way to only import the os module once and use it in each method? Thank you and have a nice day. -------------- next part -------------- An HTML attachment was scrubbed... URL: From cfuller084 at thinkingplanet.net Fri Sep 5 03:37:35 2008 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Thu, 4 Sep 2008 20:37:35 -0500 Subject: [Tutor] Need help with Factorial algorithm using Python In-Reply-To: <48BFE9AF.4000309@embarqmail.com> References: <48BFE9AF.4000309@embarqmail.com> Message-ID: <200809042037.35206.cfuller084@thinkingplanet.net> I spent the day mulling over this problem, and then implemented my solution when I got home. This is for the easier problem of 7**8 zeros: On my linux box, running something around 2 GHz, my script runs for about two minutes and the answer is 23059225. You can verify your code to that. I checked that the answer was correct for 7**2, 7**3, and 7**4. My script is only 25-30 lines long. It isn't too complicated. The only place I used strings was when verifying the length of trailing zeros, not in the actual solution at all. Cheers From bermanrl at embarqmail.com Fri Sep 5 03:27:26 2008 From: bermanrl at embarqmail.com (Robert Berman) Date: Thu, 04 Sep 2008 21:27:26 -0400 Subject: [Tutor] Need help with Factorial algorithm using Python In-Reply-To: <200809042037.35206.cfuller084@thinkingplanet.net> References: <48BFE9AF.4000309@embarqmail.com> <200809042037.35206.cfuller084@thinkingplanet.net> Message-ID: <48C08AFE.4080001@embarqmail.com> An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Fri Sep 5 03:29:42 2008 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Thu, 4 Sep 2008 18:29:42 -0700 Subject: [Tutor] how do you make this a better code? In-Reply-To: <5e6459540809041800v10c25acr6d42a4a63c12a837@mail.gmail.com> References: <5e6459540809041800v10c25acr6d42a4a63c12a837@mail.gmail.com> Message-ID: <40af687b0809041829j7cddac61s2a41a88074efb4df@mail.gmail.com> On Thu, Sep 4, 2008 at 6:00 PM, Roy Khristopher Bayot wrote: > Correct me if I am wrong but each "import os" statement only exists in each > method. Is there a way to only import the os module once and use it in each > method? > Move it to the top of the file, outside of the class definition: import os class CamHandle(object): def __init__(self): w = os.system('gphoto2 --auto-detect > CamHandleLog.txt') test = os.system('gphoto2 --capture-image >> CamHandleLog.txt') def captureImage(self): x = os.system('gphoto2 --capture-image >> CamHandleLog.txt') def getAllImages(self): y = os.system('gphoto2 --get-all-files >> CamHandleLog.txt') def deleteAllImages(self): z = os.system('gphoto2 -DR >> CamHandleLog.txt') I haven't tested your code, but this should work just fine. -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Fri Sep 5 03:42:07 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 4 Sep 2008 21:42:07 -0400 Subject: [Tutor] how do you make this a better code? In-Reply-To: <5e6459540809041800v10c25acr6d42a4a63c12a837@mail.gmail.com> References: <5e6459540809041800v10c25acr6d42a4a63c12a837@mail.gmail.com> Message-ID: <1c2a2c590809041842h52aca4e6u95645f9949deb6c1@mail.gmail.com> On Thu, Sep 4, 2008 at 9:00 PM, Roy Khristopher Bayot wrote: > class CamHandle(object): > def __init__(self): > import os > w = os.system('gphoto2 --auto-detect > CamHandleLog.txt') > test = os.system('gphoto2 --capture-image >> CamHandleLog.txt') > > def captureImage(self): > import os > x = os.system('gphoto2 --capture-image >> CamHandleLog.txt') > > Now when I import the file to the interpreter and instantiate the class, it > works. Each function works. I havent done any error handling or exception > handling yet but it works for now. However, I am bothered with the import > statements in each function. The usual method is to put the import statement at the beginning of the module. Then the imported module has global (module) scope rather than function scope. Kent From jmorcombe at westnet.com.au Fri Sep 5 05:30:36 2008 From: jmorcombe at westnet.com.au (Jim Morcombe) Date: Fri, 05 Sep 2008 11:30:36 +0800 Subject: [Tutor] Calling Python Programs from Word, pdfs, etc Message-ID: <48C0A7DC.9050804@westnet.com.au> I am thinking about some long term teaching aids, so I'm simply interested in whether these things can be done. I don't need to know how yet. 1. Is it possible to invoke a Python Program from some kind of link in a Word document, similar to the way a Java Applet is run from a Web Page. Obviously I am thinking about a Windows enviroinment only. (I guess I'm probably asking if an exe file can be launched from Winows) 2. How about from a pdf document? 3. I've never used any ebook creation software (and this is probably not the right place to ask) but does anyone have any experience with ebooks that launch Python Applications? Jim From sierra_mtnview at sbcglobal.net Fri Sep 5 07:14:35 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Thu, 04 Sep 2008 22:14:35 -0700 Subject: [Tutor] Exit from a Program While in IDLE Message-ID: <48C0C03B.4050602@sbcglobal.net> An HTML attachment was scrubbed... URL: From carroll at tjc.com Fri Sep 5 07:20:03 2008 From: carroll at tjc.com (Terry Carroll) Date: Thu, 4 Sep 2008 22:20:03 -0700 (PDT) Subject: [Tutor] Need help with Factorial algorithm using Python In-Reply-To: <48BFE9AF.4000309@embarqmail.com> Message-ID: On Thu, 4 Sep 2008, Robert Berman wrote: > "It can easily be seen that 6! = 720 and has exactly one > trailing zero. What is the lowest integer, x, such that x! has 7^20 > trailing zeros?" > > It does not, on the surface, appear to be a frontal lobe breaker. Design > an algorithm to build factorials; count the number of trailing zeros, and > the first time we hit it, we have the lowest integer. To test, I computed > factorials for 50,000--12,499 trailing zeros,100,000 trailing > zeros--24,999, 150,000 trailing zeros 37,498, and finally 200,000 > trailing zeros of 49,998. > > Obviously, running a test on 1000000 would take some time and would not > even be close to the required number of trailing zeros. At the risk of spoiling with a solution (don't worry, all code is at the end), the trick here is to realize that this is all about counting 5's. you get a zero on the end when a 10 gets into the factorial; and a 10 factors down to 2 x 5. At first glance, you'd have to count both 2s and 5s, but 2s are so plentiful in comparison to 5s, that you really only need to count 5s. So 5! has one 5, at 5. For that matter, so does 6!, 7!, 8! and 9!. All of those will have only one trailing zero. At 10! you have another 5, and now have 2 trailing zeroes; at 15!, you have 3; and at 20! you have 4. 25!, however, gives you 6 zeroes. That's because 25 = 5*5, so it's giving you 2 more fives instead of just one. 30! will get you 7 zeroes, etc. Here's how I started thinking about it: every 5 is worth one five. every 25 is worth 5 fives, plus one more five, for a total of 6 fives; and that score includes all numbers below it. every 125 is worth 5 twenty-fives, plus one more five, for a total of 31 fives. What does this get us? Well, let's say you want to know how many terminal zeroes in 290!. 290 is 2*125 + 1*25 + 3*5. A 125 is worth 31; a 25 is worth 6; and a 5 is worth 1; 2*31 + 1*6 + 3*1 = 71, so there should be 71 zeroes. That turns out to be right: [some code snipped] >>> f = fact(290) >>> print f, num_trailing_zeros(f) 60316116183878209766117976235613285674586630483425933084029202472047670485819885 24516473184964281054847594152584009528621417952272159399012893011898232929436576 79285114407298493208021847117743304953755459586044474858941338130407530467578458 33254416671760299033093062086252031499964109155039154660288221882477747977319966 16183514677158049698159171977934429370558012376711563782210013569092594615762035 60549776040291140480868660361895305429328142835207067479091087183725251309232283 59166396038270919098494331151103662489600000000000000000000000000000000000000000 000000000000000000000000000000 71 So here's my routine to address the problem. It consists of making a multiplication table of coefficients that includes the factor such as 5, 25, 125, etc., and their values (1, 6, 31, etc). Then, starting with the highest ones first, successievely determining how many times each factor goes into the number of zeroes. For example, to do the prior example working backwards, what factorial will give you 71 zeroes? Well, 71/31 gives you 2, remainder 9; so we know there are 2 125s; 9/6 gives you 1, remander 3; so we know there is 1 25; 3/1 gives you (duh) 3, so there are 3 5s. so the answer to the question "what is the first factorial with 71 trailing zeros?" is 2*125 + 1*25 + 3*5 = 290; i.e. 290! Code: def find_lowest_factbase(num_z): ''' This function returns a lowest value N for which N! terminates with num_z zeroes i.e., find_lowest_factbase(2) = 10; because 10! = 3,628,800 ''' coefflist=[] ''' coefflist is a list of lists, each sublist of which has two elements: 0: value of 5**N 1: weight of value ''' for i in range(1,1000000): #will break out well before a million value = 5**i if i == 1: weight = 1 else: weight = (coefflist[-1][1]*5)+1 if weight > num_z: break coefflist.append([value, weight]) coefflist.reverse() productpairs=[] zerosleft=num_z for L in coefflist: (quotient, remainder) = divmod(zerosleft, L[1]) productpairs.append([quotient, L[0]]) zerosleft = remainder product=0 for pair in productpairs: product = product + pair[0]*pair[1] return product I tested it by comparing the output of the two sets, one testing through 45! and one testing through 10 zeros (which works out to be the same): def fact(n): m=1 for i in range(1,n+1): m = m*i return m def num_trailing_zeros(n): s = str(n) s_no_zeros = s.rstrip('0') numz = len(s)-len(s_no_zeros) return numz #brute force: max_nz=0 for i in range(1,50): k = fact(i) nz = num_trailing_zeros(k) if nz > max_nz: print "nz=%s at %s! (%s)" % (nz, i , k) max_nz = nz # fives-algorithm: for i in range(1,11): k = find_lowest_factbase(i) print "nz=%s at %s! (%s)" % (i, k , fact(k)) And your answer? >>> print "answer: ", find_lowest_factbase(7**20) answer: 319169065190448050 From carroll at tjc.com Fri Sep 5 07:24:55 2008 From: carroll at tjc.com (Terry Carroll) Date: Thu, 4 Sep 2008 22:24:55 -0700 (PDT) Subject: [Tutor] Need help with Factorial algorithm using Python In-Reply-To: <48C03F64.7070703@embarqmail.com> Message-ID: On Thu, 4 Sep 2008, Robert Berman wrote: > Time to do some reading about regex. And here I thought I was slick > working with lists and strings. You shouldn't need a regexp for this. An easy way to count the trailing zeros is: - convert the number to a string; - make a copy, stripping off the trailing zeroes, using rstrip('0') - compare the lengths of the two strings The difference in the lengths is the number of trailing zeroes. From mail at timgolden.me.uk Fri Sep 5 09:55:41 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 05 Sep 2008 08:55:41 +0100 Subject: [Tutor] Calling Python Programs from Word, pdfs, etc In-Reply-To: <48C0A7DC.9050804@westnet.com.au> References: <48C0A7DC.9050804@westnet.com.au> Message-ID: <48C0E5FD.2010902@timgolden.me.uk> Jim Morcombe wrote: > 1. Is it possible to invoke a Python Program from some kind of link in > a Word document, similar to the way a Java Applet is run from a Web > Page. Obviously I am thinking about a Windows enviroinment only. (I > guess I'm probably asking if an exe file can be launched from Winows) Well I'd just written this email saying how unlikely it was and how horrified I'd be. And then I just threw the relevant words into Google and... http://vbadud.blogspot.com/2007/06/run-vb60-executable-from-excelword.html I haven't tried it but if you can call CreateProcess then you can do pretty much anything you like. TJG From wescpy at gmail.com Fri Sep 5 10:19:38 2008 From: wescpy at gmail.com (wesley chun) Date: Fri, 5 Sep 2008 01:19:38 -0700 Subject: [Tutor] [ANN] final 2008 Python courses, San Francisco In-Reply-To: <78b3a9580809050116w2cfd7a98s10b7b9d201a979d8@mail.gmail.com> References: <78b3a9580809050116w2cfd7a98s10b7b9d201a979d8@mail.gmail.com> Message-ID: <78b3a9580809050119q46e5f004q7d7761950429fac4@mail.gmail.com> *** will also X-post to CLP so apologies in advance for duplicates *** Need to get up-to-speed with Python as quickly as possible? Come join me, Wesley Chun, author of Prentice-Hall's bestseller "Core Python Programming," for another comprehensive intro course plus a 1-day Internet programming course coming up in November in beautiful Northern California! I look forward to meeting you! (Comprehensive) Introduction to Python Mon-Wed, 2008 Nov 10-12, 9am-5pm Internet Programming with Python Sat, 2008 Nov 15, 9am-5pm courses can be taken separately or combined for a discounted price. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - (COMPREHENSIVE) INTRODUCTION TO PYTHON Although this course may appear to those new to Python, it is also perfect for those who have tinkered with it and want to "fill in the gaps" and/or want to get more in-depth formal training. It combines the best of both an introduction to the language as well as a "Python Internals" training course. We will immerse you in the world of Python in only a few days, showing you more than just its syntax (which you don't really need a book to learn, right?). Knowing more about how Python works under the covers, including the relationship between data objects and memory management, will make you a much more effective Python programmer coming out of the gate. 3 hands-on labs each day will help hammer the concepts home. Come find out why Google, Yahoo!, Disney, ILM/LucasFilm, VMware, NASA, Ubuntu, YouTube, and Red Hat all use Python. Users supporting or jumping to Plone, Zope, TurboGears, Pylons, Django, Google App Engine, Jython, IronPython, and Mailman will also benefit! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - INTERNET PROGRAMMING WITH PYTHON This is a one-day course with lecture and lab exposing attendees to FOUR distinct areas of Internet programming: * Network Programming using Sockets -- we introduce client/server architecture and how to program sockets using Python. * Internet Client Programming -- we learn how to use Python's standard library to create FTP, NNTP, POP3, and SMTP clients * Web Programming -- before you jump on all the web framework bandwagons, it's a good idea to learn basics and the basis of how all web servers deliver dynamic content back to the client browser to prepare you better when jumping to a full-stack web framework * Intro to Django -- a lightweight introduction to the Django web framework including whipping up a very simple blog application in 20min! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - WHERE: near the San Francisco Airport (SFO/San Bruno), CA, USA WEB: http://cyberwebconsulting.com (click "Python Training") FLYER: http://starship.python.net/crew/wesc/flyerPP1combo.pdf LOCALS: easy freeway (101/280/380) with lots of parking plus public transit (BART and CalTrain) access via the San Bruno stations, easily accessible from all parts of the Bay Area VISITORS: free shuttle to/from the airport, free high-speed internet, free breakfast and regular evening receptions; fully-equipped suites See website for costs, venue info, and registration. Discounts are available for multiple registrations as well as for teachers/students. Hope to see you there! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com "Python Web Development with Django", Addison Wesley, (c) 2008 http://withdjango.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From alan.gauld at btinternet.com Fri Sep 5 10:27:44 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 5 Sep 2008 09:27:44 +0100 Subject: [Tutor] Exit from a Program While in IDLE References: <48C0C03B.4050602@sbcglobal.net> Message-ID: "Wayne Watson" wrote > seems liking quitting, exiting, or stopping a program is a > bit controversial. I've tried using sys.exit(0) while debugging > a program in IDLE, but it asks if I really want to exit. Thats because IDLE is an IDE so it interceprts the exit (actually it intercepts the esception that exit() generates) Thats what you want otherwise you'd constantly have to restart IDLE. But when you run your program for real - from Windows explorer for example it will just exit. > I just want a no-fuss, no-muss way of exiting the code > in the same fashion that when I get to the last line, > it exits next. Win XP, Python 2.4. sys.exit() will do that when you run the program standalone. If its a GUI program in Tkinter you can also use the root quit command to quit the GUI mainloop which usually exits the program too. But testing Tkinter programs from within IDLE(which is itself a Tkinter program) has always been a wee bit tricky, its better to always do your final test run outside of IDLE IMHO. After all thats how the program will eventually be used! HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld > > -- > > Wayne Watson (Watson Adventures, Prop., Nevada City, CA) > > (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) > Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet > > Interesting government experience prior their candidacy: > > Abraham Lincoln: 2 years; George Washington: 0 years; > Dwight Eisenhower: 0 years; James Buchanan: 29 years* > Barack Obama: 11 years; John McCain: 26 years > > * Not a particularly good president at all > > Web Page: -------------------------------------------------------------------------------- > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Fri Sep 5 10:31:05 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 5 Sep 2008 09:31:05 +0100 Subject: [Tutor] Calling Python Programs from Word, pdfs, etc References: <48C0A7DC.9050804@westnet.com.au> Message-ID: "Jim Morcombe" wrote >I am thinking about some long term teaching aids, so I'm simply >interested in whether these things can be done. I don't need to know >how yet. > > 1. Is it possible to invoke a Python Program from some kind of link > in a Word document, similar to the way a Java Applet is run from a > Web Page. Obviously I am thinking about a Windows enviroinment > only. (I guess I'm probably asking if an exe file can be launched > from Winows) Yes just as youd run any program from any VBA enabled program. You need to trigtger the VBA macro from the Word document and it then runs the external command. Its fairly easy. > 2. How about from a pdf document? Probably but I don;t know enough about the scripting options of PDF. You would certainly need the full Adobe acrobat authoring kit I suspect. ISTR that Acrobat can use actionscript in recent versions, but that may be wrong and anyhow I know nothing about Actionscript! > 3. I've never used any ebook creation software (and this is > probably not the right place to ask) but does anyone have any > experience with ebooks that launch Python Applications? No, sorry. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From linus_8989 at hotmail.com Fri Sep 5 12:28:01 2008 From: linus_8989 at hotmail.com (=?iso-8859-1?Q?Linus_Lindstr=F6m?=) Date: Fri, 5 Sep 2008 12:28:01 +0200 Subject: [Tutor] Problems starting python Message-ID: Hello. When i first installed python from the cd i bought it seemed to work perfectly... But then when i cancel the program and try to start it again I get the message: "IDLE's subprocess didn't make connection. Either IDLE can't start a subprocess or a personal firewall software is blocking the connection.", and the problem still stands... I've tried to completely shut down my firewall but without success... Please help me! _________________________________________________________________ Senaste sportnyheterna & rykande f?rska resultat! http://sport.msn.se/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From timovwb at gmail.com Fri Sep 5 15:34:40 2008 From: timovwb at gmail.com (Timo) Date: Fri, 05 Sep 2008 15:34:40 +0200 Subject: [Tutor] "Analyzing" music with Python Message-ID: <48c1356e.0707d00a.6343.336b@mx.google.com> I'm sorry if I don't use correct names etc.. What I want is to analyze a music file that is playing. Not sure if analyze is the good word for it. I just want to get info about the song in realtime when it is playing. Info about the current pitch and so. Let's say like most visualisation plugins in music players. The visualisations move on the music. I don't want to write such a plugin, but I want to get info to do something similar. Damn, hope this makes sense. Thanks From bermanrl at embarqmail.com Fri Sep 5 15:40:39 2008 From: bermanrl at embarqmail.com (Robert Berman) Date: Fri, 05 Sep 2008 09:40:39 -0400 Subject: [Tutor] Need help with Factorial algorithm using Python In-Reply-To: References: Message-ID: <48C136D7.8050605@embarqmail.com> An HTML attachment was scrubbed... URL: From srilyk at gmail.com Fri Sep 5 17:46:20 2008 From: srilyk at gmail.com (W W) Date: Fri, 5 Sep 2008 10:46:20 -0500 Subject: [Tutor] "Analyzing" music with Python In-Reply-To: <48c1356e.0707d00a.6343.336b@mx.google.com> References: <48c1356e.0707d00a.6343.336b@mx.google.com> Message-ID: <333efb450809050846i65e4fe26o8f4dd0e8f9b869b5@mail.gmail.com> On Fri, Sep 5, 2008 at 8:34 AM, Timo wrote: > I'm sorry if I don't use correct names etc.. What I want is to analyze a > music file that is playing. Not sure if analyze is the good word for it. I > just want to get info about the song in realtime when it is playing. Info > about the current pitch and so. > Let's say like most visualisation plugins in music players. The > visualisations move on the music. I don't want to write such a plugin, but I > want to get info to do something similar. > > Damn, hope this makes sense. I'm not sure what the library would be... you probably don't need access to the music file, but the soundcard (that's my guess anyway). this link (google: python sound visualization) may be a good place to start http://wiki.python.org/moin/Audio/ HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From srilyk at gmail.com Fri Sep 5 18:56:02 2008 From: srilyk at gmail.com (W W) Date: Fri, 5 Sep 2008 11:56:02 -0500 Subject: [Tutor] Fwd: "Analyzing" music with Python In-Reply-To: <333efb450809050954x76fc75f0l37b3d45d8766dfaa@mail.gmail.com> References: <48c1356e.0707d00a.6343.336b@mx.google.com> <333efb450809050846i65e4fe26o8f4dd0e8f9b869b5@mail.gmail.com> <48c15da4.0309d00a.136b.7780@mx.google.com> <333efb450809050954x76fc75f0l37b3d45d8766dfaa@mail.gmail.com> Message-ID: <333efb450809050956lab3f0d0sfa83caa62ac0d54e@mail.gmail.com> Forgot to reply to all... ---------- Forwarded message ---------- From: W W Date: Fri, Sep 5, 2008 at 11:54 AM Subject: Re: [Tutor] "Analyzing" music with Python To: Timo On Fri, Sep 5, 2008 at 11:26 AM, Timo wrote: > Thanks for the link, found some of those things already, but not yet a > solution. > > I'll try to make myself a bit clearer. What I want is to execute commands > when the music changes. So actually a sort of visualization, but instead of > drawing weird things on the screen, I want to execute commands. > That's not terribly different, you might just have to hack their code to something else. So instead of: if pitch == csharp: drawsomething(blue) you would modify it to: if pitch == csharp: runmyprogram(now) or something to that effect. I'm not sure how they've implemented their visualization, but they're going to have some type of notification. Perhaps it's continuous, so you create a threshold. HTH, Wayne > > > > W W schreef: > > On Fri, Sep 5, 2008 at 8:34 AM, Timo > timovwb at gmail.com>> wrote: >> >> I'm sorry if I don't use correct names etc.. What I want is to >> analyze a music file that is playing. Not sure if analyze is the >> good word for it. I just want to get info about the song in >> realtime when it is playing. Info about the current pitch and so. >> Let's say like most visualisation plugins in music players. The >> visualisations move on the music. I don't want to write such a >> plugin, but I want to get info to do something similar. >> >> Damn, hope this makes sense. >> >> >> I'm not sure what the library would be... you probably don't need access >> to the music file, but the soundcard (that's my guess anyway). >> >> this link (google: python sound visualization) may be a good place to >> start >> http://wiki.python.org/moin/Audio/ >> >> 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 -------------- next part -------------- An HTML attachment was scrubbed... URL: From timovwb at gmail.com Fri Sep 5 20:54:07 2008 From: timovwb at gmail.com (Timo) Date: Fri, 05 Sep 2008 20:54:07 +0200 Subject: [Tutor] Fwd: "Analyzing" music with Python In-Reply-To: <333efb450809050956lab3f0d0sfa83caa62ac0d54e@mail.gmail.com> References: <48c1356e.0707d00a.6343.336b@mx.google.com> <333efb450809050846i65e4fe26o8f4dd0e8f9b869b5@mail.gmail.com> <48c15da4.0309d00a.136b.7780@mx.google.com> <333efb450809050954x76fc75f0l37b3d45d8766dfaa@mail.gmail.com> <333efb450809050956lab3f0d0sfa83caa62ac0d54e@mail.gmail.com> Message-ID: <48c1804d.0508d00a.62ef.ffff99e5@mx.google.com> >if pitch == csharp: > runmyprogram(now) Yep, that is something what I'm looking for. And maybe with some other thing than pitch too (don't know what you can get from a sound file). But I looked at most of the examples of the modules and couldn't find anything like this. W W schreef: > Forgot to reply to all... > > ---------- Forwarded message ---------- > From: *W W* > > Date: Fri, Sep 5, 2008 at 11:54 AM > Subject: Re: [Tutor] "Analyzing" music with Python > To: Timo > > > > On Fri, Sep 5, 2008 at 11:26 AM, Timo > wrote: > > Thanks for the link, found some of those things already, but not > yet a solution. > > I'll try to make myself a bit clearer. What I want is to execute > commands when the music changes. So actually a sort of > visualization, but instead of drawing weird things on the screen, > I want to execute commands. > > > That's not terribly different, you might just have to hack their code > to something else. So instead of: > > if pitch == csharp: > drawsomething(blue) > > you would modify it to: > > if pitch == csharp: > runmyprogram(now) > > or something to that effect. I'm not sure how they've implemented > their visualization, but they're going to have some type of > notification. Perhaps it's continuous, so you create a threshold. > > HTH, > Wayne > > > > > > W W schreef: > > On Fri, Sep 5, 2008 at 8:34 AM, Timo >> wrote: > > I'm sorry if I don't use correct names etc.. What I want is to > analyze a music file that is playing. Not sure if analyze > is the > good word for it. I just want to get info about the song in > realtime when it is playing. Info about the current pitch > and so. > Let's say like most visualisation plugins in music players. The > visualisations move on the music. I don't want to write such a > plugin, but I want to get info to do something similar. > > Damn, hope this makes sense. > > > I'm not sure what the library would be... you probably don't > need access to the music file, but the soundcard (that's my > guess anyway). > > this link (google: python sound visualization) may be a good > place to start > http://wiki.python.org/moin/Audio/ > > 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 > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From tim at johnsons-web.com Sat Sep 6 00:42:20 2008 From: tim at johnsons-web.com (Tim Johnson) Date: Fri, 5 Sep 2008 14:42:20 -0800 Subject: [Tutor] Sending email as html Message-ID: <200809051442.20884.tim@johnsons-web.com> Greetings: I've been using smtplib for years to send plain text emails programmatically. Now I have a customer who is requesting that I (at least) investigate sending invoices by email as html. I would appreciate examples, URLs to documentation or discussions of the topic and even an argument to the contrary of sending email with embedded html. Thanks Tim From alan.gauld at btinternet.com Sat Sep 6 01:17:43 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 6 Sep 2008 00:17:43 +0100 Subject: [Tutor] Sending email as html References: <200809051442.20884.tim@johnsons-web.com> Message-ID: "Tim Johnson" wrote > I would appreciate examples, URLs to documentation or discussions of > the topic > and even an argument to the contrary of sending email with embedded > html. The argument to the contrary is simple enough - its not secure and vulnerable to 'virus' type attack. For that reason many corporate firewalls trap or even prevent its delivery. (This is due to the ability to embed script tags with VBScript functions that on a suitably enabled PVC can access the local hard drive, etc) OTOH if they insist I assume(I've never looked at the spec for HTML mail) that its just a case of inserting a boilerplate header and then adding styling tags to the message text. After that you should be able to send as plain text... However it might be easier (and is definitely safer) to send an HTML file as a mime attachment which gives the recipient some control over how/when it is opened. But if mime is OK you could use PDF which is safer still and the best format for when accurate layout needs to be transmitted in a portable format. Unfortunately there are now programs which can edit PDFs which has somewhat destroyed their value as a read-only document format for contracts, invoices etc... But for portable layout they are still the best option. Alan G. From tedroche at gmail.com Sat Sep 6 02:03:30 2008 From: tedroche at gmail.com (Ted Roche) Date: Fri, 5 Sep 2008 20:03:30 -0400 Subject: [Tutor] Sending email as html In-Reply-To: <200809051442.20884.tim@johnsons-web.com> References: <200809051442.20884.tim@johnsons-web.com> Message-ID: On Fri, Sep 5, 2008 at 6:42 PM, Tim Johnson wrote: > > I've been using smtplib for years to send plain text emails programmatically. > Now I have a customer who is requesting that I (at least) investigate sending > invoices by email as html. I'm a big fan of sending invoices as PDFs. The invoices can have as rich text and graphics as you want, print well, and work cross-platform. > I would appreciate examples, URLs to documentation or discussions of the topic > and even an argument to the contrary of sending email with embedded html. Google "HTML Email is Evil" for a pretty succinct summary. -- Ted Roche Ted Roche & Associates, LLC http://www.tedroche.com From tim at johnsons-web.com Sat Sep 6 02:30:27 2008 From: tim at johnsons-web.com (Tim Johnson) Date: Fri, 5 Sep 2008 16:30:27 -0800 Subject: [Tutor] Sending email as html In-Reply-To: References: <200809051442.20884.tim@johnsons-web.com> Message-ID: <200809051630.27749.tim@johnsons-web.com> On Friday 05 September 2008, Alan Gauld wrote: <...> > The argument to the contrary is simple enough - its not secure and > vulnerable to 'virus' type attack. For that reason many corporate > firewalls > trap or even prevent its delivery. (This is due to the ability to > embed > script tags with VBScript functions that on a suitably enabled PVC > can access the local hard drive, etc) Sounds like nothing much has changed in 5 years. I did a project like this in 1993 with another programming language despite my reservations and had the client sign a "Hold Harmless" doc before I proceeded. > OTOH if they insist I assume(I've never looked at the spec for HTML > mail) > that its just a case of inserting a boilerplate header and then adding > styling > tags to the message text. After that you should be able to send as > plain text... I've already looked at some recipes that send both html and text as an alternative.... there's one at http://code.activestate.com/recipes/67083/ > However it might be easier (and is definitely safer) to send an HTML > file as a mime attachment which gives the recipient some control over > how/when it is opened. But if mime is OK you could use PDF which > is safer still and the best format for when accurate layout needs to > be transmitted in a portable format. Unfortunately there are now > programs which can edit PDFs which has somewhat destroyed > their value as a read-only document format for contracts, invoices I'm inclined to encourage the client to spend his money on something else :-) Thanks as always, Alan From tim at johnsons-web.com Sat Sep 6 03:23:41 2008 From: tim at johnsons-web.com (Tim Johnson) Date: Fri, 5 Sep 2008 17:23:41 -0800 Subject: [Tutor] Sending email as html In-Reply-To: <200809051630.27749.tim@johnsons-web.com> References: <200809051442.20884.tim@johnsons-web.com> <200809051630.27749.tim@johnsons-web.com> Message-ID: <200809051723.41848.tim@johnsons-web.com> On Friday 05 September 2008, Tim Johnson wrote: > Sounds like nothing much has changed in 5 years. I did a project like > this in 1993 with another programming language despite my reservations > and had the client sign a "Hold Harmless" doc before I proceeded. Erratum: Should have 2003, not 1993 My apologies. tj From kent37 at tds.net Sat Sep 6 03:40:07 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 5 Sep 2008 21:40:07 -0400 Subject: [Tutor] Sending email as html In-Reply-To: <200809051630.27749.tim@johnsons-web.com> References: <200809051442.20884.tim@johnsons-web.com> <200809051630.27749.tim@johnsons-web.com> Message-ID: <1c2a2c590809051840w6ced776bpbedd25a8cb78b6e6@mail.gmail.com> On Fri, Sep 5, 2008 at 8:30 PM, Tim Johnson wrote: > On Friday 05 September 2008, Alan Gauld wrote: > <...> >> The argument to the contrary is simple enough - its not secure and >> vulnerable to 'virus' type attack. For that reason many corporate >> firewalls >> trap or even prevent its delivery. Given that MS Outlook sends HTML mail, I find that quite surprising. > I've already looked at some recipes that send both html and > text as an alternative.... there's one at > http://code.activestate.com/recipes/67083/ That looks about right - a multipart MIME body with both text/plain and text/html sections. Kent From tim at johnsons-web.com Sat Sep 6 04:33:28 2008 From: tim at johnsons-web.com (Tim Johnson) Date: Fri, 5 Sep 2008 18:33:28 -0800 Subject: [Tutor] Sending email as html In-Reply-To: <1c2a2c590809051840w6ced776bpbedd25a8cb78b6e6@mail.gmail.com> References: <200809051442.20884.tim@johnsons-web.com> <200809051630.27749.tim@johnsons-web.com> <1c2a2c590809051840w6ced776bpbedd25a8cb78b6e6@mail.gmail.com> Message-ID: <200809051833.28303.tim@johnsons-web.com> On Friday 05 September 2008, Kent Johnson wrote: > On Fri, Sep 5, 2008 at 8:30 PM, Tim Johnson wrote: > > On Friday 05 September 2008, Alan Gauld wrote: > > <...> > > > >> The argument to the contrary is simple enough - its not secure and > >> vulnerable to 'virus' type attack. For that reason many corporate > >> firewalls > >> trap or even prevent its delivery. > > Given that MS Outlook sends HTML mail, I find that quite surprising. Since 2001, I've worked in primarily in a linux environment. I use kmail. When I receive an email in HTML format, kmail presents the content as "raw" text and then gives me the option to then format the email into its intended "look and feel". thanks tim > > I've already looked at some recipes that send both html and > > text as an alternative.... there's one at > > http://code.activestate.com/recipes/67083/ > > That looks about right - a multipart MIME body with both text/plain > and text/html sections. > > Kent > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From john at fouhy.net Sat Sep 6 04:40:09 2008 From: john at fouhy.net (John Fouhy) Date: Sat, 6 Sep 2008 14:40:09 +1200 Subject: [Tutor] Need help with Factorial algorithm using Python In-Reply-To: References: <48BFE9AF.4000309@embarqmail.com> Message-ID: <5e58f2e40809051940q1ad4a865i6cae661fa589045a@mail.gmail.com> 2008/9/5 Terry Carroll : > So here's my routine to address the problem. It consists of making a > multiplication table of coefficients that includes the factor such as 5, > 25, 125, etc., and their values (1, 6, 31, etc). Then, starting with the > highest ones first, successievely determining how many times each factor > goes into the number of zeroes. For example, to do the prior example > working backwards, what factorial will give you 71 zeroes? I think there is a simpler solution :-) You can count the number of fives in the prime decomposition of a number by just dividing by 5 repeatedly until you don't get a whole number. You can then find n such that n! has x zeroes by just starting with n=0 and counting up, adding the appropriate amount at each step. Code: from __future__ import division import operator def fac(n): """ Return n! """ return reduce(operator.mul, range(1, n+1)) def zeroes(n): """ Count number of zeroes in n! """ f = fac(n) return len(str(f))-len(str(f).rstrip('0')) def fives(n): """ Count number of 5s in prime factor decomposition of n. """ i = 0 while (n/5) == (n//5): # note future division in effect i += 1 n = n//5 return i def zeroes_inv(x): """ Return n such that zeroes(n) == x. """ i = 0 count = 0 while count < x: i += 5 count += fives(i) return i Although I am curious to know how long it took your algorithm to find the answer for 7**20 ... -- John. From jfabiani at yolo.com Sat Sep 6 05:19:47 2008 From: jfabiani at yolo.com (johnf) Date: Fri, 5 Sep 2008 20:19:47 -0700 Subject: [Tutor] Sending email as html In-Reply-To: References: <200809051442.20884.tim@johnsons-web.com> Message-ID: <200809052019.47764.jfabiani@yolo.com> On Friday 05 September 2008 05:03:30 pm Ted Roche wrote: > On Fri, Sep 5, 2008 at 6:42 PM, Tim Johnson wrote: > > I've been using smtplib for years to send plain text emails > > programmatically. Now I have a customer who is requesting that I (at > > least) investigate sending invoices by email as html. > > I'm a big fan of sending invoices as PDFs. The invoices can have as > rich text and graphics as you want, print well, and work > cross-platform. > > > I would appreciate examples, URLs to documentation or discussions of the > > topic and even an argument to the contrary of sending email with embedded > > html. > > Google "HTML Email is Evil" for a pretty succinct summary. To expand on what Ted has suggested you can use ghostscript to create the PDF's on windows, linux and Mac. I have been doing it from VFP (Visual FoxPro) programs and from python for years. The invoices look very professional and are just added to the email as an attachment. -- John Fabiani From carroll at tjc.com Sat Sep 6 06:50:39 2008 From: carroll at tjc.com (Terry Carroll) Date: Fri, 5 Sep 2008 21:50:39 -0700 (PDT) Subject: [Tutor] Need help with Factorial algorithm using Python In-Reply-To: <5e58f2e40809051940q1ad4a865i6cae661fa589045a@mail.gmail.com> Message-ID: On Sat, 6 Sep 2008, John Fouhy wrote: > 2008/9/5 Terry Carroll : > > So here's my routine to address the problem. It consists of making a > > multiplication table of coefficients that includes the factor such as 5, > > 25, 125, etc., and their values (1, 6, 31, etc). Then, starting with the > > highest ones first, successievely determining how many times each factor > > goes into the number of zeroes. For example, to do the prior example > > working backwards, what factorial will give you 71 zeroes? > > I think there is a simpler solution :-) Definitely, but most require calculating the factorial first, and for large factorials, that going to be a huge computational burden. > You can count the number of fives in the prime decomposition of a > number by just dividing by 5 repeatedly until you don't get a whole > number. But that requires having the number first, doesn't it? In other words, don't you have to calculate N! in order to find out how many terminal zeroes N! has? The method I proposed determines the number of terminal zeroes in N! by examination of N, without calculating N!, which is a substantial computational savings when N is large; and in fact, makes the problem tractable for large values of N. > Although I am curious to know how long it took your algorithm to find > the answer for 7**20 ... Under a second. In a trial, I put "print time.asctime()" before and after the calculation, and it printed the same time in both print statements. How much under a second, I'm not sure. From carroll at tjc.com Sat Sep 6 07:02:20 2008 From: carroll at tjc.com (Terry Carroll) Date: Fri, 5 Sep 2008 22:02:20 -0700 (PDT) Subject: [Tutor] Need help with Factorial algorithm using Python In-Reply-To: Message-ID: On Fri, 5 Sep 2008, Terry Carroll wrote: > On Sat, 6 Sep 2008, John Fouhy wrote: > > > You can count the number of fives in the prime decomposition of a > > number by just dividing by 5 repeatedly until you don't get a whole > > number. > > But that requires having the number first, doesn't it? In other words, > don't you have to calculate N! in order to find out how many terminal > zeroes N! has? Ah, never mind, I took a closer look at your code. We're on a very similar tracks. But the number of divisions you do scales up substantially for very large numbers. By working with successive powers of 5 instead, you would only need to do log(N,5) divmods; for N=7*20: >>> math.log(7**20,5) 24.181239102443353 Only 25 divmods; then, of course, 25 multiplications to calculate the actual zero count. From lie.1296 at gmail.com Sat Sep 6 07:12:08 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 06 Sep 2008 12:12:08 +0700 Subject: [Tutor] Sending email as html In-Reply-To: References: Message-ID: <1220677928.9220.5.camel@lieryan-laptop> > Message: 3 > Date: Sat, 6 Sep 2008 00:17:43 +0100 > From: "Alan Gauld" > Subject: Re: [Tutor] Sending email as html > To: tutor at python.org > Message-ID: > Content-Type: text/plain; format=flowed; charset="iso-8859-1"; > reply-type=original > > "Tim Johnson" wrote > > > I would appreciate examples, URLs to documentation or discussions > of > > the topic > > and even an argument to the contrary of sending email with embedded > > html. > > The argument to the contrary is simple enough - its not secure and > vulnerable to 'virus' type attack. For that reason many corporate > firewalls > trap or even prevent its delivery. (This is due to the ability to > embed > script tags with VBScript functions that on a suitably enabled PVC > can access the local hard drive, etc) > > OTOH if they insist I assume(I've never looked at the spec for HTML > mail) > that its just a case of inserting a boilerplate header and then > adding > styling > tags to the message text. After that you should be able to send as > plain text... > > However it might be easier (and is definitely safer) to send an HTML > file as a mime attachment which gives the recipient some control over > how/when it is opened. But if mime is OK you could use PDF which > is safer still and the best format for when accurate layout needs to > be transmitted in a portable format. Unfortunately there are now > programs which can edit PDFs which has somewhat destroyed > their value as a read-only document format for contracts, invoices > etc... If you have used tried using any PDF editor for more than correcting typos, you'd still consider it as a read-only document. Since PDF's file isn't intended to be edited the format makes it hard for editors to have a convenient interface, most significantly is that texts are chopped and tables are turned into lines. It's just like erasing a form with a correction fluid "a kludge". > But for portable layout they are still the best option. > > Alan G. > From alan.gauld at btinternet.com Sat Sep 6 09:57:41 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 6 Sep 2008 08:57:41 +0100 Subject: [Tutor] Sending email as html References: <1220677928.9220.5.camel@lieryan-laptop> Message-ID: "Lie Ryan" wrote >> programs which can edit PDFs which has somewhat destroyed >> their value as a read-only document format for contracts, invoices >> etc... > > If you have used tried using any PDF editor for more than correcting > typos, you'd still consider it as a read-only document. True. but for contracts or invoices just changing a 1 to a 7 or vice versa can make a big difference to the money owed! And very little difference to the layout. Alan G From gew75 at hotmail.com Sat Sep 6 11:10:26 2008 From: gew75 at hotmail.com (Glen Wheeler) Date: Sat, 6 Sep 2008 19:10:26 +1000 Subject: [Tutor] Sending email as html References: <1220677928.9220.5.camel@lieryan-laptop> Message-ID: From: "Alan Gauld" > > "Lie Ryan" wrote > >>> programs which can edit PDFs which has somewhat destroyed >>> their value as a read-only document format for contracts, invoices >>> etc... >> >> If you have used tried using any PDF editor for more than correcting >> typos, you'd still consider it as a read-only document. > > True. but for contracts or invoices just changing a 1 to a 7 or vice > versa can make a big difference to the money owed! And very > little difference to the layout. > Well if it's just a matter of changing one digit this isn't so hard, since PDF files are not very hard to edit with a simple text editor. (Never have really.) From imputerate at puteracy.com Sat Sep 6 09:58:47 2008 From: imputerate at puteracy.com (peter hodgson) Date: Sat, 06 Sep 2008 02:58:47 -0500 Subject: [Tutor] Replace sequence in list - looking for direction Message-ID: <8763p97ljc.fsf@puteracy.com> greetings, fellow ventriloquists; the exchanges on this list are great tutorials; sometimes i don't quite get the finer points; like here: On Mon, Jun 16, 2008 at 10:41 AM, GTXY20 wrote: > Let's say I have a list like the following: > > a = ['a1','a2','a3','a4','a5','a6'] > > and then I have dictionary like the following: > > b = {'a1,a2,a3':'super'} > > I need some direction and thoughts on how I might seach the list for the > string (the key in dict b) sequence in list a and replace the occurance with > the value from dict b. At the end I would like to have list a represented > as: > > a = ['super', 'a4', 'a5', 'a6'] the solution: From: Tiago Saboga The following works for your example. I assume the values in the a list are unique. for key in b: keylist = key.split(',') if keylist < a: i = a.index(keylist[0]) print a[:i] + [b[key]] + a[i+len(keylist):] --------------------- but this works, too; >>> a = ['a1','a2','a3','a4','a5','a6'] >>> b = {'a1,a2,a3':'super'} >>> for key in b: ... keylist = key.split(',') ... i = a.index(keylist[0]) ... print [b[key]] + a[i+len(keylist):] ... ['super', 'a4', 'a5', 'a6'] ----------------------- now, i get it, mostly; but keylist being shorter than the list "a" >>> keylist < a True doesn't seem relevant, unless the 'for' statement were to go on and on; and if a[:i] = zilch: >>> for key in b: ... keylist = key.split(',') ... if keylist < a: # DOES THIS MEAN LENGTH? ... i = a.index(keylist[0]) # a[index of first item in the key == 0]; ... print a[:i] # a[:0] == pre-first item == None; ... [] then why bother with that part? --------------------------------- finally, how might the code handle a dictionary with more than one item? since i figured the line if keylist < a: might be part of some kind of iteration, say, until all of the items in "a" had been replaced by dictionary values, this is as far as i got: >>> a = ['a','b','c','d','e','f'] >>> b = {'a,b':'firstval', 'c,d':'secondval'} >>> for key in b: ... keylist = key.split(',') ... if keylist < a: ... i = a.index(keylist[0]) ... print a[:i] + [b[key]] + a[i+len(keylist):] ... ['firstval', 'c', 'd', 'e', 'f'] but 'secondval' did not replace 'c' and 'd' in "a"; what am i missing? thanks, imputerate From johan at accesstel.com.au Sat Sep 6 08:42:15 2008 From: johan at accesstel.com.au (Johan Geldenhuys) Date: Sat, 6 Sep 2008 16:42:15 +1000 Subject: [Tutor] Support for datetime module Message-ID: <20080906064240.FETN1865.nschwotgx02p.mx.bigpond.com@JohanPC> Hi all, I have want to use the datetime module on a system with ver 2.2.3 installed. I know it's very old, but that's what I have to deal with and can't upgrade. So please don't suggest that. As you know datetime was available from version 2.3. I want to know where can I get the datetime module so that I can include it in my package that I use on my device? I looked on the Internet but can't find it. So if anybody can give me a link to get the module, I'll be very thankful, Regards Johan -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Sat Sep 6 15:08:00 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 6 Sep 2008 09:08:00 -0400 Subject: [Tutor] Support for datetime module In-Reply-To: <20080906064240.FETN1865.nschwotgx02p.mx.bigpond.com@JohanPC> References: <20080906064240.FETN1865.nschwotgx02p.mx.bigpond.com@JohanPC> Message-ID: <1c2a2c590809060608te12e23bp5e63305ec4be2a4f@mail.gmail.com> On Sat, Sep 6, 2008 at 2:42 AM, Johan Geldenhuys wrote: > Hi all, > > I have want to use the datetime module on a system with ver 2.2.3 installed. > I know it's very old, but that's what I have to deal with and can't upgrade. > So please don't suggest that. > > As you know datetime was available from version 2.3. > > > > I want to know where can I get the datetime module so that I can include it > in my package that I use on my device? datetime is implemented in C so getting the version from 2.3 to work on 2.2 might be difficult. Apparently the version in the std lib is derived from a Python version that was part of Zope, this might be helpful if you can find the source it refers to: http://www.zope.org/Members/fdrake/DateTimeWiki/FrontPage Kent From roybayot at gmail.com Sat Sep 6 16:09:57 2008 From: roybayot at gmail.com (Roy Khristopher Bayot) Date: Sat, 6 Sep 2008 22:09:57 +0800 Subject: [Tutor] how do you make this a better code? In-Reply-To: <1c2a2c590809041842h52aca4e6u95645f9949deb6c1@mail.gmail.com> References: <5e6459540809041800v10c25acr6d42a4a63c12a837@mail.gmail.com> <1c2a2c590809041842h52aca4e6u95645f9949deb6c1@mail.gmail.com> Message-ID: <5e6459540809060709i797dfd13n3912207e582d9acf@mail.gmail.com> Hi. I tried it. It worked. Thank you. On Fri, Sep 5, 2008 at 9:42 AM, Kent Johnson wrote: > On Thu, Sep 4, 2008 at 9:00 PM, Roy Khristopher Bayot > wrote: > > > class CamHandle(object): > > def __init__(self): > > import os > > w = os.system('gphoto2 --auto-detect > CamHandleLog.txt') > > test = os.system('gphoto2 --capture-image >> CamHandleLog.txt') > > > > def captureImage(self): > > import os > > x = os.system('gphoto2 --capture-image >> CamHandleLog.txt') > > > > Now when I import the file to the interpreter and instantiate the class, > it > > works. Each function works. I havent done any error handling or exception > > handling yet but it works for now. However, I am bothered with the import > > statements in each function. > > The usual method is to put the import statement at the beginning of > the module. Then the imported module has global (module) scope rather > than function scope. > > Kent > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Sep 6 16:10:42 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 6 Sep 2008 15:10:42 +0100 Subject: [Tutor] Replace sequence in list - looking for direction References: <8763p97ljc.fsf@puteracy.com> Message-ID: "peter hodgson" wrote >> for key in b: >> keylist = key.split(',') >> if keylist < a: >> i = a.index(keylist[0]) >> print a[:i] + [b[key]] + a[i+len(keylist):] > > now, i get it, mostly; but keylist being shorter than the list "a" > >>>> keylist < a > True This is not testing the length it is testing the contents. >>> a = ['a','c','e'] >>> b = ['b','d','f'] >>> a>> b>> c = ['a','b','c'] >>> c>> d = ['a','c'] >>> d>> d>> So d winds over a since the third element not existing is taken to be lower valued than it existing. But the character values in d<1220677928.9220.5.camel@lieryan-laptop> Message-ID: "Glen Wheeler" wrote >>> If you have used tried using any PDF editor for more than >>> correcting >>> typos, you'd still consider it as a read-only document. >> >> True. but for contracts or invoices just changing a 1 to a 7 or >> vice >> versa can make a big difference to the money owed! And very >> little difference to the layout. > Well if it's just a matter of changing one digit this isn't so > hard, since PDF files are not very hard to edit with a simple text > editor. (Never have That's true if you understand the PDF format but its non trivial and way beyond most computer users. But PDF has never been absolutely secure, just better than Word documents or plain text. If you really want to check that the doc has not been altered you need to use digital signing or similar. PDF is just a discouragement. Alan G. From tim at johnsons-web.com Sat Sep 6 17:35:06 2008 From: tim at johnsons-web.com (Tim Johnson) Date: Sat, 6 Sep 2008 07:35:06 -0800 Subject: [Tutor] Sending email as html In-Reply-To: References: Message-ID: <200809060735.06213.tim@johnsons-web.com> On Saturday 06 September 2008, Glen Wheeler wrote: > From: "Alan Gauld" > > > "Lie Ryan" wrote > > > >>> programs which can edit PDFs which has somewhat destroyed > >>> their value as a read-only document format for contracts, invoices > >>> etc... > >> > >> If you have used tried using any PDF editor for more than correcting > >> typos, you'd still consider it as a read-only document. > > > > True. but for contracts or invoices just changing a 1 to a 7 or vice > > versa can make a big difference to the money owed! And very > > little difference to the layout. > > Well if it's just a matter of changing one digit this isn't so hard, > since PDF files are not very hard to edit with a simple text editor. > (Never have really.) Looks like I could make up a PDF template and then put substitutions into it. thanks tim From roybayot at gmail.com Sat Sep 6 18:04:12 2008 From: roybayot at gmail.com (Roy Khristopher Bayot) Date: Sun, 7 Sep 2008 00:04:12 +0800 Subject: [Tutor] Need help with using methods in a base class Message-ID: <5e6459540809060904y578e5e06g4f38d81cd03153d1@mail.gmail.com> Hi. I am having some difficulty using methods from a base class. I have 2 classes. The first one is Parallel which is inside the module parallel. The methods useful to me from this class are setDataStrobe(), setAutoFeed(), setInitOut(), setSelect(), and setData(). The second one is derived from the first. I called it LightsHandle. The code and traceback is written below: >>> import parallel >>> class LightsHandle(parallel.Parallel): ... def __init__(self): ... pass ... def setData(self, data): ... Parallel.setData(data) ... def setLatch(self, latch): ... Parallel.setDataStrobe(int(latch[0])) ... Parallel.setAutoFeed(int(latch[1])) ... Parallel.setInitOut(int(latch[2])) ... def generateClockPulse(self): ... Parallel.setSelect(0) ... Parallel.setSelect(1) ... >>> a = LightsHandle() >>> a.setData(0xF0) Traceback (most recent call last): File "", line 1, in File "", line 5, in setData NameError: global name 'Parallel' is not defined So I tried another one. And the code and traceback is written below. >>> import parallel >>> class LightsHandle(parallel.Parallel): ... def __init__(self): ... pass ... def setD(self, data): ... parallel.Parallel.setData(data) ... def setLatch(self, latch): ... parallel.Parallel.setDataStrobe(int(latch[0])) ... parallel.Parallel.setAutoFeed(int(latch[1])) ... parallel.Parallel.setInitOut(int(latch[2])) ... def generateClockPulse(self): ... parallel.Parallel.setSelect(0) ... parallel.Parallel.setSelect(1) ... >>> a = LightsHandle() >>> a.setD(0xF0) Traceback (most recent call last): File "", line 1, in File "", line 5, in setD TypeError: unbound method setData() must be called with Parallel instance as first argument (got int instance instead) (Some notes: I changed setData() to setD() so that there wont be a confusion. Method setData() is from the base class Parallel. Although I think setData() could be overriden.) What have I been doing wrong? Why does it say that I need a Parallel instance? According to http://www.python.org/doc/2.5/tut/node11.html#SECTION0011340000000000000000 "There is a simple way to call the base class method directly: just call "BaseClassName.methodname(self, arguments)". This is occasionally useful to clients as well. (Note that this only works if the base class is defined or imported directly in the global scope.) " Do I have a problem in scope? How can I resolve it? Thank you and have a nice day. ^_^ -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Sat Sep 6 20:49:20 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 6 Sep 2008 14:49:20 -0400 Subject: [Tutor] Need help with using methods in a base class In-Reply-To: <5e6459540809060904y578e5e06g4f38d81cd03153d1@mail.gmail.com> References: <5e6459540809060904y578e5e06g4f38d81cd03153d1@mail.gmail.com> Message-ID: <1c2a2c590809061149n51dcf71fk242b6a866fd4753b@mail.gmail.com> On Sat, Sep 6, 2008 at 12:04 PM, Roy Khristopher Bayot wrote: > Hi. I am having some difficulty using methods from a base class. > > I have 2 classes. The first one is Parallel which is inside the module > parallel. The methods useful to me from this class are setDataStrobe(), > setAutoFeed(), setInitOut(), setSelect(), and setData(). > > The second one is derived from the first. I called it LightsHandle. The code > and traceback is written below: > >>>> import parallel >>>> class LightsHandle(parallel.Parallel): > ... def __init__(self): > ... pass > ... def setData(self, data): > ... Parallel.setData(data) > ... def setLatch(self, latch): > ... Parallel.setDataStrobe(int(latch[0])) > ... Parallel.setAutoFeed(int(latch[1])) > ... Parallel.setInitOut(int(latch[2])) > ... def generateClockPulse(self): > ... Parallel.setSelect(0) > ... Parallel.setSelect(1) > ... >>>> a = LightsHandle() >>>> a.setData(0xF0) > Traceback (most recent call last): > File "", line 1, in > File "", line 5, in setData > NameError: global name 'Parallel' is not defined This error is because you did not import Parallel, you imported parallel. You have to use the full name parallel.Parallel as you figured out. You could also use from parallel import Parallel and then just refer to Parallel. > So I tried another one. And the code and traceback is written below. > >>>> import parallel >>>> class LightsHandle(parallel.Parallel): > ... def __init__(self): > ... pass > ... def setD(self, data): > ... parallel.Parallel.setData(data) > ... def setLatch(self, latch): > ... parallel.Parallel.setDataStrobe(int(latch[0])) > ... parallel.Parallel.setAutoFeed(int(latch[1])) > ... parallel.Parallel.setInitOut(int(latch[2])) > ... def generateClockPulse(self): > ... parallel.Parallel.setSelect(0) > ... parallel.Parallel.setSelect(1) > ... >>>> a = LightsHandle() >>>> a.setD(0xF0) > Traceback (most recent call last): > File "", line 1, in > File "", line 5, in setD > TypeError: unbound method setData() must be called with Parallel instance as > first argument (got int instance instead) > > (Some notes: I changed setData() to setD() so that there wont be a > confusion. Method setData() is from the base class Parallel. Although I > think setData() could be overriden.) > > What have I been doing wrong? Why does it say that I need a Parallel > instance? > > According to > http://www.python.org/doc/2.5/tut/node11.html#SECTION0011340000000000000000 > > "There is a simple way to call the base class method directly: just call > "BaseClassName.methodname(self, arguments)". This is occasionally useful to > clients as well. (Note that this only works if the base class is defined or > imported directly in the global scope.) " This quote has the answer to your question. When you call the base class method, you have to explicitly provide the self parameter, e.g. parallel.Parallel.setData(self, data) Kent From alan.gauld at btinternet.com Sat Sep 6 23:59:18 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 6 Sep 2008 22:59:18 +0100 Subject: [Tutor] Sending email as html References: <200809060735.06213.tim@johnsons-web.com> Message-ID: "Tim Johnson" wrote >> since PDF files are not very hard to edit with a simple text >> editor. >> (Never have really.) > Looks like I could make up a PDF template and then put substitutions You could although they are not pure text files so you may need to use binary mode to edit the file I think. There is an interersting looking link here: http://www.python.org/workshops/2002-02/papers/17/index.htm HTH, Alan G From alan.gauld at btinternet.com Sun Sep 7 00:07:21 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 6 Sep 2008 23:07:21 +0100 Subject: [Tutor] Need help with using methods in a base class References: <5e6459540809060904y578e5e06g4f38d81cd03153d1@mail.gmail.com> Message-ID: "Roy Khristopher Bayot" wrote > ... def generateClockPulse(self): > ... parallel.Parallel.setSelect(0) > ... parallel.Parallel.setSelect(1) > ... >>>> a = LightsHandle() >>>> a.setD(0xF0) > Traceback (most recent call last): > File "", line 1, in > File "", line 5, in setD > TypeError: unbound method setData() must be called with Parallel > instance as > first argument (got int instance instead) The error merssage gives the clue. Sonce you are calling a method on a classs not an object you need to pass in the instance reference explicitly. Its exactly as in calling the base constructor in __init__ class C(P): def __init__(self): P.__init__(self) # need to pass self here > (Some notes: I changed setData() to setD() so that there wont be a > confusion. Method setData() is from the base class Parallel. > Although I > think setData() could be overriden.) Thats not necessary, each class creates its owen namespace. > What have I been doing wrong? Why does it say that I need a Parallel > instance? Because the class needs to know where to find the instance variables. Since you are calling the class directly, not via an instance you have to pass self explicitly. Remember that in class C: def m(self, x): print x c = C(42) Then c.m() is the same as C.m(c,42). self takes on the value of the instance in the first case but in the second you have to pass it directly. When you are inside a methiod you always use the second form so you always need to pass self. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From arsyed at gmail.com Sun Sep 7 02:10:47 2008 From: arsyed at gmail.com (arsyed) Date: Sat, 6 Sep 2008 20:10:47 -0400 Subject: [Tutor] Problems starting python In-Reply-To: References: Message-ID: <9a2cc7a70809061710o1e759b2cu57fa5cf5580e564b@mail.gmail.com> On Fri, Sep 5, 2008 at 6:28 AM, Linus Lindstr?m wrote: > Hello. When i first installed python from the cd i bought it seemed to work > perfectly... But then when i cancel the program and try to start it again I > get the message: "IDLE's subprocess didn't make connection. Either IDLE > can't start a subprocess or a personal firewall software is blocking the > connection.", and the problem still stands... I've tried to completely shut > down my firewall but without success... Please help me! A little googling reveals a possible fix below; I'm not sure I get it though. If this fails, you can try running idle with the "-n" flag, which avoids running a subprocess. --- from http://www.cs.sfu.ca/CC/CSILPC/kip.html#s2-20 IDLE (Python GUI) won't start! What should I do? Sometimes when IDLE starts, it prompts the following error message: Subprocess Startup Error: IDLE's subprocess didn't make connection. Either IDLE can't start a subprocess or personal firewall software is blocking the connection. Here is the workaround (a fix is under research): * launch Windows Explorer * find (or create) a file with .py extension * right click this file, select "Edit with IDLE" Now, the IDLE (Python GUI) should start. From jfabiani at yolo.com Sun Sep 7 03:49:39 2008 From: jfabiani at yolo.com (johnf) Date: Sat, 6 Sep 2008 18:49:39 -0700 Subject: [Tutor] ftplib.storbinary and using a progress bar Message-ID: <200809061849.39760.jfabiani@yolo.com> Hi, I'm currently using ftplib.storbinary() to upload a file to a FTP server. However, I would like to inform the user of the progress being made during the file transfer (it could be a very long transfer). But ftplib.storbinary() has no callback like retrbinary() so does anyone have a thought on how I can update my user on the progress of the transfer. BTW I have to use a binary transfer because the file being transfer is not text. -- John Fabiani From carroll at tjc.com Sun Sep 7 06:20:30 2008 From: carroll at tjc.com (Terry Carroll) Date: Sat, 6 Sep 2008 21:20:30 -0700 (PDT) Subject: [Tutor] ftplib.storbinary and using a progress bar In-Reply-To: <200809061849.39760.jfabiani@yolo.com> Message-ID: On Sat, 6 Sep 2008, johnf wrote: > I'm currently using ftplib.storbinary() to upload a file to a FTP server. > However, I would like to inform the user of the progress being made during > the file transfer (it could be a very long transfer). But > ftplib.storbinary() has no callback like retrbinary() so does anyone have a > thought on how I can update my user on the progress of the transfer. Callbacks are being added in 2.6, and are in the 2.6 source now. You can download the current version of ftplib at http://svn.python.org/view/python/trunk/Lib/ftplib.py?rev=63788&view=log When I do something along these lines, I save it (usually under the local directory of the python program that uses it) under a modified name, i.e. "ftplib26.py" or "myftplib.py"; then import with: import ftplib26 as ftplib From alan.gauld at btinternet.com Sun Sep 7 10:13:17 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 7 Sep 2008 09:13:17 +0100 Subject: [Tutor] ftplib.storbinary and using a progress bar References: <200809061849.39760.jfabiani@yolo.com> Message-ID: "johnf" wrote > the file transfer (it could be a very long transfer). But > ftplib.storbinary() has no callback like retrbinary() so does anyone > have a > thought on how I can update my user on the progress of the transfer. If you don't fancy getting the 2.6 source as Terry suggested then the other way to do this kind of thing is with a separate thread. Start the new thread which just displays a progress bar (you need to find how big the file is before hand and check progress as you go too) Then in the main thread run the transfer and terminate the progress thread when you finish. How easy this is depends on your familiarity with threads I guess! As threading goes its a fairly straighforward use. Alan G. From Jaggojaggo+Py at gmail.com Sun Sep 7 11:25:23 2008 From: Jaggojaggo+Py at gmail.com (Omer) Date: Sun, 7 Sep 2008 12:25:23 +0300 Subject: [Tutor] Online Scripting Message-ID: <515008f10809070225n289c255cmf02539bbfb63a6c9@mail.gmail.com> Hello. I started a project with a goal: To have a script "read" an entire message board, dedicated to various events, process this information into an iCalendar file, and finally- base a Google Calendar on the iCal file. Now, The script is done and it works great on my desktop. The problem is, seeing as I plan this a sort of a service for the forum people, It can't be based off of my desktop, which is only available 5 ~ 6 days a week. So, Has anyone a clue as to where might I host my script, so's A: the host "runs" my script periodical (Once every Two hours? If I can configure it to only run during the day than that's even better), and B: The host lets my script create an iCal file (a single, <1MB file) and C: lets GCal have access to this file. I've looked Google App Engine. It's a huge effort: First remodeling my script to use the GAE way of opening urls, to use the GAE way of storing information, and I haven't as yet even looked into how do I store the prepared iCal file, or how do I schedule the runs of my script. The need to learn an entire platform, (Although I do plan to learn it someday), is too large for me now. (Although, if there's no choice that's what I'll do.) Sorry about this message's length, Help will be appreciated, thank you for your time. Omer. -------------- next part -------------- An HTML attachment was scrubbed... URL: From johan at accesstel.com.au Sun Sep 7 12:17:56 2008 From: johan at accesstel.com.au (Johan Geldenhuys) Date: Sun, 7 Sep 2008 20:17:56 +1000 Subject: [Tutor] Support for datetime module In-Reply-To: <1c2a2c590809060608te12e23bp5e63305ec4be2a4f@mail.gmail.com> Message-ID: <20080907101829.BNZE11041.nschwotgx03p.mx.bigpond.com@JohanPC> Thanks Kent, Let me explain what I need it for. I have a systemUpTime is seconds that I got from a SNMP agent. I want to work out when the system uptime began and want to put that in ISO format time to the millisecond. So my idea is to take a timestamp in seconds when I get the systemUpTime. I subtract the uptime from my timestamp and then format that into ISO format. That should give me a fairly accurate UTC-like time of when the systemUpTime began. Here is an example: "2008-09-04 22:29:43.221 Z" Do you think it will be difficult to work this out with the datetime module? Any suggestion would be greatly appreciated. Thanks Johan -----Original Message----- From: kent3737 at gmail.com [mailto:kent3737 at gmail.com] On Behalf Of Kent Johnson Sent: Saturday, 6 September 2008 23:08 PM To: johan at accesstel.com.au Cc: tutor at python.org Subject: Re: [Tutor] Support for datetime module On Sat, Sep 6, 2008 at 2:42 AM, Johan Geldenhuys wrote: > Hi all, > > I have want to use the datetime module on a system with ver 2.2.3 installed. > I know it's very old, but that's what I have to deal with and can't upgrade. > So please don't suggest that. > > As you know datetime was available from version 2.3. > > > > I want to know where can I get the datetime module so that I can include it > in my package that I use on my device? datetime is implemented in C so getting the version from 2.3 to work on 2.2 might be difficult. Apparently the version in the std lib is derived from a Python version that was part of Zope, this might be helpful if you can find the source it refers to: http://www.zope.org/Members/fdrake/DateTimeWiki/FrontPage Kent From kent37 at tds.net Sun Sep 7 12:20:35 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 7 Sep 2008 06:20:35 -0400 Subject: [Tutor] ftplib.storbinary and using a progress bar In-Reply-To: <200809061849.39760.jfabiani@yolo.com> References: <200809061849.39760.jfabiani@yolo.com> Message-ID: <1c2a2c590809070320s5a607c68nd259aa4f7a0789f1@mail.gmail.com> On Sat, Sep 6, 2008 at 9:49 PM, johnf wrote: > Hi, > I'm currently using ftplib.storbinary() to upload a file to a FTP server. > However, I would like to inform the user of the progress being made during > the file transfer (it could be a very long transfer). But > ftplib.storbinary() has no callback like retrbinary() so does anyone have a > thought on how I can update my user on the progress of the transfer. BTW I > have to use a binary transfer because the file being transfer is not text. storbinary() is not very complex. You could write your own version that has a callback function. Kent From kent37 at tds.net Sun Sep 7 12:23:51 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 7 Sep 2008 06:23:51 -0400 Subject: [Tutor] Online Scripting In-Reply-To: <515008f10809070225n289c255cmf02539bbfb63a6c9@mail.gmail.com> References: <515008f10809070225n289c255cmf02539bbfb63a6c9@mail.gmail.com> Message-ID: <1c2a2c590809070323y4ce09dfeh722076599e6ab033@mail.gmail.com> On Sun, Sep 7, 2008 at 5:25 AM, Omer wrote: > Has anyone a clue as to where might I host my script, so's A: the host > "runs" my script periodical (Once every Two hours? If I can configure it to > only run during the day than that's even better), and B: The host lets my > script create an iCal file (a single, <1MB file) and C: lets GCal have > access to this file. Try WebFaction.com or see http://wiki.python.org/moin/PythonHosting for many suggestions. Kent From kent37 at tds.net Sun Sep 7 13:04:07 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 7 Sep 2008 07:04:07 -0400 Subject: [Tutor] Support for datetime module In-Reply-To: <20080907101829.BNZE11041.nschwotgx03p.mx.bigpond.com@JohanPC> References: <1c2a2c590809060608te12e23bp5e63305ec4be2a4f@mail.gmail.com> <20080907101829.BNZE11041.nschwotgx03p.mx.bigpond.com@JohanPC> Message-ID: <1c2a2c590809070404m2a641504xf356cb56e162266a@mail.gmail.com> On Sun, Sep 7, 2008 at 6:17 AM, Johan Geldenhuys wrote: > Thanks Kent, > > Let me explain what I need it for. > > I have a systemUpTime is seconds that I got from a SNMP agent. > > I want to work out when the system uptime began and want to put that in ISO > format time to the millisecond. > > So my idea is to take a timestamp in seconds when I get the systemUpTime. I > subtract the uptime from my timestamp and then format that into ISO format. > That should give me a fairly accurate UTC-like time of when the systemUpTime > began. > Here is an example: "2008-09-04 22:29:43.221 Z" I think you can do all that with functions in the time module. Kent From kent37 at tds.net Sun Sep 7 13:06:09 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 7 Sep 2008 07:06:09 -0400 Subject: [Tutor] ftplib.storbinary and using a progress bar In-Reply-To: References: <200809061849.39760.jfabiani@yolo.com> Message-ID: <1c2a2c590809070406t24a34419rc14165318928098a@mail.gmail.com> On Sun, Sep 7, 2008 at 4:13 AM, Alan Gauld wrote: > "johnf" wrote > >> the file transfer (it could be a very long transfer). But >> ftplib.storbinary() has no callback like retrbinary() so does anyone have >> a >> thought on how I can update my user on the progress of the transfer. > > If you don't fancy getting the 2.6 source as Terry suggested then > the other way to do this kind of thing is with a separate thread. Start > the new thread which just displays a progress bar (you need to find > how big the file is before hand and check progress as you go too) > Then in the main thread run the transfer and terminate the progress > thread when you finish. I don't think threading will help here, the problem is that the progress information is not available. Kent From jfabiani at yolo.com Sun Sep 7 16:10:39 2008 From: jfabiani at yolo.com (johnf) Date: Sun, 7 Sep 2008 07:10:39 -0700 Subject: [Tutor] ftplib.storbinary and using a progress bar In-Reply-To: <200809061849.39760.jfabiani@yolo.com> References: <200809061849.39760.jfabiani@yolo.com> Message-ID: <200809070710.39693.jfabiani@yolo.com> On Saturday 06 September 2008 06:49:39 pm johnf wrote: > Hi, > I'm currently using ftplib.storbinary() to upload a file to a FTP server. > However, I would like to inform the user of the progress being made during > the file transfer (it could be a very long transfer). But > ftplib.storbinary() has no callback like retrbinary() so does anyone have a > thought on how I can update my user on the progress of the transfer. BTW > I have to use a binary transfer because the file being transfer is not > text. Once I took a look at the source for ftplib I decided to subclass the module. I then provided my own method with a callback. For my purpose I just passed an integer back (a counter). But thanks everyone for the help. It was a good lesson anyway. -- John Fabiani From sierra_mtnview at sbcglobal.net Sun Sep 7 16:18:06 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sun, 07 Sep 2008 07:18:06 -0700 Subject: [Tutor] Inserting an Indent in IDLE? Message-ID: <48C3E29E.1060005@sbcglobal.net> An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Sep 7 16:38:15 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 7 Sep 2008 15:38:15 +0100 Subject: [Tutor] ftplib.storbinary and using a progress bar References: <200809061849.39760.jfabiani@yolo.com> <1c2a2c590809070406t24a34419rc14165318928098a@mail.gmail.com> Message-ID: "Kent Johnson" wrote > I don't think threading will help here, the problem is that the > progress information is not available. If you are transferring from A to B and can find the size of the file at A and poll the size at B you can display progress. OTOH if that is not available you can still use a thread to indicate that *something* is happening even if you don't know when it will stop. Thus a threaded approach works for providing some kind of user feedback even if nothing else. Alan G From alan.gauld at btinternet.com Sun Sep 7 16:41:37 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 7 Sep 2008 15:41:37 +0100 Subject: [Tutor] Inserting an Indent in IDLE? References: <48C3E29E.1060005@sbcglobal.net> Message-ID: "Wayne Watson" wrote > Signature.htmlOccasionally I would like to indent 20-30 lines of > code. > I don't see a way to do this in IDLE other than brute force. Format->Indent region? Ctrl-] Format Dedent region Ctrl-[ Seems to work for me. Alan G From roybayot at gmail.com Sun Sep 7 17:07:00 2008 From: roybayot at gmail.com (Roy Khristopher Bayot) Date: Sun, 7 Sep 2008 23:07:00 +0800 Subject: [Tutor] Need help with using methods in a base class In-Reply-To: References: <5e6459540809060904y578e5e06g4f38d81cd03153d1@mail.gmail.com> Message-ID: <5e6459540809070807m4e5efd83qadaa4f85aec97930@mail.gmail.com> Hi. I added self to parts of the code. But after making an instance and using the setData method it gave out an AttributeError. >>> from parallel import Parallel >>> class LightsHandle(Parallel): ... def __init__(self): ... pass ... def setData(self, data): ... Parallel.setData(self, data) ... def setLatch(self, latch): ... Parallel.setDataStrobe(self, int(latch[0])) ... Parallel.setAutoFeed(self, int(latch[1])) ... Parallel.setInitOut(self, int(latch[2])) ... def generateClockPulse(self): ... Parallel.setSelect(self, 0) ... Parallel.setSelect(self, 1) ... >>> a = LightsHandle() >>> a.setData(0xF0) Traceback (most recent call last): File "", line 1, in File "", line 5, in setData File "/usr/lib/python2.5/site-packages/parallel/parallelppdev.py", line 563, in setData return self.PPWDATA(d) File "/usr/lib/python2.5/site-packages/parallel/parallelppdev.py", line 465, in PPWDATA fcntl.ioctl(self._fd, PPWDATA,struct.pack('B',byte)) AttributeError: LightsHandle instance has no attribute '_fd' Does this mean I have to make '_fd' in class LightsHandle? I thought that it would be somewhat "messy". And there might be other variables that werent accounted for. So I did something else. >>> class LightsHandle(Parallel): ... def __init__(self): ... Parallel.__init__(self, port = 0) ... def __del__(self): ... Parallel.__del__(self) ... def setData(self, data): ... Parallel.setData(self, data) ... def setLatch(self, latch): ... Parallel.setDataStrobe(self, int(latch[0])) ... Parallel.setAutoFeed(self, int(latch[1])) ... Parallel.setInitOut(self, int(latch[2])) ... def generateClockPulse(self): ... Parallel.setSelect(self,0) ... Parallel.setSelect(self,1) ... >>> a = LightsHandle() >>> a.setData(0xF0) >>> a.setLatch('111') >>> a.generateClockPulse() >>> a.setLatch('110') >>> a.generateClockPulse() >>> a.setData(0x0F) >>> a.setLatch('111') >>> a.generateClockPulse() There were no errors thrown. But the problem is that it doesnt work. This was suppose to control 32 LEDs (8 LEDs per latch, 6 latches total). Method setData() is suppose to control the 8 bits that you want to output on a specific latch. Method setLatch() will specify the latch. Method generateClockPulse() will cause the specific latch to take in the data and retain it there. But it doesnt work. The LEDs couldnt be controlled. I already tried using the base class and it works just fine. >>> from parallel import Parallel >>> p = Parallel() >>> p.setData(0xFF) >>> p.setDataStrobe(1) >>> p.setAutoFeed(1) >>> p.setInitOut(1) >>> p.setSelect(0) >>> p.setSelect(1) So I thought maybe there was something wrong with setLatch() since elements of the string were converted to integers. I changed the code again. >>> class LightsHandle(Parallel): ... def __init__(self): ... Parallel.__init__(self, port = 0) ... def __del__(self): ... Parallel.__del__(self) ... def setData(self, data): ... Parallel.setData(self, data) ... def setLatch(self, x, y, z): ... Parallel.setDataStrobe(self, x) ... Parallel.setAutoFeed(self, y) ... Parallel.setInitOut(self, z) ... def generateClockPulse(self): ... Parallel.setSelect(self,0) ... Parallel.setSelect(self,1) ... >>> a = LightsHandle() >>> a.setData(0xF0) >>> a.setLatch(1,1,1) >>> a.generateClockPulse() >>> a.setData(0x0F) >>> a.setLatch(1,1,1) >>> a.generateClockPulse() But no LED lights were changing as it was suppose to. Any ideas on what I dont know or what I've overlooked? On Sun, Sep 7, 2008 at 6:07 AM, Alan Gauld wrote: > "Roy Khristopher Bayot" wrote > > > ... def generateClockPulse(self): >> ... parallel.Parallel.setSelect(0) >> ... parallel.Parallel.setSelect(1) >> ... >> >>> a = LightsHandle() >>>>> a.setD(0xF0) >>>>> >>>> Traceback (most recent call last): >> File "", line 1, in >> File "", line 5, in setD >> TypeError: unbound method setData() must be called with Parallel instance >> as >> first argument (got int instance instead) >> > > The error merssage gives the clue. Sonce you are calling a method > on a classs not an object you need to pass in the instance reference > explicitly. Its exactly as in calling the base constructor in __init__ > > class C(P): > def __init__(self): > P.__init__(self) # need to pass self here > > (Some notes: I changed setData() to setD() so that there wont be a >> confusion. Method setData() is from the base class Parallel. Although I >> think setData() could be overriden.) >> > > Thats not necessary, each class creates its owen namespace. > > What have I been doing wrong? Why does it say that I need a Parallel >> instance? >> > > Because the class needs to know where to find the instance variables. > Since you are calling the class directly, not via an instance you have > to pass self explicitly. > > Remember that in > > class C: > def m(self, x): print x > > c = C(42) > > > Then c.m() is the same as C.m(c,42). self takes on the value of > the instance in the first case but in the second you have to pass > it directly. When you are inside a methiod you always use the > second form so you always need to pass self. > > 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 sierra_mtnview at sbcglobal.net Sun Sep 7 17:24:00 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sun, 07 Sep 2008 08:24:00 -0700 Subject: [Tutor] Formating from hhmms to hh:mm:ss Message-ID: <48C3F210.9040503@sbcglobal.net> An HTML attachment was scrubbed... URL: From tim at johnsons-web.com Sun Sep 7 17:27:22 2008 From: tim at johnsons-web.com (Tim Johnson) Date: Sun, 7 Sep 2008 07:27:22 -0800 Subject: [Tutor] Sending email as html In-Reply-To: References: <200809060735.06213.tim@johnsons-web.com> Message-ID: <200809070727.22922.tim@johnsons-web.com> On Saturday 06 September 2008, Alan Gauld wrote: > "Tim Johnson" wrote > > >> since PDF files are not very hard to edit with a simple text > >> editor. > >> (Never have really.) > > > > Looks like I could make up a PDF template and then put substitutions > > You could although they are not pure text files so you may need > to use binary mode to edit the file I think. :-) vim -b > There is an interersting looking link here: > > http://www.python.org/workshops/2002-02/papers/17/index.htm Yes! > HTH, thanks man - tj From greg at thewhittiers.com Sun Sep 7 18:26:12 2008 From: greg at thewhittiers.com (greg whittier) Date: Sun, 7 Sep 2008 12:26:12 -0400 Subject: [Tutor] Formating from hhmms to hh:mm:ss In-Reply-To: <48C3F210.9040503@sbcglobal.net> References: <48C3F210.9040503@sbcglobal.net> Message-ID: I'm not clear on exactly what you're looking to do, but I think you want the strftime and strptime methods. See http://docs.python.org/lib/datetime-datetime.html On Sun, Sep 7, 2008 at 11:24 AM, Wayne Watson wrote: > I've been writing various functions with datetime to change date-time > formats from one to another. For example, my file names have a time stamp of > yyyymmdd_hhmmss in their names. When I need to convert, say, time by adding > seconds to the hhmmss part of the file name, I have a function that converts > hhmmss to hh:mm:ss, and another to go the other way. In between, I add > seconds. Maybe datetime can do this more easily without the use of my > functions? > -- > > Wayne Watson (Watson Adventures, Prop., Nevada City, CA) > > (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) > Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet "If voting made any difference they wouldn't let us do it." > -- Mark Twain > > Web Page: > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From greg at thewhittiers.com Sun Sep 7 19:17:41 2008 From: greg at thewhittiers.com (greg whittier) Date: Sun, 7 Sep 2008 13:17:41 -0400 Subject: [Tutor] Formating from hhmms to hh:mm:ss In-Reply-To: <48C406D4.4050504@sbcglobal.net> References: <48C3F210.9040503@sbcglobal.net> <48C406D4.4050504@sbcglobal.net> Message-ID: Is this an actual cut and paste of your code? The problem seems to be that you're getting a time.struct_time object instead of a datetime object. See below On Sun, Sep 7, 2008 at 12:52 PM, Wayne Watson wrote: > Yes, that's correct., but that reference isn't doing it for me presently. > Here's a piece of code that might help explain what I'm trying to do: > > # program to test str... functions > import datetime > > Are you sure you didn't do "from datetime import datetime"? > > ... > # format conversion of date+time > dt1 = datetime.strptime("20080421_101145", "%Y%m%d_%H%M%S") > > I don't see how this works as written because the datetime module doesn't have a strptime function. > > print "dt1: ",dt1 > other = dt1.strftime("%Y%m%d_%H%M%S") <-- fails, line 11 > print other.replace(" ", "") > > Results: > dt1: (2008, 4, 21, 10, 11, 45, 0, 112, -1) > > > Traceback (most recent call last): > File > "C:/Sandia_Meteors/Improved_Sentinel/Sentinel_Playground/Utility_Dev/BumpSeconds", > line 11, in ? > other = dt1.strftime("%Y%m%d_%H%M%S") > AttributeError: 'time.struct_time' object has no attribute 'strftime' > > This is telling you that dt1 is a time.struct_time but I don't see how from the code you've shown here. -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Sun Sep 7 20:35:22 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 7 Sep 2008 14:35:22 -0400 Subject: [Tutor] Need help with using methods in a base class In-Reply-To: <5e6459540809070807m4e5efd83qadaa4f85aec97930@mail.gmail.com> References: <5e6459540809060904y578e5e06g4f38d81cd03153d1@mail.gmail.com> <5e6459540809070807m4e5efd83qadaa4f85aec97930@mail.gmail.com> Message-ID: <1c2a2c590809071135p18fb2707nc74a7c67aeff08c5@mail.gmail.com> On Sun, Sep 7, 2008 at 11:07 AM, Roy Khristopher Bayot wrote: > Hi. I added self to parts of the code. But after making an instance and > using the setData method it gave out an AttributeError. > >>>> from parallel import Parallel >>>> class LightsHandle(Parallel): > ... def __init__(self): > ... pass This will *prevent* Parallel.__init__() from being called. I guess this is not what you want, it is probably the cause of your trouble. Is _fd initialized in Parallel.__init__() ? > ... def setData(self, data): > ... Parallel.setData(self, data) This method is not needed at all. If you omit it, the base class method will be called automatically when you call setData() on a LightsHandle instance. > ... def setLatch(self, latch): > ... Parallel.setDataStrobe(self, int(latch[0])) > ... Parallel.setAutoFeed(self, int(latch[1])) > ... Parallel.setInitOut(self, int(latch[2])) This could be written more simply and idiomatically as ... def setLatch(self, x, y, z): ... self.setDataStrobe(x) ... self.setAutoFeed(y) ... self.setInitOut(z) Since you have not overridden these methods you can call them directly. > ... def generateClockPulse(self): > ... Parallel.setSelect(self, 0) > ... Parallel.setSelect(self, 1) Same here. >>>> a = LightsHandle() >>>> a.setData(0xF0) > Traceback (most recent call last): > File "", line 1, in > File "", line 5, in setData > File "/usr/lib/python2.5/site-packages/parallel/parallelppdev.py", line > 563, in setData > return self.PPWDATA(d) > File "/usr/lib/python2.5/site-packages/parallel/parallelppdev.py", line > 465, in PPWDATA > fcntl.ioctl(self._fd, PPWDATA,struct.pack('B',byte)) > AttributeError: LightsHandle instance has no attribute '_fd' > > Does this mean I have to make '_fd' in class LightsHandle? I thought that it > would be somewhat "messy". And there might be other variables that werent > accounted for. Probably it means you have to call the base class __init__(). >>>> a = LightsHandle() >>>> a.setData(0xF0) > > There were no errors thrown. But the problem is that it doesnt work. > I already tried using the base class and it works just fine. > >>>> from parallel import Parallel >>>> p = Parallel() >>>> p.setData(0xFF) Note this is a different value than you used above, is that significant? Kent From kent37 at tds.net Sun Sep 7 20:48:47 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 7 Sep 2008 14:48:47 -0400 Subject: [Tutor] Sending email as html In-Reply-To: <200809070727.22922.tim@johnsons-web.com> References: <200809060735.06213.tim@johnsons-web.com> <200809070727.22922.tim@johnsons-web.com> Message-ID: <1c2a2c590809071148j29f00dd5nd28dfb50f223fd1c@mail.gmail.com> On Sun, Sep 7, 2008 at 11:27 AM, Tim Johnson wrote: > On Saturday 06 September 2008, Alan Gauld wrote: >> There is an interersting looking link here: >> >> http://www.python.org/workshops/2002-02/papers/17/index.htm > Yes! Did you find the code to go with the article? My google-fu is failing me today. Kent From kent37 at tds.net Sun Sep 7 20:54:22 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 7 Sep 2008 14:54:22 -0400 Subject: [Tutor] Formating from hhmms to hh:mm:ss In-Reply-To: References: <48C3F210.9040503@sbcglobal.net> <48C406D4.4050504@sbcglobal.net> Message-ID: <1c2a2c590809071154g1326c79wc3bf2f228fa8a3b4@mail.gmail.com> On Sun, Sep 7, 2008 at 1:17 PM, greg whittier wrote: >> # program to test str... functions >> import datetime > > Are you sure you didn't do "from datetime import datetime"? or "import time" ? >> ... >> # format conversion of date+time >> dt1 = datetime.strptime("20080421_101145", "%Y%m%d_%H%M%S") > > I don't see how this works as written because the datetime module doesn't > have a strptime function. >> >> print "dt1: ",dt1 >> other = dt1.strftime("%Y%m%d_%H%M%S") <-- fails, line 11 >> print other.replace(" ", "") >> >> Results: >> dt1: (2008, 4, 21, 10, 11, 45, 0, 112, -1) Looks to me like you are confusing the time and datetime modules. time.strptime() will return a time struct; datetime.datetime.strptime() returns a datetime.datetime. Kent From johan at accesstel.com.au Sun Sep 7 21:48:25 2008 From: johan at accesstel.com.au (Johan Geldenhuys) Date: Mon, 8 Sep 2008 05:48:25 +1000 Subject: [Tutor] Support for datetime module In-Reply-To: <1c2a2c590809070404m2a641504xf356cb56e162266a@mail.gmail.com> Message-ID: <20080907194901.NXZF11041.nschwotgx03p.mx.bigpond.com@JohanPC> I can get the time up to the closest second with the time module, but not to the millisecond. When I use time.strftime, I don't know how many milliseconds are left over to use them. -----Original Message----- From: kent3737 at gmail.com [mailto:kent3737 at gmail.com] On Behalf Of Kent Johnson Sent: Sunday, 7 September 2008 21:04 PM To: johan at accesstel.com.au Cc: tutor at python.org Subject: Re: [Tutor] Support for datetime module On Sun, Sep 7, 2008 at 6:17 AM, Johan Geldenhuys wrote: > Thanks Kent, > > Let me explain what I need it for. > > I have a systemUpTime is seconds that I got from a SNMP agent. > > I want to work out when the system uptime began and want to put that in ISO > format time to the millisecond. > > So my idea is to take a timestamp in seconds when I get the systemUpTime. I > subtract the uptime from my timestamp and then format that into ISO format. > That should give me a fairly accurate UTC-like time of when the systemUpTime > began. > Here is an example: "2008-09-04 22:29:43.221 Z" I think you can do all that with functions in the time module. Kent From greg at thewhittiers.com Sun Sep 7 22:24:59 2008 From: greg at thewhittiers.com (greg whittier) Date: Sun, 7 Sep 2008 16:24:59 -0400 Subject: [Tutor] Formating from hhmms to hh:mm:ss In-Reply-To: <48C41115.1050909@sbcglobal.net> References: <48C3F210.9040503@sbcglobal.net> <48C406D4.4050504@sbcglobal.net> <48C41115.1050909@sbcglobal.net> Message-ID: On Sun, Sep 7, 2008 at 1:36 PM, Wayne Watson wrote: > Yes, cut and paste directly from the code. Positively a import as seen. > Here's the full set of code: > > # The effect of adding seconds to date-time to see if day gets changed > import datetime > dt1 = datetime.datetime(2008, 03, 10, 23, 59, 0) > print dt1 > delta = datetime.timedelta(seconds = 200) > print dt1+delta > > # format conversion of date+time > dt1 = time.strptime("20080421_101145", "%Y%m%d_%H%M%S") > > The first code you posted was different. You had datetime.strptime and not time.strptime. Your problem is dt1 is a time.struct_time which has no strftime method, producing the error. You must have imported time somewhere. This line makes dt1 a time.struct_time which causes your problem. > > print "dt1: ",dt1 > other = dt1.strftime("%Y%m%d_%H%M%S") > > Now dt1 is a time.struct_time and not a datetime.datetime object so it has no strftime method. > > ... >> # format conversion of date+time >> dt1 = datetime.strptime("20080421_101145", "%Y%m%d_%H%M%S") >> >> I don't see how this works as written because the datetime module > doesn't have a strptime function. > >> This is what you had before. Note datetime.strptime instead of time.strptime, which confused me because the datetime module doesn't have a strptime function. -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Sun Sep 7 23:13:29 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 7 Sep 2008 17:13:29 -0400 Subject: [Tutor] Support for datetime module In-Reply-To: <20080907194901.NXZF11041.nschwotgx03p.mx.bigpond.com@JohanPC> References: <1c2a2c590809070404m2a641504xf356cb56e162266a@mail.gmail.com> <20080907194901.NXZF11041.nschwotgx03p.mx.bigpond.com@JohanPC> Message-ID: <1c2a2c590809071413j4a4574abo38b3d92737a11b67@mail.gmail.com> On Sun, Sep 7, 2008 at 3:48 PM, Johan Geldenhuys wrote: > I can get the time up to the closest second with the time module, but not to > the millisecond. > When I use time.strftime, I don't know how many milliseconds are left over > to use them. OK. I guess you can use time.strptime() and strftime() to parse / format the time to the second and handle the milliseconds separately. Kent From tim at johnsons-web.com Mon Sep 8 02:33:35 2008 From: tim at johnsons-web.com (Tim Johnson) Date: Sun, 7 Sep 2008 16:33:35 -0800 Subject: [Tutor] Sending email as html In-Reply-To: <1c2a2c590809071148j29f00dd5nd28dfb50f223fd1c@mail.gmail.com> References: <200809070727.22922.tim@johnsons-web.com> <1c2a2c590809071148j29f00dd5nd28dfb50f223fd1c@mail.gmail.com> Message-ID: <200809071633.35954.tim@johnsons-web.com> On Sunday 07 September 2008, you wrote: > On Sun, Sep 7, 2008 at 11:27 AM, Tim Johnson wrote: > > On Saturday 06 September 2008, Alan Gauld wrote: > >> There is an interersting looking link here: > >> > >> http://www.python.org/workshops/2002-02/papers/17/index.htm > > > > Yes! > > Did you find the code to go with the article? My google-fu is failing me > today. No code. Googling keywords got me nowhere. Tim "Who remembers when google was a number" From sierra_mtnview at sbcglobal.net Mon Sep 8 02:42:45 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sun, 07 Sep 2008 17:42:45 -0700 Subject: [Tutor] Formating from hhmms to hh:mm:ss In-Reply-To: References: <48C3F210.9040503@sbcglobal.net> <48C406D4.4050504@sbcglobal.net> <48C41115.1050909@sbcglobal.net> <48C45C35.6080106@sbcglobal.net> Message-ID: <48C47505.20202@sbcglobal.net> An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Mon Sep 8 03:33:25 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sun, 07 Sep 2008 18:33:25 -0700 Subject: [Tutor] Formating from hhmms to hh:mm:ss In-Reply-To: References: <48C3F210.9040503@sbcglobal.net> <48C406D4.4050504@sbcglobal.net> <48C41115.1050909@sbcglobal.net> <48C45C35.6080106@sbcglobal.net> Message-ID: <48C480E5.9020501@sbcglobal.net> An HTML attachment was scrubbed... URL: From john at fouhy.net Mon Sep 8 03:41:31 2008 From: john at fouhy.net (John Fouhy) Date: Mon, 8 Sep 2008 13:41:31 +1200 Subject: [Tutor] Formating from hhmms to hh:mm:ss In-Reply-To: <48C480E5.9020501@sbcglobal.net> References: <48C3F210.9040503@sbcglobal.net> <48C406D4.4050504@sbcglobal.net> <48C41115.1050909@sbcglobal.net> <48C45C35.6080106@sbcglobal.net> <48C480E5.9020501@sbcglobal.net> Message-ID: <5e58f2e40809071841t13fd3927y518fedce70de433e@mail.gmail.com> 2008/9/8 Wayne Watson : > def adjust_ftime(atime, sec): > # yyyymmdd_hhmmss, seconds in, new yyyymmdd_hhmmss out > ts = atime[1:-7] # use time stamp portion > ayear = int(ts[0:4]) > amonth = int(ts[4:6]) > aday = int(ts[6:8]) > ahour = int(ts[9:11]) > aminute = int(ts[11:13]) > asecond = int(ts[13:15]) > print ayear, amonth, aday, asecond > dt1 = datetime.datetime(ayear, amonth, aday, ahour, aminute, asecond) > print dt1, type(dt1) > delta = datetime.timedelta(seconds = 200) > dt2 = dt1 + delta > print dt2, type(dt2) > print "what next? I need the result 20080321_113405" Hi Wayne, The functions you are looking for are strptime and strftime. As follows: >>> import datetime >>> timeStr = '20080321_113045' >>> dt1 = datetime.datetime.strptime(timeStr, '%Y%m%d_%H%M%S') >>> dt2 = dt1 + datetime.timedelta(seconds=200) >>> print dt2.strftime('%Y%m%d_%H%M%S') 20080321_113405 You can find the format codes for strptime and strftime in the documentation for the time module. Hope this helps! -- John. From kent37 at tds.net Mon Sep 8 03:57:36 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 7 Sep 2008 21:57:36 -0400 Subject: [Tutor] Formating from hhmms to hh:mm:ss In-Reply-To: <48C480E5.9020501@sbcglobal.net> References: <48C3F210.9040503@sbcglobal.net> <48C406D4.4050504@sbcglobal.net> <48C41115.1050909@sbcglobal.net> <48C45C35.6080106@sbcglobal.net> <48C480E5.9020501@sbcglobal.net> Message-ID: <1c2a2c590809071857p3f7e3d50kbd677367d9110115@mail.gmail.com> On Sun, Sep 7, 2008 at 9:33 PM, Wayne Watson wrote: > Here's as far as I can go with this. The last line of output asks the > question I need an answer for. > (Once again my direct post to tutor at python.org has failed to appear here > (sent 5:42 PDT), as before.) It arrived late for some reason. You can do what you want much more simply using datetime.strptime() and strftime(): In [2]: from datetime import datetime, timedelta In [3]: format = '%Y%m%d_%H%M%S' In [8]: d=datetime.strptime('20080321_113405', format) In [10]: d Out[10]: datetime.datetime(2008, 3, 21, 11, 34, 5) In [13]: d += timedelta(seconds=200) In [14]: d Out[14]: datetime.datetime(2008, 3, 21, 11, 37, 25) In [15]: d.strftime(format) Out[15]: '20080321_113725' Kent From sierra_mtnview at sbcglobal.net Mon Sep 8 04:28:40 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sun, 07 Sep 2008 19:28:40 -0700 Subject: [Tutor] Formating from hhmms to hh:mm:ss In-Reply-To: <1c2a2c590809071857p3f7e3d50kbd677367d9110115@mail.gmail.com> References: <48C3F210.9040503@sbcglobal.net> <48C406D4.4050504@sbcglobal.net> <48C41115.1050909@sbcglobal.net> <48C45C35.6080106@sbcglobal.net> <48C480E5.9020501@sbcglobal.net> <1c2a2c590809071857p3f7e3d50kbd677367d9110115@mail.gmail.com> Message-ID: <48C48DD8.2000506@sbcglobal.net> An HTML attachment was scrubbed... URL: From john at fouhy.net Mon Sep 8 04:57:26 2008 From: john at fouhy.net (John Fouhy) Date: Mon, 8 Sep 2008 14:57:26 +1200 Subject: [Tutor] Formating from hhmms to hh:mm:ss In-Reply-To: <48C48DD8.2000506@sbcglobal.net> References: <48C3F210.9040503@sbcglobal.net> <48C406D4.4050504@sbcglobal.net> <48C41115.1050909@sbcglobal.net> <48C45C35.6080106@sbcglobal.net> <48C480E5.9020501@sbcglobal.net> <1c2a2c590809071857p3f7e3d50kbd677367d9110115@mail.gmail.com> <48C48DD8.2000506@sbcglobal.net> Message-ID: <5e58f2e40809071957h85be09ej5dfdf698530419c@mail.gmail.com> 2008/9/8 Wayne Watson : > I'm sure you have the essence below, but I'm not familiar with the In/ Out > notation. Apparently, I need to scoop up the In lines into a file and add > some print stmts for the In[x] d lines. Kent uses IPython, which is an enhanced version of the standard python shell. That's what the In[] and Out[] bits are from. > AttributeError: type object 'datetime.datetime' has no attribute 'strptime > > This attribute problem is reminiscent of my problems. IDLE? Python 2.4.x? Python 2.4, unfortunately. datetime.strptime only came in with Python 2.5, IIRC. The Python 2.4 version is: d = datetime.datetime(*(time.strptime(date_string, format)[0:6])) (i.e. that corresponds to "d = datetime.datetime.strptime(date_string, format)") -- John. From sierra_mtnview at sbcglobal.net Mon Sep 8 05:27:05 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sun, 07 Sep 2008 20:27:05 -0700 Subject: [Tutor] Formating from hhmms to hh:mm:ss In-Reply-To: <5e58f2e40809071957h85be09ej5dfdf698530419c@mail.gmail.com> References: <48C3F210.9040503@sbcglobal.net> <48C406D4.4050504@sbcglobal.net> <48C41115.1050909@sbcglobal.net> <48C45C35.6080106@sbcglobal.net> <48C480E5.9020501@sbcglobal.net> <1c2a2c590809071857p3f7e3d50kbd677367d9110115@mail.gmail.com> <48C48DD8.2000506@sbcglobal.net> <5e58f2e40809071957h85be09ej5dfdf698530419c@mail.gmail.com> Message-ID: <48C49B89.6080701@sbcglobal.net> An HTML attachment was scrubbed... URL: From jerry.vb at gmail.com Mon Sep 8 08:46:37 2008 From: jerry.vb at gmail.com (J. Van Brimmer) Date: Sun, 07 Sep 2008 23:46:37 -0700 Subject: [Tutor] How to match strange characters Message-ID: <48C4CA4D.2080106@gmail.com> I have a legacy program at work that outputs a text file with this header: ???????????????????????????????????????????????????????????????????????????????? ? Radio Source Precession Program ? ? by John B. Doe ? ? 31 August 1992 ? ???????????????????????????????????????????????????????????????????????????????? Enter Date for Precession as (MM-DD-YYYY) or C/R for 05-28-2004 > 05-28-2004 Enter the Catalog Name or C/R for CATALOG.SRC > The Julian Date is = 2453153.5 0022+002 5.6564 +0.2713 00:22:37.54 00:16:16.65 0106+013 17.2117 +1.6052 01:08:50.80 01:36:18.58 . . . much more regular integer data lines to the end of the section. One section is created each time the program is run. Each section has one of these headers. Each section is appended to the end of the file every time the program is run. So that each new header follows the last data line in the previous section. I am trying to write a python script to strip this header (the first five lines)(these headers) from the file. The name of this legacy program is PRECESS. Every time we run PRECESS, this header is repeated, not just at the top. Here's my code so far: (code) import re def main(): f = open('/home/jerry/sepoct08.txt', 'r') # sepoct08.txt is the PRECESS output file for line in f: if re.search('????', line): print line elif re.search('> ..-..-....', line): # this line prints out print line elif re.search('Catalog', line): # this line prints out print line elif re.search('Julian', line): # this line prints out print line print "Hi there!" # I print out this just so I know my script is looping f.close() if __name__ == "__main__": main() (/code) Here's the output from my code: (output) Hi there! Hi there! Hi there! Hi there! Hi there! Enter Date for Precession as (MM-DD-YYYY) or C/R for 05-28-2004 > 05-28-2004 Hi there! Enter the Catalog Name or C/R for CATALOG.SRC > Hi there! The Julian Date is = 2453153.5 Hi there! Hi there! . . . . end of file (/output) As you can see, I can print out the three lines after the strange header lines, but not the strange character lines. How can I match on those strange characters? What are they? I'm just trying to figure out how to print out each line from the header first, then later I will modify the code to process those lines as needed. My problem is those strange characters in the top part of the header. The re module doesn't recognize them. How can I match on them, so I can delete those lines? I can't do it by line number because they aren't recognized The original PRECESS code cannot be modified. So, short of rewriting the PRECESS program, I thought it would be easy to modify the output as needed. I'm pretty sure PRECESS is written in C. Sorry for the long post, I tried to only include the relevant information. Please fire away with questions and comments. TIA, Jerry From sanelson at gmail.com Mon Sep 8 11:46:18 2008 From: sanelson at gmail.com (Stephen Nelson-Smith) Date: Mon, 8 Sep 2008 10:46:18 +0100 Subject: [Tutor] Short Contract Message-ID: Hello, I'm looking for someone to help on a short contract to build a centralised blogging system. I want a planet-style aggregation of blogs, but with the ability to see and make comments on each individual blog, from the central planet page. Ideally, it would also have a little 'icon' mug-shot of the person who writes each blog next to their entry, and a dynamically generated 'go to this guy's blog' button under each entry. I'd be happy to take an existing open-source tool (eg venus) and modify it for purpose - I think that's a better idea than writing a new blog engine. The blogs don't exist yet, so we can ensure they all live on the same blog server. If this is something you have bandwidth for, or an interest in, please contact me off list and we can discuss it. Thanks, S. From kent37 at tds.net Mon Sep 8 12:42:25 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 8 Sep 2008 06:42:25 -0400 Subject: [Tutor] Formating from hhmms to hh:mm:ss In-Reply-To: <48C49B89.6080701@sbcglobal.net> References: <48C3F210.9040503@sbcglobal.net> <48C41115.1050909@sbcglobal.net> <48C45C35.6080106@sbcglobal.net> <48C480E5.9020501@sbcglobal.net> <1c2a2c590809071857p3f7e3d50kbd677367d9110115@mail.gmail.com> <48C48DD8.2000506@sbcglobal.net> <5e58f2e40809071957h85be09ej5dfdf698530419c@mail.gmail.com> <48C49B89.6080701@sbcglobal.net> Message-ID: <1c2a2c590809080342w730c98can46c0061a3773f9c0@mail.gmail.com> On Sun, Sep 7, 2008 at 11:27 PM, Wayne Watson wrote: > Well, maybe. Here's the file the change and results: > > # Using datetime to do date-time math on a file date-time stamp and > # the creating the new stamp > from datetime import datetime, timedelta > > Traceback (most recent call last): > File > "C:/Sandia_Meteors/Improved_Sentinel/Sentinel_Playground/Utility_Dev/debugDateTime.py", > line 7, in ? > d = datetime.datetime(*(time.strptime('20080321_113405', format)[0:6])) > AttributeError: type object 'datetime.datetime' has no attribute 'datetime' This is just some confusion about imports, abetted by the naming scheme of the datetime module. The datetime module contains a datetime class. The full name of the class is datetime.datetime. If you "import datetime" then you have to use the full name. Another way to import is "from datetime import datetime". Now the name datetime refers to the class and you can just use its name alone. So, try d = datetime(*(time.strptime('20080321_113405', format)[0:6])) You can read about the import statement here: http://docs.python.org/tut/node8.html Kent From kent37 at tds.net Mon Sep 8 12:57:13 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 8 Sep 2008 06:57:13 -0400 Subject: [Tutor] How to match strange characters In-Reply-To: <48C4CA4D.2080106@gmail.com> References: <48C4CA4D.2080106@gmail.com> Message-ID: <1c2a2c590809080357u6e7827f9nec960dfc8a248470@mail.gmail.com> On Mon, Sep 8, 2008 at 2:46 AM, J. Van Brimmer wrote: > I have a legacy program at work that outputs a text file with this header: > > ???????????????????????????????????????????????????????????????????????????????? > ? Radio Source Precession Program ? > ? by John B. Doe ? > ? 31 August 1992 ? > ???????????????????????????????????????????????????????????????????????????????? > Enter Date for Precession as (MM-DD-YYYY) or C/R for 05-28-2004 > 05-28-2004 > Enter the Catalog Name or C/R for CATALOG.SRC > > The Julian Date is = 2453153.5 > 0022+002 5.6564 +0.2713 00:22:37.54 00:16:16.65 > 0106+013 17.2117 +1.6052 01:08:50.80 01:36:18.58 > . > I am trying to write a python script to strip this header (the first five > lines)(these headers) from the file. > As you can see, I can print out the three lines after the strange header > lines, but not the strange character lines. How can I match on those strange > characters? What are they? The strange characters seem to be box drawing characters from DOS codepage 437. See http://www.microsoft.com/globaldev/reference/oem/437.htm My guess is that the characters in your program are not actually the same as the characters in the file because they use different encodings. Try using the hex values for the characters: if re.search('\xc9\xcd\xcd\xcd', line): Kent From roybayot at gmail.com Mon Sep 8 15:21:20 2008 From: roybayot at gmail.com (Roy Khristopher Bayot) Date: Mon, 8 Sep 2008 21:21:20 +0800 Subject: [Tutor] Need help with using methods in a base class In-Reply-To: <1c2a2c590809071135p18fb2707nc74a7c67aeff08c5@mail.gmail.com> References: <5e6459540809060904y578e5e06g4f38d81cd03153d1@mail.gmail.com> <5e6459540809070807m4e5efd83qadaa4f85aec97930@mail.gmail.com> <1c2a2c590809071135p18fb2707nc74a7c67aeff08c5@mail.gmail.com> Message-ID: <5e6459540809080621u16664e86h70eb0b32ab766c51@mail.gmail.com> Hi. It worked. >>> class LightsHandle(Parallel): ... def __init__(self): ... Parallel.__init__(self) ... def __del__(self): ... Parallel.__del__(self) ... def setLatch(self, x, y, z): ... self.setDataStrobe(x) ... print 'Data Strobe set. \n' ... self.setAutoFeed(y) ... print 'AutoFeed set. \n' ... self.setInitOut(z) ... print 'InitOut set. \n' ... def generateClockPulse(self): ... self.setSelect(0) ... print 'Select set to 0. \n' ... self.setSelect(1) ... print 'Select set to 1. \n' Just to answer some questions. Is _fd initialized in Parallel.__init__() ? Yes it is. > I already tried using the base class and it works just fine. > >>>> from parallel import Parallel >>>> p = Parallel() >>>> p.setData(0xFF) Note this is a different value than you used above, is that significant? No, not really. It's just what I want to output. 0xFF would mean all 8 LEDs are off while 0xF0 would mean only half the lights are on. Thank you very much. On Mon, Sep 8, 2008 at 2:35 AM, Kent Johnson wrote: > On Sun, Sep 7, 2008 at 11:07 AM, Roy Khristopher Bayot > wrote: > > Hi. I added self to parts of the code. But after making an instance and > > using the setData method it gave out an AttributeError. > > > >>>> from parallel import Parallel > >>>> class LightsHandle(Parallel): > > ... def __init__(self): > > ... pass > > This will *prevent* Parallel.__init__() from being called. I guess > this is not what you want, it is probably the cause of your trouble. > Is _fd initialized in Parallel.__init__() ? > > > ... def setData(self, data): > > ... Parallel.setData(self, data) > > This method is not needed at all. If you omit it, the base class > method will be called automatically when you call setData() on a > LightsHandle instance. > > > ... def setLatch(self, latch): > > ... Parallel.setDataStrobe(self, int(latch[0])) > > ... Parallel.setAutoFeed(self, int(latch[1])) > > ... Parallel.setInitOut(self, int(latch[2])) > > This could be written more simply and idiomatically as > > ... def setLatch(self, x, y, z): > ... self.setDataStrobe(x) > ... self.setAutoFeed(y) > ... self.setInitOut(z) > > Since you have not overridden these methods you can call them directly. > > > ... def generateClockPulse(self): > > ... Parallel.setSelect(self, 0) > > ... Parallel.setSelect(self, 1) > > Same here. > > >>>> a = LightsHandle() > >>>> a.setData(0xF0) > > Traceback (most recent call last): > > File "", line 1, in > > File "", line 5, in setData > > File "/usr/lib/python2.5/site-packages/parallel/parallelppdev.py", line > > 563, in setData > > return self.PPWDATA(d) > > File "/usr/lib/python2.5/site-packages/parallel/parallelppdev.py", line > > 465, in PPWDATA > > fcntl.ioctl(self._fd, PPWDATA,struct.pack('B',byte)) > > AttributeError: LightsHandle instance has no attribute '_fd' > > > > Does this mean I have to make '_fd' in class LightsHandle? I thought that > it > > would be somewhat "messy". And there might be other variables that werent > > accounted for. > > Probably it means you have to call the base class __init__(). > > >>>> a = LightsHandle() > >>>> a.setData(0xF0) > > > > There were no errors thrown. But the problem is that it doesnt work. > > > I already tried using the base class and it works just fine. > > > >>>> from parallel import Parallel > >>>> p = Parallel() > >>>> p.setData(0xFF) > > Note this is a different value than you used above, is that significant? > > Kent > -------------- next part -------------- An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Mon Sep 8 16:45:34 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 08 Sep 2008 07:45:34 -0700 Subject: [Tutor] Formating from hhmms to hh:mm:ss In-Reply-To: <1c2a2c590809080342w730c98can46c0061a3773f9c0@mail.gmail.com> References: <48C3F210.9040503@sbcglobal.net> <48C41115.1050909@sbcglobal.net> <48C45C35.6080106@sbcglobal.net> <48C480E5.9020501@sbcglobal.net> <1c2a2c590809071857p3f7e3d50kbd677367d9110115@mail.gmail.com> <48C48DD8.2000506@sbcglobal.net> <5e58f2e40809071957h85be09ej5dfdf698530419c@mail.gmail.com> <48C49B89.6080701@sbcglobal.net> <1c2a2c590809080342w730c98can46c0061a3773f9c0@mail.gmail.com> Message-ID: <48C53A8E.5070506@sbcglobal.net> An HTML attachment was scrubbed... URL: From kent37 at tds.net Mon Sep 8 16:54:03 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 8 Sep 2008 10:54:03 -0400 Subject: [Tutor] Need help with using methods in a base class In-Reply-To: <5e6459540809080621u16664e86h70eb0b32ab766c51@mail.gmail.com> References: <5e6459540809060904y578e5e06g4f38d81cd03153d1@mail.gmail.com> <5e6459540809070807m4e5efd83qadaa4f85aec97930@mail.gmail.com> <1c2a2c590809071135p18fb2707nc74a7c67aeff08c5@mail.gmail.com> <5e6459540809080621u16664e86h70eb0b32ab766c51@mail.gmail.com> Message-ID: <1c2a2c590809080754k4bfcecb9t94dea54673afef03@mail.gmail.com> On Mon, Sep 8, 2008 at 9:21 AM, Roy Khristopher Bayot wrote: > Hi. It worked. :-) >>>> class LightsHandle(Parallel): > ... def __init__(self): > ... Parallel.__init__(self) > ... def __del__(self): > ... Parallel.__del__(self) These two methods are not needed. If you omit them, the base class methods will be called by default. You only need a subclass __init__() method if it is doing initialization specific to the subclass. It is very rare to define a __del__() method at all. Kent From jerry.vb at gmail.com Mon Sep 8 17:01:26 2008 From: jerry.vb at gmail.com (J. Van Brimmer) Date: Mon, 08 Sep 2008 08:01:26 -0700 Subject: [Tutor] How to match strange characters In-Reply-To: <1c2a2c590809080357u6e7827f9nec960dfc8a248470@mail.gmail.com> References: <48C4CA4D.2080106@gmail.com> <1c2a2c590809080357u6e7827f9nec960dfc8a248470@mail.gmail.com> Message-ID: <48C53E46.6080403@gmail.com> Kent Johnson wrote: > On Mon, Sep 8, 2008 at 2:46 AM, J. Van Brimmer wrote: > >> I have a legacy program at work that outputs a text file with this header: >> >> ???????????????????????????????????????????????????????????????????????????????? >> ? Radio Source Precession Program ? >> ? by John B. Doe ? >> ? 31 August 1992 ? >> ???????????????????????????????????????????????????????????????????????????????? >> Enter Date for Precession as (MM-DD-YYYY) or C/R for 05-28-2004 > 05-28-2004 >> Enter the Catalog Name or C/R for CATALOG.SRC > >> The Julian Date is = 2453153.5 >> 0022+002 5.6564 +0.2713 00:22:37.54 00:16:16.65 >> 0106+013 17.2117 +1.6052 01:08:50.80 01:36:18.58 >> . >> I am trying to write a python script to strip this header (the first five >> lines)(these headers) from the file. >> > > >> As you can see, I can print out the three lines after the strange header >> lines, but not the strange character lines. How can I match on those strange >> characters? What are they? >> > > The strange characters seem to be box drawing characters from DOS > codepage 437. See > http://www.microsoft.com/globaldev/reference/oem/437.htm > > My guess is that the characters in your program are not actually the > same as the characters in the file because they use different > encodings. Try using the hex values for the characters: > if re.search('\xc9\xcd\xcd\xcd', line): > > Kent > Thanks Kent, that worked. This is what the output looks like: $ python srclist.py ??????????????????????????????????????????????????????????????????????????????? Hi there! Hi there! Not exactly what I expected, but at least it's recognizing the line, now I can delete it. Thanks a million! Jerry From ptmcg at austin.rr.com Mon Sep 8 16:09:11 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 8 Sep 2008 09:09:11 -0500 Subject: [Tutor] How to match strange characters In-Reply-To: References: Message-ID: <953509956B0A4CDAB0787C8F65C44B15@AWA2> Instead of trying to match on the weird characters, in order to remove them, here is a pyparsing program that ignores those header lines and just extracts the interesting data for each section. In a pyparsing program, you start by defining what patterns you want to look for. This is similar to the re module, but uses friendlier names like OneOrMore, Group, and Combine instead of special characters that require backslashes and so on. By default, pyparsing skips over whitespace between expressions, so we use Combine to override this (as in realnum, in which we want to match "3.1415", but not "3 . 1415"). Here is the opening part of the program, that defines the basic bits in your data file, and the input parameter prompts: from pyparsing import Combine, Word, nums, Literal, Group, oneOf, OneOrMore # define basic expressions realnum = Combine(Word(nums) + "." + Word(nums)) two_digit_num = Word(nums,exact=2) four_digit_num = Word(nums,exact=4) date = Combine(two_digit_num + '-' + two_digit_num + '-' + four_digit_num) timestamp = Combine(two_digit_num + ':' + two_digit_num + ':' + two_digit_num + '.' + two_digit_num) # literal prompt strings enter_date = Literal("Enter Date for Precession as (MM-DD-YYYY) or C/R for ") enter_catalog = Literal("Enter the Catalog Name or C/R for CATALOG.SRC >") the_julian_date_is = Literal("The Julian Date is =") # build up the header definition enter_date_line = enter_date + date + ">" julian_date_line = the_julian_date_is + realnum("julian_date") header = Group(enter_date_line + date("date") + enter_catalog + julian_date_line) This next part uses similar style to define the format of the lines of data. # build up the definition for a line of data field_1 = Word(nums,exact=4) + "+" + Word(nums,exact=3) field_2 = realnum field_3 = Combine(oneOf("+ -") + realnum) field_4 = timestamp field_5 = timestamp # change the results names as appropriate - I just made these up data_line = Group( field_1("fld1") + field_2("magnitude") + field_3("phase") + field_4("start_time") + field_5("end_time") ) I guessed at/made up names for the fields in the data_line ("fld1", "magnitude", etc.). You should change these to names that make sense in your application. Now a final definition that puts everything together: # put everything together into a PRECESS run header+data section section = header("header") + OneOrMore(data_line)("data") And now use section.scanString to locate all the matching data in your input file: test = """ ?????????????????????????????????????????????? ? Radio Source Precession Program ? ? by John B. Doe ? ? 31 August 1992 ? ?????????????????????????????????????????????? Enter Date for Precession as (MM-DD-YYYY) or C/R for 05-28-2004 > 05-28-2004 Enter the Catalog Name or C/R for CATALOG.SRC > The Julian Date is = 2453153.5 0022+002 5.6564 +0.2713 00:22:37.54 00:16:16.65 0106+013 17.2117 +1.6052 01:08:50.80 01:36:18.58 """ # use scanString to read through the input data - this will ignore the # parts of the header with the weird characters for data_section, start,end in section.scanString(test): # each data_section returns the parsed results, which can be treated # like an object or a dict, using the results names for attribute names # or dict keys - the dump() method shows a structured output, keys() # values(), and items() work just like in a dict print data_section.dump() print data_section.header.julian_date # note the use of results name to access the "data" part for d in data_section.data: print d.dump() print " ", d.start_time, d.end_time, d.phase Note how the results names are used to access the matched fields in the input. This creates the following output: [['Enter Date for Precession as (MM-DD-YYYY) or C/R for ', '05-28-2004', ... - data: [['0022', '+', '002', '5.6564', '+0.2713', '00:22:37.54', ... - header: ['Enter Date for Precession as (MM-DD-YYYY) or C/R for ', ... - date: 05-28-2004 - julian_date: 2453153.5 2453153.5 ['0022', '+', '002', '5.6564', '+0.2713', '00:22:37.54', '00:16:16.65'] - end_time: 00:16:16.65 - fld1: ['0022', '+', '002'] - magnitude: 5.6564 - phase: +0.2713 - start_time: 00:22:37.54 00:22:37.54 00:16:16.65 +0.2713 ['0106', '+', '013', '17.2117', '+1.6052', '01:08:50.80', '01:36:18.58'] - end_time: 01:36:18.58 - fld1: ['0106', '+', '013'] - magnitude: 17.2117 - phase: +1.6052 - start_time: 01:08:50.80 01:08:50.80 01:36:18.58 +1.6052 You can get the complete program at this pastebin URL: http://pyparsing.pastebin.com/m6f0ae6bc If you still want to use re's, then this program might still help you in at least laying out what your re's should match for at different places in the data. -- Paul From jerry.vb at gmail.com Mon Sep 8 17:59:20 2008 From: jerry.vb at gmail.com (J. Van Brimmer) Date: Mon, 08 Sep 2008 08:59:20 -0700 Subject: [Tutor] How to match strange characters In-Reply-To: <953509956B0A4CDAB0787C8F65C44B15@AWA2> References: <953509956B0A4CDAB0787C8F65C44B15@AWA2> Message-ID: <48C54BD8.6010507@gmail.com> Thanks Paul, this looks like just what I need to reformat PRECESS's output into what I need. Thanks, Jerry Paul McGuire wrote: > Instead of trying to match on the weird characters, in order to remove them, > here is a pyparsing program that ignores those header lines and just > extracts the interesting data for each section. > > In a pyparsing program, you start by defining what patterns you want to look > for. This is similar to the re module, but uses friendlier names like > OneOrMore, Group, and Combine instead of special characters that require > backslashes and so on. By default, pyparsing skips over whitespace between > expressions, so we use Combine to override this (as in realnum, in which we > want to match "3.1415", but not "3 . 1415"). > > Here is the opening part of the program, that defines the basic bits in your > data file, and the input parameter prompts: > > from pyparsing import Combine, Word, nums, Literal, Group, oneOf, OneOrMore > > # define basic expressions > realnum = Combine(Word(nums) + "." + Word(nums)) > two_digit_num = Word(nums,exact=2) > four_digit_num = Word(nums,exact=4) > date = Combine(two_digit_num + '-' + two_digit_num + '-' + four_digit_num) > timestamp = Combine(two_digit_num + ':' + two_digit_num + ':' + > two_digit_num + '.' + two_digit_num) > > # literal prompt strings > enter_date = Literal("Enter Date for Precession as (MM-DD-YYYY) or C/R for > ") > enter_catalog = Literal("Enter the Catalog Name or C/R for CATALOG.SRC >") > the_julian_date_is = Literal("The Julian Date is =") > > # build up the header definition > enter_date_line = enter_date + date + ">" > julian_date_line = the_julian_date_is + realnum("julian_date") > header = Group(enter_date_line + date("date") + > enter_catalog + julian_date_line) > > > This next part uses similar style to define the format of the lines of data. > > # build up the definition for a line of data > field_1 = Word(nums,exact=4) + "+" + Word(nums,exact=3) > field_2 = realnum > field_3 = Combine(oneOf("+ -") + realnum) > field_4 = timestamp > field_5 = timestamp > # change the results names as appropriate - I just made these up > data_line = Group( field_1("fld1") + field_2("magnitude") + > field_3("phase") + field_4("start_time") + field_5("end_time") ) > > I guessed at/made up names for the fields in the data_line ("fld1", > "magnitude", etc.). You should change these to names that make sense in > your application. > > Now a final definition that puts everything together: > > # put everything together into a PRECESS run header+data section > section = header("header") + OneOrMore(data_line)("data") > > > And now use section.scanString to locate all the matching data in your input > file: > test = """ > ?????????????????????????????????????????????? > ? Radio Source Precession Program ? > ? by John B. Doe ? > ? 31 August 1992 ? > ?????????????????????????????????????????????? > Enter Date for Precession as (MM-DD-YYYY) or C/R for 05-28-2004 > > 05-28-2004 > Enter the Catalog Name or C/R for CATALOG.SRC > > The Julian Date is = 2453153.5 > 0022+002 5.6564 +0.2713 00:22:37.54 00:16:16.65 > 0106+013 17.2117 +1.6052 01:08:50.80 01:36:18.58 > """ > > # use scanString to read through the input data - this will ignore the > # parts of the header with the weird characters > for data_section, start,end in section.scanString(test): > # each data_section returns the parsed results, which can be treated > # like an object or a dict, using the results names for attribute names > # or dict keys - the dump() method shows a structured output, keys() > # values(), and items() work just like in a dict > print data_section.dump() > print data_section.header.julian_date > # note the use of results name to access the "data" part > for d in data_section.data: > print d.dump() > print " ", d.start_time, d.end_time, d.phase > > > Note how the results names are used to access the matched fields in the > input. > > This creates the following output: > [['Enter Date for Precession as (MM-DD-YYYY) or C/R for ', '05-28-2004', ... > - data: [['0022', '+', '002', '5.6564', '+0.2713', '00:22:37.54', ... > - header: ['Enter Date for Precession as (MM-DD-YYYY) or C/R for ', ... > - date: 05-28-2004 > - julian_date: 2453153.5 > 2453153.5 > ['0022', '+', '002', '5.6564', '+0.2713', '00:22:37.54', '00:16:16.65'] > - end_time: 00:16:16.65 > - fld1: ['0022', '+', '002'] > - magnitude: 5.6564 > - phase: +0.2713 > - start_time: 00:22:37.54 > 00:22:37.54 00:16:16.65 +0.2713 > ['0106', '+', '013', '17.2117', '+1.6052', '01:08:50.80', '01:36:18.58'] > - end_time: 01:36:18.58 > - fld1: ['0106', '+', '013'] > - magnitude: 17.2117 > - phase: +1.6052 > - start_time: 01:08:50.80 > 01:08:50.80 01:36:18.58 +1.6052 > > You can get the complete program at this pastebin URL: > http://pyparsing.pastebin.com/m6f0ae6bc > > If you still want to use re's, then this program might still help you in at > least laying out what your re's should match for at different places in the > data. > > -- Paul > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From rickrune at gmail.com Mon Sep 8 19:59:56 2008 From: rickrune at gmail.com (Rick Rune) Date: Mon, 8 Sep 2008 10:59:56 -0700 Subject: [Tutor] Having Python check a program in win32. Message-ID: I'm looking to create a Python timed infinite loop (run foo, wait 1min, run foo) that will monitor if a particular program is running under Win32, and if it is not running to execute it. Can someone point me in the right direction to look? Thanks, -Rick -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at timgolden.me.uk Mon Sep 8 21:31:39 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 08 Sep 2008 20:31:39 +0100 Subject: [Tutor] Having Python check a program in win32. In-Reply-To: References: Message-ID: <48C57D9B.5010807@timgolden.me.uk> Rick Rune wrote: > I'm looking to create a Python timed infinite loop (run foo, wait 1min, > run foo) that will monitor if a particular program is running under > Win32, and if it is not running to execute it. Can someone point me in > the right direction to look? WMI. Example of sort here: http://timgolden.me.uk/python/wmi_cookbook.html#watch_notepad tho' you'll need to adjust it to meet your needs. TJG From Mike.Hansen at atmel.com Mon Sep 8 23:13:37 2008 From: Mike.Hansen at atmel.com (Hansen, Mike) Date: Mon, 8 Sep 2008 15:13:37 -0600 Subject: [Tutor] Support for datetime module In-Reply-To: <1c2a2c590809060608te12e23bp5e63305ec4be2a4f@mail.gmail.com> References: <20080906064240.FETN1865.nschwotgx02p.mx.bigpond.com@JohanPC> <1c2a2c590809060608te12e23bp5e63305ec4be2a4f@mail.gmail.com> Message-ID: <7941B2693F32294AAF16C26B679A258D03908A87@csomb01.corp.atmel.com> > -----Original Message----- > From: tutor-bounces+mike.hansen=atmel.com at python.org > [mailto:tutor-bounces+mike.hansen=atmel.com at python.org] On > Behalf Of Kent Johnson > Sent: Saturday, September 06, 2008 7:08 AM > To: johan at accesstel.com.au > Cc: tutor at python.org > Subject: Re: [Tutor] Support for datetime module > > On Sat, Sep 6, 2008 at 2:42 AM, Johan Geldenhuys > wrote: > > Hi all, > > > > I have want to use the datetime module on a system with ver > 2.2.3 installed. > > I know it's very old, but that's what I have to deal with > and can't upgrade. > > So please don't suggest that. > > > > As you know datetime was available from version 2.3. > > > > > > > > I want to know where can I get the datetime module so that > I can include it > > in my package that I use on my device? > > datetime is implemented in C so getting the version from 2.3 to work > on 2.2 might be difficult. > > Apparently the version in the std lib is derived from a Python version > that was part of Zope, this might be helpful if you can find the > source it refers to: > http://www.zope.org/Members/fdrake/DateTimeWiki/FrontPage > > Kent This is probably moot since the OP solved the issue using other means, but I thought datetime was based on mxdatetime. Even if it isn't, mxdatetime supports Python 2.1 and newer. http://www.egenix.com/products/python/mxBase/mxDateTime/ Mike From johan at accesstel.com.au Tue Sep 9 08:34:34 2008 From: johan at accesstel.com.au (Johan Geldenhuys) Date: Tue, 9 Sep 2008 16:34:34 +1000 Subject: [Tutor] Support for datetime module In-Reply-To: <7941B2693F32294AAF16C26B679A258D03908A87@csomb01.corp.atmel.com> Message-ID: <20080909063501.UBTN2301.nschwotgx01p.mx.bigpond.com@JohanPC> I managed to get a version of the datetime module in Python and used in my package. It works fine. Thanks Johan -----Original Message----- From: tutor-bounces+johan=accesstel.com.au at python.org [mailto:tutor-bounces+johan=accesstel.com.au at python.org] On Behalf Of Hansen, Mike Sent: Tuesday, 9 September 2008 7:14 AM To: tutor at python.org Subject: Re: [Tutor] Support for datetime module > -----Original Message----- > From: tutor-bounces+mike.hansen=atmel.com at python.org > [mailto:tutor-bounces+mike.hansen=atmel.com at python.org] On > Behalf Of Kent Johnson > Sent: Saturday, September 06, 2008 7:08 AM > To: johan at accesstel.com.au > Cc: tutor at python.org > Subject: Re: [Tutor] Support for datetime module > > On Sat, Sep 6, 2008 at 2:42 AM, Johan Geldenhuys > wrote: > > Hi all, > > > > I have want to use the datetime module on a system with ver > 2.2.3 installed. > > I know it's very old, but that's what I have to deal with > and can't upgrade. > > So please don't suggest that. > > > > As you know datetime was available from version 2.3. > > > > > > > > I want to know where can I get the datetime module so that > I can include it > > in my package that I use on my device? > > datetime is implemented in C so getting the version from 2.3 to work > on 2.2 might be difficult. > > Apparently the version in the std lib is derived from a Python version > that was part of Zope, this might be helpful if you can find the > source it refers to: > http://www.zope.org/Members/fdrake/DateTimeWiki/FrontPage > > Kent This is probably moot since the OP solved the issue using other means, but I thought datetime was based on mxdatetime. Even if it isn't, mxdatetime supports Python 2.1 and newer. http://www.egenix.com/products/python/mxBase/mxDateTime/ Mike _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From pine508 at hotmail.com Wed Sep 10 00:56:37 2008 From: pine508 at hotmail.com (Che M) Date: Tue, 9 Sep 2008 18:56:37 -0400 Subject: [Tutor] ways to sync databases with Python and SQLite? Message-ID: Hi list, I have been trying to create a small desktop application with Python that uses a small SQLite database. Recently I've got use of a 2nd computer (for my job) and have thought now about using the app on that one as well. I'd like to get ideas about how I could extend the application so that the databases on each computer could be kept "synchronized" (not sure that is the right term here); that is, each new change on either computer would be updated on the other computer(s), given a bit of help from the user. I know that, for example, the Chandler PIM has a "hub" that allows sync'ing across multiple computers (though I was surprised to see it is a 8 step process for the user: http://chandlerproject.org/Projects/GetStarted#Sync%20Chandler%20Desktop%20across%20Mul ) (I realize a good way to do all of this is entirely as a web service, but that is beyond my abilities, and I am trying to just complete a desktop app before learning much of that) So, if anyone has ideas on ways to do this with Python and Sqlite that are: - fairly simple (I'm not a real programmer) - not laborious for the user to do (so that they actually keep the two dbs in sync) I'd love to hear about it. Thanks, Che _________________________________________________________________ Stay up to date on your PC, the Web, and your mobile phone with Windows Live. http://clk.atdmt.com/MRT/go/msnnkwxp1020093185mrt/direct/01/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Sep 10 01:51:02 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 10 Sep 2008 00:51:02 +0100 Subject: [Tutor] ways to sync databases with Python and SQLite? References: Message-ID: "Che M" wrote in message > I'd like to get ideas about how I could extend the application so > that the > databases on each computer could be kept "synchronized" How do you intend to get the two computers to talk? Basically for any kind of synch both com,puters need to be able to compare notes. So the first question is what do we mean by synching here. Will it be over a network (the internet?)? Is it via a memory stick file transfer? > (I realize a good way to do all of this is entirely as > a web service, but that is beyond my abilities, Its one possibility but I'm not sure I'd say it was "the best" way. > So, if anyone has ideas on ways to do this with Python > and Sqlite that are: > - fairly simple (I'm not a real programmer) If you are using Python and SQLite then I beg to differ :-) The key here is to keep a rolling log of what has changed. It can be a simple text file - which can be transferred between PCs and used to synch or it could be a database table. You then read both synch logs and eliminate conflicts then apply the merged set of changes. (A lot easier said than done!) You might want to try a dummy application with a single table and limited update opportunities to get the feel for this before trying it on the real data! And be sure to take copious backups while testing! HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Wed Sep 10 03:47:36 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 9 Sep 2008 21:47:36 -0400 Subject: [Tutor] ways to sync databases with Python and SQLite? In-Reply-To: References: Message-ID: <1c2a2c590809091847p14f0f46ao2fddf63e7112887c@mail.gmail.com> On Tue, Sep 9, 2008 at 6:56 PM, Che M wrote: > Hi list, > > I have been trying to create a small desktop application with Python > that uses a small SQLite database. Recently I've got use of a 2nd computer > (for my job) and have thought now about using the app on that one as well. > > I'd like to get ideas about how I could extend the application so that the > databases on each computer could be kept "synchronized" (not sure that is > the right term here); that is, each new change on either computer would > be updated on the other computer(s), given a bit of help from the user. Does it have to be SQLite? Many databases, but not SQLite, can run as a server. If both computers are on the same network, an easy way to keep them in sync would be for them both to share a singe database. Both MySQL and PostgreSQL are free and work this way. > (I realize a good way to do all of this is entirely as a web service, but > that is beyond > my abilities, and I am trying to just complete a desktop app before learning > much of that) Web applications aren't necessarily that hard. For example you can get simple create/read/update/delete functionality pretty much for free with Django (in the admin and databrowse apps). http://www.djangobook.com/en/1.0/chapter06/ http://www.djangoproject.com/documentation/databrowse/ http://www.b-list.org/weblog/2007/nov/13/instant-sites/ You could continue to use the SQLite database, serve it from one computer and view it from both. Of course I have no idea how complex your app is and whether this will come close to meeting your needs... Kent From flaxeater at gmail.com Wed Sep 10 17:01:20 2008 From: flaxeater at gmail.com (Chad Crabtree) Date: Wed, 10 Sep 2008 11:01:20 -0400 Subject: [Tutor] ways to sync databases with Python and SQLite? In-Reply-To: References: Message-ID: <584940990809100801n621e10d6u5613ae5694c52571@mail.gmail.com> One way to work around this and still use SQLight is to put the database on a shared drive. SQLight does table locking, or is it file locking. Anyways conflicts will be very minimal to non-existant with only two clients as most operations will complete in microseconds. The SQLight website even says this is a fine practice. However synchronizing two separeatly running databases is a very hard task, and is very very easy to get wrong. However if all that one does is read and does no updates or deletes then you could just copy the database over to the 'client' user. On Tue, Sep 9, 2008 at 6:56 PM, Che M wrote: > Hi list, > > I have been trying to create a small desktop application with Python > that uses a small SQLite database. Recently I've got use of a 2nd computer > > (for my job) and have thought now about using the app on that one as well. > > > I'd like to get ideas about how I could extend the application so that the > databases on each computer could be kept "synchronized" (not sure that is > the right term here); that is, each new change on either computer would > be updated on the other computer(s), given a bit of help from the user. > > I know that, for example, the Chandler PIM has a "hub" that allows sync'ing > across > multiple computers (though I was surprised to see it is a 8 step process > for the user: > > http://chandlerproject.org/Projects/GetStarted#Sync%20Chandler%20Desktop%20across%20Mul) > > (I realize a good way to do all of this is entirely as a web service, but > that is beyond > my abilities, and I am trying to just complete a desktop app before > learning much of that) > > So, if anyone has ideas on ways to do this with Python and Sqlite that are: > - fairly simple (I'm not a real programmer) > - not laborious for the user to do (so that they actually keep the two dbs > in sync) > I'd love to hear about it. > > Thanks, > Che > > > ------------------------------ > Stay up to date on your PC, the Web, and your mobile phone with Windows > Live. See Now > > _______________________________________________ > 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 Wed Sep 10 17:41:31 2008 From: pine508 at hotmail.com (Che M) Date: Wed, 10 Sep 2008 11:41:31 -0400 Subject: [Tutor] ways to sync databases with Python and SQLite? In-Reply-To: <1c2a2c590809091847p14f0f46ao2fddf63e7112887c@mail.gmail.com> References: <1c2a2c590809091847p14f0f46ao2fddf63e7112887c@mail.gmail.com> Message-ID: > > I'd like to get ideas about how I could extend the application so that the > > databases on each computer could be kept "synchronized" (not sure that is > > the right term here); that is, each new change on either computer would > > be updated on the other computer(s), given a bit of help from the user. > > Does it have to be SQLite? Many databases, but not SQLite, can run as > a server. If both computers are on the same network, an easy way to > keep them in sync would be for them both to share a single database. > Both MySQL and PostgreSQL are free and work this way. It doesn't have to be SQLite--that's just what I've been learning, and there are things about it that strike me as good for my purposes. But the app is not intended to be used with a network. What I am envisioning is a personal application that one uses on one's home computer and work computers, but in most cases they'd not be on the same network. As someone else suggested, I could just copy, via a flash drive, the most recently written-to SQLite database file to the other computer, but that seems likely to go wrong in that I or the user would inevitably, at some point, wind up erasing the whole database or copying the wrong direction, etc., and I don't want this to require any user carefulness to maintain the two copies in sync. > Web applications aren't necessarily that hard. For example you can get > simple create/read/update/delete functionality pretty much for free > with Django (in the admin and databrowse apps). > http://www.djangobook.com/en/1.0/chapter06/ > http://www.djangoproject.com/documentation/databrowse/ > http://www.b-list.org/weblog/2007/nov/13/instant-sites/ I will look into that; thanks, Kent, for the references. Che _________________________________________________________________ Get more out of the Web. Learn 10 hidden secrets of Windows Live. http://windowslive.com/connect/post/jamiethomson.spaces.live.com-Blog-cns!550F681DAD532637!5295.entry?ocid=TXT_TAGLM_WL_domore_092008 -------------- next part -------------- An HTML attachment was scrubbed... URL: From pine508 at hotmail.com Wed Sep 10 17:52:17 2008 From: pine508 at hotmail.com (Che M) Date: Wed, 10 Sep 2008 11:52:17 -0400 Subject: [Tutor] ways to sync databases with Python and SQLite? In-Reply-To: References: Message-ID: > "Che M" wrote in message > > > I'd like to get ideas about how I could extend the application so > > that the > > databases on each computer could be kept "synchronized" > > How do you intend to get the two computers to talk? > Basically for any kind of synch both com,puters need to > be able to compare notes. So the first question is what > do we mean by synching here. Will it be over a network > (the internet?)? Is it via a memory stick file transfer? Considering that I want to lower the bar for the user to as low/lazy as possible--and not require them to remember to transfer the files with a flash drive or whatever--I'd think through the internet would be the best. As I replied to Kent's reply, the two computers would not be on a shared local network, though they both would have internet access. > > So, if anyone has ideas on ways to do this with Python > > and Sqlite that are: > > - fairly simple (I'm not a real programmer) > > If you are using Python and SQLite then I beg to differ :-) I appreciate that, but I often feel like a fledgling photographer who has use of a Hasselblad camera--great tools, not so great tool user! :) (but thanks to this list and others and patience...getting there...) > The key here is to keep a rolling log of what has changed. > It can be a simple text file - which can be transferred between > PCs and used to synch or it could be a database table. > You then read both synch logs and eliminate conflicts then > apply the merged set of changes. (A lot easier said than done!) > > You might want to try a dummy application with a single table > and limited update opportunities to get the feel for this before > trying it on the real data! And be sure to take copious backups > while testing! I will try something like this and then try to incorporate it with Kent's suggestion of having a (reasonably?) simple way to access this log file via a website using, maybe, Django. Keep in mind, my database will mainly be just adding about 1-10 rows a day, very little UPDATES (editing already-present rows), and will only have about 3-4 tables, 10 fields and hundreds (or at most a few thousands) of rows. It is not a business application with a big and rapidly changing database, and by definition only one change can happen at a time. Thanks, Alan, Che _________________________________________________________________ See how Windows Mobile brings your life together?at home, work, or on the go. http://clk.atdmt.com/MRT/go/msnnkwxp1020093182mrt/direct/01/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From flaxeater at gmail.com Wed Sep 10 17:57:24 2008 From: flaxeater at gmail.com (Chad Crabtree) Date: Wed, 10 Sep 2008 11:57:24 -0400 Subject: [Tutor] ways to sync databases with Python and SQLite? In-Reply-To: References: Message-ID: <584940990809100857o6cb60782w549abab2679a6b46@mail.gmail.com> One way to work around this and still use SQLight is to put the database on a shared drive. SQLight does table locking, or is it file locking. Anyways conflicts will be very minimal to non-existant with only two clients as most operations will complete in microseconds. The SQLight website even says this is a fine practice. However synchronizing two separeatly running databases is a very hard task, and is very very easy to get wrong. However if all that one does is read and does no updates or deletes then you could just copy the database over to the 'client' user. On Tue, Sep 9, 2008 at 6:56 PM, Che M wrote: > Hi list, > > I have been trying to create a small desktop application with Python > that uses a small SQLite database. Recently I've got use of a 2nd computer > > (for my job) and have thought now about using the app on that one as well. > > > I'd like to get ideas about how I could extend the application so that the > databases on each computer could be kept "synchronized" (not sure that is > the right term here); that is, each new change on either computer would > be updated on the other computer(s), given a bit of help from the user. > > I know that, for example, the Chandler PIM has a "hub" that allows sync'ing > across > multiple computers (though I was surprised to see it is a 8 step process > for the user: > > http://chandlerproject.org/Projects/GetStarted#Sync%20Chandler%20Desktop%20across%20Mul) > > (I realize a good way to do all of this is entirely as a web service, but > that is beyond > my abilities, and I am trying to just complete a desktop app before > learning much of that) > > So, if anyone has ideas on ways to do this with Python and Sqlite that are: > - fairly simple (I'm not a real programmer) > - not laborious for the user to do (so that they actually keep the two dbs > in sync) > I'd love to hear about it. > > Thanks, > Che > > > ------------------------------ > Stay up to date on your PC, the Web, and your mobile phone with Windows > Live. See Now > > _______________________________________________ > 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 Wed Sep 10 18:02:06 2008 From: pine508 at hotmail.com (Che M) Date: Wed, 10 Sep 2008 12:02:06 -0400 Subject: [Tutor] ways to sync databases with Python and SQLite? In-Reply-To: <584940990809100801n621e10d6u5613ae5694c52571@mail.gmail.com> References: <584940990809100801n621e10d6u5613ae5694c52571@mail.gmail.com> Message-ID: > One way to work around this and still use SQLight is to put the database on a shared drive. SQLight does table locking, or is it file locking. > Anyways conflicts will be very minimal to non-existant with only two clients as most operations will complete in microseconds. The SQLight > website even says this is a fine practice. I could have the database on a flash drive. I'd like to avoid that, though, because inevitably the user (mostly me) will forget to bring the drive back and forth from computer to computer. > However synchronizing two separeatly running databases is a very hard task, and is very very easy to get wrong. Well, when you say "seperately running"... In my case, it would be rare (or maybe never) that one would be writing to one computer's copy of the database at the same time as the other computer was doing it on its own. The app would be logging things in real time on one computer. Later, the other computer needs to get the update so it knows what happened. But the two copies of the database are accessed in a usually mutually exclusive way (although, yes, I guess you could run both apps on both computers at the same time and then make things difficult). I get the sense that Alan's idea of a log file to tell each DB how to change to keep current would work. What are the "very hard" aspects of that? (I don't doubt there are some real difficulties). > However if all that one does is read and does no updates or deletes then you could just copy the database over to the 'client' user. No, both DBs are going to be writing and updating. Thanks, Chad. Che On Tue, Sep 9, 2008 at 6:56 PM, Che M wrote: Hi list, I have been trying to create a small desktop application with Python that uses a small SQLite database. Recently I've got use of a 2nd computer (for my job) and have thought now about using the app on that one as well. I'd like to get ideas about how I could extend the application so that the databases on each computer could be kept "synchronized" (not sure that is the right term here); that is, each new change on either computer would be updated on the other computer(s), given a bit of help from the user. I know that, for example, the Chandler PIM has a "hub" that allows sync'ing across multiple computers (though I was surprised to see it is a 8 step process for the user: http://chandlerproject.org/Projects/GetStarted#Sync%20Chandler%20Desktop%20across%20Mul ) (I realize a good way to do all of this is entirely as a web service, but that is beyond my abilities, and I am trying to just complete a desktop app before learning much of that) So, if anyone has ideas on ways to do this with Python and Sqlite that are: - fairly simple (I'm not a real programmer) - not laborious for the user to do (so that they actually keep the two dbs in sync) I'd love to hear about it. Thanks, Che Stay up to date on your PC, the Web, and your mobile phone with Windows Live. See Now _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor _________________________________________________________________ Want to do more with Windows Live? Learn ?10 hidden secrets? from Jamie. http://windowslive.com/connect/post/jamiethomson.spaces.live.com-Blog-cns!550F681DAD532637!5295.entry?ocid=TXT_TAGLM_WL_domore_092008 -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Sep 10 19:30:07 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 10 Sep 2008 18:30:07 +0100 Subject: [Tutor] ways to sync databases with Python and SQLite? References: <584940990809100801n621e10d6u5613ae5694c52571@mail.gmail.com> Message-ID: "Che M" wrote > I get the sense that Alan's idea of a log file to tell each DB > how to change to keep current would work. What > are the "very hard" aspects of that? The main issues are around conflicting edits. If both are just adding records its OK but if one deletes a record and the other subsequently updates the same record things get a tad confusing! You need to merge the two lots of changes in time order then remove any rogue deletes and manage parallel updates. If you only allow additions to be sync'd then its all a lot easier. Or you can only apply the last update (even if for different fields). Several options to simplify things. But too simple ultimately means inconsistent records... -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From rdm at rcblue.com Wed Sep 10 21:43:01 2008 From: rdm at rcblue.com (Dick Moores) Date: Wed, 10 Sep 2008 12:43:01 -0700 Subject: [Tutor] How to revise script to call my non-default browser? Message-ID: <20080910194324.5D2E51E4012@bag.python.org> Please see This was working fine until I made Google Chrome my default browser (on Win XP). I'm having a lot of trouble with getting Chrome to play video and audio linked to on a web page. Actually, I don't need the script to call a browser at all. I just want it to call to call RealPlayer at a certain time to start playing KUOW. So I suppose I'm looking at revising line 66? Help? Thanks, Dick Moores From grishma20 at gmail.com Wed Sep 10 22:06:43 2008 From: grishma20 at gmail.com (grishma govani) Date: Wed, 10 Sep 2008 21:06:43 +0100 Subject: [Tutor] Email and MIME Message-ID: <249DAF33-9953-47F2-8CBE-4609B41AD1F0@gmail.com> Hello Everybody, I have been trying to extract the body of all the email messages from an mbox file. I have manages to separate the headers and get a string out that looks like 1) and 2) I would like to just extract the message and if there is only jibberish as in the case of 1), I would extract nothing. Can anyone help me with this. Any help would be appreciated. -Grishma 1)Subject: Fwd: Corrections Attachment: None Body: SGV5IEpvc2VmLApJJ20gYXR0YWNoaW5nIHRoZSBwZGYgd2l0aCB0aGUgY29ycmVjdGVkIHZlcnNp b24gb2YgdGhlIHRoZXNpcy4gQmVsb3cgaXMgdGhlCnN1bW1hcnkgb2YgY2hhbmdlcy4KCgoKMS4x IHBhZ2UgMToKYWRkZWQgZm9vdG5vdGUgY2xhcmlmeWluZyBzaGFsbG93IHBhcnNpbmcKCjEuMiBw 2) Subject: Paper Outline Attachment: None Body: ------=_Part_58921_30058516.1220801860686 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit Content-Disposition: inline Hi S, I have attached my paper outline to this e-mail. Any suggestions would be much appreciated -X ------=_Part_58921_30058516.1220801860686 Content-Type: text/html; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit Content-Disposition: inline
Hi S,

I have attached my paper outline to this e- mail.
Any suggestions would be much appreciated

-X
------=_Part_58921_30058516.1220801860686-- From Mike.Hansen at atmel.com Wed Sep 10 22:22:04 2008 From: Mike.Hansen at atmel.com (Hansen, Mike) Date: Wed, 10 Sep 2008 14:22:04 -0600 Subject: [Tutor] NetBeans IDE Message-ID: <7941B2693F32294AAF16C26B679A258D039565C5@csomb01.corp.atmel.com> Being an editor/IDE junkie, I'm curious about the NetBeans IDE. Is anyone using it? If so, how is it? I believe it has a add-on for python.(NBPython) Mike From kent37 at tds.net Wed Sep 10 23:09:32 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 10 Sep 2008 17:09:32 -0400 Subject: [Tutor] Email and MIME In-Reply-To: <249DAF33-9953-47F2-8CBE-4609B41AD1F0@gmail.com> References: <249DAF33-9953-47F2-8CBE-4609B41AD1F0@gmail.com> Message-ID: <1c2a2c590809101409j7b53b987ndcb879728527e2cd@mail.gmail.com> On Wed, Sep 10, 2008 at 4:06 PM, grishma govani wrote: > Hello Everybody, > > I have been trying to extract the body of all the email messages from an > mbox file. How are you doing this? Have you seen the mailbox module and this recipe: http://docs.python.org/lib/mailbox-mbox.html http://code.activestate.com/recipes/157437/ Kent From alan.gauld at btinternet.com Thu Sep 11 02:10:43 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 11 Sep 2008 01:10:43 +0100 Subject: [Tutor] NetBeans IDE References: <7941B2693F32294AAF16C26B679A258D039565C5@csomb01.corp.atmel.com> Message-ID: "Hansen, Mike" wrote > Being an editor/IDE junkie, I'm curious about the NetBeans IDE. > Is anyone using it? If so, how is it? I used it briefly in one of my several attempts to like Java. About 3 years ago I think? I preferred it to Eclipse at the time, but I've now moved to Eclipse (peer pressure and need for some plugins mainly) and so have stopped using Netbeans. It was dog slow on my 600MHz iBook with 256M of RAM but adequate on my 2GHz 1G Ram XP box.. > I believe it has a add-on for python.(NBPython) Yes, or at least Jython, and it worked fine. I can't recall if I ever had CPython working... HTH, Alan G. From sierra_mtnview at sbcglobal.net Thu Sep 11 02:13:42 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Wed, 10 Sep 2008 17:13:42 -0700 Subject: [Tutor] Dealing with Microseconds Message-ID: <48C862B6.90108@sbcglobal.net> An HTML attachment was scrubbed... URL: From kent37 at tds.net Thu Sep 11 03:37:48 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 10 Sep 2008 21:37:48 -0400 Subject: [Tutor] Dealing with Microseconds In-Reply-To: <48C862B6.90108@sbcglobal.net> References: <48C862B6.90108@sbcglobal.net> Message-ID: <1c2a2c590809101837p7c211b5avf874e61bc0fd4d1a@mail.gmail.com> On Wed, Sep 10, 2008 at 8:13 PM, Wayne Watson wrote: > I'd like to allow a user to enter a drift rate in seconds per day into a > program along with the date and time, a base, to begin calculation of > subsequent recorded date and times. datetime seems to only allow hours, > minutes and seconds in its formats. For example, 2.74 might be entered. > Using 2.74 for a time that's 24 hours from the base would cause me to record > the increase as 2 seconds. How can I account for fractional increases? I see > that the tuple allows for microseconds, but I'm not sure arithmetic or > formatting is allowed on it. I don't really understand your problem statement, maybe a better example would help? Anyway both datetime and timedelta support microseconds so I think the basic mechanism is there in the data structures. What is missing is support in strptime() / strftime(). You can easily tack on milliseconds to a formatted date. For example, In [1]: from datetime import datetime, timedelta In [4]: n Out[4]: datetime.datetime(2008, 9, 10, 21, 31, 39, 937000) In [8]: n.strftime('%Y%m%d_%H%M%S') Out[8]: '20080910_213139' In [11]: '%s.%3d' % (n.strftime('%Y%m%d_%H%M%S'), n.microsecond/1000) Out[11]: '20080910_213139.937' In [13]: n += timedelta(seconds=2, milliseconds=740) In [14]: '%s.%3d' % (n.strftime('%Y%m%d_%H%M%S'), n.microsecond/1000) Out[14]: '20080910_213142.677' Kent From sierra_mtnview at sbcglobal.net Thu Sep 11 04:08:42 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Wed, 10 Sep 2008 19:08:42 -0700 Subject: [Tutor] Dealing with Microseconds In-Reply-To: <1c2a2c590809101837p7c211b5avf874e61bc0fd4d1a@mail.gmail.com> References: <48C862B6.90108@sbcglobal.net> <1c2a2c590809101837p7c211b5avf874e61bc0fd4d1a@mail.gmail.com> Message-ID: <48C87DAA.1090308@sbcglobal.net> An HTML attachment was scrubbed... URL: From jgowen at lorettotel.net Thu Sep 11 05:29:01 2008 From: jgowen at lorettotel.net (Johnny) Date: Wed, 10 Sep 2008 22:29:01 -0500 Subject: [Tutor] absolute beginner Message-ID: <48C8907D.6090100@lorettotel.net> An HTML attachment was scrubbed... URL: From bhaaluu at gmail.com Thu Sep 11 07:07:31 2008 From: bhaaluu at gmail.com (bhaaluu) Date: Thu, 11 Sep 2008 01:07:31 -0400 Subject: [Tutor] absolute beginner In-Reply-To: <48C8907D.6090100@lorettotel.net> References: <48C8907D.6090100@lorettotel.net> Message-ID: On Wed, Sep 10, 2008 at 11:29 PM, Johnny wrote: > Anyone have any advice for an all out beginner? > Advice as in... The best book?...best tutor web page? > I am wanting so badly to learn Python. > > I have went to this site... > http://www.awaretek.com/tutorials.html > > This gave me lots of info,, but with so many books to choose from, I can't > seem to find that special one that will give me (a complete dummy) the info > I need. > > thanks > Johnny > I found this book to be a great tutorial: Python Programming for the Absolute Beginner Second Edition. Michael Dawson. Boston, MA:Thompson Course Technology, 2006. ISBN: 1598631128 Dawson uses games to teach Python. The examples are games, so the book is a lot of fun to work through. Being fun, you'll learn easier and faster than if the examples were boring academic examples. Most of the games are text-based, but the last two chapters introduce you to graphics, sound, music, and animation. 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 jerry.vb at gmail.com Thu Sep 11 07:31:17 2008 From: jerry.vb at gmail.com (J. Van Brimmer) Date: Wed, 10 Sep 2008 22:31:17 -0700 Subject: [Tutor] absolute beginner In-Reply-To: <48C8907D.6090100@lorettotel.net> References: <48C8907D.6090100@lorettotel.net> Message-ID: <48C8AD25.6040708@gmail.com> Johnny wrote: > Anyone have any advice for an all out beginner? > Advice as in... The best book?...best tutor web page? > I am wanting so badly to learn Python. > > I have went to this site... > http://www.awaretek.com/tutorials.html > > This gave me lots of info,, but with so many books to choose from, I > can't seem to find that special one that will give me (a complete > dummy) the info I need. > > thanks > Johnny > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > I'm not an absolute beginner, but I've been studying Python for about a year. I've found these to be of great help: 1) Start here: http://wiki.python.org/moin/BeginnersGuide 2) And here: http://wiki.python.org/moin/BeginnersGuide I have found these books to be the most helpful to me: 1) "Learning Python", by Mark Lutz & David Ascher, Publisher: O'Reilly 2) "Beginning Python", by Magnus Lie Hetland, Publisher: Apress 3) "Dive into Python", http://www.diveintopython.org/ There are lots of other tutorials available on the web, just do a google search for python tutorials. Here are some of my favorites: 1) http://wiki.python.org/moin/BeginnersGuide 2) http://www.codepedia.com/1/BeginnersGuideToPython_Functions 3) http://www.network-theory.co.uk/docs/pytut/index.html 4) http://bembry.org/technology/python/index.php 5) http://hetland.org/writing/instant-hacking.html Plus, there are some good forums: 1) http://www.daniweb.com/forums/forum114.html 2) http://python-forum.org/pythonforum/index.php 3) http://www.python.org/community/lists/ 4) http://www.dreamincode.net/forums/showforum29.htm 5) http://www.gidforums.com/f-52.html This should be enough to get you started. You'll just have to jump in and read, read, and read. :-) Happy reading! -------------- next part -------------- An HTML attachment was scrubbed... URL: From john at fouhy.net Thu Sep 11 07:43:58 2008 From: john at fouhy.net (John Fouhy) Date: Thu, 11 Sep 2008 17:43:58 +1200 Subject: [Tutor] absolute beginner In-Reply-To: <48C8AD25.6040708@gmail.com> References: <48C8907D.6090100@lorettotel.net> <48C8AD25.6040708@gmail.com> Message-ID: <5e58f2e40809102243g73166eddme48a28926f8f3493@mail.gmail.com> 2008/9/11 J. Van Brimmer : > This should be enough to get you started. You'll just have to jump in and > read, read, and read. :-) I would say: jump in and code, code, and code. Reading's easy, but if you're anything like me, you'll learn more through doing. The best thing a tutorial can do for you is give you a progression of things to do :-) -- John. From jerry.vb at gmail.com Thu Sep 11 07:46:41 2008 From: jerry.vb at gmail.com (J. Van Brimmer) Date: Wed, 10 Sep 2008 22:46:41 -0700 Subject: [Tutor] absolute beginner In-Reply-To: <5e58f2e40809102243g73166eddme48a28926f8f3493@mail.gmail.com> References: <48C8907D.6090100@lorettotel.net> <48C8AD25.6040708@gmail.com> <5e58f2e40809102243g73166eddme48a28926f8f3493@mail.gmail.com> Message-ID: <48C8B0C1.5010103@gmail.com> John Fouhy wrote: > 2008/9/11 J. Van Brimmer : > >> This should be enough to get you started. You'll just have to jump in and >> read, read, and read. :-) >> > > I would say: jump in and code, code, and code. Reading's easy, but if > you're anything like me, you'll learn more through doing. The best > thing a tutorial can do for you is give you a progression of things to > do :-) > > Well, I found that I had to read first, and then code, code, code... ;-) From grishma20 at gmail.com Thu Sep 11 10:22:52 2008 From: grishma20 at gmail.com (grishma govani) Date: Thu, 11 Sep 2008 09:22:52 +0100 Subject: [Tutor] Extracting body of all email messages from an mbox file on computer Message-ID: <87B0CBB9-40C7-4B79-BAAE-FBB368F6EC88@gmail.com> Yes, I used the part of the code from the second link. I am using the mailbox modules too. I have the e-mails from gmail in a file on my computer. I have used the code below extract all the headers. As you can see for now I am using text stored in document as my body. I just want to extract the plain text and leave out all the html, duplicates of plain text and all the other information like content type, from etc. Can anyone help me out? mb = mailbox.UnixMailbox(file('tmp/automated/Feedback', 'r')) fout = file('Feedback.txt', 'w') msg = mb.next() while msg is not None: document = msg.fp.read() document = passthrough_filter(msg, document) msg = mb.next() def passthrough_filter(msg, document): """This prints the 'from' address of the message and returns the document unchanged. """ from_addr = msg.getaddr('From')[0] Sub = msg.get('Subject') ContentType = msg.get('Content-Type') ContentDisp = msg.get('Content-Disposition') print "From:",from_addr print "Subject:",Sub print "Attachment:",None print "Body:",document print '\n' return document On 10 Sep 2008, at 22:09, Kent Johnson wrote: > On Wed, Sep 10, 2008 at 4:06 PM, grishma govani > wrote: >> Hello Everybody, >> >> I have been trying to extract the body of all the email messages >> from an >> mbox file. > > How are you doing this? Have you seen the mailbox module and this > recipe: > http://docs.python.org/lib/mailbox-mbox.html > http://code.activestate.com/recipes/157437/ > > Kent -------------- next part -------------- An HTML attachment was scrubbed... URL: From onyxtic at gmail.com Thu Sep 11 11:05:45 2008 From: onyxtic at gmail.com (Gmail) Date: Thu, 11 Sep 2008 10:05:45 +0100 Subject: [Tutor] NetBeans IDE References: <7941B2693F32294AAF16C26B679A258D039565C5@csomb01.corp.atmel.com> Message-ID: <001e01c913ee$a5b708f0$4101a8c0@compaq> Hi Mike, I use Eclipse for Java development with a very nice plugin for Python programming. Check out the PyDev plugin I think its for eclipse only - not sure if there's something for Netbeans. http://pydev.sourceforge.net/ -- Evans http://www.javawug.com ----- Original Message ----- From: "Hansen, Mike" To: Sent: Wednesday, September 10, 2008 9:22 PM Subject: [Tutor] NetBeans IDE > Being an editor/IDE junkie, I'm curious about the NetBeans IDE. Is anyone > using it? If so, how is it? I believe it has a add-on for > python.(NBPython) > Mike > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From jaggojaggo at gmail.com Wed Sep 10 18:13:52 2008 From: jaggojaggo at gmail.com (Jaggo) Date: Wed, 10 Sep 2008 19:13:52 +0300 Subject: [Tutor] Inserting an Indent in IDLE? In-Reply-To: References: <48C3E29E.1060005@sbcglobal.net> Message-ID: <515008f10809100913y3555ea89x8f5aef5f6a55322d@mail.gmail.com> In Pywin, and so I assume IDLE follows, you can just select more than One line and press tab. On Sun, Sep 7, 2008 at 5:41 PM, Alan Gauld wrote: > > "Wayne Watson" wrote > > Signature.htmlOccasionally I would like to indent 20-30 lines of code. >> I don't see a way to do this in IDLE other than brute force. >> > > Format->Indent region? > > Ctrl-] > > Format Dedent region > > Ctrl-[ > > Seems to work for me. > > Alan G > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Thu Sep 11 12:58:36 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Thu, 11 Sep 2008 03:58:36 -0700 Subject: [Tutor] Looking at a String as a Struct? Message-ID: <48C8F9DC.3080302@sbcglobal.net> An HTML attachment was scrubbed... URL: From kent37 at tds.net Thu Sep 11 13:06:20 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 11 Sep 2008 07:06:20 -0400 Subject: [Tutor] Email and MIME In-Reply-To: <7511234C-FD51-4AA2-A165-D049D8BA7E98@gmail.com> References: <249DAF33-9953-47F2-8CBE-4609B41AD1F0@gmail.com> <1c2a2c590809101409j7b53b987ndcb879728527e2cd@mail.gmail.com> <7511234C-FD51-4AA2-A165-D049D8BA7E98@gmail.com> Message-ID: <1c2a2c590809110406i2dc03a52x9e989646b311af07@mail.gmail.com> On Wed, Sep 10, 2008 at 10:30 PM, grishma govani wrote: > Yes, I used the part of the code from the second link. > I am using the mailbox modules too. > > I have the e-mails from gmail in a file on my computer. I have used the code > below extract all the headers. As you can see for now I am using text stored > in document as my body. I just want to extract the plain text and leave out > all the html, duplicates of plain text and all the other information like > content type, from etc. If you have an mbox format file, I suggest using mboxMailbox instead of UnixMailbox. UnixMailbox is perhaps obsolete - it is not documented and it uses the deprecated rfc822.Message to return the messages. rfc822.Message doesn't seem to have any ability to decode the message body, so you are getting the raw message data. mboxMailbox returns email.Message objects which understand encoding and multipart messages. Instead of msg.fp.read() you would use the richer email.Message methods to retrieve the data. See the last example at http://docs.python.org/lib/node161.html for some hints. Kent PS Please use Reply All to reply on list. > > mb = mailbox.UnixMailbox(file('tmp/automated/Feedback', 'r')) > fout = file('Feedback.txt', 'w') > msg = mb.next() > > while msg is not None: > document = msg.fp.read() > document = passthrough_filter(msg, document) > msg = mb.next() > > > def passthrough_filter(msg, document): > """This prints the 'from' address of the message and > returns the document unchanged. > """ > from_addr = msg.getaddr('From')[0] > Sub = msg.get('Subject') > ContentType = msg.get('Content-Type') > ContentDisp = msg.get('Content-Disposition') > print "From:",from_addr > print "Subject:",Sub > print "Attachment:",None > print "Body:",document > print '\n' > return document > > > > > On 10 Sep 2008, at 22:09, Kent Johnson wrote: > >> On Wed, Sep 10, 2008 at 4:06 PM, grishma govani >> wrote: >>> >>> Hello Everybody, >>> >>> I have been trying to extract the body of all the email messages from an >>> mbox file. >> >> How are you doing this? Have you seen the mailbox module and this recipe: >> http://docs.python.org/lib/mailbox-mbox.html >> http://code.activestate.com/recipes/157437/ >> >> Kent > > From srilyk at gmail.com Thu Sep 11 13:19:06 2008 From: srilyk at gmail.com (W W) Date: Thu, 11 Sep 2008 06:19:06 -0500 Subject: [Tutor] Looking at a String as a Struct? In-Reply-To: <48C8F9DC.3080302@sbcglobal.net> References: <48C8F9DC.3080302@sbcglobal.net> Message-ID: <333efb450809110419t6f69e73dmb4b2b4d3b63118cf@mail.gmail.com> On Thu, Sep 11, 2008 at 5:58 AM, Wayne Watson wrote: > Is it possible in Python to look at a string as a "struct". I don't think > a struct exists in python. Actually, is there something analogous to a > record. In the case of strings, suppose I have string that is composed of > sub-strings like, first_name, last-name, date_of birth, which consists of > month, day, and year, and finally SSN, street_address, state, city, and > zip_code. I'd like to access these fields directly instead of lastname = > record[38:55]. What if fields are not just strings, but some numeric > values? > My guess is you really want to use a dict. Perhaps a list of dicts... or a dict of lists. Some combination of the two should give you the functionality you're looking for. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Thu Sep 11 13:19:13 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 11 Sep 2008 07:19:13 -0400 Subject: [Tutor] Looking at a String as a Struct? In-Reply-To: <48C8F9DC.3080302@sbcglobal.net> References: <48C8F9DC.3080302@sbcglobal.net> Message-ID: <1c2a2c590809110419y14308765hf636acbde653ecb@mail.gmail.com> On Thu, Sep 11, 2008 at 6:58 AM, Wayne Watson wrote: > Is it possible in Python to look at a string as a "struct". I don't think a > struct exists in python. Actually, is there something analogous to a record. > In the case of strings, suppose I have string that is composed of > sub-strings like, first_name, last-name, date_of birth, which consists of > month, day, and year, and finally SSN, street_address, state, city, and > zip_code. I'd like to access these fields directly instead of lastname = > record[38:55]. What if fields are not just strings, but some numeric values? For numeric fields, just convert as needed: quantity = int(record[55:60]) price = float(record[60::70]) If the numbers are binary, rather than ascii, see the struct module. Kent From sierra_mtnview at sbcglobal.net Thu Sep 11 15:58:08 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Thu, 11 Sep 2008 06:58:08 -0700 Subject: [Tutor] Looking at a String as a Struct? In-Reply-To: <1c2a2c590809110419y14308765hf636acbde653ecb@mail.gmail.com> References: <48C8F9DC.3080302@sbcglobal.net> <1c2a2c590809110419y14308765hf636acbde653ecb@mail.gmail.com> Message-ID: <48C923F0.9060507@sbcglobal.net> An HTML attachment was scrubbed... URL: From onyxtic at gmail.com Thu Sep 11 16:54:00 2008 From: onyxtic at gmail.com (Evans) Date: Thu, 11 Sep 2008 15:54:00 +0100 Subject: [Tutor] absolute beginner References: <48C8907D.6090100@lorettotel.net> Message-ID: <00b701c9141e$3d232e60$4101a8c0@compaq> I'd start by going through Alan's marvellous material. They are very good for beginners like yourself. If you run into any problems, just post a message here. http://www.freenetpages.co.uk/hp/alan.gauld Happy coding! -- Evans http://www.javawug.org ----- Original Message ----- From: Johnny To: Python Sent: Thursday, September 11, 2008 4:29 AM Subject: [Tutor] absolute beginner Anyone have any advice for an all out beginner? Advice as in... The best book?...best tutor web page? I am wanting so badly to learn Python. I have went to this site... http://www.awaretek.com/tutorials.html This gave me lots of info,, but with so many books to choose from, I can't seem to find that special one that will give me (a complete dummy) the info I need. thanks Johnny ------------------------------------------------------------------------------ _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From oltarasenko at gmail.com Thu Sep 11 16:56:02 2008 From: oltarasenko at gmail.com (Oleg Oltar) Date: Thu, 11 Sep 2008 17:56:02 +0300 Subject: [Tutor] Threading Message-ID: Hi! I need to open about 1200 urls from my database. And to check that those urls are really exists. I used urllib2.urlopen for it. But it's a little bit slow. I thought that it's might be a good idea to do it in a threads. So it can add some performance to my code. Unfortunately I can't get started with the treading module. There are no simple examples in the python docs. Not sure how to start. What I want to have: for my list of urls I want to start few threads, each one of them should do some validation. My code without threads: def queryDb(query, db_name = sys.argv[1]): db = MySQLdb.connect(db = db_name, read_default_file="~/.my.cnf") c = db.cursor() c.execute(query) return c def openUrl(url): error = '' try: urllib2.urlopen(url) except (urllib2.URLError, urllib2.HTTPError,httplib.BadStatusLine), error: pass return str(error) def isValuePresent(dbField): if str(dbField).find('None') is not -1: return False else: return True def displayResults(resultTable): for query in resultTable: print query def processUrl(url, guid, parent_guid): def testUrls(): error = '' resultTable = [] errorTable = ['None'] products = queryDb(query = """SELECT url, guid, parent from product;""") i = 0 for product in products.fetchall(): url = product[0] guid = product[1] parent_guid = product[2] error_code = '' #resultTable = {} #print product[0] if isValuePresent(url) is False: #print "!!!!!", "this one is none", product[0] """Checking if this is a variant and it has parent with url""" if isValuePresent(parent_guid) is True: #print parent_guid, isValuePresent(parent_guid) for parent in queryDb(query="""SELECT url from product where guid = '%s';""" %parent_guid).fetchall(): #print parent[0] '''Checking if parent product contains url''' if isValuePresent(parent[0]) is True: url = guid + "the parent url is: " + parent[0] error = openUrl(parent[0]) else: error = 'The variant with guid ' + guid + ' and his parent do not contain urls!' """So the product is parent, and it's expected that it's child will contain guids""" -------------- next part -------------- An HTML attachment was scrubbed... URL: From grishma20 at gmail.com Thu Sep 11 17:04:34 2008 From: grishma20 at gmail.com (grishma govani) Date: Thu, 11 Sep 2008 16:04:34 +0100 Subject: [Tutor] body extraction from mbox file - emails Message-ID: The Code is take from the last example on the example page. When I run the command i see the msg lenght is 25 but it run through it only once, updates and counter and does not run through the rest of messages. I want to extract the body irrespective of whether there is an attachment or not. I am not sure how exactly to do this. Can anybody help me out. Thanks in advance. -Grishma Command: python EmailParserNew.py -d /Users/tweek/Documents/ /Users/tweek/ Desktop/tmp/automated/Feedback 25 Counter: 2 Code: print msg.__len__() counter = 1 for part in msg.walk(): # multipart/* are just containers ## if part.get_content_maintype() == 'multipart': ## continue # Applications should really sanitize the given filename so that an # email message can't be used to overwrite important files filename = part.get_filename() if not filename: ext = mimetypes.guess_extension(part.get_content_type()) if not ext: # Use a generic bag-of-bits extension ext = '.bin' filename = 'part-%03d%s' % (counter, ext) counter += 1 print 'Counter:',counter fp = open(os.path.join(opts.directory, filename), 'wb') fp.write(part.get_payload(decode=True)) fp.close() -------------- next part -------------- An HTML attachment was scrubbed... URL: From roadierich at googlemail.com Thu Sep 11 17:26:56 2008 From: roadierich at googlemail.com (Richard Lovely) Date: Thu, 11 Sep 2008 16:26:56 +0100 Subject: [Tutor] absolute beginner Message-ID: I'd absolutely recommend "Python for Dummies" published by Wileys. I've not used that actual book, but I've found other books in the series extremely helpful. http://www.amazon.com/Python-Dummies-Computer-Tech/dp/0471778648/ref=pd_bbs_sr_1?ie=UTF8&s=books&qid=1221146720&sr=8-1 On Thu, Sep 11, 2008 at 3:54 PM, wrote: > ----- Original Message ----- > From: Johnny > To: Python > Sent: Thursday, September 11, 2008 4:29 AM > Subject: [Tutor] absolute beginner > > > Anyone have any advice for an all out beginner? > Advice as in... The best book?...best tutor web page? > I am wanting so badly to learn Python. > > I have went to this site... > http://www.awaretek.com/tutorials.html > > This gave me lots of info,, but with so many books to choose from, I can't seem to find that special one that will give me (a complete dummy) the info I need. > > thanks > Johnny -- Richard "Roadie Rich" Lovely, part of the JNP|UK Famile www.theJNP.com From Jaggojaggo+Py at gmail.com Thu Sep 11 17:29:22 2008 From: Jaggojaggo+Py at gmail.com (Omer) Date: Thu, 11 Sep 2008 18:29:22 +0300 Subject: [Tutor] Looking at a String as a Struct? In-Reply-To: <48C923F0.9060507@sbcglobal.net> References: <48C8F9DC.3080302@sbcglobal.net> <1c2a2c590809110419y14308765hf636acbde653ecb@mail.gmail.com> <48C923F0.9060507@sbcglobal.net> Message-ID: <515008f10809110829k63d50d86g2804806a26ab5225@mail.gmail.com> Class Person: def __init__(str): self.Firstname = str[0:4] self.Surname = str[5:7] (...) If your string separates the values of each person using tags rather than fixed lengthes, build it like: or: self.Firstname = str[0:str.find("Last name:")] self.Surname = str[str.find("Last name:")+len("Last name:"):str.find("date_of_birth")] And just create a list of these, adding various get methods for easy information retrieval. (Here's for wandering whether my way of doing it counts as Pythonic.) HTH. Omer. On Thu, Sep 11, 2008 at 4:58 PM, Wayne Watson wrote: > True enough, but that gets messy. I'd have to keep them perhaps as global > variables or pass then around a lot from function to function as a > collection. I see WW posted above you about dictionaries. Maybe that's the > way to do it. I'll look into it. > > Kent Johnson wrote: > > On Thu, Sep 11, 2008 at 6:58 AM, Wayne Watson wrote: > > > Is it possible in Python to look at a string as a "struct". I don't think a > struct exists in python. Actually, is there something analogous to a record. > In the case of strings, suppose I have string that is composed of > sub-strings like, first_name, last-name, date_of birth, which consists of > month, day, and year, and finally SSN, street_address, state, city, and > zip_code. I'd like to access these fields directly instead of lastname = > record[38:55]. What if fields are not just strings, but some numeric values? > > > For numeric fields, just convert as needed: > quantity = int(record[55:60]) > price = float(record[60::70]) > > If the numbers are binary, rather than ascii, see the struct module. > > Kent > > > > > -- > > Wayne Watson (Watson Adventures, Prop., Nevada City, CA) > > (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) > Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet "If voting made any difference they wouldn't let us do it." > -- Mark Twain > > Web Page: > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Thu Sep 11 17:38:54 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Thu, 11 Sep 2008 08:38:54 -0700 Subject: [Tutor] Fwd: Looking at a String as a Struct? In-Reply-To: <515008f10809110825k5cef666eg29ba33037d223a2c@mail.gmail.com> References: <48C8F9DC.3080302@sbcglobal.net> <515008f10809110825r2af86ed6j12eed030ec302137@mail.gmail.com> <515008f10809110825k5cef666eg29ba33037d223a2c@mail.gmail.com> Message-ID: <48C93B8E.6090106@sbcglobal.net> An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Thu Sep 11 17:39:03 2008 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Thu, 11 Sep 2008 08:39:03 -0700 Subject: [Tutor] Looking at a String as a Struct? In-Reply-To: <48C8F9DC.3080302@sbcglobal.net> References: <48C8F9DC.3080302@sbcglobal.net> Message-ID: <40af687b0809110839r11f4504alb87dc556b8183a0b@mail.gmail.com> On Thu, Sep 11, 2008 at 3:58 AM, Wayne Watson wrote: > Is it possible in Python to look at a string as a "struct". I don't think > a struct exists in python. Actually, is there something analogous to a > record. In the case of strings, suppose I have string that is composed of > sub-strings like, first_name, last-name, date_of birth, which consists of > month, day, and year, and finally SSN, street_address, state, city, and > zip_code. I'd like to access these fields directly instead of lastname = > record[38:55]. What if fields are not just strings, but some numeric values? > > I had to do a similar thing in my first real Python program (actually, I ended up making it into a library of modules that I reuse over and over.) I do a lot of work with a legacy cTree database application - fixed-length data records, C strings, lots of stuff stored as packed decimal, etc. The database is normalized into 45 files, each with its own record length and layout. I wrote 45 separate classes; here's "Patient". Note: this is OLD code, and I haven't revisited it to optimize. If I ever find the time, I'll rework these into generators - as it stands, opening each file and reading records from it and loading the resulting objects into a list or dictionary (or SQL database) is left to the calling program. Remember, this was a beginner effort. (But the programs that use this are still going strong...) You'll notice that I call, and use, "struct" - it doesn't do quite what you think it does, I think... I believe that the entire class is closer to what you meant by "struct". import struct from utils import B2int, BBBB2date, BBBB2ssn, BBBB2zip, raw2phone # some utility functions - convert a single byte to integer, 4 bytes BCD to a date, # 4 bytes BCD to a Social Security number, 4 bytes BCD to a Zip code, # format a 10-digit number into "(999) 999-9999" class Patient(object): RecordLength = 1024 TLA = "pat" ID = "" def __init__(self, rec=False): """Extract fields from patient records""" self.Valid = False if rec: if not (rec[5] == "\x00"): # skip deleted and invalid records self.Valid = True self.ChartNumber = rec[5:16].split("\x00")[0].rstrip() # these are C strings, self.LastName = "" + rec[16:31].split("\x00")[0].rstrip() # therefore null-terminated - self.FirstName = "" + rec[32:44].split("\x00")[0].rstrip() # but also might self.MI = "" + rec[45] self.AccountNumber = rec[16:31].split("\x00")[0].rstrip() # contain spaces self.Address1 = rec[982:1010].split("\x00")[0].rstrip() self.Street = rec[72:100].split("\x00")[0].rstrip() self.City = rec[101:116].split("\x00")[0].rstrip() self.State = rec[117:119].split("\x00")[0].rstrip() self.Zip = BBBB2zip(rec[120:124]) self.HomePhone = raw2phone(rec[124:134].split("\x00")[0]) self.DrivLicNum = rec[135:147].split("\x00")[0].rstrip() self.SSN = BBBB2ssn(rec[148:152]) self.Birthdate = BBBB2date(rec[152:156]) self.Sex = rec[156].split("\x00")[0] self.EmergContact = rec[157:187].split("\x00")[0].rstrip() self.EmergPhone = raw2phone(rec[188:198].split("\x00")[0]) self.EmergRelCode = rec[199:205].split("\x00")[0].rstrip() self.Message1 = rec[206:238].split("\x00")[0].rstrip() self.Message2 = rec[239:271].split("\x00")[0].rstrip() self.NrstRelName = rec[272:302].split("\x00")[0].rstrip() self.NrstRelStreet = rec[303:331].split("\x00")[0].rstrip() self.NrstRelCity = rec[332:347].split("\x00")[0].rstrip() self.NrstRelState = rec[348:350].split("\x00")[0].rstrip() self.NrstRelZip = BBBB2zip(rec[351:355]) self.NrstRelPhone = raw2phone(rec[355:365].split("\x00")[0]) self.NrstRelRelCode = rec[366:372].split("\x00")[0].rstrip() self.EmpRefSrcCode = struct.unpack('B',rec[979])[0] self.EmpName = rec[373:403].split("\x00")[0].rstrip() self.EmpContact = rec[947:975].split("\x00")[0].rstrip() self.EmpStreet = rec[404:432].split("\x00")[0].rstrip() self.EmpCity = rec[433:448].split("\x00")[0].rstrip() self.EmpState = rec[455:457].split("\x00")[0].rstrip() self.EmpZip = BBBB2zip(rec[458:462]) self.EmpPhone = raw2phone(rec[462:472].split("\x00")[0]) self.EmpPhone2 = raw2phone(rec[473:483].split("\x00")[0]) self.EmpPhone2Ext = rec[484:488].split("\x00")[0].rstrip() self.Doctor = rec[489:491].split("\x00")[0].rstrip() self.MessageCode = rec[492:495].split("\x00")[0].rstrip() self.RecallCycle = rec[496:500].split("\x00")[0].rstrip() self.Ailment = B2int(rec[501]) self.Operator = rec[503:506].split("\x00")[0].rstrip() self.EntryDate = BBBB2date(rec[507:511]) self.ChampSpnsrGrade = rec[515:517].split("\x00")[0].rstrip() self.ChampBranchOfSvc = rec[518].split("\x00")[0] self.ChampDutyStatus = struct.unpack('B',rec[520])[0] self.Facility = rec[528:531].split("\x00")[0].rstrip() self.Pharmacy = rec[570:573].split("\x00")[0].rstrip() self.Diagnosis1 = rec[574:580].split("\x00")[0].rstrip() self.Diagnosis2 = rec[581:587].split("\x00")[0].rstrip() self.Diagnosis3 = rec[588:594].split("\x00")[0].rstrip() self.Diagnosis4 = rec[595:601].split("\x00")[0].rstrip() self.ReferredBy = rec[602:606].split("\x00")[0].rstrip() self.OtherRef1 = rec[607:611].split("\x00")[0].rstrip() self.OtherRef2 = rec[612:616].split("\x00")[0].rstrip() self.OtherRef3 = rec[617:621].split("\x00")[0].rstrip() self.InsuranceType = rec[622:624].split("\x00")[0].rstrip() self.FinancialCategory = rec[625:627].split("\x00")[0].rstrip() self.MaritalStatus = rec[628].split("\x00")[0] self.StatementCode = rec[629].split("\x00")[0] self.BillingCycle = rec[630].split("\x00")[0] self.AssignmentYN = rec[631].split("\x00")[0] self.FinanceChargeYN = rec[632].split("\x00")[0] self.PriInsDeductible = struct.unpack('i',rec[633:637])[0] self.PriInsCopay = rec[637:643].split("\x00")[0].rstrip() self.PriInsCompany = rec[644:650].split("\x00")[0].rstrip() self.SecInsCompany = rec[651:657].split("\x00")[0].rstrip() self.TerInsCompany = rec[658:654].split("\x00")[0].rstrip() self.PriInsuredID = rec[665:685].split("\x00")[0].rstrip() self.SecInsuredID = rec[686:706].split("\x00")[0].rstrip() self.TerInsuredID = rec[707:727].split("\x00")[0].rstrip() self.PriInsPlanName = rec[728:748].split("\x00")[0].rstrip() self.SecInsPlanName = rec[749:769].split("\x00")[0].rstrip() self.TerInsPlanName = rec[770:790].split("\x00")[0].rstrip() self.PriInsPolicy = rec[791:806].split("\x00")[0].rstrip() self.SecInsPolicy = rec[807:822].split("\x00")[0].rstrip() self.TerInsPolicy = rec[823:838].split("\x00")[0].rstrip() self.PriInsuredRel = rec[932].split("\x00")[0] self.SecInsuredRel = rec[933].split("\x00")[0] self.TerInsuredRel = rec[934].split("\x00")[0] self.PmtAuthType = rec[935].split("\x00")[0].rstrip() -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Thu Sep 11 17:58:41 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Thu, 11 Sep 2008 08:58:41 -0700 Subject: [Tutor] Looking at a String as a Struct? In-Reply-To: <48C93BE4.1070802@sbcglobal.net> References: <48C8F9DC.3080302@sbcglobal.net> <1c2a2c590809110419y14308765hf636acbde653ecb@mail.gmail.com> <48C923F0.9060507@sbcglobal.net> <515008f10809110829k63d50d86g2804806a26ab5225@mail.gmail.com> <48C93BE4.1070802@sbcglobal.net> Message-ID: <48C94031.8040200@sbcglobal.net> An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Thu Sep 11 18:55:39 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Thu, 11 Sep 2008 09:55:39 -0700 Subject: [Tutor] No Blank Separator between Date and Time Valid? Message-ID: <48C94D8B.3090808@sbcglobal.net> An HTML attachment was scrubbed... URL: From mndrk at mail.ru Thu Sep 11 20:38:31 2008 From: mndrk at mail.ru (Krasyn) Date: Thu, 11 Sep 2008 11:38:31 -0700 (PDT) Subject: [Tutor] How to create array of variants? In-Reply-To: References: Message-ID: <19441514.post@talk.nabble.com> Kelie-2 wrote: > > Hello group, > > I'm trying to translate the following VB code into Python and not sure how > to > create an array of variants. > > Thanks for your help! > > VB Code: > Sub SetXdata() > Dim lineObj As AcadLine > Set lineObj = ThisDrawing.ModelSpace.Item(0) > > Dim DataType(0 To 1) As Integer > Dim Data(0 To 1) As Variant > > DataType(0) = 1001: Data(0) = "Test_Application" > DataType(1) = 1070: Data(1) = 600 > > lineObj.SetXdata DataType, Data > End Sub > > Python code > import array > import comtypes.client > > def SetXData(): > activedoc = > comtypes.client.GetActiveObject("AutoCAD.Application").ActiveDocument > line = activedoc.ModelSpace.Item(0) > > dataType = array.array('i', [1001, 1070]) > dataValue = array.array('?', ['Test_Application', 600]) #What should I > use > for the type code? > > line.SetXData(dataType, dataValue) > > if __name__ == "__main__": > SetXData() > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > dataType = array("h",[1001,1070]) dataValue = VARIANT(['Test_Application', 600]) -- View this message in context: http://www.nabble.com/How-to-create-array-of-variants--tp18331322p19441514.html Sent from the Python - tutor mailing list archive at Nabble.com. From optomatic at rogers.com Thu Sep 11 23:15:52 2008 From: optomatic at rogers.com (Patrick) Date: Thu, 11 Sep 2008 17:15:52 -0400 Subject: [Tutor] importing strings In-Reply-To: <00b701c9141e$3d232e60$4101a8c0@compaq> References: <48C8907D.6090100@lorettotel.net> <00b701c9141e$3d232e60$4101a8c0@compaq> Message-ID: <48C98A88.1090102@rogers.com> I would like to import a string with a "placeholder" in it. for example "this is a %s" I would then like to insert the value into it after importation, "this is a %s" (test) I have been able to import a string from another module threw a dictionary but I can't seem to figure out how to do it so that I can insert a value into the %s placeholder afterwards. I can send over more code if this is an incomplete description. Thanks in advance-Patrick From jeff at drinktomi.com Thu Sep 11 23:26:13 2008 From: jeff at drinktomi.com (Jeff Younker) Date: Thu, 11 Sep 2008 14:26:13 -0700 Subject: [Tutor] importing strings In-Reply-To: <48C98A88.1090102@rogers.com> References: <48C8907D.6090100@lorettotel.net> <00b701c9141e$3d232e60$4101a8c0@compaq> <48C98A88.1090102@rogers.com> Message-ID: On Sep 11, 2008, at 2:15 PM, Patrick wrote: > > I have been able to import a string from another module threw a > dictionary but I can't seem to figure out how to do it so that I can > insert a value into the %s placeholder afterwards. The % operator is probably what you are looking for. format = "this is a %s" subst = 'test' print format % subst FYI: You shouldn't reply to a message when you have a new question. That attaches it to the previous topic. - Jeff Younker - jeff at drinktomi.com - From jeff at drinktomi.com Thu Sep 11 23:30:48 2008 From: jeff at drinktomi.com (Jeff Younker) Date: Thu, 11 Sep 2008 14:30:48 -0700 Subject: [Tutor] Threading In-Reply-To: References: Message-ID: On Sep 11, 2008, at 7:56 AM, Oleg Oltar wrote: > Hi! > > I need to open about 1200 urls from my database. And to check that > those urls are really exists. > > I used urllib2.urlopen for it. But it's a little bit slow. I thought > that it's might be a good idea to do it in a threads. So it can add > some performance to my code. > > Unfortunately I can't get started with the treading module. There > are no simple examples in the python docs. Not sure how to start. > > > What I want to have: > for my list of urls I want to start few threads, each one of them > should do some validation. > > My code without threads: The first thing to do is to break your program into phases. Right now all your logic is intermixed. This isn't a good thing when working with threads. You want to isolate the parts that need parallelization from the parts that don't. A general stylistic note: Don't start your code with utility and helper functions. You're telling a story. Start with the big overarching logic that orchestrates all the bits in pieces. That's the plot of your story. The little helper functions are like details about a character. They get in the way until you've figured out what's going on. It seems to me like you have three distinct parts: - get the list of urls from the database - check the urls - report the urls status So your main method will look something like: def test_urls(): urls = urls_from_database() checked_urls = check(urls) report(checked_urls) The only method that needs to be parallelized is check(urls). One approach to threading is to start one thread for every URL, but if you have too many URLs you could bring your machine to its knees. Doing 30 things at once may be fine, but doing 1000 is quite possibly a problem, so you have to limit the number of threads. The classic way of doing this uses a pool of tasks and a number of worker threads that pull jobs out of the pool. Your master thread fills the pool, starts a number of worker threads, and then waits for them to finish. Each worker thread pulls a job from the pool, performs the job, writes the results to another pool. When the pool is empty the program continues. Your check method might be something like this: from Queue import Queue from threading import Thread ... def check(urls): unchecked_urls = Queue() # a queue full of url strings checked_urls = Queue() # a queue full of (url string, is_good boolean) tuples fill_job_pool(unchecked_urls, urls) start_worker_threads(unchecked_urls, checked_urls, number_workers=10) # waits until all the jobs have been emptied from the queue unchecked_urls.join() return results_from(checked_urls) def fill_job_pool(unchecked_urls, urls): for url in urls: unchecked_urls.put(url) def start_worker_threads(unchecked_urls, checked_urls, number_workers): for x in range(0, number_workers): # Creates a thread object that will call worker_thread(unchecked_urls, checked_urls) # when it is started. worker = Thread(target=worker_thread, args=(unchecked_urls, checked_urls)) # Python will terminate even if this thread is still alive. This means that the # thread doesn't need to kill itself. worker.setDaemon(True) # Start the worker thread worker.start() def results_from(checked_urls): results = [] while not checked_urls.empty(): results.append(checked_urls.get()) return results def worker_thread(job_pool, result_pool): while True: url = job_pool.get() is_good = check_url(url) result = (url, is_good) result_pool.put(result) job_pool.task_done() def check_url(url): # YOUR URL CHECK HERE return True Once you plug this into your program, you'll start finding ways that you can shorten the whole program. Instead of passing around arrays or urls and results you can pass around the queues directly. In addition you can run the report function as another thread. It prints the jobs from the result pool as they're completed. These will make the code more elegant, but the solution here gets at the heart of the problem. - Jeff Younker - jeff at drinktomi.com - From inthefridge at gmail.com Thu Sep 11 23:52:23 2008 From: inthefridge at gmail.com (Spencer Parker) Date: Thu, 11 Sep 2008 15:52:23 -0600 Subject: [Tutor] Win32 extensions Message-ID: I am tasked with a project to use WMI to script something on Windows Server 2003. I was wondering if it is possible to create a script on a linux machine and use the Win32 extensions...since I need those to use WMI python module as well. Is this actually possible? Otherwise I would have to use a windows server in order to run these scripts. I do not want to use VB is I don't have or a windows server. I am deploying Windows Servers from behind a linux PXE. -- Spencer Parker -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Sep 12 01:00:51 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 12 Sep 2008 00:00:51 +0100 Subject: [Tutor] Looking at a String as a Struct? References: <48C8F9DC.3080302@sbcglobal.net> Message-ID: "Wayne Watson" wrote > lIs it possible in Python to look at a string as a "struct". I assume you mean you have a lot of data all stored in a single string? I also assume that either the string has a fixed delimiter - like a comma separated file? Or it has fixed length fields? > I don't think a struct exists in python. What is a struct? It is a data record that can hold different field types. So yes struct exists in Python in a multitude of forms: a) a tuple is an immutable collection of items b) a list is a mutable collection of items c) a class without methods is most like a C struct So you have a choice. However I suspect that what you want is more like a C union. And no Python does not have a union concept. The best we can do is either use someting like a regex to extract fields based on the separator or use the struct module (now there's a clue?!) to extract fixed length fields from a string of bytes. struct can e used for binary data but it can also be used for fixed length string fields inside a character string. Once extracted move the new fields (with type conversion as needed) into the fields of a class or into a tuple/list. If you use a class you cancombine the decoding with the assignment in the constructor (__init__ method) You can read about all opf these data types in the Raw Materials topic of my tutor. You can read about classes in the OOP tiopic and you can read a bit about struct in the File Handling topic. 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 Sep 12 01:11:28 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 12 Sep 2008 00:11:28 +0100 Subject: [Tutor] How to create array of variants? References: <19441514.post@talk.nabble.com> Message-ID: "Krasyn" wrote >> >> I'm trying to translate the following VB code into Python and not >> sure how >> to create an array of variants. All variables in Python are effectively variants - variables that can store any type. So an array of variants equates to a Python list >> VB Code: >> Sub SetXdata() def SetXData(): >> Dim lineObj As AcadLine >> Set lineObj = ThisDrawing.ModelSpace.Item(0) lineObj = ThisDrawing.ModelSpace.Item(0) Where ThisDrawing.ModelSpace.Item(0) is s0ome kind of data structure you have defined elsewhere. Or fetch using COM. >> Dim DataType(0 To 1) As Integer >> Dim Data(0 To 1) As Variant DataType = [] Data = [] But it looks like you are trying to fake a dictionary - although VB has dictionaries! >> DataType(0) = 1001: Data(0) = "Test_Application" >> DataType(1) = 1070: Data(1) = 600 Data = {'Test_application' : 1001, 600 : 1070} >> lineObj.SetXdata DataType, Data lineObj.SetXdata( Data ) >> Python code >> import array >> import comtypes.client >> >> def SetXData(): >> activedoc = >> comtypes.client.GetActiveObject("AutoCAD.Application").ActiveDocument >> line = activedoc.ModelSpace.Item(0) >> >> dataType = array.array('i', [1001, 1070]) >> dataValue = array.array('?', ['Test_Application', 600]) #What >> should I >> use >> for the type code? >> >> line.SetXData(dataType, dataValue) Here's the snag with the dictionary approach so its back to two lists. I wouldn't use the array module just lists. It might be enough to just pass DataType and Data as two lists into the COM object. I don't know enough about Python's COM integration to be sure that it will sort it all out though. But I suspect it will. -- 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 Sep 12 01:31:15 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 12 Sep 2008 00:31:15 +0100 Subject: [Tutor] Win32 extensions References: Message-ID: "Spencer Parker" wrote > 2003. I was wondering if it is possible to create a script on a > linux > machine and use the Win32 extensions...since I need those to > use WMI python module as well. Is this actually possible? Yes if you spend a lot of money. You can buy a set of libraries from a comany called Bristol Technology (I think, it's over 8 years since I used it!) that allows you to build Windows software on a Unix box. A bit like cygwin in reverse! Some Microsoft developers actually used it during the development of the first version of Windows NT I believe! However a more practical route is probably to just install VMWare (or similar virtualisation software) and a cheap copy of Windows XP Pro/Home. > I am deploying Windows Servers from behind > a linux PXE. PXE? HTH, Alan G. From johan at accesstel.com.au Fri Sep 12 01:33:54 2008 From: johan at accesstel.com.au (Johan Geldenhuys) Date: Fri, 12 Sep 2008 09:33:54 +1000 Subject: [Tutor] No Blank Separator between Date and Time Valid? In-Reply-To: <48C94D8B.3090808@sbcglobal.net> Message-ID: <20080911233400.HWDA11041.nschwotgx03p.mx.bigpond.com@JohanPC> It all depends how you specify the format of the time you want, look at the example. >>> time.strftime('%Y%M%D%H%M%S') '200820092030' >>> >>> >>> time.strftime('%Y%M%D %H%M%S') '200820 092055' >>> Notice in the second statement, I added the space separator between the %D and %H. This statement doesn?t fail and the exception doesn?t happen: date1 = datetime(*(time.strptime(d1, formatin)[0:6])) _____ From: tutor-bounces+johan=accesstel.com.au at python.org [mailto:tutor-bounces+johan=accesstel.com.au at python.org] On Behalf Of Wayne Watson Sent: Friday, 12 September 2008 2:56 AM To: tutor at python.org Subject: [Tutor] No Blank Separator between Date and Time Valid? This program segment allows an invalid date to go undetected. See below. from datetime import datetime import time def set_time_stamp(d1): # yyyy/mm/dd hh:mm:ss in, vyyyymmdd_hhmmss.27 out formatin = '%Y/%m/%d %H:%M:%S' d1 = d1.lstrip() try: date1 = datetime(*(time.strptime(d1, formatin)[0:6])) except ValueError: print; print "Invalid date input. Use yyyy/mm/dd hh:mm:ss." return False formatout = '%Y%m%d_%H%M%S' dout = date1.strftime(formatout) print "dout: ",dout return 'v'+date1.strftime(formatout)+".27" keyopt = 0 while keyopt == 0: print date_time = raw_input("Enter date and time: ") if date_time == "end": break file_prefix = set_time_stamp(date_time) print "prefix: ",file_prefix if file_prefix == False: continue print "OK: ", file_prefix #write_pair(file_prefix, date_time) print; print "bye..." Results: Enter date and time: 2008/1/1 00:00:30 <- Valid input OK dout: 20080101_000030 prefix: v20080101_000030.27 OK: v20080101_000030.27 Enter date and time: 2008/1/100:00:30 <- Why is this valid. The fields are not spearated. dout: 20080110_000030 prefix: v20080110_000030.27 OK: v20080110_000030.27 Enter date and time: 2008/1/1 x00:00:30 <- Invalid input caught Invalid date input. Use yyyy/mm/dd hh:mm:ss. prefix: False Enter date and time: end bye ... -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet "If voting made any difference they wouldn't let us do it." -- Mark Twain Web Page: -------------- next part -------------- An HTML attachment was scrubbed... URL: From mwalsh at mwalsh.org Fri Sep 12 02:11:08 2008 From: mwalsh at mwalsh.org (Martin Walsh) Date: Thu, 11 Sep 2008 19:11:08 -0500 Subject: [Tutor] No Blank Separator between Date and Time Valid? In-Reply-To: <48C94D8B.3090808@sbcglobal.net> References: <48C94D8B.3090808@sbcglobal.net> Message-ID: <48C9B39C.9010701@mwalsh.org> Wayne Watson wrote: > This program segment allows an invalid date to go undetected. See below. > > def set_time_stamp(d1): > # yyyy/mm/dd hh:mm:ss in, vyyyymmdd_hhmmss.27 out > formatin = '%Y/%m/%d %H:%M:%S' > d1 = d1.lstrip() > try: > date1 = datetime(*(time.strptime(d1, formatin)[0:6])) > except ValueError: > print; print "Invalid date input. Use yyyy/mm/dd hh:mm:ss." > return False > > Enter date and time: 2008/1/100:00:30 <- Why is this valid. The > fields are not spearated. > dout: 20080110_000030 > prefix: v20080110_000030.27 > OK: v20080110_000030.27 > I have confirmed there is a difference in the behavior of time.strptime between python 2.4 and 2.5, and I assume you're using 2.4. It is possibly related to this bug (but hard to say for sure without looking at the source)... http://bugs.python.org/issue1340337 ... and the subsequent fix for 2.5. But, clearly something changed between releases. from http://www.python.org/download/releases/2.5/NEWS.txt """ - Bug #1340337: change time.strptime() to always return ValueError when there is an error in the format string. - Bug #1290505: Fix clearing the regex cache for time.strptime(). """ HTH, Marty From sierra_mtnview at sbcglobal.net Fri Sep 12 02:25:06 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Thu, 11 Sep 2008 17:25:06 -0700 Subject: [Tutor] Releasing a File for Access Message-ID: <48C9B6E2.4080203@sbcglobal.net> An HTML attachment was scrubbed... URL: From kent37 at tds.net Fri Sep 12 02:31:35 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 11 Sep 2008 20:31:35 -0400 Subject: [Tutor] Threading In-Reply-To: References: Message-ID: <1c2a2c590809111731t61772e78ia128a39776e09805@mail.gmail.com> On Thu, Sep 11, 2008 at 10:56 AM, Oleg Oltar wrote: > Hi! > > I need to open about 1200 urls from my database. And to check that those > urls are really exists. > > I used urllib2.urlopen for it. But it's a little bit slow. I thought that > it's might be a good idea to do it in a threads. So it can add some > performance to my code. > > Unfortunately I can't get started with the treading module. There are no > simple examples in the python docs. Not sure how to start. There are some good examples of threading in the Python cookbook, or this one: http://www.chrisarndt.de/projects/threadpool/ Kent From bgailer at gmail.com Fri Sep 12 03:31:24 2008 From: bgailer at gmail.com (bob gailer) Date: Thu, 11 Sep 2008 21:31:24 -0400 Subject: [Tutor] Releasing a File for Access In-Reply-To: <48C9B6E2.4080203@sbcglobal.net> References: <48C9B6E2.4080203@sbcglobal.net> Message-ID: <48C9C66C.8070803@gmail.com> An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Fri Sep 12 04:33:48 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Thu, 11 Sep 2008 19:33:48 -0700 Subject: [Tutor] Releasing a File for Access In-Reply-To: <48C9C66C.8070803@gmail.com> References: <48C9B6E2.4080203@sbcglobal.net> <48C9C66C.8070803@gmail.com> Message-ID: <48C9D50C.9060002@sbcglobal.net> An HTML attachment was scrubbed... URL: From inthefridge at gmail.com Fri Sep 12 07:31:16 2008 From: inthefridge at gmail.com (Spencer Parker) Date: Thu, 11 Sep 2008 23:31:16 -0600 Subject: [Tutor] Win32 extensions In-Reply-To: References: Message-ID: That was what I was afraid of...I might have to go the virtualization route instead. PXE = pre-execution environment On Thu, Sep 11, 2008 at 5:31 PM, Alan Gauld wrote: > > "Spencer Parker" wrote > > 2003. I was wondering if it is possible to create a script on a linux >> machine and use the Win32 extensions...since I need those to >> use WMI python module as well. Is this actually possible? >> > > Yes if you spend a lot of money. > You can buy a set of libraries from a comany called Bristol > Technology (I think, it's over 8 years since I used it!) that allows > you to build Windows software on a Unix box. A bit like cygwin > in reverse! Some Microsoft developers actually used it during the > development of the first version of Windows NT I believe! > > However a more practical route is probably to just install > VMWare (or similar virtualisation software) and a cheap copy > of Windows XP Pro/Home. > > I am deploying Windows Servers from behind >> a linux PXE. >> > > PXE? > > HTH, > > Alan G. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Spencer Parker -------------- next part -------------- An HTML attachment was scrubbed... URL: From rdm at rcblue.com Fri Sep 12 08:38:24 2008 From: rdm at rcblue.com (Dick Moores) Date: Thu, 11 Sep 2008 23:38:24 -0700 Subject: [Tutor] Threading In-Reply-To: <1c2a2c590809111731t61772e78ia128a39776e09805@mail.gmail.co m> References: <1c2a2c590809111731t61772e78ia128a39776e09805@mail.gmail.com> Message-ID: <20080912063837.43FAC1E4004@bag.python.org> An HTML attachment was scrubbed... URL: From rdm at rcblue.com Fri Sep 12 08:38:24 2008 From: rdm at rcblue.com (Dick Moores) Date: Thu, 11 Sep 2008 23:38:24 -0700 Subject: [Tutor] Threading In-Reply-To: <1c2a2c590809111731t61772e78ia128a39776e09805@mail.gmail.co m> References: <1c2a2c590809111731t61772e78ia128a39776e09805@mail.gmail.com> Message-ID: <20080912063837.700011E400D@bag.python.org> An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Sep 12 10:06:54 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 12 Sep 2008 09:06:54 +0100 Subject: [Tutor] Releasing a File for Access References: <48C9B6E2.4080203@sbcglobal.net> <48C9C66C.8070803@gmail.com> <48C9D50C.9060002@sbcglobal.net> Message-ID: "Wayne Watson" wrote > I need to use something like sys.exit(). sys.exit won't change the file permissions etc. It simply sets the exit status of the program. I suspect the problem is that you still have IDLE running. Have you tried testing the program outside IDLE? You might find it works OK there. Also have you checked your file permissions? You may need to change the default settings using the os module. > However, I'm in development mode right now with IDLE, > and there's a small penalty for using it with IDLE. The "penalty" is actually a benefit since having to restart IDLE and reload your working files each time you run your code is much less convenient than clicking a dialog button! :-) > Although I user might try to rename 500 files at a single shot. I assume you are intending enhancing the program to accept multiple ufilenames? > def modify_txt_file(old_fname, new_event_date): > old_prefix = old_fname[0:19] You might want to use os.basename() here as a more reliable way of extracting the extension. > input_file=open(old_fname,'r') > output_file=open(old_prefix+'.tmp','w') > print "modified txt file with event info" > # now copy tmp back to ... And you might want to use os.remove() and os.rename() to do the final copy of the tmp file back to the original. Just some thoughts -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From mail at timgolden.me.uk Fri Sep 12 10:17:28 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 12 Sep 2008 09:17:28 +0100 Subject: [Tutor] Releasing a File for Access In-Reply-To: <48C9B6E2.4080203@sbcglobal.net> References: <48C9B6E2.4080203@sbcglobal.net> Message-ID: <48CA2598.1090202@timgolden.me.uk> Wayne Watson wrote: > Enclosed is a segment of a program which copies a txt file, but replaces > the first line with a new one. The new one has a suffix of tmp. After it > executed the code and exited the program normally (running out of code), > I couldn't access the new tmp file. It was listed by Win XP, but I got a > "file in use" messge. Do I have to exit differently to free the tmp file > for inspection? If you're using 2.5+, worth using the new with statement which should ensure file closure, altho' there's nothing in your code which suggests that it shouldn't close anyhow. Also, for the purpose of your copy-except-line-1 routine, consider that files are also iterators. Put together, this snippet -- simplified for clarity -- might help things along: from __future__ import with_statement with open ("c:/temp/temp0.txt") as fin: with open ("c:/temp/temp1.txt", "w") as fout: fout.write ("NEW LINE 1\n") fin.next () fout.writelines (fin) Just in case it helps, it is possible for virus checkers and the like (and viruses themselves for that matter) to monitor file creation and to lock the file in share-delete mode. If what you have is a truly temporary file, consider using the tempfile module or at least creating it in the %TEMP% directory which will generally be excluded for virus checking, I think. TJG From mndrk at mail.ru Fri Sep 12 09:03:42 2008 From: mndrk at mail.ru (Krasyn) Date: Fri, 12 Sep 2008 00:03:42 -0700 (PDT) Subject: [Tutor] How to create array of variants? In-Reply-To: References: <19441514.post@talk.nabble.com> Message-ID: <19450606.post@talk.nabble.com> Alan Gauld wrote: > > > "Krasyn" wrote > >>> >>> I'm trying to translate the following VB code into Python and not >>> sure how >>> to create an array of variants. > > All variables in Python are effectively variants - variables that can > store any type. So an array of variants equates to a Python list > >>> VB Code: >>> Sub SetXdata() > > def SetXData(): > >>> Dim lineObj As AcadLine >>> Set lineObj = ThisDrawing.ModelSpace.Item(0) > > > lineObj = ThisDrawing.ModelSpace.Item(0) > > Where ThisDrawing.ModelSpace.Item(0) is s0ome kind of > data structure you have defined elsewhere. Or fetch using COM. > >>> Dim DataType(0 To 1) As Integer >>> Dim Data(0 To 1) As Variant > > DataType = [] > Data = [] > > But it looks like you are trying to fake a dictionary - although VB > has dictionaries! > >>> DataType(0) = 1001: Data(0) = "Test_Application" >>> DataType(1) = 1070: Data(1) = 600 > > Data = {'Test_application' : 1001, 600 : 1070} > >>> lineObj.SetXdata DataType, Data > > lineObj.SetXdata( Data ) > >>> Python code >>> import array >>> import comtypes.client >>> >>> def SetXData(): >>> activedoc = >>> comtypes.client.GetActiveObject("AutoCAD.Application").ActiveDocument >>> line = activedoc.ModelSpace.Item(0) >>> >>> dataType = array.array('i', [1001, 1070]) >>> dataValue = array.array('?', ['Test_Application', 600]) #What >>> should I >>> use >>> for the type code? >>> >>> line.SetXData(dataType, dataValue) > > Here's the snag with the dictionary approach so its back to > two lists. I wouldn't use the array module just lists. > > It might be enough to just pass DataType and Data as two lists > into the COM object. I don't know enough about Python's COM > integration to be sure that it will sort it all out though. But I > suspect > it will. > > > -- > 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 > > # -*- coding:UTF-8 -*- from comtypes.client import * from array import array acad = GetActiveObject("AutoCAD.Application") dwg = acad.ActiveDocument mspace = dwg.ModelSpace circle = mspace.AddCircle(array("d",[0,0,0]),100) circle.Color = 3 acad.ZoomExtents() dtype = array("h",[1001,1070]) # [1001,1070] doesnt' work (comtypes 0.5.1) dvalue = ['Test_Application', 600] #OK VARIANT is not needed circle.SetXData(dtype,dvalue) #test: (entget (car (entsel)) '("*")) #result:((-1 . ) (0 . "CIRCLE") (330 . ) (5 . "12A") (100 . "AcDbEntity") (67 . 0) (410 . "Model") (8 . "0") (62 . 3) (100 . "AcDbCircle") (10 0.0 0.0 0.0) (40 . 100.0) (210 0.0 0.0 1.0) (-3 ("Test_Application" (1070 . 600)))) -- View this message in context: http://www.nabble.com/How-to-create-array-of-variants--tp18331322p19450606.html Sent from the Python - tutor mailing list archive at Nabble.com. From sierra_mtnview at sbcglobal.net Fri Sep 12 13:28:54 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Fri, 12 Sep 2008 04:28:54 -0700 Subject: [Tutor] No Blank Separator between Date and Time Valid? Message-ID: <48CA5276.4050604@sbcglobal.net> An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Fri Sep 12 13:29:49 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Fri, 12 Sep 2008 04:29:49 -0700 Subject: [Tutor] Releasing a File for Access In-Reply-To: <48CA2598.1090202@timgolden.me.uk> References: <48C9B6E2.4080203@sbcglobal.net> <48CA2598.1090202@timgolden.me.uk> Message-ID: <48CA52AD.3090304@sbcglobal.net> An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Fri Sep 12 13:30:09 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Fri, 12 Sep 2008 04:30:09 -0700 Subject: [Tutor] Releasing a File for Access In-Reply-To: References: <48C9B6E2.4080203@sbcglobal.net> <48C9C66C.8070803@gmail.com> <48C9D50C.9060002@sbcglobal.net> Message-ID: <48CA52C1.2030703@sbcglobal.net> An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Fri Sep 12 13:39:21 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Fri, 12 Sep 2008 04:39:21 -0700 Subject: [Tutor] How Fix Misdirected Posts to Tutor Message-ID: <48CA54E9.5090600@sbcglobal.net> An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Fri Sep 12 13:49:22 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Fri, 12 Sep 2008 04:49:22 -0700 Subject: [Tutor] Releasing a File for Access In-Reply-To: <238888.79812.qm@web86708.mail.ukl.yahoo.com> References: <238888.79812.qm@web86708.mail.ukl.yahoo.com> Message-ID: <48CA5742.7040505@sbcglobal.net> An HTML attachment was scrubbed... URL: From kent37 at tds.net Fri Sep 12 13:55:17 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 12 Sep 2008 07:55:17 -0400 Subject: [Tutor] How Fix Misdirected Posts to Tutor In-Reply-To: <48CA54E9.5090600@sbcglobal.net> References: <48CA54E9.5090600@sbcglobal.net> Message-ID: <1c2a2c590809120455v55b97a8bu1efa80dbab39bbfd@mail.gmail.com> On Fri, Sep 12, 2008 at 7:39 AM, Wayne Watson wrote: > My Reply posts to the list only show the poster, and not the list, Yes, that is the way the list is configured. Use Reply All. Kent From sierra_mtnview at sbcglobal.net Fri Sep 12 16:54:05 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Fri, 12 Sep 2008 07:54:05 -0700 Subject: [Tutor] No Blank Separator between Date and Time Valid? In-Reply-To: <1c2a2c590809120502o7169924m949bc4fc91ddf485@mail.gmail.com> References: <48CA5276.4050604@sbcglobal.net> <1c2a2c590809120502o7169924m949bc4fc91ddf485@mail.gmail.com> Message-ID: <48CA828D.1090007@sbcglobal.net> An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Fri Sep 12 17:03:58 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Fri, 12 Sep 2008 08:03:58 -0700 Subject: [Tutor] How Fix Misdirected Posts to Tutor In-Reply-To: <1c2a2c590809120455v55b97a8bu1efa80dbab39bbfd@mail.gmail.com> References: <48CA54E9.5090600@sbcglobal.net> <1c2a2c590809120455v55b97a8bu1efa80dbab39bbfd@mail.gmail.com> Message-ID: <48CA84DE.4090201@sbcglobal.net> An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Fri Sep 12 17:08:57 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Fri, 12 Sep 2008 08:08:57 -0700 Subject: [Tutor] SBC/Yahoo and Spamguard--Stuck in Limbo Message-ID: <48CA8609.9050601@sbcglobal.net> An HTML attachment was scrubbed... URL: From mail at timgolden.me.uk Fri Sep 12 17:10:08 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 12 Sep 2008 16:10:08 +0100 Subject: [Tutor] How Fix Misdirected Posts to Tutor In-Reply-To: <48CA84DE.4090201@sbcglobal.net> References: <48CA54E9.5090600@sbcglobal.net> <1c2a2c590809120455v55b97a8bu1efa80dbab39bbfd@mail.gmail.com> <48CA84DE.4090201@sbcglobal.net> Message-ID: <48CA8650.4000305@timgolden.me.uk> Wayne Watson wrote: > Thanks. That seems to work. However, I thought I had experimented with > it and found otherwise. Now to remember to do that. It's the only list > I have that requires Reply All. It's certainly working now! There has been much debate on this in the past. (About every six months or so, if memory serves!) It's just one of those list things: some people prefer one approach; some people prefer the other. :) TJG From sierra_mtnview at sbcglobal.net Fri Sep 12 17:14:33 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Fri, 12 Sep 2008 08:14:33 -0700 Subject: [Tutor] No Blank Separator between Date and Time Valid? In-Reply-To: <48C9B39C.9010701@mwalsh.org> References: <48C94D8B.3090808@sbcglobal.net> <48C9B39C.9010701@mwalsh.org> Message-ID: <48CA8759.1030505@sbcglobal.net> An HTML attachment was scrubbed... URL: From srilyk at gmail.com Fri Sep 12 17:20:59 2008 From: srilyk at gmail.com (W W) Date: Fri, 12 Sep 2008 10:20:59 -0500 Subject: [Tutor] How Fix Misdirected Posts to Tutor In-Reply-To: <48CA8650.4000305@timgolden.me.uk> References: <48CA54E9.5090600@sbcglobal.net> <1c2a2c590809120455v55b97a8bu1efa80dbab39bbfd@mail.gmail.com> <48CA84DE.4090201@sbcglobal.net> <48CA8650.4000305@timgolden.me.uk> Message-ID: <333efb450809120820x644b2e6fo56a63412f50cd016@mail.gmail.com> On Fri, Sep 12, 2008 at 10:10 AM, Tim Golden wrote: > Wayne Watson wrote: > >> Thanks. That seems to work. However, I thought I had experimented with it >> and found otherwise. Now to remember to do that. It's the only list I have >> that requires Reply All. It's certainly working now! >> > > There has been much debate on this in the past. > (About every six months or so, if memory serves!) > > It's just one of those list things: some people prefer > one approach; some people prefer the other. :) Too bad you can't pick which way you want it! -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From srilyk at gmail.com Fri Sep 12 17:22:16 2008 From: srilyk at gmail.com (W W) Date: Fri, 12 Sep 2008 10:22:16 -0500 Subject: [Tutor] SBC/Yahoo and Spamguard--Stuck in Limbo In-Reply-To: <48CA8609.9050601@sbcglobal.net> References: <48CA8609.9050601@sbcglobal.net> Message-ID: <333efb450809120822s52670070gc0031896d41f254d@mail.gmail.com> You may be able to create a filter. If you're checking from a different account you should at least be able to create one to forward to that account. -Wayne On Fri, Sep 12, 2008 at 10:08 AM, Wayne Watson wrote: > I see a number of tutor posts are sometimes not getting to me, including > my own, because my SBC Global use of Spamguard holds them in my Spam folder. > By and large they make it they make it through. Does anyone know how to tell > Spamguard to let all main with Tutor in the title of as part of an e-mail > address to let the messages through? Presently, I have to go into the Yahoo > mailer and move them from the Spam folder into the Inbox. > -- > > Wayne Watson (Watson Adventures, Prop., Nevada City, CA) > > (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) > Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet "If voting made any difference they wouldn't let us do it." > -- Mark Twain > > Web Page: > > > _______________________________________________ > 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 nnolie at gmail.com Fri Sep 12 19:51:22 2008 From: nnolie at gmail.com (Jeremiah Stack) Date: Fri, 12 Sep 2008 09:51:22 -0800 Subject: [Tutor] Hey Variables Message-ID: I was wondering If you could help me out. I am trying to set a variable for the number of variables. ? Any help would be awesome -------------- next part -------------- An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Fri Sep 12 17:23:29 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Fri, 12 Sep 2008 08:23:29 -0700 Subject: [Tutor] No Blank Separator between Date and Time Valid? In-Reply-To: <48CA8759.1030505@sbcglobal.net> References: <48C94D8B.3090808@sbcglobal.net> <48C9B39C.9010701@mwalsh.org> <48CA8759.1030505@sbcglobal.net> Message-ID: <48CA8971.8040706@sbcglobal.net> An HTML attachment was scrubbed... URL: From bgailer at gmail.com Fri Sep 12 19:58:01 2008 From: bgailer at gmail.com (Bob Gailer) Date: Fri, 12 Sep 2008 13:58:01 -0400 Subject: [Tutor] Hey Variables In-Reply-To: References: Message-ID: <23d7abd0809121058v3dafc858l41ac782075dd10@mail.gmail.com> On Fri, Sep 12, 2008 at 1:51 PM, Jeremiah Stack wrote: > I was wondering If you could help me out. > > I am trying to set a variable for the number of variables. ? > > Any help would be awesome > More details would be wonderful. I have no idea of what you want! -- Bob Gailer 919-636-4239 -------------- next part -------------- An HTML attachment was scrubbed... URL: From nnolie at gmail.com Fri Sep 12 20:08:44 2008 From: nnolie at gmail.com (Jeremiah Stack) Date: Fri, 12 Sep 2008 10:08:44 -0800 Subject: [Tutor] Hay Variables Message-ID: Sorry, Okay, Say i want to calculate the average for Math = 91 Science = 97 and English = 96, I Declare a variable = Number of classes to divide by. So instead say later I want to add another class. Instead of adding a variable And changing the (Number of Classes = 3) variable. I would like to just add another variable and have the Number of classes variable change automatically. So NumberOfClasses = (Number variables). Hope that makes sense and without user keyboard input -------------- next part -------------- An HTML attachment was scrubbed... URL: From christopher.henk at allisontransmission.com Fri Sep 12 20:13:50 2008 From: christopher.henk at allisontransmission.com (christopher.henk at allisontransmission.com) Date: Fri, 12 Sep 2008 14:13:50 -0400 Subject: [Tutor] Hay Variables In-Reply-To: Message-ID: I would use a list of grades and the length of the list. Chris "Jeremiah Stack" Sent by: tutor-bounces+christopher.henk=allisontransmission.com at python.org 09/12/2008 02:08 PM To "Python Tutor" cc Subject [Tutor] Hay Variables Sorry, Okay, Say i want to calculate the average for Math = 91 Science = 97 and English = 96, I Declare a variable = Number of classes to divide by. So instead say later I want to add another class. Instead of adding a variable And changing the (Number of Classes = 3) variable. I would like to just add another variable and have the Number of classes variable change automatically. So NumberOfClasses = (Number variables). Hope that makes sense and without user keyboard input _______________________________________________ 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 Sep 12 21:40:26 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 12 Sep 2008 15:40:26 -0400 Subject: [Tutor] No Blank Separator between Date and Time Valid? In-Reply-To: <48CA8971.8040706@sbcglobal.net> References: <48C94D8B.3090808@sbcglobal.net> <48C9B39C.9010701@mwalsh.org> <48CA8759.1030505@sbcglobal.net> <48CA8971.8040706@sbcglobal.net> Message-ID: <1c2a2c590809121240g27e94016m14d6117355825e48@mail.gmail.com> On Fri, Sep 12, 2008 at 11:23 AM, Wayne Watson wrote: > Do you know of a work around? You could use a regular expression match to check the format. Something like import re dateRe = re.compile(r'\d\d\d\d/\d\d/\d\d \d\d:\d\d:\d\d') if dateRe.match(d1): # handle correctly formatted date else: # handle incorrect date Kent From kent37 at tds.net Fri Sep 12 21:42:40 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 12 Sep 2008 15:42:40 -0400 Subject: [Tutor] Hay Variables In-Reply-To: References: Message-ID: <1c2a2c590809121242l738bc77fnd0caf395d0e2ef63@mail.gmail.com> On Fri, Sep 12, 2008 at 2:13 PM, wrote: > > I would use a list of grades and the length of the list. or perhaps a list of (class name, grade) pairs. Kent From optomatic at rogers.com Sat Sep 13 00:30:13 2008 From: optomatic at rogers.com (Patrick) Date: Fri, 12 Sep 2008 18:30:13 -0400 Subject: [Tutor] PySQLite vs SQLalchemy Message-ID: <48CAED75.6040401@rogers.com> I guess I am a Python framework burnout. I have tried so many of them over the past two months, they are just not right for me right now. I am trying to put together a program to generate my website offline via the MVC paradigm, all I need to deal with is lots of static data. I like SQLite, it's really easy to work with. I would like to model my database in it natively but I am having quite a bit of trouble mapping the variables in the SQLIte database via PySQLite. It appears that this sort of thing is SQLalchemy's strong suit. However I would prefer not to model my data base in it. So, I am just wondering if anyone has any feedback with regard to PySQLite and SQLalchemy. Is mapping the variables from the a database via PySQLite a common problem? Is SQLalchemy being used for desktop Applications? I bought a book on SQLalchemy but PySQLite seems to have sparse documentation. We can build Python with SQLite built right in, why is there not more documentation? Thanks in advance-Patrick From lavendula6654 at yahoo.com Sat Sep 13 01:09:20 2008 From: lavendula6654 at yahoo.com (Elaine) Date: Fri, 12 Sep 2008 16:09:20 -0700 (PDT) Subject: [Tutor] Python class at Foothill College Message-ID: <882160.57215.qm@web31306.mail.mud.yahoo.com> If you would like to learn Python, Foothill College is offering a course in Palo Alto starting Wednesday evening, 24 Sept, at 6 pm. This 12-week course is designed for students who are already familiar with another structured programming language. Here is more detailed information: CIS 68K "INTRODUCTION TO PYTHON PROGRAMMING" 5 Units Meets Wednesday evenings, 6 -9:40 pm, from 24 Sept. until 10 Dec. at Middlefield campus room J3. If you would like to sign up for the class, please register beforehand by going to: http://www.foothill.fhda.edu/reg/index.php If you have questions, you can contact the instructor at: haightElaine at foothill.edu From alan.gauld at btinternet.com Sat Sep 13 01:22:47 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 13 Sep 2008 00:22:47 +0100 Subject: [Tutor] How to create array of variants? References: <19441514.post@talk.nabble.com> <19450606.post@talk.nabble.com> Message-ID: "Krasyn" wrote in message news:19450606.post at talk.nabble.com... > # -*- coding:UTF-8 -*- > from comtypes.client import * > from array import array Any reason why you are using array here? Why not just a Python list? > acad = GetActiveObject("AutoCAD.Application") > dwg = acad.ActiveDocument > mspace = dwg.ModelSpace > circle = mspace.AddCircle(array("d",[0,0,0]),100) > circle.Color = 3 > acad.ZoomExtents() > dtype = array("h",[1001,1070]) # [1001,1070] doesnt' work (comtypes > 0.5.1) > dvalue = ['Test_Application', 600] #OK VARIANT is not needed If a imple list works here will it not work for the two numbers? Just a thought, Alan G From alan.gauld at btinternet.com Sat Sep 13 01:33:26 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 13 Sep 2008 00:33:26 +0100 Subject: [Tutor] PySQLite vs SQLalchemy References: <48CAED75.6040401@rogers.com> Message-ID: "Patrick" wrote > I like SQLite, it's really easy to work with. I would like to model > my > database in it natively but I am having quite a bit of trouble > mapping > the variables in the SQLIte database via PySQLite. It appears that > this > sort of thing is SQLalchemy's strong suit. However I would prefer > not to > model my data base in it. The two approaches are fundamentally different. PySQLite is basically a wrapper to allow SQLite ro work with the standard Python DBAPI (which is quite extensively documented on the web site). SQLAlchemy is an OOP wrapper around DBAPI that makes objects persistent by hiding the SQL from you. If you know SQL then you should be able to use the DB API without any problems. What are the specific issues you are having? What are you trying to do? How? And what goes wrong? > PySQLite and SQLalchemy. Is mapping the variables from the a > database > via PySQLite a common problem? No, it works very well in my experience Within the well known issues of mapping objects to an RDBMS of course - assuming thats what you are doing. > Is SQLalchemy being used for desktop Applications? Not by me, and it seems to be mainly uwsed in Web apps but I see no reason for it not to be used in a desktop app. You just need to use an OOP design. > sparse documentation. We can build Python with SQLite built right > in, > why is there not more documentation? Because you normally use the generic DBAPI which is documented in many places including several books Basic instructions are in the Database topic of my tutor... HTH Alan G. From jfabiani at yolo.com Sat Sep 13 01:42:11 2008 From: jfabiani at yolo.com (johnf) Date: Fri, 12 Sep 2008 16:42:11 -0700 Subject: [Tutor] PySQLite vs SQLalchemy In-Reply-To: <48CAED75.6040401@rogers.com> References: <48CAED75.6040401@rogers.com> Message-ID: <200809121642.11668.jfabiani@yolo.com> On Friday 12 September 2008 03:30:13 pm Patrick wrote: > I guess I am a Python framework burnout. I have tried so many of them > over the past two months, they are just not right for me right now. I am > trying to put together a program to generate my website offline via the > MVC paradigm, all I need to deal with is lots of static data. > > I like SQLite, it's really easy to work with. I would like to model my > database in it natively but I am having quite a bit of trouble mapping > the variables in the SQLIte database via PySQLite. It appears that this > sort of thing is SQLalchemy's strong suit. However I would prefer not to > model my data base in it. > > So, I am just wondering if anyone has any feedback with regard to > PySQLite and SQLalchemy. Is mapping the variables from the a database > via PySQLite a common problem? Is SQLalchemy being used for desktop > Applications? I bought a book on SQLalchemy but PySQLite seems to have > sparse documentation. We can build Python with SQLite built right in, > why is there not more documentation? > > Thanks in advance-Patrick Have you taken a look at pylons? On the surface pylons sounds like a good fit. I believe it uses SQLalchemy as it ORM. And if memory serves SQLalchemy has a feature where it will read in the data structures and setup the metadata for you. Which is what I think you are having trouble with. -- John Fabiani From jeff at drinktomi.com Sat Sep 13 01:42:12 2008 From: jeff at drinktomi.com (Jeff Younker) Date: Fri, 12 Sep 2008 16:42:12 -0700 Subject: [Tutor] PySQLite vs SQLalchemy In-Reply-To: <48CAED75.6040401@rogers.com> References: <48CAED75.6040401@rogers.com> Message-ID: On Sep 12, 2008, at 3:30 PM, Patrick wrote: > I like SQLite, it's really easy to work with. I would like to model my > database in it natively but I am having quite a bit of trouble mapping > the variables in the SQLIte database via PySQLite. It appears that > this > sort of thing is SQLalchemy's strong suit. However I would prefer > not to > model my data base in it. I'm curious why you feel that way? > So, I am just wondering if anyone has any feedback with regard to > PySQLite and SQLalchemy. Is mapping the variables from the a database > via PySQLite a common problem? Is SQLalchemy being used for desktop > Applications? I bought a book on SQLalchemy but PySQLite seems to have > sparse documentation. We can build Python with SQLite built right in, > why is there not more documentation? I personally have never even considered PySQLite. SQLAlchemy and SQLObject have covered all my needs from the small to the large quite handily. It saves me from having to resort to learning a new interface for each database, and it largely insulates my applications from changes in the underlaying database. [This isn't an academic possibility either. Much of my code is unit- tested against sqlite, but runs against mysql in production.] -jeff From tim at johnsons-web.com Sat Sep 13 02:42:19 2008 From: tim at johnsons-web.com (Tim Johnson) Date: Fri, 12 Sep 2008 16:42:19 -0800 Subject: [Tutor] Listing imported modules Message-ID: <200809121642.19532.tim@johnsons-web.com> If I execute the following code: imported = sys.modules.keys() print imported Do I indeed get a list of _all_ modules imported by this module? If so, then could anyone offer suggestion on how to "parse" the non-standard modules from this list. I.E. modules _not_ included in the standard python distribution. I can get a list of what appears to be all modules by starting the python interperter, invoke help() and then modules , but I'm looking for some way to do it programmatically. Using Python 2.5.1 on ubuntu 7.10 thanks tim -------------- next part -------------- An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Sat Sep 13 02:59:02 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Fri, 12 Sep 2008 17:59:02 -0700 Subject: [Tutor] Python class at Foothill College In-Reply-To: <882160.57215.qm@web31306.mail.mud.yahoo.com> References: <882160.57215.qm@web31306.mail.mud.yahoo.com> Message-ID: <48CB1056.3020007@sbcglobal.net> An HTML attachment was scrubbed... URL: From wescpy at gmail.com Sat Sep 13 03:34:53 2008 From: wescpy at gmail.com (wesley chun) Date: Fri, 12 Sep 2008 18:34:53 -0700 Subject: [Tutor] Python class at Foothill College In-Reply-To: <48CB1056.3020007@sbcglobal.net> References: <882160.57215.qm@web31306.mail.mud.yahoo.com> <48CB1056.3020007@sbcglobal.net> Message-ID: <78b3a9580809121834h1f39ede0tcde724c5779d4a26@mail.gmail.com> On Fri, Sep 12, 2008 at 5:59 PM, Wayne Watson wrote: > Interesting. I've been quite surprised that some community college in the > Bay Area hasn't offered Python recently. However, I'm long gone from there. > Sacramento, Davis, Rocklin, anyone? Haven't even seen any in UC extension > classes. I'm going to be near there early next week. Maybe I'll drop in to > see what books are going to be used. wayne, my Python courses are a *little* closer to you, in san francisco (as opposed to los altos hills). if i field significant interest in holding a course up there or in the nevada foothills, i'd be glad to do so. i sometimes teach the intermediate course that comes after elaine's at Foothill so i'm somewhat familiar with her's... the last time i checked, the course textbook they use is "Core Python Programming" (see link below). :-) cheers, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com "Python Web Development with Django", Addison Wesley, (c) 2008 http://withdjango.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From jfabiani at yolo.com Sat Sep 13 03:45:17 2008 From: jfabiani at yolo.com (johnf) Date: Fri, 12 Sep 2008 18:45:17 -0700 Subject: [Tutor] Python class at Foothill College In-Reply-To: <78b3a9580809121834h1f39ede0tcde724c5779d4a26@mail.gmail.com> References: <882160.57215.qm@web31306.mail.mud.yahoo.com> <48CB1056.3020007@sbcglobal.net> <78b3a9580809121834h1f39ede0tcde724c5779d4a26@mail.gmail.com> Message-ID: <200809121845.17622.jfabiani@yolo.com> On Friday 12 September 2008 06:34:53 pm wesley chun wrote: > On Fri, Sep 12, 2008 at 5:59 PM, Wayne Watson > > wrote: > > Interesting. I've been quite surprised that some community college in the > > Bay Area hasn't offered Python recently. However, I'm long gone from > > there. Sacramento, Davis, Rocklin, anyone? Haven't even seen any in UC > > extension classes. I'm going to be near there early next week. Maybe I'll > > drop in to see what books are going to be used. > > wayne, > > my Python courses are a *little* closer to you, in san francisco (as > opposed to los altos hills). if i field significant interest in > holding a course up there or in the nevada foothills, i'd be glad to > do so. > > i sometimes teach the intermediate course that comes after elaine's at > Foothill so i'm somewhat familiar with her's... the last time i > checked, the course textbook they use is "Core Python Programming" > (see link below). :-) > > cheers, > -- wesley I'd be interested if the class was advance and in the Sacramento area. -- John Fabiani From mikem at blazenetme.net Sat Sep 13 04:41:46 2008 From: mikem at blazenetme.net (Mike Meisner) Date: Fri, 12 Sep 2008 22:41:46 -0400 Subject: [Tutor] Printing Scripts with color/good formatting Message-ID: I've been working with Python on two different machines: under Windows XP and under 64-bit Vista. In the XP version, the Python 32-bit editor prints my scripts using the color coding in the editor and a comfortable to read font. Under Vista 64-bit, only the IDLE environment is available which prints my scripts without color and a larger, more difficult to read font (and there appears to be no way to customize the output). Is there an open-source editor I could use with Vista to get the more attractive, color coded script printout that I get with the 32--bit system? Thanks for your help. Mike -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Sep 13 09:18:28 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 13 Sep 2008 08:18:28 +0100 Subject: [Tutor] Printing Scripts with color/good formatting References: Message-ID: "Mike Meisner" wrote > In the XP version, the Python 32-bit editor I'm not sure which editor you mean? Is it Pythonwin? > Is there an open-source editor I could use with > Vista to get the more attractive, color coded > script printout that I get with the 32--bit system? Doesn't Pythonwin work on 64 bit Vista? If not I'm fairly sure Scite does and it uses the same editor component as Pythonwin. I think its print mechanism is the same too. HTH, Alan G From norman at khine.net Sat Sep 13 13:55:56 2008 From: norman at khine.net (Norman Khine) Date: Sat, 13 Sep 2008 13:55:56 +0200 Subject: [Tutor] Validation loop Message-ID: <48CBAA4C.9040507@khine.net> Hello, I am writting a little module that validates if a member has completed all the previous exams before they can access the current exam. The way, I thought it may work is to: Search all previous exams from the previous topics and check to see if the user has passed them, if not, then they cannot access this exam. This works to a point, in that, I only make a check in the topic before the current topic if the user has passed the exam. The problem is if, for example, I have this: topic-1 + exam1 topic-2 + no-exam topic3 + exam3 In topic-2 I don't have an exam, so my function returns true and the user can access both exam-1 and exam-3 Whereas I don't want them to access exam-3. Can you please look at my function and point me in the right direction. # Exam Access Control def can_take_exam(self, user, object): ''' Who is not allowed to take the exam: 1) If the user has not passed the exam from all the previous topics. ''' if self.is_admin(user, object): return True if not self.is_member(user, object): return False # Has the user already passed this exam? passed = object.get_result()[0] if passed: return False topic = object.parent prev_topic = topic.get_prev_topic() # First topic, user can take exam if prev_topic is None: return True # Previous topic has no exam exam = prev_topic.get_exam() if exam is None: return True # Has the user passed the previous exam? passed = exam.get_result()[0] return bool(passed) I was thinking maybe to put in the list all the previous topics and then loop through this for each exam and if all are passed then the user can take the current exam, if not then no. So I tried this: topics = object.parent.get_topics() for i, topic in enumerate(topics): all_previous_topics = topics[:i] if all_previous_topics is not None: return False for x in all_previous_topics: exam = x.get_exam(user.name) if exam is not None: passed = exam.get_result(user.name)[0] if passed: return bool(passed) But this, makes all exams non accessable. Any pointers much appreciated. Cheers Norman From bgailer at gmail.com Sat Sep 13 14:19:09 2008 From: bgailer at gmail.com (bob gailer) Date: Sat, 13 Sep 2008 08:19:09 -0400 Subject: [Tutor] Validation loop In-Reply-To: <48CBAA4C.9040507@khine.net> References: <48CBAA4C.9040507@khine.net> Message-ID: <48CBAFBD.3000601@gmail.com> Norman Khine wrote: > Hello, > I am writting a little module that validates if a member has completed > all the previous exams before they can access the current exam. > > The way, I thought it may work is to: > > Search all previous exams from the previous topics and check to see if > the user has passed them, if not, then they cannot access this exam. > > This works to a point, in that, I only make a check in the topic > before the current topic if the user has passed the exam. > > The problem is if, for example, I have this: > > topic-1 > + exam1 > topic-2 > + no-exam > topic3 > + exam3 > > In topic-2 I don't have an exam, so my function returns true and the > user can access both exam-1 and exam-3 > > Whereas I don't want them to access exam-3. > > Can you please look at my function and point me in the right direction. > > # Exam Access Control > def can_take_exam(self, user, object): > ''' > Who is not allowed to take the exam: > 1) If the user has not passed the exam from all the previous > topics. > ''' > if self.is_admin(user, object): > return True > if not self.is_member(user, object): > return False > > # Has the user already passed this exam? > passed = object.get_result()[0] > if passed: > return False > topic = object.parent > prev_topic = topic.get_prev_topic() > > # First topic, user can take exam > if prev_topic is None: > return True > > # Previous topic has no exam > exam = prev_topic.get_exam() > if exam is None: Seems that here you must recurse to the topic before prev_topic rather than returning True > return True > > # Has the user passed the previous exam? > passed = exam.get_result()[0] > return bool(passed) > > I was thinking maybe to put in the list all the previous topics and > then loop > through this for each exam and if all are passed then the user can > take the > current exam, if not then no. > > So I tried this: > > topics = object.parent.get_topics() > for i, topic in enumerate(topics): > all_previous_topics = topics[:i] > if all_previous_topics is not None: > return False > for x in all_previous_topics: > exam = x.get_exam(user.name) > if exam is not None: > passed = exam.get_result(user.name)[0] > if passed: > return bool(passed) > > > But this, makes all exams non accessable. > > Any pointers much appreciated. > > Cheers > > Norman > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Bob Gailer Chapel Hill NC 919-636-4239 When we take the time to be aware of our feelings and needs we have more satisfying interatctions with others. Nonviolent Communication provides tools for this awareness. As a coach and trainer I can assist you in learning this process. What is YOUR biggest relationship challenge? From optomatic at rogers.com Sat Sep 13 14:58:50 2008 From: optomatic at rogers.com (Patrick) Date: Sat, 13 Sep 2008 08:58:50 -0400 Subject: [Tutor] PySQLite vs SQLalchemy In-Reply-To: References: <48CAED75.6040401@rogers.com> Message-ID: <48CBB90A.9060707@rogers.com> Thanks Alan, Jeff and John! I am have been so impressed with the responses and response times I get from this list. I wish I could compensate you for your time(I'm broke at the moment), you just can't buy this "customer service" anywhere else. Hopefully when I am further along I can "man the fort" and help others too. I registered pythonwebprogramming.org, I hope to post tutorials here someday. I have had a bit of a rough go with it, hopefully I can help others later when I know what I am doing. Hey Jeff " I would prefer not to model my data base in it." > > I'm curious why you feel that way? I guess I might still end up doing so, it's just that SQLite was immediately intuitive to me. Thanks for your SQLAlchemy feedback! Hi John "Have you taken a look at pylons? " Yes, Pylons, CherryPy, Mod_Python, Django, Turbogears, Werkzeug and WebPy. I know I am a small minority but frameworks are really counter to my philosophy. I am a beginner, you would think that a beginner should start as small and as simple as possible and then work their way up as their knowledge improves. It seems to me that frameworks are just the opposite. A beginner needs to start with a bunch of directories they know nothing about and the easier the framework the more directories there seems to be. However this is not to say that this was not a good tip, I can see how valuable Pylons could be to someone, I'll probably end up with it in the end, thanks! Hey Alan "If you know SQL then you should be able to use the DB API without any problems. What are the specific issues you are having?" Thanks for your feedback, tips and your tutorial. I can see how much documentation the DB API has now. The troubles I was running into were from my poor understanding of this. Now that I have more documentation I will be just fine. "HTH" It does!, thanks From emile at fenx.com Sat Sep 13 19:38:42 2008 From: emile at fenx.com (Emile van Sebille) Date: Sat, 13 Sep 2008 10:38:42 -0700 Subject: [Tutor] Listing imported modules In-Reply-To: <200809121642.19532.tim@johnsons-web.com> References: <200809121642.19532.tim@johnsons-web.com> Message-ID: Tim Johnson wrote: > If I execute the following code: > > imported = sys.modules.keys() > > print imported > > Do I indeed get a list of _all_ modules imported by this module? > > If so, then could anyone offer suggestion on how to "parse" the > > non-standard modules from this list. I.E. modules _not_ included in > > the standard python distribution. Hmmm... it looks to me that you can import site and use sitedirs to identify the paths used for third party packages. Then filter __file__ of the sys.modules.keys() against that. HTH, Emile From tim at johnsons-web.com Sat Sep 13 19:55:19 2008 From: tim at johnsons-web.com (Tim Johnson) Date: Sat, 13 Sep 2008 09:55:19 -0800 Subject: [Tutor] Listing imported modules In-Reply-To: <1c2a2c590809122002w625b2e0w65b162bb3fd3026b@mail.gmail.com> References: <200809121642.19532.tim@johnsons-web.com> <1c2a2c590809122002w625b2e0w65b162bb3fd3026b@mail.gmail.com> Message-ID: <200809130955.19770.tim@johnsons-web.com> On Friday 12 September 2008, you wrote: > On Fri, Sep 12, 2008 at 8:42 PM, Tim Johnson wrote: > > If I execute the following code: > > > > imported = sys.modules.keys() > > > > print imported > > > > Do I indeed get a list of _all_ modules imported by this module? > > You get a list of all modules that have been imported at any time by > the running program, not necessarily just in the current module. > > > If so, then could anyone offer suggestion on how to "parse" the > > > > non-standard modules from this list. I.E. modules _not_ included in > > > > the standard python distribution. > > sys.modules is a dict mapping names to the actual modules. Most > modules have a __file__ attribute that is the path to the file > containing the module. Perhaps you could filter out the modules that > are in the standard library path and see what is left. Thanks Kent. And there is also the Global Module Index at http://docs.python.org/modindex.html. I could convert that to a data structure to use as the control. cheers tim From webmaster at monzell.com Sat Sep 13 21:53:34 2008 From: webmaster at monzell.com (Rilindo Foster) Date: Sat, 13 Sep 2008 15:53:34 -0400 Subject: [Tutor] Addition, Dictionary, KeysError Message-ID: <316CA5DD-A901-4098-A972-E2B2973D3D72@monzell.com> Another silly question (if you were to call it a question) Pulling the list of Store Orders and Sales and I am attempting to accumulate the total amount of sales per Store. In Perl, if I were to iterate through a hash, I can easily add the values and populate the hash with: TotalSales{Store} = TotalSales{Store} + Sales In Python, it won't let me do that. If I were to do what I have done in Perl: OrderDict[o[0]] = float(OrderDict[o[0]]) + float(o[1]) I kept getting a "KeyError". Am I doing this right? For some reason, I think I know the answer, but I can't put my finger on it. From webmaster at monzell.com Sat Sep 13 22:05:37 2008 From: webmaster at monzell.com (Rilindo Foster) Date: Sat, 13 Sep 2008 16:05:37 -0400 Subject: [Tutor] Addition, Dictionary, KeysError References: <316CA5DD-A901-4098-A972-E2B2973D3D72@monzell.com> Message-ID: Scratch that, I'm a dork: OrderDict[(o[0])] = OrderDict.get(o[0],0) + float(o[1]) http://www.faqts.com/knowledge_base/view.phtml/aid/4571/fid/541 :D > From: Rilindo Foster > Date: September 13, 2008 3:53:34 PM EDT > To: Tutor at python.org > Subject: Addition, Dictionary, KeysError > > Another silly question (if you were to call it a question) > > Pulling the list of Store Orders and Sales and I am attempting to > accumulate the total amount of sales per Store. > > In Perl, if I were to iterate through a hash, I can easily add the > values and populate the hash with: > > TotalSales{Store} = TotalSales{Store} + Sales > > In Python, it won't let me do that. If I were to do what I have done > in Perl: > > OrderDict[o[0]] = float(OrderDict[o[0]]) + float(o[1]) > > I kept getting a "KeyError". > > Am I doing this right? For some reason, I think I know the answer, > but I can't put my finger on it. -------------- next part -------------- An HTML attachment was scrubbed... URL: From mwalsh at mwalsh.org Sat Sep 13 22:52:02 2008 From: mwalsh at mwalsh.org (Martin Walsh) Date: Sat, 13 Sep 2008 15:52:02 -0500 Subject: [Tutor] Addition, Dictionary, KeysError In-Reply-To: References: <316CA5DD-A901-4098-A972-E2B2973D3D72@monzell.com> Message-ID: <48CC27F2.7090403@mwalsh.org> Rilindo Foster wrote: > Scratch that, I'm a dork: > > OrderDict[(o[0])] = OrderDict.get(o[0],0) + float(o[1]) > > http://www.faqts.com/knowledge_base/view.phtml/aid/4571/fid/541 > > :D > For this case you might also be interested in collections.defaultdict, added in python 2.5 I believe. from collections import defaultdict orders = defaultdict(float) orders[o[0]] += float(o[1]) HTH, Marty From mwalsh at mwalsh.org Sat Sep 13 23:06:39 2008 From: mwalsh at mwalsh.org (Martin Walsh) Date: Sat, 13 Sep 2008 16:06:39 -0500 Subject: [Tutor] Addition, Dictionary, KeysError In-Reply-To: <48CC27F2.7090403@mwalsh.org> References: <316CA5DD-A901-4098-A972-E2B2973D3D72@monzell.com> <48CC27F2.7090403@mwalsh.org> Message-ID: <48CC2B5F.4060102@mwalsh.org> Martin Walsh wrote: > Rilindo Foster wrote: >> Scratch that, I'm a dork: >> >> OrderDict[(o[0])] = OrderDict.get(o[0],0) + float(o[1]) >> >> http://www.faqts.com/knowledge_base/view.phtml/aid/4571/fid/541 >> >> :D >> > > For this case you might also be interested in collections.defaultdict, > added in python 2.5 I believe. > > from collections import defaultdict > > orders = defaultdict(float) > orders[o[0]] += float(o[1]) > > HTH, > Marty It is so unlike me to respond without the obligatory doc reference: http://docs.python.org/lib/defaultdict-objects.html http://docs.python.org/lib/defaultdict-examples.html FWIW, you can also accomplish something similar by subclassing dict and defining a __missing__ method (also added in 2.5). Something like this (untested): class OrderDict(dict): def __missing__(self, key): return 0.0 orders = OrderDict() orders[o[0]] += float(o[1]) See http://docs.python.org/lib/typesmapping.html Note that it doesn't actually update the dict with any access as defaultdict would... In [3]: orders = defaultdict(float) In [4]: orders['somekey'] Out[4]: 0.0 In [5]: orders Out[5]: defaultdict(, {'somekey': 0.0}) In [6]: orders = OrderDict() In [7]: orders['somekey'] Out[7]: 0.0 In [8]: orders Out[8]: {} HTH, Marty From Jaggojaggo+Py at gmail.com Sat Sep 13 23:42:28 2008 From: Jaggojaggo+Py at gmail.com (Omer) Date: Sun, 14 Sep 2008 00:42:28 +0300 Subject: [Tutor] Win32 extensions In-Reply-To: References: Message-ID: <515008f10809131442s3d25ef2fn45713dfd66736cc0@mail.gmail.com> On Fri, Sep 12, 2008 at 2:31 AM, Alan Gauld wrote: > Yes if you spend a lot of money. > You can buy a set of libraries from a comany called Bristol > Technology (I think, it's over 8 years since I used it!) that allows > you to build Windows software on a Unix box. A bit like cygwin > in reverse! Some Microsoft developers actually used it during the > development of the first version of Windows NT I believe! > Errm, What'd be the difference between this and WINE ? -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Sep 14 00:39:05 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 13 Sep 2008 23:39:05 +0100 Subject: [Tutor] Win32 extensions References: <515008f10809131442s3d25ef2fn45713dfd66736cc0@mail.gmail.com> Message-ID: "Omer" wrote >> You can buy a set of libraries from a comany called Bristol >> Technology (I think, it's over 8 years since I used it!) that >> allows >> you to build Windows software on a Unix box. A bit like cygwin > > Errm, What'd be the difference between this and WINE ? WINE lets you run windows programs but not develop them. ie. WINE doesn't include all the header files etc Bristol supplies the development libraries needed to build and run native Windows apps on Unix not just the DLLs needed to run software built on Windows Note that for Python programs for Windows these are not needed they are only for programs/DLLs written in C/C++. I suspect Python code using the Win32 extensions or ctypes would work OK under WINE. HTH, Alan G. From agilfoy at frontiernet.net Sun Sep 14 03:02:43 2008 From: agilfoy at frontiernet.net (Alan Gilfoy) Date: Sun, 14 Sep 2008 01:02:43 +0000 Subject: [Tutor] Doing this in reverse? Message-ID: <20080914010243.ba6wruppc0oo0c0c@webmail.frontiernet.net> I found a script at http://code.activestate.com/recipes/65212/ that allows you to convert base 10 numbers to another base. I would like to convert non-base10 numbers to base 10. I wonder if I can do so by flipping the script around a bit: # (Lovingly) ripped off from a reply to the post at # http://code.activestate.com/recipes/65212/ # The function code is from that page # User Interface + comments created by Alan Gilfoy, 2007-2008 def baseconvert(n, base): """convert positive decimal integer n to equivalent in another base (2-36)""" digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" # a thru z only apply in base 11 and up. # base 11 uses only a, base 12 uses a thru b, base 13 uses a thru c, and so on. # 'a' is equivalent to '10' in decimal, 'b' is equivalent to '11', etc. try: n = int(n) base = int(base) except: return "" if n < 0 or base < 2 or base > 36: return "" s = "" while 1: r = n % base s = digits[r] + s n = n / base if n == 0: break return s ---- I'm not entirely sure how this works; I just know that it does. It looks like the program goes through a loop that "chops away" at the inputted number, gradually adding to the outputted number as appropriate. And what exactly does the % operator mean? From marc.tompkins at gmail.com Sun Sep 14 09:08:52 2008 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Sun, 14 Sep 2008 00:08:52 -0700 Subject: [Tutor] Doing this in reverse? In-Reply-To: <20080914010243.ba6wruppc0oo0c0c@webmail.frontiernet.net> References: <20080914010243.ba6wruppc0oo0c0c@webmail.frontiernet.net> Message-ID: <40af687b0809140008l4bf0eab3w6e7246eb8cfa7087@mail.gmail.com> On Sat, Sep 13, 2008 at 6:02 PM, Alan Gilfoy wrote: > I found a script at http://code.activestate.com/recipes/65212/ that allows > you to convert base 10 numbers to another base. I would like to convert non-base10 numbers to base 10. I wonder if I can do > so by flipping the script around a bit: > The built-in int() function does what you need - give it a string representation of a number in any base 2-36; pass the base as the second argument. The return is an integer - a pure, Platonic integer - which you can then print in any base you choose. If you omit the second argument (as you usually do), the base is assumed to be 10. The documentation says that if you pass 0 as the second argument, Python will try to guess the base, but it didn't work when I tried it. Example: >> int('FF', 16) 255 Now, about the code you posted - When you perform integer division, you basically go back to second-grade math (you know, before you learned long division...) The "/" operator returns the integer quotient - example: >> 7 / 2 3 The "%" operator - aka "modulo" - returns the remainder - example: >> 7 % 2 1 So... s = "" while 1: # keep looping until we break out explicitly r = n % base # divide n by base, r is the remainder s = digits[r] + s # look up which digit r corresponds to, add it to the left side of the string we're building n = n / base # divide n by base again, this time keeping only the integer quotient if n == 0: # if quotient is 0, break # we're done -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From jmorcombe at westnet.com.au Sun Sep 14 09:46:59 2008 From: jmorcombe at westnet.com.au (Jim Morcombe) Date: Sun, 14 Sep 2008 15:46:59 +0800 Subject: [Tutor] Simple physics simulations) Message-ID: <48CCC173.8030901@westnet.com.au> I want to write a program that helps teach students how to draw ray diagrams for lenses and mirrors. Vpython seems to be used for a number of physics simulations, but may be overkill for my application. Although there are a few 3D things I would like to do, most just involves drawing curves and simple objects, and allowing the User to do the same. So the question - What is the best thing to use to draw and manipulate simple 2D objects in an application like this? Jim Morcombe From alan.gauld at btinternet.com Sun Sep 14 11:36:09 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 14 Sep 2008 10:36:09 +0100 Subject: [Tutor] Simple physics simulations) References: <48CCC173.8030901@westnet.com.au> Message-ID: "Jim Morcombe" wrote > I want to write a program that helps teach students how to draw ray > diagrams for lenses and mirrors. For simple 2D lines and arcs then the basic Canvas widget of Tkinter or wxPython would be fine. > Vpython seems to be used for a number of physics simulations, but > may be overkill for my application. I don;t know too much about VPython and have certainly never used it but it might be better suited to more complex 3D work. > like to do, most just involves drawing curves and simple objects, > and allowing the User to do the same. > > So the question - What is the best thing to use to draw and > manipulate simple 2D objects in an application like this? I'd start with the basic Canvas. There are several tutorials around showing how to build basic drawing apps and these could be modified to do what you want. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Sun Sep 14 13:48:02 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 14 Sep 2008 07:48:02 -0400 Subject: [Tutor] Doing this in reverse? In-Reply-To: <40af687b0809140008l4bf0eab3w6e7246eb8cfa7087@mail.gmail.com> References: <20080914010243.ba6wruppc0oo0c0c@webmail.frontiernet.net> <40af687b0809140008l4bf0eab3w6e7246eb8cfa7087@mail.gmail.com> Message-ID: <1c2a2c590809140448m6c60df7dm1784b0e51bf6ea14@mail.gmail.com> On Sun, Sep 14, 2008 at 3:08 AM, Marc Tompkins wrote: > The built-in int() function does what you need - give it a string > representation of a number in any base 2-36; pass the base as the second > argument. The return is an integer - a pure, Platonic integer - which you > can then print in any base you choose. > If you omit the second argument (as you usually do), the base is assumed to > be 10. > The documentation says that if you pass 0 as the second argument, Python > will try to guess the base, but it didn't work when I tried it. The docs say, "If radix is zero, the proper radix is guessed based on the contents of string; the interpretation is the same as for integer literals." 'guessed' is not really a very good choice of words; 'determined' might be better. The last part of the sentence is the clue. With one argument, int() expects just the string representation of an int; any characters that are not digits are an error. For example: In [7]: int('0xaa') --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /Users/kent/ in () ValueError: invalid literal for int() with base 10: '0xaa' If you pass 0 as the second argument, int() interprets the usual prefix for integer literals, and the above works: In [4]: int('0xaa', 0) Out[4]: 170 Also notice the difference here: In [5]: int('011') Out[5]: 11 In [6]: int('011', 0) Out[6]: 9 In the first case, the leading 0 has no special meaning and the result is 11. In the second case, the leading 0 is interpreted to mean 'octal' and the result is different. Kent From kent37 at tds.net Sun Sep 14 14:32:03 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 14 Sep 2008 08:32:03 -0400 Subject: [Tutor] Extracting body of all email messages from an mbox file on computer In-Reply-To: <87B0CBB9-40C7-4B79-BAAE-FBB368F6EC88@gmail.com> References: <87B0CBB9-40C7-4B79-BAAE-FBB368F6EC88@gmail.com> Message-ID: <1c2a2c590809140532p4c240f69s1fc2563312e5b732@mail.gmail.com> On Thu, Sep 11, 2008 at 4:22 AM, grishma govani wrote: > I have the e-mails from gmail in a file on my computer. I have used the code > below extract all the headers. As you can see for now I am using text stored > in document as my body. I just want to extract the plain text and leave out > all the html, duplicates of plain text and all the other information like > content type, from etc. Can anyone help me out? Here is a program that shows the contents of an mbox file. It shows the subject of each message and the content-type and except from each part of the message body. It works with both single and multipart messages. import mailbox def showMbox(mboxPath): box = mailbox.mbox(mboxPath) for msg in box: print msg['Subject'] showPayload(msg) print print '**********************************' print def showPayload(msg): payload = msg.get_payload() if msg.is_multipart(): div = '' for subMsg in payload: print div showPayload(subMsg) div = '------------------------------' else: print msg.get_content_type() print payload[:200] if __name__ == '__main__': showMbox('/path/to/mbox'') Kent From Jaggojaggo+Py at gmail.com Sun Sep 14 17:36:42 2008 From: Jaggojaggo+Py at gmail.com (Omer) Date: Sun, 14 Sep 2008 18:36:42 +0300 Subject: [Tutor] Printing Scripts with color/good formatting In-Reply-To: References: Message-ID: <515008f10809140836p74a31b66j755fb69aa0ad1a9@mail.gmail.com> I went through a similar process: I got used to PyWin on XP, then when switching to Vista pywin did not install with Python. So I simply downloaded and installed it. (link: http://sourceforge.net/projects/pywin32/ ) Hth, Omer. On Sat, Sep 13, 2008 at 5:41 AM, Mike Meisner wrote: > I've been working with Python on two different machines: under Windows > XP and under 64-bit Vista. > > In the XP version, the Python 32-bit editor prints my scripts using the > color coding in the editor and a comfortable to read font. Under Vista > 64-bit, only the IDLE environment is available which prints my scripts > without color and a larger, more difficult to read font (and there appears > to be no way to customize the output). > > Is there an open-source editor I could use with Vista to get the more > attractive, color coded script printout that I get with the 32--bit system? > > Thanks for your help. > > Mike > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jaggojaggo at gmail.com Sun Sep 14 17:30:43 2008 From: jaggojaggo at gmail.com (Jaggo) Date: Sun, 14 Sep 2008 18:30:43 +0300 Subject: [Tutor] Hay Variables In-Reply-To: <1c2a2c590809121242l738bc77fnd0caf395d0e2ef63@mail.gmail.com> References: <1c2a2c590809121242l738bc77fnd0caf395d0e2ef63@mail.gmail.com> Message-ID: <515008f10809140830h77e8aee5v83372785057cee19@mail.gmail.com> ... or maybe a dict of class[class-name]=grade On Fri, Sep 12, 2008 at 10:42 PM, Kent Johnson wrote: > On Fri, Sep 12, 2008 at 2:13 PM, > wrote: > > > > I would use a list of grades and the length of the list. > > or perhaps a list of (class name, grade) pairs. > > Kent > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From noufal at nibrahim.net.in Sun Sep 14 18:51:45 2008 From: noufal at nibrahim.net.in (Noufal Ibrahim) Date: Sun, 14 Sep 2008 22:21:45 +0530 Subject: [Tutor] Simple physics simulations) In-Reply-To: <48CCC173.8030901@westnet.com.au> References: <48CCC173.8030901@westnet.com.au> Message-ID: <48CD4121.6080404@nibrahim.net.in> Jim Morcombe wrote: > I want to write a program that helps teach students how to draw ray > diagrams for lenses and mirrors. Vpython seems to be used for a number > of physics simulations, but may be overkill for my application. > Although there are a few 3D things I would like to do, most just > involves drawing curves and simple objects, and allowing the User to do > the same. > > So the question - What is the best thing to use to draw and manipulate > simple 2D objects in an application like this? I'd stick to a simple 2D Gui toolkit that has a canvas. Tkinter comes by default and is usually more than sufficient for simple applications. Simple physics like the thin lens equation etc. can probably be done by hand for your application. I don't think you need to really use a *real* physics engine. For heavy duty physics simulation (the kind you see in modern games), you can take a look at the Open Dynamics Engine (http://www.ode.org/). There are Python bindings. I managed to get some of the demos to work fine. -- ~noufal http://nibrahim.net.in/ From jeff at drinktomi.com Sun Sep 14 19:36:17 2008 From: jeff at drinktomi.com (Jeff Younker) Date: Sun, 14 Sep 2008 10:36:17 -0700 Subject: [Tutor] Win32 extensions In-Reply-To: References: Message-ID: <23822C24-A97C-4B51-9964-2130B53F52E0@drinktomi.com> On Sep 11, 2008, at 2:52 PM, Spencer Parker wrote: > I am tasked with a project to use WMI to script something on Windows > Server 2003. I was wondering if it is possible to create a script > on a linux machine and use the Win32 extensions...since I need those > to use WMI python module as well. Is this actually possible? > Otherwise I would have to use a windows server in order to run these > scripts. I do not want to use VB is I don't have or a windows > server. I am deploying Windows Servers from behind a linux PXE. One option is to use VMWare or Xen to run windows as a virtual machine on whatever flavor of unix you're using. - Jeff Younker - jeff at drinktomi.com - > > -- > Spencer Parker > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From marc.tompkins at gmail.com Sun Sep 14 21:34:59 2008 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Sun, 14 Sep 2008 12:34:59 -0700 Subject: [Tutor] Doing this in reverse? In-Reply-To: <1c2a2c590809140448m6c60df7dm1784b0e51bf6ea14@mail.gmail.com> References: <20080914010243.ba6wruppc0oo0c0c@webmail.frontiernet.net> <40af687b0809140008l4bf0eab3w6e7246eb8cfa7087@mail.gmail.com> <1c2a2c590809140448m6c60df7dm1784b0e51bf6ea14@mail.gmail.com> Message-ID: <40af687b0809141234t18d0417fy4e2612b74353f63a@mail.gmail.com> On Sun, Sep 14, 2008 at 4:48 AM, Kent Johnson wrote: > The docs say, "If radix is zero, the proper radix is guessed based on > the contents of string; the interpretation is the same as for integer > literals." > > 'guessed' is not really a very good choice of words; 'determined' > might be better. The last part of the sentence is the clue. > You're right - if it had said "determined", I would have thought to insert a "0x" at the beginning of my test string. Since it said "guessed", it didn't occur to me to do that, with the following result: >> int("FF", 0) Traceback (most recent call last): File "", line 1, in ValueError: invalid literal for int() with base 0: 'FF' which seemed to say to me that the function is trying to interpret the string as base 0: what the heck would that mean, anyway? Is that not just a particularly elaborate version of division by zero? I had written a short passage reviling this as a useless feature, when it struck me that there actually is a use case for it: if you're parsing a text file (or perhaps the Windows registry?) full of numeric values in arbitrary encodings. You know - on one line there's a value expressed in decimal, then something in octal, something in binary, something in hex. If I ever run into a file like that - and so far I never have - I won't have to write a custom parser. Hurrah! -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Sun Sep 14 23:29:16 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 14 Sep 2008 17:29:16 -0400 Subject: [Tutor] Doing this in reverse? In-Reply-To: <40af687b0809141234t18d0417fy4e2612b74353f63a@mail.gmail.com> References: <20080914010243.ba6wruppc0oo0c0c@webmail.frontiernet.net> <40af687b0809140008l4bf0eab3w6e7246eb8cfa7087@mail.gmail.com> <1c2a2c590809140448m6c60df7dm1784b0e51bf6ea14@mail.gmail.com> <40af687b0809141234t18d0417fy4e2612b74353f63a@mail.gmail.com> Message-ID: <1c2a2c590809141429l5428dddajb4ea284123474099@mail.gmail.com> On Sun, Sep 14, 2008 at 3:34 PM, Marc Tompkins wrote: > On Sun, Sep 14, 2008 at 4:48 AM, Kent Johnson wrote: >> 'guessed' is not really a very good choice of words; 'determined' >> might be better. The last part of the sentence is the clue. > > You're right - if it had said "determined", I would have thought to insert a > "0x" at the beginning of my test string. BTW I submitted a bug report suggesting this change and it has been patched already :-) Kent From cfuller084 at thinkingplanet.net Sun Sep 14 23:50:02 2008 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Sun, 14 Sep 2008 16:50:02 -0500 Subject: [Tutor] Simple physics simulations) In-Reply-To: <48CCC173.8030901@westnet.com.au> References: <48CCC173.8030901@westnet.com.au> Message-ID: <200809141650.03071.cfuller084@thinkingplanet.net> You could also try out PyGeo, which is based on VisualPython. You could also use a geometry application like Kig, which has Python scripting support. http://pygeo.sourceforge.net/ http://edu.kde.org/kig/ Cheers On Sunday 14 September 2008 02:46, Jim Morcombe wrote: > I want to write a program that helps teach students how to draw ray > diagrams for lenses and mirrors. > Vpython seems to be used for a number of physics simulations, but may be > overkill for my application. Although there are a few 3D things I would > like to do, most just involves drawing curves and simple objects, and > allowing the User to do the same. > > So the question - What is the best thing to use to draw and manipulate > simple 2D objects in an application like this? > > Jim Morcombe > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From btkuhn at email.unc.edu Mon Sep 15 02:19:57 2008 From: btkuhn at email.unc.edu (btkuhn at email.unc.edu) Date: Sun, 14 Sep 2008 20:19:57 -0400 Subject: [Tutor] Practice exercise sources Message-ID: <20080914201957.w5cr5j2mio8gs8ss@webmail4.isis.unc.edu> Hi guys, I'm new to programming and have been learning Python as suggested by a friend as a good language to start with. I bought the "Learning Python" book from O'Reilly and I'm about 2/3 of the way through, and I've also read through 2 intro tutorials on the web. At this point, I understand the basics of lists, functions, objects, etc. and can code to solve simple problems. However, I'm finding that learning programming is like learning math: you can't learn simply reading the book - solving problems is what reinforces the material and helps you remember it, and teaches you to solve problems creatively. The book (although very comprehensive) doesn't have many problems, and the tutorials I've found only have basic exercises that illustrate the point they are making. I've read through some of the archives on this list and this is somewhat helpful as far as providing unique problems, but I guess what I'm looking for is a database/list of problems to solve, with answers that you can look at after you've had a go, so that you can see what the "expert" would have done. Kind of akin to the problems at the end of the chapter in a math textbook, with solutions in the back. Can anyone point me towards a good resource? Thanks very much, Ben From marc.tompkins at gmail.com Mon Sep 15 03:42:18 2008 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Sun, 14 Sep 2008 18:42:18 -0700 Subject: [Tutor] Doing this in reverse? In-Reply-To: <1c2a2c590809141429l5428dddajb4ea284123474099@mail.gmail.com> References: <20080914010243.ba6wruppc0oo0c0c@webmail.frontiernet.net> <40af687b0809140008l4bf0eab3w6e7246eb8cfa7087@mail.gmail.com> <1c2a2c590809140448m6c60df7dm1784b0e51bf6ea14@mail.gmail.com> <40af687b0809141234t18d0417fy4e2612b74353f63a@mail.gmail.com> <1c2a2c590809141429l5428dddajb4ea284123474099@mail.gmail.com> Message-ID: <40af687b0809141842u2fa3a368g477fa46b19fb215e@mail.gmail.com> On Sun, Sep 14, 2008 at 2:29 PM, Kent Johnson wrote: > On Sun, Sep 14, 2008 at 3:34 PM, Marc Tompkins > wrote: > > On Sun, Sep 14, 2008 at 4:48 AM, Kent Johnson wrote: > >> 'guessed' is not really a very good choice of words; 'determined' > >> might be better. The last part of the sentence is the clue. > > > > You're right - if it had said "determined", I would have thought to > insert a > > "0x" at the beginning of my test string. > > BTW I submitted a bug report suggesting this change and it has been > patched already :-) > > Kent > Which - the documentation, or the function? -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Sep 15 09:39:23 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 15 Sep 2008 08:39:23 +0100 Subject: [Tutor] Practice exercise sources References: <20080914201957.w5cr5j2mio8gs8ss@webmail4.isis.unc.edu> Message-ID: wrote > somewhat helpful as far as providing unique problems, but I guess > what I'm looking for is a database/list of problems to solve, with > answers Not quite the same but very useful is the Python Challenge web site. Its rather like an adventure game where the solution to one challenge takes you to the next. Its particularly good at bringing out some of the lesser known modules in the library and more obscure functions. Another option is the Useless Python web site. Be sure to visit the old site too. It has lots of suggested problems, some of which have solutions. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Mon Sep 15 12:30:27 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 15 Sep 2008 06:30:27 -0400 Subject: [Tutor] Doing this in reverse? In-Reply-To: <40af687b0809141842u2fa3a368g477fa46b19fb215e@mail.gmail.com> References: <20080914010243.ba6wruppc0oo0c0c@webmail.frontiernet.net> <40af687b0809140008l4bf0eab3w6e7246eb8cfa7087@mail.gmail.com> <1c2a2c590809140448m6c60df7dm1784b0e51bf6ea14@mail.gmail.com> <40af687b0809141234t18d0417fy4e2612b74353f63a@mail.gmail.com> <1c2a2c590809141429l5428dddajb4ea284123474099@mail.gmail.com> <40af687b0809141842u2fa3a368g477fa46b19fb215e@mail.gmail.com> Message-ID: <1c2a2c590809150330r10f5c34bl287416a6d6b058ad@mail.gmail.com> On Sun, Sep 14, 2008 at 9:42 PM, Marc Tompkins wrote: > On Sun, Sep 14, 2008 at 2:29 PM, Kent Johnson wrote: >> BTW I submitted a bug report suggesting this change and it has been >> patched already :-) >> >> Kent > > Which - the documentation, or the function? The docs. Kent From kent37 at tds.net Mon Sep 15 13:04:04 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 15 Sep 2008 07:04:04 -0400 Subject: [Tutor] Practice exercise sources In-Reply-To: <20080914201957.w5cr5j2mio8gs8ss@webmail4.isis.unc.edu> References: <20080914201957.w5cr5j2mio8gs8ss@webmail4.isis.unc.edu> Message-ID: <1c2a2c590809150404u3f49922eub45f282dba59122f@mail.gmail.com> On Sun, Sep 14, 2008 at 8:19 PM, wrote: > I've read through some of the archives on this list and this is somewhat > helpful as far as providing unique problems, but I guess what I'm looking > for is a database/list of problems to solve, Some suggestions here: http://personalpages.tds.net/~kent37/stories/00021.html#e21puzzles-and-problems Kent From norman at khine.net Mon Sep 15 16:56:00 2008 From: norman at khine.net (Norman Khine) Date: Mon, 15 Sep 2008 16:56:00 +0200 Subject: [Tutor] list slice Message-ID: <48CE7780.9000107@khine.net> Hello, I have this code: topics = object.parent.get_topics() for i, topic in enumerate(topics): all_previous_topics = topics[:i] print all_previous_topics where topics returns a list. I am trying to get all the topics before current topic in the loop. Is there a way to do this? Cheers Norman From malaclypse2 at gmail.com Mon Sep 15 17:30:24 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Mon, 15 Sep 2008 11:30:24 -0400 Subject: [Tutor] list slice In-Reply-To: <48CE7780.9000107@khine.net> References: <48CE7780.9000107@khine.net> Message-ID: <16651e80809150830t4744a80eh6715ca04608b51d@mail.gmail.com> On Mon, Sep 15, 2008 at 10:56 AM, Norman Khine wrote: > Hello, > I have this code: > > topics = object.parent.get_topics() > for i, topic in enumerate(topics): > all_previous_topics = topics[:i] > print all_previous_topics > > where topics returns a list. > > I am trying to get all the topics before current topic in the loop. > > Is there a way to do this? Yes. Is topics a list, or a function which returns a list? What you've written above works for me when topics is a list. In what way doesn't it work for you? >>> topics = ['Reading', 'Writing', 'Arithmetic'] >>> for i, topic in enumerate(topics): print "Current Topic: ", topic print "Previous Topics: ", topics[:i] Current Topic: Reading Previous Topics: [] Current Topic: Writing Previous Topics: ['Reading'] Current Topic: Arithmetic Previous Topics: ['Reading', 'Writing'] >>> -- Jerry From jtp at nc.rr.com Mon Sep 15 22:22:10 2008 From: jtp at nc.rr.com (James) Date: Mon, 15 Sep 2008 16:22:10 -0400 Subject: [Tutor] clearing lines for a 'front end' to a tool Message-ID: All, I'm writing a rather complex script which will preform quite a number of complex file system tasks in the background. The program is threaded and almost fully automated. I'm writing a 'front end' which will show a list of the "things" that are currently happening in the background in a simple (non-interactive) interface. Here's an idea of what the terminal will look like when the program is running. >>> verifying file system contents >>> starting parallel background process(es) >>> (job 1 of 5) backing up file system >>> (job 2 of 5) generating new content >>> Jobs: 0 of 5 complete, 2 running Load avg: 0.40, 0.27, 0.24 The trick here is "blocking" actions and how the output will be modified when another task starts up. Let's say that job 1 finishes; the output will look like this: >>> verifying file system contents >>> starting parallel background process(es) >>> (job 1 of 5) backing up file system >>> (job 2 of 5) generating new content >>> Done generating new content >>> (job 3 or 5) putting content in correct subdirectories >>> (job 4 of 5) tweaking new content for system >>> Jobs: 1 of 5 complete, 3 running Load avg: 0.8, 0.41, 0.2 As can be seen from the output above, when the first "blocking" job is done (2 of 5), certain other threads can be kicked off. The question here is mostly about how to generate this output. The bottom line (the 'status') *always* remains at the bottom of the screen. The other processes are updated in 'real time', so when job 2 was done, a "Done generating new content" line appeared, and the lines indicating jobs 3 and 4 appeared (while, again, the status line remained at the bottom). I'm unsure how to go about doing this... I imagine that the ANSI "clear line" value may be helpful, but I haven't had much luck getting that to work as I'd like. Curses seems like overkill in a situation like this. Any thoughts on how to best accomplish my goal? Thanks! -j From kent37 at tds.net Mon Sep 15 22:53:36 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 15 Sep 2008 16:53:36 -0400 Subject: [Tutor] clearing lines for a 'front end' to a tool In-Reply-To: References: Message-ID: <1c2a2c590809151353p46c21aexa551ae0bcfae6e2d@mail.gmail.com> On Mon, Sep 15, 2008 at 4:22 PM, James wrote: > The question here is mostly about how to generate this output. The > bottom line (the 'status') *always* remains at the bottom of the > screen. The other processes are updated in 'real time', so when job 2 > was done, a "Done generating new content" line appeared, and the lines > indicating jobs 3 and 4 appeared (while, again, the status line > remained at the bottom). > Maybe urwid would help: http://excess.org/urwid/ Kent From spython01 at gmail.com Mon Sep 15 23:48:30 2008 From: spython01 at gmail.com (Samir Parikh) Date: Mon, 15 Sep 2008 17:48:30 -0400 Subject: [Tutor] Practice exercise sources In-Reply-To: <1c2a2c590809150404u3f49922eub45f282dba59122f@mail.gmail.com> References: <20080914201957.w5cr5j2mio8gs8ss@webmail4.isis.unc.edu> <1c2a2c590809150404u3f49922eub45f282dba59122f@mail.gmail.com> Message-ID: <50a597410809151448n6eb39213t7abdb94e2719369b@mail.gmail.com> I've also been trying to work my way through www.projecteuler.net. From alan.gauld at btinternet.com Tue Sep 16 02:42:21 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 16 Sep 2008 01:42:21 +0100 Subject: [Tutor] clearing lines for a 'front end' to a tool References: Message-ID: "James" wrote > I'm writing a 'front end' which will show a list of the "things" > that > are currently happening in the background in a simple > (non-interactive) interface. Here's an idea of what the terminal > will > look like when the program is running. The critical piece of missing info is which platform/OS we are dealing with. Anyy kind of terminal control is going to be platform dependant - which is why curses may not be overkill! (except it doesn't work well on Windows) > The question here is mostly about how to generate this output. The > bottom line (the 'status') *always* remains at the bottom of the This is where terminal control comes in and a lot depends on what terninal you are using. > I'm unsure how to go about doing this... I imagine that the ANSI > "clear line" value may be helpful That would work on Windows but most *nix consoles don't use the ANSI codes consistently, most will be haoppier with DEC VT control codes (or Tektronics or Wyse). Thats where curses helps by hiding all that stuff. If on *nix use curses or any of several other console UI libraries. On Windows use native ANSI codes and/or the Conio library. Several other options here: http://py.vaults.ca/parnassus/apyllo.py/808292924.243256747 Although many may be outdated now. Finally, this would be very easy to do in a Tkinter GUI. All you need is a containing frame, a text widget and a label and either a timer or a callback structure from your threads bto trigger updates. Probably easier than using a terninal interface! HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From pine508 at hotmail.com Tue Sep 16 03:09:31 2008 From: pine508 at hotmail.com (Che M) Date: Mon, 15 Sep 2008 21:09:31 -0400 Subject: [Tutor] problem with building dict w/ SQlite SELECTS in loop Message-ID: (struggling to make an informative subject line) Hi, I have what is no-doubt a dumb problem, but I can't get past it... Given a list of items, I want to loop through the list, use the item in a SELECT statement to query an SQLite database, and use the returned data from a .fetchall() to add key/value pairs to a dictionary. My problem is that it is only working for the *first* item in my list. Each successive item shows the result of the fetchall() to be nothing. And yet I know it matches the criteria in my SELECT statements, because I can a) see it in the database, and b) if I re-order my list, the first one in the list always returns something and the others don't, even if that first one didn't return something when it was not first in the list before. It's as if after the first iteration of the loop, the SELECTs are not working. I know .fetchall() "clears" the cursor, but I would think that on the next iteration it would hit a brand new SELECT query and re-stock the cursor. But I'm getting nothing returned. Here in the lines is my flawed loop (I want to get a list of codes and a list of dates): #--------------------------------------------------------------------------------------------------- for style in self.style_list: #Get the codes... cur.execute('SELECT code FROM Codes WHERE code != "" AND Style= "' + style + '" AND start >=' + '"' + self.start_datestring + '"' + 'AND start < "' + self.end_datestring + '"') mycodes = [ str(row[0]) for row in cur.fetchall() ] #Get the dates... cur.execute('SELECT start FROM codes WHERE code != "" AND Style= "' + style + '" AND start >=' + '"' + self.start_datestring + '"' + 'AND start < "' + self.end_datestring + '"') mydates = [ str(row[0]) for row in cur.fetchall() ] #Gets a list of the the dates these took place #Add the data to the dictionary... self.style_data_dict[style] = [mydates, mycodes] #--------------------------------------------------------------------------------------------------- However, if, instead of looping, I just copy and paste everything inside the loop two times (while providing as hard-coded the style at the start of each copy of it), it does return the data both times. (Of course, that won't work in the real program, but does show, again, the SELECT statements themselves are not flawed--I think.) So, can anyone tell me what I am doing wrong in the loop? I've stared at it too long and I am just not seeing it. Thank you, Che _________________________________________________________________ Stay up to date on your PC, the Web, and your mobile phone with Windows Live. http://clk.atdmt.com/MRT/go/msnnkwxp1020093185mrt/direct/01/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From john at fouhy.net Tue Sep 16 03:29:34 2008 From: john at fouhy.net (John Fouhy) Date: Tue, 16 Sep 2008 13:29:34 +1200 Subject: [Tutor] problem with building dict w/ SQlite SELECTS in loop In-Reply-To: References: Message-ID: <5e58f2e40809151829v58da444j23240f5943015f5a@mail.gmail.com> 2008/9/16 Che M : > for style in self.style_list: > > #Get the codes... > cur.execute('SELECT code FROM Codes WHERE code != "" AND Style= "' + > style + '" > AND start >=' + '"' + self.start_datestring + '"' + 'AND start < "' > + self.end_datestring + '"') > mycodes = [ str(row[0]) for row in cur.fetchall() ] > > #Get the dates... > cur.execute('SELECT start FROM codes WHERE code != "" AND Style= "' + > style + '" > AND start >=' + '"' + self.start_datestring + '"' + 'AND start < "' > + self.end_datestring + '"') > mydates = [ str(row[0]) for row in cur.fetchall() ] #Gets a list of the > the dates these took place Hi, I can't see any obvious reasons for your problems, I'm afraid, but I do have a comment on your SQL: the sqlite module supports using ? to indicate parameters. So you could rewrite your select statements as: cur.execute("select code from codes where code != '' and style = ? and start >= ? and start < ?", (style, self.start_datestring, self.end_datestring)) which is much easier to read, and also not vulnerable to SQL injection. Secondly, any reason why you aren't getting both code and start in a single select statement? i.e. cur.execute("select code, start from codes where code != '' and style = ? and start >= ? and start < ?", (style, self.start_datestring, self.end_datestring)) (heck, you could select code, start, style form codes -- pull all the information you need in a single query, and skip the loop altogether..) -- John. From phite2009 at yahoo.com Tue Sep 16 08:40:06 2008 From: phite2009 at yahoo.com (Phite Marano) Date: Mon, 15 Sep 2008 23:40:06 -0700 (PDT) Subject: [Tutor] mailing list Message-ID: <762032.55325.qm@web46207.mail.sp1.yahoo.com> hi please send me all tutorials -------------- next part -------------- An HTML attachment was scrubbed... URL: From onyxtic at gmail.com Tue Sep 16 09:46:04 2008 From: onyxtic at gmail.com (Evans) Date: Tue, 16 Sep 2008 08:46:04 +0100 Subject: [Tutor] mailing list References: <762032.55325.qm@web46207.mail.sp1.yahoo.com> Message-ID: <00f401c917d0$46224fe0$4101a8c0@compaq> Hi, if it's Python tutorial you're after, then start from here http://docs.python.org/tut/ or do a search for 'Python tutorial' on any search engine. Good luck! -- Evans ----- Original Message ----- From: Phite Marano To: tutor at python.org Sent: Tuesday, September 16, 2008 7:40 AM Subject: [Tutor] mailing list hi please send me all tutorials ------------------------------------------------------------------------------ _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at timgolden.me.uk Tue Sep 16 10:00:57 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 16 Sep 2008 09:00:57 +0100 Subject: [Tutor] problem with building dict w/ SQlite SELECTS in loop In-Reply-To: References: Message-ID: <48CF67B9.6050903@timgolden.me.uk> Che M wrote: > (struggling to make an informative subject line) [ struggling to understand exactly what the problem is... :) ] I'm quite willing to help on this, but it's just not quite clear enough what's happening. Can I suggest that you post a *really small, self-contained* example which demonstrates the problem you're having. You might actually realise what's wrong as you do that, or if not someone like me can just run the example and see what you mean and point things out. Your code is missing just too many things for me to work out which bit is doing what. (And it's a bit awkward because of the long lines). Try posting something like this: import sqlite3 db = sqlite3.connect (":memory:") db.execute ("CREATE TABLE codes (code)") db.executemany ("INSERT INTO codes VALUES (?)", [(i,) for i in range (10)]) q = db.cursor () for n_try in range (3): q.execute ("SELECT * FROM codes WHERE code > ?", [n_try]) q.fetchall () q.close () and say what you think should happen, and what does happen. Note that the entire code I've posted there can be dropped straight into an interpreter and run which makes it much easier for people who are willing to help to see what you're trying to do. TJG From alan.gauld at btinternet.com Tue Sep 16 10:44:44 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 16 Sep 2008 09:44:44 +0100 Subject: [Tutor] mailing list References: <762032.55325.qm@web46207.mail.sp1.yahoo.com> Message-ID: "Phite Marano" wrote > hi please send me all tutorials There are many Python tutorials on the web which you can find using any search engine or the links on the Python web site. The one that suits you bestwill depend on your own preferred style of learning. The tutor mailing list is here to answer any specific questions you might have while doing the tutorials. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From inthefridge at gmail.com Tue Sep 16 18:59:28 2008 From: inthefridge at gmail.com (Spencer Parker) Date: Tue, 16 Sep 2008 10:59:28 -0600 Subject: [Tutor] WMI Message-ID: Has anyone here had any experience with WMI extensions in Python? I am trying to remotely change the IP, Subnet, and gateway of a windows machine, but I cannot figure out what it needs to change this. -- Spencer Parker -------------- next part -------------- An HTML attachment was scrubbed... URL: From roadierich at googlemail.com Tue Sep 16 19:14:33 2008 From: roadierich at googlemail.com (Richard Lovely) Date: Tue, 16 Sep 2008 18:14:33 +0100 Subject: [Tutor] Creating a chat system Server Message-ID: Does anyone have any links and or know of any good libraries for writing chat servers similar to IRC? I'm looking to add chat facilities to a game I'm working on. Thanks. -- Richard "Roadie Rich" Lovely, part of the JNP|UK Famile www.theJNP.com From srilyk at gmail.com Tue Sep 16 20:29:51 2008 From: srilyk at gmail.com (W W) Date: Tue, 16 Sep 2008 13:29:51 -0500 Subject: [Tutor] Creating a chat system Server In-Reply-To: References: Message-ID: <333efb450809161129t46a43d77ka5bd82fd518733bd@mail.gmail.com> A lot of people referenced me to twisted whenever I asked about sockets/threading. HTH, Wayne On Tue, Sep 16, 2008 at 12:14 PM, Richard Lovely wrote: > Does anyone have any links and or know of any good libraries for > writing chat servers similar to IRC? I'm looking to add chat > facilities to a game I'm working on. > > Thanks. > -- > Richard "Roadie Rich" Lovely, part of the JNP|UK Famile > www.theJNP.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 -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at timgolden.me.uk Tue Sep 16 21:01:48 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 16 Sep 2008 20:01:48 +0100 Subject: [Tutor] WMI In-Reply-To: References: Message-ID: <48D0029C.5070302@timgolden.me.uk> Spencer Parker wrote: > Has anyone here had any experience with WMI extensions in Python? > > I am trying to remotely change the IP, Subnet, and gateway of a windows > machine, but I cannot figure out what it needs to change this. You'll need the Win32_NetworkAdapterConfiguration class and, for ease, the wmi module from here: http://timgolden.me.uk/python/wmi.html import wmi c = wmi.WMI () for i in c.Win32_NetworkAdapterConfiguration (IPEnabled=True): print i You'll need things like the .SetGateways method. You can see all the methods thus: print "\n".join (i.methods) and if you print any of them, it will show its signature: print i.SetGateways HTH TJG From inthefridge at gmail.com Tue Sep 16 21:36:18 2008 From: inthefridge at gmail.com (Spencer Parker) Date: Tue, 16 Sep 2008 13:36:18 -0600 Subject: [Tutor] WMI In-Reply-To: <48D0029C.5070302@timgolden.me.uk> References: <48D0029C.5070302@timgolden.me.uk> Message-ID: This is the code that I currently have: import wmi con =wmi.WMI() ip = "10.1.10.20" subnet = "255.255.255.0" gateway = "10.1.10.1" wql = "SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = TRUE" for adapter in con.query(wql): ReturnValue = adapter.EnableStatic(IPAddress=ip, SubnetMask=subnet) On Tue, Sep 16, 2008 at 1:01 PM, Tim Golden wrote: > Spencer Parker wrote: > >> Has anyone here had any experience with WMI extensions in Python? >> >> I am trying to remotely change the IP, Subnet, and gateway of a windows >> machine, but I cannot figure out what it needs to change this. >> > > You'll need the Win32_NetworkAdapterConfiguration class and, > for ease, the wmi module from here: > > http://timgolden.me.uk/python/wmi.html > > > import wmi > > c = wmi.WMI () > > for i in c.Win32_NetworkAdapterConfiguration (IPEnabled=True): > print i > > You'll need things like the .SetGateways method. You can see > all the methods thus: > > print "\n".join (i.methods) > > and if you print any of them, it will show its signature: > > print i.SetGateways > > > > > HTH > TJG > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Spencer Parker -------------- next part -------------- An HTML attachment was scrubbed... URL: From inthefridge at gmail.com Tue Sep 16 22:07:36 2008 From: inthefridge at gmail.com (Spencer Parker) Date: Tue, 16 Sep 2008 14:07:36 -0600 Subject: [Tutor] WMI In-Reply-To: References: <48D0029C.5070302@timgolden.me.uk> Message-ID: It does of course help to spell IPAddress correctly to get this to work in the first place. LOL. It is working...thanks again for the help and the wonderful module! On Tue, Sep 16, 2008 at 1:36 PM, Spencer Parker wrote: > This is the code that I currently have: > > import wmi > > con =wmi.WMI() > ip = "10.1.10.20" > subnet = "255.255.255.0" > gateway = "10.1.10.1" > > wql = "SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = > TRUE" > > for adapter in con.query(wql): > ReturnValue = adapter.EnableStatic(IPAddress=ip, SubnetMask=subnet) > > > On Tue, Sep 16, 2008 at 1:01 PM, Tim Golden wrote: > >> Spencer Parker wrote: >> >>> Has anyone here had any experience with WMI extensions in Python? >>> >>> I am trying to remotely change the IP, Subnet, and gateway of a windows >>> machine, but I cannot figure out what it needs to change this. >>> >> >> You'll need the Win32_NetworkAdapterConfiguration class and, >> for ease, the wmi module from here: >> >> http://timgolden.me.uk/python/wmi.html >> >> >> import wmi >> >> c = wmi.WMI () >> >> for i in c.Win32_NetworkAdapterConfiguration (IPEnabled=True): >> print i >> >> You'll need things like the .SetGateways method. You can see >> all the methods thus: >> >> print "\n".join (i.methods) >> >> and if you print any of them, it will show its signature: >> >> print i.SetGateways >> >> >> >> >> HTH >> TJG >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> > > > > -- > Spencer Parker > > -- Spencer Parker -------------- next part -------------- An HTML attachment was scrubbed... URL: From winfried at tilanus.com Tue Sep 16 22:26:41 2008 From: winfried at tilanus.com (Winfried Tilanus) Date: Tue, 16 Sep 2008 22:26:41 +0200 Subject: [Tutor] Creating a chat system Server In-Reply-To: <333efb450809161129t46a43d77ka5bd82fd518733bd@mail.gmail.com> References: <333efb450809161129t46a43d77ka5bd82fd518733bd@mail.gmail.com> Message-ID: <48D01681.9090606@tilanus.com> On 09/16/2008 W W wrote: Hi, > A lot of people referenced me to twisted whenever I asked about sockets/threading. You might want to use xmpp (the protocol of jabber). Twisted can speak that, but there are other options. It is a quite versatile protocol: beside 'just chatting', about anything that is real time over the net can be done with it. A list of python-jabebr libraries can be found at: http://www.jabber.org/web/Libraries#Python Winfried -- http://www.tilanus.com xmpp:winfried at jabber.xs4all.nl tel. 015-3613996 / 06-23303960 fax. 015-3614406 From pine508 at hotmail.com Tue Sep 16 22:43:42 2008 From: pine508 at hotmail.com (Che M) Date: Tue, 16 Sep 2008 16:43:42 -0400 Subject: [Tutor] problem with building dict w/ SQlite SELECTS in loop In-Reply-To: <48CF67B9.6050903@timgolden.me.uk> References: <48CF67B9.6050903@timgolden.me.uk> Message-ID: > I'm quite willing to help on this, but it's just not quite > clear enough what's happening. Can I suggest that you > post a *really small, self-contained* example which demonstrates > the problem you're having. You might actually realise what's > wrong as you do that, or if not someone like me can just run > the example and see what you mean and point things out. > Your code is missing just too many things for me > to work out which bit is doing what. (And it's a bit > awkward because of the long lines). > > Try posting something like this: > > > import sqlite3 > > db = sqlite3.connect (":memory:") > db.execute ("CREATE TABLE codes (code)") > db.executemany ("INSERT INTO codes VALUES (?)", [(i,) for i in range (10)]) > > q = db.cursor () > for n_try in range (3): > q.execute ("SELECT * FROM codes WHERE code > ?", [n_try]) > q.fetchall () > > q.close () > > > > > and say what you think should happen, and what does > happen. Note that the entire code I've posted there > can be dropped straight into an interpreter and run > which makes it much easier for people who are willing > to help to see what you're trying to do. > > TJG > I normally do try to include a small runnable sample, but in this case it seemed too extricated into the rest of my code. As it happens, as I was fooling around with variations of your code sample, it reinforced my feeling that nothing was wrong with my loop and SQL query as such, and it was then I noticed that it was the *list* that was wrong. When I built my list, I built it using a .split() from a textbox field of comma-separated words. But, I had written: self.style_list = swlf.style_value.split(',') when I should have written it as: self.style_list = swlf.style_value.split(', ') and that missing whitespace caused my list entries to each have one whitespace in front of all but the very first item in the list, and so of course they didn't match the words in the database. So that was the problem--I had been fixating on the SQL queries and it was an improper use of .split() earlier in the code. I have a feeling this isn't the first time someone has made this mistake. Thank you for your help, Che _________________________________________________________________ See how Windows connects the people, information, and fun that are part of your life. http://clk.atdmt.com/MRT/go/msnnkwxp1020093175mrt/direct/01/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at timgolden.me.uk Tue Sep 16 22:10:43 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 16 Sep 2008 21:10:43 +0100 Subject: [Tutor] WMI In-Reply-To: References: <48D0029C.5070302@timgolden.me.uk> Message-ID: <48D012C3.3020409@timgolden.me.uk> Spencer Parker wrote: > It does of course help to spell IPAddress correctly to get this to work > in the first place. LOL. It is working...thanks again for the help and > the wonderful module! Glad it was useful. Thanks for the update. TJG From mail at timgolden.me.uk Tue Sep 16 22:53:41 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 16 Sep 2008 21:53:41 +0100 Subject: [Tutor] problem with building dict w/ SQlite SELECTS in loop In-Reply-To: References: <48CF67B9.6050903@timgolden.me.uk> Message-ID: <48D01CD5.3000400@timgolden.me.uk> Che M wrote: [... snip solution around mis-handling a string split ...] Glad you solved it. Thanks for coming back with an update. Depending on your circs, you might want to try a more general solution to that problem, like: s = "This, is,a, string, with, varying, amounts, of,space" print [s.strip () for s in s.split (",")] TJG From mail at timgolden.me.uk Tue Sep 16 22:56:12 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 16 Sep 2008 21:56:12 +0100 Subject: [Tutor] problem with building dict w/ SQlite SELECTS in loop In-Reply-To: References: <48CF67B9.6050903@timgolden.me.uk> Message-ID: <48D01D6C.7080109@timgolden.me.uk> Che M wrote: [... snip solution around mis-handling a string split ...] Glad you solved it. Thanks for coming back with an update. Depending on your circs, you might want to try a more general solution to that problem, like: s = "This, is,a, string, with, varying, amounts, of,space" print [s.strip () for s in s.split (",")] TJG From pine508 at hotmail.com Tue Sep 16 23:06:45 2008 From: pine508 at hotmail.com (Che M) Date: Tue, 16 Sep 2008 17:06:45 -0400 Subject: [Tutor] problem with building dict w/ SQlite SELECTS in loop In-Reply-To: <5e58f2e40809151829v58da444j23240f5943015f5a@mail.gmail.com> References: <5e58f2e40809151829v58da444j23240f5943015f5a@mail.gmail.com> Message-ID: > I can't see any obvious reasons for your problems, I'm afraid, but I > do have a comment on your SQL: the sqlite module supports using ? to > indicate parameters. So you could rewrite your select statements as: > > cur.execute("select code from codes where code != '' and style = ? and > start >= ? and start < ?", (style, self.start_datestring, > self.end_datestring)) > > which is much easier to read, and also not vulnerable to SQL injection. I will definitely adopt that (and had previously in other cases...for some reason here I hadn't). Thanks. > Secondly, any reason why you aren't getting both code and start in a > single select statement? i.e. > > cur.execute("select code, start from codes where code != '' and style > = ? and start >= ? and start < ?", (style, self.start_datestring, > self.end_datestring)) The reason is merely lack of experience and because of how I was using the fetchall() in one list comprehension to build each list...since I did this twice, I thought I needed to restock the cursor, since each .fetchall() depletes the cursor. But of course, that's dumb--now I just get fetchall() once first and do two list comprehensions, like: fetched_data = cur.fetchall() mycodes = [ str(row[0] for row in fetched_data ] mystyles = [ str(row[1] for row in fetched_data ] Much better--thank you. > (heck, you could select code, start, style form codes -- pull all the > information you need in a single query, and skip the loop > altogether..) I think I need the loop because the style will be multiple styles and I need to take the codes that go with each style, so I am querying style by style, so to speak. Thanks, Che _________________________________________________________________ Stay up to date on your PC, the Web, and your mobile phone with Windows Live. http://clk.atdmt.com/MRT/go/msnnkwxp1020093185mrt/direct/01/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From john at fouhy.net Wed Sep 17 00:11:06 2008 From: john at fouhy.net (John Fouhy) Date: Wed, 17 Sep 2008 10:11:06 +1200 Subject: [Tutor] problem with building dict w/ SQlite SELECTS in loop In-Reply-To: References: <5e58f2e40809151829v58da444j23240f5943015f5a@mail.gmail.com> Message-ID: <5e58f2e40809161511n6393822ayb8b5ec82fc4068b8@mail.gmail.com> 2008/9/17 Che M : >> (heck, you could select code, start, style form codes -- pull all the >> information you need in a single query, and skip the loop >> altogether..) > I think I need the loop because the style will be multiple styles and > I need to take the codes that go with each style, so I am querying > style by style, so to speak. What I meant is that you could do this: cur.execute("select code, start, style from codes where code != '' and start > ? and start <= ?", #etc) results = cur.fetchall() self.style_data_dict = {} for code, start, style in results: self.style_data_dict.setdefault(style, []).append((code, start)) This will leave your data dict in a different form from the one in your original code.. but you could change it by: for style in self.style_data_dict: self.style_data_dict[style] = zip(*self.style_data_dict[style]) -- John. From alan.gauld at btinternet.com Wed Sep 17 01:30:20 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 17 Sep 2008 00:30:20 +0100 Subject: [Tutor] problem with building dict w/ SQlite SELECTS in loop References: <5e58f2e40809151829v58da444j23240f5943015f5a@mail.gmail.com> Message-ID: "Che M" wrote > The reason is merely lack of experience and because of how I was > using the fetchall() in one list comprehension to build each list... > > (heck, you could select code, start, style form codes -- pull all > > the > > information you need in a single query, and skip the loop > I think I need the loop because the style will be multiple styles > and > I need to take the codes that go with each style, so I am querying > style by style, so to speak. Check out the GROUP BY and ORDER BY clauses of a SELECT statement. I'm pretty sure you could select all the stuff you want using a combination of those two clauses. It should be much faster and lead to more maintainable code too. Something like: select code from codes where code != '' and style = ? and > start >= ? and start < ? SELECT code, start FROM codes WHERE code != "" AND start >= begin AND start < end GROUP BY style ORDER BY style HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From rkamisetty at paypal.com Wed Sep 17 10:04:34 2008 From: rkamisetty at paypal.com (Kamisetty, Rajendra) Date: Wed, 17 Sep 2008 01:04:34 -0700 Subject: [Tutor] How to parse InputFile to generate OutputFile? In-Reply-To: <48D0029C.5070302@timgolden.me.uk> References: <48D0029C.5070302@timgolden.me.uk> Message-ID: Hi, I am new to Python and need your help to generate an output file as explained below. I need to generate an output text file based on the input text file data which has fixed length format of 142 bytes each line. Input.txt contents: ('844 - Open File Message', '011 - System Trace Audit Number: 823301', '012 - Local Time: 033543', '013 - Local Date: 0821', '024 - Function Code: 861') ('844 - Open Service Message', '011 - System Trace Audit Number: 000003', '012 - Local Time: 033543', '013 - Local Date: 0821', '024 - Function Code: 865') ('345 - Remittance Open Message', '011 - System Trace Audit Number: 023301', '026 - Upload Control: 000001') ('146 - Message', '02 - Primary Account Number is: 6751469991140620','10 - System Trace Audit Number2: 369325', 'FF47 - Security of the Internet: ') ('146 - Message', '02 - Primary Account Number is: 6751469991140620 ','10 - System Trace Audit Number2: 369315', 'FF47 - Security of the Internet: ') ('146 - Message', '02 - Primary Account Number is: 40593529008395201432 ','10 - System Trace Audit Number2: 369385', 'FF47 - Security of the Internet: ') ('146 - Message', '02 - Primary Account Number is: 4059352900839520','10 - System Trace Audit Number2: 369365', 'FF47 - Security of the Internet: ') ('146 - Message', '02 - Primary Account Number is: 4059352900839520910','10 - System Trace Audit Number2: 369375', 'FF47 - Security of the Internet: ') ('844 Close Message', '011 - System Trace Audit Number: 000012', '024 - Function Code: 860', '07 - Year of the Purchase Transaction: 08') Output.txt contents: 11 00000000000030004 050908024536000674000000 13 23 0000000000003000400828000113105470509080245364247939 000000070824800000005090805008585147778978978050908050908 24 00000000000030004 050908024536424793900067514665529949730409080000000000000016 0000000000001600C092222257UXT 050908 24 00000000000030004 050908024536424793900051310150077578900409080000000000000018 0000000000001500C092222259XUZ 050908 24 00000000000030004 050908024536424793900067514665529949730409080000000000000016 0000000000001600C092222257URT 050908 24 00000000000030004 050908024536424793900051310150077578900409080000000000000018 0000000000001500C092222304YUC 050908 24 00000000000030004 050908024536424793900067514665529949730409080000000000000016 0000000000001600C092222257OUE 050908 55 00000000000030004 05090802453600067400000006 13 1. Parse the input file to get the value (bold) appears next to string "System Trace Audit Number2". 2. Replace the value (bold) with database equivalent eg. 369325=092222257UXT 3. Generate the output file as below where everything is constant except bold text which is databse equivalent of parsed value from input file. Thanks a lot for your help! Raj. -------------- next part -------------- An HTML attachment was scrubbed... URL: From inthefridge at gmail.com Wed Sep 17 17:55:05 2008 From: inthefridge at gmail.com (Spencer Parker) Date: Wed, 17 Sep 2008 09:55:05 -0600 Subject: [Tutor] WMI In-Reply-To: <48D012C3.3020409@timgolden.me.uk> References: <48D0029C.5070302@timgolden.me.uk> <48D012C3.3020409@timgolden.me.uk> Message-ID: Is there a way to create new users in WMI? I was trying to research this on MSDN, but couldn't find it anywhere... On Tue, Sep 16, 2008 at 2:10 PM, Tim Golden wrote: > Spencer Parker wrote: > >> It does of course help to spell IPAddress correctly to get this to work in >> the first place. LOL. It is working...thanks again for the help and the >> wonderful module! >> > > > Glad it was useful. Thanks for the update. > > > TJG > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Spencer Parker -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at timgolden.me.uk Wed Sep 17 18:05:52 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 17 Sep 2008 17:05:52 +0100 Subject: [Tutor] WMI In-Reply-To: References: <48D0029C.5070302@timgolden.me.uk> <48D012C3.3020409@timgolden.me.uk> Message-ID: <48D12AE0.6010206@timgolden.me.uk> Spencer Parker wrote: > Is there a way to create new users in WMI? I was trying to research > this on MSDN, but couldn't find it anywhere... Not possible as far as I know. Do you need a domain user or a local user? TJG From mail at timgolden.me.uk Wed Sep 17 18:13:25 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 17 Sep 2008 17:13:25 +0100 Subject: [Tutor] WMI In-Reply-To: References: <48D0029C.5070302@timgolden.me.uk> <48D012C3.3020409@timgolden.me.uk> <48D12AE0.6010206@timgolden.me.uk> Message-ID: <48D12CA5.80204@timgolden.me.uk> Spencer Parker wrote: > I just need to create a local user. [copying back to the list in case it helps others] See if this sets you on the way: http://timgolden.me.uk/python/win32_how_do_i/create-a-local-group-with-a-new-user.html TJG From optomatic at rogers.com Wed Sep 17 18:30:58 2008 From: optomatic at rogers.com (Patrick) Date: Wed, 17 Sep 2008 12:30:58 -0400 Subject: [Tutor] Shell scripting Message-ID: <48D130C2.9020600@rogers.com> I was just wondering if there was a way to return the results of a python script to the bash shell? I was thinking about using the output as an argumen for another shell command. I know that we can use the shell from within Python via the OS module but I believe this is usually used to feed input into the program. Here is a silly pseudo code example: bash command | some-python-script.py | some.other-script.sh thanks in advance-Patrick From inthefridge at gmail.com Wed Sep 17 18:31:50 2008 From: inthefridge at gmail.com (Spencer Parker) Date: Wed, 17 Sep 2008 10:31:50 -0600 Subject: [Tutor] WMI In-Reply-To: <48D12CA5.80204@timgolden.me.uk> References: <48D0029C.5070302@timgolden.me.uk> <48D012C3.3020409@timgolden.me.uk> <48D12AE0.6010206@timgolden.me.uk> <48D12CA5.80204@timgolden.me.uk> Message-ID: I meant to hit reply to all...stupid Gmail(not really...all on me...LOL) Is there a way to remotely trigger an event from Linus to a windows machine? I have basically a virtual machine that this script would run from. I need to find a way to trigger this event from a linux machine that handles all of our VM's. I can find ways of doing it from a windows to windows, but not linux to windows. Any clues? Thanks again for all of the help. On Wed, Sep 17, 2008 at 10:13 AM, Tim Golden wrote: > Spencer Parker wrote: > >> I just need to create a local user. >> > > [copying back to the list in case it helps others] > > See if this sets you on the way: > > > http://timgolden.me.uk/python/win32_how_do_i/create-a-local-group-with-a-new-user.html > > TJG > -- Spencer Parker -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at alchemy.com Wed Sep 17 18:34:55 2008 From: steve at alchemy.com (Steve Willoughby) Date: Wed, 17 Sep 2008 09:34:55 -0700 Subject: [Tutor] Shell scripting In-Reply-To: <48D130C2.9020600@rogers.com> References: <48D130C2.9020600@rogers.com> Message-ID: <20080917163455.GB42380@dragon.alchemy.com> On Wed, Sep 17, 2008 at 12:30:58PM -0400, Patrick wrote: > I was just wondering if there was a way to return the results of a > python script to the bash shell? I was thinking about using the output > as an argumen for another shell command. I know that we can use the > shell from within Python via the OS module but I believe this is usually > used to feed input into the program. Anything you print to the standard output stream (sys.stdout) will be piped on to the next command. This is true for any program executed from the shell. So just a plain "print" should do what you want. > > Here is a silly pseudo code example: > > bash command | some-python-script.py | some.other-script.sh > > thanks in advance-Patrick > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Steve Willoughby | Using billion-dollar satellites steve at alchemy.com | to hunt for Tupperware. From steve at alchemy.com Wed Sep 17 18:38:45 2008 From: steve at alchemy.com (Steve Willoughby) Date: Wed, 17 Sep 2008 09:38:45 -0700 Subject: [Tutor] WMI In-Reply-To: References: <48D0029C.5070302@timgolden.me.uk> <48D012C3.3020409@timgolden.me.uk> <48D12AE0.6010206@timgolden.me.uk> <48D12CA5.80204@timgolden.me.uk> Message-ID: <20080917163845.GC42380@dragon.alchemy.com> On Wed, Sep 17, 2008 at 10:31:50AM -0600, Spencer Parker wrote: > Is there a way to remotely trigger an event from Linus to a windows machine? > I have basically a virtual machine that this script would run from. I need > to find a way to trigger this event from a linux machine that handles all of > our VM's. I can find ways of doing it from a windows to windows, but not > linux to windows. Any clues? Depends on what you mean by triggering an event. Could you give a specific example of what you want to accomplish? Depending on what you're trying to do, this could be as simple as invoking an existing network RPC call or something, to as complicated as creating a web service on windows that the linux client(s) connect to. -- Steve Willoughby | Using billion-dollar satellites steve at alchemy.com | to hunt for Tupperware. From inthefridge at gmail.com Wed Sep 17 18:52:33 2008 From: inthefridge at gmail.com (Spencer Parker) Date: Wed, 17 Sep 2008 10:52:33 -0600 Subject: [Tutor] WMI In-Reply-To: <20080917163845.GC42380@dragon.alchemy.com> References: <48D012C3.3020409@timgolden.me.uk> <48D12AE0.6010206@timgolden.me.uk> <48D12CA5.80204@timgolden.me.uk> <20080917163845.GC42380@dragon.alchemy.com> Message-ID: What I am doing is this: We have a web interface where people can provision virtual machines. Currently we do this with Linux machines and it sets a unique IP, username, startup services, and a password. This is all triggered at startup of the linux machines with perl and an xml file. We are trying to replicate this with Windows. Setting the IP and creating the user's is pretty easy...and that code you sent me did basically everything with some tweaking. When someone goes to the web interface it triggers some Expect scripts that log into the linux xen machine and trigger the whole process. We have a windows VM now that will control the process for Windows VM's. On Wed, Sep 17, 2008 at 10:38 AM, Steve Willoughby wrote: > On Wed, Sep 17, 2008 at 10:31:50AM -0600, Spencer Parker wrote: > > Is there a way to remotely trigger an event from Linus to a windows > machine? > > I have basically a virtual machine that this script would run from. I > need > > to find a way to trigger this event from a linux machine that handles all > of > > our VM's. I can find ways of doing it from a windows to windows, but not > > linux to windows. Any clues? > > Depends on what you mean by triggering an event. Could you give a > specific example of what you want to accomplish? Depending on what > you're trying to do, this could be as simple as invoking an existing > network RPC call or something, to as complicated as creating a web > service on windows that the linux client(s) connect to. > > -- > Steve Willoughby | Using billion-dollar satellites > steve at alchemy.com | to hunt for Tupperware. > -- Spencer Parker -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at alchemy.com Wed Sep 17 19:20:55 2008 From: steve at alchemy.com (Steve Willoughby) Date: Wed, 17 Sep 2008 10:20:55 -0700 Subject: [Tutor] WMI In-Reply-To: References: <48D012C3.3020409@timgolden.me.uk> <48D12AE0.6010206@timgolden.me.uk> <48D12CA5.80204@timgolden.me.uk> <20080917163845.GC42380@dragon.alchemy.com> Message-ID: <20080917172055.GD42380@dragon.alchemy.com> On Wed, Sep 17, 2008 at 10:52:33AM -0600, Spencer Parker wrote: > We have a web interface where people can provision virtual machines. > Currently we do this with Linux machines and it sets a unique IP, username, > startup services, and a password. This is all triggered at startup of the > linux machines with perl and an xml file. We are trying to replicate this > with Windows. Setting the IP and creating the user's is pretty easy...and > that code you sent me did basically everything with some tweaking. When > someone goes to the web interface it triggers some Expect scripts that log > into the linux xen machine and trigger the whole process. We have a windows > VM now that will control the process for Windows VM's. SO... a user goes to the web interface and requests a new VM, which makes a script log in to a Linux master host and kicks off a remote job there to create a new VM instance, which, when it boots up, runs another script to complete the process? I just want to make sure I got that parsed correctly. You'd basically do the same thing on the Windows machine. If the process you're triggering is a simple command-line program (like a script, maybe?) you could use an RPC call or even something like SSH to run it from the Linux system. If it's something that can be easily invoked by an object method call in .net, you could make a very simple .net web service running on the windows master waiting to kick off the provisioning process. Your web interface could have a simple Linux-side Python script which would connect to the web service and request it to run. Be careful, though. What you're describing is fraught with security issues and vulnerabilities that need to be skillfully addressed. -- Steve Willoughby | Using billion-dollar satellites steve at alchemy.com | to hunt for Tupperware. From inthefridge at gmail.com Wed Sep 17 19:37:39 2008 From: inthefridge at gmail.com (Spencer Parker) Date: Wed, 17 Sep 2008 11:37:39 -0600 Subject: [Tutor] WMI In-Reply-To: <20080917172055.GD42380@dragon.alchemy.com> References: <48D012C3.3020409@timgolden.me.uk> <48D12AE0.6010206@timgolden.me.uk> <48D12CA5.80204@timgolden.me.uk> <20080917163845.GC42380@dragon.alchemy.com> <20080917172055.GD42380@dragon.alchemy.com> Message-ID: Yes...you do have it all correct. Luckily this is all behind a private network that is firewalled. There is no way to get to this network unless you are physically on site. Since there isn't even VPN access to this network currently. This was done for the security problems associated with random scripts running that do dangerous things like this. Most of this is done with SSH on the linux side...which I am going to stick with on the windows side. I setup and SSH server running on the windows controller. It is working for the most part now. Thanks again for all of the help... On Wed, Sep 17, 2008 at 11:20 AM, Steve Willoughby wrote: > On Wed, Sep 17, 2008 at 10:52:33AM -0600, Spencer Parker wrote: > > We have a web interface where people can provision virtual machines. > > Currently we do this with Linux machines and it sets a unique IP, > username, > > startup services, and a password. This is all triggered at startup of > the > > linux machines with perl and an xml file. We are trying to replicate > this > > with Windows. Setting the IP and creating the user's is pretty > easy...and > > that code you sent me did basically everything with some tweaking. When > > someone goes to the web interface it triggers some Expect scripts that > log > > into the linux xen machine and trigger the whole process. We have a > windows > > VM now that will control the process for Windows VM's. > > SO... a user goes to the web interface and requests a new VM, which makes a > script log in to a Linux master host and kicks off a remote job there to > create a new VM instance, which, when it boots up, runs another script to > complete the process? I just want to make sure I got that parsed > correctly. > > You'd basically do the same thing on the Windows machine. If the process > you're triggering is a simple command-line program (like a script, maybe?) > you could use an RPC call or even something like SSH to run it from the > Linux system. If it's something that can be easily invoked by an object > method call in .net, you could make a very simple .net web service running > on the windows master waiting to kick off the provisioning process. Your > web interface could have a simple Linux-side Python script which would > connect to the web service and request it to run. > > Be careful, though. What you're describing is fraught with security > issues and vulnerabilities that need to be skillfully addressed. > > > -- > Steve Willoughby | Using billion-dollar satellites > steve at alchemy.com | to hunt for Tupperware. > -- Spencer Parker -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at alchemy.com Wed Sep 17 19:47:20 2008 From: steve at alchemy.com (Steve Willoughby) Date: Wed, 17 Sep 2008 10:47:20 -0700 Subject: [Tutor] WMI In-Reply-To: References: <48D012C3.3020409@timgolden.me.uk> <48D12AE0.6010206@timgolden.me.uk> <48D12CA5.80204@timgolden.me.uk> <20080917163845.GC42380@dragon.alchemy.com> <20080917172055.GD42380@dragon.alchemy.com> Message-ID: <20080917174720.GE42380@dragon.alchemy.com> On Wed, Sep 17, 2008 at 11:37:39AM -0600, Spencer Parker wrote: > Yes...you do have it all correct. Luckily this is all behind a private > network that is firewalled. There is no way to get to this network unless > you are physically on site. Since there isn't even VPN access to this > network currently. This was done for the security problems associated with > random scripts running that do dangerous things like this. Most of this is > done with SSH on the linux side...which I am going to stick with on the > windows side. I setup and SSH server running on the windows controller. It > is working for the most part now. Unfortunately your most significant threat to system security usually comes from inside your firewall... disgruntled employees, or employees who compromise something by mistake, or by using a compromised PC (virus, anyone?) or a coding error or any of many other things. It's your system, but "I have a firewall" has been said by many people in the past who ended up learning a valuable, if painful, lesson in writing secure applications. From alan.gauld at btinternet.com Wed Sep 17 21:07:12 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 17 Sep 2008 20:07:12 +0100 Subject: [Tutor] Shell scripting References: <48D130C2.9020600@rogers.com> Message-ID: "Patrick" wrote >I was just wondering if there was a way to return the results of a > python script to the bash shell? > Here is a silly pseudo code example: > > bash command | some-python-script.py | some.other-script.sh That's called pipelining and uses standard input/output streams. ########## Untested! : echo.py ##### import sys for line in sys.stdin: sys.stdout.write(line) ######################### $ ls | python echo.py | wc -l Should give much the same result as $ ls | wc -l HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From cfuller084 at thinkingplanet.net Wed Sep 17 20:45:48 2008 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Wed, 17 Sep 2008 13:45:48 -0500 Subject: [Tutor] Shell scripting In-Reply-To: <48D130C2.9020600@rogers.com> References: <48D130C2.9020600@rogers.com> Message-ID: <200809171345.49816.cfuller084@thinkingplanet.net> If you want the return code, there are at least two ways to do it. My zsh shell is configured to print the last return code in the prompt: 0 % python Python 2.4.4 (#2, Apr 15 2008, 23:43:20) [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.exit(-1) 255 % python Python 2.4.4 (#2, Apr 15 2008, 23:43:20) [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> raise SystemExit(-1) 255 % note that you are limited to eight bit integers. To get some text, the usual backquote method for grabbing the output from a command to use in your script would work. You should consult a bash manual for that, I use it so infrequently that I have to relearn it every time :) Cheers On Wednesday 17 September 2008 11:30, Patrick wrote: > I was just wondering if there was a way to return the results of a > python script to the bash shell? I was thinking about using the output > as an argumen for another shell command. I know that we can use the > shell from within Python via the OS module but I believe this is usually > used to feed input into the program. > > Here is a silly pseudo code example: > > bash command | some-python-script.py | some.other-script.sh > > thanks in advance-Patrick > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From cfuller084 at thinkingplanet.net Wed Sep 17 21:08:25 2008 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Wed, 17 Sep 2008 14:08:25 -0500 Subject: [Tutor] Shell scripting In-Reply-To: <48D130C2.9020600@rogers.com> References: <48D130C2.9020600@rogers.com> Message-ID: <200809171408.26214.cfuller084@thinkingplanet.net> Here's a trivial example using backquotes. The tricky part is getting bash to use them in conditionals, variable assignments, and such. 0 % cat > /tmp/fie.py print "Fie!" [ctrl-d] 0 % cat > /tmp/echo.sh echo `python /tmp/fie.py` [ctrl-d] 0 % sh /tmp/echo.sh Fie! 0 % Cheers On Wednesday 17 September 2008 11:30, Patrick wrote: > I was just wondering if there was a way to return the results of a > python script to the bash shell? I was thinking about using the output > as an argumen for another shell command. I know that we can use the > shell from within Python via the OS module but I believe this is usually > used to feed input into the program. > > Here is a silly pseudo code example: > > bash command | some-python-script.py | some.other-script.sh > > thanks in advance-Patrick > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From sierra_mtnview at sbcglobal.net Wed Sep 17 21:30:20 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Wed, 17 Sep 2008 12:30:20 -0700 Subject: [Tutor] Sort Output Message-ID: <48D15ACC.3080809@sbcglobal.net> An HTML attachment was scrubbed... URL: From shulin.zhuang at gmail.com Wed Sep 17 21:39:54 2008 From: shulin.zhuang at gmail.com (Shulin Zhuang) Date: Wed, 17 Sep 2008 12:39:54 -0700 Subject: [Tutor] Sort Output In-Reply-To: <48D15ACC.3080809@sbcglobal.net> References: <48D15ACC.3080809@sbcglobal.net> Message-ID: <4f1a9e210809171239q6fac8a6cs82e8ff14b53c464b@mail.gmail.com> If you use sort(a), it will be ok. >>>a =[4,2,5,8] >>>b=a >>> sort(a) : array([2, 4, 5, 8]) >>> b [4, 2, 5, 8] >>> a [4, 2, 5, 8] On Wed, Sep 17, 2008 at 12:30 PM, Wayne Watson wrote: > I'm using Python 2.4 in Win XP. I was surprised to find the result below. > > >>> a =[4,2,5,8] > >>> b = a > >>> a.sort() > >>> a > [2, 4, 5, 8] > >>> b > [2, 4, 5, 8] > > b no longer has the same value as it began. Apparently to prevent sort from > making it the same I have to resort to copying b into a first? What is the > proper way to retain a variable with the original values of a? > -- > > Wayne Watson (Watson Adventures, Prop., Nevada City, CA) > > (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) > Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet "Though no one can go back and make a brand new start, > ANYONE can start from now and make a brand new end." > -- Anonymous > > Web Page: > > > _______________________________________________ > 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 Sep 17 21:39:57 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 17 Sep 2008 15:39:57 -0400 Subject: [Tutor] Sort Output In-Reply-To: <48D15ACC.3080809@sbcglobal.net> References: <48D15ACC.3080809@sbcglobal.net> Message-ID: <1c2a2c590809171239q73dcc5a6jaab77537b3d2daa1@mail.gmail.com> On Wed, Sep 17, 2008 at 3:30 PM, Wayne Watson wrote: > I'm using Python 2.4 in Win XP. I was surprised to find the result below. > >>>> a =[4,2,5,8] >>>> b = a >>>> a.sort() >>>> a > [2, 4, 5, 8] >>>> b > [2, 4, 5, 8] > > b no longer has the same value as it began. Apparently to prevent sort from > making it the same I have to resort to copying b into a first? What is the > proper way to retain a variable with the original values of a? Yes, you have to make a copy. This is as simple as b = list(a) In your original code, a and b refer to the same list. See http://personalpages.tds.net/~kent37/kk/00012.html http://effbot.org/zone/python-objects.htm Kent From malaclypse2 at gmail.com Wed Sep 17 21:40:16 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Wed, 17 Sep 2008 15:40:16 -0400 Subject: [Tutor] Sort Output In-Reply-To: <48D15ACC.3080809@sbcglobal.net> References: <48D15ACC.3080809@sbcglobal.net> Message-ID: <16651e80809171240s32701f50t857a26492935cc66@mail.gmail.com> On Wed, Sep 17, 2008 at 3:30 PM, Wayne Watson wrote: > I'm using Python 2.4 in Win XP. I was surprised to find the result below. > >>>> a =[4,2,5,8] >>>> b = a This binds the name "b" to the same object that "a" is bound to. >>>> a.sort() >>>> a > [2, 4, 5, 8] >>>> b > [2, 4, 5, 8] > > b no longer has the same value as it began. Apparently to prevent sort from > making it the same I have to resort to copying b into a first? What is the > proper way to retain a variable with the original values of a? Yes. If you want "a" and "b" to point to different lists, you'll need to copy the list that "a" is bound to. This is a really common thing to do, and python provides an easy way to do it: >>> a = [4, 2, 5, 8] >>> b = sorted(a) >>> print a [4, 2, 5, 8] >>> print b [2, 4, 5, 8] >>> -- Jerry From greg at thewhittiers.com Wed Sep 17 21:40:48 2008 From: greg at thewhittiers.com (greg whittier) Date: Wed, 17 Sep 2008 15:40:48 -0400 Subject: [Tutor] Sort Output In-Reply-To: <48D15ACC.3080809@sbcglobal.net> References: <48D15ACC.3080809@sbcglobal.net> Message-ID: On Wed, Sep 17, 2008 at 3:30 PM, Wayne Watson wrote: > I'm using Python 2.4 in Win XP. I was surprised to find the result below. > > >>> a =[4,2,5,8] > >>> b = a > >>> a.sort() > >>> a > [2, 4, 5, 8] > >>> b > [2, 4, 5, 8] > > b no longer has the same value as it began. Apparently to prevent sort from > making it the same I have to resort to copying b into a first? What is the > proper way to retain a variable with the original values of a? > You could use b = a[:]. -------------- next part -------------- An HTML attachment was scrubbed... URL: From shantanoo at gmail.com Wed Sep 17 21:41:36 2008 From: shantanoo at gmail.com (Shantanoo Mahajan) Date: Thu, 18 Sep 2008 01:11:36 +0530 Subject: [Tutor] Sort Output In-Reply-To: <48D15ACC.3080809@sbcglobal.net> References: <48D15ACC.3080809@sbcglobal.net> Message-ID: <71BF1CD6-4180-4B86-BB75-AFF7D9405EB5@gmail.com> Solution 1: >>> a=[2,3,1,4] >>> b=a[:] >>> a [2, 3, 1, 4] >>> b [2, 3, 1, 4] >>> a.sort() >>> a [1, 2, 3, 4] >>> b [2, 3, 1, 4] >>> Solution 2: >>> from copy import deepcopy >>> a=[2,1,3,4] >>> b=deepcopy(a) >>> a [2, 1, 3, 4] >>> b [2, 1, 3, 4] >>> a.sort() >>> a [1, 2, 3, 4] >>> b [2, 1, 3, 4] >>> HTH. regards, shantanoo On 18-Sep-08, at 1:00 AM, Wayne Watson wrote: > I'm using Python 2.4 in Win XP. I was surprised to find the result > below. > > >>> a =[4,2,5,8] > >>> b = a > >>> a.sort() > >>> a > [2, 4, 5, 8] > >>> b > [2, 4, 5, 8] > > b no longer has the same value as it began. Apparently to prevent > sort from making it the same I have to resort to copying b into a > first? What is the proper way to retain a variable with the original > values of a? > -- > Wayne Watson (Watson Adventures, Prop., Nevada City, CA) > > (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) > Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet > > "Though no one can go back and make a brand new start, > ANYONE can start from now and make a brand new end." > -- Anonymous > > Web Page: > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From jtp at nc.rr.com Wed Sep 17 23:02:48 2008 From: jtp at nc.rr.com (James) Date: Wed, 17 Sep 2008 17:02:48 -0400 Subject: [Tutor] clearing lines for a 'front end' to a tool In-Reply-To: References: Message-ID: Kent / Alan, Thanks for the responses. I'm not completely certain that urwid is appropriate for the program I'm writing, as it seems to be more of a framework for developing a text GUI application. (similar to curses?) The behavior of the program I'm writing is actually identical to that of an open source product. I asked the developers of the project where I could find the code that actually produced the output that I'm mimicking, and he pointed me to the correct portion of the open source code. Below is the class that generates the output. ----- class JobStatusDisplay(object): _bound_properties = ("curval", "failed", "running") _jobs_column_width = 48 # Don't update the display unless at least this much # time has passed, in units of seconds. _min_display_latency = 2 _default_term_codes = { 'cr' : '\r', 'el' : '\x1b[K', 'nel' : '\n', } _termcap_name_map = { 'carriage_return' : 'cr', 'clr_eol' : 'el', 'newline' : 'nel', } def __init__(self, out=sys.stdout, quiet=False): object.__setattr__(self, "out", out) object.__setattr__(self, "quiet", quiet) object.__setattr__(self, "maxval", 0) object.__setattr__(self, "merges", 0) object.__setattr__(self, "_changed", False) object.__setattr__(self, "_displayed", False) object.__setattr__(self, "_last_display_time", 0) self.reset() isatty = hasattr(out, "isatty") and out.isatty() object.__setattr__(self, "_isatty", isatty) if not isatty or not self._init_term(): term_codes = {} for k, capname in self._termcap_name_map.iteritems(): term_codes[k] = self._default_term_codes[capname] object.__setattr__(self, "_term_codes", term_codes) def _init_term(self): """ Initialize term control codes. @rtype: bool @returns: True if term codes were successfully initialized, False otherwise. """ term_type = os.environ.get("TERM", "vt100") tigetstr = None try: import curses try: curses.setupterm(term_type, self.out.fileno()) tigetstr = curses.tigetstr except curses.error: pass except ImportError: pass if tigetstr is None: return False term_codes = {} for k, capname in self._termcap_name_map.iteritems(): code = tigetstr(capname) if code is None: code = self._default_term_codes[capname] term_codes[k] = code object.__setattr__(self, "_term_codes", term_codes) return True def _format_msg(self, msg): return ">>> %s" % msg def _erase(self): self.out.write( self._term_codes['carriage_return'] + \ self._term_codes['clr_eol']) self._displayed = False def _display(self, line): self.out.write(line) self._displayed = True def _update(self, msg): out = self.out if not self._isatty: out.write(self._format_msg(msg) + self._term_codes['newline']) return if self._displayed: self._erase() self._display(self._format_msg(msg)) def displayMessage(self, msg): was_displayed = self._displayed if self._isatty and self._displayed: self._erase() self.out.write(self._format_msg(msg) + self._term_codes['newline']) self._displayed = False if was_displayed: self._changed = True self.display() def reset(self): self.maxval = 0 self.merges = 0 for name in self._bound_properties: object.__setattr__(self, name, 0) if self._displayed: self.out.write(self._term_codes['newline']) self._displayed = False def __setattr__(self, name, value): old_value = getattr(self, name) if value == old_value: return object.__setattr__(self, name, value) if name in self._bound_properties: self._property_change(name, old_value, value) def _property_change(self, name, old_value, new_value): self._changed = True self.display() def _load_avg_str(self, digits=2): try: avg = os.getloadavg() except OSError, e: return str(e) return ", ".join(fpformat.fix(x, digits) for x in avg) def _display_status(self): # Don't use len(self._completed_tasks) here since that also # can include uninstall tasks. curval_str = str(self.curval) maxval_str = str(self.maxval) running_str = str(self.running) failed_str = str(self.failed) load_avg_str = self._load_avg_str() color_output = StringIO.StringIO() plain_output = StringIO.StringIO() style_file = portage.output.ConsoleStyleFile(color_output) style_file.write_listener = plain_output style_writer = portage.output.StyleWriter(file=style_file, maxcol=9999) style_writer.style_listener = style_file.new_styles f = formatter.AbstractFormatter(style_writer) number_style = "INFORM" f.add_literal_data("Jobs: ") f.push_style(number_style) f.add_literal_data(curval_str) f.pop_style() f.add_literal_data(" of ") f.push_style(number_style) f.add_literal_data(maxval_str) f.pop_style() f.add_literal_data(" complete") if self.running: f.add_literal_data(", ") f.push_style(number_style) f.add_literal_data(running_str) f.pop_style() f.add_literal_data(" running") if self.failed: f.add_literal_data(", ") f.push_style(number_style) f.add_literal_data(failed_str) f.pop_style() f.add_literal_data(" failed") padding = self._jobs_column_width - len(plain_output.getvalue()) if padding > 0: f.add_literal_data(padding * " ") f.add_literal_data("Load avg: ") f.add_literal_data(load_avg_str) self._update(color_output.getvalue()) xtermTitle(" ".join(plain_output.getvalue().split())) ----- I don't see anything in the code that particularly "stands out" on how to go about generating the output that I'd like. I do see, however, that a curses object is being instantiated. I think I'm a bit in over my head this time. ;) I did look through some of the curses documentation on the web and I didn't see much on how to clear lines. I don't really want to set up a "text GUI" application (where there are windows and menus at the top); I just want more flexibility in outputting text to the console. btw, Alan, I'm using Linux. :) -j On Mon, Sep 15, 2008 at 8:42 PM, Alan Gauld wrote: > "James" wrote > >> I'm writing a 'front end' which will show a list of the "things" that >> are currently happening in the background in a simple >> (non-interactive) interface. Here's an idea of what the terminal will >> look like when the program is running. > > The critical piece of missing info is which platform/OS we > are dealing with. Anyy kind of terminal control is going to be > platform dependant - which is why curses may not be overkill! > (except it doesn't work well on Windows) > >> The question here is mostly about how to generate this output. The >> bottom line (the 'status') *always* remains at the bottom of the > > This is where terminal control comes in and a lot depends on > what terninal you are using. > >> I'm unsure how to go about doing this... I imagine that the ANSI >> "clear line" value may be helpful > > That would work on Windows but most *nix consoles don't use > the ANSI codes consistently, most will be haoppier with DEC VT > control codes (or Tektronics or Wyse). Thats where curses helps > by hiding all that stuff. > > If on *nix use curses or any of several other console UI libraries. > On Windows use native ANSI codes and/or the Conio library. > > Several other options here: > > http://py.vaults.ca/parnassus/apyllo.py/808292924.243256747 > > Although many may be outdated now. > > Finally, this would be very easy to do in a Tkinter GUI. > All you need is a containing frame, a text widget and a label and > either a timer or a callback structure from your threads bto trigger > updates. Probably easier than using a terninal interface! > > 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 rkamisetty at paypal.com Wed Sep 17 23:08:47 2008 From: rkamisetty at paypal.com (Kamisetty, Rajendra) Date: Wed, 17 Sep 2008 14:08:47 -0700 Subject: [Tutor] How to parse InputFile to generate OutputFile? In-Reply-To: References: <48D0029C.5070302@timgolden.me.uk> Message-ID: Hi, I am new to Python and need your help to generate an output file as explained below. I need to generate an output text file based on the input text file data . Input.txt contents: ('844 - Open File Message', '011 - System Trace Audit Number: 823301', '012 - Local Time: 033543', '013 - Local Date: 0821', '024 - Function Code: 861') ('844 - Open Service Message', '011 - System Trace Audit Number: 000003', '012 - Local Time: 033543', '013 - Local Date: 0821', '024 - Function Code: 865') ('345 - Remittance Open Message', '011 - System Trace Audit Number: 023301', '026 - Upload Control: 000001') ('146 - Message', '02 - Primary Account Number is: 6751469991140620','10 - System Trace Audit Number2: 369325', 'FF47 - Security of the Internet: ') ('146 - Message', '02 - Primary Account Number is: 6751469991140620 ','10 - System Trace Audit Number2: 369315', 'FF47 - Security of the Internet: ') ('146 - Message', '02 - Primary Account Number is: 40593529008395201432 ','10 - System Trace Audit Number2: 369385', 'FF47 - Security of the Internet: ') ('146 - Message', '02 - Primary Account Number is: 4059352900839520','10 - System Trace Audit Number2: 369365', 'FF47 - Security of the Internet: ') ('146 - Message', '02 - Primary Account Number is: 4059352900839520910','10 - System Trace Audit Number2: 369375', 'FF47 - Security of the Internet: ') ('844 Close Message', '011 - System Trace Audit Number: 000012', '024 - Function Code: 860', '07 - Year of the Purchase Transaction: 08') Output.txt contents: ( which has fixed length format of 142 bytes each line.) 11 00000000000030004 050908024536000674000000 13 23 0000000000003000400828000113105470509080245364247939 000000070824800000005090805008585147778978978050908050908 24 00000000000030004 050908024536424793900067514665529949730409080000000000000016 0000000000001600C092222257UXT 050908 24 00000000000030004 050908024536424793900051310150077578900409080000000000000018 0000000000001500C092222259XUZ 050908 24 00000000000030004 050908024536424793900067514665529949730409080000000000000016 0000000000001600C092222257URT 050908 24 00000000000030004 050908024536424793900051310150077578900409080000000000000018 0000000000001500C092222304YUC 050908 24 00000000000030004 050908024536424793900067514665529949730409080000000000000016 0000000000001600C092222257OUE 050908 55 00000000000030004 05090802453600067400000006 13 1. Parse the input file to get the value (bold) appears next to string "System Trace Audit Number2". 2. Replace the value (bold) with database equivalent eg. 369325=092222257UXT 3. Generate the output file as below where everything is constant except bold text which is databse equivalent of parsed value from input file. Appreciate your help, Raj. -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Thu Sep 18 00:09:13 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 17 Sep 2008 18:09:13 -0400 Subject: [Tutor] clearing lines for a 'front end' to a tool In-Reply-To: References: Message-ID: <1c2a2c590809171509n2bb498dw62018f38d6780d8f@mail.gmail.com> On Wed, Sep 17, 2008 at 5:02 PM, James wrote: > Kent / Alan, > > Thanks for the responses. I'm not completely certain that urwid is > appropriate for the program I'm writing, as it seems to be more of a > framework for developing a text GUI application. (similar to curses?) It takes less code to do what you want in urwid. You don't have to create menus. Here is an example that is I think close to what you want. It displays a header line, a scrolling log and a fixed status line. I have never used urwid before and I whipped this up in about 1/2 hour so don't take it as gospel. It seems well-behaved, even handles resizing the terminal window. Kent # Use urwid to display a scrolling log and a fixed status line import time import urwid.curses_display import urwid class ScrollingStatus(object): def __init__(self): # This contains the log items self.items = urwid.SimpleListWalker([]) self.listbox = urwid.ListBox(self.items) # A header line so we know how to quit... instruct = urwid.Text("Press Esc to exit.") header = urwid.AttrWrap( instruct, 'header' ) # The status line self.status_line = urwid.Text('Count = 0') # Wrap it all up in a Frame self.top = urwid.Frame(self.listbox, header, urwid.AttrWrap(self.status_line, 'status')) # This is our 'status' data self.count = 0 def main(self): self.ui = urwid.curses_display.Screen() self.ui.register_palette([ ('header', 'black', 'dark cyan', 'standout'), ('status', 'black', 'light gray', 'standout'), ]) self.ui.run_wrapper( self.run ) def run(self): size = self.ui.get_cols_rows() while True: self.draw_screen( size ) keys = self.ui.get_input() if "esc" in keys: break if "window resize" in keys: size = self.ui.get_cols_rows() # Add a log item self.items.append(urwid.Text('The time is %s' % time.asctime())) self.items.set_focus(self.items.get_focus()[1] + 1) # Update the status line self.count += 1 self.status_line.set_text('Count = %s' % self.count) time.sleep(1) def draw_screen(self, size): canvas = self.top.render( size, focus=True ) self.ui.draw_screen( size, canvas ) ScrollingStatus().main() From jtp at nc.rr.com Thu Sep 18 00:20:44 2008 From: jtp at nc.rr.com (James) Date: Wed, 17 Sep 2008 18:20:44 -0400 Subject: [Tutor] clearing lines for a 'front end' to a tool In-Reply-To: <1c2a2c590809171509n2bb498dw62018f38d6780d8f@mail.gmail.com> References: <1c2a2c590809171509n2bb498dw62018f38d6780d8f@mail.gmail.com> Message-ID: Kent, Thanks for the response. As a personal opinion, do you find it more appropriate to use something like curses (since it's already built into the standard Python library), or to use something "third party" like urwid? This program will be distributed to lots of individuals that will likely not have urwid installed right off the bat. I find the Python curses documentation to be...lacking at best. ;) Thus the only benefit I see to curses over urwid is that it is already "built-in" to Python. -j On Wed, Sep 17, 2008 at 6:09 PM, Kent Johnson wrote: > On Wed, Sep 17, 2008 at 5:02 PM, James wrote: >> Kent / Alan, >> >> Thanks for the responses. I'm not completely certain that urwid is >> appropriate for the program I'm writing, as it seems to be more of a >> framework for developing a text GUI application. (similar to curses?) > > It takes less code to do what you want in urwid. You don't have to > create menus. Here is an example that is I think close to what you > want. It displays a header line, a scrolling log and a fixed status > line. I have never used urwid before and I whipped this up in about > 1/2 hour so don't take it as gospel. It seems well-behaved, even > handles resizing the terminal window. > > Kent > > # Use urwid to display a scrolling log and a fixed status line > > import time > import urwid.curses_display > import urwid > > class ScrollingStatus(object): > def __init__(self): > # This contains the log items > self.items = urwid.SimpleListWalker([]) > self.listbox = urwid.ListBox(self.items) > > # A header line so we know how to quit... > instruct = urwid.Text("Press Esc to exit.") > header = urwid.AttrWrap( instruct, 'header' ) > > # The status line > self.status_line = urwid.Text('Count = 0') > > # Wrap it all up in a Frame > self.top = urwid.Frame(self.listbox, header, > urwid.AttrWrap(self.status_line, 'status')) > > # This is our 'status' data > self.count = 0 > > def main(self): > self.ui = urwid.curses_display.Screen() > self.ui.register_palette([ > ('header', 'black', 'dark cyan', 'standout'), > ('status', 'black', 'light gray', 'standout'), > ]) > self.ui.run_wrapper( self.run ) > > def run(self): > size = self.ui.get_cols_rows() > > while True: > self.draw_screen( size ) > > keys = self.ui.get_input() > if "esc" in keys: > break > > if "window resize" in keys: > size = self.ui.get_cols_rows() > > # Add a log item > self.items.append(urwid.Text('The time is %s' % time.asctime())) > self.items.set_focus(self.items.get_focus()[1] + 1) > > # Update the status line > self.count += 1 > self.status_line.set_text('Count = %s' % self.count) > > time.sleep(1) > > def draw_screen(self, size): > canvas = self.top.render( size, focus=True ) > self.ui.draw_screen( size, canvas ) > > ScrollingStatus().main() > -- "Do not meddle in the affairs of wizards, for they are subtle and quick to anger." -Tolkien From srilyk at gmail.com Thu Sep 18 00:51:46 2008 From: srilyk at gmail.com (W W) Date: Wed, 17 Sep 2008 17:51:46 -0500 Subject: [Tutor] clearing lines for a 'front end' to a tool In-Reply-To: References: <1c2a2c590809171509n2bb498dw62018f38d6780d8f@mail.gmail.com> Message-ID: <333efb450809171551j21cb9277pcd7655ddffbf7764@mail.gmail.com> On Wed, Sep 17, 2008 at 5:20 PM, James wrote: > Kent, > > Thanks for the response. As a personal opinion, do you find it more > appropriate to use something like curses (since it's already built > into the standard Python library), or to use something "third party" > like urwid? > > This program will be distributed to lots of individuals that will > likely not have urwid installed right off the bat. > > I find the Python curses documentation to be...lacking at best. ;) > Thus the only benefit I see to curses over urwid is that it is already > "built-in" to Python. Well, assuming they are all running this on linux, then that's probably a fair concern. If they're not going to be running it on linux they'll have problems either way. I had at one point found a pretty decent seeming curses tutorial, and as far as I can tell it should be fairly trivial to create what you want using only curses. http://heather.cs.ucdavis.edu/~matloff/Python/PyCurses.pdf actually, IIRC, I downloaded some windows version of curses and ps ax since I happened to be on a windows box at the time, and it worked pretty swell. When I asked for help learning curses, most people said "Why bother? Just learn urwid". But I'm a stubborn sort and like to re-invent the wheel, as it were. Mainly because I'm currently in school and have nothing "better" to do with my time ;) Still, curses is fairly straightforward (at least so far as I've learned it), and you probably wouldn't spend much more time learning/writing a curses program than learning/writing an urwid program to do what you want. Unless you just adapt Kent's code. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Sep 18 02:27:40 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 18 Sep 2008 01:27:40 +0100 Subject: [Tutor] clearing lines for a 'front end' to a tool References: <1c2a2c590809171509n2bb498dw62018f38d6780d8f@mail.gmail.com> Message-ID: "James" wrote > Thanks for the response. As a personal opinion, do you find it more > appropriate to use something like curses (since it's already built > into the standard Python library), or to use something "third party" > like urwid? urwid is just a wrapper around curses. curses is the standard for doing text mode interfaces that go beyond simple printing of lines. Its not difficult to learn basic curses, it is slightly different to a GUI but not so very different. And there are loads of online tutorials and examples and even an O'Reilly book you can buy. Translating a C curses tuttor to Python is pretty self evident since most curses programs consist of sequences of curses calls with very little else. Those curses calls are identical in Python. > This program will be distributed to lots of individuals that will > likely not have urwid installed right off the bat. If they are on *nix they will have curses installed. If they are on Windows they almost certainly won't! > I find the Python curses documentation to be...lacking at best. ;) It assumes you know curses basics. Try here: http://tldp.org/HOWTO/NCURSES-Programming-HOWTO/index.html for a fairly comprehensive course. > Thus the only benefit I see to curses over urwid is that it is > already > "built-in" to Python. And just about every other programming language around. Its the lowest common denominator, very much like Tk is a common GUI framework, learn it in Tkinter and you can very quickly program GUIs in Ruby, Perl, C, etc... Similarly with curses, if you learn it you can code a text UI in virtually any popular language. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Thu Sep 18 02:35:18 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 18 Sep 2008 01:35:18 +0100 Subject: [Tutor] How to parse InputFile to generate OutputFile? References: <48D0029C.5070302@timgolden.me.uk> Message-ID: "Kamisetty, Rajendra" wrote > I am new to Python and need your help It will help if you start a new thread by posting a new message rather than replying to an existing one and changing the subject. Those of us with threaded readers don;t see your post because it is hidden inside the original thread! > I need to generate an output text file based on the input text file > data > Input.txt contents: > ('844 - Open File Message', > '011 - System Trace Audit Number: 823301', > '012 - Local Time: 033543', > '013 - Local Date: 0821', > '024 - Function > Code: 861') > etc/... > Output.txt contents: > ( which has fixed length format of 142 bytes each line.) > 11 00000000000030004 050908024536000674000000 > 13 > > 23 0000000000003000400828000113105470509080245364247939 > 000000070824800000005090805008585147778978978050908050908 I'm strugglibng to see the correlation here. The second line does not look like the same length as the first - unless the first is full of spaces? > 1. Parse the input file to get the value (bold) appears next to > string > "System Trace Audit Number2". > 2. Replace the value (bold) with database equivalent eg. > 369325=092222257UXT > 3. Generate the output file as below where everything is constant > except > bold text which is databse equivalent of parsed value from input > file. Tell us which step puzzles you and why. We wilol try to help. At the moment we can't tell what exactly you need help with? -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Thu Sep 18 02:43:23 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 18 Sep 2008 01:43:23 +0100 Subject: [Tutor] Sort Output References: <48D15ACC.3080809@sbcglobal.net> Message-ID: "Wayne Watson" wrote > I was surprised to find the result below. Well done, you just found one of the standard beginners gotchas! >>>> a =[4,2,5,8] >>>> b = a This makes b refer to the *same list* as a. >>>> a.sort() This sorts the list contents in-place >>>> a > [2, 4, 5, 8] As shown. >>>> b > [2, 4, 5, 8] And since b refers to the same luist as a it also reflects the rearrangement of the contents. > b no longer has the same value as it began. Actually it does. It refers to exactly the same list as a before and after the sort. The list object has not changed only the contents of the list were sorrted. > Apparently to prevent sort from making it the same > I have to resort to copying b into a first? No you need to take a copy of a when you assign it to b b = a[:] will result in b referring to a copy of a. Now if you change a's list nothing will happen to b's copy Remember that in Python variables are just names that refer to objects. Many names can refer to the same object. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Thu Sep 18 03:22:54 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 17 Sep 2008 21:22:54 -0400 Subject: [Tutor] How to parse InputFile to generate OutputFile? In-Reply-To: References: <48D0029C.5070302@timgolden.me.uk> Message-ID: <1c2a2c590809171822n23f4b685jfa8d7fd3acb4b844@mail.gmail.com> On Wed, Sep 17, 2008 at 5:08 PM, Kamisetty, Rajendra wrote: > Hi, > I am new to Python and need your help to generate an output file as > explained below. > > I need to generate an output text file based on the input text file data . > > Input.txt contents: > ('146 - Message', '02 - Primary Account Number is: 6751469991140620','10 - > System Trace Audit Number2: 369325', 'FF47 - Security of the Internet: ') > 1. Parse the input file to get the value (bold) appears next to string > "System Trace Audit Number2". If that is really all you need then a regular expression search could do it. If you need more data from the input then some sort of parser might be the easiest solution, perhaps using pyparsing. http://pyparsing.wikispaces.com/ > 2. Replace the value (bold) with database equivalent eg. 369325=092222257UXT The DB-API specification tells generally how to interface to a database. Some specifics depend on the particular database. http://www.python.org/dev/peps/pep-0249/ > 3. Generate the output file as below where everything is constant except > bold text which is databse equivalent of parsed value from input file. The output doesn't look very constant to me. If you can show what you have tried and tell us where you are stuck we can better help you. Kent From joefazee at gmail.com Wed Sep 17 14:26:06 2008 From: joefazee at gmail.com (A. Joseph) Date: Wed, 17 Sep 2008 05:26:06 -0700 Subject: [Tutor] recursive using the os.walk(path) from the os module Message-ID: Hi, I want to search through a directory and re-arrange all the files into e.g All .doc files go into MS WORD folder, all .pdf files goes into PDF Folder. I`m thinking of doing something with the os.walk(path) method from os module, I need some ideal how the algorithm should look like, maybe recursive ..any deal? Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Thu Sep 18 03:37:38 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 17 Sep 2008 21:37:38 -0400 Subject: [Tutor] clearing lines for a 'front end' to a tool In-Reply-To: References: <1c2a2c590809171509n2bb498dw62018f38d6780d8f@mail.gmail.com> Message-ID: <1c2a2c590809171837v45f97202j633237e27875d8fd@mail.gmail.com> On Wed, Sep 17, 2008 at 6:20 PM, James wrote: > Kent, > > Thanks for the response. As a personal opinion, do you find it more > appropriate to use something like curses (since it's already built > into the standard Python library), or to use something "third party" > like urwid? I don't have any problem using mature third-party software. > This program will be distributed to lots of individuals that will > likely not have urwid installed right off the bat. I don't know how much of a problem this will be for you. I installed urwid with easy_install, it's also available with apt-get or as a tarball that you install with setup.py. It does have a compiled piece so you can't just include it with the rest of your app. You may be able to integrate it with a setup.py for your app. I am new to curses and urwid but at a quick look urwid seems much easier to use... Kent From hansd at g2microsystems.com Thu Sep 18 04:14:27 2008 From: hansd at g2microsystems.com (Hans Dushanthakumar) Date: Thu, 18 Sep 2008 12:14:27 +1000 Subject: [Tutor] command history in a console In-Reply-To: <1c2a2c590809171837v45f97202j633237e27875d8fd@mail.gmail.com> References: <1c2a2c590809171509n2bb498dw62018f38d6780d8f@mail.gmail.com> <1c2a2c590809171837v45f97202j633237e27875d8fd@mail.gmail.com> Message-ID: <48D1B983.5070005@g2microsystems.com> G'day everyone. I'm experimenting with a custom console application, and trying to add command history functionality to it. It seems to basically work ok except for the fact that when I press the Up arrow key to run previous commands, the right commands are not displayed. It displays a wierd "^[[A" for each Up arrow key that I press. Inspite of this, when I hit enter, it DOES seem to run the right command. Heres a bit of code (stripped down to the bare essentials to demonstrate just this problem) that shows this behaviour: ------X Code starts here import readline import select import sys import os historyPath = ".pyhistory.test" if os.path.exists(historyPath): readline.read_history_file(historyPath) inputs = [sys.stdin] #More on this later. while 1: in_ready, out_ready, ex_ready = select.select(inputs, [], [], 10) #More on this later. x= raw_input() print "You entered: ", x ----X End of code Heres what an example run of the program looks like, with my comments: hansd at zilla:~/tools$ python test_history1.py ls <--------------------------------------Me: I entered "ls" here. So, this is the 1st command. ls You entered: ls 1 <---------------------------------------Me: 2nd command "1" 1 You entered: 1 2 <---------------------------------------Me: 3rd command "2" 2 You entered: 2 ^[[A^[[A <--------------------------Me: This is the strange characters. I pressed the Up key twice here. 1 You entered: 1 <----------------Me: So it looks like it received the right command from history :"1". So, my question is, why does it not display the right command from history instead of those "^[[A" characters? It works fine if I comment out the line "in_ready, out_ready, ex_ready = select.select(inputs, [], [], 10)". But there is a reason why I need this to be there..I'm expecting input from more sources than just the keyboard. Thanks, Hans From alan.gauld at btinternet.com Thu Sep 18 09:50:58 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 18 Sep 2008 08:50:58 +0100 Subject: [Tutor] recursive using the os.walk(path) from the os module References: Message-ID: "A. Joseph" wrote > I want to search through a directory and re-arrange all the files > into e.g > > All .doc files go into MS WORD folder, all .pdf files goes into PDF > Folder. > > I`m thinking of doing something with the os.walk(path) method from > os Which aspect is puzzling you? The use of os walk to traverse the folders? Or the algorithm to put the files into new folders? In either case you might get the answer in my Using the OS topic in my tutorial. Otherwise try posting a bit more detail on what you need. Thanks, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From iannaconec at optonline.net Thu Sep 18 12:14:54 2008 From: iannaconec at optonline.net (iannaconec at optonline.net) Date: Thu, 18 Sep 2008 10:14:54 +0000 (GMT) Subject: [Tutor] Miles Per Gallon Calculator` Message-ID: When = raw_input ( " please enter a number " ) = int? () is run as part of a python script It should take in the user stored input and store it as an integer. Am I correct. The string represented by in memory is now represented by 5 for example?If this is correct why do I get an error regarding the division of two strings if i type print " < variable> " / < variable> -------------- next part -------------- An HTML attachment was scrubbed... URL: From roadierich at googlemail.com Thu Sep 18 12:17:20 2008 From: roadierich at googlemail.com (Richard Lovely) Date: Thu, 18 Sep 2008 11:17:20 +0100 Subject: [Tutor] recursive using the os.walk(path) from the os module Message-ID: The way I'd do it is create a dict mapping extensions to folders (something like {'doc': 'word', 'pdf': 'acrobat'} ), then use os.renames(old, new), which works the same as moving when you give it a different path for new, and also magically handles creating new directories for you. The documentation for the os.walk() contains an example that could easily be modified to do what you want. The documentation is your friend. > Message: 8 > Date: Thu, 18 Sep 2008 08:50:58 +0100 > From: "Alan Gauld" > Subject: Re: [Tutor] recursive using the os.walk(path) from the os > module > To: tutor at python.org > Message-ID: > Content-Type: text/plain; format=flowed; charset="iso-8859-1"; > reply-type=original > > > "A. Joseph" wrote > >> I want to search through a directory and re-arrange all the files >> into e.g >> >> All .doc files go into MS WORD folder, all .pdf files goes into PDF >> Folder. >> >> I`m thinking of doing something with the os.walk(path) method from >> os > > Which aspect is puzzling you? The use of os walk to traverse the > folders? Or the algorithm to put the files into new folders? > > In either case you might get the answer in my Using the OS topic in > my tutorial. > > Otherwise try posting a bit more detail on what you need. > > Thanks, > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > > > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > End of Tutor Digest, Vol 55, Issue 56 > ************************************* > -- Richard "Roadie Rich" Lovely, part of the JNP|UK Famile www.theJNP.com From srilyk at gmail.com Thu Sep 18 12:51:26 2008 From: srilyk at gmail.com (W W) Date: Thu, 18 Sep 2008 05:51:26 -0500 Subject: [Tutor] Miles Per Gallon Calculator` In-Reply-To: References: Message-ID: <333efb450809180351v16d29f4cj35e9ae363e6d1fdb@mail.gmail.com> On Thu, Sep 18, 2008 at 5:14 AM, wrote: > When = raw_input ( " please enter a number " ) > = int () is run as part of a python script It should > take in the user stored input and store it as an integer. Am I correct. The > string represented by in memory is now represented by 5 for > example? > If this is correct why do I get an error regarding the division of two > strings if i type print " < variable> " / < variable> well if you have something like this: miles = int("5") gallons = 1 print "miles"/gallon the " " around miles turns miles into a string. And you just can't do that. Here's a proper example of an mpg calculator: def mpg(): miles = int( raw_input("Miles driven: ")) gallons = int( raw_input("Gallons used: ")) print "Your Miles Per Gallon: ", miles/gallons although converting them to float would allow you a little more accuracy in your measurements. But if you're just looking at whole number values, that should be fine. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Thu Sep 18 13:03:11 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 18 Sep 2008 07:03:11 -0400 Subject: [Tutor] Miles Per Gallon Calculator` In-Reply-To: References: Message-ID: <1c2a2c590809180403r691ae27cqa8de1944a80ba66f@mail.gmail.com> On Thu, Sep 18, 2008 at 6:14 AM, wrote: > When = raw_input ( " please enter a number " ) > = int () is run as part of a python script It should > take in the user stored input and store it as an integer. Am I correct. The > string represented by in memory is now represented by 5 for > example? Yes > If this is correct why do I get an error regarding the division of two > strings if i type print " < variable> " / < variable> Because " " is a string and you are dividing it by an integer. For example: In [2]: value = 5 In [3]: "value" / value --------------------------------------------------------------------------- TypeError Traceback (most recent call last) /Users/kent/Documents/Python/Tutor/ in () TypeError: unsupported operand type(s) for /: 'str' and 'int' What did you expect to print? Why did you use the / in the print statement? Kent From srilyk at gmail.com Thu Sep 18 13:05:06 2008 From: srilyk at gmail.com (W W) Date: Thu, 18 Sep 2008 06:05:06 -0500 Subject: [Tutor] command history in a console In-Reply-To: <48D1B983.5070005@g2microsystems.com> References: <1c2a2c590809171509n2bb498dw62018f38d6780d8f@mail.gmail.com> <1c2a2c590809171837v45f97202j633237e27875d8fd@mail.gmail.com> <48D1B983.5070005@g2microsystems.com> Message-ID: <333efb450809180405m651a531chdb3f12700bd31738@mail.gmail.com> On Wed, Sep 17, 2008 at 9:14 PM, Hans Dushanthakumar < hansd at g2microsystems.com> wrote: > G'day everyone. > > I'm experimenting with a custom console application, and trying to add > command history functionality to it. It seems to basically work ok except > for the fact that when I press the Up arrow key to run previous commands, > the right commands are not displayed. It displays a wierd "^[[A" for each Up > arrow key that I press. Inspite of this, when I hit enter, it DOES seem to > run the right command. > > Heres a bit of code (stripped down to the bare essentials to demonstrate > just this problem) that shows this behaviour: > > ------X Code starts here > > import readline > import select > import sys > import os > > historyPath = ".pyhistory.test" > > if os.path.exists(historyPath): > readline.read_history_file(historyPath) > > inputs = [sys.stdin] #More on this later. > > while 1: > in_ready, out_ready, ex_ready = select.select(inputs, [], [], 10) #More > on this later. > x= raw_input() > print "You entered: ", x > > ----X End of code > > Heres what an example run of the program looks like, with my comments: > > hansd at zilla:~/tools$ python test_history1.py > ls <--------------------------------------Me: I entered "ls" here. So, this > is the 1st command. > ls > You entered: ls > 1 <---------------------------------------Me: 2nd command "1" > 1 > You entered: 1 > 2 <---------------------------------------Me: 3rd command "2" > 2 > You entered: 2 > ^[[A^[[A <--------------------------Me: This is the strange characters. I > pressed the Up key twice here. > 1 > You entered: 1 <----------------Me: So it looks like it received the right > command from history :"1". > > > So, my question is, why does it not display the right command from history > instead of those "^[[A" characters? > > It works fine if I comment out the line "in_ready, out_ready, ex_ready = > select.select(inputs, [], [], 10)". But there is a reason why I need this to > be there..I'm expecting input from more sources than just the keyboard. As far as I know... ^[[A is a control character; in this case it refers to the up-arrow keypress. I'm not sure what the select module docs mention, but I'd bet your answer is there. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Thu Sep 18 17:23:52 2008 From: bgailer at gmail.com (bob gailer) Date: Thu, 18 Sep 2008 11:23:52 -0400 Subject: [Tutor] Miles Per Gallon Calculator` In-Reply-To: References: Message-ID: <48D27288.8000208@gmail.com> iannaconec at optonline.net wrote: > When = raw_input ( " please enter a number " ) > = int () is run as part of a python script It > should take in the user stored input and store it as an integer. Am I > correct. The string represented by in memory is now > represented by 5 for example? > If this is correct why do I get an error regarding the division of two > strings if i type print " < variable> " / < variable> Please make life easier for all of us by posting real code and real error messages. For example: >>> a = "cat" >>> b = 1 >>> print a/b Traceback (most recent call last): File "", line 1, in TypeError: unsupported operand type(s) for /: 'str' and 'int' -- Bob Gailer Chapel Hill NC 919-636-4239 When we take the time to be aware of our feelings and needs we have more satisfying interatctions with others. Nonviolent Communication provides tools for this awareness. As a coach and trainer I can assist you in learning this process. What is YOUR biggest relationship challenge? From gslindstrom at gmail.com Thu Sep 18 19:56:24 2008 From: gslindstrom at gmail.com (Greg Lindstrom) Date: Thu, 18 Sep 2008 12:56:24 -0500 Subject: [Tutor] PyCon 2009 (US) - Call for Tutorials Message-ID: *Pycon 2009 (US) ? Call for Tutorials* The period for submitting tutorial proposals for Pycon 2009 (US) is now open and will continue through Friday, October 31th. This year features two "pre-conference" days devoted to tutorials on Wednesday March 25 & Thursday March 26 in Chicago. This allows for more classes than ever. Tutorials are 3-hours long on a specific topic of your choice. Last year we featured classes on Learning Python, Web Development, Scientific Computing, and many more. Class size varied from 10 to over 60 students. The extended time spent in class allows teachers to cover a lot of material while allowing for interaction with students. The full Call for Tutorial Proposals, including submission details, an example proposal as well as a template, is available at < http://us.pycon.org/2009/tutorials/proposals/>. Tutorial selections will be announced in early December to give you time to prepare your class. PyCon will compensate instructors US$1,500 per tutorial. If you have any questions, please contact pycon-tutorials at python.org. Greg Lindstrom Tutorial Coordinator, PyCon 2009 -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeremiah.jester at panasonic.aero Fri Sep 19 00:12:30 2008 From: jeremiah.jester at panasonic.aero (jeremiah) Date: Thu, 18 Sep 2008 15:12:30 -0700 Subject: [Tutor] not operator Message-ID: <1221775950.9630.7.camel@jeremiah-laptop> i want to check if a dir does not exist. how do i change this statement to evaluate is NOT existing? ==False or ! operator. Also, is sys.exit appropriate to use to quit out of the program? if(os.access(target_dir, os.F_OK)): print "File does not exist!" sys.exit Disclaimer: The information contained in this transmission, including any attachments, may contain confidential information of Panasonic Avionics Corporation. This transmission is intended only for the use of the addressee(s) listed above. Unauthorized review, dissemination or other use of the information contained in this transmission is strictly prohibited. If you have received this transmission in error or have reason to believe you are not authorized to receive it, please notify the sender by return email and promptly delete the transmission. From alan.gauld at btinternet.com Fri Sep 19 01:11:34 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 19 Sep 2008 00:11:34 +0100 Subject: [Tutor] not operator References: <1221775950.9630.7.camel@jeremiah-laptop> Message-ID: "jeremiah" wrote >i want to check if a dir does not exist. how do i change this >statement > to evaluate is NOT existing? ==False or ! operator. Also, is > sys.exit > appropriate to use to quit out of the program? > > if(os.access(target_dir, os.F_OK)): > print "File does not exist!" > sys.exit if not os.access(target_dir, os.F_OK): print "File does not exist!" sys.exit Should work. Although you claim a file does not exist but seem to be testing a directory?! Also did you see the os.path.exists() function? You might find that useful. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld > > > > Disclaimer: The information contained in this transmission, > including any > attachments, may contain confidential information of Panasonic > Avionics > Corporation. This transmission is intended only for the use of the > addressee(s) listed above. Unauthorized review, dissemination or > other use > of the information contained in this transmission is strictly > prohibited. > If you have received this transmission in error or have reason to > believe > you are not authorized to receive it, please notify the sender by > return > email and promptly delete the transmission. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From christopher.henk at allisontransmission.com Fri Sep 19 01:19:29 2008 From: christopher.henk at allisontransmission.com (christopher.henk at allisontransmission.com) Date: Thu, 18 Sep 2008 19:19:29 -0400 Subject: [Tutor] not operator In-Reply-To: <1221775950.9630.7.camel@jeremiah-laptop> Message-ID: jeremiah.jester at panasonic.aero wrote on 09/18/2008 06:12:30 PM: > i want to check if a dir does not exist. how do i change this statement > to evaluate is NOT existing? ==False or ! operator. Also, is sys.exit > appropriate to use to quit out of the program? > > if(os.access(target_dir, os.F_OK)): > print "File does not exist!" > sys.exit > os.access(target_dir, os.F_OK) is going to return False if the directory does not exist so take your pick how you want to check it. if not os.access(target_dir, os.F_OK): or if os.access(target_dir, os.F_OK)==False: or if os.access(target_dir, os.F_OK)!=True: I like the first one, others like the second. the below doesn't work in python >>> if !(os.access(target_dir, os.F_OK)): SyntaxError: invalid syntax sys.exit is fine as long as you call it. sys.exit() you left off the () in your sample code, and I wasn't sure if that was a typo or not. Python will not raise an error. Chris -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at alchemy.com Fri Sep 19 01:22:33 2008 From: steve at alchemy.com (Steve Willoughby) Date: Thu, 18 Sep 2008 16:22:33 -0700 Subject: [Tutor] not operator In-Reply-To: References: <1221775950.9630.7.camel@jeremiah-laptop> Message-ID: <20080918232233.GA34754@dragon.alchemy.com> On Thu, Sep 18, 2008 at 07:19:29PM -0400, christopher.henk at allisontransmission.com wrote: > if not os.access(target_dir, os.F_OK): > if os.access(target_dir, os.F_OK)==False: > if os.access(target_dir, os.F_OK)!=True: IMHO it's generally bad form to use numeric == or != operators to compare values against True, False, and None. I'd really strongly encourage the first form. Your mileage may vary, of course. -- Steve Willoughby | Using billion-dollar satellites steve at alchemy.com | to hunt for Tupperware. From sierra_mtnview at sbcglobal.net Fri Sep 19 02:38:02 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Thu, 18 Sep 2008 17:38:02 -0700 Subject: [Tutor] deltatime difficulty Message-ID: <48D2F46A.1060504@sbcglobal.net> An HTML attachment was scrubbed... URL: From greg at thewhittiers.com Fri Sep 19 02:49:33 2008 From: greg at thewhittiers.com (greg whittier) Date: Thu, 18 Sep 2008 20:49:33 -0400 Subject: [Tutor] deltatime difficulty In-Reply-To: <48D2F46A.1060504@sbcglobal.net> References: <48D2F46A.1060504@sbcglobal.net> Message-ID: On Thu, Sep 18, 2008 at 8:38 PM, Wayne Watson wrote: > What's the problem here. It seems right to me. line 9 is diff =... > > import time > from datetime import datetime > > You've imported the datetime class from the datetime module. > > def adjust_ftime(afilename, sec): > # Vyyyymmdd_hhmmss+tag, seconds in, new yyyymmdd_hhmmss out > ts = afilename[1:-7] # use time stamp portion > format = '%Y%m%d_%H%M%S' > d = datetime(*(time.strptime(ts, format)[0:6])) > print "sec: ", sec, type(d) > diff = datetime.timedelta(seconds = sec) > > As the output below tells you, the datetime class doesn't have a "timedelta" method. This is a variation on the same confusion between the datetime module and the datetime.datetime class you've posted before. You could fix this above by doing "from datetime import datetime, timedelta" and then doing diff = timedelta(seconds = sec) or be more explicit as use "import datetime" and then reference datetime.datetime and datetime.timedelta. (Another alternative is "import datetime as dt" and then dt.datetime and dt.timedelta.) ... > > Results: > sec: 33 > Traceback (most recent call last): > File > "C:/Sandia_Meteors/Improved_Sentinel/Sentinel_Playground/Utility_Dev/junk.py", > line 14, in ? > adjust_ftime('v20080120_000020.xx.dat', 33) > File > "C:/Sandia_Meteors/Improved_Sentinel/Sentinel_Playground/Utility_Dev/junk.py", > line 9, in adjust_ftime > diff = datetime.timedelta(seconds = sec) > AttributeError: type object 'datetime.datetime' has no attribute > 'timedelta' > Hope this helps, Greg -------------- next part -------------- An HTML attachment was scrubbed... URL: From dfjennings at gmail.com Fri Sep 19 02:54:04 2008 From: dfjennings at gmail.com (Don Jennings) Date: Thu, 18 Sep 2008 20:54:04 -0400 Subject: [Tutor] deltatime difficulty In-Reply-To: <48D2F46A.1060504@sbcglobal.net> References: <48D2F46A.1060504@sbcglobal.net> Message-ID: <22ce67f0809181754o70cf8ebeq8e38ec576c53f630@mail.gmail.com> On 9/18/08, Wayne Watson wrote: > What's the problem here. It seems right to me. line 9 is diff =... >> >> import time >> from datetime import datetime >> def adjust_ftime(afilename, sec): >> # Vyyyymmdd_hhmmss+tag, seconds in, new yyyymmdd_hhmmss out >> ts = afilename[1:-7] # use time stamp portion >> format = '%Y%m%d_%H%M%S' >> d = datetime(*(time.strptime(ts, format)[0:6])) >> print "sec: ", sec, type(d) >> diff = datetime.timedelta(seconds = sec) >> print type(diff) >> d = d + diff >> return d.strftime(format) >> >> adjust_ftime('v20080120_000020.xx.dat', 33) > > > Results: > sec: 33 > Traceback (most recent call last): > File > "C:/Sandia_Meteors/Improved_Sentinel/Sentinel_Playground/Utility_Dev/junk.py", > line 14, in ? > adjust_ftime('v20080120_000020.xx.dat', 33) > File > "C:/Sandia_Meteors/Improved_Sentinel/Sentinel_Playground/Utility_Dev/junk.py", > line 9, in adjust_ftime > diff = datetime.timedelta(seconds = sec) > AttributeError: type object 'datetime.datetime' has no attribute 'timedelta' > Wayne, You only imported datetime from the datetime module. If you want to use timedelta, you'll need to import that, too. Then your line 9 becomes: diff = timedelta(seconds = sec) Take care, Don From sierra_mtnview at sbcglobal.net Fri Sep 19 03:01:39 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Thu, 18 Sep 2008 18:01:39 -0700 Subject: [Tutor] deltatime difficulty In-Reply-To: References: <48D2F46A.1060504@sbcglobal.net> Message-ID: <48D2F9F3.9030003@sbcglobal.net> An HTML attachment was scrubbed... URL: From kent37 at tds.net Fri Sep 19 05:54:33 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 18 Sep 2008 23:54:33 -0400 Subject: [Tutor] deltatime difficulty In-Reply-To: <48D2F9F3.9030003@sbcglobal.net> References: <48D2F46A.1060504@sbcglobal.net> <48D2F9F3.9030003@sbcglobal.net> Message-ID: <1c2a2c590809182054sd76a29cp3f4bf64b7eff98f1@mail.gmail.com> On Thu, Sep 18, 2008 at 9:01 PM, Wayne Watson wrote: > Well, that works. Thanks. How do I know what modules (?) or methods are in > datetime? >From the docs: http://docs.python.org/lib/node78.html or ask: In [4]: import datetime In [5]: dir(datetime) Out[5]: ['MAXYEAR', 'MINYEAR', '__doc__', '__file__', '__name__', '__package__', 'date', 'datetime', 'datetime_CAPI', 'time', 'timedelta', 'tzinfo'] Kent From sierra_mtnview at sbcglobal.net Fri Sep 19 06:29:28 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Thu, 18 Sep 2008 21:29:28 -0700 Subject: [Tutor] deltatime difficulty In-Reply-To: <48D30CC5.4000905@mwalsh.org> References: <48D2F46A.1060504@sbcglobal.net> <48D2F9F3.9030003@sbcglobal.net> <48D30CC5.4000905@mwalsh.org> Message-ID: <48D32AA8.8070105@sbcglobal.net> An HTML attachment was scrubbed... URL: From spmcinerney at hotmail.com Fri Sep 19 11:26:27 2008 From: spmcinerney at hotmail.com (Stephen McInerney) Date: Fri, 19 Sep 2008 02:26:27 -0700 Subject: [Tutor] How to print complex numbers without enclosing parentheses Message-ID: Why does the complex.__str__() method on complex numbers add the enclosing parentheses? It's unwanted, and it also makes them look like a tuple (other than the trailing comma). How can I get rid of it, other than the clunky: >>> print d(0.80-0.58j)>>> print repr(d)[1:-1]0.80-0.58j How can I change complex.__str__() ? Thanks, Stephen _________________________________________________________________ Get more out of the Web. Learn 10 hidden secrets of Windows Live. http://windowslive.com/connect/post/jamiethomson.spaces.live.com-Blog-cns!550F681DAD532637!5295.entry?ocid=TXT_TAGLM_WL_domore_092008 -------------- next part -------------- An HTML attachment was scrubbed... URL: From spmcinerney at hotmail.com Fri Sep 19 11:49:31 2008 From: spmcinerney at hotmail.com (Stephen McInerney) Date: Fri, 19 Sep 2008 02:49:31 -0700 Subject: [Tutor] Help reproing IDLE bug 3841? esp. on Windows Vista, XP Message-ID: Could anyone help reproing this minor IDLE bug?http://bugs.python.org/issue3841I found it on Windows Vista with Python 2.5 / IDLE 1.2.2. Other people have reported it does NOT occur with either: Win XP / Python 2.5 / Idle 1.2 Mac OS X 10.5.4 / Python 2.5.2 / IDLE 1.2.2 Can anyone repro it on Vista on 2.5? Vista on 2.6? Please let me know if you can/cannot repro on a combination of each of these:OS: Windows XP (SP2?), Windows Vista (SP1?), LinuxPython version: 2.5, 2.6, 2.7, 3.0IDLE versions: ? Copy-and-paste the testcase, view it inside IDLE and see what if the issue occurs.Should only take 1 minute. Thanks in advance,Stephen _________________________________________________________________ See how Windows connects the people, information, and fun that are part of your life. http://clk.atdmt.com/MRT/go/msnnkwxp1020093175mrt/direct/01/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From spmcinerney at hotmail.com Fri Sep 19 11:43:52 2008 From: spmcinerney at hotmail.com (Stephen McInerney) Date: Fri, 19 Sep 2008 02:43:52 -0700 Subject: [Tutor] Operators on complex numbers, and applying real to a list of real and complex numbers Message-ID: Two questions about complex numbers: a) why are methods __add__,__mul__ defined but not the operators '+','-','*','/' ? How can I bind the methods to the obvious operators (without creating a custom subclass of complex?) It seems pretty weird writing a.__add__(b) b) Say I have a list ll which mixes real (float) and complex numbers. ll = [1, 0.80-0.58j, 0.11+.2j] What is the best Python idiom for getting the list of real parts of elements of ll? [lx.real for lx in ll] fails because only complex numbers have a 'real' attribute, real numbers don't (slightly bizarre). Unless I write the not-so-readable: [(type(lx) is complex and lx.real or lx) for lx in ll] or define my own function. Do any of you see a need for a math.real() (or math.complex()) function, which operates on all numeric types? Then I could simply take the list comprehension [real(lx) for lx in ll] Is this worthy of a PEP? It seems simple but overlooked. Regards, Stephen _________________________________________________________________ See how Windows connects the people, information, and fun that are part of your life. http://clk.atdmt.com/MRT/go/msnnkwxp1020093175mrt/direct/01/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From ptmcg at austin.rr.com Fri Sep 19 11:49:54 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Fri, 19 Sep 2008 04:49:54 -0500 Subject: [Tutor] not operator In-Reply-To: References: Message-ID: <221D8BE2DAF440A5B25305B0C41CFC08@AWA2> >>> the below doesn't work in python >>> >>> if !(os.access(target_dir, os.F_OK)): >>> SyntaxError: invalid syntax What is that '!'? doing there? A left-handed factorial? I'm just kidding, I know that '!' is a common 'not' operator in many other programming languages. But this is Python, man! The not operator is 'not'. if not os.access(target_dir, os.F_OK): is perfectly legit Python. And I concur with Steve Willoughby's note on omitting '== True' and '== False' - the 'if' and 'while' statements are perfectly aware that their purpose is to evaluate the boolean-ness of a condition expression. Not only is '== True' in 'if blah == True:' redundant and unnecessary clutter*, it defeats some of Python's language idioms in which strings and containers (lists, dict, sets, and tuples) have an implicit boolean value indicating False if they are empty and True if non-empty. Here is an inefficient way to empty a list: listvar = range(10) while listvar: print len(listvar) listvar.pop() But change it to: while listvar == True: and the loop wont run even once - listvar is not equal to True, and never will be. To my mind, '== True' is a crutch for bad naming. Functions that return a boolean should be named 'is_blah' or 'is_foo' so that it is clear they are testing and returning the blahness or fooishness of their object. For example, let's imagine that we've written a Configuration class that has a number of properties that, when set independently, may get the class into an inconsistent state - maybe not the greatest design, but sometimes this can't be helped. So we add to our class a validation member function to return a boolean to indicate if the instance is valid or not. If we call the method 'validate', we are tempted to write: if config.validate() == True: because validate, being a transitive verb, tells us we are going to do something to config, but since 'validate' is not a name that clearly asserts a truth or falsity, we aren't exactly sure what validate is going to return for valid vs. invalid configs (I could envision a function named 'validate' could return a list of validation errors, for example). A better name here is 'is_valid', so that the '== True' can just be dropped, and the code reads clearly as: if config.is_valid(): -- Paul * yes, I know this phrase is itself multiply redundant - sometimes I just crack myself up. From d.conca at gmail.com Fri Sep 19 12:05:39 2008 From: d.conca at gmail.com (Daniele) Date: Fri, 19 Sep 2008 12:05:39 +0200 Subject: [Tutor] Name Generator Message-ID: <537341c70809190305x24439932mef5ccd7de60e5b71@mail.gmail.com> Hi list, I'd like to implement a Name Generator based on a grammar ( http://en.wikipedia.org/wiki/Context-free_grammar). Are there any standard modules that automatically generate words based on a grammar? thanks for help, Daniele -------------- next part -------------- An HTML attachment was scrubbed... URL: From srilyk at gmail.com Fri Sep 19 12:34:21 2008 From: srilyk at gmail.com (W W) Date: Fri, 19 Sep 2008 05:34:21 -0500 Subject: [Tutor] not operator In-Reply-To: <221D8BE2DAF440A5B25305B0C41CFC08@AWA2> References: <221D8BE2DAF440A5B25305B0C41CFC08@AWA2> Message-ID: <333efb450809190334n3920f71du25d1ecccb7b0db1c@mail.gmail.com> On Fri, Sep 19, 2008 at 4:49 AM, Paul McGuire wrote: > because validate, being a transitive verb, tells us we are going to do > something to config, but since 'validate' is not a name that clearly > asserts > a truth or falsity, we aren't exactly sure what validate is going to return > for valid vs. invalid configs (I could envision a function named 'validate' > could return a list of validation errors, for example). A better name here > is 'is_valid', so that the '== True' can just be dropped, and the code > reads > clearly as: > > if config.is_valid(): > > > -- Paul > > * yes, I know this phrase is itself multiply redundant - sometimes I just > crack myself up. Actually, I tend to work this same way myself (though I'm currently taking C++ at school, since they don't offer any serious python classes *tear*) - when I'm sorting an array in C++ (of course in python this is simply a method) I create a boolean value called "sorted" and give it the value False. If you were to translate my code to python it would look a bit like this: sorted = False while not sorted: swap values if swaps <= 0: sorted = True Which makes it read a lot more naturally. The same for validating input. In python you could write: valid_input = False while not valid_input: my_input = raw_input("Enter something: ") if my_input in ('my', 'criteria'): valid_input = True It's worked for me so far ;) HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From srilyk at gmail.com Fri Sep 19 12:46:16 2008 From: srilyk at gmail.com (W W) Date: Fri, 19 Sep 2008 05:46:16 -0500 Subject: [Tutor] How to print complex numbers without enclosing parentheses In-Reply-To: References: Message-ID: <333efb450809190346p57cd0b20o804260aab54a7bbf@mail.gmail.com> On Fri, Sep 19, 2008 at 4:26 AM, Stephen McInerney wrote: > > Why does the complex.__str__() method on complex numbers add the enclosing > parentheses? > It's unwanted, and it also makes them look like a tuple (other than the > trailing comma). > How can I get rid of it, other than the clunky: > > >>> print d > (0.80-0.58j) > >>> print repr(d)[1:-1] > 0.80-0.58j > > How can I change complex.__str__() ? > >>> def printComp(comp): ... comp = str(comp) ... comp = comp.strip(')') ... comp = comp.strip('(') ... print comp ... >>> printComp(d) 0.8-0.58j That's the best I could come up with... HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Fri Sep 19 13:11:22 2008 From: bgailer at gmail.com (bob gailer) Date: Fri, 19 Sep 2008 07:11:22 -0400 Subject: [Tutor] How to print complex numbers without enclosing parentheses In-Reply-To: References: Message-ID: <48D388DA.7000803@gmail.com> An HTML attachment was scrubbed... URL: From bgailer at gmail.com Fri Sep 19 13:20:44 2008 From: bgailer at gmail.com (bob gailer) Date: Fri, 19 Sep 2008 07:20:44 -0400 Subject: [Tutor] Operators on complex numbers, and applying real to a list of real and complex numbers In-Reply-To: References: Message-ID: <48D38B0C.202@gmail.com> An HTML attachment was scrubbed... URL: From kent37 at tds.net Fri Sep 19 13:34:40 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 19 Sep 2008 07:34:40 -0400 Subject: [Tutor] Operators on complex numbers, and applying real to a list of real and complex numbers In-Reply-To: References: Message-ID: <1c2a2c590809190434x775b328dncda0aa4901ed14f7@mail.gmail.com> On Fri, Sep 19, 2008 at 5:43 AM, Stephen McInerney wrote: > Two questions about complex numbers: > > a) why are methods __add__,__mul__ defined but not the > operators '+','-','*','/' ? This is true of all the numeric types. The method that implements + for a type is called __add__. Similarly * is implemented by __mul__. There are many more "special" methods that implement not only numeric operations but also things like indexing and iteration. A complete list of methods for numeric types is here: http://docs.python.org/ref/numeric-types.html > How can I bind the methods to the obvious operators (without creating a > custom > subclass of complex?) It seems pretty weird writing a.__add__(b) No need, this is done by the Python runtime. It converts a+b into a.__add__(b). (More or less...it could also end up as b.__radd__(a) or raise TypeError.) > b) Say I have a list ll which mixes real (float) and complex numbers. > ll = [1, 0.80-0.58j, 0.11+.2j] > What is the best Python idiom for getting the list of real parts of elements > of ll? > [lx.real for lx in ll] fails because only complex numbers have a 'real' > attribute, real numbers don't (slightly bizarre). > Unless I write the not-so-readable: > [(type(lx) is complex and lx.real or lx) for lx in ll] > or define my own function. You could also use getattr(lx, 'real', lx) if you prefer. > Do any of you see a need for a math.real() (or math.complex()) > function, which operates on all numeric types? > Then I could simply take the list comprehension > [real(lx) for lx in ll] > Is this worthy of a PEP? > It seems simple but overlooked. I guess someone agrees with you, at least in spirit...In Python 2.6 and 3.0, numeric types are in a hierarchy and integers and floats are also complex: In [13]: (5).real Out[13]: 5 In [18]: (5).imag Out[18]: 0 (The parentheses are needed to avoid a syntax error.) Also In [20]: import numbers In [21]: isinstance(5, numbers.Complex) Out[21]: True In [22]: isinstance(5.0, numbers.Complex) Out[22]: True From srilyk at gmail.com Fri Sep 19 13:47:10 2008 From: srilyk at gmail.com (W W) Date: Fri, 19 Sep 2008 06:47:10 -0500 Subject: [Tutor] Help reproing IDLE bug 3841? esp. on Windows Vista, XP In-Reply-To: References: Message-ID: <333efb450809190447j2faa8b92i40b87301ad80449e@mail.gmail.com> Well, I know it doesn't repro with python 2.5 on ubuntu 8.04. -Wayne On Fri, Sep 19, 2008 at 4:49 AM, Stephen McInerney wrote: > Could anyone help reproing this minor IDLE bug? > http://bugs.python.org/issue3841 > I found it on Windows Vista with Python 2.5 / IDLE 1.2.2. > Other people have reported it does NOT occur with either: > Win XP / Python 2.5 / Idle 1.2 > Mac OS X 10.5.4 / Python 2.5.2 / IDLE 1.2.2 > Can anyone repro it on Vista on 2.5? Vista on 2.6? > Please let me know if you can/cannot repro on a combination of each > of these: > OS: Windows XP (SP2?), Windows Vista (SP1?), Linux > Python version: 2.5, 2.6, 2.7, 3.0 > IDLE versions: ? > > Copy-and-paste the testcase, view it inside IDLE and see what if the issue > occurs. > Should only take 1 minute. > > Thanks in advance, > Stephen > > ------------------------------ > See how Windows connects the people, information, and fun that are part of > your life. See Now > > _______________________________________________ > 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 kent37 at tds.net Fri Sep 19 13:49:17 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 19 Sep 2008 07:49:17 -0400 Subject: [Tutor] Operators on complex numbers, and applying real to a list of real and complex numbers In-Reply-To: <48D38B0C.202@gmail.com> References: <48D38B0C.202@gmail.com> Message-ID: <1c2a2c590809190449s7d7b21bby13d70cbb58f582c2@mail.gmail.com> On Fri, Sep 19, 2008 at 7:20 AM, bob gailer wrote: > FWIW I'd like to see all numbers have real and imag attributes. Your wish has been granted in Python 2.6. Kent From dsarmientos at gmail.com Fri Sep 19 15:29:16 2008 From: dsarmientos at gmail.com (Daniel Sarmiento) Date: Fri, 19 Sep 2008 08:29:16 -0500 Subject: [Tutor] Name Generator Message-ID: Try taking a look at nltk: http://nltk.org > Date: Fri, 19 Sep 2008 12:05:39 +0200 > From: Daniele > Subject: [Tutor] Name Generator > To: tutor at python.org > Message-ID: > <537341c70809190305x24439932mef5ccd7de60e5b71 at mail.gmail.com> > Content-Type: text/plain; charset="utf-8" > > Hi list, > I'd like to implement a Name Generator based on a grammar ( > http://en.wikipedia.org/wiki/Context-free_grammar). Are there any standard > modules that automatically generate words based on a grammar? > thanks for help, > Daniele From dorjetarap at googlemail.com Fri Sep 19 17:38:11 2008 From: dorjetarap at googlemail.com (dorje tarap) Date: Fri, 19 Sep 2008 16:38:11 +0100 Subject: [Tutor] Web programming advice Message-ID: Hi All, I would really like to learn about using python for creating a website from scratch to allow me to learn about web programming and python. I have zero experience of web programming, and some limited exposure to python. Can someone recommend a book or resource that will introduce me to web programming. Thanks From Mike.Hansen at atmel.com Fri Sep 19 17:56:42 2008 From: Mike.Hansen at atmel.com (Hansen, Mike) Date: Fri, 19 Sep 2008 09:56:42 -0600 Subject: [Tutor] Web programming advice In-Reply-To: References: Message-ID: <7941B2693F32294AAF16C26B679A258D03B07FD9@csomb01.corp.atmel.com> > From: tutor-bounces+mike.hansen=atmel.com at python.org > [mailto:tutor-bounces+mike.hansen=atmel.com at python.org] On > Behalf Of dorje tarap > Sent: Friday, September 19, 2008 9:38 AM > To: Tutor at python.org > Subject: [Tutor] Web programming advice > > Hi All, > > I would really like to learn about using python for creating a website > from scratch to allow me to learn about web programming and python. > > I have zero experience of web programming, and some limited exposure > to python. Can someone recommend a book or resource that will > introduce me to web programming. > > Thanks I suggest you learn to crawl before you learn to walk and run. Do a simple form processing exercise using the cgi module to get a better understanding of how web programming works. Experiment with a templating language. Then you can try some of the web frameworks like Turbogears, Django, Web.py, ... Of course, ask questions here if you need help. http://www.devshed.com/c/a/Python/Writing-CGI-Programs-in-Python/ http://docs.python.org/lib/module-cgi.html http://wiki.python.org/moin/WebProgramming Mike From optomatic at rogers.com Fri Sep 19 18:19:32 2008 From: optomatic at rogers.com (Patrick) Date: Fri, 19 Sep 2008 12:19:32 -0400 Subject: [Tutor] Web programming advice In-Reply-To: References: Message-ID: <48D3D114.9000009@rogers.com> Hi Dorje I am a beginner like you, I can't provide perfect advice but I have been working through this same problem for months. If you use Python CGI you can get started right away with virtually any hosting company but the performance is terrible and the Python interpreter installed will be terribly old too. Python web programming generally forces us into frameworks, which most people seem happy to use. There use to be lots of Python frameworks but there are less now. Django is the most popular. Turbogears and Pylons have merged now and they would be number 2. I am in the small minority of people who are don't like frameworks. I am really struggling to get going with out one. However there are options for us too, I will mention them to you but again most people like frameworks just fine. In the old days all these frameworks did the same basic things differently. Eventually the WSGi specification was devised so that there would be a common base to work from. You can actually program directly on the WSGI layer. I am trying to do this. You get CGI like control(actually better) with high performance but there is not that much documentation and I am personally making slow progress. If you happen to be an odd ball like me you might want to take the long route too and have a look at this. Once you understand WSGI you will likely understand frameworks better too. Everyone seems to like frameworks but consider this, According to this article there have been changes to 350K lines of code in Django: http://www.djangoproject.com/weblog/2008/sep/03/1/ I am sure this is an awesomely powerful framework but how the hell does anyone understand the magic under the cover with so many lines of code? Are you really programming in Python or are you programming in Django now? Please also watch this youtube episode, a talk by Turbogears Mark Ramm: http://www.youtube.com/watch?v=fipFKyW2FA4&feature=PlayList&p=D415FAF806EC47A1&index=12 Check out the dependency graph for Django, it gives me chills. After I learn WSGI I can program without dependencies and I am looking forward to it despite the tediousness that I am sure will also come with working at this level. Please also see Werkzeug and Paste. They are tools to help program at the WSGI level. There are many, many people who can offer better guidance then me but if you have any further questions please ask, I really want to help-Patrick According to this article: http://www.djangoproject.com/weblog/2008/sep/03/1/ over 350K lines of code dorje tarap wrote: > Hi All, > > I would really like to learn about using python for creating a website > from scratch to allow me to learn about web programming and python. > > I have zero experience of web programming, and some limited exposure > to python. Can someone recommend a book or resource that will > introduce me to web programming. > > Thanks > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From flaxeater at gmail.com Fri Sep 19 18:56:49 2008 From: flaxeater at gmail.com (Chad Crabtree) Date: Fri, 19 Sep 2008 12:56:49 -0400 Subject: [Tutor] Web programming advice In-Reply-To: References: Message-ID: <584940990809190956m676d85c9tf8d8f02c3c6fedbb@mail.gmail.com> Things you need to know. In order * HTML * Javascript * CGI Webscripting, this teaches you the difference between GET and POST, with this you can make simple things, like a page view counter for example, or a simple game of hangman. * Web framework or Templating language, python is not well suited to just spraying code inside markup. On Fri, Sep 19, 2008 at 11:38 AM, dorje tarap wrote: > Hi All, > > I would really like to learn about using python for creating a website > from scratch to allow me to learn about web programming and python. > > I have zero experience of web programming, and some limited exposure > to python. Can someone recommend a book or resource that will > introduce me to web programming. > > Thanks > _______________________________________________ > 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 Sep 19 19:37:54 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 19 Sep 2008 13:37:54 -0400 Subject: [Tutor] Web programming advice In-Reply-To: <48D3D114.9000009@rogers.com> References: <48D3D114.9000009@rogers.com> Message-ID: <1c2a2c590809191037k34407b8bv57547f82b552bfd0@mail.gmail.com> On Fri, Sep 19, 2008 at 12:19 PM, Patrick wrote: > According to this article there have been changes to 350K lines of code in > Django: > http://www.djangoproject.com/weblog/2008/sep/03/1/ Note there are also 40,000 lines of new documentation. > I am sure this is an awesomely powerful framework but how the hell does > anyone understand the magic under the cover with so many lines of code? Are > you really programming in Python or are you programming in Django now? You don't have to understand all the magic under the hood. You start here: http://docs.djangoproject.com/en/dev/ You can dig into the details of the framework as needed, you don't have to understand the internals to use it. > Please also watch this youtube episode, a talk by Turbogears Mark Ramm: > http://www.youtube.com/watch?v=fipFKyW2FA4&feature=PlayList&p=D415FAF806EC47A1&index=12 > > Check out the dependency graph for Django, it gives me chills. > > After I learn WSGI I can program without dependencies Yes, if you are willing to roll your own code for everything you need. The reason the frameworks are popular is that they solve many problems that are common to many web apps. Kent From alan.gauld at btinternet.com Fri Sep 19 20:26:26 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 19 Sep 2008 19:26:26 +0100 Subject: [Tutor] Web programming advice References: <48D3D114.9000009@rogers.com> Message-ID: "Patrick" wrote > I am in the small minority of people who are don't like frameworks. There used to be a small minority of people who didn't like compiled or other high level languages. But they gradually died out... There was even a very small community who didn't like assembler, preferring to enter binary or hexcodes directly, but they died out very quickly! > really struggling to get going without one. Yep, that's why other folks like them! :-) > You can actually program directly on the WSGI layer. I am trying to > do this. You get CGI like control(actually better) with high > performance Just as you can program a Windows GUI using the Win32 API. Or use XLib on X windows. (X in very interesting because it has many layers of abstraction designed right in, from XLib to Xt to XView/Motif/GTK etc) But its all incredibly painful! > According to this article there have been changes to 350K lines of > code in Django: > http://www.djangoproject.com/weblog/2008/sep/03/1/ > > I am sure this is an awesomely powerful framework but how the hell > does anyone understand the magic under the cover with so many lines > of code? Only the developers do. There are hundreds of thousands of lines in a GUI framework too but nobody feels the need to read them all before using wxWindows or Tcl/Tk or GTK... > Are you really programming in Python or are you programming in > Django now? You are programming in Python using Django. Similarly when you import the os module you are programming in Python using the os module. If you look at the source for os and then drill down to look at the Unix C libraries utilised you will find many thousands of lines of code there too, before you ultimately call the OS system calls. If you then drill into the system call code (which you can do in Linux or Darwin) you will find that they eventually call BIOS routines written in assembler. But very few programmers bother reading the assembler code for the BIOS routine (interrupt 0x13 from memory?) that writes to disk before considering whether they should use file.writelines() in Python... The whole of software engineering is built up on layers of software provided by others. 'Framework' is just a fancy name for a particular type of layer. If it makes the job easier and delivers acceptable performance use it. If not drop down a layer. Sometimes programming at the lower levels can be useful for learning, sometimes it can be a fun challenge in its own right. But if you need to get a job done go with the highest level software support you can find! Thats why we are using Python and not C, right? -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From optomatic at rogers.com Fri Sep 19 21:28:51 2008 From: optomatic at rogers.com (Patrick) Date: Fri, 19 Sep 2008 15:28:51 -0400 Subject: [Tutor] Web programming advice In-Reply-To: References: <48D3D114.9000009@rogers.com> Message-ID: <48D3FD73.20807@rogers.com> Hi Dorje and Alan First off, everything that Alan has said is true and I would like to re-iterate my lack of qualifications. I depend on people like Alan to guide me. Just a couple of days ago I posted an extremely silly question about shell programming. So having said that I think there are two veins of discussion that would be helpful to you, One a framework discussion and the other a list of terms you need to learn. I have not used Django for any project but I have read about it and it is very popular, however just because everyone else is using does not mean you have to. Alan and Ken are right, you don't have to know what's under the hood to use a framework but I think the choice of a framework is of paramount importance. It appears to me that Django is an all-in-one monolithic application. Years ago Zope was the number 1 and now it's basically gone. Unless speed and easy of use are of paramount importance I suggest that you look at Pylons/Turbogears(unless of course you want to join me in the search for the lost city of Atlantis(WSGI programing)). This way if you do not like your framework you can take much of your code with you to another framework. I don't think this will be the case with Django. You can switch out components with relative ease with Pylons and to a lesser degree with Turbogears. Here are some terms you need to learn. I can help if you need it or you might want to search wikipedia for them: ORM relational mapper, you might look at SQLAlchemy MVC Model view Controller Templating engine WSGI Url Routing I am sure I will think of more later.... Once your done your App, you then have to host it, you have far fewer choices then with PHP. You could try Webfaction or maybe you would like to run it on a virtual server, Slice hosting has pretty cheap packages($25 ish) Sorry to make this about me again but in my defense of my last post, I really think that you do want to think about long term commitments, it takes along time to learn this stuff. I use GTK and I don't care about the code it's written in. I am confident that it will be with us in five to ten years and I am totally confident that Python will be with us for much longer. I have been thinking about learning TCL/Tk recently. It has lots of benefits but it also looks like it has been in a steady decline for some time. Choosing a language or a framework is in a sense a business decision. I don't think that the Python framework world has stabilized just yet, I am personally confused about what to do, so remember it is the blind leading the blind here but I urge you to consider something that decouples well. -Patrick Alan Gauld wrote: > "Patrick" wrote > >> I am in the small minority of people who are don't like frameworks. > > There used to be a small minority of people who didn't like compiled > or other high level languages. But they gradually died out... There > was even a very small community who didn't like assembler, preferring > to enter binary or hexcodes directly, but they died out very quickly! > >> really struggling to get going without one. > > Yep, that's why other folks like them! :-) > >> You can actually program directly on the WSGI layer. I am trying to >> do this. You get CGI like control(actually better) with high performance > > Just as you can program a Windows GUI using the Win32 API. > Or use XLib on X windows. (X in very interesting because it has > many layers of abstraction designed right in, from XLib to Xt to > XView/Motif/GTK etc) But its all incredibly painful! > >> According to this article there have been changes to 350K lines of >> code in Django: >> http://www.djangoproject.com/weblog/2008/sep/03/1/ >> >> I am sure this is an awesomely powerful framework but how the hell >> does anyone understand the magic under the cover with so many lines >> of code? > > Only the developers do. There are hundreds of thousands of lines in a > GUI framework too but nobody feels the need to read them all before > using wxWindows or Tcl/Tk or GTK... > >> Are you really programming in Python or are you programming in Django >> now? > > You are programming in Python using Django. > Similarly when you import the os module you are programming in Python > using the os module. If you look at the source for os and then drill down > to look at the Unix C libraries utilised you will find many thousands of > lines of code there too, before you ultimately call the OS system calls. > If you then drill into the system call code (which you can do in Linux or > Darwin) you will find that they eventually call BIOS routines written in > assembler. But very few programmers bother reading the assembler > code for the BIOS routine (interrupt 0x13 from memory?) that writes to > disk before considering whether they should use file.writelines() in > Python... > > The whole of software engineering is built up on layers of software > provided by others. 'Framework' is just a fancy name for a particular > type of layer. If it makes the job easier and delivers acceptable > performance use it. If not drop down a layer. > > Sometimes programming at the lower levels can be useful for learning, > sometimes it can be a fun challenge in its own right. But if you need > to get a job done go with the highest level software support you can > find! > Thats why we are using Python and not C, right? > > From optomatic at rogers.com Fri Sep 19 21:35:49 2008 From: optomatic at rogers.com (Patrick) Date: Fri, 19 Sep 2008 15:35:49 -0400 Subject: [Tutor] Web programming advice In-Reply-To: References: <48D3D114.9000009@rogers.com> Message-ID: <48D3FF15.103@rogers.com> Sorry to create another post and fill up everyones mailboxes but I forgot something important... In terms of searching for documentation I believe you should look to the framework of your choice. There is not that much non-cgi related programming documentation out there-patrick Alan Gauld wrote: > "Patrick" wrote > >> I am in the small minority of people who are don't like frameworks. > > There used to be a small minority of people who didn't like compiled > or other high level languages. But they gradually died out... There > was even a very small community who didn't like assembler, preferring > to enter binary or hexcodes directly, but they died out very quickly! > >> really struggling to get going without one. > > Yep, that's why other folks like them! :-) > >> You can actually program directly on the WSGI layer. I am trying to >> do this. You get CGI like control(actually better) with high performance > > Just as you can program a Windows GUI using the Win32 API. > Or use XLib on X windows. (X in very interesting because it has > many layers of abstraction designed right in, from XLib to Xt to > XView/Motif/GTK etc) But its all incredibly painful! > >> According to this article there have been changes to 350K lines of >> code in Django: >> http://www.djangoproject.com/weblog/2008/sep/03/1/ >> >> I am sure this is an awesomely powerful framework but how the hell >> does anyone understand the magic under the cover with so many lines >> of code? > > Only the developers do. There are hundreds of thousands of lines in a > GUI framework too but nobody feels the need to read them all before > using wxWindows or Tcl/Tk or GTK... > >> Are you really programming in Python or are you programming in Django >> now? > > You are programming in Python using Django. > Similarly when you import the os module you are programming in Python > using the os module. If you look at the source for os and then drill down > to look at the Unix C libraries utilised you will find many thousands of > lines of code there too, before you ultimately call the OS system calls. > If you then drill into the system call code (which you can do in Linux or > Darwin) you will find that they eventually call BIOS routines written in > assembler. But very few programmers bother reading the assembler > code for the BIOS routine (interrupt 0x13 from memory?) that writes to > disk before considering whether they should use file.writelines() in > Python... > > The whole of software engineering is built up on layers of software > provided by others. 'Framework' is just a fancy name for a particular > type of layer. If it makes the job easier and delivers acceptable > performance use it. If not drop down a layer. > > Sometimes programming at the lower levels can be useful for learning, > sometimes it can be a fun challenge in its own right. But if you need > to get a job done go with the highest level software support you can > find! > Thats why we are using Python and not C, right? > > From sierra_mtnview at sbcglobal.net Fri Sep 19 21:51:00 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Fri, 19 Sep 2008 12:51:00 -0700 Subject: [Tutor] Local Unbound Mystery Message-ID: <48D402A4.6040907@sbcglobal.net> An HTML attachment was scrubbed... URL: From kent37 at tds.net Fri Sep 19 22:26:07 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 19 Sep 2008 16:26:07 -0400 Subject: [Tutor] Local Unbound Mystery In-Reply-To: <48D402A4.6040907@sbcglobal.net> References: <48D402A4.6040907@sbcglobal.net> Message-ID: <1c2a2c590809191326h524eb4fcvbb4984beea55722b@mail.gmail.com> On Fri, Sep 19, 2008 at 3:51 PM, Wayne Watson wrote: > In some code I'm writing, I ran into a problem with the variable updown. I > want it to be global. I cut down the code to near the essentials. I set a > variable abc, and it seems to be happy with an almost identical use of > updown. Where's this going wrong? Although there's an implication of a > yyyy/mm/dd date, I omitted any check, so just enter a number. You don't seem to have posted the actual code you used to generate the traceback - there is no 'print updown' in sync_high2low_files(). Anyway this probably explains your problem: http://effbot.org/pyfaq/how-do-you-set-a-global-variable-in-a-function.htm Kent From sander.sweers at gmail.com Fri Sep 19 23:38:19 2008 From: sander.sweers at gmail.com (Sander Sweers) Date: Fri, 19 Sep 2008 23:38:19 +0200 Subject: [Tutor] Local Unbound Mystery In-Reply-To: <48D402A4.6040907@sbcglobal.net> References: <48D402A4.6040907@sbcglobal.net> Message-ID: On Fri, Sep 19, 2008 at 21:51, Wayne Watson wrote: The code does not belong the Traceback. When I run the code I get a different issue, see below. > def sync_high2low_files(): > morris() > sync_low2high_files() Search for the difference. Greets Sander From alan.gauld at btinternet.com Sat Sep 20 00:01:54 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 19 Sep 2008 23:01:54 +0100 Subject: [Tutor] Web programming advice References: <48D3D114.9000009@rogers.com> <48D3FD73.20807@rogers.com> Message-ID: "Patrick" wrote > is of paramount importance. It appears to me that Django is an > all-in-one monolithic application. Years ago Zope was the number 1 > and now it's basically gone. Zope is still around but it has retreated into something of a niche where it offers its own unique advantages, namely very large, high volume sites. Zope is, I believe, also the engine underneath Plone which is in itself something of a niche market content management system. > importance I suggest that you look at Pylons/Turbogears Thats still my personal preferred web framework although I haven't looked at the new stuff based on Pylons. However my experience of Web Frameworks is that they all do the same basic things and moving from Java Struts to Ruby Rails toTurboGears to Django has not been that hard. Once you figure out one of them the concepts are pretty similar its just syntax and some configuration files after that. > programing)). This way if you do not like your framework you can > take much of your code with you to another framework. I don't think > this will be the case with Django. The key to any kind of application building is to isolate the application specific business logic from the presentation logic. It should be fairtly easy to take a well cradted web application and convert it to a GUI based standalone or vice-versa. Only the presentation and interaction (the View and Controller of MVC fame) need to be modified. > You can switch out components with relative ease with Pylons and to > a lesser degree with Turbogears. Which is one of the things I like abough TG, although in practice I've never used anything but the default components! > ORM relational mapper, you might look at SQLAlchemy > MVC Model view Controller > Templating engine > WSGI > Url Routing The previous point about writing at least a basic Form submission app using raw CGI is a good one too. It does force you to learn how all of these apps work. And to understand the very real limitations and compromises in using http/HTML as the basis of a transaction handling system! It was never intended to do what we are asking of it nowadays! > Sorry to make this about me again but in my defense of my last post, > I really think that you do want to think about long term commitments Thats a very good point. Tying back to my own parallels with GUIs and OS those who picked Oberon, or BeOS or even Plan9 for their wortld beating app are probably regretting the choice. Longevity is a very important consideration. > much longer. I have been thinking about learning TCL/Tk recently. It > has lots of benefits but it also looks like it has been in a steady > decline Tcl/Tk itself is still slowly developing but the real strength of Tk is the wide support it has among other scripting languages. It is a skill that is highly portable between Tcl, Perl, Python, Lisp, Ruby, C and probably a host of other languages. tHisis directly due to two things: 1) It is a very simple GUI designed primarily to wrap up existing applications and 2) the Tcl llanguage was designed frtom the ground up to be embedded in other languages. > for some time. Choosing a language or a framework is in a sense a > business decision. I don't think that the Python framework world has > stabilized just yet, In software nothing much ever stabilises. Technology changes are the norm (with 3 notable exceptions(*)). When I started out it was BASIC, COBOL, FORTRAN and Algol. C, Pascal and ADA were the rising stars. By the time I was full time in programming it was C++, Objective C and Smalltalk battling it out for the OO space. Then Java appeared and Perl took off as a CGI tool with JavaScript on the client. That opened the door for a plethora of scripting languages including VB and .NET and PHP and Scheme and of course Python... But I don't expect to be writing a lot of Python in 10 years time. What I will be writing in is anybody's guess... (*)The exceptions of course are the perennial specialists: BASIC, COBOL and FORTRAN > consider something that decouples well. That's sound advice HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From bart.cramer at gmail.com Sat Sep 20 00:16:52 2008 From: bart.cramer at gmail.com (Bart Cramer) Date: Sat, 20 Sep 2008 00:16:52 +0200 Subject: [Tutor] Exiting a PyGTK main loop Message-ID: <2f75e6460809191516v628b62efnf0780f7a7317cfa9@mail.gmail.com> Dear all, I am a bit stuck in a small project, trying to quit a PyGTK program. Here are some relevant snippets: def init_gui (self) : self.window = gtk.Window (gtk.WINDOW_TOPLEVEL) self.window.connect ("delete_event", self.delete_event) self.window.connect ("destroy", self.destroy) def delete_event(self, widget, event, data=None) : return False def destroy(self, widget, data=None) : gtk.main_quit() Seems pretty standard so far... Now, I want the following: if a certain condition has been met (categories run out...), the program should quit, exit status 0. if len(categories) == 0 : gtk.main_quit() The error message I get is the following: RuntimeError: called outside of a mainloop So I suppose that I should send a signal or event to the main loop, which will terminate it by some magic on its own. But how do I do that? Thanks in advance for your time! Bart. From sierra_mtnview at sbcglobal.net Sat Sep 20 00:23:37 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Fri, 19 Sep 2008 15:23:37 -0700 Subject: [Tutor] Local Unbound Mystery In-Reply-To: <1c2a2c590809191326h524eb4fcvbb4984beea55722b@mail.gmail.com> References: <48D402A4.6040907@sbcglobal.net> <1c2a2c590809191326h524eb4fcvbb4984beea55722b@mail.gmail.com> Message-ID: <48D42669.8090805@sbcglobal.net> An HTML attachment was scrubbed... URL: From spmcinerney at hotmail.com Sat Sep 20 01:03:24 2008 From: spmcinerney at hotmail.com (Stephen McInerney) Date: Fri, 19 Sep 2008 16:03:24 -0700 Subject: [Tutor] Any Windows users help reproing IDLE bug 3841? Message-ID: Can a couple of Vista and XP users please test this out? Thanks - Stephen _____ Could anyone help reproing this minor IDLE bug?http://bugs.python.org/issue3841I found it on Windows Vista with Python 2.5 / IDLE 1.2.2.Other people have reported it does NOT occur with either:Win XP / Python 2.5 / Idle 1.2 Mac OS X 10.5.4 / Python 2.5.2 / IDLE 1.2.2Can anyone repro it on Vista on 2.5? Vista on 2.6?Please let me know if you can/cannot repro on a combination of each of these:OS: Windows XP (SP2?), Windows Vista (SP1?), LinuxPython version: 2.5, 2.6, 2.7, 3.0IDLE versions: ? Copy-and-paste the testcase, view it inside IDLE and see what if the issue occurs.Should only take 1 minute. Thanks in advance,Stephen _________________________________________________________________ Stay up to date on your PC, the Web, and your mobile phone with Windows Live. http://clk.atdmt.com/MRT/go/msnnkwxp1020093185mrt/direct/01/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From sander.sweers at gmail.com Sat Sep 20 12:30:12 2008 From: sander.sweers at gmail.com (Sander Sweers) Date: Sat, 20 Sep 2008 12:30:12 +0200 Subject: [Tutor] Local Unbound Mystery In-Reply-To: <48D42669.8090805@sbcglobal.net> References: <48D402A4.6040907@sbcglobal.net> <1c2a2c590809191326h524eb4fcvbb4984beea55722b@mail.gmail.com> <48D42669.8090805@sbcglobal.net> Message-ID: On Sat, Sep 20, 2008 at 00:23, Wayne Watson wrote: > Well, it made a difference, and now program and output are in agreement. Not really the code has an error so it could not have worked. > updown = +1 > while keyop <> 0: You forgot to create keyop in this example. > UnboundLocalError: local variable 'updown' referenced before assignment > ... > http://effbot.org/pyfaq/how-do-you-set-a-global-variable-in-a-function.htm Did you actually read the link Kent provided? It does not look like you did. Greets Sander From sierra_mtnview at sbcglobal.net Sat Sep 20 13:26:55 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 20 Sep 2008 04:26:55 -0700 Subject: [Tutor] Local Unbound Mystery In-Reply-To: References: <48D402A4.6040907@sbcglobal.net> <1c2a2c590809191326h524eb4fcvbb4984beea55722b@mail.gmail.com> <48D42669.8090805@sbcglobal.net> Message-ID: <48D4DDFF.30306@sbcglobal.net> An HTML attachment was scrubbed... URL: From jdmccla at regence.com Sat Sep 20 13:01:03 2008 From: jdmccla at regence.com (James D Mcclatchey) Date: Sat, 20 Sep 2008 04:01:03 -0700 Subject: [Tutor] AUTO: James D Mcclatchey is out of the office. (returning 09/29/2008) Message-ID: I am out of the office until 09/29/2008. I will respond to your message when I return. Note: This is an automated response to your message "Tutor Digest, Vol 55, Issue 63" sent on 9/20/08 3:00:29. This is the only notification you will receive while this person is away. *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 juhasecke at googlemail.com Sat Sep 20 13:51:32 2008 From: juhasecke at googlemail.com (Jan Ulrich Hasecke) Date: Sat, 20 Sep 2008 13:51:32 +0200 Subject: [Tutor] Web programming advice In-Reply-To: References: <48D3D114.9000009@rogers.com> <48D3FD73.20807@rogers.com> Message-ID: Am 20.09.2008 um 00:01 schrieb Alan Gauld: > > "Patrick" wrote > >> is of paramount importance. It appears to me that Django is an all- >> in-one monolithic application. Years ago Zope was the number 1 and >> now it's basically gone. > > Zope is still around but it has retreated into something of a niche > where it offers its own unique advantages, namely very large, > high volume sites. Zope is, I believe, also the engine underneath > Plone which is in itself something of a niche market content > management system. > Zope has not retreated into a niche, but has heavily evolved from the technical point of view in the last years. With the new component architecture Zope makes it more easy to develop and maintain huge and complex mission-critical webapplications. You can glue your applications together either with an explicit configuration language called ZCML or within a convention-over-configuration framework called Grok. With Grok it is very easy to start Zope development. The greates advantage of Zope is beside security, security and security the fact that there is a huge library of ready-to-use components to develop your custom application. And Zope has an object database, with which you can even develop outside Zope. There are some very huge installations out there and the Zope community is still alive. Plone is not a niche CMS, but the leading Python CMS if not the leading Open Source CMS around. This has been stated lately by CMSWatch. There is a very vibrant Plone community, which develops and maintains Plone. So check it out at http://plone.org The further development of Zope and Plone is secured and guided by the Zope Foundation and the Plone Foundation. So the answer to the OP is: Try out Grok to start with Zope. It is great! grok.zope.org Cheers! juh -- Business: http://hasecke.com --- Private: http://hasecke.eu --- Blog: http://www.sudelbuch.de --- History: www.generationenprojekt.de --- Europe: www.wikitution.org From alan.gauld at btinternet.com Sat Sep 20 14:26:57 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 20 Sep 2008 13:26:57 +0100 Subject: [Tutor] Local Unbound Mystery References: <48D402A4.6040907@sbcglobal.net><1c2a2c590809191326h524eb4fcvbb4984beea55722b@mail.gmail.com><48D42669.8090805@sbcglobal.net> Message-ID: > Not really the code has an error so it could not have worked. > >> updown = +1 Is this meant to be updown += 1 maybe? Although as the error message shows you need to set it to a valid value before incrementing it, so mayber you just meant updown = 1 # no need for the + sign >> while keyop <> 0: And the <> form of not equal is deprecated in favour of != so this should probably be while keyop != 0 Or better still just while keyop: > You forgot to create keyop in this example. >> UnboundLocalError: local variable 'updown' referenced before >> assignment HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Sat Sep 20 14:32:02 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 20 Sep 2008 08:32:02 -0400 Subject: [Tutor] Local Unbound Mystery In-Reply-To: <48D4DDFF.30306@sbcglobal.net> References: <48D402A4.6040907@sbcglobal.net> <1c2a2c590809191326h524eb4fcvbb4984beea55722b@mail.gmail.com> <48D42669.8090805@sbcglobal.net> <48D4DDFF.30306@sbcglobal.net> Message-ID: <1c2a2c590809200532ge218935ie365e0f83de2094e@mail.gmail.com> On Sat, Sep 20, 2008 at 7:26 AM, Wayne Watson wrote: > I do not think I've made an inaccurate observation. Is it possible the IDLE > shell is leaving something behind that I can't see? Maybe I had two shell > window up at the same time between the real and debug program. I'm not too familiar with IDLE but the version I have does have this behaviour- if I run a program that defines global variables, then the globals are available in the shell until I run another program. So if you are switching between running a program and experimenting in the shell, that may cause you some confusion. I don't think IDLE preserves variables between runs of a program. When the shell prints out the "RESTART" line, it is clearing the old variables. Whether that is the problem or not, I recommend you find a different editor or IDE to use; IMO IDLE is quite primitive and there are many better choices. Check the list archives or the Python wiki for many suggestions. http://wiki.python.org/moin/PythonEditors Kent From alan.gauld at btinternet.com Sat Sep 20 14:32:42 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 20 Sep 2008 13:32:42 +0100 Subject: [Tutor] Local Unbound Mystery References: <48D402A4.6040907@sbcglobal.net> <1c2a2c590809191326h524eb4fcvbb4984beea55722b@mail.gmail.com> <48D42669.8090805@sbcglobal.net> <48D4DDFF.30306@sbcglobal.net> Message-ID: "Wayne Watson" wrote > I do not think I've made an inaccurate observation. > Is it possible the IDLE shell is leaving something > behind that I can't see? That's very possible. The interpreter will remember its previous state for as long as its running so if you import your module into the shell, say, it will remember it, similarly if you try some code out that uses the same name as the variable in your script it can confuse the interpreter. That's why, when in doubt, always run your code outside of any IDE to find out its true behaviour. IDEs (including IDLE) are very useful tools but they can mislead as well. > I just inserted the global statement in the full program I'm not quite sure what you mean by this, but I assume you mean you had a simplified version of the problem plus the full application code that you were working on? HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From jtp at nc.rr.com Sat Sep 20 17:43:09 2008 From: jtp at nc.rr.com (James) Date: Sat, 20 Sep 2008 11:43:09 -0400 Subject: [Tutor] pexpect Message-ID: Folks, Does anyone here have experience with pexpect? I'm trying to write a pexpect script which will log into a network device, gather statistics, and then dump the raw output into a file (or a string so that I can manipulate it). I'm not having much luck. Because the connection is telnet I was able to use wireshark (a sniffer) to see the traffic between my computer (which is running the pexpect script) and the network device. Everything seems to go find until I "expect" the network device's prompt and it just hangs. Eventually pexpect throws an exception and times out. I'd be happy to share some code when I get to the computer I've been testing on. :) In the time being, has anyone seen a problem like this before? Thanks! -j From sierra_mtnview at sbcglobal.net Sat Sep 20 17:55:54 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 20 Sep 2008 08:55:54 -0700 Subject: [Tutor] Local Unbound Mystery In-Reply-To: References: <48D402A4.6040907@sbcglobal.net> <1c2a2c590809191326h524eb4fcvbb4984beea55722b@mail.gmail.com> <48D42669.8090805@sbcglobal.net> <48D4DDFF.30306@sbcglobal.net> Message-ID: <48D51D0A.1030900@sbcglobal.net> An HTML attachment was scrubbed... URL: From steve.poe at gmail.com Sat Sep 20 17:59:09 2008 From: steve.poe at gmail.com (Steve Poe) Date: Sat, 20 Sep 2008 08:59:09 -0700 Subject: [Tutor] pexpect In-Reply-To: References: Message-ID: James, I've not used pexpect, but I've done this on a Cisco switch. I found using time.sleep and read_until of the telnet class to be helpful. 10 tn = telnetlib.Telnet('') 11 #tn.set_debuglevel(9) 12 tn.read_until('Username: \xff', 5) 13 time.sleep(10) 14 tn.write('\n') 15 tn.read_until('\r\nPassword: ', 5) 16 #time.sleep(2) 17 tn.write('\n') 18 tn.read_until('#', 5) 19 tn.write('term len 0 \n') 20 tn.read_until('#', 5) 21 tn.write('show version | i restarted\n') 22 RouterStartupTimestamp = tn.read_until('#', 2) 23 tn.read_until('#', 2) 24 tn.write('show call history voice last 100\n') HTH, Steve On Sep 20, 2008, at 8:43 AM, James wrote: > Folks, > > Does anyone here have experience with pexpect? I'm trying to write a > pexpect script which will log into a network device, gather > statistics, and then dump the raw output into a file (or a string so > that I can manipulate it). > > I'm not having much luck. Because the connection is telnet I was able > to use wireshark (a sniffer) to see the traffic between my computer > (which is running the pexpect script) and the network device. > Everything seems to go find until I "expect" the network device's > prompt and it just hangs. Eventually pexpect throws an exception and > times out. > > I'd be happy to share some code when I get to the computer I've been > testing on. :) In the time being, has anyone seen a problem like this > before? > > Thanks! > -j > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From sierra_mtnview at sbcglobal.net Sat Sep 20 18:04:32 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 20 Sep 2008 09:04:32 -0700 Subject: [Tutor] Local Unbound Mystery In-Reply-To: <1c2a2c590809200532ge218935ie365e0f83de2094e@mail.gmail.com> References: <48D402A4.6040907@sbcglobal.net> <1c2a2c590809191326h524eb4fcvbb4984beea55722b@mail.gmail.com> <48D42669.8090805@sbcglobal.net> <48D4DDFF.30306@sbcglobal.net> <1c2a2c590809200532ge218935ie365e0f83de2094e@mail.gmail.com> Message-ID: <48D51F10.8080509@sbcglobal.net> An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Sat Sep 20 19:09:52 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 20 Sep 2008 10:09:52 -0700 Subject: [Tutor] Local Unbound Mystery In-Reply-To: References: <48D402A4.6040907@sbcglobal.net><1c2a2c590809191326h524eb4fcvbb4984beea55722b@mail.gmail.com><48D42669.8090805@sbcglobal.net> Message-ID: <48D52E60.8090404@sbcglobal.net> An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Sat Sep 20 19:29:30 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 20 Sep 2008 10:29:30 -0700 Subject: [Tutor] Local Unbound Mystery In-Reply-To: References: <48D402A4.6040907@sbcglobal.net><1c2a2c590809191326h524eb4fcvbb4984beea55722b@mail.gmail.com><48D42669.8090805@sbcglobal.net> Message-ID: <48D532FA.9020306@sbcglobal.net> An HTML attachment was scrubbed... URL: From robert.d.kirkpatrick at gmail.com Sat Sep 20 19:32:54 2008 From: robert.d.kirkpatrick at gmail.com (Rob Kirkpatrick) Date: Sat, 20 Sep 2008 10:32:54 -0700 Subject: [Tutor] __init__ arguments storage Message-ID: <10ea1c60809201032s69c92ab8ib72191cd7cd0f519@mail.gmail.com> Hi All, In between an object's creation and call to __init__, where are the __init__ arguments stored? Is there a class dictionary that init uses to initialize the instance? I tried printing Class.__init__, but they aren't in there. The reason I ask is that I was trying to track down a bug where it looked like an argument was being mis-passed and I wanted to use pdb to see how it was handled pre- and post-init. Cheers, Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Sep 20 20:34:06 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 20 Sep 2008 19:34:06 +0100 Subject: [Tutor] Local Unbound Mystery References: <48D402A4.6040907@sbcglobal.net><1c2a2c590809191326h524eb4fcvbb4984beea55722b@mail.gmail.com><48D42669.8090805@sbcglobal.net> <48D52E60.8090404@sbcglobal.net> Message-ID: "Wayne Watson" wrote > tried it, but, once the program ends (or dies?), the DOS-like > window disappears. How does one prevent that? Another newbie gotcha! :-) You'll find a more detailed discussion within my Add some Style topic in my tutorial, but the simplest answer is add a line like raw_input('Hit Enter to Quit') at the end of the program -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Sat Sep 20 20:40:50 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 20 Sep 2008 19:40:50 +0100 Subject: [Tutor] __init__ arguments storage References: <10ea1c60809201032s69c92ab8ib72191cd7cd0f519@mail.gmail.com> Message-ID: "Rob Kirkpatrick" wrote > In between an object's creation and call to __init__, where are the > __init__ > arguments stored? Is there a class dictionary that init uses to > initialize > the instance? I tried printing Class.__init__, but they aren't in > there. I haven't checked Pythons source code but most languasges hold the arguments to functions on the stack. So when the function gets called it just pops them off the stack into local variables. > The reason I ask is that I was trying to track down a bug where it > looked > like an argument was being mis-passed and I wanted to use pdb to see > how it > was handled pre- and post-init. I think you can safely assume that Python is passing your variables from the Class creation call to the init method OK. Any such problems would have been picked up and fixed a long time ago. However there are some oddities around default values so if thats the case with your parameters then you might see some behaviour you don't expect. Can you write a short puiece of code that reproduces the problem? Then we might be able to offer more specific help. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From cfuller at thinkingplanet.net Sat Sep 20 19:03:33 2008 From: cfuller at thinkingplanet.net (Chris Fuller) Date: Sat, 20 Sep 2008 12:03:33 -0500 Subject: [Tutor] Exiting a PyGTK main loop In-Reply-To: <2f75e6460809191516v628b62efnf0780f7a7317cfa9@mail.gmail.com> References: <2f75e6460809191516v628b62efnf0780f7a7317cfa9@mail.gmail.com> Message-ID: <200809201203.33793.cfuller@thinkingplanet.net> Defer the quit until the mainloop is running again. something like self.connect('event-after', gtk.main_quit) Cheers On Friday 19 September 2008 17:16, Bart Cramer wrote: > Dear all, > > I am a bit stuck in a small project, trying to quit a PyGTK program. > Here are some relevant snippets: > > def init_gui (self) : > > self.window = gtk.Window (gtk.WINDOW_TOPLEVEL) > > self.window.connect ("delete_event", self.delete_event) > self.window.connect ("destroy", self.destroy) > > def delete_event(self, widget, event, data=None) : > return False > > def destroy(self, widget, data=None) : > gtk.main_quit() > > Seems pretty standard so far... Now, I want the following: if a > certain condition has been met (categories run out...), the program > should quit, exit status 0. > > if len(categories) == 0 : > gtk.main_quit() > > The error message I get is the following: > > RuntimeError: called outside of a mainloop > > So I suppose that I should send a signal or event to the main loop, > which will terminate it by some magic on its own. But how do I do > that? > > Thanks in advance for your time! > > Bart. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From kent37 at tds.net Sat Sep 20 21:44:17 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 20 Sep 2008 15:44:17 -0400 Subject: [Tutor] __init__ arguments storage In-Reply-To: <10ea1c60809201032s69c92ab8ib72191cd7cd0f519@mail.gmail.com> References: <10ea1c60809201032s69c92ab8ib72191cd7cd0f519@mail.gmail.com> Message-ID: <1c2a2c590809201244xf578a75yb16371223b85f68a@mail.gmail.com> On Sat, Sep 20, 2008 at 1:32 PM, Rob Kirkpatrick wrote: > Hi All, > > In between an object's creation and call to __init__, where are the __init__ > arguments stored? Is there a class dictionary that init uses to initialize > the instance? I tried printing Class.__init__, but they aren't in there. No, there is no class dictionary like this. The arguments are stored as ordinary function call parameters. This message and the followup give a pretty good overview of what happens when you create a new class instance: http://mail.python.org/pipermail/python-list/2005-November/349806.html The implementation of this is in the __call__() method of the metaclass of the class being created. Normally this is 'type'. If you want the gory details, the implementation of type.__call__() is in the type_call() function of typeobject.c. http://svn.python.org/view/python/trunk/Objects/typeobject.c?rev=66043&view=auto > The reason I ask is that I was trying to track down a bug where it looked > like an argument was being mis-passed and I wanted to use pdb to see how it > was handled pre- and post-init. Show us the code...it's unlikely that this is a problem with the interpreter. Kent From sierra_mtnview at sbcglobal.net Sat Sep 20 22:15:17 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 20 Sep 2008 13:15:17 -0700 Subject: [Tutor] Local Unbound Mystery In-Reply-To: References: <48D402A4.6040907@sbcglobal.net><1c2a2c590809191326h524eb4fcvbb4984beea55722b@mail.gmail.com><48D42669.8090805@sbcglobal.net> <48D52E60.8090404@sbcglobal.net> Message-ID: <48D559D5.6040702@sbcglobal.net> An HTML attachment was scrubbed... URL: From jgowen at lorettotel.net Sat Sep 20 22:28:05 2008 From: jgowen at lorettotel.net (Johnny) Date: Sat, 20 Sep 2008 15:28:05 -0500 Subject: [Tutor] a simple keyboard art,,, gone wrong! Message-ID: <48D55CD5.5030401@lorettotel.net> An HTML attachment was scrubbed... URL: From robert.d.kirkpatrick at gmail.com Sat Sep 20 22:30:03 2008 From: robert.d.kirkpatrick at gmail.com (Rob Kirkpatrick) Date: Sat, 20 Sep 2008 13:30:03 -0700 Subject: [Tutor] __init__ arguments storage In-Reply-To: <1c2a2c590809201244xf578a75yb16371223b85f68a@mail.gmail.com> References: <10ea1c60809201032s69c92ab8ib72191cd7cd0f519@mail.gmail.com> <1c2a2c590809201244xf578a75yb16371223b85f68a@mail.gmail.com> Message-ID: <10ea1c60809201330yfb15ddew43661f724f3b319d@mail.gmail.com> Thanks Kent! That really makes it clear now. The bug I ran into was a while back and I've since ignored it to the point of forgetting how to invoke it, but I remember the stack trace said something about "variable received multiple arguments". I wanted to check the arguments to see if the same variable was being passed twice, and if so, which one was being used. The whole issue of how the class call stored the init args was keeping me up at night even though I didn't care about the original error anymore. It bugged me enough, I posted and true to form got an awesome (and very quick) reply. Thanks again! Rob On Sat, Sep 20, 2008 at 12:44 PM, Kent Johnson wrote: > On Sat, Sep 20, 2008 at 1:32 PM, Rob Kirkpatrick > wrote: > > Hi All, > > > > In between an object's creation and call to __init__, where are the > __init__ > > arguments stored? Is there a class dictionary that init uses to > initialize > > the instance? I tried printing Class.__init__, but they aren't in there. > > No, there is no class dictionary like this. The arguments are stored > as ordinary function call parameters. > > This message and the followup give a pretty good overview of what > happens when you create a new class instance: > http://mail.python.org/pipermail/python-list/2005-November/349806.html > > The implementation of this is in the __call__() method of the > metaclass of the class being created. Normally this is 'type'. If you > want the gory details, the implementation of type.__call__() is in the > type_call() function of typeobject.c. > > http://svn.python.org/view/python/trunk/Objects/typeobject.c?rev=66043&view=auto > > > The reason I ask is that I was trying to track down a bug where it looked > > like an argument was being mis-passed and I wanted to use pdb to see how > it > > was handled pre- and post-init. > > Show us the code...it's unlikely that this is a problem with the > interpreter. > > Kent > -------------- next part -------------- An HTML attachment was scrubbed... URL: From cbc at unc.edu Sun Sep 21 01:41:38 2008 From: cbc at unc.edu (Chris Calloway) Date: Sat, 20 Sep 2008 19:41:38 -0400 Subject: [Tutor] Web programming advice In-Reply-To: References: <48D3D114.9000009@rogers.com> <48D3FD73.20807@rogers.com> Message-ID: <37618FA2-9919-48C4-8C52-AB2AB446ADDE@unc.edu> On Sep 20, 2008, at 7:51 AM, Jan Ulrich Hasecke wrote: > Am 20.09.2008 um 00:01 schrieb Alan Gauld: >> "Patrick" wrote >> >>> is of paramount importance. It appears to me that Django is an all- >>> in-one monolithic application. Years ago Zope was the number 1 and >>> now it's basically gone. >> >> Zope is still around but it has retreated into something of a niche >> where it offers its own unique advantages, namely very large, >> high volume sites. Zope is, I believe, also the engine underneath >> Plone which is in itself something of a niche market content >> management system. >> > > Zope has not retreated into a niche, but has heavily evolved from > the technical point of view in the last years. [snip] > Plone is not a niche CMS, but the leading Python CMS if not the > leading Open Source CMS around. [snip] > So the answer to the OP is: Try out Grok to start with Zope. It is > great! I'm so glad Jan wrote that so I didn't have to. -- Sincerely, Chris Calloway http://www.secoora.org office: 332 Chapman Hall phone: (919) 599-3530 mail: Campus Box #3300, UNC-CH, Chapel Hill, NC 27599 From alan.gauld at btinternet.com Sun Sep 21 02:13:48 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 21 Sep 2008 01:13:48 +0100 Subject: [Tutor] Local Unbound Mystery References: <48D402A4.6040907@sbcglobal.net><1c2a2c590809191326h524eb4fcvbb4984beea55722b@mail.gmail.com><48D42669.8090805@sbcglobal.net> <48D52E60.8090404@sbcglobal.net> <48D559D5.6040702@sbcglobal.net> Message-ID: "Wayne Watson" wrote > Signature.htmlThanks. Still much to learn. > Where is your tutorial? see the .sig... -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Sun Sep 21 02:18:19 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 21 Sep 2008 01:18:19 +0100 Subject: [Tutor] a simple keyboard art,,, gone wrong! References: <48D55CD5.5030401@lorettotel.net> Message-ID: "Johnny" wrote > I was trying to get this keyboard art to work in Idle,,,, Remember that keyboard (aka ASCII) art relies on a monospaced font. Which font are you using to compose? And which in the shell window? HTH, Alan G From dineshbvadhia at hotmail.com Sun Sep 21 08:06:39 2008 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Sat, 20 Sep 2008 23:06:39 -0700 Subject: [Tutor] array and dictionary Message-ID: Hi! Say, I've got a numpy array/matrix of the form: [[1 6 1 2 3] [4 5 4 7 0] [2 0 8 0 2] [8 2 6 3 0] [0 7 0 3 5] [8 0 3 0 6] [8 0 0 2 2] [3 1 0 4 0] [5 0 8 0 0] [2 1 0 5 6]] And, I want to create a dictionary of rows (as the keys) mapped to lists of non-zero numbers in that row ie. dictionary_non-zeros = { 0: [1 6 1 2 3] 1: [4 5 4 7] 2: [2 8 2] ... 9: [2 1 5 6] } How do I do this? Thanks! Dinesh -------------- next part -------------- An HTML attachment was scrubbed... URL: From =?UTF-8?Q?=22Shantanoo_Mahajan_=28=E0=A4=B6=E0=A4=82=E0=A4=A4?= Sun Sep 21 08:21:32 2008 From: =?UTF-8?Q?=22Shantanoo_Mahajan_=28=E0=A4=B6=E0=A4=82=E0=A4=A4?= (=?UTF-8?Q?=22Shantanoo_Mahajan_=28=E0=A4=B6=E0=A4=82=E0=A4=A4?=) Date: Sun, 21 Sep 2008 11:51:32 +0530 Subject: [Tutor] array and dictionary In-Reply-To: References: Message-ID: Straight forward method would be... >>> a=[[1],[2]] >>> b={} >>> for x in range(len(a)): ... b[x] = a[x] ... >>> a [[1], [2]] >>> b {0: [1], 1: [2]} >>> regards, shantanoo On 21-Sep-08, at 11:36 AM, Dinesh B Vadhia wrote: > Hi! Say, I've got a numpy array/matrix of the form: > > [[1 6 1 2 3] > [4 5 4 7 0] > [2 0 8 0 2] > [8 2 6 3 0] > [0 7 0 3 5] > [8 0 3 0 6] > [8 0 0 2 2] > [3 1 0 4 0] > [5 0 8 0 0] > [2 1 0 5 6]] > > And, I want to create a dictionary of rows (as the keys) mapped to > lists of non-zero numbers in that row ie. > > dictionary_non-zeros = { > 0: [1 6 1 2 3] > 1: [4 5 4 7] > 2: [2 8 2] > ... > 9: [2 1 5 6] > } > > How do I do this? > > Thanks! > > Dinesh > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Sun Sep 21 10:15:00 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 21 Sep 2008 09:15:00 +0100 Subject: [Tutor] array and dictionary References: Message-ID: "Dinesh B Vadhia" wrote > Hi! Say, I've got a numpy array/matrix of the form: > > [[1 6 1 2 3] > [4 5 4 7 0]... > [2 1 0 5 6]] > > I want to create a dictionary of rows (as the keys) mapped > to lists of non-zero numbers in that row Caveat, I dont know about numpy arrays.But assuming they act like Python lists You can get the non zeros with a comprehension nz = [n for n in row if n != 0] you can get the row and index using enumerate for n,r in enumerate(arr): So to create a dictionary, combine the elements somethng like: d ={} for n,r in enumerate(arr): d[n] = [v for v in r if v !=0] I'm sure you could do it all in one line if you really wanted to! Also the new any() function might be usable too. All untested.... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From dineshbvadhia at hotmail.com Sun Sep 21 20:17:19 2008 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Sun, 21 Sep 2008 11:17:19 -0700 Subject: [Tutor] array and dictionary Message-ID: Alan Thanks but I've been a bit daft and described the wrong problem which is easy to solve the long way. Starting again ... Given a (numpy) array how do you create a dictionary of lists where the list contains the column indexes of non-zero elements and the dictionary key is the row index. The easy way is 2 for loops ie. import numpy from collections import defaultdict A = [[1 6 1 2 3] [4 5 4 7 0] [2 0 8 0 2] [0 0 0 3 7]] dict = defaultdict(list) I = A.shape[0] J = A.shape[1] for i in xrange(0, I, 1): for j in xrange(0, J, 1): if a[i,j] > 0: dict[i].append(j) I want to find a faster/efficient way to do this without using the 2 for loops. Thanks! Btw, I posted this on the numpy list too to make sure that there aren't any numpy functions that would help. Dinesh -------------------------------------------------------------------------------- Message: 5 Date: Sun, 21 Sep 2008 09:15:00 +0100 From: "Alan Gauld" Subject: Re: [Tutor] array and dictionary To: tutor at python.org Message-ID: Content-Type: text/plain; format=flowed; charset="iso-8859-1"; reply-type=original "Dinesh B Vadhia" wrote > Hi! Say, I've got a numpy array/matrix of the form: > > [[1 6 1 2 3] > [4 5 4 7 0]... > [2 1 0 5 6]] > > I want to create a dictionary of rows (as the keys) mapped > to lists of non-zero numbers in that row Caveat, I dont know about numpy arrays.But assuming they act like Python lists You can get the non zeros with a comprehension nz = [n for n in row if n != 0] you can get the row and index using enumerate for n,r in enumerate(arr): So to create a dictionary, combine the elements somethng like: d ={} for n,r in enumerate(arr): d[n] = [v for v in r if v !=0] I'm sure you could do it all in one line if you really wanted to! Also the new any() function might be usable too. All untested.... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld -------------- next part -------------- An HTML attachment was scrubbed... URL: From btkuhn at email.unc.edu Sun Sep 21 19:38:47 2008 From: btkuhn at email.unc.edu (btkuhn at email.unc.edu) Date: Sun, 21 Sep 2008 13:38:47 -0400 Subject: [Tutor] Exhaustive Enumeration Message-ID: <20080921133847.ecgsf6vsskc0s88g@webmail4.isis.unc.edu> This is from the MIT Opencourseware intro to computer science course, which I've been working my way through. I understand what needs to be done (I think), which is basically to test each possibility and return the list of states with the most electoral votes that can be paid for under the campaign budget. I am just at a loss as to how to do it, and I've been thinking about it all weekend. Here is the problem I am referring to. One assumption is that every $1 of money spent in a state translates into a popular vote. Many thanks for any suggestions. Also, the next part of the question asks to do the same thing using "Branch and Bound", which I also anticipate having trouble with. If I haven't described things sufficiently, the complete problem is available at: http://ocw.mit.edu/OcwWeb/Electrical-Engineering-and-Computer-Science/6-00Fall-2007/Assignments/index.htm , problem 5. Complete and test this function according to her specification below. Note that she was using exhaustive enumeration to compute the result. Your friend assured you that the function needs no more than 5 additional lines of code. # Problem 2: Exhaustive enumeration def finance_campaign_ee(budget, free_states): """ Takes a budget, in dollars, and a list of available states, as a list of dictionaries. Computes and returns the list of states that maximizes the total number of electoral votes such that these states can be acquired on the budget. Returns an empty list if no states can be acquired. """ cheap_states=[] for s in free_states: if s['pop'] <= budget: cheap_states.append(s) # Base case if len(cheap_states)==0: res_list=[] # Recursive case else: curr_state=cheap_states[0] other_states=cheap_states[1:] inc_states=finance_campaign_ee( budget-curr_state['pop'], other_states) inc_states.append(curr_state) inc_evotes=total_evotes(inc_states) excl_states=finance_campaign_ee( budget, other_states ) excl_evotes=total_evotes(excl_states) # ... your code goes here ... res_list = return res_list From bermanrl at embarqmail.com Sun Sep 21 21:28:00 2008 From: bermanrl at embarqmail.com (Robert Berman) Date: Sun, 21 Sep 2008 15:28:00 -0400 Subject: [Tutor] Exhaustive Enumeration In-Reply-To: <20080921133847.ecgsf6vsskc0s88g@webmail4.isis.unc.edu> References: <20080921133847.ecgsf6vsskc0s88g@webmail4.isis.unc.edu> Message-ID: <48D6A040.8000202@embarqmail.com> An HTML attachment was scrubbed... URL: From btkuhn at email.unc.edu Sun Sep 21 21:43:27 2008 From: btkuhn at email.unc.edu (btkuhn at email.unc.edu) Date: Sun, 21 Sep 2008 15:43:27 -0400 Subject: [Tutor] Exhaustive Enumeration In-Reply-To: <48D6A040.8000202@embarqmail.com> References: <20080921133847.ecgsf6vsskc0s88g@webmail4.isis.unc.edu> <48D6A040.8000202@embarqmail.com> Message-ID: <20080921154327.48ndwt5c4kcwgwok@webmail4.isis.unc.edu> I'm actually not enrolled in the course; MIT puts some of its course materials available online as a general resource. I am out of school and trying to teach myself python on my own. I'm very much a beginner, and since I'm not privy to the lectures or notes from this course I have to fill in things from other sources. Basically, with respect to this problem, I'm at a loss as to how to approach it. My first thought was to use some sort of nested for loop structure to iterate through each possible state combination, but I don't think this is possible, since a for loop would just test for, for instance, (state 1 and 2, state 1 and 3, state 1 and 4, etc.) and not (state 1 and 3, state 1 and 2 and 3, etc.). I could maybe make it work for a very small number of states, but if you are taking 10 states as arguments I don't see a way this could work. Also, the way the question is asked seems to imply that the new code will go after the existing code, and also that it will be only about five lines. I'm guessing that maybe some kind of recursion is required but I really don't know, and recursion is a new concept to me as well. Thanks! Quoting Robert Berman : > A very interesting problem. Given this is homework, I am not > sure what it is you want. > > Do you want the solution coded and tested? > Do you want this to include two or three algorithms optimized for > speed as well as accuracy? > > I think the problem is well enough defined so that you do not need > any clarification of what it is your professor wants from you. > > If you would like some help finding a solution set, perhaps you > would consider submitting some of your own solutions and commentary > as to where your ideas are breaking down. Then, probably, a number of > people will jump in to help you. > > Robert > > btkuhn at email.unc.edu wrote: This is from the MIT Opencourseware intro > to computer science course, which I've been working my way through. I > understand what needs to be done (I think), which is basically to > test each possibility and return the list of states with the most > electoral votes that can be paid for under the campaign budget. I am > just at a loss as to how to do it, and I've been thinking about it > all weekend. Here is the problem I am referring to. One assumption is > that every $1 of money spent in a state translates into a popular > vote. Many thanks for any suggestions. Also, the next part of the > question asks to do the same thing using "Branch and Bound", which I > also anticipate having trouble with. If I haven't described things > sufficiently, the complete problem is available at: > > http://ocw.mit.edu/OcwWeb/Electrical-Engineering-and-Computer-Science/6-00Fall-2007/Assignments/index.htm > , problem 5. > > Complete and test this function according to her specification below. > Note that she was using exhaustive > enumeration to compute the result. Your friend assured you that the > function needs no more than 5 additional > lines of code. > > # Problem 2: Exhaustive enumeration > def finance_campaign_ee(budget, free_states): """ > Takes a budget, in dollars, and a list of available states, as a > list of dictionaries. > > Computes and returns the list of states that maximizes the total > number of electoral votes such that these states can be acquired > on the budget. Returns an empty list if no states can be acquired. > > """ > cheap_states=[] > for s in free_states: > if s['pop'] <= budget: > cheap_states.append(s) > > # Base case > if len(cheap_states)==0: > res_list=[] > # Recursive case > else: > curr_state=cheap_states[0] > other_states=cheap_states[1:] > > inc_states=finance_campaign_ee( budget-curr_state['pop'], > other_states) > inc_states.append(curr_state) > inc_evotes=total_evotes(inc_states) > > excl_states=finance_campaign_ee( budget, other_states ) > excl_evotes=total_evotes(excl_states) > > # ... your code goes here ... > res_list = return res_list > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From bermanrl at embarqmail.com Sun Sep 21 22:31:18 2008 From: bermanrl at embarqmail.com (Robert Berman) Date: Sun, 21 Sep 2008 16:31:18 -0400 Subject: [Tutor] Exhaustive Enumeration In-Reply-To: <20080921154327.48ndwt5c4kcwgwok@webmail4.isis.unc.edu> References: <20080921133847.ecgsf6vsskc0s88g@webmail4.isis.unc.edu> <48D6A040.8000202@embarqmail.com> <20080921154327.48ndwt5c4kcwgwok@webmail4.isis.unc.edu> Message-ID: <48D6AF16.80601@embarqmail.com> An HTML attachment was scrubbed... URL: From bermanrl at embarqmail.com Sun Sep 21 22:40:20 2008 From: bermanrl at embarqmail.com (Robert Berman) Date: Sun, 21 Sep 2008 16:40:20 -0400 Subject: [Tutor] Exhaustive Enumeration In-Reply-To: <515008f10809211313r48da1ba4i4bd06e0d4a0f57e4@mail.gmail.com> References: <20080921133847.ecgsf6vsskc0s88g@webmail4.isis.unc.edu> <48D6A040.8000202@embarqmail.com> <515008f10809211313r48da1ba4i4bd06e0d4a0f57e4@mail.gmail.com> Message-ID: <48D6B134.4030008@embarqmail.com> An HTML attachment was scrubbed... URL: From kent37 at tds.net Sun Sep 21 22:50:36 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 21 Sep 2008 16:50:36 -0400 Subject: [Tutor] array and dictionary In-Reply-To: References: Message-ID: <1c2a2c590809211350w565d6237s4d21397411e656d2@mail.gmail.com> On Sun, Sep 21, 2008 at 2:17 PM, Dinesh B Vadhia wrote: > Given a (numpy) array how do you create a dictionary of lists where the list > contains the column indexes of non-zero elements and the dictionary key is > the row index. The easy way is 2 for loops ie. > > import numpy > from collections import defaultdict > A = > [[1 6 1 2 3] > [4 5 4 7 0] > [2 0 8 0 2] > [0 0 0 3 7]] > > dict = defaultdict(list) Don't use names of builtins as variable names! > I = A.shape[0] > J = A.shape[1] > for i in xrange(0, I, 1): > for j in xrange(0, J, 1): > if a[i,j] > 0: > dict[i].append(j) > > I want to find a faster/efficient way to do this without using the 2 for > loops. Thanks! Not sure about faster but this could be done with list/generator comprehensions: In [37]: A = \ ....: [[1, 6, 1, 2, 3], ....: [4, 5, 4, 7, 0], ....: [2, 0, 8, 0, 2], ....: [0, 0, 0, 3, 7]] In [38]: d = dict( (i, [j for j, val in enumerate(row) if val > 0]) for i, row in enumerate(A)) In [39]: d Out[39]: {0: [0, 1, 2, 3, 4], 1: [0, 1, 2, 3], 2: [0, 2, 4], 3: [3, 4]} Kent From kent37 at tds.net Mon Sep 22 03:14:36 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 21 Sep 2008 21:14:36 -0400 Subject: [Tutor] __init__ arguments storage In-Reply-To: <10ea1c60809201330yfb15ddew43661f724f3b319d@mail.gmail.com> References: <10ea1c60809201032s69c92ab8ib72191cd7cd0f519@mail.gmail.com> <1c2a2c590809201244xf578a75yb16371223b85f68a@mail.gmail.com> <10ea1c60809201330yfb15ddew43661f724f3b319d@mail.gmail.com> Message-ID: <1c2a2c590809211814k64443144n64371d7c1c8159bb@mail.gmail.com> Here is another writeup on __new__() and __init__(); http://www.voidspace.org.uk/python/weblog/arch_d7_2008_09_20.shtml#e1014 Kent From ruivaldo at gmail.com Mon Sep 22 05:15:44 2008 From: ruivaldo at gmail.com (rui) Date: Mon, 22 Sep 2008 00:15:44 -0300 Subject: [Tutor] a simple keyboard art,,, gone wrong! In-Reply-To: <48D55CD5.5030401@lorettotel.net> References: <48D55CD5.5030401@lorettotel.net> Message-ID: Try to put a 'r' letter before the opening-quote: print \ r""" _____ ___ ___ ___ _____ / ___| / | / |/ | | ___| | | / /| | / /| /| | | |__ | | _ / __| | / / |__/ | | | __| | |_| | / / | | / / | | | |___ \_____/ /_/ |_| /_/ |_| |_____| _____ _ __ ______ _____ / _ \ | | / / | ____| | _ \ | | | | | | / / | |__ | |_| | | | | | | | / / | __| | _ / | |_| | | |/ / | |____ | | \ \ \_____/ |___/ |______| |_| \_\ """ Python was trying to interpret the '\'. Cheers. [ rui ] From dextrous85 at gmail.com Mon Sep 22 08:36:28 2008 From: dextrous85 at gmail.com (vishwajeet singh) Date: Mon, 22 Sep 2008 12:06:28 +0530 Subject: [Tutor] Exhaustive Enumeration In-Reply-To: <48D6B134.4030008@embarqmail.com> References: <20080921133847.ecgsf6vsskc0s88g@webmail4.isis.unc.edu> <48D6A040.8000202@embarqmail.com> <515008f10809211313r48da1ba4i4bd06e0d4a0f57e4@mail.gmail.com> <48D6B134.4030008@embarqmail.com> Message-ID: <5487b3060809212336t273e66dfle051da1ef3bcec40@mail.gmail.com> Thanks for the link it's really useful :) On Mon, Sep 22, 2008 at 2:10 AM, Robert Berman wrote: > That it is. > > Jaggo wrote: > > Lol. And here I said to myself only, "What a nice challenge". > > On Sun, Sep 21, 2008 at 10:28 PM, Robert Berman wrote: > >> A very interesting problem. Given this is homework, I am not sure what >> it is you want. >> >> Do you want the solution coded and tested? >> Do you want this to include two or three algorithms optimized for speed as >> well as accuracy? >> >> I think the problem is well enough defined so that you do not need any >> clarification of what it is your professor wants from you. >> >> If you would like some help finding a solution set, perhaps you would >> consider submitting some of your own solutions and commentary as to where >> your ideas are breaking down. Then, probably, a number of people will jump >> in to help you. >> >> Robert >> >> btkuhn at email.unc.edu wrote: >> >> This is from the MIT Opencourseware intro to computer science course, >> which I've been working my way through. I understand what needs to be done >> (I think), which is basically to test each possibility and return the list >> of states with the most electoral votes that can be paid for under the >> campaign budget. I am just at a loss as to how to do it, and I've been >> thinking about it all weekend. Here is the problem I am referring to. One >> assumption is that every $1 of money spent in a state translates into a >> popular vote. Many thanks for any suggestions. Also, the next part of the >> question asks to do the same thing using "Branch and Bound", which I also >> anticipate having trouble with. If I haven't described things sufficiently, >> the complete problem is available at: >> >> >> http://ocw.mit.edu/OcwWeb/Electrical-Engineering-and-Computer-Science/6-00Fall-2007/Assignments/index.htm, problem 5. >> >> Complete and test this function according to her specification below. Note >> that she was using exhaustive >> enumeration to compute the result. Your friend assured you that the >> function needs no more than 5 additional >> lines of code. >> >> # Problem 2: Exhaustive enumeration >> def finance_campaign_ee(budget, free_states): """ >> Takes a budget, in dollars, and a list of available states, as a >> list of dictionaries. >> >> Computes and returns the list of states that maximizes the total >> number of electoral votes such that these states can be acquired >> on the budget. Returns an empty list if no states can be acquired. >> """ >> cheap_states=[] >> for s in free_states: >> if s['pop'] <= budget: >> cheap_states.append(s) >> >> # Base case >> if len(cheap_states)==0: >> res_list=[] >> # Recursive case >> else: >> curr_state=cheap_states[0] >> other_states=cheap_states[1:] >> >> inc_states=finance_campaign_ee( budget-curr_state['pop'], >> other_states) >> inc_states.append(curr_state) >> inc_evotes=total_evotes(inc_states) >> >> excl_states=finance_campaign_ee( budget, other_states ) >> excl_evotes=total_evotes(excl_states) >> >> # ... your code goes here ... >> res_list = return res_list >> >> _______________________________________________ >> 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 > > -- Cheers, Vishwajeet http://www.singhvishwajeet.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From tlatsas2000 at gmail.com Mon Sep 22 16:16:48 2008 From: tlatsas2000 at gmail.com (Tasos Latsas) Date: Mon, 22 Sep 2008 17:16:48 +0300 Subject: [Tutor] optparse example Message-ID: <48D7A8D0.2070106@gmail.com> Hello list, I tried the optparse example from the python library reference and it doesn't seem to work..what am I doing wrong? I keep getting the "incorrect number of arguments" message although i use the correct number.. The example is here : http://docs.python.org/lib/optparse-putting-it-all-together.html if i edit the code and write: print parser.parse_args() I get: (, []) as you can see the argument list is empty I run the program as ./parser.py -q (i also tried 'python parser.py -q' but didnt help) Thank you in advance From carlos.hanson at gmail.com Mon Sep 22 16:53:07 2008 From: carlos.hanson at gmail.com (Carlos Hanson) Date: Mon, 22 Sep 2008 07:53:07 -0700 Subject: [Tutor] optparse example In-Reply-To: <48D7A8D0.2070106@gmail.com> References: <48D7A8D0.2070106@gmail.com> Message-ID: On Mon, Sep 22, 2008 at 7:16 AM, Tasos Latsas wrote: > Hello list, > I tried the optparse example from the python library reference and it > doesn't seem to work..what am I doing wrong? > I keep getting the "incorrect number of arguments" message although i > use the correct number.. > > The example is here : > http://docs.python.org/lib/optparse-putting-it-all-together.html > > if i edit the code and write: > print parser.parse_args() > > I get: > (, []) > > as you can see the argument list is empty > I run the program as ./parser.py -q > (i also tried 'python parser.py -q' but didnt help) > > Thank you in advance > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > (I failed to send my original reply to the list) Notice the Usage message when you run the example: $ python parser.py -q Usage: parser.py [options] arg parser.py: error: incorrect number of arguments "-q" is an option, not an argument. If you look at the example, you add options: parser.add_option("-q", ... The arguments are everything left over. In this case, they are not used, but they are required. The following runs without issue: $ python parser.py junk $ python parser.py -v junk reading None... The bottom line is the example is just an example, not something you can use as is. -- Carlos Hanson From dfjennings at gmail.com Mon Sep 22 16:53:55 2008 From: dfjennings at gmail.com (Don Jennings) Date: Mon, 22 Sep 2008 10:53:55 -0400 Subject: [Tutor] optparse example In-Reply-To: <48D7A8D0.2070106@gmail.com> References: <48D7A8D0.2070106@gmail.com> Message-ID: <22ce67f0809220753qfa4e76tfef9f582e3eea125@mail.gmail.com> On 9/22/08, Tasos Latsas wrote: > Hello list, > I tried the optparse example from the python library reference and it > doesn't seem to work..what am I doing wrong? > I keep getting the "incorrect number of arguments" message although i > use the correct number.. Actually, you aren't using the correct number of arguments for the code as written. This line: if len(args) != 1: parser.error("incorrect number of arguments") checks to see if the arguments, not to be confused with the options, are greater than one. So, one way you might call the script would be: python parser.py somefile.txt Take care, Don From jeremiah.jester at panasonic.aero Mon Sep 22 18:34:54 2008 From: jeremiah.jester at panasonic.aero (jeremiah) Date: Mon, 22 Sep 2008 09:34:54 -0700 Subject: [Tutor] Exhaustive Enumeration In-Reply-To: <48D6AF16.80601@embarqmail.com> References: <20080921133847.ecgsf6vsskc0s88g@webmail4.isis.unc.edu> <48D6A040.8000202@embarqmail.com> <20080921154327.48ndwt5c4kcwgwok@webmail4.isis.unc.edu> <48D6AF16.80601@embarqmail.com> Message-ID: <1222101294.3557.4.camel@jeremiah-laptop> Download links... 1) Think Python (about 240 pages)--Allen Downey and http://www.greenteapress.com/thinkpython/thinkpython.html > 2) A Byte of Python (about 100 pages) http://www.swaroopch.com/notes/Python#Download On Sun, 2008-09-21 at 16:31 -0400, Robert Berman wrote: > First, thank you for the explanation. > > I admire your desire to learn bull riding by jumping on the monster's > back. The problem with assignments based on a course is that many > professors and associates have learned the only way to insure student > class attendance is to obfuscate the assignment list. I think you may > be missing some important information available to anyone with the > class syllabus or the notes of an above average student. It could > also be that at this time this assignment might be more than you > should tackle. You certainly know more about your own skill level than > anyone else. > > The best possible suggestions I have to offer is to download two > python tutorial texts (neither of which is quick to read or > superficial in content). > > 1) Think Python (about 240 pages)--Allen Downey and > > 2) A Byte of Python (about 100 pages) > > I use a Byte of Python as a very good reference manual. Think Python > has a number of problems after each chapter as well as some problems > that will make your brain itch as you solve them. Think Python might > be a very good way to get into the functionalities that might make > your MIT teaser a bit more manageable. > > In any case, best of luck no matter which path you pursue. > > Robert > > > > btkuhn at email.unc.edu wrote: > > I'm actually not enrolled in the course; MIT puts some of its course > > materials available online as a general resource. I am out of school > > and trying to teach myself python on my own. I'm very much a > > beginner, and since I'm not privy to the lectures or notes from this > > course I have to fill in things from other sources. Basically, with > > respect to this problem, I'm at a loss as to how to approach it. My > > first thought was to use some sort of nested for loop structure to > > iterate through each possible state combination, but I don't think > > this is possible, since a for loop would just test for, for > > instance, (state 1 and 2, state 1 and 3, state 1 and 4, etc.) and > > not (state 1 and 3, state 1 and 2 and 3, etc.). I could maybe make > > it work for a very small number of states, but if you are taking 10 > > states as arguments I don't see a way this could work. Also, the way > > the question is asked seems to imply that the new code will go after > > the existing code, and also that it will be only about five lines. > > I'm guessing that maybe some kind of recursion is required but I > > really don't know, and recursion is a new concept to me as well. > > > > Thanks! > > > > Quoting Robert Berman : > > > > > A very interesting problem. Given this is homework, I am > > > not > > > sure what it is you want. > > > > > > Do you want the solution coded and tested? > > > Do you want this to include two or three algorithms optimized for > > > speed as well as accuracy? > > > > > > I think the problem is well enough defined so that you do not > > > need > > > any clarification of what it is your professor wants from you. > > > > > > If you would like some help finding a solution set, perhaps you > > > would consider submitting some of your own solutions and > > > commentary > > > as to where your ideas are breaking down. Then, probably, a number > > > of > > > people will jump in to help you. > > > > > > Robert > > > > > > btkuhn at email.unc.edu wrote: This is from the MIT Opencourseware > > > intro > > > to computer science course, which I've been working my way > > > through. I > > > understand what needs to be done (I think), which is basically to > > > test each possibility and return the list of states with the most > > > electoral votes that can be paid for under the campaign budget. I > > > am > > > just at a loss as to how to do it, and I've been thinking about > > > it > > > all weekend. Here is the problem I am referring to. One assumption > > > is > > > that every $1 of money spent in a state translates into a popular > > > vote. Many thanks for any suggestions. Also, the next part of the > > > question asks to do the same thing using "Branch and Bound", which > > > I > > > also anticipate having trouble with. If I haven't described > > > things > > > sufficiently, the complete problem is available at: > > > > > > http://ocw.mit.edu/OcwWeb/Electrical-Engineering-and-Computer-Science/6-00Fall-2007/Assignments/index.htm > > > , problem 5. > > > > > > Complete and test this function according to her specification > > > below. > > > Note that she was using exhaustive > > > enumeration to compute the result. Your friend assured you that > > > the > > > function needs no more than 5 additional > > > lines of code. > > > > > > # Problem 2: Exhaustive enumeration > > > def finance_campaign_ee(budget, free_states): """ > > > Takes a budget, in dollars, and a list of available states, as > > > a > > > list of dictionaries. > > > > > > Computes and returns the list of states that maximizes the > > > total > > > number of electoral votes such that these states can be > > > acquired > > > on the budget. Returns an empty list if no states can be > > > acquired. > > > > > > """ > > > cheap_states=[] > > > for s in free_states: > > > if s['pop'] <= budget: > > > cheap_states.append(s) > > > > > > # Base case > > > if len(cheap_states)==0: > > > res_list=[] > > > # Recursive case > > > else: > > > curr_state=cheap_states[0] > > > other_states=cheap_states[1:] > > > > > > inc_states=finance_campaign_ee( budget-curr_state['pop'], > > > other_states) > > > inc_states.append(curr_state) > > > inc_evotes=total_evotes(inc_states) > > > > > > excl_states=finance_campaign_ee( budget, other_states ) > > > excl_evotes=total_evotes(excl_states) > > > > > > # ... your code goes here ... > > > res_list = return res_list > > > > > > _______________________________________________ > > > 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 Disclaimer: The information contained in this transmission, including any attachments, may contain confidential information of Panasonic Avionics Corporation. This transmission is intended only for the use of the addressee(s) listed above. Unauthorized review, dissemination or other use of the information contained in this transmission is strictly prohibited. If you have received this transmission in error or have reason to believe you are not authorized to receive it, please notify the sender by return email and promptly delete the transmission. From dineshbvadhia at hotmail.com Tue Sep 23 05:11:58 2008 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Mon, 22 Sep 2008 20:11:58 -0700 Subject: [Tutor] array of different datatypes Message-ID: I have looked (honestly!) and cannot see an array structure to allow different datatypes per column. I need a 2 column array with column 1 = an integer and column 2 = chars, and after populating the array, sort on column 2 with column 1 sorted relatively. Thanks! Dinesh -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at alchemy.com Tue Sep 23 05:16:29 2008 From: steve at alchemy.com (Steve Willoughby) Date: Mon, 22 Sep 2008 20:16:29 -0700 Subject: [Tutor] array of different datatypes In-Reply-To: References: Message-ID: <48D85F8D.2040000@alchemy.com> Dinesh B Vadhia wrote: > I have looked (honestly!) and cannot see an array structure to allow different datatypes per column. I need a 2 column array with column 1 = an integer and column 2 = chars, and after populating the array, sort on column 2 with column 1 sorted relatively. If by "array" you mean a regular Python list, the data type of every single element may be different. So it's just how lists always work. a = [[1, 'hello'], [2, 'world'], [42, 'fish'], ] > Thanks! > > Dinesh > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From dineshbvadhia at hotmail.com Tue Sep 23 05:33:03 2008 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Mon, 22 Sep 2008 20:33:03 -0700 Subject: [Tutor] array of different datatypes In-Reply-To: <48D85F8D.2040000@alchemy.com> References: <48D85F8D.2040000@alchemy.com> Message-ID: Thanks Steve. How do you sort on the second element of each list to get: a' = [[42, 'fish'], [1, 'hello'] [2, 'world'] ] From: Steve Willoughby Sent: Monday, September 22, 2008 8:16 PM To: Dinesh B Vadhia Cc: tutor at python.org Subject: Re: [Tutor] array of different datatypes Dinesh B Vadhia wrote: > I have looked (honestly!) and cannot see an array structure to allow different datatypes per column. I need a 2 column array with column 1 = an integer and column 2 = chars, and after populating the array, sort on column 2 with column 1 sorted relatively. If by "array" you mean a regular Python list, the data type of every single element may be different. So it's just how lists always work. a = [[1, 'hello'], [2, 'world'], [42, 'fish'], ] > Thanks! > > Dinesh > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at alchemy.com Tue Sep 23 05:50:52 2008 From: steve at alchemy.com (Steve Willoughby) Date: Mon, 22 Sep 2008 20:50:52 -0700 Subject: [Tutor] array of different datatypes In-Reply-To: References: <48D85F8D.2040000@alchemy.com> Message-ID: <48D8679C.1020709@alchemy.com> Dinesh B Vadhia wrote: > Thanks Steve. How do you sort on the second element of each list to get: > > a' = [[42, 'fish'], > [1, 'hello'] > [2, 'world'] > ] something like this would do the trick: a_prime = sorted(a, key=(lambda i: i[1])) sorted(a) returns a new list consisting of the elements in a but in sorted order. the key= parameter says how to derive the sort key from any given element; in this case, the elements being sorted are themselves lists, and element #1 in the sub-list (a.k.a. "row") is the key. > > > > From: Steve Willoughby > Sent: Monday, September 22, 2008 8:16 PM > To: Dinesh B Vadhia > Cc: tutor at python.org > Subject: Re: [Tutor] array of different datatypes > > > Dinesh B Vadhia wrote: >> I have looked (honestly!) and cannot see an array structure to allow different datatypes per column. I need a 2 column array with column 1 = an integer and column 2 = chars, and after populating the array, sort on column 2 with column 1 sorted relatively. > > > If by "array" you mean a regular Python list, the data type of > every single element may be different. So it's just how lists > always work. > > a = [[1, 'hello'], > [2, 'world'], > [42, 'fish'], > ] > >> Thanks! >> >> Dinesh >> >> >> >> ------------------------------------------------------------------------ >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor > > From reed at reedobrien.com Tue Sep 23 14:27:24 2008 From: reed at reedobrien.com (Reed O'Brien) Date: Tue, 23 Sep 2008 08:27:24 -0400 Subject: [Tutor] array of different datatypes In-Reply-To: <48D8679C.1020709@alchemy.com> References: <48D85F8D.2040000@alchemy.com> <48D8679C.1020709@alchemy.com> Message-ID: <22BA95DA-7F1F-4476-B546-C1A3D31C4ED3@reedobrien.com> On Sep 22, 2008, at 11:50 PM, Steve Willoughby wrote: > Dinesh B Vadhia wrote: >> Thanks Steve. How do you sort on the second element of each list >> to get: >> a' = [[42, 'fish'], >> [1, 'hello'] >> [2, 'world'] >> ] > > something like this would do the trick: > > a_prime = sorted(a, key=(lambda i: i[1])) > > sorted(a) returns a new list consisting of the elements in a > but in sorted order. the key= parameter says how to derive the > sort key from any given element; in this case, the elements > being sorted are themselves lists, and element #1 in the sub-list > (a.k.a. "row") is the key. try itemgetter: In [1]: a = [[42, 'fish'], ...: [2, 'world'], ...: [1, 'hello']] In [2]: from operator import itemgetter In [3]: sorted(a, key=itemgetter(1)) Out[3]: [[42, 'fish'], [1, 'hello'], [2, 'world']] > > >> From: Steve Willoughby Sent: Monday, September 22, 2008 8:16 PM >> To: Dinesh B Vadhia Cc: tutor at python.org Subject: Re: [Tutor] array >> of different datatypes >> Dinesh B Vadhia wrote: >>> I have looked (honestly!) and cannot see an array structure to >>> allow different datatypes per column. I need a 2 column array >>> with column 1 = an integer and column 2 = chars, and after >>> populating the array, sort on column 2 with column 1 sorted >>> relatively. >> If by "array" you mean a regular Python list, the data type of >> every single element may be different. So it's just how lists >> always work. >> a = [[1, 'hello'], >> [2, 'world'], >> [42, 'fish'], >> ] >>> Thanks! >>> >>> Dinesh >>> >>> >>> >>> ------------------------------------------------------------------------ >>> >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From john.toliver at gmail.com Tue Sep 23 17:16:42 2008 From: john.toliver at gmail.com (John Toliver) Date: Tue, 23 Sep 2008 11:16:42 -0400 Subject: [Tutor] A question about how python handles numbers larger than it's 32 bit limit Message-ID: <1222183003.2267.57.camel@john-laptop> Greetings, The book I have says when you anticipate that you will be working with numbers larger than what python can handle, you place an "L" after the number to signal python to treat it as a large number. Does this "treating" of the number only mean that Python won't try to represent the number internally as a 32bit integer? Python still appears to be representing the number only with an L behind it so what is happening to the number then. Is the L behind the number telling python to handle this large number in HEX instead which would fit into the 32 bit limit? thanks in advance, John T From adam.jtm30 at gmail.com Tue Sep 23 17:24:48 2008 From: adam.jtm30 at gmail.com (Adam Bark) Date: Tue, 23 Sep 2008 16:24:48 +0100 Subject: [Tutor] A question about how python handles numbers larger than it's 32 bit limit In-Reply-To: <1222183003.2267.57.camel@john-laptop> References: <1222183003.2267.57.camel@john-laptop> Message-ID: 2008/9/23 John Toliver > Greetings, > > The book I have says when you anticipate that you will be working with > numbers larger than what python can handle, you place an "L" after the > number to signal python to treat it as a large number. Does this > "treating" of the number only mean that Python won't try to represent > the number internally as a 32bit integer? Python still appears to be > representing the number only with an L behind it so what is happening to > the number then. Is the L behind the number telling python to handle > this large number in HEX instead which would fit into the 32 bit limit? > > thanks in advance, > > John T The L stands for long integer and means that it will usually use twice the space of a regular integer so in this case 64bits. HTH Adam. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at alchemy.com Tue Sep 23 17:33:44 2008 From: steve at alchemy.com (Steve Willoughby) Date: Tue, 23 Sep 2008 08:33:44 -0700 Subject: [Tutor] A question about how python handles numbers larger than it's 32 bit limit In-Reply-To: References: <1222183003.2267.57.camel@john-laptop> Message-ID: <20080923153344.GA44946@dragon.alchemy.com> On Tue, Sep 23, 2008 at 04:24:48PM +0100, Adam Bark wrote: > 2008/9/23 John Toliver > > > Greetings, > > > > The book I have says when you anticipate that you will be working with > > numbers larger than what python can handle, you place an "L" after the > > number to signal python to treat it as a large number. Does this > > "treating" of the number only mean that Python won't try to represent > > the number internally as a 32bit integer? Python still appears to be > > representing the number only with an L behind it so what is happening to > > the number then. Is the L behind the number telling python to handle > > this large number in HEX instead which would fit into the 32 bit limit? > > > > thanks in advance, > > > > John T > > > The L stands for long integer and means that it will usually use twice the > space of a regular integer so in this case 64bits. s/64bits/infinite/ Python is not C :) In Python, long integers are unlimited precision values, so you can accurately store a number like 32432471704327419865487605452750436198382489276811235713483294872389573259823495174875098750298475019874230984710985743980572840957432098578029107923471 if you want to. They aren't handled as *fast* as regular native integer values (which are implemented as the C "long int" type internally in CPython, so they may be 32 bits or possibly(?) longer), but they are unlimited in size. Python will automatically promote an integer to a long when it gets too big, so you don't *have* to put the L on the end or use long() to construct one explicitly, unless you really want it to be long type from the beginning. -- Steve Willoughby | Using billion-dollar satellites steve at alchemy.com | to hunt for Tupperware. From kent37 at tds.net Tue Sep 23 18:13:01 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 23 Sep 2008 12:13:01 -0400 Subject: [Tutor] A question about how python handles numbers larger than it's 32 bit limit In-Reply-To: <1222183003.2267.57.camel@john-laptop> References: <1222183003.2267.57.camel@john-laptop> Message-ID: <1c2a2c590809230913v1a2000c1s47b82165eaf1d26c@mail.gmail.com> On Tue, Sep 23, 2008 at 11:16 AM, John Toliver wrote: > Greetings, > > The book I have says when you anticipate that you will be working with > numbers larger than what python can handle, you place an "L" after the > number to signal python to treat it as a large number. Your book is a little old, the "L" has not been required since Python 2.4. Kent From mwalsh at mwalsh.org Tue Sep 23 21:07:00 2008 From: mwalsh at mwalsh.org (Martin Walsh) Date: Tue, 23 Sep 2008 14:07:00 -0500 Subject: [Tutor] array of different datatypes In-Reply-To: <22BA95DA-7F1F-4476-B546-C1A3D31C4ED3@reedobrien.com> References: <48D85F8D.2040000@alchemy.com> <48D8679C.1020709@alchemy.com> <22BA95DA-7F1F-4476-B546-C1A3D31C4ED3@reedobrien.com> Message-ID: <48D93E54.1010404@mwalsh.org> Reed O'Brien wrote: > On Sep 22, 2008, at 11:50 PM, Steve Willoughby wrote: > >> Dinesh B Vadhia wrote: >>> Thanks Steve. How do you sort on the second element of each list to >>> get: >>> a' = [[42, 'fish'], >>> [1, 'hello'] >>> [2, 'world'] >>> ] >> >> something like this would do the trick: >> >> a_prime = sorted(a, key=(lambda i: i[1])) >> >> sorted(a) returns a new list consisting of the elements in a >> but in sorted order. the key= parameter says how to derive the >> sort key from any given element; in this case, the elements >> being sorted are themselves lists, and element #1 in the sub-list >> (a.k.a. "row") is the key. > > try itemgetter: > > In [1]: a = [[42, 'fish'], > ...: [2, 'world'], > ...: [1, 'hello']] > > In [2]: from operator import itemgetter > In [3]: sorted(a, key=itemgetter(1)) > > Out[3]: [[42, 'fish'], [1, 'hello'], [2, 'world']] > >>> From: Steve Willoughby Sent: Monday, September 22, 2008 8:16 PM >>> To: Dinesh B Vadhia Cc: tutor at python.org Subject: Re: [Tutor] array >>> of different datatypes >>> Dinesh B Vadhia wrote: >>>> I have looked (honestly!) and cannot see an array structure to allow >>>> different datatypes per column. I need a 2 column array with column >>>> 1 = an integer and column 2 = chars, and after populating the array, >>>> sort on column 2 with column 1 sorted relatively. itemgetter also allows you to do something like this (2.5 and later)... In [1]: a = [[42, 'fish'], [1, 'hello'], [2, 'world'], [41, 'fish']] In [2]: sorted(a, key=itemgetter(1, 0)) Out[2]: [[41, 'fish'], [42, 'fish'], [1, 'hello'], [2, 'world']] ... which would give you the "relative" sort you asked about for column 1. But at that point, if I had control over the input data structure -- I would probably reverse the order, and then just use a vanilla sorted call without any key arg. >>> If by "array" you mean a regular Python list, the data type of >>> every single element may be different. So it's just how lists >>> always work. >>> a = [[1, 'hello'], >>> [2, 'world'], >>> [42, 'fish'], >>> ] >>>> Thanks! >>>> >>>> Dinesh From jeremiah.jester at panasonic.aero Tue Sep 23 23:38:29 2008 From: jeremiah.jester at panasonic.aero (jeremiah) Date: Tue, 23 Sep 2008 14:38:29 -0700 Subject: [Tutor] image processing Message-ID: <1222205909.6617.4.camel@jeremiah-laptop> I'm trying to do simple image manipulation but am getting an error. any ideas what i am doing wrong here? Thanks JJ #!/usr/bin/python import ImageFilter,Image name="test.jpg" file=open("./"+name,"w") pic=Image.open(file) pic.rotate(45) pic.save("new_" + name) pic.show() the error: Traceback (most recent call last): File "image_filter.py", line 7, in pic=Image.open(file) File "/usr/lib/python2.5/site-packages/PIL/Image.py", line 1893, in open prefix = fp.read(16) IOError: [Errno 9] Bad file descriptor Disclaimer: The information contained in this transmission, including any attachments, may contain confidential information of Panasonic Avionics Corporation. This transmission is intended only for the use of the addressee(s) listed above. Unauthorized review, dissemination or other use of the information contained in this transmission is strictly prohibited. If you have received this transmission in error or have reason to believe you are not authorized to receive it, please notify the sender by return email and promptly delete the transmission. From malaclypse2 at gmail.com Tue Sep 23 23:52:56 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Tue, 23 Sep 2008 17:52:56 -0400 Subject: [Tutor] image processing In-Reply-To: <1222205909.6617.4.camel@jeremiah-laptop> References: <1222205909.6617.4.camel@jeremiah-laptop> Message-ID: <16651e80809231452w1ea4e494o851d0fdc046bf1b@mail.gmail.com> On Tue, Sep 23, 2008 at 5:38 PM, jeremiah wrote: > I'm trying to do simple image manipulation but am getting an error. any > ideas what i am doing wrong here? > > file=open("./"+name,"w") > pic=Image.open(file) You're opening the file for "w"riting, then asking PIL to read it. That's not going to work. In fact, there's no reason for you to open the file yourself. Just pass the filename, like this: pic=Image.open(name) -- Jerry From emile at fenx.com Tue Sep 23 23:48:49 2008 From: emile at fenx.com (Emile van Sebille) Date: Tue, 23 Sep 2008 14:48:49 -0700 Subject: [Tutor] image processing In-Reply-To: <1222205909.6617.4.camel@jeremiah-laptop> References: <1222205909.6617.4.camel@jeremiah-laptop> Message-ID: jeremiah wrote: > I'm trying to do simple image manipulation but am getting an error. any > ideas what i am doing wrong here? > > Thanks > JJ > > #!/usr/bin/python > import ImageFilter,Image > name="test.jpg" > file=open("./"+name,"w") Right here you're opening the file in write mode, in effect creating a new file ready to be written to. You probably want to use mode 'rb' HTH, Emile > pic=Image.open(file) > pic.rotate(45) > pic.save("new_" + name) > pic.show() > > the error: > > Traceback (most recent call last): > File "image_filter.py", line 7, in > pic=Image.open(file) > File "/usr/lib/python2.5/site-packages/PIL/Image.py", line 1893, in > open > prefix = fp.read(16) > IOError: [Errno 9] Bad file descriptor > > > > > Disclaimer: The information contained in this transmission, including any > attachments, may contain confidential information of Panasonic Avionics > Corporation. This transmission is intended only for the use of the > addressee(s) listed above. Unauthorized review, dissemination or other use > of the information contained in this transmission is strictly prohibited. > If you have received this transmission in error or have reason to believe > you are not authorized to receive it, please notify the sender by return > email and promptly delete the transmission. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From hkroh at Anadigics.com Wed Sep 24 00:13:31 2008 From: hkroh at Anadigics.com (Herold Kroh) Date: Tue, 23 Sep 2008 18:13:31 -0400 Subject: [Tutor] please explain this error Message-ID: Hi all, New to this python thing.. I am trying to run a python script to convert sccs data to svn data (sccs2svn.py). Downloaded this off the web, and it sounds like it should do what I need it to, but I can not seem to get it to run. I keep getting the following error message: Traceback (most recent call last): File "/home/hkroh/bin/python_scripts/sccs_te.py", line 481, in ? core.run_app(run) File "/usr/src/build/554290-x86_64/install/usr/lib/python2.3/site-packages/sv n/core.py", line 33, in run_app File "/home/hkroh/bin/python_scripts/sccs_te.py", line 418, in run interface.add(i) File "/home/hkroh/bin/python_scripts/sccs_te.py", line 242, in add print self._commit(revision, delta.getDate(), transaction, subpool) File "/home/hkroh/bin/python_scripts/sccs_te.py", line 162, in _commit return repos.svn_repos_fs_commit_txn(self.repos_ptr, txn, subpool) libsvn._core.SubversionException: ("Can't remove 'SVN_skill/db/transactions/0-1.txn': Directory not empty", 39) I go to the offending directory and I see a .nfs file. When I touch the file, it disappears. I do not know enough about python, or the add on module that is causing this failure. Can someone please point me in the right direction in solving my problem. Please let me know what else you need to know to help with this. Thanks in advance for any help, Herold -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at alchemy.com Wed Sep 24 00:44:56 2008 From: steve at alchemy.com (Steve Willoughby) Date: Tue, 23 Sep 2008 15:44:56 -0700 Subject: [Tutor] please explain this error In-Reply-To: References: Message-ID: <20080923224456.GA64497@dragon.alchemy.com> On Tue, Sep 23, 2008 at 06:13:31PM -0400, Herold Kroh wrote: > libsvn._core.SubversionException: ("Can't remove > 'SVN_skill/db/transactions/0-1.txn': Directory not empty", 39) > > I go to the offending directory and I see a .nfs file. When I > touch the file, it disappears. The problem here is with NFS, really. The .nfs files are how the NFS system handles the case where files are deleted on the fileserver but still open on a client. (Under Unix, a file can still be open and all its data accessed even if deleted from the filesystem... it won't *really* go away until it's closed, too. But NFS doesn't represent that case well so a temporary filename is used.) Unless your Python program is what's holding the offending file(s) open... any idea what's keeping the file in use? -- Steve Willoughby | Using billion-dollar satellites steve at alchemy.com | to hunt for Tupperware. From jopython at gmail.com Wed Sep 24 02:41:16 2008 From: jopython at gmail.com (Joe Python) Date: Tue, 23 Sep 2008 20:41:16 -0400 Subject: [Tutor] Sorting Dictionary of Dictionary by certain Value Message-ID: Hi Pythonistas, I have a large dictionary of dictionary (50,000+ keys) which has a structure as follows: DoD = { 'flintstones' : { 'husband' : "fred", 'pal' : "barney", 'income' : 500, }, 'jetsons' : { 'husband' : "george", 'wife' : "jane", 'his boy' : "elroy", 'income' : 700, }, 'simpsons' : { 'husband' : "homer", 'wife' : "marge", 'kid' : "bart", 'income' : 600, }, }; I want to sort the dictionary by 'income' Is there an efficient way to do the same. Thanks in advance. - Jo -------------- next part -------------- An HTML attachment was scrubbed... URL: From john at fouhy.net Wed Sep 24 02:59:25 2008 From: john at fouhy.net (John Fouhy) Date: Wed, 24 Sep 2008 12:59:25 +1200 Subject: [Tutor] Sorting Dictionary of Dictionary by certain Value In-Reply-To: References: Message-ID: <5e58f2e40809231759h570ef207l2b57909dbef5e98f@mail.gmail.com> 2008/9/24 Joe Python : > Hi Pythonistas, > > I have a large dictionary of dictionary (50,000+ keys) which has a structure > as follows: [snip] > I want to sort the dictionary by 'income' > Is there an efficient way to do the same. Note that you cannot sort a dictionary. The best you can do is build a list containing the dictionary keys in the appropriate order and use the dictionary in combination with that list. You could try this: 1. Build a dictionary mapping income to list of families. 2. Sort keys to this dictionary. 3. Iterate through this sorted list, emitting family names. e.g. from collections import defaultdict familiesByIncome = defaultdict(list) for family in DoD: familiesByIncome[DoD[family]['income']].append(family) incomes = familiesByIncome.keys() incomes.sort() # sorts from lowest to highest familiesSorted = [] for inc in incomes: familiesSorted.extend(familiesByIncome[inc]) ## HTH! -- John. From bill at celestial.net Wed Sep 24 03:09:45 2008 From: bill at celestial.net (Bill Campbell) Date: Tue, 23 Sep 2008 18:09:45 -0700 Subject: [Tutor] Sorting Dictionary of Dictionary by certain Value In-Reply-To: <5e58f2e40809231759h570ef207l2b57909dbef5e98f@mail.gmail.com> References: <5e58f2e40809231759h570ef207l2b57909dbef5e98f@mail.gmail.com> Message-ID: <20080924010945.GA3335@ayn.mi.celestial.com> On Wed, Sep 24, 2008, John Fouhy wrote: >2008/9/24 Joe Python : >> Hi Pythonistas, >> >> I have a large dictionary of dictionary (50,000+ keys) which has a structure >> as follows: >[snip] >> I want to sort the dictionary by 'income' >> Is there an efficient way to do the same. > >Note that you cannot sort a dictionary. The best you can do is build >a list containing the dictionary keys in the appropriate order and use >the dictionary in combination with that list. What you can do is create a class for the objects in the top level dictionary, and create a __cmp__ method in that class using cmp to compare the objects in the dictionary, finally sorting the values. class MyStuff(object): def __init__(self, name, income): self.name = name self.income = int(income) def cmp(self, other): return(cmp((-self.income, self.name), -other.income, other.name)) d = dict( key1 = MyStuff('john', 10000), key2 = MyStuff('bill', 20000), ) vals = d.values() vals.sort() # vals should be sorted by income in descending order and name. Bill -- INTERNET: bill at celestial.com Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way Voice: (206) 236-1676 Mercer Island, WA 98040-0820 Fax: (206) 232-9186 People who relieve others of their money with guns are called robbers. It does not alter the immorality of the act when the income transfer is carried out by government. From bill at celestial.net Wed Sep 24 03:11:23 2008 From: bill at celestial.net (Bill Campbell) Date: Tue, 23 Sep 2008 18:11:23 -0700 Subject: [Tutor] Sorting Dictionary of Dictionary by certain Value In-Reply-To: <20080924010945.GA3335@ayn.mi.celestial.com> References: <5e58f2e40809231759h570ef207l2b57909dbef5e98f@mail.gmail.com> <20080924010945.GA3335@ayn.mi.celestial.com> Message-ID: <20080924011123.GA3511@ayn.mi.celestial.com> On Tue, Sep 23, 2008, Bill Campbell wrote: >On Wed, Sep 24, 2008, John Fouhy wrote: >>2008/9/24 Joe Python : >>> Hi Pythonistas, >>> >>> I have a large dictionary of dictionary (50,000+ keys) which has a structure >>> as follows: >>[snip] >>> I want to sort the dictionary by 'income' >>> Is there an efficient way to do the same. >> >>Note that you cannot sort a dictionary. The best you can do is build >>a list containing the dictionary keys in the appropriate order and use >>the dictionary in combination with that list. > >What you can do is create a class for the objects in the top >level dictionary, and create a __cmp__ method in that class using >cmp to compare the objects in the dictionary, finally sorting the >values. > >class MyStuff(object): > def __init__(self, name, income): > self.name = name > self.income = int(income) Whoops The method below should be def __cmp__ > def cmp(self, other): > return(cmp((-self.income, self.name), -other.income, other.name)) > >d = dict( > key1 = MyStuff('john', 10000), > key2 = MyStuff('bill', 20000), >) > >vals = d.values() >vals.sort() ># vals should be sorted by income in descending order and name. > >Bill >-- >INTERNET: bill at celestial.com Bill Campbell; Celestial Software LLC >URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way >Voice: (206) 236-1676 Mercer Island, WA 98040-0820 >Fax: (206) 232-9186 > >People who relieve others of their money with guns are called robbers. It >does not alter the immorality of the act when the income transfer is >carried out by government. >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > -- Bill -- INTERNET: bill at celestial.com Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way Voice: (206) 236-1676 Mercer Island, WA 98040-0820 Fax: (206) 232-9186 Microsoft is to computers what Phillip Morris is to lungs. From bermanrl at embarqmail.com Wed Sep 24 03:27:21 2008 From: bermanrl at embarqmail.com (Robert Berman) Date: Tue, 23 Sep 2008 21:27:21 -0400 Subject: [Tutor] Sorting Dictionary of Dictionary by certain Value In-Reply-To: References: Message-ID: <48D99779.8070901@embarqmail.com> An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Wed Sep 24 04:02:09 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Tue, 23 Sep 2008 19:02:09 -0700 Subject: [Tutor] How Match a Dot? Message-ID: <48D99FA1.2070302@sbcglobal.net> An HTML attachment was scrubbed... URL: From kent37 at tds.net Wed Sep 24 04:12:15 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 23 Sep 2008 22:12:15 -0400 Subject: [Tutor] How Match a Dot? In-Reply-To: <48D99FA1.2070302@sbcglobal.net> References: <48D99FA1.2070302@sbcglobal.net> Message-ID: <1c2a2c590809231912u76c97c22q8a74c9d7f9d20fe4@mail.gmail.com> On Tue, Sep 23, 2008 at 10:02 PM, Wayne Watson wrote: > How do I match a dot in, for example, abc.txt? I want to match it exactly. > There must be some sort of escape. Assuming you want to match in a regular expression, use \ as an escape and use raw strings. In [40]: import re In [41]: m=re.search(r'\.', 'abc.de') In [43]: m.start() Out[43]: 3 Kent From kent37 at tds.net Wed Sep 24 04:18:30 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 23 Sep 2008 22:18:30 -0400 Subject: [Tutor] Sorting Dictionary of Dictionary by certain Value In-Reply-To: References: Message-ID: <1c2a2c590809231918m68729826n3ac7ffe57320bf2@mail.gmail.com> On Tue, Sep 23, 2008 at 8:41 PM, Joe Python wrote: > Hi Pythonistas, > > I have a large dictionary of dictionary (50,000+ keys) which has a structure > as follows: > DoD = { > 'flintstones' : { > 'husband' : "fred", > 'pal' : "barney", > 'income' : 500, > }, > 'jetsons' : { > 'husband' : "george", > 'wife' : "jane", > 'his boy' : "elroy", > 'income' : 700, > }, > 'simpsons' : { > 'husband' : "homer", > 'wife' : "marge", > 'kid' : "bart", > 'income' : 600, > }, > }; > > I want to sort the dictionary by 'income' > Is there an efficient way to do the same. As has been pointed out, you can't sort a dictionary, it is unordered. You can sort the list of key, value pairs. The simplest way is to make a key function that extracts the value on which to sort. The key, value pairs will look like ('flintstones', { 'husband' : "fred", 'pal' : "barney", 'income' : 500, ) You want to sort on the 'income' element of the value; this key function will work: def key(item): return item[1]['income'] Then sort with sorted(DoD.iteritems(), key=key) Kent From sierra_mtnview at sbcglobal.net Wed Sep 24 05:05:42 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Tue, 23 Sep 2008 20:05:42 -0700 Subject: [Tutor] How Match a Dot? In-Reply-To: <1c2a2c590809231912u76c97c22q8a74c9d7f9d20fe4@mail.gmail.com> References: <48D99FA1.2070302@sbcglobal.net> <1c2a2c590809231912u76c97c22q8a74c9d7f9d20fe4@mail.gmail.com> Message-ID: <48D9AE86.2010603@sbcglobal.net> An HTML attachment was scrubbed... URL: From sudhir.kumar at brainwavelive.com Wed Sep 24 08:41:04 2008 From: sudhir.kumar at brainwavelive.com (sudhir.kumar at brainwavelive.com) Date: Tue, 23 Sep 2008 23:41:04 -0700 Subject: [Tutor] WHAT IS THE DIFFERENCE BETWEEN FILTER AND REDUCE FUNCTION Message-ID: <20080923234104.anpr0spltogos4o8@webmail.brainwavelive.com> From steve at alchemy.com Wed Sep 24 09:40:13 2008 From: steve at alchemy.com (Steve Willoughby) Date: Wed, 24 Sep 2008 00:40:13 -0700 Subject: [Tutor] WHAT IS THE DIFFERENCE BETWEEN FILTER AND REDUCE FUNCTION In-Reply-To: <20080923234104.anpr0spltogos4o8@webmail.brainwavelive.com> References: <20080923234104.anpr0spltogos4o8@webmail.brainwavelive.com> Message-ID: <48D9EEDD.7070100@alchemy.com> Warning: this is going to look *a lot* better if you view it in a fixed-width font so things line up properly. Both functions apply a function to a list of values, but they do so in different ways. filter() applies a function to each element of a list in turn, returning a new list containing only those elements from the original list for which the function returned True (when given the element as the function argument). In effect, it "filters" a list, like a physical filter would allow some particles to pass and catch others. Only those elements meeting a certain criteria pass through the filter. def is_odd(i): return i%2 != 0 a = [1, 2, 3, 4] b = filter(is_odd, a) b now contains [1, 3] The same thing could be done using lambda instead of defining a named function, of course: a = [1, 2, 3, 4] b = filter(lambda i: i%2!=0, a) The reduce() function does something quite different. It reduces a list of values to a single result by repeatedly applying the result of the transformation to the next one, adding a new element each time. This way you get a cumulative effect. The most obvious example of such a function (to me, anyway) is a factorial function. n! = 1*2*3*4*...*n So you could implement the factorial function in Python using iteration, like this: def factorial(n): result = 0 for i in range(1,n+1): result *= i return result But we could also do this with reduce(), given a list of integers to multiply: def product(x, y): return x * y a = [1, 2, 3, 4, 5, 6] b = reduce(product, a) b is now 720. What this will do is to start with the first two elements of a, and pass them to the product() function, then pass the result of that operation along with the next element to the product() function again, and so on until it has reduced the list to a single result: a = [1, 2, 3, 4, 5, 6] product(1, 2) | | | | -> 2 product(2, 3) | | | -> 6 product(6, 4) | | -> 24 product(24, 5) | -> 120 product(120, 6) -> 720 or in other words, this computes (((((1*2)*3)*4)*5)*6) = 720 So our factorial function could have been implemented like this using reduce: def factorial(n): return reduce(lambda x,y: x*y, range(1,n+1)) HTH HAND steve From sudhir.tact.mca at gmail.com Wed Sep 24 12:46:31 2008 From: sudhir.tact.mca at gmail.com (sudhir sahu) Date: Wed, 24 Sep 2008 16:16:31 +0530 Subject: [Tutor] Subject: header intact. Message-ID: <4c0a2dab0809240346n7bbf3f9enec3590c7421d4de@mail.gmail.com> ---------- Forwarded message ---------- From: Date: Wed, Sep 24, 2008 at 4:14 PM Subject: The results of your email commands To: sudhir.tact.mca at gmail.com The results of your email command are provided below. Attached is your original message. - Results: Ignoring non-text/plain MIME parts - Unprocessed: From: > > Date: Wed, Sep 24, 2008 at 3:14 PM Subject: Your confirmation is required to join the Tutor mailing list To: sudhir.tact.mca at gmail.com Mailing list subscription confirmation notice for mailing list Tutor We have received a request for subscription of your email address, "sudhir.tact.mca at gmail.com", to the tutor at python.org mailing list. To confirm that you want to be added to this mailing list, simply reply to this message, keeping the Subject: header intact. Or visit this web page: http://mail.python.org/mailman/confirm/tutor/e29d3177873143be8813dc62cf452fcb191d9528 Or include the following line -- and only the following line -- in a message to tutor-request at python.org: confirm e29d3177873143be8813dc62cf452fcb191d9528 - Ignored: Note that simply sending a `reply' to this message should work from most mail readers, since that usually leaves the Subject: line in the right form (additional "Re:" text in the Subject: is okay). If you do not wish to be subscribed to this list, please simply disregard this message. If you think you are being maliciously subscribed to the list, or have any other questions, send them to tutor-owner at python.org. - Done. ---------- Forwarded message ---------- From: "sudhir sahu" To: tutor-request at python.org Date: Wed, 24 Sep 2008 16:13:39 +0530 Subject: Fwd: Your confirmation is required to join the Tutor mailing list ---------- Forwarded message ---------- From: > Date: Wed, Sep 24, 2008 at 3:14 PM Subject: Your confirmation is required to join the Tutor mailing list To: sudhir.tact.mca at gmail.com Mailing list subscription confirmation notice for mailing list Tutor We have received a request for subscription of your email address, "sudhir.tact.mca at gmail.com", to the tutor at python.org mailing list. To confirm that you want to be added to this mailing list, simply reply to this message, keeping the Subject: header intact. Or visit this web page: http://mail.python.org/mailman/confirm/tutor/e29d3177873143be8813dc62cf452fcb191d9528 Or include the following line -- and only the following line -- in a message to tutor-request at python.org: confirm e29d3177873143be8813dc62cf452fcb191d9528 Note that simply sending a `reply' to this message should work from most mail readers, since that usually leaves the Subject: line in the right form (additional "Re:" text in the Subject: is okay). If you do not wish to be subscribed to this list, please simply disregard this message. If you think you are being maliciously subscribed to the list, or have any other questions, send them to tutor-owner at python.org. -------------- next part -------------- An HTML attachment was scrubbed... URL: From Mike.Hansen at atmel.com Wed Sep 24 16:34:28 2008 From: Mike.Hansen at atmel.com (Hansen, Mike) Date: Wed, 24 Sep 2008 08:34:28 -0600 Subject: [Tutor] Sorting Dictionary of Dictionary by certain Value In-Reply-To: References: Message-ID: <7941B2693F32294AAF16C26B679A258D03BFABEC@csomb01.corp.atmel.com> > -----Original Message----- > Hi Pythonistas, > > I have a large dictionary of dictionary (50,000+ keys) which > has a structure as follows: > DoD = { > 'flintstones' : { > 'husband' : "fred", > 'pal' : "barney", > 'income' : 500, > }, > 'jetsons' : { > 'husband' : "george", > 'wife' : "jane", > 'his boy' : "elroy", > 'income' : 700, > }, > 'simpsons' : { > 'husband' : "homer", > 'wife' : "marge", > 'kid' : "bart", > 'income' : 600, > }, > }; > > I want to sort the dictionary by 'income' > Is there an efficient way to do the same. > Thanks in advance. > > - Jo > This sounds like it'd be a good job for a database...perhaps SQLite? Mike From hkroh at Anadigics.com Wed Sep 24 16:26:01 2008 From: hkroh at Anadigics.com (Herold Kroh) Date: Wed, 24 Sep 2008 10:26:01 -0400 Subject: [Tutor] please explain this error Message-ID: Steve, Thanks for your reply. Yes. The python program is or was keeping the file open.. This is failing at the commit stage of the program, in checking in the svn data. So how do I go about fixing this? Any help and insight is appreciated. Herold ------------------------------------ Anadigics Herold Kroh hkroh at anadigics.com 141 Mt Bethel Rd Warren NJ, 07059 US tel: 908-668-5000 ext 6151 mobile: 570-510-2611 AIM: hekroh Skype ID:hekroh ------------------------------------ -----Original Message----- From: Steve Willoughby [mailto:steve at alchemy.com] Sent: Tuesday, September 23, 2008 6:45 PM To: Herold Kroh Cc: python-help at python.org; tutor at python.org Subject: Re: [Tutor] please explain this error On Tue, Sep 23, 2008 at 06:13:31PM -0400, Herold Kroh wrote: > libsvn._core.SubversionException: ("Can't remove > 'SVN_skill/db/transactions/0-1.txn': Directory not empty", 39) > > I go to the offending directory and I see a .nfs file. When I > touch the file, it disappears. The problem here is with NFS, really. The .nfs files are how the NFS system handles the case where files are deleted on the fileserver but still open on a client. (Under Unix, a file can still be open and all its data accessed even if deleted from the filesystem... it won't *really* go away until it's closed, too. But NFS doesn't represent that case well so a temporary filename is used.) Unless your Python program is what's holding the offending file(s) open... any idea what's keeping the file in use? -- Steve Willoughby | Using billion-dollar satellites steve at alchemy.com | to hunt for Tupperware. From sierra_mtnview at sbcglobal.net Wed Sep 24 17:36:17 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Wed, 24 Sep 2008 08:36:17 -0700 Subject: [Tutor] Where Does the DOS Window Come From? Message-ID: <48DA5E71.8050907@sbcglobal.net> An HTML attachment was scrubbed... URL: From srilyk at gmail.com Wed Sep 24 17:45:39 2008 From: srilyk at gmail.com (W W) Date: Wed, 24 Sep 2008 10:45:39 -0500 Subject: [Tutor] Where Does the DOS Window Come From? In-Reply-To: <48DA5E71.8050907@sbcglobal.net> References: <48DA5E71.8050907@sbcglobal.net> Message-ID: <333efb450809240845r74cb8b33u369d9ad8cb8f86fe@mail.gmail.com> On Wed, Sep 24, 2008 at 10:36 AM, Wayne Watson wrote: > I'm looking at a GUI application that I hope to modify in the next few > weeks. When it's executed the expected GUI appears along with a DOS window. > Occasionally, I think, I've seen something put in the DOS window. How do I > stop it from appearing and how do I find why it's used? > My guess, though I'm not on windows ATM to test: any time the "print" command is used, it outputs to the command line. And in windows, more often than not that probably means "create". So look through and find any "print" commands and comment those out, and my guess it it should silence the window... but I don't know for sure. 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 -------------- next part -------------- An HTML attachment was scrubbed... URL: From simozack at yahoo.it Wed Sep 24 18:22:38 2008 From: simozack at yahoo.it (simone) Date: Wed, 24 Sep 2008 18:22:38 +0200 Subject: [Tutor] Where Does the DOS Window Come From? In-Reply-To: <48DA5E71.8050907@sbcglobal.net> References: <48DA5E71.8050907@sbcglobal.net> Message-ID: <48DA694E.80502@yahoo.it> Wayne Watson ha scritto: > I'm looking at a GUI application that I hope to modify in the next few > weeks. When it's executed the expected GUI appears along with a DOS > window. Occasionally, I think, I've seen something put in the DOS > window. How do I stop it from appearing and how do I find why it's used? If you don't want the DOS window, you can change the extension of the file to .pyw instead of .py, but in this case you will not see the messages printed by the print statement. -- Simone Chiacchiera con i tuoi amici in tempo reale! http://it.yahoo.com/mail_it/foot/*http://it.messenger.yahoo.com From kent37 at tds.net Wed Sep 24 18:16:30 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 24 Sep 2008 12:16:30 -0400 Subject: [Tutor] Where Does the DOS Window Come From? In-Reply-To: <48DA5E71.8050907@sbcglobal.net> References: <48DA5E71.8050907@sbcglobal.net> Message-ID: <1c2a2c590809240916s752f0de8id4eeb0454f6db64a@mail.gmail.com> On Wed, Sep 24, 2008 at 11:36 AM, Wayne Watson wrote: > I'm looking at a GUI application that I hope to modify in the next few > weeks. When it's executed the expected GUI appears along with a DOS window. > Occasionally, I think, I've seen something put in the DOS window. How do I > stop it from appearing and how do I find why it's used? To stop the DOS window from appearing, run the program using pythonw instead of python. See the section "Running GUI Applications" here: http://oreilly.com/catalog/pythonwin32/chapter/ch20.html Kent From marc.tompkins at gmail.com Wed Sep 24 18:52:54 2008 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Wed, 24 Sep 2008 09:52:54 -0700 Subject: [Tutor] Where Does the DOS Window Come From? In-Reply-To: <48DA694E.80502@yahoo.it> References: <48DA5E71.8050907@sbcglobal.net> <48DA694E.80502@yahoo.it> Message-ID: <40af687b0809240952k746adb34g1b995eb08bccd313@mail.gmail.com> > > I'm looking at a GUI application that I hope to modify in the next few >> weeks. When it's executed the expected GUI appears along with a DOS window. >> Occasionally, I think, I've seen something put in the DOS window. How do I >> stop it from appearing and how do I find why it's used? >> > > If you don't want the DOS window, you can change the extension of the file > to .pyw instead of .py, but in this case you will not see the messages > printed by the print statement. > Not to be pedantic, but that's NOT a DOS window, it's a Python terminal. (It just happens to be black-and-white, 80x25 character mode, the same as DOS - but that's just because DOS was originally designed to use the same monitor as an IBM terminal.) You'd get the same thing under Linux or OS X. But yes, to amplify what others have said - you can invoke the script with "pythonw script.py", or just change its extension to ".pyw" and it will automatically be opened with pythonw (assuming that your file associations have been set correctly, which it sounds like they have.) -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Wed Sep 24 19:25:15 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Wed, 24 Sep 2008 10:25:15 -0700 Subject: [Tutor] Where Does the DOS Window Come From? In-Reply-To: <1c2a2c590809240916s752f0de8id4eeb0454f6db64a@mail.gmail.com> References: <48DA5E71.8050907@sbcglobal.net> <1c2a2c590809240916s752f0de8id4eeb0454f6db64a@mail.gmail.com> Message-ID: <48DA77FB.5030503@sbcglobal.net> An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Sep 24 19:51:13 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 24 Sep 2008 18:51:13 +0100 Subject: [Tutor] Where Does the DOS Window Come From? References: <48DA5E71.8050907@sbcglobal.net> Message-ID: "Wayne Watson" wrote > When it's executed the expected GUI appears along with > a DOS window. Occasionally, I think, I've seen something > put in the DOS window. The DOS window is the XP Command prompt execution environment as used by the python interpreter,. Its where the stdin, stdout and stderr streams appear by default. Thus any print statements will appear there and any raw_input requests will be read from there. You should eliminate print or raw_input statements from a GUI if you want to eliminate the DOS window. > How do I stop it from appearing and how do I find why it's used? To stop it appearing you need to run pythonw instead of python and the easiest way to do that is change the extension from .py to .pyw OTOH you may find it convenient for debugging to keep the DOS window until everything is working as a place for debug/test print statements to appear. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From eike at users.sourceforge.net Wed Sep 24 20:43:57 2008 From: eike at users.sourceforge.net (Eike Welk) Date: Wed, 24 Sep 2008 20:43:57 +0200 Subject: [Tutor] please explain this error In-Reply-To: References: Message-ID: <200809242043.57930.eike@users.sourceforge.net> Hello Herold! I have three ideas what you could do: - Try to run the script on the server. Maybe even take NFS down while running the script. Or as a variation, run the script in a directory which is on the local disk. It seems the script is confused by some specific behavior of NFS. (There is at least some hope that the script once worked for its author.) - Email the script's author about the bug and ask him for advice. Put an error report into the script's Bugzilla if one exists. - Try to understand the script and fix it. Kind regards, Eike. From jeremiah.jester at panasonic.aero Thu Sep 25 00:55:12 2008 From: jeremiah.jester at panasonic.aero (jeremiah) Date: Wed, 24 Sep 2008 15:55:12 -0700 Subject: [Tutor] user agent Message-ID: <1222296913.6617.25.camel@jeremiah-laptop> I'm trying to force the user agent in a python login script... My question is what are the possible user agents I can specify and how do I print the user agent at the end of the script so I know that it was accurately saved. Here is the first bit of my code. Any suggestions? thx, JJ == #!/usr/bin/python import cookielib, urllib2 import urllib cookie_jar = cookielib.CookieJar() opener = urllib2.build_opener( urllib2.HTTPCookieProcessor(cookie_jar) ) """ User Agent Setting - change ua_value to modify user agent options are: 'Mozilla/5.0', 'ie5' """ ua_value="ie5" opener.addheaders = [('User-agent', ua_value)] Disclaimer: The information contained in this transmission, including any attachments, may contain confidential information of Panasonic Avionics Corporation. This transmission is intended only for the use of the addressee(s) listed above. Unauthorized review, dissemination or other use of the information contained in this transmission is strictly prohibited. If you have received this transmission in error or have reason to believe you are not authorized to receive it, please notify the sender by return email and promptly delete the transmission. From alan.gauld at btinternet.com Thu Sep 25 01:55:41 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 25 Sep 2008 00:55:41 +0100 Subject: [Tutor] user agent References: <1222296913.6617.25.camel@jeremiah-laptop> Message-ID: "jeremiah" wrote > I'm trying to force the user agent in a python login script... Might I ask why? It should never be necessary and is extremely user hostile. Especially given that many modern browsers are capable of emulating the troublesome ones - ie IE! And future versions might change the rules and you then have a huge maintenance overhead of keeping your list of browsers updated. If at all possible it's better to put the effort into making your code browser neutral. Which mainly meams avoiding unusual HTML constructs, using ECMAscript rather than any vendor specific variant of JavaScript and not trying to control layout and style too closely (that's what PDF is for!) > question is what are the possible user agents I can specify Thats a changing question because the number of browsers and what they report to the server is changing constantly. Its usually more common to simply specify a small subset of the most common ones and anyone with the audacity to prefer an alternative hgets a more or less rude message telling them to pick another browser.... > print the user agent at the end of the script so I know that it was > accurately saved. Here is the first bit of my code. Its stored in an environment variable. How you access that will depend on your server/framework but as a last resort os.getenv() should work. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Thu Sep 25 02:28:06 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 24 Sep 2008 20:28:06 -0400 Subject: [Tutor] user agent In-Reply-To: References: <1222296913.6617.25.camel@jeremiah-laptop> Message-ID: <1c2a2c590809241728h3930ccc5qc3298c1438057ea1@mail.gmail.com> On Wed, Sep 24, 2008 at 7:55 PM, Alan Gauld wrote: > "jeremiah" wrote >> >> I'm trying to force the user agent in a python login script... > > Might I ask why? > It should never be necessary and is extremely user hostile. > Especially given that many modern browsers are capable of emulating the > troublesome ones - ie IE! And future versions might change the rules and you > then have a huge maintenance overhead of keeping your list of browsers > updated. Alan, I think you might have this backwards. I think jeremiah wants to specify the user agent on the client side of the connection. Kent From kent37 at tds.net Thu Sep 25 02:31:51 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 24 Sep 2008 20:31:51 -0400 Subject: [Tutor] user agent In-Reply-To: <1222296913.6617.25.camel@jeremiah-laptop> References: <1222296913.6617.25.camel@jeremiah-laptop> Message-ID: <1c2a2c590809241731i5b8aaeebofb06c5eb0d9181a2@mail.gmail.com> On Wed, Sep 24, 2008 at 6:55 PM, jeremiah wrote: > I'm trying to force the user agent in a python login script... My > question is what are the possible user agents I can specify Here is a rather long list: http://www.user-agents.org/ but presumably there is a particular browser you want to emulate? > and how do I > print the user agent at the end of the script so I know that it was > accurately saved. I don't understand where you want to save the user agent. Kent From emperor.ghaz at gmail.com Thu Sep 25 10:24:31 2008 From: emperor.ghaz at gmail.com (Steve Collins) Date: Thu, 25 Sep 2008 04:24:31 -0400 Subject: [Tutor] How to replace instances Message-ID: <63e3a6e10809250124x3307122erb524bb2e2f303342@mail.gmail.com> I've written a save/load function for a simple program using cPickle. Upon saving, a master list, to which all instances are added in their __init__, is pickled. when the program starts, if the user wishes to load, a variable "load" is set to one, and the pickled list is loaded. All the classes either A) initialize using the arguments provided or B) using the the attributes of the instances in the un-pickled list. This seems a little clunky to me, but it basically works. However, some of the instances refer explicitly to other instances instances. It's obvious why this causes problems. It occurred to me to simply replace the instances with the ones in the un-pickled list, but I don't know how. I tried using the following approach: class Z: def __init__(self,y): self.y = y def replaceZ (self,withWhat): self = withWhat That doesn't raise any errors, but it also doesn't work: >>> a = X(10) >>> b = X(20) >>> print a.y 10 >>> print b.y 20 >>> b.replaceZ(a) >>> print b.y 20 >>> a <__main__.X instance at 0x00D4AE18> >>> b <__main__.X instance at 0x00D54328> >>> Can anyone tell me how to achieve this? -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Sep 25 10:49:12 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 25 Sep 2008 09:49:12 +0100 Subject: [Tutor] user agent References: <1222296913.6617.25.camel@jeremiah-laptop> <1c2a2c590809241728h3930ccc5qc3298c1438057ea1@mail.gmail.com> Message-ID: "Kent Johnson" wrote > > Alan, I think you might have this backwards. I think jeremiah wants > to > specify the user agent on the client side of the connection. Ah! In that case it makes sense. Ignore my ramblings :-) Alan G From kent37 at tds.net Thu Sep 25 12:58:56 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 25 Sep 2008 06:58:56 -0400 Subject: [Tutor] How to replace instances In-Reply-To: <63e3a6e10809250124x3307122erb524bb2e2f303342@mail.gmail.com> References: <63e3a6e10809250124x3307122erb524bb2e2f303342@mail.gmail.com> Message-ID: <1c2a2c590809250358m4952f181u3a81e6fb5aedae80@mail.gmail.com> On Thu, Sep 25, 2008 at 4:24 AM, Steve Collins wrote: > However, some of the instances refer explicitly to other instances > instances. It's obvious why this causes problems. It occurred to me to > simply replace the instances with the ones in the un-pickled list, but I > don't know how. > I tried using the following approach: > > class Z: > def __init__(self,y): > self.y = y > def replaceZ (self,withWhat): > self = withWhat 'self' is just another parameter passed to the method, so this just rebinds a local name. This example doesn't seem to illustrate the situation you describe. You can replace the 'y' attribute of a Z object by assigning to it. One solution might be to make all your objects pickleable. Pickle tracks object references and handles embedded references correctly. > That doesn't raise any errors, but it also doesn't work: > >>>> a = X(10) >>>> b = X(20) Presumably this should be Z(10), Z(20) ? >>>> print a.y > 10 >>>> print b.y > 20 >>>> b.replaceZ(a) >>>> print b.y > 20 If you want 'b' to refer to the same thing as 'a', just assign b = a I think you have some common misconceptions about the nature of variables and assignment in Python. This may help: http://personalpages.tds.net/~kent37/kk/00012.html Kent From emperor.ghaz at gmail.com Thu Sep 25 14:03:38 2008 From: emperor.ghaz at gmail.com (Steve Collins) Date: Thu, 25 Sep 2008 08:03:38 -0400 Subject: [Tutor] How to replace instances In-Reply-To: <1c2a2c590809250358m4952f181u3a81e6fb5aedae80@mail.gmail.com> References: <63e3a6e10809250124x3307122erb524bb2e2f303342@mail.gmail.com> <1c2a2c590809250358m4952f181u3a81e6fb5aedae80@mail.gmail.com> Message-ID: <63e3a6e10809250503r649a90d8s9db949008bfc03b7@mail.gmail.com> On 9/25/08, Kent Johnson wrote: > On Thu, Sep 25, 2008 at 4:24 AM, Steve Collins > wrote: > >> However, some of the instances refer explicitly to other instances >> instances. It's obvious why this causes problems. It occurred to me to >> simply replace the instances with the ones in the un-pickled list, but I >> don't know how. > >> I tried using the following approach: >> >> class Z: >> def __init__(self,y): >> self.y = y >> def replaceZ (self,withWhat): >> self = withWhat > > 'self' is just another parameter passed to the method, so this just > rebinds a local name. > That makes sense. At least I understand why it doesn't work now. > This example doesn't seem to illustrate the situation you describe. > You can replace the 'y' attribute of a Z object by assigning to it. > > One solution might be to make all your objects pickleable. Pickle > tracks object references and handles embedded references correctly. > >> That doesn't raise any errors, but it also doesn't work: >> >>>>> a = X(10) >>>>> b = X(20) > > Presumably this should be Z(10), Z(20) ? >>>>> print a.y >> 10 >>>>> print b.y >> 20 >>>>> b.replaceZ(a) >>>>> print b.y >> 20 > > If you want 'b' to refer to the same thing as 'a', just assign > b = a that's what I was trying (incorrectly) to achieve the above example. but how can I do this for an arbitrary number of objects in a list? I have a list x = [a,b,c] and a list y = [d,e,f], both filled with instance objects. I want the instance at x[n] to reference the instance at y[n] n = 0 while n < range(len(x)) x[n] = y[n] n+=1 given the contents of your link, I understand why x == [d,e,f] and not a == d etc., but how can I make a == d by iterating through two lists? > > I think you have some common misconceptions about the nature of > variables and assignment in Python. This may help: > http://personalpages.tds.net/~kent37/kk/00012.html > > Kent > I should note that I am very much a novice programmer, and really appreciate the feedback. Thanks, Steve From kent37 at tds.net Thu Sep 25 15:17:35 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 25 Sep 2008 09:17:35 -0400 Subject: [Tutor] How to replace instances In-Reply-To: <63e3a6e10809250503r649a90d8s9db949008bfc03b7@mail.gmail.com> References: <63e3a6e10809250124x3307122erb524bb2e2f303342@mail.gmail.com> <1c2a2c590809250358m4952f181u3a81e6fb5aedae80@mail.gmail.com> <63e3a6e10809250503r649a90d8s9db949008bfc03b7@mail.gmail.com> Message-ID: <1c2a2c590809250617m79e1d801hdf4c904153a95e1b@mail.gmail.com> On Thu, Sep 25, 2008 at 8:03 AM, Steve Collins wrote: > that's what I was trying (incorrectly) to achieve the above example. > but how can I do this for an arbitrary number of objects in a list? > > I have a list x = [a,b,c] and a list y = [d,e,f], both filled with > instance objects. Note that lists don't contain objects, they contain references to objects. > I want the instance at x[n] to reference the > instance at y[n] This doesn't really make sense, if x[n] and y[n] are the same type of object. You can have x[n] and y[n] reference the same object, or you can have them reference different objects with the same value. > n = 0 > while n < range(len(x)) > x[n] = y[n] > n+=1 That seems to do what you want. After this loop, x[n] and y[n] will refer to the same object. How is it not? I think you still misunderstand what objects and lists and references are, and this misunderstanding is making it hard to for me to understand what you are really trying to accomplish. Perhaps you can give a slightly longer example with real classes and lists, perhaps one that doesn't do what you want, and we can correct it. Kent From adrian.greyling at gmail.com Thu Sep 25 21:25:15 2008 From: adrian.greyling at gmail.com (Adrian Greyling) Date: Thu, 25 Sep 2008 15:25:15 -0400 Subject: [Tutor] Current path (of program) Message-ID: <866c750d0809251225k5a466305v769b12195bec2677@mail.gmail.com> I've been using "os.getcwd()" to get my program's "current path". I know it's actually returning my "current working directory", but it's been working okay, until today... I used py2exe (and InnoSetup) to create a standalone executable (for Windows) and then a shortcut icon on the desktop to "MyProg.exe". Problem is, now "os.getcwd()" returns "C:\Documents and Settings\ME\Desktop\" as it's current working directory, not the "C:\Program Files\MyCoolProgram\" that I was expecting. I'm trying to use a "relative path reference" so that the user can install the program to whatever directory he/she wants, but that my program won't "lose track" of the subdirectories it requires for additional files. Anyone run into the same sort of problem? Better yet, anyone know how to solve this? Thanks everyone! Adrian -------------- next part -------------- An HTML attachment was scrubbed... URL: From adrian.greyling at gmail.com Thu Sep 25 21:58:35 2008 From: adrian.greyling at gmail.com (Adrian Greyling) Date: Thu, 25 Sep 2008 15:58:35 -0400 Subject: [Tutor] Current path (of program) In-Reply-To: <866c750d0809251225k5a466305v769b12195bec2677@mail.gmail.com> References: <866c750d0809251225k5a466305v769b12195bec2677@mail.gmail.com> Message-ID: <866c750d0809251258h1175e723kf77c6b8adf8ed6d7@mail.gmail.com> Is it a faux pas to answer your own question?? I found this after I tweaked my search terms.. >From "Dive Into Python" ( http://diveintopython.org/functional_programming/finding_the_path.html) pathname = os.path.dirname(sys.argv[0]) currpath = os.path.abspath(pathname) "Regardless of how you run a script, sys.argv[0] will always contain the name of the script, exactly as it appears on the command line. This may or may not include any path information. os.path.dirname takes a filename as a string and returns the directory path portion. If the given filename does not include any path information, os.path.dirname returns an empty string. os.path.abspath is the key here. It takes a pathname, which can be partial or even blank, and returns a fully qualified pathname." Sorry about that folks... Adrian On Thu, Sep 25, 2008 at 3:25 PM, Adrian Greyling wrote: > I've been using "os.getcwd()" to get my program's "current path". I know > it's actually returning my "current working directory", but it's been > working okay, until today... I used py2exe (and InnoSetup) to create a > standalone executable (for Windows) and then a shortcut icon on the desktop > to "MyProg.exe". Problem is, now "os.getcwd()" returns "C:\Documents and > Settings\ME\Desktop\" as it's current working directory, not the "C:\Program > Files\MyCoolProgram\" that I was expecting. > > I'm trying to use a "relative path reference" so that the user can install > the program to whatever directory he/she wants, but that my program won't > "lose track" of the subdirectories it requires for additional files. > > Anyone run into the same sort of problem? Better yet, anyone know how to > solve this? > > Thanks everyone! > Adrian > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jopython at gmail.com Thu Sep 25 23:44:45 2008 From: jopython at gmail.com (Joe) Date: Thu, 25 Sep 2008 17:44:45 -0400 Subject: [Tutor] Sorting Dictionary of Dictionary by certain Value In-Reply-To: <1c2a2c590809231918m68729826n3ac7ffe57320bf2@mail.gmail.com> References: <1c2a2c590809231918m68729826n3ac7ffe57320bf2@mail.gmail.com> Message-ID: <48DC064D.2080503@gmail.com> An HTML attachment was scrubbed... URL: From cspears2002 at yahoo.com Fri Sep 26 01:08:35 2008 From: cspears2002 at yahoo.com (Christopher Spears) Date: Thu, 25 Sep 2008 16:08:35 -0700 (PDT) Subject: [Tutor] inheriting from a class Message-ID: <109667.77184.qm@web51602.mail.re2.yahoo.com> I'm working out of "Game Programming (The L Line)" by Andy Harris. He writes subclasses like so: class TransCircle(collisionObjects.Circle): def __init__(self): collisionObjects.Circle.__init__(self) self.image.set_colorkey((255, 255, 255)) Basically, he is creating a TransCircle class that inherits attributes from a Circle class inside the collisionObjects module. Is calling Circle's constructor inside of TransCircle's constructor necessary for inheritance to work? Here is a little test that I ran: In [2]: class A: ...: def __init__(self): ...: print "Class A!" ...: ...: In [3]: class B (A): ...: def __init__(self): ...: print "Class B!" ...: ...: In [4]: In [4]: a = A() Class A! In [5]: b = B(a) --------------------------------------------------------------------------- exceptions.TypeError Traceback (most recent call last) /media/ TypeError: __init__() takes exactly 1 argument (2 given) In [6]: b = B() Class B! Looks like I don't have to call A's constructor. Or am I missing something? From dineshbvadhia at hotmail.com Fri Sep 26 01:35:06 2008 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Thu, 25 Sep 2008 16:35:06 -0700 Subject: [Tutor] defaultdict(set) Message-ID: I'm using defaultdict(set) to store a dictionary d = {value : set_items} where value = integer and set_items = set() of characters and it works perfectly. I would like to also store the length of the set ie. l = len(set_items) with the dictionary but don't how to do it using a defaultdict(). Any ideas? Dinesh -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Sep 26 01:54:40 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 26 Sep 2008 00:54:40 +0100 Subject: [Tutor] inheriting from a class References: <109667.77184.qm@web51602.mail.re2.yahoo.com> Message-ID: "Christopher Spears" wrote > class TransCircle(collisionObjects.Circle): > def __init__(self): > collisionObjects.Circle.__init__(self) > self.image.set_colorkey((255, 255, 255)) > > Basically, he is creating a TransCircle class that inherits > attributes from a Circle class inside the collisionObjects module. > Is calling Circle's constructor inside of TransCircle's constructor > necessary for inheritance to work? No its not necessary, but its a very good idea. Essentially if the super class does any initialisation of its attributes in its init method then if you don't call it from the sub class then that initialisation will not be done. So if you want to risjk using an object where some of the attributes don't exist or have unpredictable values go ahead, but don't expect your code to work smoothly! Or alternatively you could find out what the super class init does and do it all manually but thats a lot of work and if you get the sequence wrong it could still fail... > Here is a little test that I ran: > In [2]: class A: > ...: def __init__(self): > ...: print "Class A!" > ...: This initialiser doesn't initialise anything Try it with: > In [2]: class A: > ...: def __init__(self, message="Class A"): self.message = message > ...: print self.message > ...: > In [3]: class B (A): > ...: def __init__(self): > ...: print "Class B!" Again no initialisation here. Try > In [3]: class B (A): > ...: def __init__(self): A.__init__(self) > ...: print "Class B message:", self.message > In [4]: a = A() > Class A! > > In [6]: b = B() > Class B! > > Looks like I don't have to call A's constructor. > Or am I missing something? No if the init doesn't actually initialise anything then you don't need to call it. But note that even here the behaviour is different. If you had called A.init you would have had 2 print statements not one from B. Using my version above, if you miss out the call to A.init you get an error because self.message is undefined... The purpose of initialisation is to set state not normally to just print messages. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From jeremiah.jester at panasonic.aero Fri Sep 26 02:20:51 2008 From: jeremiah.jester at panasonic.aero (jeremiah) Date: Thu, 25 Sep 2008 17:20:51 -0700 Subject: [Tutor] twill help In-Reply-To: References: <109667.77184.qm@web51602.mail.re2.yahoo.com> Message-ID: <1222388451.15987.7.camel@jeremiah-laptop> Any python twill users on here? When I login to a form login page through twill, my session vars and cookies are set correctly. however, when i do this through a python script (in attempt to automate the proccess) these same variables are not saved and I cannot login. Do I need to pass them some how? Here's what I'm doing... >>twill-sh >> extend_with filename >>login someusername somepassword >>show_cookies #coorect vars don't print File... #!/usr/bin/python from twill.commands import * def login(u, p): go('https://dartdev.panasonic.aero/home/login.php') fv(1, 'username', u) fv(1, 'password', p) submit Thanks! JJ Disclaimer: The information contained in this transmission, including any attachments, may contain confidential information of Panasonic Avionics Corporation. This transmission is intended only for the use of the addressee(s) listed above. Unauthorized review, dissemination or other use of the information contained in this transmission is strictly prohibited. If you have received this transmission in error or have reason to believe you are not authorized to receive it, please notify the sender by return email and promptly delete the transmission. From kent37 at tds.net Fri Sep 26 03:13:31 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 25 Sep 2008 21:13:31 -0400 Subject: [Tutor] defaultdict(set) In-Reply-To: References: Message-ID: <1c2a2c590809251813k6dc6b1b1kf922cb75b8a454e1@mail.gmail.com> On Thu, Sep 25, 2008 at 7:35 PM, Dinesh B Vadhia wrote: > I'm using defaultdict(set) to store a dictionary d = {value : set_items} > where value = integer and set_items = set() of characters and it works > perfectly. > > I would like to also store the length of the set ie. l = len(set_items) with > the dictionary but don't how to do it using a defaultdict(). Any ideas? Why not just take the length when you need it? There is no need to store it separately. e.g. len(d[3]) Kent From Jaggojaggo+Py at gmail.com Fri Sep 26 11:27:54 2008 From: Jaggojaggo+Py at gmail.com (Omer) Date: Fri, 26 Sep 2008 12:27:54 +0300 Subject: [Tutor] Current path (of program) In-Reply-To: <866c750d0809251258h1175e723kf77c6b8adf8ed6d7@mail.gmail.com> References: <866c750d0809251225k5a466305v769b12195bec2677@mail.gmail.com> <866c750d0809251258h1175e723kf77c6b8adf8ed6d7@mail.gmail.com> Message-ID: <515008f10809260227x3235c980s23304afe4d797695@mail.gmail.com> No, I shouldn't think it is. Lots o' folk use this list in archived mode and the important bit is that each question comes with an answer, regardless of the actual persons involved. On Thu, Sep 25, 2008 at 10:58 PM, Adrian Greyling wrote: > Is it a faux pas to answer your own question?? I found this after I > tweaked my search terms.. > > From "Dive Into Python" ( > http://diveintopython.org/functional_programming/finding_the_path.html) > > pathname = os.path.dirname(sys.argv[0]) > currpath = os.path.abspath(pathname) > > "Regardless of how you run a script, sys.argv[0] will always contain the > name of the script, exactly as it appears on the command line. This may or > may not include any path information. os.path.dirname takes a filename as a > string and returns the directory path portion. If the given filename does > not include any path information, os.path.dirname returns an empty string. > os.path.abspath is the key here. It takes a pathname, which can be partial > or even blank, and returns a fully qualified pathname." > > > Sorry about that folks... > Adrian > > > > > > > > On Thu, Sep 25, 2008 at 3:25 PM, Adrian Greyling < > adrian.greyling at gmail.com> wrote: > >> I've been using "os.getcwd()" to get my program's "current path". I know >> it's actually returning my "current working directory", but it's been >> working okay, until today... I used py2exe (and InnoSetup) to create a >> standalone executable (for Windows) and then a shortcut icon on the desktop >> to "MyProg.exe". Problem is, now "os.getcwd()" returns "C:\Documents and >> Settings\ME\Desktop\" as it's current working directory, not the "C:\Program >> Files\MyCoolProgram\" that I was expecting. >> >> I'm trying to use a "relative path reference" so that the user can install >> the program to whatever directory he/she wants, but that my program won't >> "lose track" of the subdirectories it requires for additional files. >> >> Anyone run into the same sort of problem? Better yet, anyone know how to >> solve this? >> >> Thanks everyone! >> Adrian >> > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From roadierich at googlemail.com Fri Sep 26 19:16:46 2008 From: roadierich at googlemail.com (Richard Lovely) Date: Fri, 26 Sep 2008 18:16:46 +0100 Subject: [Tutor] How to replace instances Message-ID: Hi, I'm not going to guess at why this doesn't work, but I've got a potential solution for you: class Z(object): def __init__(self,y): self.y = y def replaceZ (self,withWhat): self.__dict__ = withWhat.__dict__ Is there a reason you can't use a simple assignment (x=y) outside of the class? On 9/25/08, tutor-request at python.org wrote: > Date: Thu, 25 Sep 2008 04:24:31 -0400 > From: "Steve Collins" > Subject: [Tutor] How to replace instances > To: tutor at python.org > Message-ID: > <63e3a6e10809250124x3307122erb524bb2e2f303342 at mail.gmail.com> > Content-Type: text/plain; charset="iso-8859-1" > > I've written a save/load function for a simple program using cPickle. Upon > saving, a master list, to which all instances are added in their __init__, > is pickled. when the program starts, if the user wishes to load, a variable > "load" is set to one, and the pickled list is loaded. All the classes either > A) initialize using the arguments provided or B) using the the attributes of > the instances in the un-pickled list. This seems a little clunky to me, but > it basically works. > However, some of the instances refer explicitly to other instances > instances. It's obvious why this causes problems. It occurred to me to > simply replace the instances with the ones in the un-pickled list, but I > don't know how. > > I tried using the following approach: > > class Z: > def __init__(self,y): > self.y = y > def replaceZ (self,withWhat): > self = withWhat > > > That doesn't raise any errors, but it also doesn't work: > > >>> a = X(10) > >>> b = X(20) > >>> print a.y > 10 > >>> print b.y > 20 > >>> b.replaceZ(a) > >>> print b.y > 20 > >>> a > <__main__.X instance at 0x00D4AE18> > >>> b > <__main__.X instance at 0x00D54328> > >>> > > Can anyone tell me how to achieve this? > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > -- Richard "Roadie Rich" Lovely, part of the JNP|UK Famile www.theJNP.com From cuciferus at gmail.com Sat Sep 27 17:52:55 2008 From: cuciferus at gmail.com (cuciferus at gmail.com) Date: Sat, 27 Sep 2008 18:52:55 +0300 Subject: [Tutor] paste question Message-ID: <200809271852.56171.cuciferus@gmail.com> Hi list! I made a little script to whom I wish to pass some pasted(with middle click(x11 style)) multi-row text. But if I pass say 99 rows it crashes with no error it exits to bash. Any ideas why? from sys import exit a=0 while True: s=raw_input() a+=1 if s=="finish": print "you have ", ((a-1)/5), " questions left" print "in", ((a-1)/100), " pages" a=0 From alan.gauld at btinternet.com Sat Sep 27 21:27:56 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 27 Sep 2008 20:27:56 +0100 Subject: [Tutor] paste question References: <200809271852.56171.cuciferus@gmail.com> Message-ID: wrote Sorry but I'm confused. > I made a little script to whom I wish to pass some pasted(with > middle > click(x11 style)) multi-row text. But if I pass say 99 rows it > crashes with no > error it exits to bash. Any ideas why? Do you mean you are trying to paste a long piece of text into the raw_input prompt? Otherwise I'm not sure what the code below has to do with anything? > from sys import exit you don;t use exit... > a=0 > while True: This will loop forever (or until an error) since you have no break statement. > s=raw_input() > a+=1 > if s=="finish": > print "you have ", ((a-1)/5), " questions left" You might be wanting to use the % mod operator here instead of division? Otherwise it will always report a low value. And 'a' records how many responses have been given not how many questions are left. > print "in", ((a-1)/100), " pages" Similarly a has nothing to do with pages... It looks like you need more variables, or something! > a=0 This does't make much sense to me either. But mostly I'm confused about what exactly you are doing with the paste and when. Assuming it is at the raw_input stage you could try printing s just to see what was read. That way when it exists you should still see what was last input. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From jgowen at lorettotel.net Sat Sep 27 21:41:22 2008 From: jgowen at lorettotel.net (Johnny) Date: Sat, 27 Sep 2008 14:41:22 -0500 Subject: [Tutor] accessing files, (EXE files) Making EXE files from Python Message-ID: <48DE8C62.4050300@lorettotel.net> An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Sep 27 23:50:06 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 27 Sep 2008 22:50:06 +0100 Subject: [Tutor] accessing files, (EXE files) Making EXE files from Python References: <48DE8C62.4050300@lorettotel.net> Message-ID: "Johnny" wrote > I was wanting (as a project for learning) to be able to make > a menu program for executing various programs on my hard drive. OK, As a first project thats good. I'd start with a text based menu then rtry to convert it to a GUI later maybe. > Can you call on EXE files from python? Yes, there are several ways of doing this but the current "official" way of doing it is via the subprocess module. There are several examples in the module documentation. Also if you are on Windows you may find the os.startfile command useful to execute whatever is the default program for a given file. Notepad for .txt files for example. Its like double clicking in Windows Explorer. > also, one last question,,, > How can you turn your newly made python program into a > exe program to pass out to friends? Yes, or you can build an installer that installs Python on your friends PC too. (A bit like installing the Java JVM to run Java programs) But while its not very hard, its not trivial either so I'd concentrate on learning Python first. If your friends want a copy get them to install Python first (they might even want to learn too when they can see what you can do! :-) Once you've gotten the hang of Python you can take a look at Py2exe and other similar programs. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From xboxmuncher at gmail.com Sun Sep 28 05:20:38 2008 From: xboxmuncher at gmail.com (xbmuncher) Date: Sat, 27 Sep 2008 23:20:38 -0400 Subject: [Tutor] Monitoring HTTP connections? Message-ID: How can I monitor the HTTP connections my windows xp system makes with python? I'm running a program that makes requests to websites over HTTP, I know this by using a program like wireshark. I'd basically like to have a python program know when this other program makes these requests and be able to save the request data, so I know what it is requesting (to what website). Kind of like a mini- wireshark like program but only for HTTP requests. -------------- next part -------------- An HTML attachment was scrubbed... URL: From cuciferus at gmail.com Sun Sep 28 09:45:59 2008 From: cuciferus at gmail.com (cuciferus at gmail.com) Date: Sun, 28 Sep 2008 10:45:59 +0300 Subject: [Tutor] paste question In-Reply-To: References: <200809271852.56171.cuciferus@gmail.com> Message-ID: <200809281045.59508.cuciferus@gmail.com> On Saturday 27 September 2008 22:27:56 Alan Gauld wrote: > wrote > > Sorry but I'm confused. > > > I made a little script to whom I wish to pass some pasted(with > > middle > > click(x11 style)) multi-row text. But if I pass say 99 rows it > > crashes with no > > error it exits to bash. Any ideas why? > > Do you mean you are trying to paste a long piece of text into the > raw_input prompt? Yes > > Otherwise I'm not sure what the code below has to do with anything? > > > from sys import exit > > you don;t use exit... Sorry I was embarased with my exit function hence I have not pasted it in the mail > > > a=0 > > while True: > > This will loop forever (or until an error) since you have no break > statement. > > > s=raw_input() > > a+=1 > > if s=="finish": > > print "you have ", ((a-1)/5), " questions left" > > You might be wanting to use the % mod operator here instead > of division? Otherwise it will always report a low value. And 'a' > records how many responses have been given not how many > questions are left. > > > print "in", ((a-1)/100), " pages" > > Similarly a has nothing to do with pages... It looks like you > need more variables, or something! > > > a=0 > > This does't make much sense to me either. I'm good here. You see I'm doing some online tests for my graduation exam(don't know what is the equivalent in English), and in a test are hundreds of questions(I would give the site but it's in Romanian and requiers registration). The thing is it doesn't display the number of questions left unanswered, But it displays the status of questions(answered and unaswered). I copy the unanswered questions and paste it in console: here a question is displayed in 5 rows, and yeah you guessed I have 20 questions/page. In bash I was doing it with echo "paste here"|wc-l and worked but when I paste in python shell a large amount of text it exits. > > But mostly I'm confused about what exactly you are doing with > the paste and when. > > Assuming it is at the raw_input stage you could try printing > s just to see what was read. That way when it exists you > should still see what was last input. > > HTH, Hope I was more clear this time From alan.gauld at btinternet.com Sun Sep 28 10:16:24 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 28 Sep 2008 09:16:24 +0100 Subject: [Tutor] paste question References: <200809271852.56171.cuciferus@gmail.com> <200809281045.59508.cuciferus@gmail.com> Message-ID: wrote > I'm good here. You see I'm doing some online tests for my graduation > and in a test are hundreds of questions. The thing is it doesn't > display > the number of questions left unanswered, But it displays the status > of > questions(answered and unaswered). I copy the unanswered questions > and paste it in console: here a question is displayed in 5 rows, and > I have 20 questions/page. So you select, witgh the mouse, all of the "unanswered" questions from the web page and paste that into the raw_input() request in your python script? Have you tried just printing the pasted information to the consiole to make sure it gets read correctly? However that still confuses me about what your script is trying to do: a=0 while True: s=raw_input() This should read the entire content of the paste buffer. All 100 lines of text. a+=1 if s=="finish": This will only do anything if the pasted text is exactly "finish". That seems unlikely, I suspect you might have line endings and other stuff in there too. print "you have ", ((a-1)/5), " questions left" print "in", ((a-1)/100), " pages" But if we assume that the text was "finish" you would then come into this block which would print out "0 questions left in 0 pages" until a is greater than 6 and 101 respectively. I'm beginning to suspect you really want something like this pseudo code: s = raw_input('Paste here> ') for count, line in enumerate(s): pass print "You have ", count/5," questions left in ", count/100," pages" Am I close? -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Sun Sep 28 10:37:26 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 28 Sep 2008 09:37:26 +0100 Subject: [Tutor] paste question References: <200809271852.56171.cuciferus@gmail.com><200809281045.59508.cuciferus@gmail.com> Message-ID: "Alan Gauld" wrote >> questions(answered and unaswered). I copy the unanswered questions >> and paste it in console: here a question is displayed in 5 rows, >> and >> I have 20 questions/page. > > I'm beginning to suspect you really want something like > this pseudo code: > > s = raw_input('Paste here> ') > for count, line in enumerate(s): pass > print "You have ", count/5," questions left in ", count/100," pages" Had a rethink... I don't know enough about how the X paste mechanism and the console stdin work together but this may not work because raw_input will probably stop reading at the first \n character. You probably need to use sys.stdin.read: print 'paste now' s = sys.stdin.read() count = s.split('\n) # no need for a loop. print "You have ", count/5," questions left in ", count/100," pages" Maybe... -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From cuciferus at gmail.com Sun Sep 28 11:04:40 2008 From: cuciferus at gmail.com (cuciferus at gmail.com) Date: Sun, 28 Sep 2008 12:04:40 +0300 Subject: [Tutor] paste question In-Reply-To: References: <200809271852.56171.cuciferus@gmail.com> <200809281045.59508.cuciferus@gmail.com> Message-ID: <200809281204.40428.cuciferus@gmail.com> On Sunday 28 September 2008 11:16:24 Alan Gauld wrote: > wrote > > > I'm good here. You see I'm doing some online tests for my graduation > > and in a test are hundreds of questions. The thing is it doesn't > > display > > the number of questions left unanswered, But it displays the status > > of > > questions(answered and unaswered). I copy the unanswered questions > > and paste it in console: here a question is displayed in 5 rows, and > > I have 20 questions/page. > > So you select, witgh the mouse, all of the "unanswered" questions > from the web page and paste that into the raw_input() request in your > python script? yup > > Have you tried just printing the pasted information to the consiole > to make sure it gets read correctly? I'm using kmail-svn as mail client maybe not all my original message was send, but I did mention I was doing this in bash with: echo "pasted text here"|wc -l > > However that still confuses me about what your script is trying to do: > > a=0 > while True: > s=raw_input() > > This should read the entire content of the paste buffer. > All 100 lines of text. > > a+=1 > if s=="finish": > > This will only do anything if the pasted text is exactly "finish". > That seems unlikely, I suspect you might have line endings > and other stuff in there too. I thought I'll manually insert a "finish" after each paste > > print "you have ", ((a-1)/5), " questions left" > print "in", ((a-1)/100), " pages" > > But if we assume that the text was "finish" you would then > come into this block which would print out "0 questions left in 0 > pages" > until a is greater than 6 and 101 respectively. > > I'm beginning to suspect you really want something like > this pseudo code: > > s = raw_input('Paste here> ') > for count, line in enumerate(s): pass > print "You have ", count/5," questions left in ", count/100," pages" that would return me the number of words per line(right?). I have the following table:http://img515.imageshack.us/my.php?image=200809281154091280x1024hf2.png And when I paste it into raw_input one line spreads in 5. And the unexpected thing goes like so, for s=raw_input('paste here'): paste here: M2201151 Reactivitatea crescuta a cailor repiratorii se ... CS Neabordata CS cuci at cuci ~ $ Reactivitatea crescuta a cailor repiratorii se ... -bash: Reactivitatea: command not found So do I have a row limit in raw_input? I know there must be a better, more pythonic way but, well I'm subscribed to python-tutor :) Thanks! > > Am I close? From cuciferus at gmail.com Sun Sep 28 11:58:31 2008 From: cuciferus at gmail.com (cuciferus at gmail.com) Date: Sun, 28 Sep 2008 12:58:31 +0300 Subject: [Tutor] paste question In-Reply-To: References: <200809271852.56171.cuciferus@gmail.com> Message-ID: <200809281258.31524.cuciferus@gmail.com> On Sunday 28 September 2008 11:37:26 Alan Gauld wrote: > "Alan Gauld" wrote > > >> questions(answered and unaswered). I copy the unanswered questions > >> and paste it in console: here a question is displayed in 5 rows, > >> and > >> I have 20 questions/page. > > > > I'm beginning to suspect you really want something like > > this pseudo code: > > > > s = raw_input('Paste here> ') > > for count, line in enumerate(s): pass > > print "You have ", count/5," questions left in ", count/100," pages" > > Had a rethink... > > I don't know enough about how the X paste mechanism and the > console stdin work together but this may not work because > raw_input will probably stop reading at the first \n character. > You probably need to use sys.stdin.read: > > print 'paste now' > s = sys.stdin.read() > count = s.split('\n) # no need for a loop. > print "You have ", count/5," questions left in ", count/100," pages" yup this did the trick, actually len(count)/5 . Thanks man! > > Maybe... From kent37 at tds.net Sun Sep 28 13:39:53 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 28 Sep 2008 07:39:53 -0400 Subject: [Tutor] Monitoring HTTP connections? In-Reply-To: References: Message-ID: <1c2a2c590809280439r19ade56avbd1f60fda494deb8@mail.gmail.com> On Sat, Sep 27, 2008 at 11:20 PM, xbmuncher wrote: > How can I monitor the HTTP connections my windows xp system makes with > python? > > I'm running a program that makes requests to websites over HTTP, I know this > by using a program like wireshark. I'd basically like to have a python > program know when this other program makes these requests and be able to > save the request data, so I know what it is requesting (to what website). > Kind of like a mini- wireshark like program but only for HTTP requests. Why not just set up wireshark with a filter for HTTP requests? http://www.wireshark.org/docs/wsug_html_chunked/ChCapCaptureFilterSection.html You could also use a proxy server to log the traffic; several Python proxy servers are listed here: http://www.xhaus.com/alan/python/proxies.html Kent From tomar.arun at gmail.com Sun Sep 28 16:46:14 2008 From: tomar.arun at gmail.com (Arun Tomar) Date: Sun, 28 Sep 2008 20:16:14 +0530 Subject: [Tutor] python regex help Message-ID: <1222613174.19482.9.camel@arun-laptop.solution.internal> hi! i've data extracted in the form of list using regex. it looks something like the one below. ==================================================== print reobj ['Jyoti Soni - 0 Year(s) 0 Month(s)\n', 'Tel: 09975610476(M)\n', '\n', 'Minal - 0 Year(s) 0 Month(s)\n', 'Tel: 9890498376(M)\n', '011 02162 250553(R)\n'] ==================================================== i'm trying to use regex to remove the following information 1. - 0 Years * 2. Tel: & (M) 3. (R) & store the remaining portion as a new list. I've been using shell scripting & using sed & pipes i've solved it, but with python, i need to practice more ;). regds, arun. -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: This is a digitally signed message part URL: From alan.gauld at btinternet.com Sun Sep 28 18:26:25 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 28 Sep 2008 17:26:25 +0100 Subject: [Tutor] python regex help References: <1222613174.19482.9.camel@arun-laptop.solution.internal> Message-ID: "Arun Tomar" wrote > I've been using shell scripting & using sed & pipes i've solved it, > but with python, i need to practice more ;). Can you show us some output as you'd like irt? Can you show us the sed script that works? Also can you show us the Python code that doesn't work and what went wrong? Its easier to fix what's broken than to guess at what might do what you want :-) -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From timovwb at gmail.com Sun Sep 28 18:51:18 2008 From: timovwb at gmail.com (Timo) Date: Sun, 28 Sep 2008 18:51:18 +0200 Subject: [Tutor] Downloading Files from the net Message-ID: <48dfb602.2283420a.7dff.2f6f@mx.google.com> What is the best/correct way to download files from a webpage? www.example.com/example.mp3 for instance. I know how to open the site (with urllib), but have no idea how to write the file to the harddisk. Cheers From tomar.arun at gmail.com Sun Sep 28 19:49:39 2008 From: tomar.arun at gmail.com (Arun Tomar) Date: Sun, 28 Sep 2008 23:19:39 +0530 Subject: [Tutor] python regex help In-Reply-To: References: <1222613174.19482.9.camel@arun-laptop.solution.internal> Message-ID: <1222624179.19482.21.camel@arun-laptop.solution.internal> On Sun, 2008-09-28 at 17:26 +0100, Alan Gauld wrote: > "Arun Tomar" wrote > > > I've been using shell scripting & using sed & pipes i've solved it, > > but with python, i need to practice more ;). > > Can you show us some output as you'd like irt? > Can you show us the sed script that works? sample data: Contact Candidate Jyoti Soni - 0 Year(s) 0 Month(s) MCA Keyskills: C , C + + , Java , JSP , Oracle , S / W Testing B.Sc Pt.Ravishanker University,Raipur MCA Pt.Ravishanker University,Raipur Currently in: Pune CTC(p.a): Not Disclosed Modified: 27 Sep 2007 Tel: 09975610476(M) Account Information Account Information Contact Candidate Minal - 0 Year(s) 0 Month(s) MCA Keyskills: c , c + + , java , ASP . NET , VB , Oracle , Dimploma in Web Designing B.Sc Shivaji University , Maharasthra MCA Shivaji University , Maharashtra Currently in: Pune CTC(p.a): INR 0 Lac(s) 5 Thousand Modified: 27 Jan 2006 Last Active: 06 Sep 2007 Tel: 9890498376(M) 011 02162 250553(R) Account Information Account Information small shell scripts that works: #!/bin/bash print $1 sed -ne '/Contact/,+1p' -e '/Tel/p' $1 |sed -e '/Contact Candidate/d'| sed -e 's/\-//'|sed -e '/^$/d'|sed -e 's/ *$//'|sed -e 's/Tel://g' -e 's/(M)//g' -e 's/0 Year(s) 0 Month(s)//g' -e 's/(R)//g' -e '/> Similar Resumes/d' sample output Jyoti Soni 09975610476 Minal 9890498376 > > Also can you show us the Python code that doesn't work > and what went wrong? Its easier to fix what's broken than > to guess at what might do what you want :-) python code that works, after that i'm a bit lost ;) import re filename = "script.txt" #regex pattern p1 = re.compile("Contact Candidate",re.IGNORECASE) p2 = re.compile ("Tel:", re.IGNORECASE) #open the file fh = open(filename,'r') #read the contents of the file to an array. file_array = fh.readlines() #create an empty array new_array = [] mod_array = [] for i in range(len(file_array)): if p1.search(file_array[i]): new_array.append(file_array[i+1]) if p2.search(file_array[i]): new_array.append(file_array[i]) new_array.append(file_array[i+1]) basically i'm trying my hand with text manipulation with python. i'm thorough with shell scripting, sed & awk. after this data is extracted i would like to convert it to a csv file, then i would like to insert the data into a database etc etc. i hope this gives a good idea of what i'm trying to do. regds, arun. -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: This is a digitally signed message part URL: From tomar.arun at gmail.com Sun Sep 28 20:19:55 2008 From: tomar.arun at gmail.com (Arun Tomar) Date: Sun, 28 Sep 2008 23:49:55 +0530 Subject: [Tutor] python regex help In-Reply-To: References: <1222613174.19482.9.camel@arun-laptop.solution.internal> Message-ID: <1222625995.19482.27.camel@arun-laptop.solution.internal> On Sun, 2008-09-28 at 17:26 +0100, Alan Gauld wrote: > "Arun Tomar" wrote > > > I've been using shell scripting & using sed & pipes i've solved it, > > but with python, i need to practice more ;). ok, i got it. here is the code that needs to be included after code in the last mail ;) sub1 = "(-.*)|(Tel:)|\(M\)|\(R\)" new_reg = re.compile(sub1) for n in range(len(new_array)): mod_array.append(new_reg.sub('',new_array[n])) cheers, arun. From metolone+gmane at gmail.com Sun Sep 28 21:14:54 2008 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Sun, 28 Sep 2008 12:14:54 -0700 Subject: [Tutor] Downloading Files from the net References: <48dfb602.2283420a.7dff.2f6f@mx.google.com> Message-ID: "Timo" wrote in message news:48dfb602.2283420a.7dff.2f6f at mx.google.com... > What is the best/correct way to download files from a webpage? > > www.example.com/example.mp3 for instance. > > I know how to open the site (with urllib), but have no idea how to write > the file to the harddisk. Quick and dirty, if example.mp3 isn't too big to fit in memory at once: import urllib fin = urllib.urlopen('http://www.example.com/example.mp3') fout = open('example.mp3','wb') fout.write(fin.read()) fin.close() fout.close() -Mark From metolone+gmane at gmail.com Sun Sep 28 21:42:27 2008 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Sun, 28 Sep 2008 12:42:27 -0700 Subject: [Tutor] python regex help References: <1222613174.19482.9.camel@arun-laptop.solution.internal> <1222625995.19482.27.camel@arun-laptop.solution.internal> Message-ID: "Arun Tomar" wrote in message news:1222625995.19482.27.camel at arun-laptop.solution.internal... > On Sun, 2008-09-28 at 17:26 +0100, Alan Gauld wrote: >> "Arun Tomar" wrote >> >> > I've been using shell scripting & using sed & pipes i've solved it, >> > but with python, i need to practice more ;). > ok, i got it. > here is the code that needs to be included after code in the last mail ;) > > sub1 = "(-.*)|(Tel:)|\(M\)|\(R\)" > new_reg = re.compile(sub1) > for n in range(len(new_array)): > mod_array.append(new_reg.sub('',new_array[n])) Given your original data, this should work: ---------------------cut-------------------------------- data = '''\ Contact Candidate Jyoti Soni - 0 Year(s) 0 Month(s) MCA Keyskills: C , C + + , Java , JSP , Oracle , S / W Testing B.Sc Pt.Ravishanker University,Raipur MCA Pt.Ravishanker University,Raipur Currently in: Pune CTC(p.a): Not Disclosed Modified: 27 Sep 2007 Tel: 09975610476(M) Account Information Account Information Contact Candidate Minal - 0 Year(s) 0 Month(s) MCA Keyskills: c , c + + , java , ASP . NET , VB , Oracle , Dimploma in Web Designing B.Sc Shivaji University , Maharasthra MCA Shivaji University , Maharashtra Currently in: Pune CTC(p.a): INR 0 Lac(s) 5 Thousand Modified: 27 Jan 2006 Last Active: 06 Sep 2007 Tel: 9890498376(M) 011 02162 250553(R) Account Information Account Information ''' import re record = re.compile(r'(?ms)Contact Candidate\s*\n(.*?) -.*?\nTel: (\d+)') print record.findall(data) ----------------------cut------------------------ Output: [('Jyoti Soni', '09975610476'), ('Minal', '9890498376')] -Mark From kent37 at tds.net Mon Sep 29 00:00:03 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 28 Sep 2008 18:00:03 -0400 Subject: [Tutor] Downloading Files from the net In-Reply-To: <48dfb602.2283420a.7dff.2f6f@mx.google.com> References: <48dfb602.2283420a.7dff.2f6f@mx.google.com> Message-ID: <1c2a2c590809281500n37afda3bq2d03bb9dfefab1e2@mail.gmail.com> On Sun, Sep 28, 2008 at 12:51 PM, Timo wrote: > What is the best/correct way to download files from a webpage? > > www.example.com/example.mp3 for instance. > > I know how to open the site (with urllib), but have no idea how to write the > file to the harddisk. urllib.urlretrieve() will do it if you don't need anything fancy like authentication. Kent From tsmundahl at comcast.net Mon Sep 29 01:36:07 2008 From: tsmundahl at comcast.net (tsmundahl at comcast.net) Date: Sun, 28 Sep 2008 23:36:07 +0000 Subject: [Tutor] Hello and some questions. Message-ID: <092820082336.1795.48E014E70004ADE800000703221652796604080E0B029A039C9B@comcast.net> Hello all. I recently starting taking Python in my state college. I joined the Python.org users group and I posted a couple of codes examples that I was having problems with, and I am wondering if there is anyone in this community that can help me. I did get some great advice on my previous posts however my code is still not working. I have two problems that I have to write code for. The first problem is a program that will take a list of ten grades from a user and then calculate the average of the ten numbers entered. The user can only use the numbers 1-10. Example. "The total average of the grades you entered in was 5" which would be the average using number 1-10 in a sequence, but it needs to calculate an average no matter if the user puts in 3 "5's" and 7 "10's". The average must be calculated. I did get some help in the python forums with this and I have come up the following, but I am getting a syntax error on the line that calls out "total" as a variable. Here is the code: value = [ ] for i in range(10): range += 1 print (int(float(raw_input("Please enter a grade, use numbers 1 - 10: "))) # getting a syntax error on this line total = sum(value) average = total/10.0 print "The average sum of all of the grades that you entered is ", ("%.2f" % average) raw_input("\nPlease hit enter to quit.") ///The code does not work. The next problem is supposed to use the while loop. A user is supposed to enter some grade values. The user will continue to be prompted to enter grade values until the user has entered in "9999" as a grade value. Then the program is supposed to calculate the average of all of the grades entered including the 9999. Here is my code, This code is not working either: target = 9999 value = [ ] while i in value < or not == target: i += 1 print grade (int(float(raw_input("Please enter a grade: "))) total = sum(value) average = total/target print "The average grade that you entered is ", ("%.2f" % average) raw_input("Please hit enter to exit.") ///Can anyone tell me what I am doing wrong on either of these problems? I know it is a logic error, but I am new to this so please bare with me. Again, thanks for your help. I am new to this forum so please have patience with me when I am posting. Thank you, Thomas Mundahl From andreengels at gmail.com Mon Sep 29 01:52:57 2008 From: andreengels at gmail.com (Andre Engels) Date: Mon, 29 Sep 2008 01:52:57 +0200 Subject: [Tutor] Hello and some questions. In-Reply-To: <092820082336.1795.48E014E70004ADE800000703221652796604080E0B029A039C9B@comcast.net> References: <092820082336.1795.48E014E70004ADE800000703221652796604080E0B029A039C9B@comcast.net> Message-ID: <6faf39c90809281652p706ba881m65899bd01ea55bb3@mail.gmail.com> On Mon, Sep 29, 2008 at 1:36 AM, wrote: > I did get some help in the python forums with this and I have come up the following, but I am getting a syntax error on the line that calls out "total" as a variable. Here is the code: The actual problem is in the previous line: print (int(float(raw_input("Please enter a grade, use numbers 1 - 10: "))) If you count, there are 4 (s and 3 )s in there. Because every ( should have a corresponding ) and vice versa, Python thinks that this statement has not finished yet. It gives a syntax error at the _next_ line, because there it finds something that cannot be a correct continuation of this statement. However, even if you would do that, the result would still not be what you want. It will give 0 each time, because value will always be the empty list. Rather than printing out the grade that the user entered, you would want to put it in the list value (an unlucky choice of a name for a list of grades, in my opinion) > The next problem is supposed to use the while loop. A user is supposed to enter some grade values. The user will continue to be prompted to enter grade values until the user has entered in "9999" as a grade value. Then the program is supposed to calculate the average of all of the grades entered including the 9999. > > Here is my code, This code is not working either: > > target = 9999 > > value = [ ] > > while i in value < or not == target: That line will indeed cause Python to stumble. I'm not even sure what you want to do here, so I can't really say what it should have been. -- Andr? Engels, andreengels at gmail.com From xboxmuncher at gmail.com Mon Sep 29 02:33:49 2008 From: xboxmuncher at gmail.com (xbmuncher) Date: Sun, 28 Sep 2008 20:33:49 -0400 Subject: [Tutor] Monitoring HTTP connections? In-Reply-To: <1c2a2c590809280439r19ade56avbd1f60fda494deb8@mail.gmail.com> References: <1c2a2c590809280439r19ade56avbd1f60fda494deb8@mail.gmail.com> Message-ID: >>Why not just set up wireshark with a filter for HTTP requests? Because I want to use the data from the HTTP requests in my python program, so it needs to be a way I can do it natively within my python program, so I can use the data it retrieves...- Show quoted text - On Sun, Sep 28, 2008 at 7:39 AM, Kent Johnson wrote: > On Sat, Sep 27, 2008 at 11:20 PM, xbmuncher wrote: > > How can I monitor the HTTP connections my windows xp system makes with > > python? > > > > I'm running a program that makes requests to websites over HTTP, I know > this > > by using a program like wireshark. I'd basically like to have a python > > program know when this other program makes these requests and be able to > > save the request data, so I know what it is requesting (to what website). > > Kind of like a mini- wireshark like program but only for HTTP requests. > > Why not just set up wireshark with a filter for HTTP requests? > > http://www.wireshark.org/docs/wsug_html_chunked/ChCapCaptureFilterSection.html > > You could also use a proxy server to log the traffic; several Python > proxy servers are listed here: > http://www.xhaus.com/alan/python/proxies.html > > Kent > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Sep 29 02:43:05 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 29 Sep 2008 01:43:05 +0100 Subject: [Tutor] Hello and some questions. References: <092820082336.1795.48E014E70004ADE800000703221652796604080E0B029A039C9B@comcast.net> Message-ID: wrote > The first problem is a program that will take a list of ten grades > from a user and then calculate the average > > value = [ ] > > for i in range(10): > range += 1 > print (int(float(raw_input("Please enter a grade, use numbers 1 - > 10: "))) This is very confused. First the range += 1 is going to be wierd because range is a function and you are trying to add one to it! Don't use variable names that are the same as built in functions. Secondly you only need to convert the value to an int. You don't need the float conversion as well. Thirdly, as already pointed out you never assign the value anywhere you just print it. You want to append it to your value list. (Also as a general style point its a good idea to name collections as plurals so use "values" instead of "value" - it just reads better) And finally the source of the error, the mismatched parens. Remember Python errors, especially syntax errorts, are often to be found a line or two before where they are reported. > The next problem is supposed to use the while loop. > A user is supposed to enter some grade values... > continue to be prompted to enter grade values until > the user has entered in "9999" as a grade value. > calculate the average of all of the grades entered including the > 9999. Really? How bizarre! > Here is my code, This code is not working either: > > target = 9999 > > value = [ ] > > while i in value < or not == target: I have no idea what you intended here. It doesn't read logically as a piece of Python or math or even English... If you remove the < sign it might make some sense as English, although not as Python... while i in value or not == target might be translated into Python as while i in value or not i == target or while i in value or i != target But in both cases its wrong since you are testing whether i is in the list of values which is not part of the excercise. It should just be while i != target: where wec assume i is the value input by the user. > i += 1 But you don't want to increment i you want to get it from the user, so i = int(raw_input(....)) Same mistake as before: you are not storing the values entered anywhere. > print grade (int(float(raw_input("Please enter a grade: "))) And you haven't assigned anything to grade and you are simply printing the input value rather than storing it in values > total = sum(value) > average = total/target And this divides the total by 9999 even if there are only 2 entries... 9999 was supposed to be the magic value used to stop the entry process not a count of how many entries were made. > print "The average grade that you entered is ", ("%.2f" % average) You need to read up on string formatting too. It should be: print "The average grade that you entered is %.2f" % average > Can anyone tell me what I am doing wrong on either of > these problems? I know it is a logic error, but I am new It's more than just logic errors you have some basic syntax issues as well as failing to understand the concepts of variables storing values during processing. print displays but assignment(=) stores. And append() adds to a list... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alecwh at gmail.com Mon Sep 29 02:53:33 2008 From: alecwh at gmail.com (Alec Henriksen) Date: Sun, 28 Sep 2008 18:53:33 -0600 Subject: [Tutor] mod_python, mod_wsgi, web.py, django! What to use? Message-ID: <1222649613.6727.6.camel@alecwh-laptop> Hello, This is my first time posting to this board, so please forgive me if I mess something up. So, lets say I want to develop a distributable web application (such as phpBB or Drupal) for Python. What platform (mod_wsgi, mod_python) would I use to reach as many users as possible, and on top of that, which (if any) framework should I use to develop this web application? Also, what are some popular python web applications (forums, cms) that I could take example of? What did they use? What is currently lacking in Python's web application selection? -- Alec Henriksen @ http://alecwh.com From srilyk at gmail.com Mon Sep 29 03:00:42 2008 From: srilyk at gmail.com (W W) Date: Sun, 28 Sep 2008 20:00:42 -0500 Subject: [Tutor] Monitoring HTTP connections? In-Reply-To: References: <1c2a2c590809280439r19ade56avbd1f60fda494deb8@mail.gmail.com> Message-ID: <333efb450809281800t7b9b7658gf821b273d8736dae@mail.gmail.com> On Sun, Sep 28, 2008 at 7:33 PM, xbmuncher wrote: > >>Why not just set up wireshark with a filter for HTTP requests? > Because I want to use the data from the HTTP requests in my python program, > so it needs to be a way I can do it natively within my python program, so I > can use the data it retrieves... > there's a tutorial about python sockets somewhere that I forget (a quick google search should be helpful), and one of the examples is a proxy server; you connect to it, it connects to some website. If you know much about programming/python, it shouldn't take *too* much effort to re-purpose it for what you're trying to do. I've never used the twisted framework but it should probably also be similarly helpful (from what I've heard). HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From dwbarne at earthlink.net Mon Sep 29 03:05:48 2008 From: dwbarne at earthlink.net (dwbarne at earthlink.net) Date: Sun, 28 Sep 2008 19:05:48 -0600 (GMT-06:00) Subject: [Tutor] trying to put Tkinter widget handlers in a module Message-ID: <9654648.1222650348658.JavaMail.root@mswamui-valley.atl.sa.earthlink.net> I am writing a large Python/Tkinter/Pmw program. It has become so big that I would like to move some of the widget handlers to a module for import. The following small program illustrates: # --- begin code --- # checkbutton frame using python & Tkinter from Tkinter import * import string class CheckButton_1(Frame): def __init__(self,msg): Frame.__init__(self,master) self.grid( ) self.createWidgets() def createWidgets(self): self.var = IntVar() c = Checkbutton( master, text='Check if yes', variable=self.var, command=self.handlerCheckButton, ) c.grid( ) def handlerCheckButton(self): self.doNotSend=self.var.get() if self.doNotSend: print "\nChecked" else: print "\nNot checked" if __name__ == "__main__": master=Tk() master.title("Checkbutton test") msg='If checked, do NOT send me a copy of this email' check=CheckButton_1(msg) check.mainloop() # --- end code --- If the method 'handlerCheckButton(self)' is moved to a module, them imported, the button may come up but once the Checkbutton is checked, the code crashes with an error. Is there no way to put handlers in a module and import them? Is 'self' getting in the way? Daniel B. From john at fouhy.net Mon Sep 29 05:13:04 2008 From: john at fouhy.net (John Fouhy) Date: Mon, 29 Sep 2008 16:13:04 +1300 Subject: [Tutor] trying to put Tkinter widget handlers in a module In-Reply-To: <9654648.1222650348658.JavaMail.root@mswamui-valley.atl.sa.earthlink.net> References: <9654648.1222650348658.JavaMail.root@mswamui-valley.atl.sa.earthlink.net> Message-ID: <5e58f2e40809282013k2f379716u6908518ee0d79b44@mail.gmail.com> 2008/9/29 : > I am writing a large Python/Tkinter/Pmw program. It has become so big that I would like to move some of the widget handlers to a module for import. The following small program illustrates: > > # --- begin code --- [...] > c = Checkbutton( > master, > text='Check if yes', > variable=self.var, > command=self.handlerCheckButton, > ) [...] > def handlerCheckButton(self): > self.doNotSend=self.var.get() > if self.doNotSend: > print "\nChecked" > else: > print "\nNot checked" > > Is there no way to put handlers in a module and import them? Is 'self' getting in the way? Short answer -- yes. Well, I guess so -- if you posted the error message you're getting, I'd be able to say for sure. Essentially, you're trying to take the event handlers out of the class, but this is a problem because they refer to attributes of the class. To get around it, you need to supply your handlers with a reference to the Frame object. I guess you could try something like this: ### handlers.py ### def handleCheckButton(obj): def handler(): obj.doNotSend = obj.var.get() if obj.doNotSend: print '\nChecked' else: print '\nNot checked' return handler ### main code ### c = Checkbutton( master, text='Check if yes', variable=self.var, command=handlers.handleCheckButton(self) ) ### I think this would work, though I have not checked it. Whether it is a good idea, though, is another question. I think moving some of your class functionality out to another module could easily confuse people.. -- John. From tomar.arun at gmail.com Mon Sep 29 06:09:26 2008 From: tomar.arun at gmail.com (Arun Tomar) Date: Mon, 29 Sep 2008 09:39:26 +0530 Subject: [Tutor] vim python debugging Message-ID: <1222661366.26749.5.camel@arun-laptop.solution.internal> hi! I"m trying to setup vim for python debugging mode. But it gives me error. Has anyone succeeded in doing so. link: http://code.google.com/p/vimpdb/ ideally I'm trying to evaluate vim & emacs as command line editors & debugging for python. arun. From tomar.arun at gmail.com Mon Sep 29 06:23:01 2008 From: tomar.arun at gmail.com (Arun Tomar) Date: Mon, 29 Sep 2008 09:53:01 +0530 Subject: [Tutor] vim python debugging In-Reply-To: <1222661525.6811.0.camel@alecwh-laptop> References: <1222661366.26749.5.camel@arun-laptop.solution.internal> <1222661525.6811.0.camel@alecwh-laptop> Message-ID: <1222662181.26749.8.camel@arun-laptop.solution.internal> On Sun, 2008-09-28 at 22:12 -0600, Alec Henriksen wrote: > It would be very helpful to include the error message you received... I > can't help you, but just a thought. > > On Mon, 2008-09-29 at 09:39 +0530, Arun Tomar wrote: > > hi! > > > > I"m trying to setup vim for python debugging mode. But it gives me > > error. Has anyone succeeded in doing so. > > > > link: > > http://code.google.com/p/vimpdb/ > > > > ideally I'm trying to evaluate vim & emacs as command line editors & > > debugging for python. > > error that i get: http://code.google.com/p/vimpdb/issues/detail?id=3 regds, arun. From cbabcock at asciiking.com Mon Sep 29 06:13:46 2008 From: cbabcock at asciiking.com (Chris Babcock) Date: Sun, 28 Sep 2008 21:13:46 -0700 Subject: [Tutor] mod_python, mod_wsgi, web.py, django! What to use? In-Reply-To: <1222649613.6727.6.camel@alecwh-laptop> References: <1222649613.6727.6.camel@alecwh-laptop> Message-ID: <20080928211346.698a8131@mail.asciiking.com> > So, lets say I want to develop a distributable web application (such > as phpBB or Drupal) for Python. What platform (mod_wsgi, mod_python) > would I use to reach as many users as possible, and on top of that, > which (if any) framework should I use to develop this web application? A lot of applications run on Apache with mod_wsgi or mod_python or as stand alone applications with or without mod_proxy. For my own environment, which usually involves some static pages and PHP apps, I prefer mod_wsgi. If you go the framework route then your application should end up being agnostic to this detail of the deployment. I happen to like the TurboGears 2 framework. It implements Pylons with a number of sane choices in the development environment. Using the SQL Alchemy ORM means that I define my data in Python and call the mapper instead of defining both a Python data structure and an SQL schema. Where portability is an issue Alchemy takes care of it transparently. Genshi is the default template engine for TG2. The performance is adequate for me and that choice allows me to have non-Pythonista friends work on the user interface. > Also, what are some popular python web applications (forums, cms) > that I could take example of? What did they use? They used PHP. :-/ I think that Python suffered for a while because it was too easy to write frameworks. For a long time it was a truism that there were as many Python frameworks as developers. I think that made Python an inconsistent performer for web applications, but mod_wsgi makes Python's relative performance under Apache compared to other web scripting languages a non-issue for the first time. > What is currently lacking in Python's web application selection? E-Commerce: http://www.oreillynet.com/onlamp/blog/2007/08/fear_and_loathing_with_low_end.html In Python e-commerce, the only significant player is Satchmo. There's an alpha release for a plug-able CMS built on TG2 due for release next week. I'd love to see an e-commerce plug-in. Chris -- Make a difference in the world and support more Diplomacy projects and services then you can shake a dagger at, please read: http://members.bluegoosenews.com/diplomacy/blog/2008/09/24/a_special_note_for_diplomacy_players - or - http://tinyurl.com/3wx6lb Blue Goose is willing to give me $250 to support various services and projects in the Diplomacy hobby. The blog post above will tell you why they are doing this, what I will do with the money, and what you can do to help me get it. From timovwb at gmail.com Mon Sep 29 09:54:36 2008 From: timovwb at gmail.com (Timo) Date: Mon, 29 Sep 2008 09:54:36 +0200 Subject: [Tutor] Downloading Files from the net In-Reply-To: References: <48dfb602.2283420a.7dff.2f6f@mx.google.com> Message-ID: <48e089b7.01a8420a.0c91.0636@mx.google.com> Mark Tolonen schreef: > "Timo" wrote in message > news:48dfb602.2283420a.7dff.2f6f at mx.google.com... >> What is the best/correct way to download files from a webpage? >> >> www.example.com/example.mp3 for instance. >> >> I know how to open the site (with urllib), but have no idea how to >> write the file to the harddisk. > > Quick and dirty, if example.mp3 isn't too big to fit in memory at once: > > import urllib > fin = urllib.urlopen('http://www.example.com/example.mp3') > fout = open('example.mp3','wb') > fout.write(fin.read()) > fin.close() > fout.close() > > -Mark > > Ok, this is what I found too, tested it and it worked. But this "if example.mp3 isn't too big to fit in memory at once" makes me "worry". Ofcourse not for a simple mp3, but if it is a much larger file. From timovwb at gmail.com Mon Sep 29 10:32:09 2008 From: timovwb at gmail.com (Timo) Date: Mon, 29 Sep 2008 10:32:09 +0200 Subject: [Tutor] Downloading Files from the net In-Reply-To: <1c2a2c590809281500n37afda3bq2d03bb9dfefab1e2@mail.gmail.com> References: <48dfb602.2283420a.7dff.2f6f@mx.google.com> <1c2a2c590809281500n37afda3bq2d03bb9dfefab1e2@mail.gmail.com> Message-ID: <48e09283.1cae420a.0ea2.04b4@mx.google.com> Kent Johnson schreef: > On Sun, Sep 28, 2008 at 12:51 PM, Timo wrote: > >> What is the best/correct way to download files from a webpage? >> >> www.example.com/example.mp3 for instance. >> >> I know how to open the site (with urllib), but have no idea how to write the >> file to the harddisk. >> > > urllib.urlretrieve() will do it if you don't need anything fancy like > authentication. > > Kent > Ok thanks, this works! And this would be the best way to do it? Also some larger, around 100-200mb, files? Cheers From alan.gauld at btinternet.com Mon Sep 29 11:41:38 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 29 Sep 2008 10:41:38 +0100 Subject: [Tutor] trying to put Tkinter widget handlers in a module References: <9654648.1222650348658.JavaMail.root@mswamui-valley.atl.sa.earthlink.net> Message-ID: wrote >I am writing a large Python/Tkinter/Pmw program. It has become > so big that I would like to move some of the widget handlers > to a module for import. The normal way to factor a GUI is by class. Move the entire class into a separate module. You cannot separate the methods of a class from the class definition. You can define an event handler outside of a class and you could then put them into a separate module but then you lose access to the state information held by the class. Modularising by class makes much more sense. It would be very unusual for a GUI class to be so big it needed to be split into separate modules. That would usually indicate that application logic was getting mixed in with the presentation logic of the GUI. 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 Mon Sep 29 11:50:28 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 29 Sep 2008 10:50:28 +0100 Subject: [Tutor] trying to put Tkinter widget handlers in a module References: <9654648.1222650348658.JavaMail.root@mswamui-valley.atl.sa.earthlink.net> <5e58f2e40809282013k2f379716u6908518ee0d79b44@mail.gmail.com> Message-ID: "John Fouhy" wrote > To get around it, you need to supply your handlers with a reference > to > the Frame object. I guess you could try something like this: > > ### handlers.py ### > def handleCheckButton(obj): > def handler(): > obj.doNotSend = obj.var.get() > if obj.doNotSend: > print '\nChecked' > else: > print '\nNot checked' > return handler > > ### main code ### > c = Checkbutton( > master, > text='Check if yes', > variable=self.var, > command=handlers.handleCheckButton(self) > ) > ### There is a simpler way using lambdas: ### handlers module ### def handler(obj): obj.doNotSend = obj.var.get() if obj.doNotSend: print '\nChecked' else: print '\nNot checked' ### main code ### c = Checkbutton( master, text='Check if yes', variable=self.var, command=lambda : handlers.handler(self) ) > I think moving some of your class functionality out to another > module could easily confuse people.. This is key. In general it is better to keep the handlers in the class. However the handlers should be quite short. If they need to manipulate data etc then that should be in a separate method/function which should be in a separate module. Event handlers typically manipulate GUI widgets. Adding data for display, extracting data from dialog fields, greying/ungreying menu items and buttons etc. Any manipulation of the data should be delegated to the model classes that represent the core objects in the application. These models are the ones that should exist in other modules. 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 Mon Sep 29 11:55:32 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 29 Sep 2008 10:55:32 +0100 Subject: [Tutor] mod_python, mod_wsgi, web.py, django! What to use? References: <1222649613.6727.6.camel@alecwh-laptop> Message-ID: "Alec Henriksen" wrote > So, lets say I want to develop a distributable web application (such > as > phpBB or Drupal) for Python. What platform (mod_wsgi, mod_python) > would > I use to reach as many users as possible, and on top of that, which > (if > any) framework should I use to develop this web application? The biggest limitation by far on Python web development is lack of Python support on the web servers. You need to find a provider that either gives you an account on a server with which you can install any frameworks you desire, or, find a provider which supports your framework. Even basic CGI with Python is a problem on most web hosting sites because although PHP and Perl will usually exist(and often Java too) it is much less common to find Python. And if you do it may be very old, often v2.2 or even older! > What is currently lacking in Python's web application selection? Very little is lacking on the Python side - see a recent thread here - but support on commercial web hosts is patchy. You need to check exactly what is available from your host before signing up. 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 Mon Sep 29 12:00:14 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 29 Sep 2008 11:00:14 +0100 Subject: [Tutor] vim python debugging References: <1222661366.26749.5.camel@arun-laptop.solution.internal><1222661525.6811.0.camel@alecwh-laptop> <1222662181.26749.8.camel@arun-laptop.solution.internal> Message-ID: "Arun Tomar" wrote >> > I"m trying to setup vim for python debugging mode. But it gives >> > me >> > error. Has anyone succeeded in doing so. >> > >> > link: >> > http://code.google.com/p/vimpdb/ >> > >> > ideally I'm trying to evaluate vim & emacs as command line >> > editors & >> > debugging for python. >> > > error that i get: > > http://code.google.com/p/vimpdb/issues/detail?id=3 It looks to me that you need to have the version of vim with Python compiled in as the macro language. I've never used vimpdb so don't know but the error messages all say that vim doesn't understanmd Python commands. And that will be true unless you use the Python enabled version of vim. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From lie.1296 at gmail.com Mon Sep 29 12:14:58 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 29 Sep 2008 17:14:58 +0700 Subject: [Tutor] Tutor Digest, Vol 55, Issue 84 In-Reply-To: References: Message-ID: <1222683298.6509.19.camel@lieryan-laptop> On Mon, 2008-09-29 at 03:00 +0200, tutor-request at python.org wrote: > > Message: 2 > Date: Sun, 28 Sep 2008 23:36:07 +0000 > From: tsmundahl at comcast.net > Subject: [Tutor] Hello and some questions. > To: tutor at python.org > Message-ID: > <092820082336.1795.48E014E70004ADE800000703221652796604080E0B029A039C9B at comcast.net> > > > Hello all. > > I recently starting taking Python in my state college. I joined the > Python.org users group and I posted a couple of codes examples that I > was having problems with, and I am wondering if there is anyone in > this community that can help me. I did get some great advice on my > previous posts however my code is still not working. I have two > problems that I have to write code for. > > The first problem is a program that will take a list of ten grades > from a user and then calculate the average of the ten numbers entered. > The user can only use the numbers 1-10. Example. "The total average of > the grades you entered in was 5" which would be the average using > number 1-10 in a sequence, but it needs to calculate an average no > matter if the user puts in 3 "5's" and 7 "10's". The average must be > calculated. > > I did get some help in the python forums with this and I have come up > the following, but I am getting a syntax error on the line that calls > out "total" as a variable. Here is the code: > > value = [ ] > > for i in range(10): > range += 1 > print (int(float(raw_input("Please enter a grade, use numbers 1 - > 10: "))) > > # getting a syntax error on this line > total = sum(value) > > average = total/10.0 > > print "The average sum of all of the grades that you entered is ", > ("%.2f" % average) > > > raw_input("\nPlease hit enter to quit.") > > ///The code does not work. This is what you want: # make integer division returns float from __future__ import division # set grade to empty list grades = [] # do something 10 times for i in range(10): # prompt user for grade and convert it into int grade = int(raw_input('Please enter a grade: ')) # append the grade to the list grades.append(grade) # sum() returns the sum of the list # len() returns the number of element in the list average = sum(grades) / len(grades) # print the result print 'Average: %.2f' % average > The next problem is supposed to use the while loop. A user is supposed > to enter some grade values. The user will continue to be prompted to > enter grade values until the user has entered in "9999" as a grade > value. Then the program is supposed to calculate the average of all of > the grades entered including the 9999. > > Here is my code, This code is not working either: > > target = 9999 > > value = [ ] > > while i in value < or not == target: > i += 1 > print grade (int(float(raw_input("Please enter a grade: "))) > > > total = sum(value) > > average = total/target > > print "The average grade that you entered is ", ("%.2f" % average) > > raw_input("Please hit enter to exit.") > > > ///Can anyone tell me what I am doing wrong on either of these > problems? I know it is a logic error, but I am new to this so please > bare with me. Again, thanks for your help. I am new to this forum so > please have patience with me when I am posting. > > Thank you, > > > > Thomas Mundahl From kent37 at tds.net Mon Sep 29 12:35:39 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 29 Sep 2008 06:35:39 -0400 Subject: [Tutor] How to replace instances In-Reply-To: <63e3a6e10809282143w65e442fem4fff1a827d7328e1@mail.gmail.com> References: <63e3a6e10809250124x3307122erb524bb2e2f303342@mail.gmail.com> <1c2a2c590809250358m4952f181u3a81e6fb5aedae80@mail.gmail.com> <63e3a6e10809250503r649a90d8s9db949008bfc03b7@mail.gmail.com> <1c2a2c590809250617m79e1d801hdf4c904153a95e1b@mail.gmail.com> <63e3a6e10809282143w65e442fem4fff1a827d7328e1@mail.gmail.com> Message-ID: <1c2a2c590809290335r9d1051dlae0f61b8ad2cb96d@mail.gmail.com> Replying to the list.. On Mon, Sep 29, 2008 at 12:43 AM, Steve Collins wrote: > Sorry it took me so long to respond; I haven't been able to afford any time > to such leisurely pursuits as programming. > I'm not cc'ing this to the Mailing list, becuase I fear it may get a little > long. It's not too long. > >> I think you still misunderstand what objects and lists and references >> are, > > > I agree. :D > >> >> this misunderstanding is making it hard to for me to >> understand what you are really trying to accomplish. Perhaps you can >> give a slightly longer example with real classes and lists, perhaps >> one that doesn't do what you want, and we can correct it. > > > Alright, this is a pared-down example of my problem. The program I'm trying > to write is a text-adventure game (seemed like a fun way to learn my way > around programming) > > there are, for example, classes which describe rooms and items: > > class Item: > def __init__(self, name): > self.name = name > itemIndex[ name ] = self > masterIndex.append(self) > > class Room: > def __init__(self, name, items): > self.name = name > self.items = items > masterIndex.append(self) > > ## which are initialized as they should appear at the beginning of the game > > iBook = Item( "book" ) > rLibrary = Room( "library", [iBook] ) > > ## when the player enters a room, currentRoom is set to the Room being > entered into. when the player enters the "take" command and specifies > "book," and sends itemIndex[ "book" ] (which is iBook) to a function is > called which goes something like: > > takeMethod(takeWhat): > if takeWhat in currentArea.items: > (remove the item from currentArea.items, add it to the player's > inventory and display "you took whatever") > else: > (display "you cant take that.") > > this works very well, and I seem to have created a working text adventure > game. my new problem is the save/load function > if the player saves, masterIndex is pickled to save.dat > when the game starts again the player has the option of loading from > save.dat. > I did this so I could avoid having a file for every pickled instance, but I > can't figure out what to do with the unpickled list. You should be pickling all the game objects and restore them from the pickle *instead* of the normal init. The unpickled masterindex should become the actual masterindex. This contains all the current items and rooms. Also pickle the player, to save inventory and location and any other player attributes. Restore the pickled player to the actual player. One way to do this would be to > > The closest I came to a solution was this: > > L = 0 > > class Item: > def __init__(self, name): > if new game: > self.name = name > elif load game: > self.name = loadedList[L].name > itemIndex[ self.name ] = self > masterIndex.append(self) > > class Room: > def __init__(self, name, items): > if new game > self.name = name > self.items = items > elif load game: > self.name = loadedList[L].name > self.items = loadedList[L].name > masterIndex.append(self) > > When the game is loaded, the player can't take the book, becuase the > takeItem function does not find itemIndex["book"] in the current room, > because itemIndex ["book"] refers to the newly initialized iBook, instead of > the old iBook. > > Even as I was writing the previous sentence, I realized that if I moved > itemIndex[ self.name ] = self to the "elif load game" condition and changed > it to "itemIndex[ self.name ] = loadedList[L]" that would fix this > particular problem. I tried it with the various dictionaries in the game, > and it does. But in the actual game, the classes refer to each in much more > complicated ways, which I fear could break this fix. It also feels clumsy, > to have all these instnaces which have the exact same data as the loaded > ones, but don't actually refer to them. > > another solution I thought of was this: > > if new game: > iBook = Item( "book" ) > rLibrary = Room( "library", [iBook] ) > elif load game: > L = 0 > iBook = loadedLis[L] > L +=1 > rLibrary = loadedList[L] > etc., etc. if new game: # normal object initialization elif load game # load masterlist from pickle file > > I think this would work well, but, again, it seems clumsy and would also > triple the number of lines I'd need in the instance initializing portion of > the program. I may be wrong, but I feel like I should be able to do this > from a loop. If you have any insight into my problem, I'd greatly appreciate > it. > > Steve Kent From kent37 at tds.net Mon Sep 29 12:39:14 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 29 Sep 2008 06:39:14 -0400 Subject: [Tutor] Downloading Files from the net In-Reply-To: <48e09283.1cae420a.0ea2.04b4@mx.google.com> References: <48dfb602.2283420a.7dff.2f6f@mx.google.com> <1c2a2c590809281500n37afda3bq2d03bb9dfefab1e2@mail.gmail.com> <48e09283.1cae420a.0ea2.04b4@mx.google.com> Message-ID: <1c2a2c590809290339k4bc1622fg7046a04ca0b42003@mail.gmail.com> On Mon, Sep 29, 2008 at 4:32 AM, Timo wrote: > Kent Johnson schreef: >> urllib.urlretrieve() will do it if you don't need anything fancy like >> authentication. >> >> Kent >> > > Ok thanks, this works! And this would be the best way to do it? Also some > larger, around 100-200mb, files? It will work with any file that will fit on disk - the input is buffered and saved to disk as it is read, it doesn't read the whole URL at once. Kent From sierra_mtnview at sbcglobal.net Mon Sep 29 13:27:49 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 29 Sep 2008 04:27:49 -0700 Subject: [Tutor] Reading Files and Such Message-ID: <48E0BBB5.2050206@sbcglobal.net> An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Mon Sep 29 13:34:16 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 29 Sep 2008 04:34:16 -0700 Subject: [Tutor] Text Scatter Plots? Message-ID: <48E0BD38.9000904@sbcglobal.net> An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Sep 29 16:13:10 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 29 Sep 2008 15:13:10 +0100 Subject: [Tutor] Text Scatter Plots? References: <48E0BD38.9000904@sbcglobal.net> Message-ID: "Wayne Watson" wrote > Is there a text graphics module that does say scatter plots or > histograms? > I'm thinking of stuff prior to the graphics era of computing. Not that I'm aware of. The best I can think of is to use curses - see a recent thread. Other than that you can create a 2D table in memory then dump that to a text based screen. Best I can think of. There wasn't much prior to graphics in computing, even many of the earliest computer programs produced graphs, it was just that they did it on paper. Remember the earliest keyboards were attached to printers so most early graphics programs simply printed a dot matrix pattern to the printer. The plot utility can stuill do that today. And Gnuplot - for which there is a Python interface - is a souped up version that can display on graphics terminals too. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld I'm looking for something really simple. > > -- > > Wayne Watson (Watson Adventures, Prop., Nevada City, CA) > > (121.01 Deg. W, 39.26 Deg. N) GMT-8 hr std. time) > > "Truth is mighty and will prevail. There is nothing wrong > with this, except that it ain't so." -- Mark Twain > > Web Page: -------------------------------------------------------------------------------- > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From sierra_mtnview at sbcglobal.net Mon Sep 29 17:33:43 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 29 Sep 2008 08:33:43 -0700 Subject: [Tutor] Text Scatter Plots? In-Reply-To: References: <48E0BD38.9000904@sbcglobal.net> Message-ID: <48E0F557.70206@sbcglobal.net> An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Mon Sep 29 17:35:27 2008 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Mon, 29 Sep 2008 08:35:27 -0700 Subject: [Tutor] mod_python, mod_wsgi, web.py, django! What to use? In-Reply-To: References: <1222649613.6727.6.camel@alecwh-laptop> Message-ID: <40af687b0809290835n3af3bb02scc0c7ec30301c59@mail.gmail.com> On Mon, Sep 29, 2008 at 2:55 AM, Alan Gauld wrote: > The biggest limitation by far on Python web development is lack > of Python support on the web servers. You need to find a provider that > either gives you an account on a server with which you can install any > frameworks you desire, or, find a provider which supports your framework. In my experience, it's not that uncommon for hosting providers to support Python - but most of the popular frameworks use "long-running processes" (I put that in quotes because I suppose it's a matter of opinion exactly how long is long.) GoDaddy in particular, and budget shared hosting services in general, don't support Django/TurboGears/Pylons etc. for this reason - but if you want to roll your own, you can. Django, TurboGears, and Pylons have pages that list hosting providers who _do_ support them. http://code.djangoproject.com/wiki/DjangoFriendlyWebHosts http://docs.turbogears.org/1.0/Hosting http://pylonshq.com/project/pylonshq/wiki/Hosting -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From srilyk at gmail.com Mon Sep 29 17:43:44 2008 From: srilyk at gmail.com (W W) Date: Mon, 29 Sep 2008 10:43:44 -0500 Subject: [Tutor] Text Scatter Plots? In-Reply-To: <48E0F557.70206@sbcglobal.net> References: <48E0BD38.9000904@sbcglobal.net> <48E0F557.70206@sbcglobal.net> Message-ID: <333efb450809290843o258a57ads5fd6ec5e8dbcf46e@mail.gmail.com> On Mon, Sep 29, 2008 at 10:33 AM, Wayne Watson wrote: > I didn't see any posts with curses in the Subject, but my participation > here 2/2008 to now with a hole in the middle where I turned to other matters > than Python. Is there an archive? > > Before GUIs, crude scatter plots and histograms on TTYs and IBM electronic > typewriters were used with only the symbols on the keyboard. Some were > pretty decent and effective. > I suppose if you really wanted to try your hand at it you could use something like string formatting, along with a monospace font to try and create some sort of ASCII plot... I don't know of any tool that's already built to do such a thing, though. -a different Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Mon Sep 29 18:03:59 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 29 Sep 2008 12:03:59 -0400 Subject: [Tutor] Text Scatter Plots? In-Reply-To: <48E0F557.70206@sbcglobal.net> References: <48E0BD38.9000904@sbcglobal.net> <48E0F557.70206@sbcglobal.net> Message-ID: <1c2a2c590809290903p7a75c5e6y6d0aa9f8bd2913fa@mail.gmail.com> On Mon, Sep 29, 2008 at 11:33 AM, Wayne Watson wrote: > I don't really want to dabble with graphics at this point, although I have > some months ago, but maybe I can grab something very elementary and use it. > At the moment, I don't want to get into all the finery of using GUIs. > However, it seems as though there ought to be some really simple set up to > just produce a scatter plot. Maybe I'm overestimating the difficulty. Producing a scatterplot with matplotlib and displaying the result in a window can be pretty simple. Here is an example that displays a sine curve in eight lines of code: http://msenux.redwoods.edu/mathdept/python/simple.php Kent From adrian.greyling at gmail.com Mon Sep 29 19:05:53 2008 From: adrian.greyling at gmail.com (Adrian Greyling) Date: Mon, 29 Sep 2008 13:05:53 -0400 Subject: [Tutor] pysqlite and SQLite Message-ID: <866c750d0809291005r171b75eah32ef669be60240e1@mail.gmail.com> Probably a really dumb question, but... Do I have to download and install SQLite before pysqlite will work properly? Thanks, Adrian -------------- next part -------------- An HTML attachment was scrubbed... URL: From adrian.greyling at gmail.com Mon Sep 29 19:27:53 2008 From: adrian.greyling at gmail.com (Adrian Greyling) Date: Mon, 29 Sep 2008 13:27:53 -0400 Subject: [Tutor] pysqlite and SQLite In-Reply-To: <584940990809291009i4cbaea79s8fd06912012e59b6@mail.gmail.com> References: <866c750d0809291005r171b75eah32ef669be60240e1@mail.gmail.com> <584940990809291009i4cbaea79s8fd06912012e59b6@mail.gmail.com> Message-ID: <866c750d0809291027p71c43e29x2f3282726bc5bcce@mail.gmail.com> Thanks for the response Chad! I'm using Python 2.5.2, so I guess I'm in the clear then, although I'm still getting an unexplained error message. I've taken my program and used GUI2exe to create a standalone executable. When I run said executable on my own WinXP machine, it works just fine. When I attempt to use the same executable (including the "dist" directory) on a (virtually) identical PC, I get the following error message: pysqlite2.dbapi2.OperationalError: near ",": syntax error I understand the error, but not why I get it on one PC and not another... Adrian On Mon, Sep 29, 2008 at 1:09 PM, Chad Crabtree wrote: > If you are using Python 2.5 or newer then no you will not need to install > SQLite. > > On Mon, Sep 29, 2008 at 1:05 PM, Adrian Greyling < > adrian.greyling at gmail.com> wrote: > >> Probably a really dumb question, but... Do I have to download and install >> SQLite before pysqlite will work properly? >> Thanks, >> Adrian >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> > -------------- next part -------------- An HTML attachment was scrubbed... URL: From roadierich at googlemail.com Mon Sep 29 19:29:49 2008 From: roadierich at googlemail.com (Richard Lovely) Date: Mon, 29 Sep 2008 18:29:49 +0100 Subject: [Tutor] pysqlite and SQLite In-Reply-To: <866c750d0809291005r171b75eah32ef669be60240e1@mail.gmail.com> References: <866c750d0809291005r171b75eah32ef669be60240e1@mail.gmail.com> Message-ID: If you're compiling from source you do: http://oss.itsystementwicklung.de/trac/pysqlite/browser/doc/install-source.txt If you've got an installer, it shouldn't let you install if you don't have the right things installed. Even if you can install pysqlite, you wouldn't be able to run any pysqlite code if you don't have the sqlite software. 2008/9/29 Adrian Greyling : > Probably a really dumb question, but... Do I have to download and install > SQLite before pysqlite will work properly? > Thanks, > Adrian > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Richard "Roadie Rich" Lovely, part of the JNP|UK Famile www.theJNP.com From srini_iyyer_bio at yahoo.com Tue Sep 30 00:19:02 2008 From: srini_iyyer_bio at yahoo.com (Srinivas Iyyer) Date: Mon, 29 Sep 2008 15:19:02 -0700 (PDT) Subject: [Tutor] re.compile concatenating two searh words Message-ID: <366829.43777.qm@web38105.mail.mud.yahoo.com> Hi Tutors, I have a list with elements as strings. I want to search if any of these element strings has two words of my interest. How can I ask re.compile to look for both words. my words are 'good' and 'bad'. import re pat = re.compile('good'+'bad') a = ['Rama is a good boy','Raghu is a good boy','Sita is a good girl','Ravana is a bad boy','Duryodhan is a bad guy','good is an acceptable nature while bad is unwanted nature in a person'] pat.findall(a) I want to search instances of both 'bad' and 'good' in a string. from the list 'a' above, I am expecting the result: 'good is an acceptable nature while bad is unwanted nature in a person' how can I define my pattern using re.compile. I appreciate your help. thank you. srini From bgailer at gmail.com Tue Sep 30 00:27:56 2008 From: bgailer at gmail.com (bob gailer) Date: Mon, 29 Sep 2008 18:27:56 -0400 Subject: [Tutor] Reading Files and Such In-Reply-To: <48E0BBB5.2050206@sbcglobal.net> References: <48E0BBB5.2050206@sbcglobal.net> Message-ID: <48E1566C.1090107@gmail.com> Wayne Watson wrote: > I have a Python application that requires the program be run in a > specific folder, Win XP. It analyzes and modifies txt files there, and > only txt files. The mods require creating a tmp file. The tmp files > could just as well be an xyz suffix file. That is, it seems as though > they could be almost any non-conflicting type with hundreds of file > types in use. There may be other file types in the folder, possibly > jpg. As such, why would I want to use the tmp files module? > > With a similar program, it requires reading through all txt files, > among other files types, in the folder. It purely analyzes the data in > the txt files. Is there some way of doing the reading without the use > of os.listdir()? I'm finding it a little hard to grok your question / concern. One does not use os.listdir() to read files. One opens them then uses read or readline. There are many ways to get and filter directory contents. I guess you would benefit from the glob module. import glob fileList = glob.glob('*.txt') -- Bob Gailer Chapel Hill NC 919-636-4239 When we take the time to be aware of our feelings and needs we have more satisfying interatctions with others. Nonviolent Communication provides tools for this awareness. As a coach and trainer I can assist you in learning this process. What is YOUR biggest relationship challenge? From steve at alchemy.com Tue Sep 30 00:43:11 2008 From: steve at alchemy.com (Steve Willoughby) Date: Mon, 29 Sep 2008 15:43:11 -0700 Subject: [Tutor] re.compile concatenating two searh words In-Reply-To: <366829.43777.qm@web38105.mail.mud.yahoo.com> References: <366829.43777.qm@web38105.mail.mud.yahoo.com> Message-ID: <20080929224311.GB80636@dragon.alchemy.com> On Mon, Sep 29, 2008 at 03:19:02PM -0700, Srinivas Iyyer wrote: > Hi Tutors, > I have a list with elements as strings. I want to search if any of these element strings has two words of my interest. How can I ask re.compile to look for both words. > > my words are 'good' and 'bad'. > > import re > > pat = re.compile('good'+'bad') Ok, first of all think about how the compiler will interpret and act upon this expression. You are calling a function with a single argument. That argument is 'good'+'bad', which means to concatenate those two strings into a single string value 'goodbad', and that is the value passed to re.compile(). The re.compile() function cannot know that you added the strings, since that is done before it ever gets to work, so if you were thinking that somehow was meaningful to the regular expression, that was a mistaken impression. > a = ['Rama is a good boy','Raghu is a good boy','Sita is a good girl','Ravana is a bad boy','Duryodhan is a bad guy','good is an acceptable nature while bad is unwanted nature in a person'] So you want to match any sentence with BOTH 'good' AND 'bad' in them? you could say: re.compile('good.*bad') but that would work only if good came first. It would not match a string like 'The bad thing about good people is...' You could do re.compile('good.*bad|bad.*good') I suppose, or several other possibilities. I'm not sure exactly what to suggest since I am guessing you're trying to give a simplified example and aren't literally looking for this pattern in your program. > pat.findall(a) findall is really for finding all the occurrences of a pattern in a string, not all the matching strings in a list. you can do this in a filter() to get what I think you're trying to accomplish. -- Steve Willoughby | Using billion-dollar satellites steve at alchemy.com | to hunt for Tupperware. From malaclypse2 at gmail.com Tue Sep 30 01:18:01 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Mon, 29 Sep 2008 19:18:01 -0400 Subject: [Tutor] re.compile concatenating two searh words In-Reply-To: <366829.43777.qm@web38105.mail.mud.yahoo.com> References: <366829.43777.qm@web38105.mail.mud.yahoo.com> Message-ID: <16651e80809291618p4d65baa6p82d271138dd997b6@mail.gmail.com> On Mon, Sep 29, 2008 at 6:19 PM, Srinivas Iyyer wrote: > Hi Tutors, > I have a list with elements as strings. I want to search if any of these element strings has two words of my interest. How can I ask re.compile to look for both words. > > my words are 'good' and 'bad'. If this really reflects your requirements, regular expressions are not a good choice in the first place. Instead, I would use some of python's built in string functionality, like this: >>> a = ['Rama is a good boy','Raghu is a good boy','Sita is a good girl','Ravana is a bad boy','Duryodhan is a bad guy','good is an acceptable nature while bad is unwanted nature in a person'] >>> for item in a: if 'good' in item and 'bad' in item: print item good is an acceptable nature while bad is unwanted nature in a person >>> -- Jerry From parrisdc at gmail.com Tue Sep 30 04:33:56 2008 From: parrisdc at gmail.com (Don Parris) Date: Mon, 29 Sep 2008 22:33:56 -0400 Subject: [Tutor] range/for list change behavior Message-ID: <1eba300b0809291933i5e53f89cs4ff6b1838a2456ae@mail.gmail.com> Hi all, After a rather long (and unfortunate) break from tinkering with Python, I am back at it. I am working through the book Learning Python (based on 2.2/2.3 - I use 2.5), and in the chapter on while/for loops, ran across the following example: >>> L = [1, 2, 3, 4, 5] >>> for i in range(len(L)): ... L[1] += 1 # this is a typo I made - should have been L[i], not L[1]. ... >>> L [1, 7, 3, 4, 5] I did correct my typo, but what I do not understand is how range arrived at a '7', where the '2' should be. My best guess is that L[1] is treated as the index of the value '2'. I hope that learning how my error affected the result will help me grasp the concept a little better. Thanks! Don -- D.C. Parris Minister, Journalist, Free Software Advocate https://www.xing.com/profile/Don_Parris http://www.linkedin.com/in/dcparris sip:dcparris at ekiga.net -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at alchemy.com Tue Sep 30 05:17:52 2008 From: steve at alchemy.com (Steve Willoughby) Date: Mon, 29 Sep 2008 20:17:52 -0700 Subject: [Tutor] range/for list change behavior In-Reply-To: <1eba300b0809291933i5e53f89cs4ff6b1838a2456ae@mail.gmail.com> References: <1eba300b0809291933i5e53f89cs4ff6b1838a2456ae@mail.gmail.com> Message-ID: <48E19A60.3010408@alchemy.com> Don Parris wrote: > Hi all, > > After a rather long (and unfortunate) break from tinkering with Python, > I am back at it. I am working through the book Learning Python (based > on 2.2/2.3 - I use 2.5), and in the chapter on while/for loops, ran > across the following example: > > >>> L = [1, 2, 3, 4, 5] > >>> for i in range(len(L)): > ... L[1] += 1 # this is a typo I made - > should have been L[i], not L[1]. > ... > >>> L > [1, 7, 3, 4, 5] > > I did correct my typo, but what I do not understand is how range arrived > at a '7', where the '2' should be. My best guess is that L[1] is > treated as the index of the value '2'. I hope that learning how my You are correct. In the expression L[n], you are referring to the nth element in the list L (where n starts at 0). So L[1] is the element which starts off with the value 2 in your example. When you execute: for i in range(len(L)): L[1] += 1 that will increment element #1 once each time through the loop, giving you the result [1, 7, 3, 4, 5] If you correct your loop to read as: for i in range(len(L)): L[i] += 1 You'll get [2, 3, 4, 5, 6] as the result. i will iterate over the range from 0 to len(L)-1, or [0,1,2,3,4] and for each of those numbers increment the corresponding element of L. > error affected the result will help me grasp the concept a little better. > > Thanks! > Don > -- > D.C. Parris > Minister, Journalist, Free Software Advocate > https://www.xing.com/profile/Don_Parris > http://www.linkedin.com/in/dcparris > sip:dcparris at ekiga.net > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From shiv_mbm at hotmail.com Tue Sep 30 12:00:42 2008 From: shiv_mbm at hotmail.com (ShivKumar Anand) Date: Tue, 30 Sep 2008 15:30:42 +0530 Subject: [Tutor] unable to import Image module from my application Message-ID: I am using Python Image library on windows and it is running well. I am using RHEL E4 on another machine and when I installed "python-imaging-1.1.6-2.el4.rf.i386.rpm", still i am not able to call the Image and ImagOps modules from my application on this Linux machine. After that --I manually added Imaging1.1.4 folder in /usr/lib/Python2.4/site-packages and added entry in easy_install.pth. After that, I am able to import the modules from python prompt, but still I am not able to import from my application. I am not able to figure out the exact reason for this. Kindly guiide me. Thanks in anticipation. Shiv _________________________________________________________________ Search for videos of Bollywood, Hollywood, Mollywood and every other wood, only on Live.com http://www.live.com/?scope=video&form=MICOAL -------------- next part -------------- An HTML attachment was scrubbed... URL: From joefazee at gmail.com Tue Sep 30 16:32:55 2008 From: joefazee at gmail.com (A. Joseph) Date: Tue, 30 Sep 2008 07:32:55 -0700 Subject: [Tutor] Replacing cmd.exe with custom .py application Message-ID: Instead of going to the command line all the time, I want to create a small customized cmd.exe of my own, how can I get the return value from os.system() because I was thinking I can do soothing with os.system(), In case my question is not clear, just like an IDE that plugged in another .exe application. Sorry for any mistake in my question. Just help me if you can -------------- next part -------------- An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Tue Sep 30 20:27:55 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Tue, 30 Sep 2008 11:27:55 -0700 Subject: [Tutor] Tutor Archives and PC Crash Message-ID: <48E26FAB.5010206@sbcglobal.net> My Win/PC crashed yesterday and I'm not able to follow my recent posts. I'm on another computer now. Is there an archive for the tutor list? From dyoo at cs.wpi.edu Tue Sep 30 20:38:16 2008 From: dyoo at cs.wpi.edu (Danny Yoo) Date: Tue, 30 Sep 2008 14:38:16 -0400 Subject: [Tutor] Tutor Archives and PC Crash In-Reply-To: <48E26FAB.5010206@sbcglobal.net> References: <48E26FAB.5010206@sbcglobal.net> Message-ID: Yup. See: http://mail.python.org/pipermail/tutor/ for the archive. There's also a searchable interface from GMANE: http://dir.gmane.org/gmane.comp.python.tutor From pierre.dagenais at ncf.ca Tue Sep 30 21:58:10 2008 From: pierre.dagenais at ncf.ca (Pierre Dagenais) Date: Tue, 30 Sep 2008 15:58:10 -0400 Subject: [Tutor] python: can't open file 'test.py' : [Errno 2] No such file or directory Message-ID: <48E284D2.7040201@ncf.ca> The file test.py is in I:\Python25\MyCode, if I enter: C:\>Python25\MyCode\python25 test.py at the DOS prompt, everything works as I would expect. However when I enter the same command from any other directory I get this error: C:\>python test.py python: can't open file 'test.py' : [Errno 2] No such file or directory I've set the environment variable pythonpath as C:\>set pythonpath = C:\\Python25\\MyCode what am I doing wrong, Thank u for your help, From srilyk at gmail.com Tue Sep 30 23:05:32 2008 From: srilyk at gmail.com (W W) Date: Tue, 30 Sep 2008 16:05:32 -0500 Subject: [Tutor] python: can't open file 'test.py' : [Errno 2] No such file or directory In-Reply-To: <48E284D2.7040201@ncf.ca> References: <48E284D2.7040201@ncf.ca> Message-ID: <333efb450809301405m47c52c32t178e8b2e0d65c34e@mail.gmail.com> On Tue, Sep 30, 2008 at 2:58 PM, Pierre Dagenais wrote: > The file test.py is in I:\Python25\MyCode, > if I enter: > > C:\>Python25\MyCode\python25 test.py at the DOS prompt, everything works > as I would expect. > > However when I enter the same command from any other directory I get this > error: > > C:\>python test.py > python: can't open file 'test.py' : [Errno 2] No such file or directory > > I've set the environment variable pythonpath as > C:\>set pythonpath = C:\\Python25\\MyCode > I'm not entirely sure about Windows, but my guess is that your problem is that the pythonpath isn't what you need to set. I would venture to guess that it's searching for test.py in your current path. If I'm correct in my thinking, all it does when you set the python path is tells python to execute in that directory, so if your script contains something like f = open("myfile.txt", "w") it will put it in that directory. You may want to try this: The path is now managed by Windows 2000 / Windows XP and not the autoexec.bat or autoexec.nt files. To change the system environment variables, follow the below steps. 1. From the desktop , right-click My Computer and click properties. 2. In the System Properties window, click on the Advanced tab . 3. In the Advanced section, click the Environment Variables button . 4. Finally, in the Environment Variables window, highlight the path variable in the Systems Variable section and click edit. Add or modify the path lines with the paths you wish the computer to access. Each different directory is separated with a semicolon as shown below. C:\Program Files;C:\Winnt;C:\Winnt\System32 from: http://www.computerhope.com/issues/ch000549.htm Try adding the path to your code in that way, and see if it works. 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 -------------- next part -------------- An HTML attachment was scrubbed... URL: From timothy.grant at gmail.com Tue Sep 30 23:06:04 2008 From: timothy.grant at gmail.com (Timothy Grant) Date: Tue, 30 Sep 2008 14:06:04 -0700 Subject: [Tutor] python: can't open file 'test.py' : [Errno 2] No such file or directory In-Reply-To: <48E284D2.7040201@ncf.ca> References: <48E284D2.7040201@ncf.ca> Message-ID: On Tue, Sep 30, 2008 at 12:58 PM, Pierre Dagenais wrote: > The file test.py is in I:\Python25\MyCode, > if I enter: > > C:\>Python25\MyCode\python25 test.py at the DOS prompt, everything works as > I would expect. > > However when I enter the same command from any other directory I get this > error: > > C:\>python test.py > python: can't open file 'test.py' : [Errno 2] No such file or directory > > I've set the environment variable pythonpath as > C:\>set pythonpath = C:\\Python25\\MyCode > what am I doing wrong, > Thank u for your help, > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > You need to give the full path to your test.py file. PYTHONPATH sets the python library search path. -- Stand Fast, tjg. [Timothy Grant] From alan.gauld at btinternet.com Tue Sep 30 23:15:36 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 30 Sep 2008 22:15:36 +0100 Subject: [Tutor] Text Scatter Plots? References: <48E0BD38.9000904@sbcglobal.net> <48E0F557.70206@sbcglobal.net> Message-ID: "Wayne Watson" wrote > Before GUIs, crude scatter plots and histograms on TTYs > and IBM electronic typewriters were used with only the > symbols on the keyboard. Some were pretty decent and > effective. Basioc charts can be done that way but usually they are just produceed by print statements with no special charting or plotting software. The earliest plotting software that I'm aware of all used bitmap imaging to the dot matrix printers of the time > I don't really want to dabble with graphics at this point The point of the graphics libraries like gnuplot is that they make it easier to produce real graphics than it is to try fancy printing techniques. > I don't want to get into all the finery of using GUIs. The plotting libraries can usually throw up a window for you. It won't be a full GUI application just a floating window in screen with a graph drawn in it. Check out the screenshots. Alternatively they can save the image to a file which you can display in any graopghics program or web browser of your choice. > However, it seems as though there ought to be some > really simple set up to just produce a scatter plot. > Maybe I'm overestimating the difficulty. One way to find out would be to try writing one yourself. You could then make it available to the community. Sounds like a useful project... -- 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 Sep 30 23:23:09 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 30 Sep 2008 22:23:09 +0100 Subject: [Tutor] Replacing cmd.exe with custom .py application References: Message-ID: "A. Joseph" wrote > Instead of going to the command line all the time, I want to create > a small > customized cmd.exe of my own, I'm not sure that I understand what you are trying to do. But trying to replace cmd.exe is a very very bad idea. Lots of bits of your operatinfg system rely on cmd.exe and bad things are likely to start happening! > how can I get the return value from > os.system() Same as any other function: retval = os.system('notepad.exe') > because I was thinking I can do soothing with os.system(), In > case my question is not clear, just like an IDE that plugged in > another > .exe application. Sorry, that didn't clarify anything for me! :-) Are you trying to write your own operating system shell environment (to use instead of cmd.exe)? Are you trying to write a Python based command shell? Or are you trying to create your own IDE? I'm confused. -- 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 Sep 30 23:26:19 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 30 Sep 2008 22:26:19 +0100 Subject: [Tutor] Tutor Archives and PC Crash References: <48E26FAB.5010206@sbcglobal.net> Message-ID: "Danny Yoo" wrote in message news:d06401780809301138y26b88a67kb96454dd6b92a651 at mail.gmail.com... > Yup. See: > > http://mail.python.org/pipermail/tutor/ > > for the archive. There's also a searchable interface from GMANE: > > http://dir.gmane.org/gmane.comp.python.tutor And another at ActiveState.com http://lists.activestate.com/tutor at python.org Alan G