From kromag@nsacom.net Wed Aug 1 00:53:14 2001 From: kromag@nsacom.net (kromag@nsacom.net) Date: Tue, 31 Jul 2001 16:53:14 -0700 (PDT) Subject: [Tutor] [Long!] Varying degrees of precision Message-ID: <200107312353.f6VNrEY29493@pop.nsacom.net> Hi all! Sorry I've been a stranger lately, but I have been decending into C. I have noticed that there are some weirdnesses occouring when converting integers to floats in python. I wrote the following module as the beginnings of a "hot rod math" project. The first function, suck() gives the proper cfm flow for a carburetor on an engine of a given size at a given rpm. ------------begin rodney.py----------- '''Suck gives a good idea of the required carburetor flow for an engine of a given volume in cubic centimeters at a given RPM. Note: suck does not round up to nearest cfm, but merely strip everything to the right of the decimal. If you are really, really anal, replace 'int(cfm) with 'cfm' in the lines below and revel in your increased accuracy... then cry as you realize you can't buy a carb for your Buick that flows at the exactly optimal 347.83669982303041 CF/M. Now calm down.''' '''usage: suck(350,5500,'sae') or: suck(2000.00,6000.00,'cc') <---here it is! Hint: 'sae' is the only thing you have to remember. 'cc' could be replaced by 'booger' and it would still work.''' def suck(cc,rpm,increment): if increment == 'sae': cid=cc else: cid=cc/16.387 # This line converts from cc to cid- lazy. cfm=( cid/2 )*( rpm/1728 )*.85 #Assumes 85% volumetric effeciency. #return int( cfm ) return cfm ------------end rodney.py--------------- rodney.py returns: ------------begin rodney output--------- Python 2.0 (#8, Oct 16 2000, 17:27:58) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. IDLE 0.6 -- press F1 for help >>> >>> from rodney import suck >>> suck(2000,6000,'cc') 155.61115518398728 >>> suck(2000.00,6000.00,'cc') 180.10550368517048 >>> ------------end rodney output------------ note the differences in the results! I figured this out when I wrote the following lame C program: ----------lame c program----------------- #include float rpm; float cc; float cid; float cfm; main() { rpm=6000; cc=2000; cid=cc/16.387; cfm=(cid/2)*(rpm/1728)*.85; printf("%f",cfm); return(0); } ---------end lame c program--------------- which returns 180.105499 Is this a case of weak typing biting me on the backside, or is there a pythonic way to specify a float? Thanks! From kromag@nsacom.net Wed Aug 1 00:57:40 2001 From: kromag@nsacom.net (kromag@nsacom.net) Date: Tue, 31 Jul 2001 16:57:40 -0700 (PDT) Subject: [Tutor] [Long!] Varying degrees of precision Message-ID: <200107312357.f6VNveY04968@pop.nsacom.net> Hi all! Sorry I've been a stranger lately, but I have been decending into C. I have noticed that there are some weirdnesses occouring when converting integers to floats in python. I wrote the following module as the beginnings of a "hot rod math" project. The first function, suck() gives the proper cfm flow for a carburetor on an engine of a given size at a given rpm. ------------begin rodney.py----------- '''Suck gives a good idea of the required carburetor flow for an engine of a given volume in cubic centimeters at a given RPM. Note: suck does not round up to nearest cfm, but merely strip everything to the right of the decimal. If you are really, really anal, replace 'int(cfm) with 'cfm' in the lines below and revel in your increased accuracy... then cry as you realize you can't buy a carb for your Buick that flows at the exactly optimal 347.83669982303041 CF/M. Now calm down.''' '''usage: suck(350,5500,'sae') or: suck(2000.00,6000.00,'cc') <---here it is! Hint: 'sae' is the only thing you have to remember. 'cc' could be replaced by 'booger' and it would still work.''' def suck(cc,rpm,increment): if increment == 'sae': cid=cc else: cid=cc/16.387 # This line converts from cc to cid- lazy. cfm=( cid/2 )*( rpm/1728 )*.85 #Assumes 85% volumetric effeciency. #return int( cfm ) return cfm ------------end rodney.py--------------- rodney.py returns: ------------begin rodney output--------- Python 2.0 (#8, Oct 16 2000, 17:27:58) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. IDLE 0.6 -- press F1 for help >>> >>> from rodney import suck >>> suck(2000,6000,'cc') 155.61115518398728 >>> suck(2000.00,6000.00,'cc') 180.10550368517048 >>> ------------end rodney output------------ note the differences in the results! I figured this out when I wrote the following lame C program: ----------lame c program----------------- #include float rpm; float cc; float cid; float cfm; main() { rpm=6000; cc=2000; cid=cc/16.387; cfm=(cid/2)*(rpm/1728)*.85; printf("%f",cfm); return(0); } ---------end lame c program--------------- which returns 180.105499 Is this a case of weak typing biting me on the backside, or is there a pythonic way to specify a float? Thanks! From Charlie Clark Thu Aug 2 18:19:53 2001 From: Charlie Clark (Charlie Clark) Date: Thu, 02 Aug 2001 19:19:53 +0200 Subject: [Tutor] Help with Parsing HTML files Message-ID: <00038a8f403fd220_mailit@mail.isis.de> As part of a prototype I need to be able to plug in several different content websites and pull headlines to put them on my own website through the medium of a database. I know that the normal way of doing is the subscribing to some XML-based format but that isn't possible at the moment as the streams would be too expensive (around Euro 5000 per stream per month). We have a couple of Visual Basic scripts doing this at the moment but I have suggested the move away: the scripts are not easily reusable or extensible; Python would give us platform independence and moving from VB + MS SQL to Python + PostgreSQL or similar has a certain commercial logic. Scenario: a wbe page providing content (x articles on the page all in the same format) there are no handy comment tags in the source differentiating the various parts of interest. What's the best way to go about parsing the HTML? I've looked at sgmllib and htmllib and am a bit lost. The worst thing for me about Python's documentation is it's lack of examples. I leafed through all the Python books in the bookshop today but failed to find much inspiration. One of the problems I'll admit to having is not being able to work out how to use a class simply by reading it's code - it just doesn't work for me :-(( I see the following alternatives: 1) extend and improve on treating the source as plain-text. Making use of regular expressions might be useful here. 2) use a library module to parse the html-source and get it to release the appropriate objects I'd really like to be able to have a system which could easily be trained to deal with new source formats on a kind of template basis. Here's a made up example source .... .... continues with the rest of the articles I'm currently analysing the source and working out ways to separate articles from each other and then read individual articles. As I'm having to read the source into a single string I can see sgmllib and htmllib calling, I just don't know what they are saying to me so at the moment it's a question while string contains articles: markers = [list of markers] start = string.find(markers[0]) stop = string.find(markers[-1]) article = string[start:stop] do_something_with_article(article, markers=markers) # pulls out the contens and writes them into the database string = string[stop:] Would it be possible to take this source and mark it up as a template which would in turn generate markers for automated parsing? So would become Then a program could learn how to parse a new page based on the template and happily go about doing it. This would separate templating from programming and be useful in itself. Would this be a good idea? How would I go about doing this "properly" using the modules? Many thanx for any help and pointers. Charlie -- Charlie Clark Helmholtzstr. 20 Dьsseldorf D- 40215 Tel: +49-211-938-5360 GSM: +49-178-463-6199 http://www.begeistert.org From jcosby@mindspring.com Thu Aug 2 16:48:07 2001 From: jcosby@mindspring.com (Jon Cosby) Date: Thu, 2 Aug 2001 08:48:07 -0700 Subject: [Tutor] Re: Hit Counter Message-ID: Thanks for the responses so far. I've made some changes, but so far haven't resolved the problem. I've added the line to my Web page, which by the looks of it, should execute the script each time I load the Web page. It's only running when I the script page. Can anybody see why this is? -----------------counter.pyw---------------------------------- #! c:\python21\pythonw.exe print "Content-type: text/html" print print "Python Hit Counter" print "" InFile = open("count.dat", "r") Hits = InFile.readline() x = int(Hits) + 1 h = str(x) OutFile = open("count.dat", "w") OutFile.write(h) OutFile.close() print "

Jon Cosby's web page - Total hits:



" for i in h: print "" print "" -------------------------------------------------------------- Jon Cosby jcosby@mindspring.com www.jcosby.com From dsh8290@rit.edu Thu Aug 2 19:48:58 2001 From: dsh8290@rit.edu (dman) Date: Thu, 2 Aug 2001 14:48:58 -0400 Subject: [Tutor] Re: Hit Counter In-Reply-To: ; from jcosby@mindspring.com on Thu, Aug 02, 2001 at 08:48:07AM -0700 References: Message-ID: <20010802144858.B8596@harmony.cs.rit.edu> On Thu, Aug 02, 2001 at 08:48:07AM -0700, Jon Cosby wrote: | Thanks for the responses so far. I've made some changes, but | so far haven't resolved the problem. I've added the line | | | | to my Web page, which by the looks of it, should execute the | script each time I load the Web page. It's only running when | I the script page. Can anybody see why this is? What web server are you using? '' ends a comment (though '>' might be enough). Thus everything in between those have no effect at all. I do recall seeing that on previous versions of Zope that sort of syntax was used in their DTML files. -D From Charlie Clark Thu Aug 2 19:53:46 2001 From: Charlie Clark (Charlie Clark) Date: Thu, 02 Aug 2001 20:53:46 +0200 Subject: [Tutor] Re: Hit Counter References: Message-ID: <00038a909005fa9e_mailit@mail.isis.de> >Thanks for the responses so far. I've made some changes, but >so far haven't resolved the problem. I've added the line > > > >to my Web page, which by the looks of it, should execute the >script each time I load the Web page. It's only running when >I the script page. Can anybody see why this is? This won't work. You can't get a web page to do any work as HTML doesn't have any commands. is just a comment in HTML which means it *won't* be interpreted by anything at all! You've got two choices: either turn the page itself into a script (save it as .cgi and in the appropriate directory) in which case it will call other scripts *or* call the script via a trick such as . The general advice is against ".pyw" as this won't necessarily work if you move the script to another computer. Is your webserver configured to run Python files? Does "/cgi-bin/counter.pyw" work in your browser? Charlie -- Charlie Clark Helmholtzstr. 20 Dьsseldorf D- 40215 Tel: +49-211-938-5360 GSM: +49-178-463-6199 http://www.begeistert.org From alan.gauld@bt.com Thu Aug 2 16:44:29 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Thu, 2 Aug 2001 16:44:29 +0100 Subject: [Tutor] range() in 2.1 Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BE3B@mbtlipnt02.btlabs.bt.co.uk> A question: I am still using Python 2.0 but am reviewing an article which uses Python 2.1. Throughout the article the examples consistently act as if range(10) returns the values 1..9 whereas in all the earlier pythons it would return 0..9 Have the authors got it wrong or did range() change behaviour in v2.1 - I find that hard to believe! OTOH the examples in the article look like a cut n paste from a terminal session at the >>> prompt (including copyright message etc) Puzzled. Alan G. From Charlie Clark Thu Aug 2 20:11:54 2001 From: Charlie Clark (Charlie Clark) Date: Thu, 02 Aug 2001 21:11:54 +0200 Subject: [Tutor] range() in 2.1 References: <5104D4DBC598D211B5FE0000F8FE7EB20E66BE3B@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <00038a90d0e66304_mailit@mail.isis.de> >the values 1..9 whereas in all the earlier pythons >it would return 0..9 > >Have the authors got it wrong or did range() change >behaviour in v2.1 - I find that hard to believe! >OTOH the examples in the article look like a cut n paste >from a terminal session at the >>> prompt (including >copyright message etc) If that's the case let me try ;-) Python 2.1 (#2, Apr 26 2001, 21:54:18) [GCC 2.9-beos-991026] on beos5 Type "copyright", "credits" or "license" for more information. >>> for i in range(10): print i, ... 0 1 2 3 4 5 6 7 8 9 >>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] mm, looks pretty the same as ever to me. I would wonder a lot if it had changed, that surely break a lot of things!!! Charlie -- Charlie Clark Helmholtzstr. 20 Dьsseldorf D- 40215 Tel: +49-211-938-5360 GSM: +49-178-463-6199 http://www.begeistert.org From dsh8290@rit.edu Thu Aug 2 20:38:14 2001 From: dsh8290@rit.edu (dman) Date: Thu, 2 Aug 2001 15:38:14 -0400 Subject: [Tutor] range() in 2.1 In-Reply-To: <00038a90d0e66304_mailit@mail.isis.de>; from charlie@begeistert.org on Thu, Aug 02, 2001 at 09:11:54PM +0200 References: <5104D4DBC598D211B5FE0000F8FE7EB20E66BE3B@mbtlipnt02.btlabs.bt.co.uk> <00038a90d0e66304_mailit@mail.isis.de> Message-ID: <20010802153814.B8819@harmony.cs.rit.edu> On Thu, Aug 02, 2001 at 09:11:54PM +0200, Charlie Clark wrote: | >the values 1..9 whereas in all the earlier pythons | >it would return 0..9 | > | >Have the authors got it wrong or did range() change | >behaviour in v2.1 - I find that hard to believe! | >OTOH the examples in the article look like a cut n paste | >from a terminal session at the >>> prompt (including | >copyright message etc) | | If that's the case let me try ;-) | | Python 2.1 (#2, Apr 26 2001, 21:54:18) | [GCC 2.9-beos-991026] on beos5 ... | mm, looks pretty the same as ever to me. I would wonder a lot if it had | changed, that surely break a lot of things!!! Same here with Python 2.1 (#1, Apr 17 2001, 09:45:01) [GCC 2.95.3-2 (cygwin special)] on cygwin_nt-4.01 and Python 2.1 (#1, Jul 27 2001, 15:48:55) [GCC 2.95.2 19991024 (release)] on sunos5 I think that article must be rather buggy :-). -D From ak@silmarill.org Thu Aug 2 20:21:26 2001 From: ak@silmarill.org (Andrei Kulakov) Date: Thu, 02 Aug 2001 15:21:26 -0400 Subject: [Tutor] range() in 2.1 In-Reply-To: <"from alan.gauld"@bt.com> References: <5104D4DBC598D211B5FE0000F8FE7EB20E66BE3B@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <20010802152126.A7501@sill.silmarill.org> On Thu, Aug 02, 2001 at 04:44:29PM +0100, alan.gauld@bt.com wrote: > A question: > > I am still using Python 2.0 but am reviewing an > article which uses Python 2.1. Throughout the article > the examples consistently act as if range(10) returns > the values 1..9 whereas in all the earlier pythons > it would return 0..9 Prentice, right? I noticed this too and it is, indeed, very odd. I have no idea how they got this result - I use 2.1 and it starts with 0, as it should. Note that later on they sometimes use range(1, num). > > Have the authors got it wrong or did range() change > behaviour in v2.1 - I find that hard to believe! > OTOH the examples in the article look like a cut n paste > from a terminal session at the >>> prompt (including > copyright message etc) > > Puzzled. Me too. > > Alan G. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: http://silmarill.org/cymbaline From arcege@speakeasy.net Thu Aug 2 20:45:38 2001 From: arcege@speakeasy.net (Michael P. Reilly) Date: Thu, 2 Aug 2001 15:45:38 -0400 (EDT) Subject: [Tutor] Re: Hit Counter In-Reply-To: <20010802144858.B8596@harmony.cs.rit.edu> from "dman" at Aug 02, 2001 02:48:58 PM Message-ID: <200108021945.f72JjcV01097@dsl092-074-184.bos1.dsl.speakeasy.net> dman wrote > > On Thu, Aug 02, 2001 at 08:48:07AM -0700, Jon Cosby wrote: > | Thanks for the responses so far. I've made some changes, but > | so far haven't resolved the problem. I've added the line > | > | > | > | to my Web page, which by the looks of it, should execute the > | script each time I load the Web page. It's only running when > | I the script page. Can anybody see why this is? > > What web server are you using? '' ends a comment (though '>' might be > enough). Thus everything in between those have no effect at all. I > do recall seeing that on previous versions of Zope that sort of syntax > was used in their DTML files. Most all web servers in the last ten years have been able to handle Server-Side Includes (SSIs), IF activated in the server. It all depends on what the server allows. Zope is not the web, it is one application server on the web, and there are more books out there describing (in part) SSIs than Zope and DTML. -Arcege -- +----------------------------------+-----------------------------------+ | Michael P. Reilly | arcege@speakeasy.net | From dsh8290@rit.edu Thu Aug 2 20:50:24 2001 From: dsh8290@rit.edu (dman) Date: Thu, 2 Aug 2001 15:50:24 -0400 Subject: [Tutor] Re: Hit Counter In-Reply-To: <200108021945.f72JjcV01097@dsl092-074-184.bos1.dsl.speakeasy.net>; from arcege@dsl092-074-184.bos1.dsl.speakeasy.net on Thu, Aug 02, 2001 at 03:45:38PM -0400 References: <20010802144858.B8596@harmony.cs.rit.edu> <200108021945.f72JjcV01097@dsl092-074-184.bos1.dsl.speakeasy.net> Message-ID: <20010802155024.A8870@harmony.cs.rit.edu> On Thu, Aug 02, 2001 at 03:45:38PM -0400, Michael P. Reilly wrote: | dman wrote | | > On Thu, Aug 02, 2001 at 08:48:07AM -0700, Jon Cosby wrote: | > | Thanks for the responses so far. I've made some changes, but | > | so far haven't resolved the problem. I've added the line | > | | > | | > | | > | to my Web page, which by the looks of it, should execute the | > | script each time I load the Web page. It's only running when | > | I the script page. Can anybody see why this is? | > | > What web server are you using? '' ends a comment (though '>' might be | > enough). Thus everything in between those have no effect at all. I | > do recall seeing that on previous versions of Zope that sort of syntax | > was used in their DTML files. | | Most all web servers in the last ten years have been able to handle | Server-Side Includes (SSIs), IF activated in the server. It all depends | on what the server allows. I haven't really used SSI, but I thought the syntax was more like the C preprocessor : #include I could be way off though since it has been a while since I read anything on SSI. | Zope is not the web, it is one application server on the web, and | there are more books out there describing (in part) SSIs than Zope | and DTML. Right, but that syntax (commands, etc, embedded in comments) looks familiar from having looked over Zope docs. :-) -D From Charlie Clark Thu Aug 2 21:19:19 2001 From: Charlie Clark (Charlie Clark) Date: Thu, 02 Aug 2001 22:19:19 +0200 Subject: [Tutor] Re: Hit Counter References: <20010802144858.B8596@harmony.cs.rit.edu> <200108021945.f72JjcV01097@dsl092-074-184.bos1.dsl.speakeasy.net> <20010802155024.A8870@harmony.cs.rit.edu> Message-ID: <00038a91c1f98227_mailit@mail.isis.de> >| Most all web servers in the last ten years have been able to handle >| Server-Side Includes (SSIs), IF activated in the server. It all depends >| on what the server allows. Be that as it may I think we're getting a little off track with the original question. >I haven't really used SSI, but I thought the syntax was more like the >C preprocessor : > >#include yep. But what's the point? The counter does nothing else than duplicate the log file. A really crude hit counter would simply count how many lines are in the log file! >I could be way off though since it has been a while since I read >anything on SSI. > >| Zope is not the web, it is one application server on the web, and >| there are more books out there describing (in part) SSIs than Zope >| and DTML. > >Right, but that syntax (commands, etc, embedded in comments) looks >familiar from having looked over Zope docs. :-) This is true. Zope's DTML uses this notation - it's useful because it doesn't show up in a preview and most HTML editors leave it alone. Other embedded scripting approaches use something similar where the directives ar embedded in the comments. The server knows when to pass a file to an engine by the file extension (phtml, shtl, asp, jsp, php, psp, cfm, stm, dtml) and the engine interprets (and removes= the directives embedded in the comments. But this never happens for plain HTML files and Jon's post seemed to want a line that could be added to each web page ie. .html and of course the python involved. "exec" can only be used inside a python script, so it won't work here. For reaons which others are much better at explaining it is to be used with caution! The web-counter could work as a server side include. Jon, does your server support SSI? Do you have it running? If not either an embedded scripting language is necessary or an object in the page will have to call the script. Using an image to do this is about the best way of making sure it works. Charlie -- Charlie Clark Helmholtzstr. 20 Dьsseldorf D- 40215 Tel: +49-211-938-5360 GSM: +49-178-463-6199 http://www.begeistert.org From fleet@teachout.org Fri Aug 3 00:22:01 2001 From: fleet@teachout.org (fleet@teachout.org) Date: Thu, 2 Aug 2001 19:22:01 -0400 (EDT) Subject: [Tutor] Time problem Message-ID: I'm quite happy with the three letter abbreviations for the months; but my client prefers to have them spelled out. I can't find a way to do that in time module or the python docs. Do I need to create a dictionary ({"Jan":"January"} etc.)? (Hmmm. Forgot to check google python list search function). - fleet - From kalle@gnupung.net Fri Aug 3 01:08:57 2001 From: kalle@gnupung.net (Kalle Svensson) Date: Fri, 3 Aug 2001 02:08:57 +0200 Subject: [Tutor] Time problem In-Reply-To: ; from fleet@teachout.org on Thu, Aug 02, 2001 at 07:22:01PM -0400 References: Message-ID: <20010803020857.A15635@gandalf> Sez fleet@teachout.org: > I'm quite happy with the three letter abbreviations for the months; but my > client prefers to have them spelled out. I can't find a way to do that in > time module or the python docs. Do I need to create a dictionary > ({"Jan":"January"} etc.)? Use %B instead of %b to strftime(). >>> import time >>> time.strftime("%b %B", time.localtime()) 'Aug August' Peace, Kalle -- Free Dmitry Sklyarov! - http://www.freesklyarov.org/ From shalehperry@home.com Fri Aug 3 04:58:26 2001 From: shalehperry@home.com (Sean 'Shaleh' Perry) Date: Thu, 02 Aug 2001 20:58:26 -0700 (PDT) Subject: [Tutor] Help with Parsing HTML files In-Reply-To: <00038a8f403fd220_mailit@mail.isis.de> Message-ID: I know this does not directly help, but several of us have posted examples of htmllib code in recent months. Do a search for htmlllib in the archives. If you still need help, one of us should be able to pull the message we sent up. From zdanie@europe.com Fri Aug 3 07:34:55 2001 From: zdanie@europe.com (=?windows-1251?Q?=CF=EE=F0=F2=EE=E2=E0=FF,_19?=) Date: Fri, 3 Aug 2001 10:34:55 +0400 Subject: [Tutor] =?windows-1251?Q?=CF=F0=EE=E4=E0=E5=F2=F1=FF_=E0=E4=EC=E8=ED=E8=F1=F2=F0=E0=F2=E8=E2=ED=EE=E5_=E7=E4=E0=ED=E8=E5_=E2_=CA=E0=E7=E0=ED=E8?= Message-ID: <5151200185363455202@Athlon> Здравствуйте! Наше почтение. Предлагаем приобрести в собственность административное здание в Казани (Татарстан, Россия): - Общая площадь 910 кв. м; - 2 этажа; - Большое количество помещений от 7 до 200 кв.м; - Собственная территория - земельный участок 0,101 Га. Здание - бывшая столовая речного порта. Имеет выгодное расположение: - напротив здания - второй по величине оптовый продуктовый городской рынок; - удобные подъездные пути; - близко к центру города - 5 мин. езды; - близко к ж/д вокзалу - 5 мин. езды; - рядом речной порт; - рядом ж/д пути. Здание идеально подходит для размещения офиса представительства Вашей компании в Татарстане или Поволжье. Возможна компоновка "офис/склад". Все коммуникации подведены. Здание требует ремонта (полная внутренняя отделка, включая новые оконные и дверные блоки). Здание находится в частной собственности. Земля - в бессрочном пользовании. Цена здания - БОЛЕЕ ЧЕМ ДОСТУПНА. Если вы заинтересованы в получении от нас более подробной информации о данном объекте, отправьте пустое письмо по адресу: zdanie@europe.com. При этом в "Теме" сообщения ОБЯЗАТЕЛЬНО напишите: "Пришлите подробную информацию". From kent@springfed.com Fri Aug 3 12:25:33 2001 From: kent@springfed.com (Kent Tenney) Date: Fri, 3 Aug 2001 06:25:33 -0500 Subject: [Tutor] Help with Parsing HTML files In-Reply-To: <00038a8f403fd220_mailit@mail.isis.de> References: Message-ID: <200108031127.GAA13677@svc1.netwk-innov.net> I had a look at the archives, I don't see how to search it, only to browse a month of postings at a time. -- Kent Tenney, kent@springfed.com on 08/03/2001 On Thu, 02 Aug 2001 20:58:26 -0700 (PDT), Sean 'Shaleh' Perry= wrote: =3D>I know this does not directly help, but several of us have= posted examples of =3D>htmllib code in recent months. =A0Do a search for htmlllib in the= archives. =3D> =3D>If you still need help, one of us should be able to pull the= message we sent up. =3D> =3D>_______________________________________________ =3D>Tutor maillist =A0- =A0Tutor@python.org =3D>http://mail.python.org/mailman/listinfo/tutor From Charlie Clark Fri Aug 3 13:24:02 2001 From: Charlie Clark (Charlie Clark) Date: Fri, 03 Aug 2001 14:24:02 +0200 Subject: [Tutor] Help with Parsing HTML files References: <200108031127.GAA13677@svc1.netwk-innov.net> Message-ID: <00038a9f3c1014f2_mailit@mail.isis.de> >I had a look at the archives, I don't see how to search it, >only to browse a month of postings at a time. I couldn't find a search button either so I downloaded the last three months and searched them in my editor. It was in the merry month of may that this was last up for discussion and Remco posted the following snippet: import htmllib class ImgFinder(htmllib.HTMLParser): def __init__(self): # Normal HTMLParser takes a 'formatter' argument but we don't need it htmllib.HTMLParser.__init__(self, None) def handle_image(self, source, alt, *args): # *args holds "ismap", "align", "width" and "height", if available, # but we ignore those here print "Found an image!" print "Source =", source, "Alt =", alt finder = ImgFinder() finder.feed(aa) # Feed in the string, it should find the images Now I need an idiot proof user guide for this. We create an instance of ImgFinder which is based on htmllib.HTMLParser. When we construct an instance of this class we format to None. We add a method "handle_image" which has some nice arguments and prints "Found an image!" together with the image source and alt tag. "finder" is an instance of our class and gets fed a string - I assume this would be the contents of an HTML file. What I don't see is how the handle_image function/method looks for images and I need to learn how to use this in order to modify it for my own dark purposes! Please help. Charlie From lep@aber.ac.uk Fri Aug 3 14:17:58 2001 From: lep@aber.ac.uk (Leighton Pritchard) Date: Fri, 03 Aug 2001 14:17:58 +0100 Subject: [Tutor] Re: Hit Counter Message-ID: <5.1.0.14.0.20010803140346.040bd5c0@pophost.aber.ac.uk> Hi Jon et al, and are both valid SSI directives. The problems with server side includes are twofold: Not all servers allow SSIs. In this case, neither instruction works. Servers that allow SSIs do not always allow you to use the exec directive - you can turn this off in the config files, or in .htaccess. Here, the first directive will work (i.e. plonk the plaintext contents of filename into the page), but the second won't. Which is probably the situation you're in. Have a look at: http://www.bignosebird.com/ssi.shtml http://hoohoo.ncsa.uiuc.edu/docs/tutorials/includes.html http://httpd.apache.org/docs/howto/ssi.html for more info. I think Charlie's earlier advice is probably the pragmatic way to go for you. -- Dr Leighton Pritchard GRSC T44, Cledwyn Building Institute of Biological Sciences University of Wales, Aberystwyth, SY23 3DD Tel 01970 622353 ext. 2353 PGP public key - http://www.keyserver.net (0x47B4A485) From kromag@nsacom.net Fri Aug 3 18:07:54 2001 From: kromag@nsacom.net (kromag@nsacom.net) Date: Fri, 3 Aug 2001 10:07:54 -0700 (PDT) Subject: [Tutor] Hanging myself on substitution Message-ID: <200108031707.f73H7sY05980@pop.nsacom.net> I have asked variants of this question several times, but for some reason it just doesn't stick. This is a simple "pick ten cards" reader that guffs a list out of a text file, chooses one "card", prints it to the screen, then removes the "card" from the list. What I am trying to do recalculate the number of items in the list. I count them, then put that number as the second integer in a random.randint() function. -------begin pickacard.py----------- import random import string cards=open('\windows\desktop\cards.txt','r') schmack=cards.readlines() counter=0 while counter <10: total_cards=len(schmack) '''here is where my pain begins...''' choose=random.randint(1,%i)% total_cards #<-grrr! chosen=schmack[choose] del schmack[choose] print chosen counter=counter+1 -------end pickacard.py------------ of course the depricated: random.randint(1, string.atoi(`total_cards`)) as in: ------begin uglypickacard.py------ import random import string cards=open('\windows\desktop\cards.txt','r') schmack=cards.readlines() total_cards=len(schmack) counter=0 while counter <10: total_cards=len(schmack) choose=random.randint(1,string.atoi(`total_cards`)) chosen=schmack[choose] del schmack[choose] print chosen counter=counter+1 -------end uglypickacard.py--------- seems to work fine. What is the proper method so's I don't shoot myself in the foot later? From kromag@nsacom.net Fri Aug 3 18:17:39 2001 From: kromag@nsacom.net (kromag@nsacom.net) Date: Fri, 3 Aug 2001 10:17:39 -0700 (PDT) Subject: [Tutor] ....and another thing! Message-ID: <200108031717.f73HHdY18143@pop.nsacom.net> In the following: mport random import string cards=open('\windows\desktop\cards.txt','r') schmack=cards.readlines() counter=0 while counter <10: total_cards=len(schmack) choose=random.randint(1,string.atoi(`total_cards`)) chosen=schmack[choose] del schmack[choose] print chosen counter=counter+1 I will get the occasional: Traceback (most recent call last): File "reader.py", line 9, in ? chosen=schmack[choose] IndexError: list index out of range >Exit code: 1 It seems to me that: total_cards=len(schmack) should recalculate the number of items in the list with each iteration of the loop. Since there are 72 items in the list, and one item is removed from the list at the end of every iteration, it stands to reason that the list index should be accurately recalculated by len(). Where am I going wrong? From sabrina@madisoncomunicacao.com.br Fri Aug 3 16:10:38 2001 From: sabrina@madisoncomunicacao.com.br (Sabrina) Date: Fri, 3 Aug 2001 12:10:38 -0300 Subject: [Tutor] Form action with python script Message-ID: <00ff01c11c2e$7482b140$5d01a8c0@intranet.madisoncomunicacao.com.br> This is a multi-part message in MIME format. ------=_NextPart_000_00FC_01C11C15.4EE165D0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi, I'm working with a Python Script in Zope but I'm having some problems. = I'm trying to call a python script in a "form action" because I have to = make some calculations with some values of this form. I call like this: =
but normally a form action calls another page. So, the question is: I'd like to call a python script and, in this = script, make a redirect to another page(url). Can I do that?? I hope you can help me :) Sorry if I'm not being clear! Sabrina Araujo. ------=_NextPart_000_00FC_01C11C15.4EE165D0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Hi,
 
I'm working with a Python Script = in Zope but=20 I'm having some problems. I'm trying to call a python script = in a=20 "form action" because I have to make some calculations with some values = of this=20 form. I call like this: <form name=3D"form1"=20 action=3D"a_python_script">
but normally a form action calls = another=20 page.
So, the question is: I'd like to = call a python=20 script and, in this script, make a redirect to another page(url). = Can I do=20 that??
 
I hope you can help me :)
Sorry if I'm not being = clear!
 
Sabrina=20 Araujo.
------=_NextPart_000_00FC_01C11C15.4EE165D0-- From kromag@nsacom.net Fri Aug 3 18:24:42 2001 From: kromag@nsacom.net (kromag@nsacom.net) Date: Fri, 3 Aug 2001 10:24:42 -0700 (PDT) Subject: [Tutor] Re: ...and another thing Message-ID: <200108031724.f73HOgY27753@pop.nsacom.net> Once again, the script: import random import string cards=open('\windows\desktop\cards.txt','r') schmack=cards.readlines() counter=0 while counter <3: total_cards=len(schmack) choose=random.randint(1,string.atoi(`total_cards`)) chosen=schmack[choose] del schmack[choose] print chosen counter=counter+1 Could it be that since I am removing the items in the list by number, that any time that number is called again I get my index out of range error?: Traceback (most recent call last): File "reader.py", line 9, in ? chosen=schmack[choose] IndexError: list index out of range >Exit code: 1 Is there any way to re-assign the numbers (positions?) in the list? I tried just doing: schmack=schmack in hopes that would reassign the positions. Unfortunately I don't have my books with me today! Yikes! d From dsh8290@rit.edu Fri Aug 3 16:40:01 2001 From: dsh8290@rit.edu (dman) Date: Fri, 3 Aug 2001 11:40:01 -0400 Subject: [Tutor] ....and another thing! In-Reply-To: <200108031717.f73HHdY18143@pop.nsacom.net>; from kromag@nsacom.net on Fri, Aug 03, 2001 at 10:17:39AM -0700 References: <200108031717.f73HHdY18143@pop.nsacom.net> Message-ID: <20010803114001.G9253@harmony.cs.rit.edu> On Fri, Aug 03, 2001 at 10:17:39AM -0700, kromag@nsacom.net wrote: | total_cards=len(schmack) | choose=random.randint(1,string.atoi(`total_cards`)) ^^^^^^^^^^^^^^^^^^^^^^^^^^ Why convert the integer to a string, then parse the string back to an integer? Also, as I look at http://python.mirrors.netnumina.com/doc/current/lib/module-random.html#l2h-875 I see that randint can return a number that is equal to the lower or upper bounds. You are using that number as the index in the next line. | chosen=schmack[choose] | I will get the occasional: | | Traceback (most recent call last): | File "reader.py", line 9, in ? | chosen=schmack[choose] | IndexError: list index out of range | >Exit code: 1 | should recalculate the number of items in the list with each iteration of the | loop. Since there are 72 items in the list, and one item is removed from the | list at the end of every iteration, it stands to reason that the list index | should be accurately recalculated by len(). Where am I going wrong? If 'l' is a list, l[ len( l ) ] will try to access the element just past the end of the list. For your line above you want : choose = random.randint( 0 , total_cards-1 ) and it will work. By lowering the lower bound I am allowing the first card to be chosen as well. HTH, -D From Charlie Clark Fri Aug 3 17:08:21 2001 From: Charlie Clark (Charlie Clark) Date: Fri, 03 Aug 2001 18:08:21 +0200 Subject: [Tutor] Re: ...and another thing References: <200108031724.f73HOgY27753@pop.nsacom.net> Message-ID: <00038aa25e4fe37f_mailit@mail.isis.de> >import random >import string >cards=open('\windows\desktop\cards.txt','r') >schmack=cards.readlines() >counter=0 >while counter <3: > total_cards=len(schmack) > choose=random.randint(1,string.atoi(`total_cards`)) > chosen=schmack[choose] > del schmack[choose] > print chosen > counter=counter+1 mm, I'd rewrite this a little for legibility. What d-man has already said about the random function seems to cover most of the problem but I wonder why you are using 'while'. I think a 'for' construction would make more sense as it does the iterating for you so there is no need to count manually. import random file_in = open('\windows\desktop\cards.txt','r') cards = file_in.readlines() num_cards = len(cards) for i in range(3): #I think your first example would have been #range(num_cards) to deal all the cards card = random.randint(0, num_cards) print cards[card] del demo[card] Charlie (hopeless at programming but interested in style) From Charlie Clark Fri Aug 3 17:14:42 2001 From: Charlie Clark (Charlie Clark) Date: Fri, 03 Aug 2001 18:14:42 +0200 Subject: [Tutor] Re: ...and another thing References: <200108031724.f73HOgY27753@pop.nsacom.net> <00038aa25e4fe37f_mailit@mail.isis.de> Message-ID: <00038aa274fd2844_mailit@mail.isis.de> >import random >file_in = open('\windows\desktop\cards.txt','r') >cards = file_in.readlines() > > >for i in range(3): #I think your first example would have been > #range(num_cards) to deal all the cards > card = random.randint(0, num_cards) > print cards[card] > del demo[card] oops need to correct myself here. You're right, as num_cards changes each loop it should be inside the loop itself. Having said that it should just be a reference... oh well. it needs to be in the loop. And, of course, I made the same mistake as you about forgetting the difference betweent the number of items in an object and indexing them. The correct code should be: for i in range(3): # or range(whatever) num_cards = len(cards) card = random.randint(0, num_cards-1) print cards[card] del demo[card] Charlie From alan.gauld@bt.com Fri Aug 3 17:25:25 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri, 3 Aug 2001 17:25:25 +0100 Subject: [Tutor] Hanging myself on substitution Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BE46@mbtlipnt02.btlabs.bt.co.uk> > import random > import string > cards=open('\windows\desktop\cards.txt','r') > schmack=cards.readlines() > counter=0 > while counter <10: > total_cards=len(schmack) move this outside the loop since you only need to do it once. > '''here is where my pain begins...''' > choose=random.randint(1,%i)% total_cards #<-grrr! The % format operator only works on strings you should do: choose=random.randint(1,total_cards) # or use random.choice maybe? > chosen=schmack[choose] > del schmack[choose] # now decrement total_cards coz youve removed one. total_cards -= 1 > print chosen > counter=counter+1 You could use a "for counter in range(10):" to do the same job with less work... Alan G. From tidddl@hotmail.com Fri Aug 3 17:36:31 2001 From: tidddl@hotmail.com (Darryl Tidd) Date: Fri, 3 Aug 2001 11:36:31 -0500 Subject: [Tutor] New to this Message-ID: This is a multi-part message in MIME format. ------=_NextPart_000_0070_01C11C10.8A8808F0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi, I'm new to this stuff. I'm trying to learn to write some programs = in Python, I was wondering if someone could give me some exercises to = do. I.e. I need some ideas on some programs to write for practice in = this stuff. Any help will be appreciated. Darryl Tidd ------=_NextPart_000_0070_01C11C10.8A8808F0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Hi, I'm new to this stuff.  I'm = trying to=20 learn to write some programs in Python, I was wondering if someone could = give me=20 some exercises to do.  I.e. I need some ideas on some programs to = write for=20 practice in this stuff.
 
Any help will be = appreciated.
 
Darryl Tidd
------=_NextPart_000_0070_01C11C10.8A8808F0-- From rob@jam.rr.com Fri Aug 3 17:46:23 2001 From: rob@jam.rr.com (Rob Andrews) Date: Fri, 3 Aug 2001 11:46:23 -0500 Subject: [Tutor] New to this In-Reply-To: Message-ID: This is a multi-part message in MIME format. ------=_NextPart_000_0004_01C11C11.EB4E8D20 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: 7bit Ah, the sort of question I live for.... http://www.lowerstandard.com/python/ Useless Python (now that it's back up after all those technical difficulties) tries to be a good Python playground. What sort of programming do you think you might want to write in Python? Perhaps we could point you to some really good material suited to you. And remember you can ask for an assist at any point. Uselessly, Rob Your one-stop shop for newbie source code! Useless Python: http://www.lowerstandard.com/python/ -----Original Message----- From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of Darryl Tidd Sent: Friday, August 03, 2001 11:37 AM To: Python Group Subject: [Tutor] New to this Hi, I'm new to this stuff. I'm trying to learn to write some programs in Python, I was wondering if someone could give me some exercises to do. I.e. I need some ideas on some programs to write for practice in this stuff. Any help will be appreciated. Darryl Tidd ------=_NextPart_000_0004_01C11C11.EB4E8D20 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Ah,=20 the sort of question I live for....
 
http://www.lowerstandard.co= m/python/
 
Useless Python (now that it's back up after = all those=20 technical difficulties) tries to be a good Python=20 playground.
 
What=20 sort of programming do you think you might want to write in Python? = Perhaps we=20 could point you to some really good material suited to you. And remember = you can=20 ask for an assist at any point.
 
Uselessly,
Rob
 

Your one-stop shop for newbie source code!
Useless = Python: http://www.lowerstandard.com/python/

-----Original Message-----
From: = tutor-admin@python.org=20 [mailto:tutor-admin@python.org]On Behalf Of Darryl = Tidd
Sent:=20 Friday, August 03, 2001 11:37 AM
To: Python = Group
Subject:=20 [Tutor] New to this

Hi, I'm new to this stuff.  I'm = trying to=20 learn to write some programs in Python, I was wondering if someone = could give=20 me some exercises to do.  I.e. I need some ideas on some programs = to=20 write for practice in this stuff.
 
Any help will be = appreciated.
 
Darryl = Tidd
------=_NextPart_000_0004_01C11C11.EB4E8D20-- From bsass@freenet.edmonton.ab.ca Fri Aug 3 18:09:34 2001 From: bsass@freenet.edmonton.ab.ca (Bruce Sass) Date: Fri, 3 Aug 2001 11:09:34 -0600 (MDT) Subject: [Tutor] New to this In-Reply-To: Message-ID: On Fri, 3 Aug 2001, Darryl Tidd wrote: > Hi, I'm new to this stuff. I'm trying to learn to write some programs in Python, I was wondering if someone could give me some exercises to do. I.e. I need some ideas on some programs to write for practice in this stuff. > > Any help will be appreciated. You could start with a couple of filters; one to strip HTML from email, another to enforce line lengths of about 72 characters. ;-) I think it is most instructive to do exercises from languages you already know, first, then move onto fresh stuff in Python. The idea being... you know the how's and why's of those exercises already, so you can concentrate on the Python translation. - Bruce From rob@jam.rr.com Fri Aug 3 18:59:57 2001 From: rob@jam.rr.com (Rob Andrews) Date: Fri, 3 Aug 2001 12:59:57 -0500 Subject: [Tutor] New to this In-Reply-To: Message-ID: # # You could start with a couple of filters; # one to strip HTML from email, # another to enforce line lengths of about 72 characters. # ;-) # Nah, a better idea is to write a script that randomly inserts HTML tags into plain text email messages, then BCC the messages to the Pine Users email list (if such a thing exists). Muwhahahaha! 3;-> Me? Evil? Rob Your one-stop shop for newbie source code! Useless Python: http://www.lowerstandard.com/python/ From ak@silmarill.org Fri Aug 3 16:03:43 2001 From: ak@silmarill.org (Andrei Kulakov) Date: Fri, 03 Aug 2001 11:03:43 -0400 Subject: [Tutor] ....and another thing! In-Reply-To: <"from kromag"@nsacom.net> References: <200108031717.f73HHdY18143@pop.nsacom.net> Message-ID: <20010803110343.A12609@sill.silmarill.org> On Fri, Aug 03, 2001 at 10:17:39AM -0700, kromag@nsacom.net wrote: > In the following: > > mport random import random > import string > cards=open('\windows\desktop\cards.txt','r') 'r' is redundant.. > schmack=cards.readlines() > counter=0 > while counter <10: > total_cards=len(schmack) > choose=random.randint(1,string.atoi(`total_cards`)) ?? wouldn't random.randint(1,total_cards) work just as well? > chosen=schmack[choose] > del schmack[choose] > print chosen > counter=counter+1 > > > I will get the occasional: > > Traceback (most recent call last): > File "reader.py", line 9, in ? > chosen=schmack[choose] > IndexError: list index out of range > >Exit code: 1 > > It seems to me that: > > total_cards=len(schmack) > > should recalculate the number of items in the list with each iteration of the > loop. Since there are 72 items in the list, and one item is removed from the > list at the end of every iteration, it stands to reason that the list index > should be accurately recalculated by len(). Where am I going wrong? I'm not sure, but maybe it's off-by-one error? Anyway, if you use random.choice(), it should be just fine. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: http://silmarill.org/cymbaline From ak@silmarill.org Fri Aug 3 15:52:00 2001 From: ak@silmarill.org (Andrei Kulakov) Date: Fri, 03 Aug 2001 10:52:00 -0400 Subject: [Tutor] Hanging myself on substitution In-Reply-To: <"from kromag"@nsacom.net> References: <200108031707.f73H7sY05980@pop.nsacom.net> Message-ID: <20010803105200.A12551@sill.silmarill.org> On Fri, Aug 03, 2001 at 10:07:54AM -0700, kromag@nsacom.net wrote: > I have asked variants of this question several times, but for some reason it > just doesn't stick. This is a simple "pick ten cards" reader that guffs a > list out of a text file, chooses one "card", prints it to the screen, then > removes the "card" from the list. I'm sorry I didn't read the code carefully, but it /sounds/ like you may want to use random.choice(list) that returns a random item from list. > > What I am trying to do recalculate the number of items in the list. I count > them, then put that number as the second integer in a random.randint() > function. > > -------begin pickacard.py----------- > > import random > import string > cards=open('\windows\desktop\cards.txt','r') > schmack=cards.readlines() > counter=0 > while counter <10: > total_cards=len(schmack) > '''here is where my pain begins...''' > choose=random.randint(1,%i)% total_cards #<-grrr! > chosen=schmack[choose] > del schmack[choose] > print chosen > counter=counter+1 > -------end pickacard.py------------ > > of course the depricated: > > random.randint(1, string.atoi(`total_cards`)) > > as in: > > ------begin uglypickacard.py------ > import random > import string > cards=open('\windows\desktop\cards.txt','r') > schmack=cards.readlines() > total_cards=len(schmack) > counter=0 > while counter <10: > total_cards=len(schmack) > choose=random.randint(1,string.atoi(`total_cards`)) > chosen=schmack[choose] > del schmack[choose] > print chosen > counter=counter+1 > -------end uglypickacard.py--------- > > seems to work fine. What is the proper method so's I don't shoot myself in > the foot later? > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: http://silmarill.org/cymbaline From vlindberg@verio.net Fri Aug 3 19:30:52 2001 From: vlindberg@verio.net (VanL) Date: Fri, 03 Aug 2001 12:30:52 -0600 Subject: [Tutor] Replacement of items in a list Message-ID: <3B6AEDDC.7000205@verio.net> Why is this? :::::::::::::: Begin test.py #!/usr/bin/env python import string lst = ['ONE', 'TWO', 'THREE'] lst1 = lst[:] lst2 = lst[:] def replace1(list): """ Uses item replacement""" for x in list: x = string.lower(x) def replace2(list): """Uses position replacement""" for x in range(len(list)): list[x] = string.lower(list[x]) :::::::: Begin Interpreter Session >>> from test import * >>> dir() ['__builtins__', '__doc__' ace2', 'string'] >>> lst1 ['ONE', 'TWO', 'THREE'] >>> lst2 ['ONE', 'TWO', 'THREE'] >>> replace1(lst1) >>> replace2(lst2) >>> lst1 ['ONE', 'TWO', 'THREE'] >>> lst2 ['one', 'two', 'three'] From sheila@thinkspot.net Fri Aug 3 20:05:30 2001 From: sheila@thinkspot.net (Sheila King) Date: Fri, 03 Aug 2001 12:05:30 -0700 Subject: [Tutor] How to make foreign characters Message-ID: <3C4488B06F6@kserver.org> Hello, I need some advice and pointers: I've been teaching my 15 year old son his first programming language. (A good summertime project while off from school) Of course, Python. Anyhow, the project we are working on right now, is a french/english vocabulary quiz, that asks you random words (either french or english) and then you supply the translation. (I hope we will get some use out of this in the coming school year.) And now the question: How does one make the foreign characters in French (and other foreign languages). Like the accent symbols, or the "c" with the funny doo-hicky on the bottom? I figure it has something to do with Unicode, but I looked at the Unicode module documentation, and still didn't understand how I could get started typing symbols like that. I want it to be fairly easy to display and to type the special characters in this quiz game. -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From dsh8290@rit.edu Fri Aug 3 20:09:04 2001 From: dsh8290@rit.edu (dman) Date: Fri, 3 Aug 2001 15:09:04 -0400 Subject: [Tutor] Replacement of items in a list In-Reply-To: <3B6AEDDC.7000205@verio.net>; from vlindberg@verio.net on Fri, Aug 03, 2001 at 12:30:52PM -0600 References: <3B6AEDDC.7000205@verio.net> Message-ID: <20010803150904.F9622@harmony.cs.rit.edu> On Fri, Aug 03, 2001 at 12:30:52PM -0600, VanL wrote: | Why is this? | | :::::::::::::: Begin test.py | | #!/usr/bin/env python | | import string | | lst = ['ONE', 'TWO', 'THREE'] | lst1 = lst[:] | lst2 = lst[:] | | def replace1(list): | """ Uses item replacement""" | for x in list: The for loop is just a shorthand notation for (except that you have no access to the 'i') try : i = 0 while 1 : x = list[i] i+=1 except IndexError : pass So what you have as the variable 'x' is a reference to an item in the list. The list is irrelevant in this function, except as a convenient way to get to all the various x's | x = string.lower(x) Here you change your local variable 'x' to refer to a new string, but you haven't touched the list at all. | def replace2(list): | """Uses position replacement""" | for x in range(len(list)): | list[x] = string.lower(list[x]) This works because you have modified the list as opposed to simply adjusting a local reference. HTH, -D From dsh8290@rit.edu Fri Aug 3 20:15:24 2001 From: dsh8290@rit.edu (dman) Date: Fri, 3 Aug 2001 15:15:24 -0400 Subject: [Tutor] How to make foreign characters In-Reply-To: <3C4488B06F6@kserver.org>; from sheila@thinkspot.net on Fri, Aug 03, 2001 at 12:05:30PM -0700 References: <3C4488B06F6@kserver.org> Message-ID: <20010803151524.G9622@harmony.cs.rit.edu> On Fri, Aug 03, 2001 at 12:05:30PM -0700, Sheila King wrote: | Hello, I need some advice and pointers: | | I've been teaching my 15 year old son his first programming language. (A | good summertime project while off from school) Of course, Python. | | Anyhow, the project we are working on right now, is a french/english | vocabulary quiz, that asks you random words (either french or english) | and then you supply the translation. (I hope we will get some use out of | this in the coming school year.) Sounds good. | And now the question: | | How does one make the foreign characters in French (and other foreign | languages). Like the accent symbols, or the "c" with the funny doo-hicky | on the bottom? I figure it has something to do with Unicode, but I | looked at the Unicode module documentation, and still didn't understand | how I could get started typing symbols like that. You need either Unicode or the proper charsets. Some "ASCII" charsets (such as iso8859) use the characters above 127 for special symbols and letters with accents. If you find all the characters you need in one of those charsets then you can use that as long as you set the display properly. For example I use 'less' as the pager for my emails. I had to set the environment variable "LESSCHARSET" to "iso8859" in order for those characters to be displayed properly. As for inserting them, it is up to your editor how that works (I haven't looked into that yet since I don't need it yet). Unicode is just another way to convert the integers in memory to glyphs on a screen. I haven't used it but it is supposed to be able to represent (nearly) all the characters in all the alphabets simultaneously (something that ASCII charsets can't do). | I want it to be fairly easy to display and to type the special | characters in this quiz game. That would be nice. I suppose you could have all input treated as a Python expression and enter the Unicode literals the same way you would in a program. (or add the u"" around the input programmatically) Then eval() the expression to get the unicode string out of it. Sorry I don't have a real solution. -D From rob@jam.rr.com Fri Aug 3 20:56:38 2001 From: rob@jam.rr.com (Rob Andrews) Date: Fri, 3 Aug 2001 14:56:38 -0500 Subject: [Tutor] MySQL mangling & list subscription question Message-ID: An associate recently stopped heckling Python for just long enough to look at some Python code and has now fallen insanely in love with the language. (He's a PHP man, historically.) However, he told me he's been unable to subscribe to the Tutor list because of the problems with www.python.org and asked me to forward this query to the list. # # Rob we are trying to display the customer information in a form. # # 1. How do we pull specific customer records from the data base # # 2. assign the data to a variable # # 3. display the variable in the form and change the variable # in the record. # For a little context, he is trying to pull data from a MySQL database and assign it to a variable in Python. I can do a fair bit of Python and a little SQL, but I've yet to mix the two. Can anyone point to some current resources or show a quick example I can pass on? Thanks, Rob Your one-stop shop for newbie source code! Useless Python: http://www.lowerstandard.com/python/ From ak@silmarill.org Fri Aug 3 19:44:47 2001 From: ak@silmarill.org (Andrei Kulakov) Date: Fri, 03 Aug 2001 14:44:47 -0400 Subject: [Tutor] Replacement of items in a list In-Reply-To: <"from vlindberg"@verio.net> References: <3B6AEDDC.7000205@verio.net> Message-ID: <20010803144447.A518@sill.silmarill.org> On Fri, Aug 03, 2001 at 12:30:52PM -0600, VanL wrote: > Why is this? > > :::::::::::::: Begin test.py > > #!/usr/bin/env python > > import string > > lst = ['ONE', 'TWO', 'THREE'] > lst1 = lst[:] > lst2 = lst[:] > > def replace1(list): > """ Uses item replacement""" > for x in list: > x = string.lower(x) This doesn't change values in list. for x in list: iterates over newly created values that it takes from list. Here's how I'd do it (2.0+): >>> lst ['ONE', 'TWO', 'THREE'] >>> newlst = [x.lower() for x in lst] >>> newlst ['one', 'two', 'three'] -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: http://silmarill.org/cymbaline From dyoo@hkn.eecs.berkeley.edu Fri Aug 3 21:18:40 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 3 Aug 2001 13:18:40 -0700 (PDT) Subject: [Tutor] Help with Parsing HTML files In-Reply-To: <200108031127.GAA13677@svc1.netwk-innov.net> Message-ID: On Fri, 3 Aug 2001, Kent Tenney wrote: > I had a look at the archives, I don't see how to search it, > only to browse a month of postings at a time. Another way of searching through the postings is to go through Activestate's repository of tutor: http://aspn.activestate.com/ASPN/Mail/Browse/Threaded/python-Tutor They allow searching from this interface, so it should be useful for you. --- By the way, I'm trying to write a small "tutor-curator" website that will try catagorizing all the messages on tutor. At the moment, I'm still trying to figure out exactly how to do this... *grin* If I get something up and running, I'll announce it to the list. From dyoo@hkn.eecs.berkeley.edu Fri Aug 3 21:27:16 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 3 Aug 2001 13:27:16 -0700 (PDT) Subject: [Tutor] Replacement of items in a list In-Reply-To: <20010803144447.A518@sill.silmarill.org> Message-ID: On Fri, 3 Aug 2001, Andrei Kulakov wrote: > On Fri, Aug 03, 2001 at 12:30:52PM -0600, VanL wrote: > > Why is this? > > > > :::::::::::::: Begin test.py > > > > #!/usr/bin/env python > > > > import string > > > > lst = ['ONE', 'TWO', 'THREE'] > > lst1 = lst[:] > > lst2 = lst[:] > > > > def replace1(list): > > """ Uses item replacement""" > > for x in list: > > x = string.lower(x) > > This doesn't change values in list. for x in list: iterates over > newly created values that it takes from list. Here's how I'd do it (2.0+): > > >>> lst > ['ONE', 'TWO', 'THREE'] > >>> newlst = [x.lower() for x in lst] > >>> newlst > ['one', 'two', 'three'] Alternatively, you can modify elements in the list if you access the items by index: ### def lowercaseList(L): for i in range(len(L)): L[i] = string.lower(L[i]) ### Doing it by index will allow you to make changes to the list. By the way, you might want to avoid naming your variables things like "list" or "str" --- those names are already being used by built-in functions in Python. Python will let us redefine what they mean, but in most cases, this is a very bad idea... *grin* Hope this helps! From wrong@crosswinds.net Fri Aug 3 21:46:09 2001 From: wrong@crosswinds.net (charlie derr) Date: Fri, 3 Aug 2001 16:46:09 -0400 Subject: [Tutor] ....and another thing! In-Reply-To: <200108031717.f73HHdY18143@pop.nsacom.net> Message-ID: My guess is that the line: choose=random.randint(1,string.atoi(`total_cards`)) is incorrect. I think you are never picking the first card, and you are occasionally picking outside the range of schmack[]. Remember that python indexes start at 0, not at 1. I also don't really understand why you use the string.atoi() construction (but maybe there's a reason for it). Try this: choose=random.randint(0, total_cards - 1) (or if there's a reason for string.atoi() that i'm missing): choose=random.randint(0, string.atoi(`total_cards`) - 1) good luck, ~c + +In the following: + +mport random +import string +cards=open('\windows\desktop\cards.txt','r') +schmack=cards.readlines() +counter=0 +while counter <10: + total_cards=len(schmack) + choose=random.randint(1,string.atoi(`total_cards`)) + chosen=schmack[choose] + del schmack[choose] + print chosen + counter=counter+1 + + +I will get the occasional: + +Traceback (most recent call last): + File "reader.py", line 9, in ? + chosen=schmack[choose] +IndexError: list index out of range +>Exit code: 1 + +It seems to me that: + +total_cards=len(schmack) + +should recalculate the number of items in the list with each +iteration of the +loop. Since there are 72 items in the list, and one item is +removed from the +list at the end of every iteration, it stands to reason that the +list index +should be accurately recalculated by len(). Where am I going wrong? + +_______________________________________________ +Tutor maillist - Tutor@python.org +http://mail.python.org/mailman/listinfo/tutor + From dyoo@hkn.eecs.berkeley.edu Fri Aug 3 21:48:45 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 3 Aug 2001 13:48:45 -0700 (PDT) Subject: [Tutor] MySQL mangling & list subscription question In-Reply-To: Message-ID: On Fri, 3 Aug 2001, Rob Andrews wrote: > # Rob we are trying to display the customer information in a form. > # > # 1. How do we pull specific customer records from the data base > # > # 2. assign the data to a variable > # > # 3. display the variable in the form and change the variable > # in the record. > # First things first: your friend will need to download a database module for MySQL. You can direct your friend here; http://python.org/topics/database/modules.html for a list of the popular ones. There's a very good one for MySQL called MySQLdb, which can be found from sourceforge.net here: http://sourceforge.net/project/showfiles.php?group_id=22307&release_id=37980 Doing SQL queries in Python is fairly regular between all the database modules --- first, you'll want to get a connection, the object that will let us talk to the database. We can imagine that it will look like this: ### import MySQLdb connection = MySQLdb.connect(user="bilbo", passwd="elbereth", db="The Red Book") ### Once we have this connection, we can grab a "cursor" from the connection that will let us execute queries: ### cursor = connection.cursor() ### What sort of thing might we want to know about? Perhaps we're looking for all the names in a merry band of thieves raiding a dragon's den. What we want to do is tell Python to start up the search: ### cursor.execute("""select name, email from addressbook where height < 3""") ### But it's not enough to tell it to do the search... we also want it to give us back the results! We have several options here: we can pull them out, one at a time: ### name, email = cursor.fetchone() ### or we can do it all at once: ### thief_information = cursor.fetchall() ### I have NOT been able to test this code though, so I might have made a mistake somewhere. It's probably a good idea to refer your friend to the "Python Database API v2.0", which is very dry, but at least it's authoritative about what functions can be called: http://python.org/topics/database/DatabaseAPI-2.0.html The other question about changing values in the database is an SQL-specific one: ask your friend to take a look at: http://devshed.com/Server_Side/MySQL/Intro so that they can get a brief overview on how do do SQL queries that do "UPDATE"'s and "INSERT"'s. I think UPDATE is what your friend will need to change values in the database. Have them practice on a throw-away database first though: SQL makes it really easy to do something silly like "DELETE FROM IMPORTANT_CRITICAL_DATA" without any warnings. Feel free to ask more questions about this. Hope this helps! From DavidCraig@pia.ca.gov Fri Aug 3 22:08:09 2001 From: DavidCraig@pia.ca.gov (DavidCraig@pia.ca.gov) Date: Fri, 03 Aug 2001 14:08:09 -0700 Subject: [Tutor] Can you see my error? Message-ID: I input ..............to #----------------------------------------------------------- # Main Program #------------------------------------------------------------ gKeys = map(lambda x:regex.compile(x[0]),gPats) gValues = map(lambda x:x[1],gPats) print "Therapist \n------------" print "Talk to the program by typing in plain English, using normal upper-" print 'and lower-case letters and punctuation. Enter "quit" when done.' print '='*72 print "Hello. How are you feeling today?" s = "" while s != "quit": try: s = raw_input(">") except EOFError: s = "quit" print s while s[-1] in "!.": s = s[:-1] print respond(s,gKeys,gValues) The message I get is: >>> Traceback (most recent call last): File "C:/Python21/Practice/therapist1.py", line 273, in ? gKeys = map(lambda x:regex.compile(x[0]),gPats) File "C:/Python21/Practice/therapist1.py", line 273, in gKeys = map(lambda x:regex.compile(x[0]),gPats) error: Badly placed parenthesis Any help would be appreciated. Thanks in advance. Dave D. H. Craig, CSM From mbc2@netdoor.com Fri Aug 3 22:26:55 2001 From: mbc2@netdoor.com (Brad Chandler) Date: Fri, 3 Aug 2001 16:26:55 -0500 Subject: [Tutor] MySQL mangling & list subscription question References: Message-ID: <002401c11c63$0627dba0$111c0d0a@spb.state.ms.us> This is something I use to connect to a MySQL server running on my windows box. It should work exactly the same on linux except for the import and database connection lines. I don't have an example of that at the moment. import dbi, odbc mydb=odbc.odbc("mysql/brad/homer") #this function takes an odbc data source, name, pass cursor = mydb.cursor() cursor.execute("select * from mytable") result = cursor.fetchall() The "result" variable will contain an array of all the rows and columns returned from your query. If it's just one item, you should be able to assign to a variable like this: myitem = result[0][0] If it returns multiple rows and columns you'll have to loop through the "result" variable, something like this: for row in result: for cell in row: print cell The following code will put your result into a dictionary, using the column names as the keys. This slows things down a bit, but it makes my programs a lot easier to read when I can access my fields by the column name rather than their position. result = cursor.fetchall() numrows = len(result) rowarray = [] for x in range(0,numrows): numfields = len(result[x]) rowdict = {} for y in range(0,numfields): rowdict[cursor.description[y][0]] = result[x][y] rowarray.append(rowdict) I guess this would be an array of dictionaries, if your result returns more than one row. You can then access the fields like this: for x in rowarray: print x.get('colname','notfound') I hope some of this helps. ----- Original Message ----- From: "Rob Andrews" To: "Tutor@Python. Org" Sent: Friday, August 03, 2001 2:56 PM Subject: [Tutor] MySQL mangling & list subscription question > An associate recently stopped heckling Python for just long enough to > look at some Python code and has now fallen insanely in love with the > language. (He's a PHP man, historically.) > > However, he told me he's been unable to subscribe to the Tutor list > because of the problems with www.python.org and asked me to forward this > query to the list. > > # > # Rob we are trying to display the customer information in a form. > # > # 1. How do we pull specific customer records from the data base > # > # 2. assign the data to a variable > # > # 3. display the variable in the form and change the variable > # in the record. > # > > For a little context, he is trying to pull data from a MySQL database > and assign it to a variable in Python. I can do a fair bit of Python and > a little SQL, but I've yet to mix the two. Can anyone point to some > current resources or show a quick example I can pass on? > > Thanks, > Rob > > Your one-stop shop for newbie source code! > Useless Python: http://www.lowerstandard.com/python/ > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From mbc2@netdoor.com Fri Aug 3 22:45:27 2001 From: mbc2@netdoor.com (Brad Chandler) Date: Fri, 3 Aug 2001 16:45:27 -0500 Subject: [Tutor] MySQL mangling & list subscription question References: <002401c11c63$0627dba0$111c0d0a@spb.state.ms.us> Message-ID: <003101c11c65$9bc2e400$111c0d0a@spb.state.ms.us> ----- Original Message ----- From: "Brad Chandler" To: Sent: Friday, August 03, 2001 4:26 PM Subject: Re: [Tutor] MySQL mangling & list subscription question > This is something I use to connect to a MySQL server running on my windows > box. It should work exactly the same on linux except for the import and > database connection lines. I don't have an example of that at the moment. > > import dbi, odbc > > mydb=odbc.odbc("mysql/brad/homer") #this function takes an odbc data source, > name, pass That should be "odbc datasource/database name/password". From dyoo@hkn.eecs.berkeley.edu Sat Aug 4 00:01:32 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 3 Aug 2001 16:01:32 -0700 (PDT) Subject: [Tutor] Can you see my error? In-Reply-To: Message-ID: On Fri, 3 Aug 2001 DavidCraig@pia.ca.gov wrote: > The message I get is: > > >>> > Traceback (most recent call last): > File "C:/Python21/Practice/therapist1.py", line 273, in ? > gKeys = map(lambda x:regex.compile(x[0]),gPats) > File "C:/Python21/Practice/therapist1.py", line 273, in > gKeys = map(lambda x:regex.compile(x[0]),gPats) > error: Badly placed parenthesis I don't see anything wrong with the parentheses in the map expression. Perhaps it might have something to do with the string you're passing into regex.compile: regular expressions, too, use parentheses when they compile a pattern. Maybe that error message is coming from the regular expression engine, and not Python. As a debugging tool, can you do the following? ### gKeys = [] for pattern in gPats: print "I'm going to compile", pattern[0], "now." gKeys.append(regex.compile(pattern[0])) ### It's longer, but it might give us some idea of what's going on. Also, you may want to use the "re" module instead of the "regex" library --- regex is a bit deprecated. Good luck! From shalehperry@home.com Sat Aug 4 07:55:00 2001 From: shalehperry@home.com (Sean 'Shaleh' Perry) Date: Fri, 03 Aug 2001 23:55:00 -0700 (PDT) Subject: [Tutor] Help with Parsing HTML files In-Reply-To: <00038a9f3c1014f2_mailit@mail.isis.de> Message-ID: > > What I don't see is how the handle_image function/method looks for images and > I need to learn how to use this in order to modify it for my own dark > purposes! Please help. > Ok, here is the comment from sgmllib.py (note, try reading the python modules, they are often easy to follow): # SGML parser base class -- find tags and call handler functions. # Usage: p = SGMLParser(); p.feed(data); ...; p.close(). # The dtd is defined by deriving a class which defines methods # with special names to handle tags: start_foo and end_foo to handle # and , respectively, or do_foo to handle by itself. # (Tags are converted to lower case for this purpose.) The data # between tags is passed to the parser by calling self.handle_data() # with some data as argument (the data may be split up in arbutrary # chunks). Entity references are passed by calling # self.handle_entityref() with the entity reference as argument. Then a look at htmllib.py shows: def do_img(self, attrs): align = '' alt = '(image)' ismap = '' src = '' width = 0 height = 0 for attrname, value in attrs: if attrname == 'align': align = value if attrname == 'alt': alt = value if attrname == 'ismap': ismap = value if attrname == 'src': src = value if attrname == 'width': try: width = string.atoi(value) except: pass if attrname == 'height': try: height = string.atoi(value) except: pass self.handle_image(src, alt, ismap, align, width, height) So, the class ImgFinder shown in your code implements handle_image, overriding the one in htmllib's HTMLParser. The code path looks something like this (in a psuedo code + python mix): parse html found tag parse options in tag if class defines start_tag: call start_tag(options) elif class defines do_tag: call do_tag(options) else: unknown_tag(options) When the parser encounters myimage.png the class checks for: start_img then do_img and if neither is found unknown_tag is called. Since htmllib defines do_img that function is called. When self.handle_image is called the one from ImgFinder is used instead of the one from the parent class. Hope that helps. From lumbricus@gmx.net Sat Aug 4 11:57:16 2001 From: lumbricus@gmx.net (lumbricus@gmx.net) Date: Sat, 4 Aug 2001 12:57:16 +0200 Subject: [Tutor] New to this In-Reply-To: <20010803210816.A25716@Laplace.localdomain>; from lumbricus@gmx.net on Fri, Aug 03, 2001 at 09:08:16PM +0200 References: <20010803210816.A25716@Laplace.localdomain> Message-ID: <20010804125716.A29466@Laplace.localdomain> On Fri, Aug 03, 2001 at 09:08:16PM +0200, Jцrg Wцlke wrote: On Fri, Aug 03, 2001 at 12:59:57PM -0500, Rob Andrews wrote: > # > # You could start with a couple of filters; > # one to strip HTML from email, > # another to enforce line lengths of about 72 characters. > # ;-) > # > > Nah, a better idea is to write a script that randomly inserts HTML tags > into plain text email messages, then BCC the messages to the Pine Users > email list (if such a thing exists). > > Muwhahahaha! > 3;-> > > Me? Evil? > Rob > "The PROPER way to handle HTML postings is to cancel the article, then hire a hitman to kill the poster, his wife and kids, fuck his dog and smash his computer into little bits. Anything more is just extremism." -Paul Tomblin in alt.sysadmin.recovery SCNR Bad day J"o! PS: Why is my favourite dialup provider blacklisted at your site? -- You will be awarded some great honor. You will have a long and unpleasant discussion with your supervisor. From tescoil@irtc.net Sat Aug 4 12:35:00 2001 From: tescoil@irtc.net (Tesla Coil) Date: Sat, 04 Aug 2001 06:35:00 -0500 Subject: [Tutor] New to this References: Message-ID: <3B6BDDE4.15B813EB@irtc.net> On 3 August 2001, Bruce Sass wrote: > You could start with a couple of filters; > one to strip HTML from email, > another to enforce line lengths of about 72 characters. > ;-) Speaking of FORTRAN... ;) Recently discovered the FPIG project: http://cens.ioc.ee/projects/f2py2e/ Definitely belongs on the Useless Challenge list to do *anything* with this. From clanoftheinsane@hotmail.com Sat Aug 4 16:03:43 2001 From: clanoftheinsane@hotmail.com (paul) Date: Sat, 4 Aug 2001 11:03:43 -0400 Subject: [Tutor] foreign lists Message-ID: This is a multi-part message in MIME format. ------=_NextPart_000_0009_01C11CD5.1FECA9E0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable is it possible to access a list from another file and save whatever = changes are made to the list after the original program has been run? i = made a simple book database which matches book titles with certain = attributes each book contains. i want to be able to create the main = list of books and have my program access that list. i also want any = additions made to the list to be changed in that foreign list, so that = next time the program is run, the list will include the new addition. = right now, though, i have it so that each time the program runs, it = starts with a blank list. any suggestions??? if anyone wants the code, = i'll be happy to post that also. thanks paul brown ------=_NextPart_000_0009_01C11CD5.1FECA9E0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
is it possible to access a list from = another file=20 and save whatever changes are made to the list after the original = program has=20 been run?  i made a simple book database which matches book titles = with=20 certain attributes each book contains.  i want to be able to create = the=20 main list of books and have my program access that list.  i also = want any=20 additions made to the list to be changed in that foreign list, so that = next time=20 the program is run, the list will include the new addition.  right = now,=20 though, i have it so that each time the program runs, it starts with a = blank=20 list.  any suggestions???  if anyone wants the code, i'll be = happy to=20 post that also.
thanks
paul brown
------=_NextPart_000_0009_01C11CD5.1FECA9E0-- From Charlie Clark Sat Aug 4 16:39:11 2001 From: Charlie Clark (Charlie Clark) Date: Sat, 04 Aug 2001 17:39:11 +0200 Subject: [Tutor] foreign lists References: Message-ID: <00038ab613d40dff_mailit@mail.isis.de> >is it possible to access a list from another file and save whatever changes >are made to the list after the original program has been run? i made a >simple book database which matches book titles with certain attributes each >book contains. i want to be able to create the main list of books and have >my program access that list. i also want any additions made to the list to >be changed in that foreign list, so that next time the program is run, the >list will include the new addition. right now, though, i have it so that >each time the program runs, it starts with a blank list. any suggestions??? >if anyone wants the code, i'll be happy to post that also. It's not clear to me at least what you mean. Your catalogue is a text file? Along the lines of title; author; publication date; category Please specific about what you want your program to do: add books to the list.... I don't understand at all what you mean by 'foreign list'. As long as you can access the catalogue file you can make copies of it and do whatever you want with those copies. Please send what code you have. Charlie From tjenkins@devis.com Sat Aug 4 17:37:07 2001 From: tjenkins@devis.com (Tom Jenkins) Date: Sat, 04 Aug 2001 12:37:07 -0400 Subject: [Tutor] Form action with python script References: <00ff01c11c2e$7482b140$5d01a8c0@intranet.madisoncomunicacao.com.br> Message-ID: <3B6C24B3.4080907@devis.com> Sabrina wrote: > Hi, > > > > I'm working with a Python Script in Zope but I'm having some problems. > I'm trying to call a python script in a "form action" because I have to > make some calculations with some values of this form. I call like this: > > > but normally a form action calls another page. > > So, the question is: I'd like to call a python script and, in this > script, make a redirect to another page(url). Can I do that?? > > > > I hope you can help me :) > > Sorry if I'm not being clear! > > > > Sabrina Araujo. > Hello Sabrina, just so you know, there is a zope mailing list (very high traffic) that you can subscribe to on zope.org. Now, you want to call a python script. i'm assuming that this is a python script on the file system (an external python script) as opposed to a Python Script in the zope object database. To call the external script you have to wrap it with a zope object (external method). In the zope management screen, add an External Method. The paragraph you get when adding the External Method is pretty straightforward. The one thing you must do is put your .py file in zope's Extensions directory. here is a pretty good How-To: http://www.zope.org/Documentation/How-To/ExternalMethods hope this helps -- Tom Jenkins devIS - Development Infostructure http://www.devis.com From Charlie Clark Sat Aug 4 19:03:52 2001 From: Charlie Clark (Charlie Clark) Date: Sat, 04 Aug 2001 20:03:52 +0200 Subject: [Tutor] foreign lists LONG References: <00038ab613d40dff_mailit@mail.isis.de> Message-ID: <00038ab819495827_mailit@mail.isis.de> >sorry about that confusion. i'll try to explain better. i want to have a >list that includes book names with book attributes (for example, the book >name might be "Catcher in the Rye" and the book attributes might be >"maturation" and "teenage"). i want to be able to have a list of about 50 >books with their attributes, and i want the list to be in the following >form: > >[["Catcher in the Rye", "maturation", "teenage"], [book, attribute], ...] > >this way, the program i have written will access the first element of each >element in the main list, which is the book title, and every other element >in those smaller lists are attributes. here's the code, maybe this will >help: Looks fine. You just need to add a routine to read in your file to your booklists and to do this you need to change the way you write your records. If use 'split' and 'join' to make lists from strings and strings from lists you can reliably read what you've written mm, I'm sure I like the way you're adding attributes. It looks prone to error. It might be easier to use a dictionary. attributes = ['title', 'author', 'category'] # and so on. These will be our defaults as you currently haven't got the file. You can then simplify managing your books by accessing via key rather than trusting for luck on accessing by index. If you use the first line of your file to store your the names of those attributes you're even better plus this might make it easier to move to a full blown database. This is going to mean rewriting some of your routines but I think you'll find it helpful. Let's try this with two books just to get the principle right. Our database is going to be semi-colon separated text-file, like this: title;author;category catcher in the rye;J D Salinger;maturity gormenghast;Mervyn Peake;fantasy if we just read the first line of our file we can set up our attributes: try: file_in = open("books.txt", "rb") # "rb" is necessary only in windows attributes = file_in.readline() file_in.close() # close the file after use except: #file doesn't exist attributes = ['title', 'author', 'category'] # default attributes attributes = attributes.split(";") # will give us a list of attributes booklist = [] let's read the rest of the file books = f.readlines() for record in books: record = record.split(";") book = {} for attribute in attributes: book[attribute] = record[attributes.index(attribute)] booklist.append(book) booklist now looks like this: [{'title': 'catcher in the rye', 'author': 'J D Salinger', 'category': 'maturity'}, {'title': 'gormenghast', 'author': 'Mervyn Peake', 'category': 'fantasy'}] and it means you can do searches on it like this Look for books with category == "maturity"... for book in booklist: if book['category'] == 'maturity': print book.values() # you might want to do some sorting or such will give us ['catcher in the rye', 'J D Salinger', 'maturity'] Add a book simply by calling the input new_book = {} for attribute in attributes: new_book[attribute] = raw_input("%s "%(attribute)) booklist.append(new_book) I think you should be able to rebuild the rest of your functions based on this method. All that's left is storing our list when quitting. As we've decided to use a text file for storage, we're going to need to keep things in order but it doesn't matter which order I hope! Dictionaries rearrange their order to make themselves faster to use. #storage file_out = open("books.txt", "w") # or whatever you're calling it first_line = attributes.join(";") file_out.write(first_line + "\n") s = "" # temporary string to store our records for book in booklist: record = [] for attribute in attributes: record.append(book[attribute]) record = string.join(record, ";") # turn a list into a string s += record + "\n" separate each record by line file_out.write(s) file_out.close() # always good practice to close files explicitly Proof of the pudding will be in the eating... Let us know how you get on. Using a text file is only one way of doing this and isn't a good idea for big catalogues. It might be quicker to use classes for your books and pickle the instances which would reduce the overhead at the beginning an end but don't ask me how this is done: I tried it once and failed miserably. Charlie From bsass@freenet.edmonton.ab.ca Sat Aug 4 19:23:06 2001 From: bsass@freenet.edmonton.ab.ca (Bruce Sass) Date: Sat, 4 Aug 2001 12:23:06 -0600 (MDT) Subject: [Tutor] foreign lists In-Reply-To: Message-ID: Hi, On Sat, 4 Aug 2001, paul wrote: --- > is it possible to access a list from another file and save whatever changes are made to the list after the original program has been run? i made a simple book database which matches book titles with certain attributes each book contains. i want to be able to create the main list of books and have my program access that list. i also want any additions made to the list to be changed in that foreign list, so that next time the program is run, the list will include the new addition. right now, though, i have it so that each time the program runs, it starts with a blank list. any suggestions??? if anyone wants the code, i'll be happy to post that also. --- You have a whole lot of choices, which is best depends on what you want to do with your database (who and what has access, by which methods, and what your objectives are (fun, education, profit)). Checking into these three areas should help you see what the options are: __repr__, eval, open, pickle, etc. (i.e., put it in a file, you get to do all the work); anydbm (let the system handle the low level DB stuff); mysql, postgresql, etc. (third-party stuff, lots of different views of the data, put it on the web) HTH - Bruce From ak@silmarill.org Sat Aug 4 16:09:04 2001 From: ak@silmarill.org (Andrei Kulakov) Date: Sat, 04 Aug 2001 11:09:04 -0400 Subject: [Tutor] foreign lists In-Reply-To: <"from clanoftheinsane"@hotmail.com> References: Message-ID: <20010804110904.A498@sill.silmarill.org> On Sat, Aug 04, 2001 at 11:03:43AM -0400, paul wrote: > is it possible to access a list from another file and save whatever changes are made to the list after the original program has been run? i made a simple book database which matches book titles with certain attributes each book contains. i want to be able to create the main list of books and have my program access that list. i also want any additions made to the list to be changed in that foreign list, so that next time the program is run, the list will include the new addition. right now, though, i have it so that each time the program runs, it starts with a blank list. any suggestions??? if anyone wants the code, i'll be happy to post that also. > thanks > paul brown That sounds similar to my program pybook, Gutenberg Texts reader - silmarill.org/pybook . You can try looking at the source, it's fairly clean and commented. -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: http://silmarill.org/cymbaline From dyoo@hkn.eecs.berkeley.edu Sat Aug 4 20:39:21 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 4 Aug 2001 12:39:21 -0700 (PDT) Subject: [Tutor] Help with Parsing HTML files In-Reply-To: Message-ID: On Fri, 3 Aug 2001, Sean 'Shaleh' Perry wrote: > > What I don't see is how the handle_image function/method looks for > images and > I need to learn how to use this in order to modify it for > my own dark > purposes! Please help. > Maybe an example will help --- Here's a small example that, given a web site, tries to pull out all the image names. (Rob, here's another useless python script. *grin*) This example will use htmllib to help us "parse" and hunt down IMG tags. I don't think we need to explicitly rewrite handle_image(). For HTML elements that have start and end tags, let's define "start_nameofsometag()" and "end_nameofsometag()" methods. However, since an IMG tag stands alone, we'll write a do_img() method instead. ### import htmllib import formatter import sys import urllib class ImagePuller(htmllib.HTMLParser): def __init__(self): htmllib.HTMLParser.__init__(self, formatter.NullFormatter()) self.list_of_images = [] def do_img(self, attributes): for name, value in attributes: if name == 'src': new_image = value self.list_of_images.append(new_image) def getImageList(self): return self.list_of_images if __name__ == '__main__': url = sys.argv[1] url_contents = urllib.urlopen(url).read() puller = ImagePuller() puller.feed(url_contents) print puller.getImageList() ### For more information about this, take a look at: http://python.org/doc/current/lib/module-sgmllib.html From fleet@teachout.org Sat Aug 4 21:30:02 2001 From: fleet@teachout.org (fleet@teachout.org) Date: Sat, 4 Aug 2001 16:30:02 -0400 (EDT) Subject: [Tutor] sys.exit() not working Message-ID: In the following code sys.exit() fails on the first test (denoted <---FAILS); but works fine on the second test (denoted <---WORKS). The only difference I see is that in the second test I provide an error condition and in the first test I don't. Which brings me to another question: The error returned if there are no jpg/JPG files in the directory appears to be a shell error message (RH Linux 7.0) and not a Python error (because of popen, I presume). If I *need* an error condition after except, what do I put there (first test)? What occurs now, if this is run with no jpg/JPG files in the directory, is the error message for test one gets printed, the test one 'sys.exit()' gets ignored and the following test gets run. Entering a "return" there causes that test to fail, and the test 2 error message gets printed and the file exits to my shell (from whence it was launched). TIA, - fleet - -------------------------------------------- #! /usr/bin/python """ Creates body of Sylvia's E-bay index. At this point, file sizing must be completed, captions file must be cleaned up and everything ready to go. """ import os import sys import string # Get list of .jpg (or .JPG) files try: files=string.split(os.popen("ls -1D *.[jJ][pP][gG]").read(),"\012") except: print "ls: *.[jJ][pP][gG]: No such file or directory" sys.exit() #<--- FAILS # Get captions try: captions=string.split(open(raw_input("Enter Captions filename: "),"r").read(),"\012") except IOError: print "No such file" sys.exit() #<--- WORKS # Compare lengths of files and captions if len(files) == len(captions): pass else: print "Nr. of files (%s) doesn't match Nr. of captions (%s)" % (len(files), len(captions)) sys.exit() # Create temp.html for insertion into index.html temp=open("temp.html","a") # The last line in "files" and "captions" is empty; hence len(files)-1 # write filenames and captions to temp.html for i in range(0,len(files)-1): temp.write('
  • (%s) - %s
  • \n' % (files[i], files[i], captions[i])) # close temp.html temp.close() # get index.html from the mirror directories os.popen("cp /home/raq2/brickhouse/ebay/index.html /home/dev/brickhouse/ebay") # exit sys.exit() From arcege@speakeasy.net Sat Aug 4 21:45:50 2001 From: arcege@speakeasy.net (Michael P. Reilly) Date: Sat, 4 Aug 2001 16:45:50 -0400 Subject: [Tutor] sys.exit() not working In-Reply-To: ; from fleet@teachout.org on Sat, Aug 04, 2001 at 04:30:02PM -0400 References: Message-ID: <20010804164550.A1759@speakeasy.net> On Sat, Aug 04, 2001 at 04:30:02PM -0400, fleet@teachout.org wrote: > The only difference I see is that in the second test I provide an error > condition and in the first test I don't. Which brings me to another > question: The error returned if there are no jpg/JPG files in the > directory appears to be a shell error message (RH Linux 7.0) and not a > Python error (because of popen, I presume). If I *need* an error > condition after except, what do I put there (first test)? Did you try the first expression in an interpreter? I did and I got no error (though there was a message written to stderr). In fact, popen won't return an error, even if you gave it an invalid command. >>> string.split(os.popen('ls -1D /etc/*.[Jj][Pp][Gg]').read(), "\012") ls: /etc/*.[Jj][Pp][Gg]: No such file or directory [''] >>> The result is a list containing an empty string. No exception is raised so the except clause is not executed. If you wanted an exception, then you would have to check the result and raise an exception yourself. Incidently, you might want to look at the glob module, it will do this better for you, I think. Also, readlines() doesthe same as string.split(read(), '\n'). >>> os.popen('ls -1D /etc/*.[Jj][Pp][Gg]').readlines() ls: /etc/*.[Jj][Pp][Gg]: No such file or directory [] >>> import glob >>> glob.glob('/etc/*.[Jj][Pp][Gg]') [] >>> (I use "/etc/" since I know there are no jpeg files there. ;)) -Arcege -- +----------------------------------+-----------------------------------+ | Michael P. Reilly | arcege@speakeasy.net | From bsass@freenet.edmonton.ab.ca Sat Aug 4 21:44:27 2001 From: bsass@freenet.edmonton.ab.ca (Bruce Sass) Date: Sat, 4 Aug 2001 14:44:27 -0600 (MDT) Subject: [Tutor] sys.exit() not working In-Reply-To: Message-ID: On Sat, 4 Aug 2001 fleet@teachout.org wrote: > In the following code sys.exit() fails on the first test (denoted > <---FAILS); but works fine on the second test (denoted <---WORKS). > > The only difference I see is that in the second test I provide an error > condition and in the first test I don't. Which brings me to another > question: The error returned if there are no jpg/JPG files in the > directory appears to be a shell error message (RH Linux 7.0) and not a > Python error (because of popen, I presume). If I *need* an error > condition after except, what do I put there (first test)? > > What occurs now, if this is run with no jpg/JPG files in the directory, is > the error message for test one gets printed, the test one 'sys.exit()' > gets ignored and the following test gets run. Entering a "return" there > causes that test to fail, and the test 2 error message gets printed and > the file exits to my shell (from whence it was launched). <...> > # Get list of .jpg (or .JPG) files > try: > files=string.split(os.popen("ls -1D *.[jJ][pP][gG]").read(),"\012") > except: > print "ls: *.[jJ][pP][gG]: No such file or directory" > sys.exit() #<--- FAILS You need to test if "files" is really a list of files, or a message from "ls", Python has no way of knowing the later is really an error. - Bruce From ak@silmarill.org Sat Aug 4 21:37:20 2001 From: ak@silmarill.org (Andrei Kulakov) Date: Sat, 04 Aug 2001 16:37:20 -0400 Subject: [Tutor] sys.exit() not working In-Reply-To: <"from fleet"@teachout.org> References: Message-ID: <20010804163720.A1881@sill.silmarill.org> On Sat, Aug 04, 2001 at 04:30:02PM -0400, fleet@teachout.org wrote: > In the following code sys.exit() fails on the first test (denoted > <---FAILS); but works fine on the second test (denoted <---WORKS). > > The only difference I see is that in the second test I provide an error > condition and in the first test I don't. Which brings me to another > question: The error returned if there are no jpg/JPG files in the > directory appears to be a shell error message (RH Linux 7.0) and not a > Python error (because of popen, I presume). If I *need* an error > condition after except, what do I put there (first test)? > > What occurs now, if this is run with no jpg/JPG files in the directory, is > the error message for test one gets printed, the test one 'sys.exit()' > gets ignored and the following test gets run. Entering a "return" there > causes that test to fail, and the test 2 error message gets printed and > the file exits to my shell (from whence it was launched). > > TIA, > - fleet - > > -------------------------------------------- > #! /usr/bin/python > > """ > Creates body of Sylvia's E-bay index. At this point, file sizing must be completed, captions > file must be cleaned up and everything ready to go. > """ > > import os > import sys > import string > > > # Get list of .jpg (or .JPG) files > try: > files=string.split(os.popen("ls -1D *.[jJ][pP][gG]").read(),"\012") > except: > print "ls: *.[jJ][pP][gG]: No such file or directory" Does this print? If not, then the following line should not and does not run. > sys.exit() #<--- FAILS > > # Get captions > try: > captions=string.split(open(raw_input("Enter Captions filename: "),"r").read(),"\012") > except IOError: > print "No such file" > sys.exit() #<--- WORKS > > # Compare lengths of files and captions > if len(files) == len(captions): > pass > else: > print "Nr. of files (%s) doesn't match Nr. of captions (%s)" % (len(files), len(captions)) > sys.exit() > > # Create temp.html for insertion into index.html > temp=open("temp.html","a") > > # The last line in "files" and "captions" is empty; hence len(files)-1 > # write filenames and captions to temp.html > for i in range(0,len(files)-1): > temp.write('
  • (%s) - %s
  • \n' % (files[i], files[i], captions[i])) > > # close temp.html > temp.close() > > # get index.html from the mirror directories > os.popen("cp /home/raq2/brickhouse/ebay/index.html /home/dev/brickhouse/ebay") > > # exit > sys.exit() > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: http://silmarill.org/cymbaline From fleet@teachout.org Sat Aug 4 23:39:05 2001 From: fleet@teachout.org (fleet@teachout.org) Date: Sat, 4 Aug 2001 18:39:05 -0400 (EDT) Subject: [Tutor] (no subject) Message-ID: >From: Michael P. Reilly >Subject: Re: [Tutor] sys.exit() not working > >On Sat, Aug 04, 2001 at 04:30:02PM -0400, fleet@teachout.org wrote: >> The only difference I see is that in the second test I provide an error >> condition and in the first test I don't. Which brings me to another >> question: The error returned if there are no jpg/JPG files in the >> directory appears to be a shell error message (RH Linux 7.0) and not a >> Python error (because of popen, I presume). If I *need* an error >> condition after except, what do I put there (first test)? > >Did you try the first expression in an interpreter? I did and I got >no error (though there was a message written to stderr). In fact, >popen won't return an error, even if you gave it an invalid command. > >>>> string.split(os.popen('ls -1D /etc/*.[Jj][Pp][Gg]').read(), "\012") >ls: /etc/*.[Jj][Pp][Gg]: No such file or directory >[''] Well, yes, I did. I considered the shell message an error (even if Python didn't) and just assumed a failure. Didn't realize an empty list was returned. >The result is a list containing an empty string. No exception is raised >so the except clause is not executed. If you wanted an exception, >then you would have to check the result and raise an exception yourself. And changing the "try" block to a straight "if" statement works wonders. if len(files)==1 and files[0]=='': #in the event there's only one file sys.exit() #in the list or the first file in #a list could be ''. ?? Since the shell produces a relatively understandable error message, (and I don't know how to suppress it), I don't bother to print an error message of my own. (That changes if I use glob, though.) >Incidently, you might want to look at the glob module, it will do >this better for you, I think. Also, readlines() doesthe same as >string.split(read(), '\n'). Good point on the readlines(). >>>> os.popen('ls -1D /etc/*.[Jj][Pp][Gg]').readlines() >ls: /etc/*.[Jj][Pp][Gg]: No such file or directory >[] >>>> import glob >>>> glob.glob('/etc/*.[Jj][Pp][Gg]') >[] And glob doesn't include that nasty empty line at the bottom of the list either! Thanks! >(I use "/etc/" since I know there are no jpeg files there. ;)) I assumed as much. I have these occasional rare flashes of insight! :) Regards, - fleet - From fleet@teachout.org Sat Aug 4 23:40:15 2001 From: fleet@teachout.org (fleet@teachout.org) Date: Sat, 4 Aug 2001 18:40:15 -0400 (EDT) Subject: [Tutor] sys.exit() not working Message-ID: >From: Bruce Sass >Subject: Re: [Tutor] sys.exit() not working > >On Sat, 4 Aug 2001 fleet@teachout.org wrote: > >> In the following code sys.exit() fails on the first test (denoted >> <---FAILS); but works fine on the second test (denoted <---WORKS). >> > >You need to test if "files" is really a list of files, or a message >from "ls", Python has no way of knowing the later is really an error. That was my problem! Thanks! See my reply to Michael. Regards, - fleet - From fleet@teachout.org Sat Aug 4 23:42:00 2001 From: fleet@teachout.org (fleet@teachout.org) Date: Sat, 4 Aug 2001 18:42:00 -0400 (EDT) Subject: [Tutor] sys.exit() not working Message-ID: Sorry - left off the subject when I replied the first time. ---------- Forwarded message ---------- Date: Sat, 4 Aug 2001 18:39:05 -0400 (EDT) From: fleet@teachout.org To: python tutor list Cc: Michael P. Reilly >From: Michael P. Reilly >Subject: Re: [Tutor] sys.exit() not working > >On Sat, Aug 04, 2001 at 04:30:02PM -0400, fleet@teachout.org wrote: >> The only difference I see is that in the second test I provide an error >> condition and in the first test I don't. Which brings me to another >> question: The error returned if there are no jpg/JPG files in the >> directory appears to be a shell error message (RH Linux 7.0) and not a >> Python error (because of popen, I presume). If I *need* an error >> condition after except, what do I put there (first test)? > >Did you try the first expression in an interpreter? I did and I got >no error (though there was a message written to stderr). In fact, >popen won't return an error, even if you gave it an invalid command. > >>>> string.split(os.popen('ls -1D /etc/*.[Jj][Pp][Gg]').read(), "\012") >ls: /etc/*.[Jj][Pp][Gg]: No such file or directory >[''] Well, yes, I did. I considered the shell message an error (even if Python didn't) and just assumed a failure. Didn't realize an empty list was returned. >The result is a list containing an empty string. No exception is raised >so the except clause is not executed. If you wanted an exception, >then you would have to check the result and raise an exception yourself. And changing the "try" block to a straight "if" statement works wonders. if len(files)==1 and files[0]=='': #in the event there's only one file sys.exit() #in the list or the first file in #a list could be ''. ?? Since the shell produces a relatively understandable error message, (and I don't know how to suppress it), I don't bother to print an error message of my own. (That changes if I use glob, though.) >Incidently, you might want to look at the glob module, it will do >this better for you, I think. Also, readlines() doesthe same as >string.split(read(), '\n'). Good point on the readlines(). >>>> os.popen('ls -1D /etc/*.[Jj][Pp][Gg]').readlines() >ls: /etc/*.[Jj][Pp][Gg]: No such file or directory >[] >>>> import glob >>>> glob.glob('/etc/*.[Jj][Pp][Gg]') >[] And glob doesn't include that nasty empty line at the bottom of the list either! Thanks! >(I use "/etc/" since I know there are no jpeg files there. ;)) I assumed as much. I have these occasional rare flashes of insight! :) Regards, - fleet - From csmith@blakeschool.org Sun Aug 5 02:04:09 2001 From: csmith@blakeschool.org (Christopher Smith) Date: Sat, 04 Aug 2001 20:04:09 -0500 Subject: [Tutor] Re: using IDLE and changing variables In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66BE26@mbtlipnt02.btlabs.bt.co.uk> References: <5104D4DBC598D211B5FE0000F8FE7EB20E66BE26@mbtlipnt02.btlabs.bt.co.uk> Message-ID: alan.gauld@bt.com writes: >> Let's say at one point you had a variable x defined >> and you used it in several places. Then you change >> the variable from x to y but forget to change it >> everywhere. > >That'd be a programmer error in every environment I've >ever used. Some language compilers will tell you if you >remove the original declaration/definition of the variable >(x in your case) and then try to use it. Python will >warn you in some situations. But it has nothing to do >with IDLE per se, it's all to do with Python itself. (Sorry, I meant IDE.) Yes, I realize that it's an error on the programmer's part, but Python usually knows enough to warn you. The reason I suggested that it was an IDE error is that if it purged memory before running a script that you are working on it woud realize that an error was occuring. Here's a really simple demonstration of what I mean: #new script x=2 print x (when you run this you see "2" printed in the output window.) #modified print x You still see "2" printed in the output window. >> I guess what I'm looking for is something like BASIC's "new" >> command that flushes out everything of the session and begins >> fresh. > >The interactive prompt doesn't have that feature but >working in IDLE the best thing IMHO is simply to create >a new file using File|New... Yes, I see that's a good approach. It appears that each user created script window and the interactive window keep track of their own variables and modules. > /c > From fleet@teachout.org Sun Aug 5 02:22:05 2001 From: fleet@teachout.org (fleet@teachout.org) Date: Sat, 4 Aug 2001 21:22:05 -0400 (EDT) Subject: [Tutor] File copying - best way? Message-ID: Between os.popen("cp /path1/newfile /path2/oldfile") and open("/path1/newfile","w").write(open("/path2/oldfile","r").read()) Which, if either, is the "preferred" method of copying a file? The second will raise an IOError if it fails. I have no clue how to test the first. Are there other and/or better methods of copying a file? - fleet - From deirdre@deirdre.net Sat Aug 4 21:01:08 2001 From: deirdre@deirdre.net (Deirdre Saoirse Moen) Date: Sat, 4 Aug 2001 13:01:08 -0700 Subject: [Tutor] How to make foreign characters In-Reply-To: <3C4488B06F6@kserver.org> References: <3C4488B06F6@kserver.org> Message-ID: At 12:05 PM -0700 8/3/01, Sheila King wrote: >Anyhow, the project we are working on right now, is a french/english >vocabulary quiz, that asks you random words (either french or english) >and then you supply the translation. (I hope we will get some use out of >this in the coming school year.) > >And now the question: > >How does one make the foreign characters in French (and other foreign >languages). Like the accent symbols, or the "c" with the funny doo-hicky >on the bottom? I figure it has something to do with Unicode, but I >looked at the Unicode module documentation, and still didn't understand >how I could get started typing symbols like that. > >I want it to be fairly easy to display and to type the special >characters in this quiz game. The catch, of course, is that the answer is somewhat OS-dependent, both for input and for display. I know that on the MacOS, option-e is used for the acute accent, option-c for the cedilla, option-i for the circumflex. On python on the Mac, it doesn't recognize these special characters for input because the shell terminal doesn't (but if one was running a GUI program, it might -- I haven't tried). -- _Deirdre Stash-o-Matic: http://fuzzyorange.com http://deirdre.net Adobe put Dmitry in jail for the crime against society of revealing that they were selling ROT-13 as "encryption." He is rotting in US prison as a political prisoner for speaking out. http://freesklyarov.org From deirdre@deirdre.net Sat Aug 4 21:04:03 2001 From: deirdre@deirdre.net (Deirdre Saoirse Moen) Date: Sat, 4 Aug 2001 13:04:03 -0700 Subject: [Tutor] MySQL mangling & list subscription question In-Reply-To: References: Message-ID: At 2:56 PM -0500 8/3/01, Rob Andrews wrote: >For a little context, he is trying to pull data from a MySQL database >and assign it to a variable in Python. I can do a fair bit of Python and >a little SQL, but I've yet to mix the two. Can anyone point to some >current resources or show a quick example I can pass on? Honestly, it's not that different from PHP, except that one must do the work (as in Perl or C) to pull the variables out of the form explicitly. In PHP, they're defined for you. PHP has a lot of shortcuts for web stuff, but that's really all it does well. -- _Deirdre Stash-o-Matic: http://fuzzyorange.com http://deirdre.net Adobe put Dmitry in jail for the crime against society of revealing that they were selling ROT-13 as "encryption." He is rotting in US prison as a political prisoner for speaking out. http://freesklyarov.org From tescoil@irtc.net Sun Aug 5 02:39:27 2001 From: tescoil@irtc.net (Tesla Coil) Date: Sat, 04 Aug 2001 20:39:27 -0500 Subject: [Tutor] File copying - best way? References: Message-ID: <3B6CA3CF.4AFE65C0@irtc.net> On 4 August 2001, fleet@teachout.org wrote: > Are there other and/or better methods of copying a file? Yes, the shutil module: http://www.python.org/doc/current/lib/module-shutil.html From arcege@speakeasy.net Sun Aug 5 02:56:50 2001 From: arcege@speakeasy.net (Michael P. Reilly) Date: Sat, 4 Aug 2001 21:56:50 -0400 Subject: [Tutor] File copying - best way? In-Reply-To: ; from fleet@teachout.org on Sat, Aug 04, 2001 at 09:22:05PM -0400 References: Message-ID: <20010804215650.A986@speakeasy.net> On Sat, Aug 04, 2001 at 09:22:05PM -0400, fleet@teachout.org wrote: > Between > os.popen("cp /path1/newfile /path2/oldfile") > and > open("/path1/newfile","w").write(open("/path2/oldfile","r").read()) > > Which, if either, is the "preferred" method of copying a file? The second > will raise an IOError if it fails. I have no clue how to test the first. > > Are there other and/or better methods of copying a file? I am more partial to the copy2() function in the "shutil" module. It is more like "cp -p" on UNIX. It is also portable. Otherwise, I would write it out explicitly: infile = open("/path2/oldfile", "rb") outfile = open("/path1/newfile", "wb") block = infile.read(8192) while block: outfile.write(block) block = infile.read(8192) outfile.close() infile.close() The problem with keeping everything on one line is that a) it is harder to debug (possibly stepping through code or adding print statements), and b) it is harder to insert try-except clauses later if you need them. Also, if the file is large, reading everything at once can be a big waste of memory (and might even overflow the memory on larger programs). Reading in chucks is much more efficient. And unless you know you want to get lines, always copy in binary. -Arcege -- +----------------------------------+-----------------------------------+ | Michael P. Reilly | arcege@speakeasy.net | From tescoil@irtc.net Sun Aug 5 03:03:15 2001 From: tescoil@irtc.net (Tesla Coil) Date: Sat, 04 Aug 2001 21:03:15 -0500 Subject: [Tutor] Re: using IDLE and changing variables References: <5104D4DBC598D211B5FE0000F8FE7EB20E66BE26@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <3B6CA963.4540A436@irtc.net> On 4 August 2001, Christopher Smith wrote: > The reason I suggested that it was an IDE error is > that if it purged memory before running a script > that you are working on it woud realize that an > error was occuring. Here's a really simple > demonstration of what I mean: > > #new script > x=2 > print x > > (when you run this you see "2" printed in the output window.) > > #modified > print x > > You still see "2" printed in the output window. Discussed in the "Up All Night with IDLE" thread in January: http://mail.python.org/pipermail/tutor/2001-January/003082.html I've since stopped using IDLE, and apart from the above, now immensely favor using nedit. http://nedit.org From ak@silmarill.org Sun Aug 5 02:23:23 2001 From: ak@silmarill.org (Andrei Kulakov) Date: Sat, 04 Aug 2001 21:23:23 -0400 Subject: [Tutor] File copying - best way? In-Reply-To: <"from fleet"@teachout.org> References: Message-ID: <20010804212323.A4529@sill.silmarill.org> On Sat, Aug 04, 2001 at 09:22:05PM -0400, fleet@teachout.org wrote: > Between > os.popen("cp /path1/newfile /path2/oldfile") > and > open("/path1/newfile","w").write(open("/path2/oldfile","r").read()) > > Which, if either, is the "preferred" method of copying a file? The second > will raise an IOError if it fails. I have no clue how to test the first. > > Are there other and/or better methods of copying a file? shutil.copy() -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: http://silmarill.org/cymbaline From fleet@teachout.org Sun Aug 5 04:35:31 2001 From: fleet@teachout.org (fleet@teachout.org) Date: Sat, 4 Aug 2001 23:35:31 -0400 (EDT) Subject: [Tutor] File copying - best way? In-Reply-To: <20010804215650.A986@speakeasy.net> Message-ID: Thanks again, Michael. Thanks also to that electric personality, Tesla Coil! :) >From a beginner's perspective, I'm finding this constant ongoing discovery of additional modules a little disconcerting. For a 24-line (so far) shell script, I now have 5 modules to import. (And if I remove the "try" tests, only 8 lines!) Is there a list somewhere that breaks the modules down into categories such as "file handling" (and that includes ALL the modules pertaining to file handling)? (I even thought of os.popen("cat file1 > file2") !) :) It's late and I'm getting grumpy. Tomorrow is another day! Best regards and thanks again! - fleet - On Sat, 4 Aug 2001, Michael P. Reilly wrote: > On Sat, Aug 04, 2001 at 09:22:05PM -0400, fleet@teachout.org wrote: > > Between > > os.popen("cp /path1/newfile /path2/oldfile") > > and > > open("/path1/newfile","w").write(open("/path2/oldfile","r").read()) > > > > Which, if either, is the "preferred" method of copying a file? The second > > will raise an IOError if it fails. I have no clue how to test the first. > > > > Are there other and/or better methods of copying a file? > > I am more partial to the copy2() function in the "shutil" module. > It is more like "cp -p" on UNIX. It is also portable. > > Otherwise, I would write it out explicitly: > > infile = open("/path2/oldfile", "rb") > outfile = open("/path1/newfile", "wb") > block = infile.read(8192) > while block: > outfile.write(block) > block = infile.read(8192) > outfile.close() > infile.close() > > The problem with keeping everything on one line is that a) it is harder > to debug (possibly stepping through code or adding print statements), > and b) it is harder to insert try-except clauses later if you need them. > > Also, if the file is large, reading everything at once can be a big > waste of memory (and might even overflow the memory on larger programs). > Reading in chucks is much more efficient. And unless you know you want > to get lines, always copy in binary. > > -Arcege > > From dyoo@hkn.eecs.berkeley.edu Sun Aug 5 04:52:28 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 4 Aug 2001 20:52:28 -0700 (PDT) Subject: [Tutor] File copying - best way? In-Reply-To: Message-ID: On Sat, 4 Aug 2001 fleet@teachout.org wrote: > > Thanks again, Michael. Thanks also to that electric personality, Tesla > Coil! :) > > >From a beginner's perspective, I'm finding this constant ongoing discovery > of additional modules a little disconcerting. For a 24-line (so far) > shell script, I now have 5 modules to import. (And if I remove the "try" > tests, only 8 lines!) Is there a list somewhere that breaks the modules > down into categories such as "file handling" (and that includes ALL the > modules pertaining to file handling)? You might find: http://www.python.org/doc/current/lib/lib.html what you're looking for. It's organized in a nice, large, disconcerting table of contents. *grin* If you have more questions, feel free to ask! From tescoil@irtc.net Sun Aug 5 06:37:31 2001 From: tescoil@irtc.net (Tesla Coil) Date: Sun, 05 Aug 2001 00:37:31 -0500 Subject: [Tutor] File copying - best way? References: Message-ID: <3B6CDB9B.B7764132@irtc.net> On 4 August 2001, fleet@teachout.org wrote: > From a beginner's perspective, I'm finding this > constant ongoing discovery of additional modules > a little disconcerting. For a 24-line (so far) > shell script, I now have 5 modules to import. You're doing well. You could write 240 lines, then discover there were 5 modules you could have imported instead. BTDT, count on being there and doing it again sometime. In addition to the online library documentation for which Danny Yoo provided the link, there's _Python Essential Reference_ by David M. Beazley on New Riders Press -- The title I would have been recommending when new subscribers ask "what book should I get to learn Python," but been waiting for the second edition to arrive that covers 2.1. It's now arrived, and it's worth all of the price. You could buy a few books introducing Python. You can have a whole bunch of them on your shelf later. No offense to the authors -- they've written with the goal of introducing you, and they acheive that. This one stays within arm's length of the computer. If you see the first edition discounted, grab it. You never know when you'll be walking down the street and see a 1.5.2 interpreter. From dyoo@hkn.eecs.berkeley.edu Sun Aug 5 09:42:03 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 5 Aug 2001 01:42:03 -0700 (PDT) Subject: [Tutor] Can you see my error? [regex module] In-Reply-To: Message-ID: On Fri, 3 Aug 2001, Danny Yoo wrote: > On Fri, 3 Aug 2001 DavidCraig@pia.ca.gov wrote: > > > The message I get is: > > > > >>> > > Traceback (most recent call last): > > File "C:/Python21/Practice/therapist1.py", line 273, in ? > > gKeys = map(lambda x:regex.compile(x[0]),gPats) > > File "C:/Python21/Practice/therapist1.py", line 273, in > > gKeys = map(lambda x:regex.compile(x[0]),gPats) > > error: Badly placed parenthesis I'm exploring this problem a little bit more. Take a look: ### >>> import re >>> re.compile(")") Traceback (innermost last): File "", line 1, in ? File "/usr/lib/python1.5/re.py", line 79, in compile code=pcre_compile(pattern, flags, groupindex) pcre.error: ('unmatched brackets', 0) ### What sort of strings are you feeding into regex.compile()? The exception triggered here has the same tone as your error, although not exactly. Python normally yells out "SyntaxError" on a typical parentheses mismatching: ### >>> print ("I should break")) File "", line 1 print ("I should break")) ^ SyntaxError: invalid syntax ### so I don't think your error has to do with your program... at least, not from the level of source code. After looking through Python source, I've found that the string "Badly placed parenthesis" is coming somewhere from the regular expression module: ### [dyoo@ns Python-2.1]$ grep -i -r 'Badly placed parenthesis' * Modules/regexpr.c: return "Badly placed parenthesis"; ### and this happens when the regular expression engine sees too many right parenthesis: ### ## Deep down in the bowels of regexpr.c case Rclosepar: { if (paren_depth <= 0) goto parenthesis_error; ### Hmmm.... ### >>> import regex __main__:1: DeprecationWarning: the regex module is deprecated; please use the re module >>> # yes, yes, I know... but let me try this... >>> regex.compile('\)') Traceback (most recent call last): File "", line 1, in ? regex.error: Badly placed parenthesis ### There's the little critter! Check up and see what strings you're sending to regex.compile(). Anyway, tell us if you get the bug fixed; the uncertainty of not knowing is driving me nuts. *grin* Hope this helps! From dyoo@hkn.eecs.berkeley.edu Sun Aug 5 10:03:35 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 5 Aug 2001 02:03:35 -0700 (PDT) Subject: [Tutor] Can you see my error? [regex is buggy, avoid it!] In-Reply-To: Message-ID: On Sun, 5 Aug 2001, Danny Yoo wrote: > Hmmm.... > > ### > >>> import regex > __main__:1: DeprecationWarning: the regex module is deprecated; please use > the re module > >>> # yes, yes, I know... but let me try this... > >>> regex.compile('\)') [Note: I should have been more careful by using raw strings: regex.compile(r'\)') But the test case still stands. *grin*] > Traceback (most recent call last): > File "", line 1, in ? > regex.error: Badly placed parenthesis > ### > > There's the little critter! I forgot to complete my thoughts on this. Here goes... ...There's the little critter! ... And that's DEFINITELY a bug in regex: quoted right parens should be a perfectly fine regular expression. I guess that's why regex is deprecated. *grin* The easy fix is to use 're' instead: it has the same interface as regex, and doesn't have the bug that you're running into: ### >>> rparen_re = re.compile(r"\)") >>> rparen_re.search("I don't have an rparen") >>> rparen_re.search("But (I) do") ### So 're' does the right thing in terms of handling quoted rparens. That was an unexpected bug! I'm pretty sure that regex's brokenness is what was causing the problem. Switch over to 're', and your program should be fine. My curiosity is satisfied... and now I can sleep... *grin* From lumbricus@gmx.net Sat Aug 4 23:59:09 2001 From: lumbricus@gmx.net (lumbricus@gmx.net) Date: Sun, 5 Aug 2001 00:59:09 +0200 Subject: [Tutor] sys.exit() not working In-Reply-To: ; from fleet@teachout.org on Sat, Aug 04, 2001 at 06:42:00PM -0400 References: Message-ID: <20010805005909.A30984@Laplace.localdomain> On Sat, Aug 04, 2001 at 06:42:00PM -0400, fleet@teachout.org wrote: > Sorry - left off the subject when I replied the first time. > > > Since the shell produces a relatively understandable error message, (and I > don't know how to suppress it), ls ./*.murks 2>/dev/null > > Regards, > - fleet - > HTH n' Greetings J"o! :-) -- After all, all he did was string together a lot of old, well-known quotations. -- H.L. Mencken, on Shakespeare From fleet@teachout.org Sun Aug 5 13:57:24 2001 From: fleet@teachout.org (fleet@teachout.org) Date: Sun, 5 Aug 2001 08:57:24 -0400 (EDT) Subject: [Tutor] File copying - best way? In-Reply-To: <3B6CDB9B.B7764132@irtc.net> Message-ID: On Sun, 5 Aug 2001, Tesla Coil wrote: > In addition to the online library documentation > for which Danny Yoo provided the link, there's > _Python Essential Reference_ by David M. Beazley > on New Riders Press -- The title I would have been > recommending when new subscribers ask "what book > should I get to learn Python," but been waiting > for the second edition to arrive that covers 2.1. > I have _Python Essential Reference_, Second Edition and _Core Python Programming_. I found _Learning Python_ in the local libraray system and it's on it's second extension. I'll probably buy it also. I'm in the "if you don't know how to spell, a dictionary is useless" phase, I guess. I'm enthusiastic about Python, so until I emerge from this phase, I'll probably continue to annoy you guys! :) - fleet - From fleet@teachout.org Sun Aug 5 13:47:00 2001 From: fleet@teachout.org (fleet@teachout.org) Date: Sun, 5 Aug 2001 08:47:00 -0400 (EDT) Subject: [Tutor] File copying - best way? In-Reply-To: Message-ID: On Sat, 4 Aug 2001, Danny Yoo wrote: > > >From a beginner's perspective, I'm finding this constant ongoing discovery > > of additional modules a little disconcerting. For a 24-line (so far) > > shell script, I now have 5 modules to import. (And if I remove the "try" > > tests, only 8 lines!) Is there a list somewhere that breaks the modules > > down into categories such as "file handling" (and that includes ALL the > > modules pertaining to file handling)? > > You might find: > > http://www.python.org/doc/current/lib/lib.html > > what you're looking for. It's organized in a nice, large, disconcerting > table of contents. *grin* Well, it *is* disconcerting. Using 'glob' in the browser "find" function, I find grouped together: 6.18 getopt -- Parser for command line options 6.19 tempfile -- Generate temporary file names 6.20 errno -- Standard errno system symbols 6.21 glob -- Unix style pathname pattern expansion 6.22 fnmatch -- Unix filename pattern matching 6.23 shutil -- High-level file operations and three of the six actually contain the word 'file' in the description. Missing are "stat" (and it's close kin), "os", "fileinput", "xreadlines", "filecmp", "popen2" (and 3 and 4??), and maybe "mmap". "getopt" and "tempfile" don't do much for me right at the moment. "fnmatch" is a mystery and there's no example. (The narrative mentions glob() uses fnmatch() - so I'm probably better off with "glob". "glob" and "shutil" I will find useful. I think I might find "errno" useful also - but I have no clue how to use it. Would this have allowed me to test: os.popen("ls *.jpg") if it found no jpg files? - fleet - From arcege@speakeasy.net Sun Aug 5 14:53:44 2001 From: arcege@speakeasy.net (Michael P. Reilly) Date: Sun, 5 Aug 2001 09:53:44 -0400 Subject: [Tutor] File copying - best way? In-Reply-To: ; from fleet@teachout.org on Sun, Aug 05, 2001 at 08:47:00AM -0400 References: Message-ID: <20010805095344.A8513@speakeasy.net> On Sun, Aug 05, 2001 at 08:47:00AM -0400, fleet@teachout.org wrote: > - but I have no clue how to use it. Would this have allowed me to test: > > os.popen("ls *.jpg") > > if it found no jpg files? Much like a C program, you need to get the exit status value and decode it. The close() method returns the exit status. def list_jpegs(): class StoppedProgram(Exception): pass class ProgramTerminated(Exception): pass import os f = os.popen("ls -1 *.jpg", "r") files = f.readlines() stat = f.close() # this is what is returned by wait(2) # if rc is false (0 or None) then everything is fine if not rc: rc = 0 # program terminated normally, but possibly with error elif os.WIFEXITED(stat): rc = os.WEXITSTATUS(stat) # was cntl-Z type or something similar? elif os.WIFSTOPPED(stat): raise StoppedProgram(os.WSTOPSIG(stat)) # the program was abnormally terminated, cntl-C or logout or kill elif os.WIFSIGNALLED(stat): raise ProgramTerminated(os.WTERMSIG(stat)) return rc, files # return exit status and list You could also raise an exception if rc is true. A design flaw in how Python handles these things is that the os.W* functions cannot take the None value returned by most of the functions (like popen().close() and os.wait()) that are to pass the values to them. So you need to check the value before passing them to os.WIFEXITED, os.WSTOPSIG, etc.. For the most part, if the result is false, then you know things are fine. -Arcege -- +----------------------------------+-----------------------------------+ | Michael P. Reilly | arcege@speakeasy.net | From fleet@teachout.org Sun Aug 5 18:06:09 2001 From: fleet@teachout.org (fleet@teachout.org) Date: Sun, 5 Aug 2001 13:06:09 -0400 (EDT) Subject: [Tutor] errno module - was File copying - best way? In-Reply-To: <20010805095344.A8513@speakeasy.net> Message-ID: I will study this and look at the rest of the exceptions listed for 'os;' but what about the 'errno' module? - fleet - On Sun, 5 Aug 2001, Michael P. Reilly wrote: > On Sun, Aug 05, 2001 at 08:47:00AM -0400, fleet@teachout.org wrote: > > - but I have no clue how to use it. Would this have allowed me to test: > > > > os.popen("ls *.jpg") > > > > if it found no jpg files? > > Much like a C program, you need to get the exit status value and > decode it. The close() method returns the exit status. > > def list_jpegs(): > class StoppedProgram(Exception): > pass > class ProgramTerminated(Exception): > pass > import os > f = os.popen("ls -1 *.jpg", "r") > files = f.readlines() > > stat = f.close() # this is what is returned by wait(2) > # if rc is false (0 or None) then everything is fine > if not rc: > rc = 0 > > # program terminated normally, but possibly with error > elif os.WIFEXITED(stat): > rc = os.WEXITSTATUS(stat) > > # was cntl-Z type or something similar? > elif os.WIFSTOPPED(stat): > raise StoppedProgram(os.WSTOPSIG(stat)) > > # the program was abnormally terminated, cntl-C or logout or kill > elif os.WIFSIGNALLED(stat): > raise ProgramTerminated(os.WTERMSIG(stat)) > > return rc, files # return exit status and list > > You could also raise an exception if rc is true. A design flaw in how > Python handles these things is that the os.W* functions cannot take > the None value returned by most of the functions (like popen().close() > and os.wait()) that are to pass the values to them. So you need to > check the value before passing them to os.WIFEXITED, os.WSTOPSIG, etc.. > For the most part, if the result is false, then you know things are fine. > > -Arcege > > From clanoftheinsane@hotmail.com Sun Aug 5 19:15:05 2001 From: clanoftheinsane@hotmail.com (paul) Date: Sun, 5 Aug 2001 14:15:05 -0400 Subject: [Tutor] executables Message-ID: This is a multi-part message in MIME format. ------=_NextPart_000_0009_01C11DB9.0647AB40 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable what is the best way to make a python script into an executable file? ------=_NextPart_000_0009_01C11DB9.0647AB40 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
    what is the best way to make a python = script into=20 an executable file?
    ------=_NextPart_000_0009_01C11DB9.0647AB40-- From kalle@gnupung.net Sun Aug 5 19:33:43 2001 From: kalle@gnupung.net (Kalle Svensson) Date: Sun, 5 Aug 2001 20:33:43 +0200 Subject: [Tutor] errno module - was File copying - best way? In-Reply-To: ; from fleet@teachout.org on Sun, Aug 05, 2001 at 01:06:09PM -0400 References: <20010805095344.A8513@speakeasy.net> Message-ID: <20010805203342.A28870@gandalf> Sez fleet@teachout.org: > > I will study this and look at the rest of the exceptions listed for 'os;' > but what about the 'errno' module? The errno module is used for mapping a error code set by a failed C system call to a name and the other way around: >>> try: ... f = open("/usr/testfile", "w") ... except IOError, e: ... pass ... >>> e >>> dir(e) ['args', 'errno', 'filename', 'strerror'] >>> errno.errorcode[e.errno] 'EACCES' >>> errno.EACCES 13 >>> errno.EACCES == e.errno 1 >>> print e [Errno 13] Permission denied: '/usr/testfile' >>> Peace, Kalle -- Free Dmitry Sklyarov! - http://www.freesklyarov.org/ From kalle@gnupung.net Sun Aug 5 19:45:45 2001 From: kalle@gnupung.net (Kalle Svensson) Date: Sun, 5 Aug 2001 20:45:45 +0200 Subject: [Tutor] executables In-Reply-To: ; from clanoftheinsane@hotmail.com on Sun, Aug 05, 2001 at 02:15:05PM -0400 References: Message-ID: <20010805204545.B28870@gandalf> Sez paul: > what is the best way to make a python script into an executable file? 1) py2exe: http://sourceforge.net/projects/py2exe/ 2) installer: http://www.mcmillan-inc.com/builder.html Peace, Kalle -- Free Dmitry Sklyarov! - http://www.freesklyarov.org/ From bsass@freenet.edmonton.ab.ca Sun Aug 5 19:46:08 2001 From: bsass@freenet.edmonton.ab.ca (Bruce Sass) Date: Sun, 5 Aug 2001 12:46:08 -0600 (MDT) Subject: [Tutor] executables In-Reply-To: Message-ID: On Sun, 5 Aug 2001, paul wrote: > what is the best way to make a python script into an executable file? chmod a+x script.py ;-) But I suspect you are looking for py2exe and similar software... searching the mailing list archives for "py2exe" should get you lots of opinions on which is the best (or maybe a MS user will point you to the best thread on the subject). - Bruce From arcege@speakeasy.net Sun Aug 5 19:53:33 2001 From: arcege@speakeasy.net (Michael P. Reilly) Date: Sun, 5 Aug 2001 14:53:33 -0400 Subject: [Tutor] errno module - was File copying - best way? In-Reply-To: ; from fleet@teachout.org on Sun, Aug 05, 2001 at 01:06:09PM -0400 References: <20010805095344.A8513@speakeasy.net> Message-ID: <20010805145332.A1000@speakeasy.net> On Sun, Aug 05, 2001 at 01:06:09PM -0400, fleet@teachout.org wrote: > > I will study this and look at the rest of the exceptions listed for 'os;' > but what about the 'errno' module? >>> import os, sys >>> os.strerror >>> print os.strerror.__doc__ strerror(code) -> string Translate an error code to a message string. >>> import errno >>> errno.ENOENT 2 >>> os.strerror(errno.ENOENT) 'No such file or directory' The strerror() function is just like in C. Lets try a few errors. The open() function raises the IOError exception, which is related to the OSError exception. The actual error is a field in the exception instance. >>> try: open('/etc/nosuchfile') ... except IOError, err1: pass ... >>> err1 >>> print err1 [Errno 2] No such file or directory: '/etc/nosuchfile' >>> vars(err1) {'filename': '/etc/nosuchfile', 'strerror': 'No such file or directory', 'args': (2, 'No such file or directory'), 'errno': 2} >>> err1.errno 2 >>> errno.ENOENT == err1.errno 1 So the 'errno' member of the exception is the same as the C global. >>> try: open('/etc/passwd', 'w') ... except IOError, err2: pass ... >>> print err2 [Errno 13] Permission denied: '/etc/passwd' >>> err2.errno == errno.EACCES 1 >>> err2.errno 13 Also notice that the filename is included. Not on all, but the ones that relate to file errors, will have this attribute. Since a lot of different possible values can come from the exception, sometimes it is valuable to search for the proper error in the except clause: try: dbfile = open(dbfilename, 'rb+') except IOError, err: if err.errno == errno.EACCES: dbfilename = find_alternate_location(dbfilename) dbfile = open(dbfilename, 'wb') elif err.errno == errno.ENOENT: dbfile = open(dbfilename, 'wb+') initialize_database(dbfile) The only other purpose I have found for using the errno module is when you are raising your own IOError or OSError exceptions. import errno ... raise IOError(errno.EAGAIN, os.strerror(errno.EAGAIN)) That's pretty much it. -Arcege -- +----------------------------------+-----------------------------------+ | Michael P. Reilly | arcege@speakeasy.net | From csmith@blakeschool.org Sun Aug 5 20:49:38 2001 From: csmith@blakeschool.org (Christopher Smith) Date: Sun, 05 Aug 2001 14:49:38 -0500 Subject: [Tutor] Working interactively with IDE (refreshing script; namespace updating) Message-ID: After reading the "Up All Night with IDLE" thread http://mail.python.org/pipermail/tutor/2001-January/003082.html and seeing the post by Patrick regarding "Refreshing a script" I came up with the following way to work with IDE: The problem: When you are working on a script in a window and you make changes to an object (variable, function, etc...) name, the old object still exists. This means that you will not always get an "is not defined" error even though you would if you quit and tried to run your script after restarting IDE. Example: ORIGINAL x=2 print "x=",x MODIFIED y=1 print "y=",x ## <--forgot to change the 2nd x # the modified program will print "y= 2" -- even # though the x variable is undefined in the script it is # still remembered by Python in this IDE window and # that is what you told it (inadvertently) to print. A solution: Work with two scripts, one to load your active work and one containing your developing script: # tester.py (this just loads and reloads your work) import mywork reload(mywork) mywork.testmywork() # mywork.py (this is the one that will contain your work def testmywork(): x=2 print "x=",x When you make changes to "mywork.py" and *save* these changes and then run the "tester.py" program as written, you work in "mywork" will be reloaded and if you have a modification like shown above, you will generate an error since x is not defined. When your scipt runs as you want it to, copy the text of "mywork.py", delete the first line, and unindent one level and save under a new name. The one-best-solution (IMO): IDE would automatically do this sort of thing with a script that is being run --not in the interactive window which prompts you with the ">>>" but in the script windows that are created and used to write new scripts. /c From jack@oratrix.nl Sun Aug 5 21:01:13 2001 From: jack@oratrix.nl (Jack Jansen) Date: Sun, 05 Aug 2001 22:01:13 +0200 Subject: [Tutor] Re: [Pythonmac-SIG] Working interactively with IDE (refreshing script; namespace updating) In-Reply-To: Message by "Christopher Smith" , Sun, 05 Aug 2001 14:49:38 -0500 , Message-ID: <20010805200118.C2FC3162E06@oratrix.oratrix.nl> I think I would categorise this as a bug in IDE, I think it should clear out the namespace of the module before running it again. Or at least there should be an option alongside the "run as __main__", "run profiled", etc. to get this behaviour. -- Jack Jansen | ++++ stop the execution of Mumia Abu-Jamal ++++ Jack.Jansen@oratrix.com | ++++ if you agree copy these lines to your sig ++++ www.oratrix.nl/~jack | see http://www.xs4all.nl/~tank/spg-l/sigaction.htm From alan.gauld@bt.com Sun Aug 5 22:37:20 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun, 5 Aug 2001 22:37:20 +0100 Subject: [Tutor] File copying - best way? Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BE48@mbtlipnt02.btlabs.bt.co.uk> > _Python Essential Reference_ by David M. Beazley > It's now arrived, and it's worth all of the price. I agree, in fact I'm going to buy it even tho' I only got edition 1 a few months ago... NewRiders seem to ave beaten O'Reilly at their own game with this one. I saw F/s O'Reilly equivalent book and I still think the NewRiders one is better. > No offense to the authors -- they've written with > the goal of introducing you, and they acheive that. As one such author, no offense taken In fact my books epilogue says, in effect: "Now you know how to program go out and buy a reference book" > This one stays within arm's length of the computer. Right next to the O'Reilly Pocket reference - also due in a V2 soon... Alan G From alan.gauld@bt.com Sun Aug 5 22:46:55 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun, 5 Aug 2001 22:46:55 +0100 Subject: [Tutor] File copying - best way? Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BE49@mbtlipnt02.btlabs.bt.co.uk> > "errno" useful also > - but I have no clue how to use it. Would this have allowed > me to test: > > os.popen("ls *.jpg") > > if it found no jpg files? No. The reason being that in Unix 'ls' findng no files is NOT an error. 'ls' simply reports, quite accurately, the contents of a directory, if it's empty 'ls' returns am empty list! That's not an error. 'ls' will return an error if you ask it to list the contents of a non existent directory however. In that case the errno() stuff might be useful to you... Alan g From lumbricus@gmx.net Sun Aug 5 23:12:09 2001 From: lumbricus@gmx.net (lumbricus@gmx.net) Date: Mon, 6 Aug 2001 00:12:09 +0200 Subject: [Tutor] File copying - best way? In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66BE49@mbtlipnt02.btlabs.bt.co.uk>; from alan.gauld@bt.com on Sun, Aug 05, 2001 at 10:46:55PM +0100 References: <5104D4DBC598D211B5FE0000F8FE7EB20E66BE49@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <20010806001209.A2262@Laplace.localdomain> On Sun, Aug 05, 2001 at 10:46:55PM +0100, alan.gauld@bt.com wrote: > > > "errno" useful also > > - but I have no clue how to use it. Would this have allowed > > me to test: > > > > os.popen("ls *.jpg") > > > > if it found no jpg files? > > No. The reason being that in Unix 'ls' findng no files is > NOT an error. Hmm... $ cd /etc $ ls [snip] $ echo "$?" 0 $ ls ./*.jpg ls: ./*.jpg: Datei oder Verzeichnis nicht gefunden $ echo "$?" 1 $ It sets errno on my System $ uname -a Linux Laplace.localdomain 2.2.19 #1 Sam Apr 21 17:18:27 CEST 2001 i586 unknown 'ls' simply reports, quite accurately, the contents > of a directory, if it's empty 'ls' returns am empty list! That's > not an error. 'ls' will return an error if you ask it to list > the contents of a non existent directory however. > > In that case the errno() stuff might be useful to you... > > Alan g > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- When it is not necessary to make a decision, it is necessary not to make a decision. From fleet@teachout.org Sun Aug 5 23:42:42 2001 From: fleet@teachout.org (fleet@teachout.org) Date: Sun, 5 Aug 2001 18:42:42 -0400 (EDT) Subject: [Tutor] errno module - was File copying - best way? In-Reply-To: <20010805145332.A1000@speakeasy.net> Message-ID: On Sun, 5 Aug 2001, Michael P. Reilly wrote: > On Sun, Aug 05, 2001 at 01:06:09PM -0400, fleet@teachout.org wrote: > > > > I will study this and look at the rest of the exceptions listed for 'os;' > > but what about the 'errno' module? [good examples clipped - see previous message] > > Also notice that the filename is included. Not on all, but the ones that > relate to file errors, will have this attribute. That could be handy. > Since a lot of different possible values can come from the exception, > sometimes it is valuable to search for the proper error in the except > clause: > > try: > dbfile = open(dbfilename, 'rb+') > except IOError, err: > if err.errno == errno.EACCES: > dbfilename = find_alternate_location(dbfilename) > dbfile = open(dbfilename, 'wb') > > elif err.errno == errno.ENOENT: > dbfile = open(dbfilename, 'wb+') > initialize_database(dbfile) Would this be a good candidate for a Class - ie FindError() try: dbfile = open(dbfilename, 'rb+') except IOError: FindError() Something like that? > The only other purpose I have found for using the errno module is when > you are raising your own IOError or OSError exceptions. Ok. But errno module won't work with the os.popen() function because it (popen) doesn't raise an exception if it fails? Am I close? - fleet - From fleet@teachout.org Sun Aug 5 23:48:20 2001 From: fleet@teachout.org (fleet@teachout.org) Date: Sun, 5 Aug 2001 18:48:20 -0400 (EDT) Subject: [Tutor] File copying - best way? In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66BE49@mbtlipnt02.btlabs.bt.co.uk> Message-ID: Ok. This makes sense (although I always considered "no such file of directory" an error message. I guess it's just more of an explanation! :) Thanks, - fleet - On Sun, 5 Aug 2001 alan.gauld@bt.com wrote: > > > "errno" useful also > > - but I have no clue how to use it. Would this have allowed > > me to test: > > > > os.popen("ls *.jpg") > > > > if it found no jpg files? > > No. The reason being that in Unix 'ls' findng no files is > NOT an error. 'ls' simply reports, quite accurately, the contents > of a directory, if it's empty 'ls' returns am empty list! That's > not an error. 'ls' will return an error if you ask it to list > the contents of a non existent directory however. > > In that case the errno() stuff might be useful to you... > > Alan g > From fleet@teachout.org Mon Aug 6 00:10:36 2001 From: fleet@teachout.org (fleet@teachout.org) Date: Sun, 5 Aug 2001 19:10:36 -0400 (EDT) Subject: [Tutor] sys.exit() not working Message-ID: >From: lumbricus@gmx.net >Subject: Re: [Tutor] sys.exit() not working > >On Sat, Aug 04, 2001 at 06:42:00PM -0400, fleet@teachout.org wrote: >> Since the shell produces a relatively understandable error message, (and I >> don't know how to suppress it), > >ls ./*.murks 2>/dev/null > >HTH n' Greetings >J"o! :-) It sure does! Vielen Dank! - fleet - From kalle@gnupung.net Mon Aug 6 01:06:12 2001 From: kalle@gnupung.net (Kalle Svensson) Date: Mon, 6 Aug 2001 02:06:12 +0200 Subject: [clanoftheinsane@hotmail.com: Re: [Tutor] executables] Message-ID: <20010806020612.B29847@gandalf> I'm forwarding this to the list for better (or any) response. ----- Forwarded message from paul ----- From: "paul" To: "Kalle Svensson" Subject: Re: [Tutor] executables Date: Sun, 5 Aug 2001 15:00:10 -0400 X-Mailer: Microsoft Outlook Express 5.00.2314.1300 X-Originating-IP: [24.9.23.190] X-OriginalArrivalTime: 05 Aug 2001 18:59:47.0514 (UTC) FILETIME=[CBFA41A0:01C11DE0] why is the py2exe so hard to use? i can't figure it out. i downloaded it, and i made a "setup.py" script. i dont understand the part it says about making a distutils setup-script. can someone help? thanks, paul ----- End forwarded message ----- Peace, Kalle -- Free Dmitry Sklyarov! - http://www.freesklyarov.org/ From elmlish@onebox.com Mon Aug 6 05:13:31 2001 From: elmlish@onebox.com (Israel C. Evans) Date: Sun, 05 Aug 2001 21:13:31 -0700 Subject: [Tutor] regular expression woes .. Message-ID: <20010806041331.GDLS3258.mta06.onebox.com@onebox.com> Does anybody know why when I try... >>> pat = re.compile('_.*' | '\..*') Traceback (most recent call last): File "", line 1, in ? pat = re.compile('_.*' | '\..*') TypeError: unsupported operand type(s) for | I get the error that I do? The documentation says: "|" A|B, where A and B can be arbitrary REs, creates a regular expression that will match either A or B. An arbitrary number of REs can be separated by the "|" in this way. This can be used inside groups (see below) as well. REs separated by "|" are tried from left to right, and the first one that allows the complete pattern to match is considered the accepted branch. This means that if A matches, B will never be tested, even if it would produce a longer overall match. In other words, the "|" operator is never greedy. To match a literal "|", use \|, or enclose it inside a character class, as in [|]. It would seem to me that I'm using '|' correctly but obviously I'm not. I've also tried >>> pat1 = re.compile('_.*') >>> pat2 = re.compile('\..*') >>> allpat = re.compile(pat1 | pat2) ....same error as before... and >>> pat = re.compile(('_.*') | ('\..*')) Any ideas? Thanks, ~Israel~ __________________________________________________ FREE voicemail, email, and fax...all in one place. Sign Up Now! http://www.onebox.com From mark21rowe@yahoo.com Mon Aug 6 05:33:41 2001 From: mark21rowe@yahoo.com (Mark Rowe) Date: Mon, 06 Aug 2001 16:33:41 +1200 Subject: [Tutor] executables References: Message-ID: <3B6E1E25.10002@yahoo.com> IMO if you have MS Visual C++ it is easiest to use the Freeze tool that comes with the Python source archive. I have tried using Py2exe and installer, but without much success. Mark paul wrote: > what is the best way to make a python script into an executable file? > _________________________________________________________ Do You Yahoo!? Get your free @yahoo.com address at http://mail.yahoo.com From rob@jam.rr.com Mon Aug 6 05:39:22 2001 From: rob@jam.rr.com (Rob Andrews) Date: Sun, 5 Aug 2001 23:39:22 -0500 Subject: [Tutor] executables In-Reply-To: <3B6E1E25.10002@yahoo.com> Message-ID: # Subject: Re: [Tutor] executables # # # IMO if you have MS Visual C++ it is easiest to use the Freeze # tool that # comes with the Python source archive. I have tried using Py2exe and # installer, but without much success. # MS Visual C++? I think I've missed the connection. Rob Your one-stop shop for newbie source code! Useless Python: http://www.lowerstandard.com/python/ From bsass@freenet.edmonton.ab.ca Mon Aug 6 05:54:33 2001 From: bsass@freenet.edmonton.ab.ca (Bruce Sass) Date: Sun, 5 Aug 2001 22:54:33 -0600 (MDT) Subject: [Tutor] regular expression woes .. In-Reply-To: <20010806041331.GDLS3258.mta06.onebox.com@onebox.com> Message-ID: On Sun, 5 Aug 2001, Israel C. Evans wrote: > Does anybody know why when I try... > > >>> pat = re.compile('_.*' | '\..*') > Traceback (most recent call last): > File "", line 1, in ? > pat = re.compile('_.*' | '\..*') > TypeError: unsupported operand type(s) for | > > I get the error that I do? Because you can't "or" two strings, if you could you would be passing the result onto re.compile. Is this what you are after... >>> import re >>> pat = re.compile("_.*|\..*") >>> [you may want to re-read the bit about using raw strings for regular expressions] <...> > I've also tried > >>> pat1 = re.compile('_.*') > >>> pat2 = re.compile('\..*') > >>> allpat = re.compile(pat1 | pat2) > > ....same error as before... ...because you are doing the same as before, trying to "or" two strings. - Bruce From wmperry@swbell.net Mon Aug 6 06:16:28 2001 From: wmperry@swbell.net (William Perry) Date: Mon, 06 Aug 2001 00:16:28 -0500 Subject: [clanoftheinsane@hotmail.com: Re: [Tutor] executables] In-Reply-To: <20010806020612.B29847@gandalf> References: <20010806020612.B29847@gandalf> Message-ID: <200108060016280980.073C838A@mail.swbell.net> I had the same problem, I'm assuming that downloaded means downloaded AND installed. The directions are a bit cryptic but followed faithfully the do result in an .EXE.. place the setup.py and the .py file in the same directory and run the setup from the command line HTH? W M Perry *********** REPLY SEPARATOR *********** On 8/6/01 at 2:06 AM Kalle Svensson wrote: >I'm forwarding this to the list for better (or any) response. > >----- Forwarded message from paul ----- > >From: "paul" >To: "Kalle Svensson" >Subject: Re: [Tutor] executables >Date: Sun, 5 Aug 2001 15:00:10 -0400 >X-Mailer: Microsoft Outlook Express 5.00.2314.1300 >X-Originating-IP: [24.9.23.190] >X-OriginalArrivalTime: 05 Aug 2001 18:59:47.0514 (UTC) FILETIME=[CBFA41A0:01C11DE0] > >why is the py2exe so hard to use? i can't figure it out. i downloaded it, >and i made a "setup.py" script. i dont understand the part it says about >making a distutils setup-script. can someone help? > >thanks, >paul > > >----- End forwarded message ----- > >Peace, > Kalle >-- >Free Dmitry Sklyarov! - http://www.freesklyarov.org/ > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From sheila@thinkspot.net Mon Aug 6 06:23:14 2001 From: sheila@thinkspot.net (Sheila King) Date: Sun, 05 Aug 2001 22:23:14 -0700 Subject: [clanoftheinsane@hotmail.com: Re: [Tutor] executables] In-Reply-To: <20010806020612.B29847@gandalf> References: <20010806020612.B29847@gandalf> Message-ID: <397178C220F@kserver.org> On Mon, 6 Aug 2001 02:06:12 +0200, Kalle Svensson wrote about [clanoftheinsane@hotmail.com: Re: [Tutor] executables]: :why is the py2exe so hard to use? i can't figure it out. i downloaded it, :and i made a "setup.py" script. i dont understand the part it says about :making a distutils setup-script. can someone help? : :thanks, :paul Maybe this document will help? http://www.python.org/doc/current/dist/dist.html -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From clanoftheinsane@hotmail.com Mon Aug 6 07:16:30 2001 From: clanoftheinsane@hotmail.com (paul) Date: Mon, 6 Aug 2001 02:16:30 -0400 Subject: [Tutor] Re: executables (i can't figure this one out) Message-ID: This is a multi-part message in MIME format. ------=_NextPart_000_000D_01C11E1D.CE7D7D60 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable hey guys, i just can't figure this stuff out. i've got all the = distutils things, and i made my setup.py file (and that might be where i = messed up). after i ran setup.py with the "sdist" parameter, it created = a folder with a readme and the setup.py file in it. but i'm stuck. the = instructions available aren't very good, unless i'm just totally missing = something. thanks for all you guys' help, it is much appreciated, paul brown ------=_NextPart_000_000D_01C11E1D.CE7D7D60 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
    hey guys, i just can't figure this = stuff out. =20 i've got all the distutils things, and i made my setup.py file (and that = might=20 be where i messed up).  after i ran setup.py with the "sdist" = parameter, it=20 created a folder with a readme and the setup.py file in it.  but = i'm=20 stuck.  the instructions available aren't very good, unless i'm = just=20 totally missing something.
     
    thanks for all you guys' help, it is = much=20 appreciated,
    paul brown
    ------=_NextPart_000_000D_01C11E1D.CE7D7D60-- From Charlie Clark Mon Aug 6 09:04:03 2001 From: Charlie Clark (Charlie Clark) Date: Mon, 06 Aug 2001 10:04:03 +0200 Subject: [Tutor] Help with Parsing HTML files References: Message-ID: <00038ad7f3d8a75d_mailit@mail.isis.de> >Maybe an example will help --- Here's a small example that, given a web >site, tries to pull out all the image names. (Rob, here's another useless >python script. *grin*) > >This example will use htmllib to help us "parse" and hunt down IMG tags. >I don't think we need to explicitly rewrite handle_image(). For HTML >elements that have start and end tags, let's define >"start_nameofsometag()" and "end_nameofsometag()" methods. However, since >an IMG tag stands alone, we'll write a do_img() method instead. > > > >### >import htmllib >import formatter >import sys >import urllib > >class ImagePuller(htmllib.HTMLParser): > def __init__(self): > htmllib.HTMLParser.__init__(self, > formatter.NullFormatter()) > self.list_of_images = [] > > def do_img(self, attributes): > for name, value in attributes: > if name == 'src': > new_image = value > self.list_of_images.append(new_image) > > def getImageList(self): > return self.list_of_images > >if __name__ == '__main__': > url = sys.argv[1] > url_contents = urllib.urlopen(url).read() > puller = ImagePuller() > puller.feed(url_contents) > print puller.getImageList() >### > > >For more information about this, take a look at: > > http://python.org/doc/current/lib/module-sgmllib.html I've looked at this but as it doesn't come with examples I'm stumped. If do_img is a method of ImagePuller, when is it called and how does it look for images? It seems to do this via tag analysis where a tag contains "src" which won't just be images but any inline element (object, script, frame, etc.) and how do I overwrite or modify it to work with specific tags together with specific content. The pages I'm pulling in are "contaminated" - HTML and content are horribly mixed so that I can't depend on looking at specific tabs. My current script looks for a specific table beginning
    Date title

    Article
    DateDate
    Runde but the next one I have to write looks for a table cell and has a different separator. I can parse the files with htmllib and sgmllib. I think sgmllib is probably more useful as I can check each tab and start "buffering" (I think that's the appropriate term) content if necessary providing I look at the results of sgmllib line for line. Maybe once I've mastered this I can put the definition into a method? On a different note but to do with the fact that I have trouble understanding classes: there is a lexical inconsistency between class methods and standard functions isn't there? In a function the number of arguments is the same in its definition as when it's called. def does_little(something): print something does_little('hi') prints 'hi' in a class I'd always have to have the magical 'self' in there as well wouldn't I? class NewObject: def does_little(self, something): print something x = NewObject('hi') x.does_little('hi') prints 'hi' I don't know why but I just have trouble with this inconsistency. Is it really necessary? From dyoo@hkn.eecs.berkeley.edu Mon Aug 6 09:43:14 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 6 Aug 2001 01:43:14 -0700 (PDT) Subject: [Tutor] Help with Parsing HTML files [html/OOP] In-Reply-To: <00038ad7f3d8a75d_mailit@mail.isis.de> Message-ID: On Mon, 6 Aug 2001, Charlie Clark wrote: > >### > >import htmllib > >import formatter > >import sys > >import urllib > > > >class ImagePuller(htmllib.HTMLParser): > > def __init__(self): > > htmllib.HTMLParser.__init__(self, > > formatter.NullFormatter()) > > self.list_of_images = [] > > > > def do_img(self, attributes): > > for name, value in attributes: > > if name == 'src': > > new_image = value > > self.list_of_images.append(new_image) > > > > def getImageList(self): > > return self.list_of_images > > > >if __name__ == '__main__': > > url = sys.argv[1] > > url_contents = urllib.urlopen(url).read() > > puller = ImagePuller() > > puller.feed(url_contents) > > print puller.getImageList() > >### > > > > > >For more information about this, take a look at: > > > > http://python.org/doc/current/lib/module-sgmllib.html > I've looked at this but as it doesn't come with examples I'm stumped. Don't worry too much yet: the documentation to htmllib assumes that you already know about OOP style programming, as well as event-driving programming. If both are new topics, then this might take a little while to figure out. > If do_img is a method of ImagePuller, when is it called and how does it look > for images? It seems to do this via tag analysis where a tag contains "src" Yes, there's some analysis being done behind the scenes in sgmllib. The do_img() method actually gets called during the feed()ing process: puller.feed() feed() is something that's defined in sgmllib. Whenever it encounters a new tag, it dynamically tries to call an appropriately named method. If it runs into a P tag, for example, it'll try calling "start_p". Let's take a small look at sgmllib for a second: ### def finish_starttag(self, tag, attrs): try: method = getattr(self, 'start_' + tag) except AttributeError: try: method = getattr(self, 'do_' + tag) except AttributeError: self.unknown_starttag(tag, attrs) return -1 else: self.handle_starttag(tag, method, attrs) return 0 ### Here, sgmllib's parser tries to call methods by "permission": it just goes ahead and tries calling start_sometagname(), and if something bad happens, it backs away. No harm done. By subclassing and defining our own start_sometagname/do_sometagname for the tags that we're interested in, we allow those permissive method calls to go through. > for images? It seems to do this via tag analysis where a tag contains > "src" which won't just be images but any inline element (object, > script, frame, etc.) and how do I overwrite or modify it to work with > specific tags together with specific content. The pages I'm pulling in For each specific tag, we can add an additional method with a particular tag name. For example, to get the parsing to pay attention to bold tags and underlines, we can do something like this: ### class EmphasisGlancer(htmllib.HTMLParser): def __init__(self): htmllib.HTMLParser.__init__(self, formatter.NullFormatter()) self.in_bold = 0 self.in_underline = 0 def start_b(self, attrs): print "Hey, I see a bold tag!" self.in_bold = 1 def end_b(self): self.in_bold = 0 def start_u(self, attrs): print "Hey, I see some underscored text!" self.in_underline = 1 def end_u(self): self.in_underline = 0 def start_blink(self, attrs): print "Hey, this is some heinously blinking test... *grrrr*" def handle_data(self, data): if self.in_bold: print "BOLD:", data elif self.in_underline: print "UNDERLINE:", data ### I have not tested this code yet, but hopefully I haven't made too many typos. If you play around with it, you might find that sgmllib/htmllib isn't as bad as you think. I should stop here, since the message is too long. I'll try answering your second question tomorrow. Talk to you later! From Charlie Clark Mon Aug 6 10:15:33 2001 From: Charlie Clark (Charlie Clark) Date: Mon, 06 Aug 2001 11:15:33 +0200 Subject: [Tutor] Help with Parsing HTML files [html/OOP] References: Message-ID: <00038ad8f3897cb6_mailit@mail.isis.de> >Don't worry too much yet: the documentation to htmllib assumes that you >already know about OOP style programming, as well as event-driving >programming. If both are new topics, then this might take a little while >to figure out. > Basically yes and thanx for the encouragement. > >> If do_img is a method of ImagePuller, when is it called and how does it >look >> for images? It seems to do this via tag analysis where a tag contains >"src" > > >Yes, there's some analysis being done behind the scenes in sgmllib. The >do_img() method actually gets called during the feed()ing process: > > puller.feed() > >feed() is something that's defined in sgmllib. Whenever it encounters a >new tag, it dynamically tries to call an appropriately named method. If >it runs into a P tag, for example, it'll try calling "start_p". Let's >take a small look at sgmllib for a second: Right, simple but effective. Pity the documentation doesn't make this clearer. I think I've also understood you're example of extending the class to deal attributes in certain ways. I need to do some thinking on this though. Once thing I'd like to do but still haven't worked out is mimic what calling sgmllib does on its own and get all that intelligence put into a file so that I can do my analysis of it. At the moment I'm copying my source file into my python library and renaming it test.html and runnung sgmllib > output.txt. This gives me a nice hierarchical model which simply distinguishes between formatting and data. Because it's easier for me I would like to be able to pass the results of sgmllib's work line for line to my own functions. I think I need to use sgmllib as I need the tag classifications in the analysis and htmllib does away with them. How would I go about this? Once I've worked out what my functions should do I guess it should be quite easy to turn them into methods in my own special class. Easy in theory that is. I probably still need a lot of help ;-) Have a good night's sleep and talk to you later today! Charlie From toodles@yifan.net Mon Aug 6 11:30:08 2001 From: toodles@yifan.net (Andrew Wilkins) Date: Mon, 6 Aug 2001 18:30:08 +0800 Subject: [Tutor] foreign lists In-Reply-To: Message-ID: >> is it possible to access a list from another file and save whatever changes are made to the list after >> the original program has been run? Sorry about the delay, I'm back at school now! Charlie did answer, I just thought I'd point you to a class I created called ListShelf. http://www.lowerstandard.com/python/ListShelf.py Basically I made it for the same purpose as you (well in the technical side, I didn't want to use it make a book database.) It opens a file and uses the cPickle module to create a persistent list object. This works much like the shelve module does, while shelve uses dictionaries, ListShelf (aptly named, no?) uses lists. You create an instance of the class, then you treat it as a list. If however you want to pass the list to another object, you'd have to use the instances 'data' attribute. Here's how you'd use it... >>> import ListShelf >>> x=ListShelf.ListShelf('my_list_file.dat') >>> x.append(('Catcher in the Rye',('maturation','teenage'))) >>> x [('Catcher in the Rye', ('maturation', 'teenage'))] >>> del x; #Just to prove it is persistent... >>> x=ListShelf.ListShelf('my_list_file.dat') >>> x [('Catcher in the Rye', ('maturation', 'teenage'))] HTH, Andrew From kalle@gnupung.net Mon Aug 6 12:37:13 2001 From: kalle@gnupung.net (Kalle Svensson) Date: Mon, 6 Aug 2001 13:37:13 +0200 Subject: [Tutor] executables In-Reply-To: ; from rob@jam.rr.com on Sun, Aug 05, 2001 at 11:39:22PM -0500 References: <3B6E1E25.10002@yahoo.com> Message-ID: <20010806133713.A439@gandalf> Sez Rob Andrews: > # Subject: Re: [Tutor] executables > # > # > # IMO if you have MS Visual C++ it is easiest to use the Freeze > # tool that > # comes with the Python source archive. I have tried using Py2exe and > # installer, but without much success. > # > > MS Visual C++? I think I've missed the connection. Freeze requires a C compiler, and on Windows MSVC++ is the easiest to use with Python as it's the compiler the developers use. IANAWU, though. Peace, Kalle -- Free Dmitry Sklyarov! - http://www.freesklyarov.org/ From rhystucker@yahoo.com Mon Aug 6 12:48:51 2001 From: rhystucker@yahoo.com (rhys tucker) Date: Mon, 6 Aug 2001 04:48:51 -0700 (PDT) Subject: [Tutor] Using os.path.walk Message-ID: <20010806114851.24748.qmail@web12107.mail.yahoo.com> I'm trying to use os.path.walk. #/usr/bin/env python import os, shelve db = shelve.open("shelveTestDB") startdir = os.curdir arg = 1 # How should I deal with this unused paramater? def diraction(arg, dirname, names): count = 0 files = names for fl in files: if os.path.isfile(fl): count = count + 1 db[fl] = count os.path.walk(startdir, diraction, arg) db.close() For me, the names paramater changes with subsequent calls to diraction, but files does not. It also appears that "for fl in files" is run only 3 times in total (with the same files list). thanks, rhys __________________________________________________ Do You Yahoo!? Make international calls for as low as $.04/minute with Yahoo! Messenger http://phonecard.yahoo.com/ From lsloan@umich.edu Mon Aug 6 14:04:17 2001 From: lsloan@umich.edu (Lance E Sloan) Date: Mon, 06 Aug 2001 09:04:17 -0400 Subject: [Tutor] foreign lists In-Reply-To: Your message of "Sat, 04 Aug 2001 11:03:43 EDT." Message-ID: <200108061304.JAA03928@birds.us.itd.umich.edu> "paul" wrote: > is it possible to access a list from another file and save whatever = > changes are made to the list after the original program has been run? i = > made a simple book database which matches book titles with certain = > attributes each book contains. i want to be able to create the main = > list of books and have my program access that list. i also want any = > additions made to the list to be changed in that foreign list, so that = > next time the program is run, the list will include the new addition. = > right now, though, i have it so that each time the program runs, it = > starts with a blank list. any suggestions??? if anyone wants the code, = > i'll be happy to post that also. Paul, Somebody asked a similar question a week or two ago. He wanted to put a list in a web page form that would be submitted back to a CGI (written in Python, of course) that could then use it again. The difference is that in your problem, you want it written to a file, rather than a web form. I'll assume you know how to read and write to a file. If you just print a list, Python will format it the same way you would if you put one in your program: >>> groceries = ['eggs', 'baked beans', 'spam'] >>> print groceries ['eggs', 'baked beans', 'spam'] So, you could print yout list to the file and you're all set. When you read the list back from the file, you will read it into a string, which you can convert back to a list using the eval() function: >>> food = eval("['eggs', 'baked beans', 'spam']") >>> food ['eggs', 'baked beans', 'spam'] >>> food[0] 'eggs' The last line of that example is just to prove that "food" really is a list. This is pretty simplistic. I've heard of a Python module called "pickle" which will convert an object (a list is an object) into a string that you can save to a file or however you like and you can later "unpickle" it to get the original object back. That would probably be better. I've never used it myself. I would suggest that you reconsider lists as your choice of data structure, though. You should probably use a database instead. Look at the various modules that came with Python that contain "db" in their names. You'll probably find one that suits your needs. Alternatively, if you're wedded to the list idea, how about a list of dictionaries? Each book would have it's own dictionary in the list: >>> books = [{'author': 'Monty', 'title': 'Pointed Sticks'}, ... {'author': 'Python', 'title': 'How to tell a witch'}] >>> books [{'author': 'Monty', 'title': 'Sharp objects'}, {'author': 'Python', 'title': 'How To Tell a Witch'}] >>> books[0]['title'] 'Pointed Sticks' >>> books[1]['author'] 'Python' Those last two lines I wrote are examples of getting the title of the first book (the first is numbered zero) and the author of the second. -- Lance E Sloan Web Services, Univ. of Michigan: Full-service Web and database design, development, and hosting. Specializing in Perl & Python CGIs. http://websvcs.itd.umich.edu/ - "Putting U on the Web" From alan.gauld@bt.com Mon Aug 6 10:28:10 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon, 6 Aug 2001 10:28:10 +0100 Subject: [Tutor] File copying - best way? Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BE4A@mbtlipnt02.btlabs.bt.co.uk> > Ok. This makes sense (although I always considered "no such file of > directory" an error message. I guess it's just more of an > explanation! :) Good point. In fact my statement below is wrong: > > not an error. 'ls' will return an error if you ask it to list > > the contents of a non existent directory however. > > > > In that case the errno() stuff might be useful to you... As you say 'ls' just alerts you to the fact that the directory doesn't exist it is still not an "error" in a programming sense. I guess the only real error ls returns will be cases where it gets confused about the state of a directory or something. Come to think of it I'm not sure I've ever seen 'ls' return an actual error message (eg. with the word 'error' in it...) and playing with it I can't find a way to force it to either... Alan G. From alan.gauld@bt.com Mon Aug 6 10:51:24 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon, 6 Aug 2001 10:51:24 +0100 Subject: [Tutor] File copying - best way? Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BE4B@mbtlipnt02.btlabs.bt.co.uk> > On Sun, Aug 05, 2001 at 10:46:55PM +0100, alan.gauld@bt.com wrote: > > No. The reason being that in Unix 'ls' findng no files is > > NOT an error. > $ ls > [snip] > $ echo "$?" > 0 > $ ls ./*.jpg > ls: ./*.jpg: Datei oder Verzeichnis nicht gefunden > $ echo "$?" > 1 > It sets errno on my System Interesting - back to the terminal to try again.... Ah! I was testing with a malformed C program: #include #include "errno.h" #include "stdlib.h" void main(){ // this works system("ls /etc"); perror("Test:"); // this doesn't system("ls /frutty"); perror("Test:"); } I should of course have been testing the return value of system(). status = system("ls /etc/fruuty"); printf("status = %d\n", status); errno held the result of system(), not the result of the command executed by system() - oops! Alan G. From alan.gauld@bt.com Mon Aug 6 11:02:58 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon, 6 Aug 2001 11:02:58 +0100 Subject: [Tutor] regular expression woes .. Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BE4D@mbtlipnt02.btlabs.bt.co.uk> > Does anybody know why when I try... > > >>> pat = re.compile('_.*' | '\..*') > Traceback (most recent call last): > File "", line 1, in ? > pat = re.compile('_.*' | '\..*') > TypeError: unsupported operand type(s) for | Coz the re function takes a single RE as a string. You are trying to take the bitwise OR of two strings and pass the result. Bitwise ORs don't work with strings... You need to form the whole RE as a single string. "_.*|\..*" OR maybe "(_.*)|(\..*)" depending onm exactly what you want. BTW. Somebody has put on the web a really nice RE syntax checker written in Python and Tkinter. You might want to do a search and see if you can pick it up... > >>> pat = re.compile(('_.*') | ('\..*')) I suspect this is the correct one if you just wrap it all as a string... Alan G From alan.gauld@bt.com Mon Aug 6 10:57:49 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon, 6 Aug 2001 10:57:49 +0100 Subject: [clanoftheinsane@hotmail.com: Re: [Tutor] executables] Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BE4C@mbtlipnt02.btlabs.bt.co.uk> > From: "paul" > why is the py2exe so hard to use? i can't figure it out. Because its not a normal thing to do with Python. Python wasn't designed to create executable binaries. In fact I always think its pretty amazing that poeople figure out how to do this kind of stuff at all - and I'm still not sure I understand why... The payload savings aren't worth it IMHO. If you want executable binaries you are better using C, Delphi, VB, FORTRAN or whatever IMHO. But if you insist on bending a scripting language into a pseudo executable format py2exe makes it as easy as seems reasonable. Another approach is to use Jython of course - that gives you a java class file that woill run under any JVM. And is easier than py2exe to use but brings its own set of limitations. Now as for the specifics of using py2exe you'll need to get somebody else to answer, like I said I've never quite seen the point... Alan g. From norman@earth.ox.ac.uk Mon Aug 6 16:22:13 2001 From: norman@earth.ox.ac.uk (Norman Charnley) Date: Mon, 6 Aug 2001 16:22:13 +0100 (BST) Subject: [Tutor] Setting default font in Tkinter In-Reply-To: Message-ID: Is there a way to change the default font in Tkinter for all applications (using Python 2.1 under RedHat Linux 7.1)? I know I can set it specifically when I am creating widgets, but it would be useful to have the default a little more readable. In particular, when I fire up Idle, the menu font (not the editing font, which IS configurable) is awful, and although I can mostly fix it up by poking about in EditorWindow.py, that seems a messy way to have to go. Thanks in advance for any help.... Norman ================================================= Dr. Norman Charnley Department of Earth Sciences University of Oxford ================================================== From Ray Leyva" This is a multi-part message in MIME format. ------=_NextPart_000_001F_01C11E73.9451B6A0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable To All, I'm trying to write a small automation tool for the IE COM object. = Using Dispatch in Win32. Here's a snippet. .... snip .... from win32com.client import Dispatch ... snip .... def openbrowser(self): self.ie =3D Dispatch("InternetExplorer.Application") self.ie.Visible=3D1 .... snip .... Whenever I run this code it will automatically take control of whatever = explorer interface is already running, including but not limited to any = 'Windows Explorer' file browsers currently open ( It will only take = control of one of these windows ). I was wondering if there is a way to = issue a Dispatch command to force it to open in a new window. I appreciate any and all help, and will respond with any clarifications = that are needed. I'm hoping to submit this as a cookbook recipe if I = can ever get a few of these niggling little issues out of the way. TIA Ray ------=_NextPart_000_001F_01C11E73.9451B6A0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
    To All,
     
    I'm trying to write a small automation = tool for the=20 IE COM object.  Using Dispatch in Win32.  Here's a=20 snippet.
     
    .... snip ....
     
    from win32com.client import=20 Dispatch
    ... snip ....
     
        def=20 openbrowser(self):
            self.ie = =3D=20 Dispatch("InternetExplorer.Application")
         = ;  =20 self.ie.Visible=3D1
     
    .... snip ....
     
    Whenever I run this code it will = automatically=20 take control of whatever explorer interface is already running, = including but=20 not limited to any 'Windows Explorer' file browsers currently open ( It = will=20 only take control of one of these windows ).  I was wondering if = there is a=20 way to issue a Dispatch command to force it to open in a new=20 window.
     
    I appreciate any and all help, and will = respond=20 with any clarifications that are needed.  I'm hoping to submit this = as=20 a cookbook recipe if I can ever get a few of these niggling little = issues=20 out of the way.
     
    TIA
    Ray
    ------=_NextPart_000_001F_01C11E73.9451B6A0-- From kromag@nsacom.net Mon Aug 6 23:23:09 2001 From: kromag@nsacom.net (kromag@nsacom.net) Date: Mon, 6 Aug 2001 15:23:09 -0700 (PDT) Subject: [Tutor] transpose problems in PIL Message-ID: <200108062223.f76MN9t30645@pop.nsacom.net> Howdy. For some strange reason that I cannot fathom I am having difficulty with transpose() in PIL. To wit: import Image import os import sys background=Image.open("\windows\desktop\doug.jpg") clip1=Image.open("\windows\desktop\robo.gif") clip2=clip1.transpose(Image.ROTATE_180) clip3=clip1.transpose(Image.FLIP_RIGHT_LEFT) clip4=clip2.transpose(Image.FLIP_RIGHT_LEFT) pos1=(10,10,94,92) pos2=(10,385,94,467) pos3=(296,10,380,92) pos4=(296,387,380,469) background.paste(clip1,pos1) background.paste(clip2, pos2) background.paste(clip3,pos3) background.paste(clip4,pos4) background.save("\windows\desktop\test.jpg","JPEG") it gives me the error: >pythonw -u card_builder.py Traceback (most recent call last): File "card_builder.py", line 7, in ? clip3=clip1.transpose(Image.FLIP_RIGHT_LEFT) AttributeError: FLIP_RIGHT_LEFT >Exit code: 1 Image.ROTATE_180 works just fine. Clues? From kromag@nsacom.net Mon Aug 6 23:30:56 2001 From: kromag@nsacom.net (kromag@nsacom.net) Date: Mon, 6 Aug 2001 15:30:56 -0700 (PDT) Subject: [Tutor] transpose problems in PIL Message-ID: <200108062230.f76MUut06186@pop.nsacom.net> Howdy. For some strange reason that I cannot fathom I am having difficulty with transpose() in PIL. To wit: import Image import os import sys background=Image.open("\windows\desktop\doug.jpg") clip1=Image.open("\windows\desktop\robo.gif") clip2=clip1.transpose(Image.ROTATE_180) clip3=clip1.transpose(Image.FLIP_RIGHT_LEFT) clip4=clip2.transpose(Image.FLIP_RIGHT_LEFT) pos1=(10,10,94,92) pos2=(10,385,94,467) pos3=(296,10,380,92) pos4=(296,387,380,469) background.paste(clip1,pos1) background.paste(clip2, pos2) background.paste(clip3,pos3) background.paste(clip4,pos4) background.save("\windows\desktop\test.jpg","JPEG") it gives me the error: >pythonw -u card_builder.py Traceback (most recent call last): File "card_builder.py", line 7, in ? clip3=clip1.transpose(Image.FLIP_RIGHT_LEFT) AttributeError: FLIP_RIGHT_LEFT >Exit code: 1 Image.ROTATE_180 works just fine. Clues? From kalle@gnupung.net Mon Aug 6 21:31:15 2001 From: kalle@gnupung.net (Kalle Svensson) Date: Mon, 6 Aug 2001 22:31:15 +0200 Subject: [Tutor] transpose problems in PIL In-Reply-To: <200108062223.f76MN9t30645@pop.nsacom.net>; from kromag@nsacom.net on Mon, Aug 06, 2001 at 03:23:09PM -0700 References: <200108062223.f76MN9t30645@pop.nsacom.net> Message-ID: <20010806223115.A2167@gandalf> Sez kromag@nsacom.net: > Howdy. > > For some strange reason that I cannot fathom I am having difficulty with > transpose() in PIL. [snip] > it gives me the error: > > > >pythonw -u card_builder.py > Traceback (most recent call last): > File "card_builder.py", line 7, in ? > clip3=clip1.transpose(Image.FLIP_RIGHT_LEFT) > AttributeError: FLIP_RIGHT_LEFT > >Exit code: 1 > > Image.ROTATE_180 works just fine. Clues? I've never used PIL, so I'm just guesing here, but two things to check: Could it be Image.FLIP_LEFT_RIGHT or something? Is it implemented in the version of PIL you're using? Peace, Kalle -- Free Dmitry Sklyarov! - http://www.freesklyarov.org/ From fleet@teachout.org Mon Aug 6 22:04:59 2001 From: fleet@teachout.org (fleet@teachout.org) Date: Mon, 6 Aug 2001 17:04:59 -0400 (EDT) Subject: [Tutor] errno module - was File copying - best way? Message-ID: >From: Kalle Svensson >Subject: Re: [Tutor] errno module - was File copying - best way? > >Sez fleet@teachout.org: >> >> I will study this and look at the rest of the exceptions listed for 'os;' >> but what about the 'errno' module? > >The errno module is used for mapping a error code set by a failed C system >call to a name and the other way around: > >>>> try: >... f = open("/usr/testfile", "w") >... except IOError, e: <---------------- this was what I was missing! >... pass >... This error, value thing was what I was missing. Things make a lot more sense now! Thanks all! - fleet - From agauld@crosswinds.net Tue Aug 7 00:02:50 2001 From: agauld@crosswinds.net (agauld@crosswinds.net) Date: Tue, 7 Aug 2001 00:02:50 +0100 Subject: [Tutor] Korean tutor available Message-ID: <20010806230514.6CE944CA21@member-mx1.crosswinds.net> Thanks to "johnsonj" I now have a Korean version of my online tutor available. Before I generally announce its presence and add a link to it from the top level is there anyone on this list who can read Korean and can take a quick look to sanity check it? http://www.crosswinds.net/~agauld/korean/ My Korean is non-existent! TIA, Alan G. From jessw@loop.com Tue Aug 7 00:35:57 2001 From: jessw@loop.com (Jesse W) Date: Mon, 6 Aug 2001 16:35:57 -0700 Subject: [Tutor] Re: using IDLE and changing variables In-Reply-To: <3B6CA963.4540A436@irtc.net> Message-ID: <3B6EC76D.10115.16DEA8F@localhost> Dear all, Whenever I see this thread again(and I have seen it often :-) ), I think to myself: "This does not look to hard to hack up, why don't I do it?" Well, finally, I have. Here it is: ----------------------------------------------------------------------------- def reset(namespace, user_safe_items=()): """Reset given namespace to a "pristine" state. This is a widely requested function which will remove from the current namespace everything execpt the items listed in below.""" safe_items=['__builtins__', '__doc__', '__name__', 'reset']\ +list(user_safe_items) for item in namespace.keys(): if item not in safe_items: exec "del "+item in namespace ----------------------------------------------------------------------------- I expect (and hope) it is simple enough to be clear. Jesse F. W From nott@it.uts.edu.au Tue Aug 7 03:21:13 2001 From: nott@it.uts.edu.au (Tom Nott) Date: Tue, 7 Aug 2001 12:21:13 +1000 Subject: [Tutor] Dictionaries supplying arguments to functions Message-ID: <20010807122113.C10406@it.uts.edu.au> Is it possible to have a dictionary supply the arguments to a function? I'm after something like: def fn(p1, p2, p3): print p1 print p2 print p3 d = {'p1':'How ', 'p2':'are ', 'p3':'you'} callWithDict(fn, d) -- Tom Nott From dyoo@hkn.eecs.berkeley.edu Tue Aug 7 03:26:15 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 6 Aug 2001 19:26:15 -0700 (PDT) Subject: [Tutor] transpose problems in PIL In-Reply-To: <20010806223115.A2167@gandalf> Message-ID: On Mon, 6 Aug 2001, Kalle Svensson wrote: > > For some strange reason that I cannot fathom I am having difficulty with > > transpose() in PIL. > [snip] > > it gives me the error: > > > > > > >pythonw -u card_builder.py > > Traceback (most recent call last): > > File "card_builder.py", line 7, in ? > > clip3=clip1.transpose(Image.FLIP_RIGHT_LEFT) > > AttributeError: FLIP_RIGHT_LEFT > > >Exit code: 1 > > > > Image.ROTATE_180 works just fine. Clues? > > I've never used PIL, so I'm just guesing here, but two things to check: > > Could it be Image.FLIP_LEFT_RIGHT or something? > Is it implemented in the version of PIL you're using? According to the PIL handbook at: http://www.pythonware.com/library/pil/handbook/image.htm you can do the following transposes: FLIP_LEFT_RIGHT FLIP_TOP_BOTTOM ROTATE_90 ROTATE_180 ROTATE_270 Hope this helps! From dyoo@hkn.eecs.berkeley.edu Tue Aug 7 03:31:55 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 6 Aug 2001 19:31:55 -0700 (PDT) Subject: [Tutor] Korean tutor available In-Reply-To: <20010806230514.6CE944CA21@member-mx1.crosswinds.net> Message-ID: On Tue, 7 Aug 2001 agauld@crosswinds.net wrote: > Thanks to "johnsonj" I now have a Korean version of my online tutor > available. Before I generally announce its presence and add a link to > it from the top level is there anyone on this list who can read Korean > and can take a quick look to sanity check it? > > http://www.crosswinds.net/~agauld/korean/ > > My Korean is non-existent! I can sorta form the words as sounds... *sigh* You might want to talk to Christian Tismer; he's given Python talks in Korea before, and may have some native-Korean contacts that can double check your material. His email address is: tismer@tismer.com From kalle@gnupung.net Tue Aug 7 03:41:56 2001 From: kalle@gnupung.net (Kalle Svensson) Date: Tue, 7 Aug 2001 04:41:56 +0200 Subject: [Tutor] Dictionaries supplying arguments to functions In-Reply-To: <20010807122113.C10406@it.uts.edu.au>; from nott@it.uts.edu.au on Tue, Aug 07, 2001 at 12:21:13PM +1000 References: <20010807122113.C10406@it.uts.edu.au> Message-ID: <20010807044156.D2167@gandalf> Sez Tom Nott: > Is it possible to have a dictionary supply the arguments to a function? > > I'm after something like: > > def fn(p1, p2, p3): > print p1 > print p2 > print p3 > > d = {'p1':'How ', 'p2':'are ', 'p3':'you'} > > callWithDict(fn, d) Yes. In all (modern, at least) Python versions: apply(fn, (), d) In Python 2.0 and later: fn(**d) does the same thing. apply() still works, but looks a little ugly. More about apply(): http://www.python.org/doc/current/lib/built-in-funcs.html Peace, Kalle -- Free Dmitry Sklyarov! - http://www.freesklyarov.org/ From dyoo@hkn.eecs.berkeley.edu Tue Aug 7 03:48:29 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 6 Aug 2001 19:48:29 -0700 (PDT) Subject: [Tutor] Dictionaries supplying arguments to functions In-Reply-To: <20010807122113.C10406@it.uts.edu.au> Message-ID: On Tue, 7 Aug 2001, Tom Nott wrote: > Is it possible to have a dictionary supply the arguments to a function? > > I'm after something like: > > def fn(p1, p2, p3): > print p1 > print p2 > print p3 > > d = {'p1':'How ', 'p2':'are ', 'p3':'you'} > > callWithDict(fn, d) Yes, very much so: ### >>> def fn(p1, p2, p3): ... print p1 ... print p2 ... print p3 ... >>> d = { 'p1' : 'Pie 1', ... 'p2' : 'Pentium 2', ... 'p3' : 'Phosphorus 3' } >>> fn(**d) Pie 1 Pentium 2 Phosphorus 3 ### Put two stars at the front of the dictionary you're feeding in the function, and it'll match up properly with the arguments. The reason they use double stars is because '**' is also used to get keyword arguments as a dictionary: ### >>> def getInsertQuery(table, **key_values): ... query = "insert into " + table ... mykeys = key_values.keys() ... query += " (%s) " % ', '.join(mykeys) ... values = [ key_values[key] for key in mykeys ] ... query += " values (%s) " % ', '.join(values) ... return query ... >>> getInsertQuery('messages', subject='testing', ... message='this is a test', ... author='dyoo') 'insert into messages (subject, author, message) values (testing, dyoo, this is a test) ' ### You might find out more about this here: http://python.org/doc/current/tut/node6.html#SECTION006720000000000000000 although, admittedly, I'm a little forgetful about where I actually learned about this feature... *grin* Does anyone know where this is actually documented? Hope this helps! From kalle@gnupung.net Tue Aug 7 04:14:22 2001 From: kalle@gnupung.net (Kalle Svensson) Date: Tue, 7 Aug 2001 05:14:22 +0200 Subject: [Tutor] Dictionaries supplying arguments to functions In-Reply-To: ; from dyoo@hkn.eecs.berkeley.edu on Mon, Aug 06, 2001 at 07:48:29PM -0700 References: <20010807122113.C10406@it.uts.edu.au> Message-ID: <20010807051422.A6412@gandalf> Sez Danny Yoo: > On Tue, 7 Aug 2001, Tom Nott wrote: [stuff about double stars and function definitions/calls] > You might find out more about this here: > > http://python.org/doc/current/tut/node6.html#SECTION006720000000000000000 > > although, admittedly, I'm a little forgetful about where I actually > learned about this feature... *grin* Does anyone know where this is > actually documented? Well, that depends on what you mean by documented... func(**d): http://python.org/doc/current/ref/calls.html def func(**kw): http://python.org/doc/current/ref/function.html This isn't very readable, though, being a part of the language reference. I think I read about func(**d) for the first time in Andrew M. Kuchling's "What's new in Python 2.0" (http://www.amk.ca/python/2.0/). Peace, Kalle -- Free Dmitry Sklyarov! - http://www.freesklyarov.org/ From deirdre@deirdre.net Tue Aug 7 07:54:52 2001 From: deirdre@deirdre.net (Deirdre Saoirse Moen) Date: Mon, 6 Aug 2001 23:54:52 -0700 Subject: [Tutor] Welcome Danny Message-ID: Danny You, a frequent poster, is now one of the "official" tutors as Wes and I have had spotty time to devote to the list. I'm sure y'all will agree he's been extremely helpful over the months. -- _Deirdre Stash-o-Matic: http://fuzzyorange.com http://deirdre.net "Cannot run out of time.... Is infinite time. You... are finite.... Zathrus... is finite. This... is wrong tool!" -- Zathrus From rob@jam.rr.com Tue Aug 7 13:38:57 2001 From: rob@jam.rr.com (Rob Andrews) Date: Tue, 7 Aug 2001 07:38:57 -0500 Subject: [Tutor] Welcome Danny In-Reply-To: Message-ID: Cheers! Rob Your one-stop shop for newbie source code! Useless Python: http://www.lowerstandard.com/python/ # -----Original Message----- # From: tutor-admin@python.org # [mailto:tutor-admin@python.org]On Behalf Of # Deirdre Saoirse Moen # Sent: Tuesday, August 07, 2001 1:55 AM # To: tutor@python.org # Subject: [Tutor] Welcome Danny # # # Danny You, a frequent poster, is now one of the "official" tutors as # Wes and I have had spotty time to devote to the list. I'm sure y'all # will agree he's been extremely helpful over the months. # -- # _Deirdre Stash-o-Matic: http://fuzzyorange.com http://deirdre.net # "Cannot run out of time.... Is infinite time. You... are finite.... # Zathrus... is finite. This... is wrong tool!" -- Zathrus # # _______________________________________________ # Tutor maillist - Tutor@python.org # http://mail.python.org/mailman/listinfo/tutor From ppathiyi@cisco.com Tue Aug 7 13:44:26 2001 From: ppathiyi@cisco.com (Praveen Pathiyil) Date: Tue, 7 Aug 2001 18:14:26 +0530 Subject: [Tutor] Welcome Danny References: Message-ID: <02b101c11f3e$b192b5e0$37ef87c0@ppathiyipc> Three Cheers for Danny ... ----- Original Message ----- From: "Deirdre Saoirse Moen" To: Sent: Tuesday, August 07, 2001 12:24 PM Subject: [Tutor] Welcome Danny > Danny You, a frequent poster, is now one of the "official" tutors as > Wes and I have had spotty time to devote to the list. I'm sure y'all > will agree he's been extremely helpful over the months. > -- > _Deirdre Stash-o-Matic: http://fuzzyorange.com http://deirdre.net > "Cannot run out of time.... Is infinite time. You... are finite.... > Zathrus... is finite. This... is wrong tool!" -- Zathrus > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From aschmidt@nv.cc.va.us Tue Aug 7 13:43:31 2001 From: aschmidt@nv.cc.va.us (Schmidt, Allen J.) Date: Tue, 7 Aug 2001 08:43:31 -0400 Subject: [Tutor] transpose problems in PIL Message-ID: <5CDFEBB60E7FD311B9E30000F6D6090608CB8C27@novamail2.nv.cc.va.us> Forwarded from a friend.... I'm trying to extract the IPTC/NAA caption information from JPEGs stored by Photoshop. I've noticed the IPTC plugin for the Python Imaging Library, but can't figure out how it works and can't seem to find any helpful docs on it. Two questions: Anyone know how to do this, and is it best once I've figure out that part of the puzzle to access it through an external method? Or is Zope gonna strip out the information when the image is made into an image object? Thanks! If anyone has any info on this topic, we would appreciate anything you could offer. Allen From Charlie Clark Tue Aug 7 13:50:36 2001 From: Charlie Clark (Charlie Clark) Date: Tue, 07 Aug 2001 14:50:36 +0200 Subject: [Tutor] Welcome Danny References: Message-ID: <00038af012797b00_mailit@mail.isis.de> >Danny You, a frequent poster, is now one of the "official" tutors as >Wes and I have had spotty time to devote to the list. I'm sure y'all >will agree he's been extremely helpful over the months. congratulations Danny! Charlie From lumbricus@gmx.net Tue Aug 7 14:30:30 2001 From: lumbricus@gmx.net (lumbricus@gmx.net) Date: Tue, 7 Aug 2001 15:30:30 +0200 Subject: [Tutor] Welcome Danny In-Reply-To: <00038af012797b00_mailit@mail.isis.de>; from charlie@begeistert.org on Tue, Aug 07, 2001 at 02:50:36PM +0200 References: <00038af012797b00_mailit@mail.isis.de> Message-ID: <20010807153030.A6341@Laplace.localdomain> On Tue, Aug 07, 2001 at 02:50:36PM +0200, Charlie Clark wrote: > >Danny You, a frequent poster, is now one of the "official" tutors as > >Wes and I have had spotty time to devote to the list. I'm sure y'all > >will agree he's been extremely helpful over the months. > congratulations Danny! dito and good luck and may the source be with you > > Charlie > Greetings J"o! :-) -- God created a few perfect heads. The rest he covered with hair. From pobrien@orbtech.com Tue Aug 7 14:43:48 2001 From: pobrien@orbtech.com (Patrick K. O'Brien) Date: Tue, 7 Aug 2001 08:43:48 -0500 Subject: [Tutor] Announce: PythonCard just posted a new release Message-ID: I know I haven't been here in a while, and that is because I've been heavily involved in two projects. One is PythonCard, which is a software construction kit (in the spirit of Apple's HyperCard) written in Python. A new version has just been released and development is progressing steadily. You might want to take a look if you have an interest in building GUI apps in Python with the same ease as HyperCard. The other project is PyCrust. It seems that every so often people on the tutor and/or edu lists talk about developing a custom python shell to do tutorials and such. Well, one of the neat things about PythonCard is its built-in shell window, which allows you to manipulate all parts of your application at runtime, with all the syntax coloring, call tips and auto-complete features that you would expect from a python shell. PythonCard uses a plug-in python shell, called PyCrust, which is available for use in any python project. You can learn more about PyCrust at http://sourceforge.net/projects/pycrust/. You can learn more about PythonCard at http://sourceforge.net/projects/pythoncard/ and the details of its latest release are included below. Both projects have mailing lists that you can join and we would love to have more participants. Consider this an invitation. --- Patrick K. O'Brien Orbtech "I am, therefore I think." -----Original Message----- From: Kevin Altis [mailto:altis@semi-retired.com] Sent: Monday, August 06, 2001 9:48 PM To: Pythoncard Subject: [pythoncard] Announce: PythonCardPrototype release 0.3 http://sourceforge.net/project/showfiles.php?group_id=19015 Changes since 0.2.1 added changelog.txt and readme.txt files menubar is now optional if a 'menubar' key is not found in a Stack's resource file then a menubar won't be created. log.py documented proof.py updated to work with log.py changes MessageEvent was removed from proof.py since message sending bewteen widgets is currently disabled The working directory is changed to the directory of the main resource file such as minimal.rsrc.py when PythonCard starts up to avoid problems with filenames in the .rsrc.py files and any data files used by the application. Property Editor and Shell windows can be overlapped by the main app window Due to a bug, the Message Watcher must still remain on top added getCurrentBackground to PythonCardApp class PythonCard now includes PyCrust (-s on command-line) interactivePrompt renamed to shell, all references changed PyCrustFrame class moved to debug.py along with test for PyCrust import PyCrust shell is version 0.3 PythonCard turned into PythonCardPrototype package All samples changed to use the new package naming All samples can now be run "standalone" so any _standalone.py files in the samples have been removed. __version__.py contains the current release number New cvs tree on SourceForge, the old proto tree is no longer used PythonCard.py renamed to loader.py and loader.py overhauled added deleteWidget method added find, deprecated findByName added turtle graphics sample added a Property Editor (-p on command-line) due to time constraints, the Property Editor is only a property viewer in this release. You can use the set methods for widgets to change values inside the shell if you need to. added gainFocus and loseFocus messages to all widgets added StaticLine widget ComponentSpec and AttributeSpec classes added to enhance parsing of spec.py ka --- Kevin Altis altis@semi-retired.com ------------------------ Yahoo! Groups Sponsor ---------------------~--> Small business owners... Tell us what you think! http://us.click.yahoo.com/vO1FAB/txzCAA/ySSFAA/saFolB/TM ---------------------------------------------------------------------~-> To unsubscribe from this group, send an email to: pythoncard-unsubscribe@yahoogroups.com Your use of Yahoo! Groups is subject to http://docs.yahoo.com/info/terms/ From Charlie Clark Tue Aug 7 16:45:03 2001 From: Charlie Clark (Charlie Clark) Date: Tue, 07 Aug 2001 17:45:03 +0200 Subject: [Tutor] Help with Parsing HTML files [html/OOP] References: Message-ID: <00038af2825872bf_mailit@mail.isis.de> >class EmphasisGlancer(htmllib.HTMLParser): > def __init__(self): > htmllib.HTMLParser.__init__(self, > formatter.NullFormatter()) > self.in_bold = 0 > self.in_underline = 0 > > def start_b(self, attrs): > print "Hey, I see a bold tag!" > self.in_bold = 1 > > def end_b(self): > self.in_bold = 0 > > def start_u(self, attrs): > print "Hey, I see some underscored text!" > self.in_underline = 1 > > def end_u(self): > self.in_underline = 0 > > > def start_blink(self, attrs): > print "Hey, this is some heinously blinking test... *grrrr*" > > > def handle_data(self, data): > if self.in_bold: > print "BOLD:", data > elif self.in_underline: > print "UNDERLINE:", data >### > > >I have not tested this code yet, but hopefully I haven't made too many >typos. If you play around with it, you might find that sgmllib/htmllib >isn't as bad as you think. Getting there but my head is really hurting. I've been to the bookshop and picked up Fredrik Lundh's book and tried to make sense of that :-( I still don't understand when to use sgmllib and when to use htmllib. I don't know whether they are good or bad at the moment. I made my own sample parser based on this little snippet. Start_"tag" can be set to do something, I guess do_"tag" can be used to use some logic on a tag whether the attributes are okay and handle_data does things with the data which is enclosed by the tag. How do I deal with nested structures where the data I'm interested in goes across several tags, some of which aren't properly closed in the source!? Here's some sample source: Runde Rennen –Zeit 13:59:49:(MEZ)Wettersonnig
    Herzlich willkommen


    .... I thought I might be able to use the flag setting method to indicate the start of the article which in this case in the font tag. class TagFinder(htmllib.HTMLParser): def __init__(self): htmllib.HTMLParser.__init__(self, formatter.NullFormatter()) #why is the necessary? what does it do? self.text = 0 slef.article = [] # collect an individual article self.articles = [] # list of all articles def start_font(self, attrs): self.text = 1 # the font tag isn't closed so we'll reset the flag when the table starts def start_table(self, args): self.text = 0 def handle_data(self, data): if self.text: self.article.append(string.lstrip(data)) # spaces cause problems elif self.article != []: self.articles.append(" ".join(self.article)) # add to the list collection self.article = [] content = # read in from a file, cleaned up and searched to the beginning c = TagFinder() c.feed(content) c.close() open("out.txt", "w").write("\n-----\n".join(c.articles)) # nearly obfuscated It seems to work but also to run slower than my previous version not that it really matters in this case. I would very much appreciate any comments on this as I am sure it could be improved! Charlie From kojo@hal-pc.org Tue Aug 7 16:43:48 2001 From: kojo@hal-pc.org (Kojo Idrissa) Date: Tue, 07 Aug 2001 10:43:48 -0500 Subject: [Tutor] Welcome Danny In-Reply-To: <02b101c11f3e$b192b5e0$37ef87c0@ppathiyipc> References: Message-ID: <5.1.0.14.0.20010807104221.00ae2e18@Pop3.norton.antivirus> Hip-Hip, Horray!!! Hip-Hip, Horray!!! Hip-Hip, Horray!!! There, all three. :-) Congrats Danny. So, when does the free buffet get started? At 06:14 PM 8/7/2001 +0530, Praveen Pathiyil wrote: >Three Cheers for Danny ... **************************** Kojo Idrissa kojo@hal-pc.org http://www.hal-pc.org/~kojo/ **************************** From shalehperry@home.com Tue Aug 7 17:00:09 2001 From: shalehperry@home.com (Sean 'Shaleh' Perry) Date: Tue, 07 Aug 2001 09:00:09 -0700 (PDT) Subject: [Tutor] Using os.path.walk In-Reply-To: <20010806114851.24748.qmail@web12107.mail.yahoo.com> Message-ID: My own hacking: >>> def diraction(arg, dirname, names): ... global count ... for file in names: ... if os.path.isfile(file): ... print file ... count = count + 1 >>> count = 0 >>> diraction(1, '.', ['foo', 'file_that_exists']) file_that_exists >>> count 1 >>> os.path.walk('.', diraction, None) lots of files >>> count 90 >>> Hope that helps some. The 'arg' is simply for convenience, you often want one more piece of info in the diraction function. If you do not use it, feel free to pass 'None' (equiv of NULL). count has to be global to be useful. The only reason to assign files = names (which does not do what you think) is if you were changing the names list. However, assigning foo = list just makes foo another name for list, it does not actually copy. For that you need foo = list[:]. Observe: >>> l = ['foo', 'bar', 'baz'] >>> nl = l >>> l[0] 'foo' >>> nl[0] 'foo' >>> nl[0] = 'wuzzy' >>> l[0] 'wuzzy' >>> nl = [] >>> nl = l[:] >>> nl[0] 'wuzzy' >>> l[0] = 'hmmm' >>> nl[0] 'wuzzy' From tescoil@irtc.net Tue Aug 7 17:38:23 2001 From: tescoil@irtc.net (Tesla Coil) Date: Tue, 07 Aug 2001 11:38:23 -0500 Subject: [Tutor] Welcome Danny References: Message-ID: <3B70197F.F5A99988@irtc.net> On 6 August 2001, Deirdre Saoirse Moen wrote: > Danny You, a frequent poster, is now one of the > "official" tutors as Wes and I have had spotty > time to devote to the list. I'm sure y'all will > agree he's been extremely helpful over the months. He gets a free Python T-shirt or coffee cup for this, I would hope... From israel@lith.com Tue Aug 7 17:43:37 2001 From: israel@lith.com (Israel Evans) Date: Tue, 7 Aug 2001 09:43:37 -0700 Subject: [Tutor] Welcome Danny Message-ID: Three and three thirds cheers for all of our illustrious tutors!! -----Original Message----- From: Praveen Pathiyil [mailto:ppathiyi@cisco.com] Sent: Tuesday, August 07, 2001 5:44 AM To: tutor@python.org Subject: Re: [Tutor] Welcome Danny Three Cheers for Danny ... ----- Original Message ----- From: "Deirdre Saoirse Moen" To: Sent: Tuesday, August 07, 2001 12:24 PM Subject: [Tutor] Welcome Danny > Danny You, a frequent poster, is now one of the "official" tutors as > Wes and I have had spotty time to devote to the list. I'm sure y'all > will agree he's been extremely helpful over the months. > -- > _Deirdre Stash-o-Matic: http://fuzzyorange.com http://deirdre.net > "Cannot run out of time.... Is infinite time. You... are finite.... > Zathrus... is finite. This... is wrong tool!" -- Zathrus > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From rob@jam.rr.com Tue Aug 7 17:44:55 2001 From: rob@jam.rr.com (Rob Andrews) Date: Tue, 7 Aug 2001 11:44:55 -0500 Subject: free T-shirts RE: [Tutor] Welcome Danny In-Reply-To: <3B70197F.F5A99988@irtc.net> Message-ID: Now that's a great idea. I think the list parents and tutors all deserve some nice kick-backs. Maybe we can come up with a Python Tutor logo (GIMP vs. Photoshop contest, anyone?) and have some branded merchandise made. *I helped a newbie, and all I got was this lousy T-shirt!" Rob Your one-stop shop for newbie source code! Useless Python: http://www.lowerstandard.com/python/ # -----Original Message----- # From: tutor-admin@python.org # [mailto:tutor-admin@python.org]On Behalf Of # Tesla Coil # Sent: Tuesday, August 07, 2001 11:38 AM # To: Deirdre Saoirse Moen # Cc: tutor@python.org; Danny Yoo # Subject: Re: [Tutor] Welcome Danny # # # On 6 August 2001, Deirdre Saoirse Moen wrote: # > Danny You, a frequent poster, is now one of the # > "official" tutors as Wes and I have had spotty # > time to devote to the list. I'm sure y'all will # > agree he's been extremely helpful over the months. # # He gets a free Python T-shirt or coffee cup for this, # I would hope... # # # _______________________________________________ # Tutor maillist - Tutor@python.org # http://mail.python.org/mailman/listinfo/tutor From rwaters@csmbid.com Tue Aug 7 20:17:34 2001 From: rwaters@csmbid.com (Randy Waters) Date: Tue, 07 Aug 2001 14:17:34 -0500 Subject: [Tutor] Using os.path.walk across platforms Message-ID: <3B703ECE.4B348976@csmbid.com> Hello. I have an interesting little challenge. I need to copy files from an NT server to multiple Linux servers. The Python script needs to execute on a UNIX server. I am using ftplib and os.path. My problem is that the standard 'LIST' in (ftplib) retrlines needs to be captured to a list so that I can check to see if a entry is a directory or not. If I were executing only on UNIX/Linux I could use os.path.walk without a problem, but I am trying to "walk" down an NT path from UNIX. This script: #!/usr/bin/python import os, string from ftplib import FTP def TheList(arg, dirname, names): for name in names: print os.path.join(dirname, name) if os.path.isdir(name): print name + ' is a directory...' def GetFiles(): session = FTP() session.connect('myserver.domain.com', port=8282) session.login() os.path.walk(session.retrlines('LIST'), TheList, None) session.close() return GetFiles() ------------------- Returns this type of information: dr-xr-xr-x 1 owner group 0 Dec 7 2000 Co pack projects dr-xr-xr-x 1 owner group 0 May 29 14:52 COA dr-xr-xr-x 1 owner group 0 Aug 2 8:45 HANDLING -r-xr-xr-x 1 owner group 12800 Nov 4 1996 INFRZPR2.DOC ------------------- If I could test the 1st position for 'd' then I would know that I have to chdir and read down the tree. Using os.path.isdir does not work probably because I am running my script on a UNIX server logged into an NT server. If anyone has any ideas I would appreciate it. Thank you and what a great language! From lumbricus@gmx.net Tue Aug 7 20:41:15 2001 From: lumbricus@gmx.net (lumbricus@gmx.net) Date: Tue, 7 Aug 2001 21:41:15 +0200 Subject: [Tutor] Using os.path.walk across platforms In-Reply-To: <3B703ECE.4B348976@csmbid.com>; from rwaters@csmbid.com on Tue, Aug 07, 2001 at 02:17:34PM -0500 References: <3B703ECE.4B348976@csmbid.com> Message-ID: <20010807214115.A8384@Laplace.localdomain> On Tue, Aug 07, 2001 at 02:17:34PM -0500, Randy Waters wrote: > Hello. I have an interesting little challenge. I need to copy files from > an NT server to multiple Linux servers. The Python script needs to > execute on a UNIX server. I am using ftplib and os.path. > > My problem is that the standard 'LIST' in (ftplib) retrlines needs to be > captured to a list so that I can check to see if a entry is a directory > or not. If I were executing only on UNIX/Linux I could use os.path.walk > without a problem, but I am trying to "walk" down an NT path from UNIX. > > This script: > > #!/usr/bin/python > > import os, string > >from ftplib import FTP > > def TheList(arg, dirname, names): > for name in names: > print os.path.join(dirname, name) > if os.path.isdir(name): > print name + ' is a directory...' > > def GetFiles(): > session = FTP() > session.connect('myserver.domain.com', port=8282) > session.login() > os.path.walk(session.retrlines('LIST'), TheList, None) > session.close() > return > > GetFiles() > ------------------- > Returns this type of information: > > dr-xr-xr-x 1 owner group 0 Dec 7 2000 Co pack > projects > dr-xr-xr-x 1 owner group 0 May 29 14:52 COA > dr-xr-xr-x 1 owner group 0 Aug 2 8:45 HANDLING > -r-xr-xr-x 1 owner group 12800 Nov 4 1996 INFRZPR2.DOC > > ------------------- > > If I could test the 1st position for 'd' then I would know that I have > to chdir and read down the tree. Using os.path.isdir does not work > probably because I am running my script on a UNIX server logged into an ^^^^^^^^ Have you tried it? I can't right now, but i don't see a problem (or am i missing something?) > NT server. > > If anyone has any ideas I would appreciate it. Thank you and what a > great language! > Greetings J"o! :-) -- To be sure of hitting the target, shoot first and, whatever you hit, call it the target. From dyoo@hkn.eecs.berkeley.edu Tue Aug 7 23:50:07 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 7 Aug 2001 15:50:07 -0700 (PDT) Subject: [Tutor] Welcome Danny In-Reply-To: Message-ID: On Tue, 7 Aug 2001, Israel Evans wrote: > Three and three thirds cheers for all of our illustrious tutors!! Hear, hear! I wouldn't be here if it weren't for everyone on the list. Thank you again for the support. From kauphlyn@speakeasy.org Wed Aug 8 03:04:59 2001 From: kauphlyn@speakeasy.org (Daniel Coughlin) Date: Tue, 7 Aug 2001 19:04:59 -0700 (PDT) Subject: [Tutor] Using os.path.walk across platforms (fwd) Message-ID: Hello, I wrote a function that might do the trick for you. I am not familiar enough with the os.path.walk function to know exactly what you are wanting, but I added a new function and rewrote a couple of lines in your script, which returns a list of all the directories in the present working directory. This will work for a script running on unix connecting to an NT filesystem (at least it worked on mine ;-) . It did not work going from NT to Unix. You might need to tweak the regular expression to get it exact. I am sure this can be improved upon however. #!/usr/bin/python import os, string, re from ftplib import FTP def FilterDirectories(listing): templist = [] dirlist = [] for item in listing: if item[0] == 'd': templist.append(re.split(':',item)) for item in templist: dirlist.append(string.strip(re.sub('\d*','',item[1]))) for item in dirlist: print item + ' is a directory..' return dirlist def GetFiles(): listings = [] #going to be a list of retrlines session = FTP() session.connect('myhost', port=21) session.login(user=USERNAME, passwd='*****') #os.path.walk(session.retrlines('LIST'),TheList,None) session.cwd('Music') # delete this line session.retrlines('LIST', listings.append) FilterDirectories(listings) session.close() GetFiles() ----------------------------------------------- The output on my system is : Bell and Sebastian is a directory.. cocteau twins is a directory.. rachels is a directory.. Radiohead is a directory.. Sly & The Family Stone is a directory.. Sonic Youth is a directory.. Talking Heads is a directory.. (These are all, in fact, directories!) Then I suppose you could use the dirlist to loop through each of the directories using chdir. Hope this helps. Daniel PS Hooray for Danny Yoo!!! > >---------- Forwarded message ---------- >Date: Tue, 07 Aug 2001 14:17:34 -0500 >From: Randy Waters >To: "tutor@python.org" >Subject: [Tutor] Using os.path.walk across platforms > >Hello. I have an interesting little challenge. I need to copy files from >an NT server to multiple Linux servers. The Python script needs to >execute on a UNIX server. I am using ftplib and os.path. > >My problem is that the standard 'LIST' in (ftplib) retrlines needs to be >captured to a list so that I can check to see if a entry is a directory >or not. If I were executing only on UNIX/Linux I could use os.path.walk >without a problem, but I am trying to "walk" down an NT path from UNIX. > >This script: > >#!/usr/bin/python > >import os, string >from ftplib import FTP > >def TheList(arg, dirname, names): > for name in names: > print os.path.join(dirname, name) > if os.path.isdir(name): > print name + ' is a directory...' > >def GetFiles(): > session = FTP() > session.connect('myserver.domain.com', port=8282) > session.login() > os.path.walk(session.retrlines('LIST'), TheList, None) > session.close() > return > >GetFiles() >------------------- >Returns this type of information: > >dr-xr-xr-x 1 owner group 0 Dec 7 2000 Co pack >projects >dr-xr-xr-x 1 owner group 0 May 29 14:52 COA >dr-xr-xr-x 1 owner group 0 Aug 2 8:45 HANDLING >-r-xr-xr-x 1 owner group 12800 Nov 4 1996 INFRZPR2.DOC > >------------------- > >If I could test the 1st position for 'd' then I would know that I have >to chdir and read down the tree. Using os.path.isdir does not work >probably because I am running my script on a UNIX server logged into an >NT server. > >If anyone has any ideas I would appreciate it. Thank you and what a >great language! > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > _________________________________________________________________ Get your FREE download of MSN Explorer at http://explorer.msn.com/intl.asp From wheelege@tsn.cc Wed Aug 8 04:21:36 2001 From: wheelege@tsn.cc (Glen Wheeler) Date: Wed, 8 Aug 2001 13:21:36 +1000 Subject: [Tutor] Welcome Danny References: Message-ID: <00f201c11fb9$478fc5e0$12a616ca@ACE> > Danny You, a frequent poster, is now one of the "official" tutors as > Wes and I have had spotty time to devote to the list. I'm sure y'all > will agree he's been extremely helpful over the months. Yeah yeah, go Danny go! This is very well deserved :) From seand88@hotmail.com Wed Aug 8 04:29:22 2001 From: seand88@hotmail.com (sean dowie) Date: Wed, 8 Aug 2001 04:29:22 +0100 Subject: [Tutor] string to list of characters Message-ID: I want to turn a word into a list of the letters, eg "dog" becomes ['d', 'o', 'g']. Is there a simple way to use split() or something to do this, or do I have to loop through each letter of the string? Thanks in advance Sean From ak@silmarill.org Wed Aug 8 04:36:20 2001 From: ak@silmarill.org (Andrei Kulakov) Date: Tue, 07 Aug 2001 23:36:20 -0400 Subject: [Tutor] string to list of characters In-Reply-To: <"from seand88"@hotmail.com> References: Message-ID: <20010807233619.A1857@sill.silmarill.org> On Wed, Aug 08, 2001 at 04:29:22AM +0100, sean dowie wrote: > I want to turn a word into a list of the letters, eg "dog" becomes ['d', > 'o', 'g']. > Is there a simple way to use split() or something to do this, or do I have > to loop through each letter of the string? > > Thanks in advance > Sean >>> word = "dog" >>> l = [letter for letter in word] >>> l ['d', 'o', 'g'] >>> That's list comprehension.. It's described in detail in the tutorial. It's kind of neat. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: http://silmarill.org/cymbaline From wheelege@tsn.cc Wed Aug 8 04:35:57 2001 From: wheelege@tsn.cc (Glen Wheeler) Date: Wed, 8 Aug 2001 13:35:57 +1000 Subject: [Tutor] Dictionaries supplying arguments to functions References: Message-ID: <01ea01c11fbb$3cfacf60$12a616ca@ACE> > <...> > > although, admittedly, I'm a little forgetful about where I actually > learned about this feature... *grin* Does anyone know where this is > actually documented? > Sure, if I remember correctly it's in the calls section of the python documentation. Let me have a search.... Yup! Still going strong, here is the link... http://www.python.org/doc/current/ref/calls.html Ah the language reference :) Glen. From rick@niof.net Wed Aug 8 04:49:26 2001 From: rick@niof.net (Rick Pasotto) Date: Tue, 7 Aug 2001 23:49:26 -0400 Subject: [Tutor] string to list of characters In-Reply-To: Message-ID: <20010807234926.D27164@tc.niof.net> On Wed, Aug 08, 2001 at 04:29:22AM +0100, sean dowie wrote: > I want to turn a word into a list of the letters, eg "dog" becomes > ['d', 'o', 'g']. Is there a simple way to use split() or something to > do this, or do I have to loop through each letter of the string? >>> w = 'dog' >>> l = list(w) >>> print w dog >>> print l ['d', 'o', 'g'] -- We must cease believing in anything in this world, in facts, in justice, in universal consent, in human language; or else we must admit that these two words, "property" and "plunder", express opposite, irreconcilable ideas that can no more be identified than yes and no, light and dark, good and evil, harmony and discord. Taken literally, the famous formula, property is theft, is therefore absurdity raised to the nth degree. It would be no less outlandish to say that theft is property; that what is legal is illegal; that what is, in not, etc. -- Frйdйric Bastiat (1801-1850) Rick Pasotto rickp@telocity.com http://www.niof.net From tescoil@irtc.net Wed Aug 8 06:17:55 2001 From: tescoil@irtc.net (Tesla Coil) Date: Wed, 08 Aug 2001 00:17:55 -0500 Subject: [Tutor] Re: using IDLE and changing variables References: <3B6EC76D.10115.16DEA8F@localhost> Message-ID: <3B70CB83.1582168D@irtc.net> On 6 August 2001, Jesse W wrote: > Whenever I see this thread again (and I have seen > it often :-) ), I think to myself: "This does not > look to hard to hack up, why don't I do it?" Well, > finally, I have. Here it is: Hm. That just makes it all the more puzzling why it hasn't been built into IDLE already, and why no one seems to be taking up the task: http://idlefork.sourceforge.net/tasks.php From dyoo@hkn.eecs.berkeley.edu Wed Aug 8 06:26:15 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 7 Aug 2001 22:26:15 -0700 (PDT) Subject: [Tutor] string to list of characters In-Reply-To: Message-ID: On Wed, 8 Aug 2001, sean dowie wrote: > I want to turn a word into a list of the letters, eg "dog" becomes > ['d', 'o', 'g']. Is there a simple way to use split() or something to > do this, or do I have to loop through each letter of the string? By the way, you can treat a string as a "sequence" of characters: ### >>> kujo = 'dog' >>> kujo[0] 'd' >>> for letter in kujo: ... print letter ... d o g ### and many of the operations that work with lists can work equally well with strings. So, depending on the task, you might not need to turn "dog" into ['d', 'o', 'g']. From ppathiyi@cisco.com Wed Aug 8 06:50:03 2001 From: ppathiyi@cisco.com (Praveen Pathiyil) Date: Wed, 8 Aug 2001 11:20:03 +0530 Subject: [Tutor] XML Parser Message-ID: <03c801c11fcd$f8d3a060$37ef87c0@ppathiyipc> This is a multi-part message in MIME format. ------=_NextPart_000_03C5_01C11FFC.11E255F0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi All, I am trying out some basic stuff on XML with Python. But I am = unable to get a parser instance on my system ( I have cut and pasted = some code which i tried out for this.). Also the "drivers" modules under = xml.sax and "pyexpat" is not installed. (Since i am working on the = server of my company, I can't install these packages myself). How do I proceed to get a parser instance ? Thanks in Advance, Praveen. ******************************************* Python 2.1 (#2, Jun 20 2001, 11:49:49)=20 [GCC 2.9-cisco-98r1] on sunos5 Type "copyright", "credits" or "license" for more information. >>>=20 >>> from xml.sax import xmlreader >>>=20 >>> parser =3D xmlreader.XMLReader() >>>=20 >>> parser.parse("comic_books") Traceback (most recent call last): File "", line 1, in ? File = "/sw/packages/python/2.1/sparc-sun-solaris2.5.1/lib/python2.1/xml/sax/xml= reader.py", line 32, in parse raise NotImplementedError("This method must be implemented!") NotImplementedError: This method must be implemented! ******************************************* >>> from xml.sax.saxutils import xmlreader=20 >>>=20 >>> parser =3D xmlreader.XMLReader() >>>=20 >>> parser.parse("comic_books") Traceback (most recent call last): File "", line 1, in ? File = "/sw/packages/python/2.1/sparc-sun-solaris2.5.1/lib/python2.1/xml/sax/xml= reader.py", line 32, in parse raise NotImplementedError("This method must be implemented!") NotImplementedError: This method must be implemented! ******************************************* ------=_NextPart_000_03C5_01C11FFC.11E255F0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
    Hi All,
     
            I am trying out some basic = stuff on=20 XML with Python. But I am unable to get a parser instance on my system ( = I have=20 cut and pasted some code which i tried out for this.). Also the = "drivers"=20 modules under xml.sax and "pyexpat" is not installed. (Since i am = working on the=20 server of my company, I can't install these packages myself).
            How do I proceed to get = a parser=20 instance ?
     
     
    Thanks in Advance,
    Praveen.
     
    *******************************************
    Python 2.1 (#2, Jun 20 2001, 11:49:49)
    [GCC 2.9-cisco-98r1] on=20 sunos5
    Type "copyright", "credits" or "license" for more=20 information.
    >>>
    >>> from xml.sax import=20 xmlreader
    >>>
    >>> parser =3D=20 xmlreader.XMLReader()
    >>>
    >>>=20 parser.parse("comic_books")
    Traceback (most recent call = last):
      File=20 "<stdin>", line 1, in ?
      File=20 "/sw/packages/python/2.1/sparc-sun-solaris2.5.1/lib/python2.1/xml/sax/xml= reader.py",=20 line 32, in parse
        raise NotImplementedError("This = method=20 must be implemented!")
    NotImplementedError: This method must be=20 implemented!
    *******************************************
     
    >>> from xml.sax.saxutils import xmlreader =
    >>>=20
    >>> parser =3D xmlreader.XMLReader()
    >>> =
    >>>=20 parser.parse("comic_books")
    Traceback (most recent call = last):
      File=20 "<stdin>", line 1, in ?
      File=20 "/sw/packages/python/2.1/sparc-sun-solaris2.5.1/lib/python2.1/xml/sax/xml= reader.py",=20 line 32, in parse
        raise NotImplementedError("This = method=20 must be implemented!")
    NotImplementedError: This method must be=20 implemented!
    *******************************************
    ------=_NextPart_000_03C5_01C11FFC.11E255F0-- From sheila@thinkspot.net Wed Aug 8 07:30:56 2001 From: sheila@thinkspot.net (Sheila King) Date: Tue, 07 Aug 2001 23:30:56 -0700 Subject: [Tutor] Using string.strip() Message-ID: <6DEEE30280@kserver.org> OK, I'm having another one of my dumb moments... As I read the docs for the strip() function for strings, it removes all leading and trailing characters that are defined in the string.whitespace constant, correct? And I even looked in there and SAW the '\n' character listed as a whitespace element. Now, why isn't this working? I have a file that contains something like this: N ;; no, cs student ;; N ;; no ;; S ;; case-sensitive ;; Y ;; yes ;; N ;; no ;; I read it in as a string, let's call it messagebody Then I do this: responses = messagebody.split(';;') Now, that will leave leading and trailing '\n' characters on the items in the responses list, so I try this: for item in responses: item = item.strip() But when I run it and print out the results, I still have leading and trailing '\n' characters on the individual list elements, as though the strip() function had no effect. I've tried a few other things, too, but none of them seem to be working, either. I thought that this was the whole purpose of the string.strip() command? -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From haiyang_yang@hotmail.com Wed Aug 8 07:36:04 2001 From: haiyang_yang@hotmail.com (Haiyang) Date: Wed, 8 Aug 2001 15:36:04 +0900 Subject: [Tutor] How to convert an integer into a binary? Message-ID: How can I convert an interger into a binary code in Python? Thank you. ##PythonPython## From dyoo@hkn.eecs.berkeley.edu Wed Aug 8 07:58:22 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 7 Aug 2001 23:58:22 -0700 (PDT) Subject: [Tutor] Using string.strip() In-Reply-To: <6DEEE30280@kserver.org> Message-ID: On Tue, 7 Aug 2001, Sheila King wrote: > I have a file that contains something like this: > > N > ;; > no, cs student > ;; > N > ;; > no > ;; > S > ;; > case-sensitive > ;; > Y > ;; > yes > ;; > N > ;; > no > ;; > > I read it in as a string, let's call it messagebody > > Then I do this: > > responses = messagebody.split(';;') > > Now, that will leave leading and trailing '\n' characters on the items > in the responses list, so I try this: > > for item in responses: > item = item.strip() Ah! Try this: ### for i in range(len(responses)): responses[i] = responses[i].strip() ### What you were doing before WAS doing some strip()ping, but unfortunately, the changes weren't being made to the list elements themselves. We can see this if we try this: ### for i in range(len(responses)): item = responses[i] item = item.strip() ## By this point, item really is strip()ped down, but we haven't ## modified responses[i]! print repr(item) print repr(responses[i]) ### Alternatively, try list comprehensions: ### responses = [item.strip() for item in responses] ### Hope this helps! From r.b.rigilink@chello.nl Wed Aug 8 08:11:19 2001 From: r.b.rigilink@chello.nl (Roeland Rengelink) Date: Wed, 08 Aug 2001 09:11:19 +0200 Subject: [Tutor] Using string.strip() References: <6DEEE30280@kserver.org> Message-ID: <3B70E617.208DDEA4@chello.nl> Hi Sheila, For me this works as advertised message = ''' N ;; no, cs student ;; N ;; no ;; S ;; case-sensitive ''' lines = message.split(";;") print lines lines = [line.strip() for line in lines] print lines gives: ['\nN\n', '\nno, cs student\n', '\nN\n', '\nno\n', '\nS\n', '\ncase-sensitive\n'] ['N', 'no, cs student', 'N', 'no', 'S', 'case-sensitive'] Maybe you can post a complete non-working example. Roeland Sheila King wrote: > > OK, I'm having another one of my dumb moments... > > As I read the docs for the strip() function for strings, it removes all > leading and trailing characters that are defined in the > string.whitespace constant, correct? And I even looked in there and SAW > the '\n' character listed as a whitespace element. > > Now, why isn't this working? > > I have a file that contains something like this: > > N > ;; > no, cs student > ;; > N > ;; > no > ;; > S > ;; > case-sensitive > ;; > Y > ;; > yes > ;; > N > ;; > no > ;; > > I read it in as a string, let's call it messagebody > Then I do this: > > responses = messagebody.split(';;') > > Now, that will leave leading and trailing '\n' characters on the items > in the responses list, so I try this: > > for item in responses: > item = item.strip() > > But when I run it and print out the results, I still have leading and > trailing '\n' characters on the individual list elements, as though the > strip() function had no effect. > > I've tried a few other things, too, but none of them seem to be working, > either. > > I thought that this was the whole purpose of the string.strip() command? > You're right, and it should work. Afraid the bug is in your code somewhere. > -- > Sheila King > http://www.thinkspot.net/sheila/ > http://www.k12groups.org/ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- r.b.rigilink@chello.nl "Half of what I say is nonsense. Unfortunately I don't know which half" From hnowak@cuci.nl Wed Aug 8 08:15:28 2001 From: hnowak@cuci.nl (Hans Nowak) Date: Wed, 8 Aug 2001 09:15:28 +0200 Subject: [Tutor] Using string.strip() Message-ID: <3B882585@twigger.nl> >===== Original Message From Sheila King ===== >OK, I'm having another one of my dumb moments... > >As I read the docs for the strip() function for strings, it removes all >leading and trailing characters that are defined in the >string.whitespace constant, correct? And I even looked in there and SAW >the '\n' character listed as a whitespace element. > >Now, why isn't this working? > >I have a file that contains something like this: > >N >;; >no, cs student >;; >N >;; >no >;; >S >;; >case-sensitive >;; >Y >;; >yes >;; >N >;; >no >;; > >I read it in as a string, let's call it messagebody >Then I do this: > >responses = messagebody.split(';;') > >Now, that will leave leading and trailing '\n' characters on the items >in the responses list, so I try this: > >for item in responses: > item = item.strip() Note that this for loop "as is" doesn't do anything to the responses list... it just strips an item, then discards it. Maybe this is the reason why it doesn't have the desired effect? >But when I run it and print out the results, I still have leading and >trailing '\n' characters on the individual list elements, as though the >strip() function had no effect. The following works for me: import string responses = messagebody.split(";;") responses = map(string.strip, responses) print responses HTH, --Hans Nowak From dyoo@hkn.eecs.berkeley.edu Wed Aug 8 08:13:39 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 8 Aug 2001 00:13:39 -0700 (PDT) Subject: [Tutor] How to convert an integer into a binary? In-Reply-To: Message-ID: On Wed, 8 Aug 2001, Haiyang wrote: > How can I convert an interger into a binary code in Python? Good question! By the way, going the other way around, from binary to an integer, is very easy: ### >>> int('111001', 2) 57 ### and might be useful later on. [This message does NOT have an "answer" attached to it, but it gives hints on one way to do the int->binary conversion.] One thing to notice is that if a number is odd, then its binary (base-2) representation will end with a '1'. Here are a few examples: ### >>> int('10101', 2) 21 # is odd >>> int('1010', 2) 10 # is even >>> int('101', 2) 5 # is odd >>> int('10', 2) 2 # is even >>> int('1', 2) 1 ### So if you have some number, then it's really easy to know about the last digit: just check to see if the number's even or odd. Knowing what the rest of the digits look like might still be a mystery though. The second thing that might be useful is to look again at the example above, but this time staring at two things: the binary number itself, and its integer equivalent: integer binary ------- ------ 21 10101 10 1010 5 101 2 10 1 1 Take a look at it, and see if you can spot a pattern. Here's another interpreter example with a peculiar pattern: ### >>> int('100110', 2) 38 >>> int('10011', 2) 19 >>> int('1001', 2) 9 >>> int('100', 2) 4 >>> int('10', 2) 2 >>> int('1', 2) 1 ### Forgive me: I'm being deliberately obscure here. *grin* If you're impatient, please feel free to ask again, and one of us can reply with some example code. Good luck to you! From sheila@thinkspot.net Wed Aug 8 08:14:19 2001 From: sheila@thinkspot.net (Sheila King) Date: Wed, 08 Aug 2001 00:14:19 -0700 Subject: [Tutor] Using string.strip() In-Reply-To: <3B882585@twigger.nl> References: <3B882585@twigger.nl> Message-ID: <95AF930883@kserver.org> On Wed, 8 Aug 2001 09:15:28 +0200, Hans Nowak wrote about RE: [Tutor] Using string.strip(): :Note that this for loop "as is" doesn't do anything to the responses list... :it just strips an item, then discards it. Maybe this is the reason why it :doesn't have the desired effect? Thanks to all who responded and pointed this out. As I said, I was having a dumb moment. I certainly should have known better. I especially liked the solution: responses = [item.strip() for item in responses] That is really the coolest. (I'm still not good at the list comprehensions thing.) On Wed, 08 Aug 2001 09:11:19 +0200, Roeland Rengelink wrote about Re: [Tutor] Using string.strip(): : :Maybe you can post a complete non-working example. Certainly, I can: Python 2.0 (#8, Oct 16 2000, 17:27:58) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. IDLE 0.6 -- press F1 for help >>> import string >>> messagebody = '''\ N ;; no, cs student ;; N ;; no ;; S ;; case-sensitive ;; Y ;; yes ;; N ;; no ;; ''' >>> responses = messagebody.split(';;') >>> print responses ['N\012', '\012no, cs student\012', '\012N\012', '\012no\012', '\012S\012', '\012case-sensitive\012', '\012Y\012', '\012yes\012', '\012N\012', '\012no\012', '\012'] >>> for item in responses: item = item.strip() >>> print responses ['N\012', '\012no, cs student\012', '\012N\012', '\012no\012', '\012S\012', '\012case-sensitive\012', '\012Y\012', '\012yes\012', '\012N\012', '\012no\012', '\012'] >>> Of course, as has been pointed out, I'm not doing anything to the list itself, only to the items and not reassigning them back to the list. Thanks to all for the swift responses. I will now go dent my head a bit... -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From larsga@garshol.priv.no Wed Aug 8 08:19:22 2001 From: larsga@garshol.priv.no (Lars Marius Garshol) Date: 08 Aug 2001 09:19:22 +0200 Subject: [Tutor] Re: [XML-SIG] XML Parser In-Reply-To: <03c801c11fcd$f8d3a060$37ef87c0@ppathiyipc> References: <03c801c11fcd$f8d3a060$37ef87c0@ppathiyipc> Message-ID: Hi Praveen, * Praveen Pathiyil | | I am trying out some basic stuff on XML with Python. But I am unable | to get a parser instance on my system ( I have cut and pasted some | code which i tried out for this.). Also the "drivers" modules under | xml.sax and "pyexpat" is not installed. If you have installed only Python itself, and not the PyXML package that may not be a problem. | How do I proceed to get a parser instance ? from xml.sax import make_parser parser = make_parser() This should do the trick. If pyexpat really isn't installed you'll get an exception. --Lars M. From dyoo@hkn.eecs.berkeley.edu Wed Aug 8 08:59:58 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 8 Aug 2001 00:59:58 -0700 (PDT) Subject: [Tutor] XML Parser In-Reply-To: <03c801c11fcd$f8d3a060$37ef87c0@ppathiyipc> Message-ID: On Wed, 8 Aug 2001, Praveen Pathiyil wrote: > I am trying out some basic stuff on XML with Python. But I am > unable to get a parser instance on my system ( I have cut and pasted > some code which i tried out for this.). Also the "drivers" modules > under xml.sax and "pyexpat" is not installed. (Since i am working on > the server of my company, I can't install these packages myself). > How do I proceed to get a parser instance ? > Hello! Let's take a look! [warning: this message is a little long] xml.sax.XMLReader is not meant to be used directly: it is "documentation", that is, it's an interface that says that anything that parses XML should do the sort of functions listed in: http://www.python.org/doc/current/lib/module-xml.sax.xmlreader.html To actually get at a real XML parser, try xml.sax.make_parser() instead: ### >>> parser = xml.sax.make_parser() ### Python will search our system for an approprate XML parser; on many systems, Python will use xml.parsers.expat. Try this first, and see if an error message pops up or not. If an error occurs, then you'll probably need to install Expat from: http://sourceforge.net/project/showfiles.php?group_id=10127&release_id=45670 If you do get that exception, email us, and we can try fixing it. Anyway, let's assume that you didn't run into an error. *grin* Once we have this real parser, then we can start calling XMLReader'ish methods on it, and be fairly sure that these methods will work: ### >>> parser.parse >>> parser.setContentHandler ### Now we need to tell the parser what sort of content we're interested in. If you look at the documentation on xmlreader, you'll see a bunch of setFoobar()-style functions: we'll need to do something with that. This will be easier if we have some sort of concrete example to work with. If we have some sort of document, like: ### mydoc = """

    Philip and Alex's Guide to Web Publishing

    This is a really neat book.

    The Practical SQL Handbook

    This is also a neat book.

    The Lord of the Rings

    Frodo Lives!

    """ ### it might be nice to write something that parses out all the

    headers in a document. What we'll do will look very similar to someone who has played with sgmllib: we'll be writing a subclass that can look at specific things, and that means writing a ContentHandler: (http://www.python.org/doc/current/lib/content-handler-objects.html) Here's one example of such a handler: ### class HeadlineHandler(ContentHandler): """We're just interested in

    headlines...""" def __init__(self): self.in_h1 = 0 def startElement(self, name, attrs): if name == 'h1': self.in_h1 = 1 def endElement(self, name): if name == 'h1': self.in_h1 = 0 def characters(self, content): if self.in_h1: print content ### Let's put all the pieces together, and see if this contraption can fly: ### import xml.sax from xml.sax.handler import ContentHandler from StringIO import StringIO class HeadlineHandler(ContentHandler): """We're just interested in

    headlines...""" def __init__(self): self.in_h1 = 0 def startElement(self, name, attrs): if name == 'h1': self.in_h1 = 1 def endElement(self, name): if name == 'h1': self.in_h1 = 0 def characters(self, content): if self.in_h1: print content if __name__ == '__main__': mydoc = """

    Philip and Alex's Guide to Web Publishing

    This is a really neat book.

    The Practical SQL Handbook

    This is also a neat book.

    The Lord of the Rings

    Frodo Lives!

    """ parser = xml.sax.make_parser() handler = HeadlineHandler() parser.setContentHandler(handler) parser.parse(StringIO(mydoc)) ## a little silliness since parser.parse needs a "file". Much ## easier would have been to say, more directly: ## ## handler = HeadlineHandler() ## xml.sax.parseString(mydoc, handler) ## ### ### dyoo@coffeetable:~$ python xmltest.py Philip and Alex's Guide to Web Publishing The Practical SQL Handbook The Lord of the Rings ### I have to stop now, or I won't be able to wake up tomorrow. *grin* I know this is insufficient, but I hope it's somewhat helpful. Good luck! From lumbricus@gmx.net Wed Aug 8 09:26:13 2001 From: lumbricus@gmx.net (lumbricus@gmx.net) Date: Wed, 8 Aug 2001 10:26:13 +0200 Subject: [Tutor] How to convert an integer into a binary? In-Reply-To: ; from haiyang_yang@hotmail.com on Wed, Aug 08, 2001 at 03:36:04PM +0900 References: Message-ID: <20010808102613.A9748@Laplace.localdomain> On Wed, Aug 08, 2001 at 03:36:04PM +0900, Haiyang wrote: > How can I convert an interger into a binary code in Python? Hello! This should become a faq ;-) import sys e=[] try: z=int(raw_input("Number?\n> ")) except: print "Need a number." sys.exit(1) while (z > 0): if (z & 1) == 1: e.append(1) else: e.append(0) z=z>>1 e.reverse() print e > > Thank you. HTH and Greetings J"o! :-) -- Life would be so much easier if we could just look at the source code. -- Dave Olson From ppathiyi@cisco.com Wed Aug 8 09:39:31 2001 From: ppathiyi@cisco.com (Praveen Pathiyil) Date: Wed, 8 Aug 2001 14:09:31 +0530 Subject: [Tutor] Re: [XML-SIG] XML Parser References: <03c801c11fcd$f8d3a060$37ef87c0@ppathiyipc> Message-ID: <05bd01c11fe5$a54be1b0$37ef87c0@ppathiyipc> When I try that, I get an exception. So I guess that it is because pyexpat is not installed ... Thanks, Praveen. >>> >>> from xml.sax import make_parser >>> >>> parser = make_parser() Traceback (most recent call last): File "", line 1, in ? File "/netapp/toolmaster/sw.sparc-sunos5/packages/python/2.1.1/sparc-sun-solaris2 .5.1/lib/python2.1/xml/sax/__init__.py", line 88, in make_parser xml.sax._exceptions.SAXReaderNotAvailable: No parsers found >>> ----- Original Message ----- From: "Lars Marius Garshol" To: "Praveen Pathiyil" Cc: ; Sent: Wednesday, August 08, 2001 12:49 PM Subject: [Tutor] Re: [XML-SIG] XML Parser > > Hi Praveen, > > * Praveen Pathiyil > | > | I am trying out some basic stuff on XML with Python. But I am unable > | to get a parser instance on my system ( I have cut and pasted some > | code which i tried out for this.). Also the "drivers" modules under > | xml.sax and "pyexpat" is not installed. > > If you have installed only Python itself, and not the PyXML package > that may not be a problem. > > | How do I proceed to get a parser instance ? > > from xml.sax import make_parser > parser = make_parser() > > This should do the trick. If pyexpat really isn't installed you'll get > an exception. > > --Lars M. > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From koen@behindthesofa.dhs.org Wed Aug 8 11:14:25 2001 From: koen@behindthesofa.dhs.org (Koen) Date: Wed, 08 Aug 2001 12:14:25 +0200 Subject: [Tutor] Using string.strip() References: <6DEEE30280@kserver.org> Message-ID: <3B711101.3010108@behindthesofa.dhs.org> Sheila King wrote: >OK, I'm having another one of my dumb moments... > > >Now, that will leave leading and trailing '\n' characters on the items >in the responses list, so I try this: > >for item in responses: > item = item.strip() > >But when I run it and print out the results, I still have leading and >trailing '\n' characters on the individual list elements, as though the >strip() function had no effect. > This is not a problem with the strip or split command. the problem is in the for loop. see the following examples: for item in responses: item = item.strip() for item in range(len(responses)): responses[item] = responses[item].strip() in the first example, second line, the variable /item /is in no way related with the list /responses/. in the second example, you change the elements /in the list/ itself. You should ALWAYS use this second method when altering contents of lists!! Cheers, Koen From alan.gauld@bt.com Wed Aug 8 11:23:38 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 8 Aug 2001 11:23:38 +0100 Subject: [Tutor] string to list of characters Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BE6B@mbtlipnt02.btlabs.bt.co.uk> > I want to turn a word into a list of the letters, eg "dog" > Is there a simple way to use split() or something to do this, Probably, but, > to loop through each letter of the string? >>> s = 'dog' >>> c = [] >>> for ch in s: c.append(ch) >>> c ['d', 'o', 'g'] >>> Doesn't seem too onerous to me... Alan G From lonetwin@yahoo.com Wed Aug 8 11:49:23 2001 From: lonetwin@yahoo.com (steve) Date: Wed, 8 Aug 2001 16:19:23 +0530 Subject: [Tutor] How to convert an integer into a binary? In-Reply-To: <20010808102613.A9748@Laplace.localdomain> References: <20010808102613.A9748@Laplace.localdomain> Message-ID: <01080816045200.11351@mercury.in.cqsl.com> On Wednesday 08 August 2001 13:56, you wrote: > On Wed, Aug 08, 2001 at 03:36:04PM +0900, Haiyang wrote: > > How can I convert an interger into a binary code in Python? > > Hello! > > This should become a faq ;-) And also should be put on Useless, Rob ??? Peace Steve =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D > import sys > e=3D[] > try: > =09z=3Dint(raw_input("Number?\n> ")) > except: > =09print "Need a number." > =09sys.exit(1) > while (z > 0): > =09if (z & 1) =3D=3D 1: > =09=09e.append(1) > =09else: > =09=09e.append(0) > z=3Dz>>1 > e.reverse() > print e --=20 ----------------------------------------- bug, n: =09=09A son of a glitch. ----------------------------------------- From alan.gauld@bt.com Wed Aug 8 12:06:15 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 8 Aug 2001 12:06:15 +0100 Subject: [Tutor] How to convert an integer into a binary? Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BE6E@mbtlipnt02.btlabs.bt.co.uk> > How can I convert an interger into a binary code in Python? I assume you mean to print it as a binary number? It is already stored in binary internally! To print it try something like: >>> x = 42 >>> while x > 0: ... i = x&1 ... print i, ... x = x >>1 ... 0 1 0 1 0 1 HTH, Alan G. From alan.gauld@bt.com Wed Aug 8 12:10:11 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 8 Aug 2001 12:10:11 +0100 Subject: [Tutor] Using string.strip() Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BE6F@mbtlipnt02.btlabs.bt.co.uk> > Alternatively, try list comprehensions: > responses = [item.strip() for item in responses] Or the easier to read(in this case) map: responses = map(string.strip,responses) comprehensions are OK if dealing with multiple variables but for simple mappings like this I much prefer map() - it always seems much less like black magic! Alan g From seand88@hotmail.com Wed Aug 8 13:07:40 2001 From: seand88@hotmail.com (sean dowie) Date: Wed, 8 Aug 2001 13:07:40 +0100 Subject: [Tutor] string to list of characters - thanks! References: Message-ID: Thanks Danny and Alan I didn't realize I could use >>> for letter in myString and it looks like strings are more versatile than I thought. From ppathiyi@cisco.com Wed Aug 8 13:26:47 2001 From: ppathiyi@cisco.com (Praveen Pathiyil) Date: Wed, 8 Aug 2001 17:56:47 +0530 Subject: [Tutor] Re: [XML-SIG] XML Parser References: <03c801c11fcd$f8d3a060$37ef87c0@ppathiyipc> <05bd01c11fe5$a54be1b0$37ef87c0@ppathiyipc> Message-ID: <06c401c12005$64d2b3a0$37ef87c0@ppathiyipc> Hi All, >From where can i download the following modules ?(which comes under xml.sax) drivers, saxutils, saxexts, saxlib. Does the modules for DOM also uses the same parsers as SAX ? (Those under xml.parsers.expat ?) Thanks, Praveen. From csmith@blakeschool.org Wed Aug 8 14:43:20 2001 From: csmith@blakeschool.org (Christopher Smith) Date: Wed, 08 Aug 2001 08:43:20 -0500 Subject: [Tutor] Re: How to convert an integer into a binary? Message-ID: lumbricus@gmx.net wrote: | On Wed, Aug 08, 2001 at 03:36:04PM +0900, Haiyang wrote: | > How can I convert an interger into a binary code in Python? | | Hello! | | This should become a faq ;-) | | import sys | e=[] | try: | z=int(raw_input("Number? | > ")) | except: | print "Need a number." | sys.exit(1) | while (z > 0): | if (z & 1) == 1: | e.append(1) | else: | e.append(0) | z=z>>1 | e.reverse() | print e | Thanks for the bit-operations approach! (Watch out for the trivial z=0 case, though, which should return e=[0] instead of [].) It inspired me to change the approach that I had taken when needing this function. Here's what I came up with: def d2b(numb,b=2): '''Returns a list containing the base b representation of the decimal number, big end first. ''' l=[numb] while l[0]>=b: l.insert(1,0) l[0],l[1]=divmod(l[0],b) return l There's already a version on the Useless site. Coupling what you had (case for b==2) with the above might make for a good addition, though. /c From lumbricus@gmx.net Wed Aug 8 14:58:46 2001 From: lumbricus@gmx.net (lumbricus@gmx.net) Date: Wed, 8 Aug 2001 15:58:46 +0200 Subject: [Tutor] Re: How to convert an integer into a binary? In-Reply-To: ; from csmith@blakeschool.org on Wed, Aug 08, 2001 at 08:43:20AM -0500 References: Message-ID: <20010808155846.A10683@Laplace.localdomain> On Wed, Aug 08, 2001 at 08:43:20AM -0500, Christopher Smith wrote: > lumbricus@gmx.net wrote: > > Thanks for the bit-operations approach! (Watch out for the trivial z=0 > case, though, which should return e=[0] instead of [].) Yes *duck* silly me *patsch* It inspired me to > change the approach that I had taken when needing this function. Here's > what I came up with: > > def d2b(numb,b=2): > '''Returns a list containing the base b representation of > the decimal number, big end first. > ''' > l=[numb] > while l[0]>=b: > l.insert(1,0) > l[0],l[1]=divmod(l[0],b) > return l > How beautyful :-) (saved) > There's already a version on the Useless site. Coupling > what you had (case for b==2) with the above might make for a good > addition, though. > > /c > Greetings J"o! :-) -- No matter how old a mother is, she watches her middle-aged children for signs of improvement. -- Florida Scott-Maxwell From martin@loewis.home.cs.tu-berlin.de Wed Aug 8 15:52:01 2001 From: martin@loewis.home.cs.tu-berlin.de (Martin v. Loewis) Date: Wed, 8 Aug 2001 16:52:01 +0200 Subject: [Tutor] Re: [XML-SIG] XML Parser In-Reply-To: <05bd01c11fe5$a54be1b0$37ef87c0@ppathiyipc> References: <03c801c11fcd$f8d3a060$37ef87c0@ppathiyipc> <05bd01c11fe5$a54be1b0$37ef87c0@ppathiyipc> Message-ID: <200108081452.f78Eq1i00943@mira.informatik.hu-berlin.de> > When I try that, I get an exception. So I guess that it is because pyexpat > is not installed ... Indeed, on Solaris, it is unlikely that pyexpat is installed. I recommend uncommenting the pyexpat line in Modules/Setup, following the instructions above, and re-installing Python. Just building a libexpat.a, and re-running Python's make to get pyexpat.so would be sufficient as well. Regards, Martin From alan.gauld@bt.com Wed Aug 8 17:48:41 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 8 Aug 2001 17:48:41 +0100 Subject: [Tutor] Re: How to convert an integer into a binary? Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BE72@mbtlipnt02.btlabs.bt.co.uk> > On Wed, Aug 08, 2001 at 08:43:20AM -0500, Christopher Smith wrote: > > what I came up with: > > > > def d2b(numb,b=2): > > '''Returns a list containing the base b representation of > > the decimal number, big end first. > > ''' > > l=[numb] > > while l[0]>=b: > > l.insert(1,0) > > l[0],l[1]=divmod(l[0],b) > > return l Ooh, thats nice! It was sufficiently clever I had to insert a couple of print statements round the divmod to check how it worked. Interesting use of insert, I like it... Alan g PS In my previous attempt at this I forgot the reverse operation at the end, sorry, that was careless. But having seen this solution it becomes irrelevant... :-) From pythonpython@hotmail.com Wed Aug 8 18:08:41 2001 From: pythonpython@hotmail.com (Python Newbie) Date: Thu, 9 Aug 2001 02:08:41 +0900 Subject: [Tutor] Python Books Message-ID: Can you recommend a few GOOD Python books(for someone who has some experience in programming)? There are so many Python books out there; I am not sure which one I should read... Shall I do the O'reilly's "Learning Python" and "Programming Python"? Or "Python Bible 2.1"? Or ...? What are the books which give detailed explanations? Thank you for your help. From ak@silmarill.org Wed Aug 8 18:13:45 2001 From: ak@silmarill.org (Andrei Kulakov) Date: Wed, 08 Aug 2001 13:13:45 -0400 Subject: [Tutor] Python Books In-Reply-To: <"from pythonpython"@hotmail.com> References: Message-ID: <20010808131345.A4813@sill.silmarill.org> On Thu, Aug 09, 2001 at 02:08:41AM +0900, Python Newbie wrote: > Can you recommend a few GOOD Python books(for someone who has some > experience in programming)? > There are so many Python books out there; I am not sure which one I should > read... > Shall I do the O'reilly's "Learning Python" and "Programming Python"? > Or "Python Bible 2.1"? > Or ...? > What are the books which give detailed explanations? Here's a datapoint: I had a bit of experience in C, having written a few small 100-line or so programs. I never done anything even remotely serious, though. I bought "programming python" and found that it went over my head, but now that I know more about python, I began re-reading it and found it far more useful. So, if you're about as experienced as I was, try an easier book for starters. > > Thank you for your help. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: http://silmarill.org/cymbaline From csmith@blakeschool.org Wed Aug 8 18:27:32 2001 From: csmith@blakeschool.org (Christopher Smith) Date: Wed, 08 Aug 2001 12:27:32 -0500 Subject: [Tutor] Reset function Message-ID: Dear tutor, I looked at the reset function presented recently to "purify the namespace" before running a program (reset(vars())) and the last line has me stumped. Here's a simplified version: ### def reset(namespace, user_safe_items=()): for item in namespace.keys(): exec "del "+item in namespace ### I thought something like "del item"; or "del namespace[item]" might work (they don't). What is the "item in namespace" doing?? Namespace isn't a sequence so why does this even work? Any help appreciated. /c From dyoo@hkn.eecs.berkeley.edu Wed Aug 8 18:39:18 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 8 Aug 2001 10:39:18 -0700 (PDT) Subject: [Tutor] Reset function In-Reply-To: Message-ID: On Wed, 8 Aug 2001, Christopher Smith wrote: > Dear tutor, > > I looked at the reset function presented recently to "purify the namespace" > before running a program (reset(vars())) and the last line has me stumped. > > Here's a simplified version: > > ### > def reset(namespace, user_safe_items=()): > for item in namespace.keys(): > exec "del "+item in namespace Try parsing it like this: exec ("del" + item) in namespace It might actually be better to write it like this to avoid confusion. The 'in namespace' part is an optional part of the exec statement: http://www.python.org/doc/current/ref/exec.html Good luck! From brian@dorseys.org Wed Aug 8 18:41:10 2001 From: brian@dorseys.org (Brian Dorsey) Date: Wed, 8 Aug 2001 10:41:10 -0700 Subject: [Tutor] Python Books In-Reply-To: <20010808131345.A4813@sill.silmarill.org>; from sill@optonline.net on Wed, Aug 08, 2001 at 01:13:45PM -0400 References: <"from pythonpython"@hotmail.com> <20010808131345.A4813@sill.silmarill.org> Message-ID: <20010808104110.A15643@dorseys.org> Another data point: (and my first post to the Tutor list. ;) My experience before python: quite a bit of SQL and a fair amount of VBA (in Access) and VBScript (ASP pages). I started with Learning Python and loved it. The pace and style of writing worked well for me and it's short enough I felt I was actually getting a handle on things. It seems that it provides a solid foundation to work from, teaching the things you'll need to know whenever you write anyhting in python. I think there are several other intro books which cover the same material, this just the one I happened across. The intro tutorial on www.python.org is pretty good as well... but I seem to need to have a book in front of me to learn... maybe I need a second monitor to show the docs on.. ;) Take care, -Brian PS- Anyone else have any need to send email from Lotus Notes via python and COM?:) I've got a short, simple script working. On Wed, Aug 08, 2001 at 01:13:45PM -0400, Andrei Kulakov wrote: > On Thu, Aug 09, 2001 at 02:08:41AM +0900, Python Newbie wrote: > > Can you recommend a few GOOD Python books(for someone who has some > > experience in programming)? > > There are so many Python books out there; I am not sure which one I should > > read... > > Shall I do the O'reilly's "Learning Python" and "Programming Python"? > > Or "Python Bible 2.1"? > > Or ...? > > What are the books which give detailed explanations? > > Here's a datapoint: I had a bit of experience in C, having written a few > small 100-line or so programs. I never done anything even remotely serious, > though. I bought "programming python" and found that it went over my head, > but now that I know more about python, I began re-reading it and found > it far more useful. So, if you're about as experienced as I was, try an > easier book for starters. > From israel@lith.com Wed Aug 8 18:46:57 2001 From: israel@lith.com (Israel Evans) Date: Wed, 8 Aug 2001 10:46:57 -0700 Subject: [Tutor] Using os.path.walk across platforms (fwd) Message-ID: -----Original Message----- From: Daniel Coughlin [mailto:kauphlyn@speakeasy.org] Sent: Tuesday, August 07, 2001 7:05 PM To: rwaters@csmbid.com Cc: tutor@python.org Subject: Re: [Tutor] Using os.path.walk across platforms (fwd) Hello, I wrote a function that might do the trick for you. I am not familiar enough with the os.path.walk function to know exactly what you are wanting, but I added a new function and rewrote a couple of lines in your script, which returns a list of all the directories in the present working directory. This will work for a script running on unix connecting to an NT filesystem (at least it worked on mine ;-) . It did not work going from NT to Unix. You might need to tweak the regular expression to get it exact. I am sure this can be improved upon however. #!/usr/bin/python import os, string, re from ftplib import FTP def FilterDirectories(listing): templist = [] dirlist = [] for item in listing: if item[0] == 'd': templist.append(re.split(':',item)) for item in templist: dirlist.append(string.strip(re.sub('\d*','',item[1]))) for item in dirlist: print item + ' is a directory..' return dirlist def GetFiles(): listings = [] #going to be a list of retrlines session = FTP() session.connect('myhost', port=21) session.login(user=USERNAME, passwd='*****') #os.path.walk(session.retrlines('LIST'),TheList,None) session.cwd('Music') # delete this line session.retrlines('LIST', listings.append) FilterDirectories(listings) session.close() GetFiles() ----------------------------------------------- The output on my system is : Bell and Sebastian is a directory.. cocteau twins is a directory.. rachels is a directory.. Radiohead is a directory.. Sly & The Family Stone is a directory.. Sonic Youth is a directory.. Talking Heads is a directory.. (These are all, in fact, directories!) Then I suppose you could use the dirlist to loop through each of the directories using chdir. Hope this helps. Daniel PS Hooray for Danny Yoo!!! > >---------- Forwarded message ---------- >Date: Tue, 07 Aug 2001 14:17:34 -0500 >From: Randy Waters >To: "tutor@python.org" >Subject: [Tutor] Using os.path.walk across platforms > >Hello. I have an interesting little challenge. I need to copy files from >an NT server to multiple Linux servers. The Python script needs to >execute on a UNIX server. I am using ftplib and os.path. > >My problem is that the standard 'LIST' in (ftplib) retrlines needs to be >captured to a list so that I can check to see if a entry is a directory >or not. If I were executing only on UNIX/Linux I could use os.path.walk >without a problem, but I am trying to "walk" down an NT path from UNIX. > >This script: > >#!/usr/bin/python > >import os, string >from ftplib import FTP > >def TheList(arg, dirname, names): > for name in names: > print os.path.join(dirname, name) > if os.path.isdir(name): > print name + ' is a directory...' > >def GetFiles(): > session = FTP() > session.connect('myserver.domain.com', port=8282) > session.login() > os.path.walk(session.retrlines('LIST'), TheList, None) > session.close() > return > >GetFiles() >------------------- >Returns this type of information: > >dr-xr-xr-x 1 owner group 0 Dec 7 2000 Co pack >projects >dr-xr-xr-x 1 owner group 0 May 29 14:52 COA >dr-xr-xr-x 1 owner group 0 Aug 2 8:45 HANDLING >-r-xr-xr-x 1 owner group 12800 Nov 4 1996 INFRZPR2.DOC > >------------------- > >If I could test the 1st position for 'd' then I would know that I have >to chdir and read down the tree. Using os.path.isdir does not work >probably because I am running my script on a UNIX server logged into an >NT server. > >If anyone has any ideas I would appreciate it. Thank you and what a >great language! > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > _________________________________________________________________ Get your FREE download of MSN Explorer at http://explorer.msn.com/intl.asp _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From israel@lith.com Wed Aug 8 18:50:00 2001 From: israel@lith.com (Israel Evans) Date: Wed, 8 Aug 2001 10:50:00 -0700 Subject: [Tutor] Using os.path.walk across platforms (fwd) Message-ID: whoops. It think I just sent a blank email out. sorry, trigger finger overload... I don't know if this will work on the nt to unix, I haven't tested it because I don't have access to either one right yet, but I just re3cently did something that used all of the generic os stuff to print out a list of directories and files. This could be tweaked to do the same thing for you, I think.. Anyway here it is... let me know If I'm on crack or anything... ------------------------------------------------- #! e:\ehold\python21 import os, os.path def dircont(rootdir=os.getcwd()): """Types out a list of directories and files in specified directory """ dirlist = [] filelist = [] for item in os.listdir(rootdir): itempath = os.path.join(rootdir, item) if os.path.isdir(itempath): dirlist.append(item) if os.path.isfile(itempath): filelist.append(item) print 'Root Directory: ', rootdir print '\nFiles:' for item in filelist: print '\t',item print '\nDirectories:' for item in dirlist: print '\t',item if __name__ == '__main__': import os, os.path rootdir = raw_input('directory to search:>') dircont(rootdir) raw_input('press any key to end') ---------------------------------------------------------- -----Original Message----- From: Daniel Coughlin [mailto:kauphlyn@speakeasy.org] Sent: Tuesday, August 07, 2001 7:05 PM To: rwaters@csmbid.com Cc: tutor@python.org Subject: Re: [Tutor] Using os.path.walk across platforms (fwd) Hello, I wrote a function that might do the trick for you. I am not familiar enough with the os.path.walk function to know exactly what you are wanting, but I added a new function and rewrote a couple of lines in your script, which returns a list of all the directories in the present working directory. This will work for a script running on unix connecting to an NT filesystem (at least it worked on mine ;-) . It did not work going from NT to Unix. You might need to tweak the regular expression to get it exact. I am sure this can be improved upon however. #!/usr/bin/python import os, string, re from ftplib import FTP def FilterDirectories(listing): templist = [] dirlist = [] for item in listing: if item[0] == 'd': templist.append(re.split(':',item)) for item in templist: dirlist.append(string.strip(re.sub('\d*','',item[1]))) for item in dirlist: print item + ' is a directory..' return dirlist def GetFiles(): listings = [] #going to be a list of retrlines session = FTP() session.connect('myhost', port=21) session.login(user=USERNAME, passwd='*****') #os.path.walk(session.retrlines('LIST'),TheList,None) session.cwd('Music') # delete this line session.retrlines('LIST', listings.append) FilterDirectories(listings) session.close() GetFiles() ----------------------------------------------- The output on my system is : Bell and Sebastian is a directory.. cocteau twins is a directory.. rachels is a directory.. Radiohead is a directory.. Sly & The Family Stone is a directory.. Sonic Youth is a directory.. Talking Heads is a directory.. (These are all, in fact, directories!) Then I suppose you could use the dirlist to loop through each of the directories using chdir. Hope this helps. Daniel PS Hooray for Danny Yoo!!! > >---------- Forwarded message ---------- >Date: Tue, 07 Aug 2001 14:17:34 -0500 >From: Randy Waters >To: "tutor@python.org" >Subject: [Tutor] Using os.path.walk across platforms > >Hello. I have an interesting little challenge. I need to copy files from >an NT server to multiple Linux servers. The Python script needs to >execute on a UNIX server. I am using ftplib and os.path. > >My problem is that the standard 'LIST' in (ftplib) retrlines needs to be >captured to a list so that I can check to see if a entry is a directory >or not. If I were executing only on UNIX/Linux I could use os.path.walk >without a problem, but I am trying to "walk" down an NT path from UNIX. > >This script: > >#!/usr/bin/python > >import os, string >from ftplib import FTP > >def TheList(arg, dirname, names): > for name in names: > print os.path.join(dirname, name) > if os.path.isdir(name): > print name + ' is a directory...' > >def GetFiles(): > session = FTP() > session.connect('myserver.domain.com', port=8282) > session.login() > os.path.walk(session.retrlines('LIST'), TheList, None) > session.close() > return > >GetFiles() >------------------- >Returns this type of information: > >dr-xr-xr-x 1 owner group 0 Dec 7 2000 Co pack >projects >dr-xr-xr-x 1 owner group 0 May 29 14:52 COA >dr-xr-xr-x 1 owner group 0 Aug 2 8:45 HANDLING >-r-xr-xr-x 1 owner group 12800 Nov 4 1996 INFRZPR2.DOC > >------------------- > >If I could test the 1st position for 'd' then I would know that I have >to chdir and read down the tree. Using os.path.isdir does not work >probably because I am running my script on a UNIX server logged into an >NT server. > >If anyone has any ideas I would appreciate it. Thank you and what a >great language! > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > _________________________________________________________________ Get your FREE download of MSN Explorer at http://explorer.msn.com/intl.asp _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From wilson@visi.com Wed Aug 8 18:54:42 2001 From: wilson@visi.com (Timothy Wilson) Date: Wed, 8 Aug 2001 12:54:42 -0500 (CDT) Subject: [Tutor] Python Books In-Reply-To: Message-ID: On Thu, 9 Aug 2001, Python Newbie wrote: > Can you recommend a few GOOD Python books(for someone who has some > experience in programming)? > There are so many Python books out there; I am not sure which one I should > read... > Shall I do the O'reilly's "Learning Python" and "Programming Python"? > Or "Python Bible 2.1"? > Or ...? > What are the books which give detailed explanations? Try Wesley Chun's "Core Python Programming." You won't be disappointed. -Tim -- Tim Wilson | Visit Sibley online: | Check out: Henry Sibley HS | http://www.isd197.org | http://www.zope.com W. St. Paul, MN | | http://slashdot.org wilson@visi.com | | http://linux.com From ak@silmarill.org Wed Aug 8 18:58:26 2001 From: ak@silmarill.org (Andrei Kulakov) Date: Wed, 08 Aug 2001 13:58:26 -0400 Subject: [Tutor] Python Books In-Reply-To: <"from brian"@dorseys.org> References: Message-ID: <20010808135826.A5054@sill.silmarill.org> On Wed, Aug 08, 2001 at 10:41:10AM -0700, Brian Dorsey wrote: > Another data point: (and my first post to the Tutor list. ;) > > My experience before python: quite a bit of SQL and a fair amount of VBA (in Access) and VBScript (ASP pages). I started with Learning Python and loved it. The pace and style of writing worked well for me and it's short enough I felt I was actually getting a handle on things. It seems that it provides a solid foundation to work from, teaching the things you'll need to know whenever you write anyhting in python. I think there are several other intro books which cover the same material, this just the one I happened across. > > The intro tutorial on www.python.org is pretty good as well... but I seem to need to have a book in front of me to learn... maybe I need a second monitor to show the docs on.. ;) > > Take care, > -Brian > > PS- Anyone else have any need to send email from Lotus Notes via python and COM?:) I've got a short, simple script working. Not me, but you can submit it to vaults of parnassus (link at python.org), be patient though as it sometimes takes more than a week for submission to go through. [snipped] -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: http://silmarill.org/cymbaline From bwinton@tor.dhs.org Wed Aug 8 19:32:14 2001 From: bwinton@tor.dhs.org (Blake Winton) Date: Wed, 8 Aug 2001 14:32:14 -0400 Subject: [Tutor] Python Books In-Reply-To: <20010808135826.A5054@sill.silmarill.org> References: <"from brian"@dorseys.org> <20010808135826.A5054@sill.silmarill.org> Message-ID: <20010808143214.A10748@tor.dhs.org> * Andrei Kulakov [010808 14:02]: > > PS- Anyone else have any need to send email from Lotus Notes > > via python and COM?:) I've got a short, simple script > > working. > Not me, but you can submit it to vaults of parnassus (link at > python.org), be patient though as it sometimes takes more than > a week for submission to go through. Or, if no-one else has that need, perhaps the Useless Python Pages would be more appropriate? ;) http://www.lowerstandard.com/python/pythonsource.html (Which should really have a link from the lowerstandard.com main site...) Later, Blake. -- 9:40pm up 52 days, 21:07, 2 users, load average: 0.02, 0.09, 0.07 From rob@jam.rr.com Wed Aug 8 19:42:50 2001 From: rob@jam.rr.com (Rob Andrews) Date: Wed, 8 Aug 2001 13:42:50 -0500 Subject: [Tutor] Python Books In-Reply-To: <20010808104110.A15643@dorseys.org> Message-ID: # > > Can you recommend a few GOOD Python books(for someone who has some # > > experience in programming)? # > > There are so many Python books out there; I am not sure # which one I should # > > read... # > > Shall I do the O'reilly's "Learning Python" and # "Programming Python"? # > > Or "Python Bible 2.1"? # > > Or ...? # > > What are the books which give detailed explanations? For someone with some programming experience, *Learning Python* has some good discussion. *Core Python Programming* is an excellent book covering the basics and an introduction to some more intermediate topics. These days I find *Core Python Programming* and *Programming Python* to be an awesome combination. *Core* seems like a great introductory textbook, and *Programming Python (2nd edition)* is like a big, thick tutorial on real world Python. # PS- Anyone else have any need to send email from Lotus Notes # via python and COM?:) I've got a short, simple script working. May I recommend Useless Python? --> http://www.lowerstandard.com/python/ Rob Your one-stop shop for newbie source code! Useless Python: http://www.lowerstandard.com/python/ From kromag@nsacom.net Wed Aug 8 22:10:15 2001 From: kromag@nsacom.net (kromag@nsacom.net) Date: Wed, 8 Aug 2001 14:10:15 -0700 (PDT) Subject: [Tutor] PIL paste-in problems Message-ID: <200108082110.f78LAEt08015@pop.nsacom.net> I am attempting to paste two images to either top corner of another image: ---------------begin pasty------------ import Image import os import sys bg=Image.open("\windows\desktop\doug.jpg").crop() paste_in=Image.open("\windows\desktop\robo.gif").crop() #get the boundaries bg_size=bg.getbbox() paste_in_size=paste_in.getbbox() #offset 10 pixels from the sides offset=(10) #establish positions pos0=(bg_size[0]+offset, bg_size[1]+offset, paste_in_size[2]+offset, paste_in_size[3]+offset) pos1=(bg_size[2] -paste_in_size[0] -offset, bg_size[1] +offset, bg_size[2] - offset, bg_size[1]+offset+paste_in_size[3]) #paste `em into the background image. bg.paste(paste_in,pos0) bg.paste(paste_in,pos1) bg.save("\windows\desktop\test.jpg","JPEG") #run dancing into the sunset wearing a lavender loincloth... -----------------end pasty---------------- I get the error: >pythonw -u card_builder.py Traceback (most recent call last): File "card_builder.py", line 16, in ? bg.paste(paste_in,pos1) File "c:python20pilImage.py", line 571, in paste self.im.paste(im, box) ValueError: images do not match >Exit code: 1 Now I don't think my image is out of bounds. How can the images not match, since they are the same image? I must confess extreme confusion. From droux@tuks.co.za Wed Aug 8 20:36:24 2001 From: droux@tuks.co.za (Danie Roux) Date: Wed, 8 Aug 2001 21:36:24 +0200 Subject: [Tutor] gdbm and locking Message-ID: <20010808213624.A3982@maple.up.ac.za> Can I trust on Python/OS to ensure proper locking for gdbm databases? If two programs is trying to write at the same time, will the data still be valid? Thank you! -- Danie Roux *shuffle* Adore Unix From jessw@loop.com Wed Aug 8 20:37:34 2001 From: jessw@loop.com (Jesse W) Date: Wed, 8 Aug 2001 12:37:34 -0700 Subject: [Tutor] Reset function In-Reply-To: References: Message-ID: <3B71328E.3316.98DB92@localhost> Dear Danny, et all, Danny Yoo wrote: > On Wed, 8 Aug 2001, Christopher Smith wrote: > > Dear tutor, > > > > I looked at the reset function presented recently to "purify the > > namespace" before running a program (reset(vars())) and the last > > line has me stumped. > > > > Here's a simplified version: > > > > ### > > def reset(namespace, user_safe_items=()): > > for item in namespace.keys(): > > exec "del "+item in namespace > > Try parsing it like this: > > exec ("del" + item) in namespace > > It might actually be better to write it like this to avoid confusion. > The 'in namespace' part is an optional part of the exec statement: > > http://www.python.org/doc/current/ref/exec.html > > Good luck! Opps. Yah, I should have realized that that "exec SomeCode in GlobalNamespace" thing was pretty obscure. Heck, I even had to look it up myself when I was writing the function! Thank you Danny, for explaining it to Chris. :-) Oh, and congratulations on your apotheosis. ;-) Cheers for the tutor list, Jesse F. Weinstein From pobrien@orbtech.com Wed Aug 8 21:51:41 2001 From: pobrien@orbtech.com (Patrick K. O'Brien) Date: Wed, 8 Aug 2001 15:51:41 -0500 Subject: [Tutor] Announce: PyCrust 0.5 release now available Message-ID: PyCrust version 0.5 has been committed to CVS and is also available as a .zip file at http://sourceforge.net/project/showfiles.php?group_id=31263&release_id=47302 . Please give it a try and see what you think. PyCrust is an interactive Python Shell that can be run standalone, or integrated into other Python applications built with wxPython. PyCrust is built around Scintilla, and requires wxPython and Python 2.1 or greater. http://sourceforge.net/projects/pycrust/ --- Patrick K. O'Brien Orbtech "I am, therefore I think." From curtis.larsen@Covance.Com Wed Aug 8 21:53:42 2001 From: curtis.larsen@Covance.Com (Curtis Larsen) Date: Wed, 08 Aug 2001 15:53:42 -0500 Subject: [Tutor] "Secure" Input? Message-ID: Hey folks - This may have been covered before but does anyone have a suggestion as to how to set up a "secure" (raw?) input that doesn't echo characters back, or echos only stars? I'm looking for a genteel way to ask for a password (of course) so... what think? Thanks! Curtis ----------------------------------------------------- Confidentiality Notice: This e-mail transmission may contain confidential or legally privileged information that is intended only for the individual or entity named in the e-mail address. If you are not the intended recipient, you are hereby notified that any disclosure, copying, distribution, or reliance upon the contents of this e-mail is strictly prohibited. If you have received this e-mail transmission in error, please reply to the sender, so that we can arrange for proper delivery, and then please delete the message from your inbox. Thank you. From ak@silmarill.org Wed Aug 8 22:07:08 2001 From: ak@silmarill.org (Andrei Kulakov) Date: Wed, 08 Aug 2001 17:07:08 -0400 Subject: [Tutor] "Secure" Input? In-Reply-To: <"from curtis.larsen"@Covance.Com> References: Message-ID: <20010808170708.A1163@sill.silmarill.org> On Wed, Aug 08, 2001 at 03:53:42PM -0500, Curtis Larsen wrote: > Hey folks - > > This may have been covered before but does anyone have a suggestion as > to how to set up a "secure" (raw?) input that doesn't echo characters > back, or echos only stars? I'm looking for a genteel way to ask for a > password (of course) so... what think? > > > Thanks! > Curtis GUI or console? In GUI there are various special entry box methods, different for each GUI, I think (although I never done GUI myself). In console, here's one way: def set_normal_term(self): """Set 'normal' terminal settings""" if sys.version_info[0] == 2 and sys.version_info[1] == 0: termios.tcsetattr(self.fd, TERMIOS.TCSAFLUSH, self.old_term) else: termios.tcsetattr(self.fd, termios.TCSAFLUSH, self.old_term) def set_curses_term(self): """Set 'normal' terminal settings""" if sys.version_info[0] == 2 and sys.version_info[1] == 0: termios.tcsetattr(self.fd, TERMIOS.TCSAFLUSH, self.new_term) else: termios.tcsetattr(self.fd, termios.TCSAFLUSH, self.new_term) self.fd = sys.stdin.fileno() self.new_term = termios.tcgetattr(self.fd) self.old_term = termios.tcgetattr(self.fd) if sys.version_info[0] == 2 and sys.version_info[1] == 0: self.new_term[3] = self.new_term[3] & ~TERMIOS.ICANON & ~TERMIOS.ECH O else: self.new_term[3] = self.new_term[3] & ~termios.ICANON & ~termios.ECH O (it's different for 2.0 and newer versions, I don't know about 1.5). self.set_curses_term() while 1: c = os.read(self.fd, 1) print '*' if c == '\n': # check if pwd is right and break out.. - Andrei > > > > ----------------------------------------------------- > Confidentiality Notice: This e-mail transmission > may contain confidential or legally privileged > information that is intended only for the individual > or entity named in the e-mail address. If you are not > the intended recipient, you are hereby notified that > any disclosure, copying, distribution, or reliance > upon the contents of this e-mail is strictly prohibited. > > If you have received this e-mail transmission in error, > please reply to the sender, so that we can arrange > for proper delivery, and then please delete the message > from your inbox. Thank you. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: http://silmarill.org/cymbaline From kalle@gnupung.net Wed Aug 8 22:14:22 2001 From: kalle@gnupung.net (Kalle Svensson) Date: Wed, 8 Aug 2001 23:14:22 +0200 Subject: [Tutor] "Secure" Input? In-Reply-To: ; from curtis.larsen@Covance.Com on Wed, Aug 08, 2001 at 03:53:42PM -0500 References: Message-ID: <20010808231422.A23233@gandalf> Sez Curtis Larsen: > Hey folks - > > This may have been covered before but does anyone have a suggestion as > to how to set up a "secure" (raw?) input that doesn't echo characters > back, or echos only stars? I'm looking for a genteel way to ask for a > password (of course) so... what think? Check out the standard module getpass. http://python.org/doc/current/lib/module-getpass.html Peace, Kalle -- [ kalle@gnupung.net ][ Thought control, brought to you by the WIPO! ] [ http://gnupung.net/ ][ http://anti-dmca.org/ http://eurorights.org/ ] From sheila@thinkspot.net Wed Aug 8 22:20:47 2001 From: sheila@thinkspot.net (Sheila King) Date: Wed, 08 Aug 2001 14:20:47 -0700 Subject: [Tutor] "Secure" Input? In-Reply-To: References: Message-ID: <1180ED90DAE@kserver.org> On Wed, 08 Aug 2001 15:53:42 -0500, "Curtis Larsen" wrote about [Tutor] "Secure" Input?: :Hey folks - : :This may have been covered before but does anyone have a suggestion as :to how to set up a "secure" (raw?) input that doesn't echo characters :back, or echos only stars? I'm looking for a genteel way to ask for a :password (of course) so... what think? How about the getpass module? http://www.python.org/doc/current/lib/module-getpass.html -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From pobrien@orbtech.com Wed Aug 8 22:12:52 2001 From: pobrien@orbtech.com (Patrick K. O'Brien) Date: Wed, 8 Aug 2001 16:12:52 -0500 Subject: [Tutor] Sorry about the PyCrust cross-posting Message-ID: Big time mistake. I really messed up when I cross-posted that announcement. It won't happen again. Please accept my apologies. --- Patrick K. O'Brien Orbtech "I am, therefore I think." From brian@dorseys.org Thu Aug 9 00:58:06 2001 From: brian@dorseys.org (Brian Dorsey) Date: Wed, 8 Aug 2001 16:58:06 -0700 Subject: [Tutor] Notes email from Python [was: Python Books] In-Reply-To: <20010808143214.A10748@tor.dhs.org>; from bwinton@tor.dhs.org on Wed, Aug 08, 2001 at 02:32:14PM -0400 References: <"from <20010808135826.A5054@sill.silmarill.org> <20010808143214.A10748@tor.dhs.org> Message-ID: <20010808165806.D19415@dorseys.org> I just submited it (such as it is. ;) to useless Python, so it'll probably show up there shortly. Until then, if anyone would like to play with it, email me directly and I'll send it on. ;) Take care, -Brian On Wed, Aug 08, 2001 at 02:32:14PM -0400, Blake Winton wrote: > * Andrei Kulakov [010808 14:02]: > > > PS- Anyone else have any need to send email from Lotus Notes > > > via python and COM?:) I've got a short, simple script > > > working. > > Not me, but you can submit it to vaults of parnassus (link at > > python.org), be patient though as it sometimes takes more than > > a week for submission to go through. > > Or, if no-one else has that need, perhaps the Useless Python > Pages would be more appropriate? ;) > > http://www.lowerstandard.com/python/pythonsource.html > > (Which should really have a link from the lowerstandard.com main > site...) > > Later, > Blake. From tbrauch@mindless.com Thu Aug 9 01:26:50 2001 From: tbrauch@mindless.com (Timothy M. Brauch) Date: Wed, 08 Aug 2001 20:26:50 -0400 Subject: [Tutor] Pippy Message-ID: <3B71D8CA.776E0A89@mindless.com> Has anyone used Pippy? How similar/different is it to Python? I am getting ready to upgrade my computer, and I get a free Palm computer from the store I am buying most of my new hardware. I wondered if I'd be able to sit down and write out and test programs for use in the real world on my Palm? - Tim From wesc@deirdre.org Thu Aug 9 01:17:39 2001 From: wesc@deirdre.org (Wesley Chun) Date: Wed, 8 Aug 2001 17:17:39 -0700 (PDT) Subject: [Tutor] closing files In-Reply-To: Message-ID: On Mon, 30 Jul 2001, Danny Yoo wrote: > On Mon, 30 Jul 2001 fleet@teachout.org wrote: > > > When opened files are not closed, what are the dangers? Are files closed > > by Python under some circumstances and, if so, which circumstances? > > When the variable goes out of scope, Python will automagically close() the > file for us. For example, your line: > > > open("writefile","w").write(open("readfile","r").read()) > > is ok because Python transparently is doing the close()ing for us. > > (I'm being a little handwavy: it has more to do with the fact that the > _reference count_ of the file goes to zero.) as danny has indicated, Python's garbage collection mechanism takes care of the files when they go out of scope. however, being from "the old school" and its dangers from C programming, i recommend that you explicitly close your files... it's more politically-correct, as far as i'm concerned. in C (and other languages which do NOT clean up after your mess), the dangers of not closing files does exist and is the greatest when a file is open for write. in such cases, data which has been "written," i.e., sent from user-land to the kernel buffers awaiting a real write to disk may not be flushed, causing your data to per- haps *not* get written to the file or some similar inconsistency. sure a one-liner is elegant, but have a close() in there will help make the code functionality more succinct even if there's an extra line or 2 of code. the other thing is that if that body of code does not go out of scope, the file remains open and an operating system resource consumed until a close() occurs or the file handle goes out of scope. in applications which open lots of files, this is not a good idea because you may run out of file descriptors and not be able to open any more files until some of the already-opened ones are closed. hope this helps! -wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Silicon Valley-SF Bay Area Python users group: http://baypiggies.org "Core Python Programming", Prentice Hall PTR, December 2000 http://starship.python.net/crew/wesc/cpp/ wesley.j.chun :: wesc@baypiggies.org cyberweb.consulting :: silicon.valley, ca http://www.roadkill.com/~wesc/cyberweb/ From wesc@deirdre.org Thu Aug 9 01:22:58 2001 From: wesc@deirdre.org (Wesley Chun) Date: Wed, 8 Aug 2001 17:22:58 -0700 (PDT) Subject: [Tutor] python source code In-Reply-To: <200107311337.f6VDbsQ22863@dsl092-074-184.bos1.dsl.speakeasy.net> Message-ID: On Tue, 31 Jul 2001, Michael P. Reilly wrote: > support wrote > > I am trying to obtain the source code for python ver. 1.5.2 for purposes > > of rebuilding, as I need to change what functions are actually called in > > C for pythons calls of open, write close, etc... (File I/O).. currently > > python doesn't use the win32API funcs for this, which i need to use for > > the program im working on to operate on NT, and over networks. IF > > anyone knows where i can get the source or has done this or has any > > advice for this (such as how to include the win32API in the C file, or > > which functions from python are defined where in the source code) I > > would be greatly appreciated. > > The Python core does not use win32 APIs because it is not a win32 > application; it is supported on multiple platforms. However there are > full extensions for the win32 APIs, including CreateFile and CreatePipe. > > Before you start cracking the code, you probably want to download and > look at those extensions: win32all at . > The module you are looking for in that package is called "win32file". as michael has suggested, i believe the code in the win32all package will probably contain what you're looking for... no need reinventing the wheel if it's already been done right? the exact web page from Mark where you can download all versions of win32all software (for all versions of Python) is located here: http://www.activestate.com/Products/ActivePython/win32all.html hope this helps! -wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Silicon Valley-SF Bay Area Python users group: http://baypiggies.org "Core Python Programming", Prentice Hall PTR, December 2000 http://starship.python.net/crew/wesc/cpp/ wesley.j.chun :: wesc@baypiggies.org cyberweb.consulting :: silicon.valley, ca http://www.roadkill.com/~wesc/cyberweb/ From fleet@teachout.org Thu Aug 9 03:31:53 2001 From: fleet@teachout.org (fleet@teachout.org) Date: Wed, 8 Aug 2001 22:31:53 -0400 (EDT) Subject: [Tutor] closing files In-Reply-To: Message-ID: On Wed, 8 Aug 2001, Wesley Chun wrote: > On Mon, 30 Jul 2001, Danny Yoo wrote: > > On Mon, 30 Jul 2001 fleet@teachout.org wrote: > > > > > When opened files are not closed, what are the dangers? Are files closed > > > by Python under some circumstances and, if so, which circumstances? > > > > When the variable goes out of scope, Python will automagically close() the > > file for us. For example, your line: > > > > > open("writefile","w").write(open("readfile","r").read()) > > > > is ok because Python transparently is doing the close()ing for us. > > > as danny has indicated, Python's garbage collection mechanism > takes care of the files when they go out of scope. however, > being from "the old school" and its dangers from C programming, > i recommend that you explicitly close your files... it's more > politically-correct, as far as i'm concerned. Ok. Thanks. And for the explanation. > sure a one-liner is elegant, but have a close() in there will help > make the code functionality more succinct even if there's an extra > line or 2 of code. the other thing is that if that body of code > does not go out of scope, the file remains open and an operating > system resource consumed until a close() occurs or the file handle > goes out of scope. Elegant? Well, I had "REALLY REALLY NIFTY" more in mind! :) I recently revisited a couple of things I wrote like that, and I agree it's not always easy to read. :( (However, just to satisfy my curiosity, could I have tacked a '.close()' on there?) > in applications which open lots of files, this is not a good idea > because you may run out of file descriptors and not be able to open > any more files until some of the already-opened ones are closed. Yes, I see where that could become a problem. > hope this helps! Immensely! Thanks - and thanks for Core Python Programming. I'm studying the "Sequences" chapter now. - fleet - From ppathiyi@cisco.com Thu Aug 9 05:47:20 2001 From: ppathiyi@cisco.com (Praveen Pathiyil) Date: Thu, 9 Aug 2001 10:17:20 +0530 Subject: [Tutor] XML Parser References: Message-ID: <07ad01c1208e$6366a240$37ef87c0@ppathiyipc> Thanks Danny ... After going thru your mail, I understood how to use these functions .. But can you explain the concept behind the interface functions and how python achieves this by having classes for these functions ? I guess it is implemented as abstract base classes and we are supposed to have derived classes of our own where we should override the functions with our own function implementations. But a formal explanation would be a great thing .... Thanks, Praveen. ----- Original Message ----- From: "Danny Yoo" To: "Praveen Pathiyil" Cc: ; Sent: Wednesday, August 08, 2001 1:29 PM Subject: Re: [Tutor] XML Parser > On Wed, 8 Aug 2001, Praveen Pathiyil wrote: > > > I am trying out some basic stuff on XML with Python. But I am > > unable to get a parser instance on my system ( I have cut and pasted > > some code which i tried out for this.). Also the "drivers" modules > > under xml.sax and "pyexpat" is not installed. (Since i am working on > > the server of my company, I can't install these packages myself). > > How do I proceed to get a parser instance ? > > > > > Hello! Let's take a look! > > [warning: this message is a little long] > > > > xml.sax.XMLReader is not meant to be used directly: it is "documentation", > that is, it's an interface that says that anything that parses XML should > do the sort of functions listed in: > > http://www.python.org/doc/current/lib/module-xml.sax.xmlreader.html > > > To actually get at a real XML parser, try xml.sax.make_parser() instead: > > ### > >>> parser = xml.sax.make_parser() > ### > > Python will search our system for an approprate XML parser; on many > systems, Python will use xml.parsers.expat. Try this first, and see if an > error message pops up or not. If an error occurs, then you'll probably > need to install Expat from: > > http://sourceforge.net/project/showfiles.php?group_id=10127&release_id=45670 > > > If you do get that exception, email us, and we can try fixing it. > Anyway, let's assume that you didn't run into an error. *grin* > > > Once we have this real parser, then we can start calling XMLReader'ish > methods on it, and be fairly sure that these methods will work: > > ### > >>> parser.parse > > >>> parser.setContentHandler > 0x80d276c> > ### > > > > Now we need to tell the parser what sort of content we're interested > in. If you look at the documentation on xmlreader, you'll see a bunch of > setFoobar()-style functions: we'll need to do something with that. This > will be easier if we have some sort of concrete example to work > with. > > > If we have some sort of document, like: > > ### > mydoc = """ > >

    Philip and Alex's Guide to Web Publishing

    >

    This is a really neat book.

    >

    The Practical SQL Handbook

    >

    This is also a neat book.

    >

    The Lord of the Rings

    >

    Frodo Lives!

    > """ > ### > > it might be nice to write something that parses out all the

    headers > in a document. What we'll do will look very similar to someone who has > played with sgmllib: we'll be writing a subclass that can look at > specific things, and that means writing a ContentHandler: > > (http://www.python.org/doc/current/lib/content-handler-objects.html) > > Here's one example of such a handler: > > > ### > class HeadlineHandler(ContentHandler): > """We're just interested in

    headlines...""" > def __init__(self): > self.in_h1 = 0 > > > def startElement(self, name, attrs): > if name == 'h1': self.in_h1 = 1 > > > def endElement(self, name): > if name == 'h1': self.in_h1 = 0 > > > def characters(self, content): > if self.in_h1: > print content > ### > > > > > Let's put all the pieces together, and see if this contraption can fly: > > ### > import xml.sax > from xml.sax.handler import ContentHandler > from StringIO import StringIO > > class HeadlineHandler(ContentHandler): > """We're just interested in

    headlines...""" > def __init__(self): > self.in_h1 = 0 > > > def startElement(self, name, attrs): > if name == 'h1': self.in_h1 = 1 > > > def endElement(self, name): > if name == 'h1': self.in_h1 = 0 > > > def characters(self, content): > if self.in_h1: > print content > > > if __name__ == '__main__': > mydoc = """ > >

    Philip and Alex's Guide to Web Publishing

    >

    This is a really neat book.

    >

    The Practical SQL Handbook

    >

    This is also a neat book.

    >

    The Lord of the Rings

    >

    Frodo Lives!

    > """ > parser = xml.sax.make_parser() > handler = HeadlineHandler() > parser.setContentHandler(handler) > parser.parse(StringIO(mydoc)) > > ## a little silliness since parser.parse needs a "file". Much > ## easier would have been to say, more directly: > ## > ## handler = HeadlineHandler() > ## xml.sax.parseString(mydoc, handler) > ## > ### > > > ### > dyoo@coffeetable:~$ python xmltest.py > Philip and Alex's Guide to Web Publishing > The Practical SQL Handbook > The Lord of the Rings > ### > > > I have to stop now, or I won't be able to wake up tomorrow. *grin* I know > this is insufficient, but I hope it's somewhat helpful. Good luck! > > From wesc@deirdre.org Thu Aug 9 07:46:15 2001 From: wesc@deirdre.org (Wesley Chun) Date: Wed, 8 Aug 2001 23:46:15 -0700 (PDT) Subject: [Tutor] Using string.strip() In-Reply-To: <95AF930883@kserver.org> Message-ID: On Wed, 8 Aug 2001, Sheila King wrote: > On Wed, 8 Aug 2001 09:15:28 +0200, Hans Nowak wrote > about RE: [Tutor] Using string.strip(): > > :Note that this for loop "as is" doesn't do anything to the responses list... > :it just strips an item, then discards it. Maybe this is the reason why it > :doesn't have the desired effect? > > Thanks to all who responded and pointed this out. > > As I said, I was having a dumb moment. I certainly should have known > better. > > I especially liked the solution: > > responses = [item.strip() for item in responses] > > That is really the coolest. (I'm still not good at the list > comprehensions thing.) the example you brought up is one motivating reason for creating list comprehensions... the syntax still seems a little weird to me since it's relatively new. as alan points out, it replaces the earlier syntax of (and in many ways obsoleting map()): responses = map(string.strip, responses) another reason why is that it (list comprehensions) saves one extra function call (to map()) and does not have to lookup objects over and over. anyway, just my $0.02. cheers! -wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Silicon Valley-SF Bay Area Python users group: http://baypiggies.org "Core Python Programming", Prentice Hall PTR, December 2000 http://starship.python.net/crew/wesc/cpp/ wesley.j.chun :: wesc@baypiggies.org cyberweb.consulting :: silicon.valley, ca http://www.roadkill.com/~wesc/cyberweb/ From alan.gauld@bt.com Thu Aug 9 10:31:38 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Thu, 9 Aug 2001 10:31:38 +0100 Subject: [Tutor] Python Books Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BE73@mbtlipnt02.btlabs.bt.co.uk> > There are so many Python books out there I think thats better than it as a couple of years ago. Then you had the choice of 2 good books and 2 not very good ones. Now we are spoilt for choice! :-) > Shall I do the O'reilly's "Learning Python" and > "Programming Python"? If you like O'Reilly's style then I'd say yes. But wesley Chun's book is a good single volume piece. And if you have a lot of programming experience you might find Dave Beasleys 'Python Essential Reference is all you need.' After all the tutor that comes with Python is very good and along with Dave's book should be enough for most programmers IMHO. All the details you could reasonably want are in the online docs - language reference and module/library reference. Alan g From ppathiyi@cisco.com Thu Aug 9 11:49:33 2001 From: ppathiyi@cisco.com (Praveen Pathiyil) Date: Thu, 9 Aug 2001 16:19:33 +0530 Subject: [Tutor] Secure Shell (ssh) Message-ID: <08dc01c120c0$f9cf8120$37ef87c0@ppathiyipc> This is a multi-part message in MIME format. ------=_NextPart_000_08D9_01C120EF.13246770 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi All, Is there a Secure Shell (ssh) implementation in python anywhere ? Thanks, Praveen. ------=_NextPart_000_08D9_01C120EF.13246770 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
    Hi All,
     
    Is there a Secure Shell (ssh) implementation in python anywhere = ?
     
    Thanks,
    Praveen.
    ------=_NextPart_000_08D9_01C120EF.13246770-- From Blake.Garretson@dana.com Thu Aug 9 13:54:28 2001 From: Blake.Garretson@dana.com (Blake.Garretson@dana.com) Date: Thu, 9 Aug 2001 08:54:28 -0400 Subject: [Tutor] Pippy Message-ID: >From: "Timothy M. Brauch" > >Has anyone used Pippy? How similar/different is it to Python? I am >getting ready to upgrade my computer, and I get a free Palm computer >from the store I am buying most of my new hardware. I wondered if I'd >be able to sit down and write out and test programs for use in the real >world on my Palm? I've used Pippy 0.6 and recently Pippy 0.7. They are using Python version 1.5.2+ which has string methods. The web site says they are planning a 2.0 upgrade. It is very cool, however, it's not especially useful just yet. With the latest release, you can import Python code from the Memo pad, so reusing code is now possible. That was a big step IMO. The main problems with Pippy (for me anyway) are that it lacks floating point numbers and interactive input. Input must generally come from "files" in the form of Memo notes. As far as floats go, you obviously can't do any real math without them, and that's mostly what I use Python for. Pippy has some real potential though. There is talk of being able to make Palm GUI's with it someday. Even with Pippy's current shortcomings, how cool is running any version of Python in the palm of your hand? Blake Garretson From Blake.Garretson@dana.com Thu Aug 9 13:56:10 2001 From: Blake.Garretson@dana.com (Blake.Garretson@dana.com) Date: Thu, 9 Aug 2001 08:56:10 -0400 Subject: [Tutor] Python Books Message-ID: >From: "Python Newbie" > >Can you recommend a few GOOD Python books(for someone who has some >experience in programming)? >There are so many Python books out there; I am not sure which one I should >read... >Shall I do the O'reilly's "Learning Python" and "Programming Python"? >Or "Python Bible 2.1"? Since I've never seen anyone else describe the Python 2.1 Bible, I'll do so since I bought it about 3-4 weeks ago. It is a great reference for someone who knows what they are already doing in Python. It covers simple and very complex topics. It shows you how to extend Python with C modules, parse XML, use NumPy, etc. It even has a chapter on wxPython (wxWindows) which is something most books totally ignore in favor of Tkinter (which this book covers as well.) This book really shows the versatility of Python. Here's the bad part: The book often demonstrates one concept by using code that includes other complex concepts without explaining them. If you know some Python, you'll be fine, but the authors regularly include code that won't be explained until later, so the examples have quite a bit of "magic" in them. I think the examples that baffled me were when they were trying to explain something simple, but use a function like "map" (before it had been explained) in the code when it wasn't even necessary. I also seem to recall that they use "import" for quite some time before explaining what it does. The idiom if (__name__=="__main__"): is also used without immediate explanation. I know my way around Python pretty well, and there were a few times that I thought, "I would NEVER have understood this if I didn't already know what's going on here." Having said all that, I really think this is a great book, butit is not for beginners, as the authors clearly state in the first few pages. If you know the basics of Python and need instruction (and examples) of more advanced topics, this is the book for you. One of the coolest things about this book is that it includes the newest features of the Python language. It really does cover Python 2.1, and it points out when a language feature is Python 2.0 or 2.1 specific. Incidentally, I also own Programming Python, Learning Python, and Teach Yourself Python in 24 Hours, but I've been using the Python 2.1 Bible the most the last few weeks. It is a great reference of advanced topics. For total beginners, I would certainly recommend Teach Yourself Python. For someone who's programmed before in any language, Learning Python is great. Dive into Programming Python once you've read some other Python book. The Python 2.1 Bible reminds me of Programming Python since it's a good second book, but a lousy first book. HTH, Blake Garretson From fasal.waseem@cis.co.uk Thu Aug 9 16:38:34 2001 From: fasal.waseem@cis.co.uk (fasal.waseem@cis.co.uk) Date: Thu, 9 Aug 2001 15:38:34 +0000 Subject: [Tutor] Fasal Waseem/DSS/ISD/Chief/CIS is out of the office. Message-ID: I will be out of the office starting 09/08/2001 and will not return until 17/08/2001. I will respond to your message when I return. Or please contact Martyn Smith on 4498 martyn.smith@cis.co.uk ************************************************************************* This e-mail may contain confidential information or be privileged. It is intended to be read and used only by the named recipient(s). If you are not the intended recipient(s) please notify us immediately so that we can make arrangements for its return: you should not disclose the contents of this e-mail to any other person, or take any copies. Unless stated otherwise by an authorised individual, nothing contained in this e-mail is intended to create binding legal obligations between us and opinions expressed are those of the individual author. The CIS marketing group, which is regulated for Investment Business by the Personal Investment Authority, includes: Co-operative Insurance Society Limited Registered in England number 3615R - for life assurance and pensions CIS Unit Managers Limited Registered in England and Wales number 2369965 (also regulated by IMRO) - for unit trusts and PEPs CIS Policyholder Services Limited Registered in England and Wales number 3390839 - for ISAs and investment products bearing the CIS name Registered offices: Miller Street, Manchester M60 0AL Telephone 0161-832-8686 Internet http://www.cis.co.uk E-mail cis@cis.co.uk CIS Deposit and Instant Access Savings Accounts are held with The Co-operative Bank p.l.c., registered in England and Wales number 990937, P.O. Box 101, 1 Balloon Street, Manchester M60 4EP, and administered by CIS Policyholder Services Limited as agent of the Bank. CIS is a member of the General Insurance Standards Council CIS & the CIS logo (R) Co-operative Insurance Society Limited ******************************************************************************** From pythonpython@hotmail.com Thu Aug 9 16:13:11 2001 From: pythonpython@hotmail.com (Python Snake) Date: Fri, 10 Aug 2001 00:13:11 +0900 Subject: [Tutor] Python Monks? Message-ID: Is there an interactive Python community website like Perl's www.perlmonks.org? Thank you! From dyoo@hkn.eecs.berkeley.edu Thu Aug 9 16:26:30 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 9 Aug 2001 08:26:30 -0700 (PDT) Subject: [Tutor] gdbm and locking In-Reply-To: <20010808213624.A3982@maple.up.ac.za> Message-ID: On Wed, 8 Aug 2001, Danie Roux wrote: > Can I trust on Python/OS to ensure proper locking for gdbm databases? Yes, but you'll want to send the right sort of flags when you open the gdbm file. According to the documentation at: http://www.python.org/doc/lib/module-gdbm.html you can open the database in locked mode automatically; I think you have to feed in the parameter 'u' to actually get gdbm to ignore locking, so you should be ok. I have to admit, though, that I haven't used this module yet. You might want to ask your question on the main Python newsgroup as well to see what they suggest. Good luck! From rob@jam.rr.com Thu Aug 9 16:41:28 2001 From: rob@jam.rr.com (Rob Andrews) Date: Thu, 09 Aug 2001 10:41:28 -0500 Subject: [Tutor] Python Monks? References: Message-ID: <3B72AF28.CEEAF106@jam.rr.com> Python Snake wrote: > > Is there an interactive Python community website like Perl's > www.perlmonks.org? > > Thank you! I haven't seen anything quite like this, although there are a number of interesting offerings out there. Here be a Python discussion forum, compliments of oriellynet.com: http://www.oreillynet.com/cs/user/forum/cs_disc/241 At first glance, it doesn't appear to be experiencing heavy traffic. I'd love to add more interactive community features to Useless Python, but development time is a precious commodity. So upgrades happen a little at a time. I would like Useless to reach a point soon where people can have a more personalized experience, but keep pointing discussion in the direction of lists like Python Tutor and others. In fact, I'd like to at least have a page of links to available lists with good descriptions to help people decide who to talk to about the material. Useless has just about outgrown its current site design again, BTW, so if anyone would like to contribute suggestions, graphics, or anything, let me know. Rob -- As foretold by Nostradamus.... Useless Python! http://www.lowerstandard.com/python From phil@xfr.co.uk Thu Aug 9 17:13:13 2001 From: phil@xfr.co.uk (Philip Kilner) Date: Thu, 09 Aug 2001 17:13:13 +0100 Subject: [Tutor] Python Monks? In-Reply-To: <3B72AF28.CEEAF106@jam.rr.com> Message-ID: Hi Rob, In article <3B72AF28.CEEAF106@jam.rr.com>, Rob Andrews wrote: > I'd love to add more interactive community features to Useless Python, > but development time is a precious commodity. > I know this is a really, really, obvious suggestion - but Zope + Squishdot would do the job (or at least /a/ job! ) with near-zero development resource. I don't know if there are any hosting issues with you for this, but if we're looking for something we can play with quickly, we (Inca Internet) could host it and you could whack it in a frame on "useless"... Just a thot! Regards PhilK Thu, 09 Aug 2001 17:06 +0100 Sundown dazzling day Gold through my eyes But my eyes turned within Only see Starless and bible black "Starless" - King Crimson (1974) From rwaters@csmbid.com Thu Aug 9 18:58:14 2001 From: rwaters@csmbid.com (Randy Waters) Date: Thu, 9 Aug 2001 12:58:14 -0500 Subject: [Tutor] Using os.path.walk across platforms (fwd) In-Reply-To: Message-ID: <000701c120fc$dd0dc880$040910ac@csmbid.com> Thanks a lot for the code. It works very well and I will put it in my little Python bag of tricks for future reference! However, I finally did get the results I wanted from ftplib .retrlines after playing around with the output from 'LIST'. This snippet of code lets me detect whether my NT files are directories or not so that I can do a chdir via ftplib and copy the files in subdirectories. Thanks again for your help, Israel and Daniel. -------- #!/usr/bin/python import os from ftplib import FTP session = FTP() session.connect('someserver.somedomain.com', port=2188) session.login() rootList = [] dirList = [] session.retrlines('LIST', rootList.append) for i in range (len(rootList)): if rootList[i][0] == 'd': dirList.append(rootList[i]) for j in range (len(dirList)): print dirList[j] session.close() -----Original Message----- From: Israel Evans [mailto:israel@lith.com] Sent: Wednesday, August 08, 2001 12:50 PM To: 'Daniel Coughlin'; rwaters@csmbid.com Cc: tutor@python.org Subject: RE: [Tutor] Using os.path.walk across platforms (fwd) whoops. It think I just sent a blank email out. sorry, trigger finger overload... I don't know if this will work on the nt to unix, I haven't tested it because I don't have access to either one right yet, but I just re3cently did something that used all of the generic os stuff to print out a list of directories and files. This could be tweaked to do the same thing for you, I think.. Anyway here it is... let me know If I'm on crack or anything... ------------------------------------------------- #! e:\ehold\python21 import os, os.path def dircont(rootdir=os.getcwd()): """Types out a list of directories and files in specified directory """ dirlist = [] filelist = [] for item in os.listdir(rootdir): itempath = os.path.join(rootdir, item) if os.path.isdir(itempath): dirlist.append(item) if os.path.isfile(itempath): filelist.append(item) print 'Root Directory: ', rootdir print '\nFiles:' for item in filelist: print '\t',item print '\nDirectories:' for item in dirlist: print '\t',item if __name__ == '__main__': import os, os.path rootdir = raw_input('directory to search:>') dircont(rootdir) raw_input('press any key to end') ---------------------------------------------------------- -----Original Message----- From: Daniel Coughlin [mailto:kauphlyn@speakeasy.org] Sent: Tuesday, August 07, 2001 7:05 PM To: rwaters@csmbid.com Cc: tutor@python.org Subject: Re: [Tutor] Using os.path.walk across platforms (fwd) Hello, I wrote a function that might do the trick for you. I am not familiar enough with the os.path.walk function to know exactly what you are wanting, but I added a new function and rewrote a couple of lines in your script, which returns a list of all the directories in the present working directory. This will work for a script running on unix connecting to an NT filesystem (at least it worked on mine ;-) . It did not work going from NT to Unix. You might need to tweak the regular expression to get it exact. I am sure this can be improved upon however. #!/usr/bin/python import os, string, re from ftplib import FTP def FilterDirectories(listing): templist = [] dirlist = [] for item in listing: if item[0] == 'd': templist.append(re.split(':',item)) for item in templist: dirlist.append(string.strip(re.sub('\d*','',item[1]))) for item in dirlist: print item + ' is a directory..' return dirlist def GetFiles(): listings = [] #going to be a list of retrlines session = FTP() session.connect('myhost', port=21) session.login(user=USERNAME, passwd='*****') #os.path.walk(session.retrlines('LIST'),TheList,None) session.cwd('Music') # delete this line session.retrlines('LIST', listings.append) FilterDirectories(listings) session.close() GetFiles() ----------------------------------------------- The output on my system is : Bell and Sebastian is a directory.. cocteau twins is a directory.. rachels is a directory.. Radiohead is a directory.. Sly & The Family Stone is a directory.. Sonic Youth is a directory.. Talking Heads is a directory.. (These are all, in fact, directories!) Then I suppose you could use the dirlist to loop through each of the directories using chdir. Hope this helps. Daniel PS Hooray for Danny Yoo!!! > >---------- Forwarded message ---------- >Date: Tue, 07 Aug 2001 14:17:34 -0500 >From: Randy Waters >To: "tutor@python.org" >Subject: [Tutor] Using os.path.walk across platforms > >Hello. I have an interesting little challenge. I need to copy files from >an NT server to multiple Linux servers. The Python script needs to >execute on a UNIX server. I am using ftplib and os.path. > >My problem is that the standard 'LIST' in (ftplib) retrlines needs to be >captured to a list so that I can check to see if a entry is a directory >or not. If I were executing only on UNIX/Linux I could use os.path.walk >without a problem, but I am trying to "walk" down an NT path from UNIX. > >This script: > >#!/usr/bin/python > >import os, string >from ftplib import FTP > >def TheList(arg, dirname, names): > for name in names: > print os.path.join(dirname, name) > if os.path.isdir(name): > print name + ' is a directory...' > >def GetFiles(): > session = FTP() > session.connect('myserver.domain.com', port=8282) > session.login() > os.path.walk(session.retrlines('LIST'), TheList, None) > session.close() > return > >GetFiles() >------------------- >Returns this type of information: > >dr-xr-xr-x 1 owner group 0 Dec 7 2000 Co pack >projects >dr-xr-xr-x 1 owner group 0 May 29 14:52 COA >dr-xr-xr-x 1 owner group 0 Aug 2 8:45 HANDLING >-r-xr-xr-x 1 owner group 12800 Nov 4 1996 INFRZPR2.DOC > >------------------- > >If I could test the 1st position for 'd' then I would know that I have >to chdir and read down the tree. Using os.path.isdir does not work >probably because I am running my script on a UNIX server logged into an >NT server. > >If anyone has any ideas I would appreciate it. Thank you and what a >great language! > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > _________________________________________________________________ Get your FREE download of MSN Explorer at http://explorer.msn.com/intl.asp _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From curtis.larsen@Covance.Com Thu Aug 9 22:25:46 2001 From: curtis.larsen@Covance.Com (Curtis Larsen) Date: Thu, 09 Aug 2001 16:25:46 -0500 Subject: [Tutor] "Secure" Input? Message-ID: Thanks to everyone who replied -- that 'getpasswd' module looks like the ticket. (Although it doesn't work on one of my OSes -- I'll probably use much of the supplied script for that one.) Thanks again, Curtis ----------------------------------------------------- Confidentiality Notice: This e-mail transmission may contain confidential or legally privileged information that is intended only for the individual or entity named in the e-mail address. If you are not the intended recipient, you are hereby notified that any disclosure, copying, distribution, or reliance upon the contents of this e-mail is strictly prohibited. If you have received this e-mail transmission in error, please reply to the sender, so that we can arrange for proper delivery, and then please delete the message from your inbox. Thank you. From ppathiyi@cisco.com Fri Aug 10 04:35:05 2001 From: ppathiyi@cisco.com (Praveen Pathiyil) Date: Fri, 10 Aug 2001 09:05:05 +0530 Subject: [Tutor] Interface Functions ... Message-ID: <09a401c1214d$72a15a60$37ef87c0@ppathiyipc> This is a multi-part message in MIME format. ------=_NextPart_000_09A1_01C1217B.8BC9D980 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi All, Sorry for posting my question again. I thought that may be = nobody answered my question because the subject of the mail was "XML = Parser" !!! Thanks, Praveen. ___________________________________________ Can someone explain the concept behind the interface functions and how = python achieves this by having classes for these functions ? I guess it = is implemented as abstract base classes and we are supposed to have = derived classes of our own where we should override the functions with = our own function implementations. But a formal explanation would be a = great thing ..... ---------------------------------------------------------- ------=_NextPart_000_09A1_01C1217B.8BC9D980 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
    Hi All,
     
            Sorry for posting my question = again.=20 I thought that may be nobody answered my question because the subject of = the=20 mail was "XML Parser" !!!
     
    Thanks,
    Praveen.
    ___________________________________________
     
    Can someone explain the concept behind the interface functions and = how=20 python achieves this by having classes for these functions ? I guess it = is=20 implemented as abstract base classes and we are supposed to have derived = classes=20 of our own where we should override the functions with our own function=20 implementations. But a formal explanation would be a great thing = .....
     
    ----------------------------------------------------------
    =
     
     
    ------=_NextPart_000_09A1_01C1217B.8BC9D980-- From newsreport@stockrage.com Fri Aug 10 09:21:04 2001 From: newsreport@stockrage.com (newsreport@stockrage.com) Date: Fri, 10 Aug 2001 03:21:04 -0500 Subject: [Tutor] SPECIAL INVESTMENT REPORT on CBYI Message-ID: <200108100821.DAA27382@ns1.canadawebhouse.com> Calbay International Report IMPORTANT MESSAGE FROM SENDER!

    Please read our disclaimer on this profile on Calbay.

    FEATURED COMPANY

    Ticker Symbol: OTC:CBYI

    COMPANY NAME: Cal-Bay International

    Company homepage: http://www.calbayinc.com

     

    Cal-Bay International (OTC:CBYI) is one of the fastest growing companies in distributing environmental, process and safety equipment instrumentation and related products and services. There is an explosion in the safety instrumentation industry with the need for more power plants and cheap fuel. Cal-Bay International is a major benefactor of the growing need for cheap fuel both oil and natural gas by supplying the specialized moisture analyzers for industrial applications in natural gas production and transmission, specialty/pure gas production.

    CBYI is a very profitable company that is rapidly expanding in the business of "SMELL TECHNOLOGY" analyzers. These analyzers have an established market in leak detection and monitoring in most chemical, oil and pipeline industries. Every airport passenger, grocery store item, restaurant order, hospital patient, package and container coming into the United States will be monitored using this type of "SMELL TECHNOLOGY" in the next decade.

    The company is fully reporting. There are 21,390,000 total outstanding shares, most of which are very closely held. The float contains less than 1,000,000 shares. The stock has very nice support between $1.00 and $1.30, but should enjoy rapid and significant appreciation as developments are made public, and as market awareness grows for this new company. We expect it to move near or over $2 in the near term. Overall, however, we consider this to be a great candidate for a long term hold with tremendous upside potential, and our 1 year target price is $4.

    Some highlights regarding CBYI :

    • CBYI has an excellent management team with an impressive client list including: Anheuser-Busch, Chevron Refining, Mitsubishi Heavy Industries, GE-Energy & Environmental Research, the U.S. Air Force, and several Universities along the California coast.

      CBYI is very unique since it also is focused on the data processing behind smell technology in developing Internet based software for complex data management solutions. This software mimics the way the brain interprets complex sensory information using pattern matching algorithms.

    • Smell technology using analyzers will be found in almost every application of everyday life. The most effected areas are hazardous materials detection, process control, food quality and bacteria identification, and medical diagnosis and monitoring. Smell technology is already an established industry in current leak detection and monitoring in most chemical companies, pipeline industry, and with trained dogs in customs to airport security.

    • CBYI has been in business since 1976 and is a fully reporting and SEC compliant company. CBYI is a very profitable company is on track to beat all earnings estimates with its recent growth.

    • CBYI has just recently filed for trading on the NASD OTCBB. Cal-Bay International, Inc. recently filed it's form 10-SB and will likely be listed BB in the next 90 to 120 days.

    • CBYI has SEVERAL exclusive contracts.

    • The current industry market for safety, environmental, and monitoring analyzers exceed revenues of $900,000,000. Estimates today indicate that there could be as much as $25 billion in revenues from smell technology by the end of 2005. With current Revenue project growth of 150% year over year Cal-Bay International is well poised to in the smell technology market. The smell technology market should enjoy a triple digit growth rate for the next five or more years.

    • The expansion opportunity in this industry is encouraged by governmental grants in the detection and clean-up of retired military sites through-out the world. This assures tremendous revenue growth for CBYI in the upcoming years.

    You can read many more details at http://www.calbayinc.com

    This company is new and yet to be fully discovered by the overall market. As with all microcaps, a certain amount of volatility and risk are to be expected in exchange for a potentially fantastic upside. We encourage all to do further research before investing.

    Happy Investing!

    IMPORTANT MESSAGE!

    This message is sent in compliance of the new e-mail bill section 301. Per section 301, Paragraph (a) (2) (C) of S. 1618, further transmissions to you by the sender of this e-mail will be stopped at no cost to you. This message is not intended for residents in the state of WA, NV, CA & VA. Screening of addresses has been done to the best of our technical ability. If you are a Washington, Virginia or California resident please remove yourself. We respect all removal requests.

    To discontinue receipt of further notice and to be removed from our database, please go to the bottom of this email and click on the link to unsubscribe. Any attempts to disrupt the removal e-mail address etc., will not allow us to be able to retrieve and process the removal requests.

    ---------------------------------------------------------------------------
    To be unsubscribed from the mailing list, simply click on the link below:
    Unsubscribe tutor@python.org


    From Charlie Clark Fri Aug 10 09:29:42 2001 From: Charlie Clark (Charlie Clark) Date: Fri, 10 Aug 2001 10:29:42 +0200 Subject: [Tutor] Python Monks? References: Message-ID: <00038b28c6f3195a_mailit@mail.isis.de> >I know this is a really, really, obvious suggestion - but Zope + Squishdot >would do the job (or at least /a/ job! ) with near-zero development >resource. hear! hear! Charlie From Charlie Clark Fri Aug 10 09:37:29 2001 From: Charlie Clark (Charlie Clark) Date: Fri, 10 Aug 2001 10:37:29 +0200 Subject: [Tutor] Help with vars() Message-ID: <00038b28e2c6ccbe_mailit@mail.isis.de> I'd like to use vars() in together with a database command (Marc Andrй Lemburg's mxODBC) but seem to have missed something. articles = {'sternzeichen': 'Wassermann', 'text': 'Es wird besser', 'headline': 'Horoskop f\xc3\xbcr Peter'} when I use insert = "%headline, %text, %sternzeichen" %vars(articles) I get a TypeError: TypeError: vars() argument must have __dict__ attribute but articles is a dictionary... what screamingly obvious thing am I missing? Charlie From dyoo@hkn.eecs.berkeley.edu Fri Aug 10 10:18:50 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 10 Aug 2001 02:18:50 -0700 (PDT) Subject: [Tutor] Help with vars() In-Reply-To: <00038b28e2c6ccbe_mailit@mail.isis.de> Message-ID: On Fri, 10 Aug 2001, Charlie Clark wrote: > I'd like to use vars() in together with a database command (Marc Andr=E9= =20 > Lemburg's mxODBC) but seem to have missed something. >=20 > articles =3D {'sternzeichen': 'Wassermann', 'text': 'Es wird besser',=20 > 'headline': 'Horoskop f\xc3\xbcr Peter'} >=20 > when I use > insert =3D "%headline, %text, %sternzeichen" %vars(articles) Hi Charlie. Let's take a look: ### >>> articles =3D {'sternzeichen': 'Wassermann', 'text': 'Es wird besser', =2E.. 'headline': 'Horoskop f\xc3\xbcr Peter'} >>> vars(articles) Traceback (most recent call last): File "", line 1, in ? TypeError: vars() argument must have __dict__ attribute >>> print vars.__doc__ vars([object]) -> dictionary =20 Without arguments, equivalent to locals(). With an argument, equivalent to object.__dict__. ### I see. vars() is meant to grab all the variables out of something like a module, but it appears that we can't do the same on a dictionary. The error message is somewhat confusing: the online docs should make it more clear that not just any old object will do... hmmm. I'll have to think about a good reason why it behaves that way. > I get a TypeError: > TypeError: vars() argument must have __dict__ attribute >=20 > but articles is a dictionary... what screamingly obvious thing am I > missing? Start screaming. *grin* We won't need to call vars() at all: we can just do the interpolation directly with the dictionary that's in our hands: ### >>> insert =3D "%(headline)s, %(text)s, %(sternzeichen)s" % articles >>> print insert Horoskop fr Peter, Es wird besser, Wassermann ### Note: the string formatting above requires us to put the variables in the '%(foo)s' sorta format --- the trailing 's' doesn't stand for plurality, but for 'string'ality. Hope this helps! From Charlie Clark Fri Aug 10 10:33:29 2001 From: Charlie Clark (Charlie Clark) Date: Fri, 10 Aug 2001 11:33:29 +0200 Subject: [Tutor] Help with vars() References: Message-ID: <00038b29ab03b9ac_mailit@mail.isis.de> >Start screaming. *grin* We won't need to call vars() at all: we can just >do the interpolation directly with the dictionary that's in our hands: > >### >>>> insert = "%(headline)s, %(text)s, %(sternzeichen)s" % articles >>>> print insert >Horoskop fr Peter, Es wird besser, Wassermann >### > > >Note: the string formatting above requires us to put the variables in the >'%(foo)s' sorta format --- the trailing 's' doesn't stand for plurality, >but for 'string'ality. > >Hope this helps! Yes, it does but it's confusing and isn't explicit in the documentation. %s(name) or %d(name) would make more sense to me. Charlie From lonetwin Fri Aug 10 11:01:12 2001 From: lonetwin (lonetwin) Date: Fri, 10 Aug 2001 15:31:12 +0530 (IST) Subject: [Tutor] Help with vars() In-Reply-To: <00038b29ab03b9ac_mailit@mail.isis.de> Message-ID: On Fri, 10 Aug 2001, Charlie Clark wrote: >>Start screaming. *grin* We won't need to call vars() at all: we can just >>do the interpolation directly with the dictionary that's in our hands: >> >>### >>>>> insert = "%(headline)s, %(text)s, %(sternzeichen)s" % articles >>>>> print insert >>Horoskop fr Peter, Es wird besser, Wassermann >>### >> >> >>Note: the string formatting above requires us to put the variables in the >>'%(foo)s' sorta format --- the trailing 's' doesn't stand for plurality, >>but for 'string'ality. >> >>Hope this helps! >Yes, it does but it's confusing and isn't explicit in the documentation. >%s(name) or %d(name) would make more sense to me. Ehe....I didn't know about the %(foo)[s|d|whatever] format string, all this time I was doing things like (for the example above): insert = "%s, %s, %s" % (articles['headline'], articles['text'], articles['sternzeichen']) Now, I'm curious, is this a *BAD THING* to do ??? Peace Steve ----------------------------------------- bug, n: A son of a glitch. ----------------------------------------- From Charlie Clark Fri Aug 10 11:18:33 2001 From: Charlie Clark (Charlie Clark) Date: Fri, 10 Aug 2001 12:18:33 +0200 Subject: [Tutor] Help with vars() References: Message-ID: <00038b2a4c30daa9_mailit@mail.isis.de> >Ehe....I didn't know about the %(foo)[s|d|whatever] format string, all this > time I was doing things like (for the example above): > > insert = "%s, %s, %s" % (articles['headline'], articles['text'], >articles['sternzeichen']) > > Now, I'm curious, is this a *BAD THING* to do ??? http://starship.python.net/quick-ref1_52.html and search for vars() as it's not in the standard documentation I don't think what you do is bad as I had to do it like that myself but it is a bit clumsy particularly when you have a lot of keys. Charlie From patrick@enterprise-hr.com Fri Aug 10 12:10:23 2001 From: patrick@enterprise-hr.com (P Kirk) Date: Fri, 10 Aug 2001 12:10:23 +0100 Subject: [Tutor] Certification Message-ID: <20010810121023.A10974@enterprise.kirks.net> Hi all, Is there a certification program for Python? -- Patrick "sig free and joyful"" Kirk GSM: +44 7876 560 646 ICQ: 42219699 From rob@jam.rr.com Fri Aug 10 13:27:38 2001 From: rob@jam.rr.com (Rob Andrews) Date: Fri, 10 Aug 2001 07:27:38 -0500 Subject: [Tutor] Certification References: <20010810121023.A10974@enterprise.kirks.net> Message-ID: <3B73D33A.8A30A3BA@jam.rr.com> P Kirk wrote: > > Hi all, > > Is there a certification program for Python? > -- The only Python certification I have seen is the Brainbench Python 1.5 certification. This is taken online via web browser, costs about $20 USD, and is open-book (so you can keep all your references handy while taking the test). They use the honor system, trusting you not to have Danny Yoo and Tim Peters secretly helping you out. Brainbench tests use the type of test that adapts itself to your skill level based on your correct answers as you go. Everyone is asked the same number of questions, but people who know more are given a chance to prove it. I have 5 Brainbench certifications (but not in Python) and can vouch for them. The tests do challenge. Rob -- As foretold by Nostradamus.... Useless Python! http://www.lowerstandard.com/python From rob@jam.rr.com Fri Aug 10 13:45:45 2001 From: rob@jam.rr.com (Rob Andrews) Date: Fri, 10 Aug 2001 07:45:45 -0500 Subject: [Tutor] Python Books References: Message-ID: <3B73D779.5E710943@jam.rr.com> What I'm missing is a good > introduction to object oriented programming with Python for people new > to both and the online documentation should include more examples. > Learning Python (Lutz/Ascher) and Core Python Programming (Chun) each have discussions of OOP, and Chun seems to explain it nicely. My own experience learning Python OOP has been that you can code even simple scripts and pick up some OOP by chance. Python has so much OOP snuck in, that if you practice up on your prodedural/functional programming in Python for a few months, you will very likely have picked up some of the basics nearly by accident. Another really fine resource for this sort of thing is the Python Tutor archives (http://mail.python.org/pipermail/tutor/). I have been blown away enough by some of the explanations provided by the Tutor list to ponder the idea of a Python Tutor anthology. A nice introductory book could be pieced together from the discussions of this list. If you look at the available OOP documentation for Python and still want more discussion of OOP in general, check out Bruce Eckel's site (http://www.mindview.net/Books). He is slowly working on a Thinking In Python book, but his discussions of OOP tucked away in Thinking in Java and Thinking in C++ are pretty great. As Useless Python enters its next stage of evolution (which is in development now, thanks largely to the assistance of Tesla Coil), I hope to see more people taking scripts there now and submitting new versions of those scripts re-written in OOP, with more efficient choices, etc. A few people have done this already, but we need to decide how to reorganize it all to make these connections more obvious. Anyone with suggestions or contributions is welcome to toss in your $.02 worth. Should we divide by categories, dish up Python Server Pages, add some sort of Useless search engine, etc.? I'm slightly familiar with Zipe, less so with Squishdot. I need more coffee, Rob -- As foretold by Nostradamus.... Useless Python! http://www.lowerstandard.com/python From gyromagnetic@excite.com Fri Aug 10 14:57:24 2001 From: gyromagnetic@excite.com (Leona Euler) Date: Fri, 10 Aug 2001 06:57:24 -0700 (PDT) Subject: [Tutor] Issues with initializing lists Message-ID: <7358884.997451844526.JavaMail.imail@digger.excite.com> Hi, I am a bit confused about the usage of lists in Python. For an application I am writing, I would like to create a list of lists with some default values, and then fill in certain items in the list later. As an example: >>> l1=[[None]*3]*4 >>> l1 [[None, None, None], [None, None, None], [None, None, None], [None, None, None]] Now, suppose I want to fill in the second item in the second sublist. I try >>> l1[1][1]='hello' Then 'l1' looks like >>> l1 [[None, 'hello', None], [None, 'hello', None], [None, 'hello', None], [None, 'hello', None]] Note how 'hello' has propagated to each sublist. Why is this? I could do l1=[] >>> for i in range(4): ... l1.append([]) ... for j in range(3): ... l1[i].append(None) ... l1[1][1]='hello' >>> l1 [[None, None, None], [None, 'hello', None], [None, None, None], [None, None, None]] This looks fine. But this approach really seems excessive. My real question is how do I conveniently initialize such a list so that I can later fill in the sublists? Thanks. -Brad _______________________________________________________ Send a cool gift with your E-Card http://www.bluemountain.com/giftcenter/ From r.b.rigilink@chello.nl Fri Aug 10 16:01:55 2001 From: r.b.rigilink@chello.nl (Roeland Rengelink) Date: Fri, 10 Aug 2001 17:01:55 +0200 Subject: [Tutor] Issues with initializing lists References: <7358884.997451844526.JavaMail.imail@digger.excite.com> Message-ID: <3B73F763.679722B2@chello.nl> Hi Brad, This one bites everyone sooner or later. To show what's going on, let me give a simpler example first: >>> l1 = [1, 2, 3] # create a list and let l1 refer to that list >>> l2 = l1 # let l2 refer to the object l1 is referring to >>> l1[1] = 'Oops' # let item 1 in the object l1 is referring to, refer to 'Oops' >>> l2 # show the object l2 is referring to [1, 'Oops', 3] >>> l1 is l2 # are l1 and l2 referring to the same object ? 1 # yes Leona Euler (aka Brad) wrote: > > Hi, > I am a bit confused about the usage of lists in Python. For an application I > am writing, I would like to create a list of lists with some default values, > and then fill in certain items in the list later. > > As an example: > >>> l1=[[None]*3]*4 Here a list is created with four references to a list containing 3 None objects I.e. equivalent to: >>> l0 = [None, None, None] >>> l1 = [l0, l0, l0, l0] > >>> l1 > [[None, None, None], [None, None, None], [None, None, None], [None, None, > None]] > > Now, suppose I want to fill in the second item in the second sublist. I try > >>> l1[1][1]='hello' > > Then 'l1' looks like > > >>> l1 > [[None, 'hello', None], [None, 'hello', None], [None, 'hello', None], [None, > 'hello', None]] > > Note how 'hello' has propagated to each sublist. > > Why is this? > Because the second sublist refers to the same list object as the first, third and fourth sublist. > I could do > > l1=[] > >>> for i in range(4): > ... l1.append([]) > ... for j in range(3): > ... l1[i].append(None) > ... > l1[1][1]='hello' > >>> l1 > [[None, None, None], [None, 'hello', None], [None, None, None], [None, None, > None]] > > This looks fine. But this approach really seems excessive. > Nevertheless, this is the right approach. You could simplify this somewhat with: >>> l = [] >>> for i in range(4): ... l.append([None]*3) Hope this helps, Roeland -- r.b.rigilink@chello.nl "Half of what I say is nonsense. Unfortunately I don't know which half" From Eastwoodmarkw@cs.com Fri Aug 10 16:09:32 2001 From: Eastwoodmarkw@cs.com (Eastwoodmarkw@cs.com) Date: Fri, 10 Aug 2001 11:09:32 EDT Subject: [Tutor] 1.5.2 threading, wxDialog and wxstaticText Message-ID: <96.185503fc.28a5532c@cs.com> Hi - I'm new to python. Using threads and wxDialog (modeless) with wxStaticText. When using threads(derived Threading class) to run a function that instantiates a class instance ........ the wxStaticText object fails to initialise itself in the dialog until all prior threads are run. I've tried using sleep, wxSleep(no good without the wxApp derived class instance - i've found) but even sleep does not allow the wxStaticText intial message to be displayed in the dialog - only does once all other threads have run. So, todate - using wxDialog with wxStaticText and then periodic ...SetLabel() does not work using threads - even the initial text output defined prior to ...Show(true) does not display until all 'controlled' threads have run. A nice solution would be a modeless frame or panel. The probable solution is to upgrade python but this is not an option. So, does anyone know how I can build a wxGauge(progress), wxStaticText stuff in a wxDialog with real time updates using threads? Cheers Mark From rob@jam.rr.com Fri Aug 10 17:19:00 2001 From: rob@jam.rr.com (Rob Andrews) Date: Fri, 10 Aug 2001 11:19:00 -0500 Subject: [Tutor] Tesla Coil's more Useless than ever Message-ID: <3B740974.D5A8D546@jam.rr.com> Just FYI: Tesla Coil has added a new snazzy look to Useless Python, although if you use a browser that does not display .png images, there may be issues. Among the new additions is the first of a series of images people can use to brag about their contributions to Useless. For a site designed and maintained by Python Tutor volunteers,the site looks nice, does it not? And with a quick count of about 130 .py files available for Python newbies to play with, the Python Tutor community has already created what I think is one of the most promising CP4E-ish projects around. I've got to parse that log file.... Rob -- Pythonistas rock! Useless Python! http://www.lowerstandard.com/python From tescoil@irtc.net Fri Aug 10 17:59:43 2001 From: tescoil@irtc.net (Tesla Coil) Date: Fri, 10 Aug 2001 11:59:43 -0500 Subject: [Tutor] Tesla Coil's more Useless than ever References: <3B740974.D5A8D546@jam.rr.com> Message-ID: <3B7412FF.93F9F141@irtc.net> On 10 August 2001, Rob Andrews wrote: > Tesla Coil has added a new snazzy look to Useless > Python, although if you use a browser that does > not display .png images, there may be issues. And if it's not Lynx, then the issues are the developers who wrote your browser. ;) From tjenkins@devis.com Fri Aug 10 18:33:38 2001 From: tjenkins@devis.com (Tom Jenkins) Date: Fri, 10 Aug 2001 13:33:38 -0400 Subject: [Tutor] Issues with initializing lists References: <7358884.997451844526.JavaMail.imail@digger.excite.com> Message-ID: <3B741AF2.4070608@devis.com> Hello, Yep this one bites _everyone_ at some point. Lets take a look... Leona Euler wrote: > Hi, > > As an example: > >>>>l1=[[None]*3]*4 >>>>l1 >>>> > [[None, None, None], [None, None, None], [None, None, None], [None, None, > None]] What is happening here is that 4 copies of the _same_ list are being generated. We can confirm this in the interpreter: >>> l1 = [[None]*3]*4 >>> print l1 [[None, None, None], [None, None, None], [None, None, None], [None, None, None]] >>> for sub in l1: ... print id(sub) ... 17189420 17189420 17189420 17189420 >>> Note the print id(sub) call... lets see what the docs say: >>> id.__doc__ "id(object) -> integer\n\nReturn the identity of an object. This is guaranteed to be unique among\nsimultaneously existing objects. (Hint: it's the object's memory address.)" >>> Ok so we see that they all point to the same memory location. [snip] > > I could do > > l1=[] > >>>>for i in range(4): >>>> > ... l1.append([]) > ... for j in range(3): > ... l1[i].append(None) > ... > l1[1][1]='hello' > >>>>l1 >>>> > [[None, None, None], [None, 'hello', None], [None, None, None], [None, None, > None]] > Lets look at this one in the interpreter: >>> l2 = [] >>> for i in range(4): ... l2.append([]) ... for j in range(3): ... l2[i].append(None) ... >>> print l2 [[None, None, None], [None, None, None], [None, None, None], [None, None, None]] >>> for sub in l2: ... print id(sub) ... 15857188 15854956 15852996 15858828 >>> Ok different numbers, so different memory locations, so different objects. So now we know _why_ it was working / not working in the previous two algorithms. > This looks fine. But this approach really seems excessive. > Lets see if we can tighten this up. >>> l3 = [] >>> for i in range(4): ... l3.append([None]*3) ... >>> print l3 [[None, None, None], [None, None, None], [None, None, None], [None, None, None]] >>> for sub in l3: ... print id(sub) ... 17236724 15244756 17238524 17238444 >>> ok, cool that one is shorter and gives us different ids. Now lets see if there is another way. Basically anytime you see a simple loop like above, you should be able to replace it with a list comprehension (on python 2 and above). So lets try that... >>> l4 = [[None]*3 for x in range(4)] >>> print l4 [[None, None, None], [None, None, None], [None, None, None], [None, None, None]] >>> for sub in l4: ... print id(sub) ... 17182676 17182004 17182380 17236980 >>> >>> l4[1][1] = 'hello' >>> print l4 [[None, None, None], [None, 'hello', None], [None, None, None], [None, None, None]] >>> Viola! -- Tom Jenkins devIS - Development Infostructure http://www.devis.com From RWare@INTERPLASTIC.com Fri Aug 10 18:35:36 2001 From: RWare@INTERPLASTIC.com (Ryan Ware) Date: Fri, 10 Aug 2001 12:35:36 -0500 Subject: [Tutor] Python helps defeat Code Red Message-ID: <8794B3B640FED2118D8600C00D0020A593F790@ipserver2.interplastic.com> > Below is a post I clipped from the Twin Cities Linux Users Group. > > Looks like Python works very well for short hacks like that other language > that begins with a "p" also. :) > > This is up on #debian's info bot: > http://www.stone.nu/projects/python_scripts/code_red_warn.py.gz > > The script goes through your access.log, finds the ip from any default.ida > requests, and then sends a http request to the hacked box, forcing > root.exe to start a browser on the users system that directs them to a > warning page. > > It's neat. Not legal I'm sure, but neat non the less. > From dsh8290@rit.edu Fri Aug 10 18:54:27 2001 From: dsh8290@rit.edu (dman) Date: Fri, 10 Aug 2001 13:54:27 -0400 Subject: [Tutor] Python helps defeat Code Red In-Reply-To: <8794B3B640FED2118D8600C00D0020A593F790@ipserver2.interplastic.com>; from RWare@interplastic.com on Fri, Aug 10, 2001 at 12:35:36PM -0500 References: <8794B3B640FED2118D8600C00D0020A593F790@ipserver2.interplastic.com> Message-ID: <20010810135427.B1296@harmony.cs.rit.edu> On Fri, Aug 10, 2001 at 12:35:36PM -0500, Ryan Ware wrote: | > Below is a post I clipped from the Twin Cities Linux Users Group. | > | > Looks like Python works very well for short hacks like that other language | > that begins with a "p" also. :) Cool. I've only seen perl examples so far. What interests me is the possiblity of dermining the requestor's IP address from within a CGI script. Call the CGI script /default.ida and it will be the infected system's fault that they ran the script :-). You can claim that you are generating the web page by "screen scraping" another web page (at /scripts/root.exe of course). -D From lonetwin@yahoo.com Fri Aug 10 15:41:11 2001 From: lonetwin@yahoo.com (steve) Date: Fri, 10 Aug 2001 20:11:11 +0530 Subject: Fwd: Re: [Tutor] Issues with initializing lists Message-ID: <01081020111101.23308@mercury.in.cqsl.com> Hi there, I don't know why what you said is happening, is happening...!! It looks mighty strange, though with list comprehensions you can get what you want= =2E.. code: =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D >>> l =3D [ [None]*3 for x in range(0,4) ] >>> l [[None, None, None], [None, None, None], [None, None, None], [None, None, None]] >>> l[1][1] =3D 'foo' >>> l [[None, None, None], [None, 'foo', None], [None, None, None], [None, None= , None]] =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D hope that helps....and hope some of the gurus explain this deep mystery s= oon =2E..:) Peace Steve > Hi, > I am a bit confused about the usage of lists in Python. For an applicat= ion > I am writing, I would like to create a list of lists with some default > values, and then fill in certain items in the list later. > > As an example: > >>> l1=3D[[None]*3]*4 > >>> l1 > > [[None, None, None], [None, None, None], [None, None, None], [None, Non= e, > None]] > > Now, suppose I want to fill in the second item in the second sublist. I= try > > >>> l1[1][1]=3D'hello' > > Then 'l1' looks like > > >>> l1 > > [[None, 'hello', None], [None, 'hello', None], [None, 'hello', None], > [None, 'hello', None]] > > Note how 'hello' has propagated to each sublist. > > Why is this? > > > I could do > > l1=3D[] > > >>> for i in range(4): > > ... =09l1.append([]) > ... =09for j in range(3): > ... =09=09l1[i].append(None) > ... > l1[1][1]=3D'hello' > > >>> l1 > > [[None, None, None], [None, 'hello', None], [None, None, None], [None, > None, None]] > > This looks fine. But this approach really seems excessive. > > My real question is how do I conveniently initialize such a list so tha= t I > can later fill in the sublists? ----------------------------------------- bug, n: =09=09A son of a glitch. ----------------------------------------- ------------------------------------------------------- --=20 ----------------------------------------- bug, n: =09=09A son of a glitch. ----------------------------------------- From Charlie Clark Fri Aug 10 19:55:09 2001 From: Charlie Clark (Charlie Clark) Date: Fri, 10 Aug 2001 20:55:09 +0200 Subject: [Tutor] Help with Parsing HTML files [html/OOP] References: Message-ID: <00038b3183b7bd4b_mailit@mail.isis.de> Danny Yoo gave me the following example: >class EmphasisGlancer(htmllib.HTMLParser): > def __init__(self): > htmllib.HTMLParser.__init__(self, > formatter.NullFormatter()) > self.in_bold = 0 > self.in_underline = 0 > > def start_b(self, attrs): > print "Hey, I see a bold tag!" > self.in_bold = 1 > > def end_b(self): > self.in_bold = 0 > > def start_u(self, attrs): > print "Hey, I see some underscored text!" > self.in_underline = 1 > > def end_u(self): > self.in_underline = 0 > > > def start_blink(self, attrs): > print "Hey, this is some heinously blinking test... *grrrr*" > > > def handle_data(self, data): > if self.in_bold: > print "BOLD:", data > elif self.in_underline: > print "UNDERLINE:", data >### Well, I've had more success than I would have imagined possible but I'm still struggling with some stuff in this sisyphian task. What I'm still having difficulty with: 1) Nested tags
    and html entities cause difficulties as they can be included with impunity inside other tags. I've been setting flags and collecting data only to get tripped up by
    or an html-entity and seeing as I'm parsing German text there a lot of those. 2) Doing work only on specific attributes I've written little string searches to fast forward in a page and reduce the size of what has to be parsed. For the same reason I'd like to be able to stop parsing on a specific event. I've now got a particularly nasty webpage which distributes its relevant content in various blocks and triggering on simple anchors catches too much data. How do I go about this? The specific example would be checking the colour of a specific table cell: there doesn't seem to be predefined methods for tables in htmllib so do they all get handled with "unknown tag"? Would the thing to do be to use a def start_td or a do_td? and what do the _bgn methods do? The reason I ask is because the example in the "Python standard library" works with "anchor_bgn" and not "do_a" or "start_a" I'm thinking along the lines of self.text = 0 # flag for whether I need the text def ....td(self, attrs) if self.bgcolor = "eeeeff": store data, nested_tags else: fast_foward(next_td) many thanx, Charlie From csmith@blakeschool.org Fri Aug 10 21:52:35 2001 From: csmith@blakeschool.org (Christopher Smith) Date: Fri, 10 Aug 2001 15:52:35 -0500 Subject: [Tutor] Re: Algebraic symbol manipulation program idea Message-ID: Shelley Walsh wrote: | I am a mathematics instructor and lately I have been learning Python | partly out of fascination with its potential for helping to explain | algebra. Yesterday I downloaded a symbol manipulation program called | Pythonica and got to thinking that there ought to be an easier way to I read the whole post and am interested in this sort of thing as well but don't have time to respond much now. Just wanted to note that I, too, just found Pythonica in my search for a symbolic manipulation program and found a bit of a parsing bug. When given 2*3+2^2/3 Pythonica returns: in FullForm: Divide[Plus[Times[2,3],Power[2,2]],3] evaluates to: 3.33333333333 but it should probably be something like: Plus[Times[2,3],Divide[Power[2,2],3]] and evaluate to 7.33333333333 /c From allan.crooks@btinternet.com Sat Aug 11 01:08:40 2001 From: allan.crooks@btinternet.com (Allan Crooks) Date: Sat, 11 Aug 2001 01:08:40 +0100 Subject: [Tutor] Hashing Message-ID: <3B748598.14470.2A7F06F@localhost> Hi, Does anyone know exactly how the hash method derives a hash for tuples? Or strings? >>> a, b, c, d = (1,), (2,), (3,), (4,) >>> map (hash, [a, b, c, d]) [-1660579480, -1660579477, -1660579478, -1660579475] The above code does seem slightly bewildering to me, anyone got any ideas? Allan. From kalle@gnupung.net Sat Aug 11 01:39:04 2001 From: kalle@gnupung.net (Kalle Svensson) Date: Sat, 11 Aug 2001 02:39:04 +0200 Subject: [Tutor] Hashing In-Reply-To: <3B748598.14470.2A7F06F@localhost>; from allan.crooks@btinternet.com on Sat, Aug 11, 2001 at 01:08:40AM +0100 References: <3B748598.14470.2A7F06F@localhost> Message-ID: <20010811023904.A5460@gandalf> [Allan Crooks] > Hi, > > Does anyone know exactly how the hash method derives a hash > for tuples? Or strings? > > >>> a, b, c, d = (1,), (2,), (3,), (4,) > >>> map (hash, [a, b, c, d]) > [-1660579480, -1660579477, -1660579478, -1660579475] > > The above code does seem slightly bewildering to me, anyone got > any ideas? >From the Python source code: static long tuplehash(PyTupleObject *v) { register long x, y; register int len = v->ob_size; register PyObject **p; x = 0x345678L; p = v->ob_item; while (--len >= 0) { y = PyObject_Hash(*p++); if (y == -1) return -1; x = (1000003*x) ^ y; } x ^= v->ob_size; if (x == -1) x = -2; return x; } long PyObject_Hash(PyObject *v) { PyTypeObject *tp = v->ob_type; if (tp->tp_hash != NULL) return (*tp->tp_hash)(v); if (tp->tp_compare == NULL && RICHCOMPARE(tp) == NULL) { return _Py_HashPointer(v); /* Use address as hash value */ } /* If there's a cmp but no hash defined, the object can't be hashed */ PyErr_SetString(PyExc_TypeError, "unhashable type"); return -1; } This basically means that a tuple hash is a function of the individual objects' hashes. Individual objects are hashed in different ways depending on the tp_hash field of the type (tp_hash of PyTuple_Type is tuplehash). Check out different objects and their hash functions in the Objects subdirectory of the source code distribution. Web access to current CVS source code is at http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/python/dist/src/ Peace, Kalle -- [ kalle@gnupung.net ][ Thought control, brought to you by the WIPO! ] [ http://gnupung.net/ ][ http://anti-dmca.org/ http://eurorights.org/ ] From wrong@crosswinds.net Sat Aug 11 02:15:16 2001 From: wrong@crosswinds.net (charlie derr) Date: Fri, 10 Aug 2001 21:15:16 -0400 Subject: [Tutor] Hashing In-Reply-To: <3B748598.14470.2A7F06F@localhost> Message-ID: +-----Original Message----- +From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of +Allan Crooks +Sent: Friday, August 10, 2001 8:09 PM +To: tutor@python.org +Subject: [Tutor] Hashing + + +Hi, + +Does anyone know exactly how the hash method derives a hash +for tuples? Or strings? + +>>> a, b, c, d = (1,), (2,), (3,), (4,) +>>> map (hash, [a, b, c, d]) +[-1660579480, -1660579477, -1660579478, -1660579475] + +The above code does seem slightly bewildering to me, anyone got +any ideas? no ideas, but i found something strange while playing around >>> hash((0,)) -1660579479 >>> hash((-1,)) 1660579479 >>> hash((-2,)) 1660579479 aren't these values supposed to be unique? ~c + +Allan. + +_______________________________________________ +Tutor maillist - Tutor@python.org +http://mail.python.org/mailman/listinfo/tutor + From elmlish@onebox.com Sat Aug 11 03:25:42 2001 From: elmlish@onebox.com (Israel C. Evans) Date: Fri, 10 Aug 2001 19:25:42 -0700 Subject: [Tutor] Object Oriented References? and a couple of questions <--LONG Message-ID: <20010811022542.HMEV18626.mta08.onebox.com@onebox.com> Hello all, I'm trying to hack my way into the verdant valley that is Pythonic Object Orientism. Would anybody have any recommendations for info on the subject? Other than general interest in the subject, I'm trying to do something right now, that might work well with OOP(i'd know for sure, if I was more familiar with the subject). The example I have right now goes a little something like this... I've got a Cook who will scan a directory for ingredients, sift them so that we are using only the ingredients we want, and then cook up a bunch of Python Objects. Then I've got a Host who will deal with the Diners and handle all of their requests and make sure everyone gets what they need. I've also got a number of Recipies (object templates) for The Cook to use. This is how I'm thinking I'll lay things out, let me know if this isn't the best OO way to do things. Now I'd like to break down the Cook to highlight some of the questions that I had. The Cook will first scan a directory, and make a list of all the files. This will be his Pantry. He will then Sift through the pantry for the files required by the Recipe. This will create a list of files stripped of their extensions and such that will be refered to as the Ingredients. These Ingredients will be used to Bake a bunch of objects that I plan to use later. When I'm setting up the Cook class I'm thinking the gather(), sift(), and bake() will be methods of the class, and the pantry, ingredients and recipe are all attributes(?). When I set up the __init__function would I want to set it up like this... def __init__(self, pantry, ingredients, recipe): self.pantry = pantry self.ingredients = ingredients self.recipe = recipe and then call the Cook methods to create the values of the attributes(still don't know if that is the right terminology)? If so when would I do that. I'm really foggy on how to properly use classes to create objects and then use those objects. As you can see, I'm in dire need of a good explanation. Sorry for the lengthy rambling message, but any help would be most sincerely appreciated... Thanks, ~Israel~ __________________________________________________ FREE voicemail, email, and fax...all in one place. Sign Up Now! http://www.onebox.com From r.b.rigilink@chello.nl Sat Aug 11 06:19:16 2001 From: r.b.rigilink@chello.nl (Roeland Rengelink) Date: Sat, 11 Aug 2001 07:19:16 +0200 Subject: [Tutor] Re: Algebraic symbol manipulation program idea References: Message-ID: <3B74C054.12989270@chello.nl> Hi Christopher, I'm interested in this stuff too, but I couldn't find the original message you're replying to. Do you have a link somewhere? Roeland Christopher Smith wrote: > > Shelley Walsh wrote: > | I am a mathematics instructor and lately I have been learning Python > | partly out of fascination with its potential for helping to explain > | algebra. Yesterday I downloaded a symbol manipulation program called > | Pythonica and got to thinking that there ought to be an easier way to > > > I read the whole post and am interested in this sort of thing as > well but don't have time to respond much now. Just wanted to note > that I, too, just found Pythonica in my search for a symbolic > manipulation program and found a bit of a parsing bug. > > When given 2*3+2^2/3 Pythonica returns: > > in FullForm: Divide[Plus[Times[2,3],Power[2,2]],3] > evaluates to: 3.33333333333 > > but it should probably be something like: > > Plus[Times[2,3],Divide[Power[2,2],3]] > > and evaluate to 7.33333333333 > > /c > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- r.b.rigilink@chello.nl "Half of what I say is nonsense. Unfortunately I don't know which half" From dyoo@hkn.eecs.berkeley.edu Sat Aug 11 06:44:34 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 10 Aug 2001 22:44:34 -0700 (PDT) Subject: [Tutor] Hashing [And why hash() NEVER returns -1] In-Reply-To: Message-ID: On Fri, 10 Aug 2001, charlie derr wrote: > +Hi, > + > +Does anyone know exactly how the hash method derives a hash > +for tuples? Or strings? > + > +>>> a, b, c, d = (1,), (2,), (3,), (4,) > +>>> map (hash, [a, b, c, d]) > +[-1660579480, -1660579477, -1660579478, -1660579475] > + > +The above code does seem slightly bewildering to me, anyone got > +any ideas? > > no ideas, but i found something strange while playing around > > > >>> hash((0,)) > -1660579479 > >>> hash((-1,)) > 1660579479 > >>> hash((-2,)) > 1660579479 > > aren't these values supposed to be unique? Actually, no; hash values are only guaranteed to be "probably" unique among different objects. Think "Social Security Number". *grin* [note: this message is long, and it involves looking deeply into the Python/C API.] What ends up happening is that certain thing "collide" with the same hash value, and they have to, since there are so many more "things" than integers. A good hash function does try to distribute things as evenly as possible. If you look in some algorithm book, you'll hear about things like "linear probing" or "linear chaining", techniques to deal with hash collisions. Let's take a look at the string hashing function, stripped down to it's C'ish essence, just to get a feel for the thing: /******/ /* (dyoo) I cut some code out to make it easier to read */ static long string_hash(PyStringObject *a) { register int len; register unsigned char *p; register long x; len = a->ob_size; p = (unsigned char *) a->ob_sval; x = *p << 7; while (--len >= 0) x = (1000003*x) ^ *p++; x ^= a->ob_size; if (x == -1) x = -2; return x; } /******/ It's doing some weird bitwise mess with the strings: it takes each character of the string and looks at it as a number, spins it around with some multplication against a prime, twists it with bitwise XORs... It's definitely meant to mess with your head. *grin* There's probably some number theory involved with this function that guarantees that that most strings will get different values. Still, we know that Python integers can only have 2**32 distinct values... ### >>> hash(2**32L) 1 >>> hash(1) 1 ### Better get back to your question: > >>> hash((-1,)) > 1660579479 > >>> hash((-2,)) > 1660579479 > > aren't these values supposed to be unique? All Python hash functions apparently try to avoid return -1 as a hash value. The string_hash() function above forces the hash id to -2 if the function even considered return -1, and the same thing happens with integers too! Take a look: ### static long int_hash(PyIntObject *v) { /* XXX If this is changed, you also need to change the way Python's long, float and complex types are hashed. */ long x = v -> ob_ival; if (x == -1) x = -2; return x; } ### But why? Because '-1' is being used internally by Python as a "sentinel" value. If we take a closer look at the dictobject.c file, we'll see that a lot of Python's internal functions use '-1' to signal that some hideous error has occured: /******/ /*** somewhere in the deep, dark corners of dictobject.h... ***/ if (!PyString_Check(key) || (hash = ((PyStringObject *) key)->ob_shash) == -1) #endif { hash = PyObject_Hash(key); if (hash == -1) { PyErr_Clear(); return NULL; } } /******/ Hmmm.... I wonder... ### >>> class TestNegative1: ... def __hash__(self): return -1 ... >>> instance = TestNegative1() >>> hash(instance) -2 ### Cute. I get the feeling we've gone way too deeply into the C code. We should stop now. *grin* Hope this helps! From r.b.rigilink@chello.nl Sat Aug 11 07:42:37 2001 From: r.b.rigilink@chello.nl (Roeland Rengelink) Date: Sat, 11 Aug 2001 08:42:37 +0200 Subject: [Tutor] Hashing References: Message-ID: <3B74D3DD.296FED76@chello.nl> charlie derr wrote: > > +-----Original Message----- > +From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of > +Allan Crooks > +Sent: Friday, August 10, 2001 8:09 PM > +To: tutor@python.org > +Subject: [Tutor] Hashing > + > + > +Hi, > + > +Does anyone know exactly how the hash method derives a hash > +for tuples? Or strings? > + > +>>> a, b, c, d = (1,), (2,), (3,), (4,) > +>>> map (hash, [a, b, c, d]) > +[-1660579480, -1660579477, -1660579478, -1660579475] > + > +The above code does seem slightly bewildering to me, anyone got > +any ideas? > > no ideas, but i found something strange while playing around > > >>> hash((0,)) > -1660579479 > >>> hash((-1,)) > 1660579479 > >>> hash((-2,)) > 1660579479 > > aren't these values supposed to be unique? > Nope, They couldn't be. hash() should be (is) able map a potentially infinite number of objects to the finite set of integers. Note that integers (except -1, see Danny's reply) are their own hashes, which already uses the set of all possible hash numbers once. Note: hash(hash(x)) == hash(x) for all python objects x When python compares hashes for two objects, and finds they are the same, it will compare objects to determine if they are really the same object. This leads to an interesting result: class A: def __hash__(self): return 1 # instances always the same hash value def __cmp__(self, other): return 0 # instances always compare equal a, b = A(), A() d = {a:'a', b:'b'} print a, b -> <__main__.A instance at 0x814741c> <__main__.A instance at 0x814ba54> print d -> {<__main__.A instance at 0x814741c>: 'b'} and (big surprise): d = {a:'a', 1:'c'} print d -> {<__main__.A instance at 0x814741c>: 'c'} While: class A: def __hash__(self): return 1 # instances always the same hash value def __cmp__(self, other): return 1 # instances always compare unequal a, b = A(), A() d = {a:'a', b:'b'} print a, b -> (<__main__.A instance at 0x81494bc>, <__main__.A instance at 0x81476ac>) print d -> {<__main__.A instance at 0x81494bc>: 'a', <__main__.A instance at 0x81476ac>: 'b'} Have fun, Roeland -- r.b.rigilink@chello.nl "Half of what I say is nonsense. Unfortunately I don't know which half" From sburr@mac.com Sat Aug 11 09:20:37 2001 From: sburr@mac.com (Steven Burr) Date: Sat, 11 Aug 2001 01:20:37 -0700 Subject: [Tutor] Help with vars() In-Reply-To: Message-ID: <20010811081754.YWRL19537.femail42.sdc1.sfba.home.com@localhost> On Friday, August 10, 2001, at 02:18 AM, Danny Yoo wrote: > On Fri, 10 Aug 2001, Charlie Clark wrote: > >> I'd like to use vars() in together with a database command (Marc = Andr=E9 >> Lemburg's mxODBC) but seem to have missed something. >> >> articles =3D {'sternzeichen': 'Wassermann', 'text': 'Es wird besser', >> 'headline': 'Horoskop f\xc3\xbcr Peter'} >> >> when I use >> insert =3D "%headline, %text, %sternzeichen" %vars(articles) > [snip] > Start screaming. *grin* We won't need to call vars() at all: we can=20= > just > do the interpolation directly with the dictionary that's in our hands: > > ### >>>> insert =3D "%(headline)s, %(text)s, %(sternzeichen)s" % articles >>>> print insert > Horoskop fr Peter, Es wird besser, Wassermann > ### But if you really want to use vars, you can: >>> class Blank: ... pass ... >>> article =3D Blank() >>> article.headline =3D "Horoscope for Peter" >>> article.text =3D "Things are looking up!" >>> article.asterisk =3D "Aquarius" >>> print "\n%(headline)s* \n\n%(text)s\n----\n*%(asterisk)s" %=20 vars(article) Horoscope for Peter* Things are looking up! ---- *Aquarius From sburr@mac.com Sat Aug 11 09:24:41 2001 From: sburr@mac.com (Steven Burr) Date: Sat, 11 Aug 2001 01:24:41 -0700 Subject: [Tutor] Help with vars() In-Reply-To: <00038b2a4c30daa9_mailit@mail.isis.de> Message-ID: <20010811082158.YIRF16754.femail34.sdc1.sfba.home.com@localhost> On Friday, August 10, 2001, at 03:18 AM, Charlie Clark wrote: >> Ehe....I didn't know about the %(foo)[s|d|whatever] format string, all >> this >> time I was doing things like (for the example above): >> >> insert = "%s, %s, %s" % (articles['headline'], articles['text'], >> articles['sternzeichen']) >> >> Now, I'm curious, is this a *BAD THING* to do ??? > > http://starship.python.net/quick-ref1_52.html and search for vars() as > it's > not in the standard documentation Au contraire! http://www.python.org/doc/current/lib/built-in-funcs.html i'm-not-a-polyglot-but-i-play-one-on-tv'ly yours, sburrious From rnd@onego.ru Sat Aug 11 10:12:50 2001 From: rnd@onego.ru (Roman Suzi) Date: Sat, 11 Aug 2001 13:12:50 +0400 (MSD) Subject: [Tutor] Windows, Python and me Message-ID: Hello, I am not sure if my question fits here, but I see lots of such questions in c.l.p and probably this one could gather expert answers, easily found later via google. Keywords: Python Win32 Windows DOS prompt path setup start run install CRLF edit editor IDLE For more than 4 years already I am working with Linux. But in order to do packaging of Python related material I need to make it "right" in Windows. And here I understand how difficult things in Windows are (compared to Linux). Below I refer to Win98 SE. 1. After installing Python under Windows, I can't just type "python" in DOS-prompt to run scripts. What is the easy way for the novice to set PATH correctly? ("> start python" works fine). 2. Some tar.gz archives are using LF-line ends (and this is right thing for UNIX or under IDLE). However, such scripts are not editable in NotePad which is fabulous default Windows editor. What is the better choice: to get/provide CR-LF-ed text files or (how?) make users decode text files for themselves? The deadlock is: NotePad can't be used due to LF-ed py-files and IDLE internal editor can't be used because IDLE doesn't support non-latin-1 chars... I could suggest Emacs, but for beginners... They will be pissed off not only for Emacs, but Python alltogether. This way or that solution must be "freely distributable". 3. What is the preferred way to run setup.py script? (MS DOS prompt doesn't work due to the problem no 1 above and if it works, how do I open MS DOS prompt in the needed directory and not in the C:\WINDOWS> ? (using cd or adding some bat or pif files to the directory with unzipped contents is not an option: it makes feel like Python doesn't suit into Windows environment well). Or do I need to get some freeware kind of Norton Editor for such tasks? (What Windows "Explorer" is for, then?) * * * I think, these questions have impact on Python usability under Windows. Probably, the best solution could be adding GUI to Distutils, so running JUST setup.py without options will bring up a dialog with all available options or at least a text-prompt for them (like this is done for Mac which do not have command line). The reason I posted this to Tutor is that probably I need to learn more about Windows+Python to resolve problems stated above. And yes, I have read Distutils docs. (please, tell if I need to reread them). Thank you for answers! Sincerely yours, Roman Suzi -- _/ Russia _/ Karelia _/ Petrozavodsk _/ rnd@onego.ru _/ _/ Saturday, August 11, 2001 _/ Powered by Linux RedHat 6.2 _/ _/ "After a hard day, it's nice to come home to a warm cat." _/ From Charlie Clark Sat Aug 11 11:08:54 2001 From: Charlie Clark (Charlie Clark) Date: Sat, 11 Aug 2001 12:08:54 +0200 Subject: [Tutor] Help with vars() References: <20010811081754.YWRL19537.femail42.sdc1.sfba.home.com@localhost> Message-ID: <00038b3e4785f725_mailit@mail.isis.de> >But if you really want to use vars, you can: > > >>> class Blank: >... pass >... > >>> article = Blank() > >>> article.headline = "Horoscope for Peter" > >>> article.text = "Things are looking up!" > >>> article.asterisk = "Aquarius" > >>> print "\n%(headline)s* \n\n%(text)s\n----\n*%(asterisk)s" % >vars(article) > >Horoscope for Peter* > >Things are looking up! >---- >*Aquarius so vars() acts like a dictionary type wrapper and as such isn't necessary for dictionaries themselves? article.headline in a class is equivalent to article['headline'] in a dictionary in this case? Just different ways of storing and retrieving the same information. mm, can see the drive to unify types and classes to tidy this up. I'm actually storing a dictionary in a class, returning it in a function and assigning the return to a new variable to do further work on. Can probably improve on this once I get better at the whole OOP thing. Thanx Charlie From delirious@atchoo.be Sat Aug 11 16:42:50 2001 From: delirious@atchoo.be (Simon Vandemoortele) Date: Sat, 11 Aug 2001 14:42:50 -0100 Subject: [Tutor] Python function seem to have a memory ??? Message-ID: <01081114425000.07601@shinsekai> I am making my first contact with python through the means of the tutoria= l (http://www.python.org/doc/current/tut/) and I would like some clarificat= ion=20 on the example: --- quote --- Important warning: The default value is evaluated only once. This makes a= =20 difference when the default is a mutable object such as a list or diction= ary.=20 For example, the following function accumulates the arguments passed to i= t on=20 subsequent calls:=20 def f(a, l =3D []): l.append(a) return l print f(1) print f(2) print f(3) This will print=20 [1] [1, 2] [1, 2, 3] --- end quote --- One thing I find astonishing about this is the fact that python functions= =20 seem to have memory; each call of f() leads to a different result ! Does = this=20 mean that the variable 'l' keeps its content even after the function retu= rns=20 ? This seems very strange to me as I have never seen it in other language= s.=20 Some explanation/comments/corrections ? Thx, Simon --=20 If you took all the students that felt asleep in class and laid them end to end, they'd be a lot more comfortable. =09=09-- "Graffiti in the Big Ten" From kalle@gnupung.net Sat Aug 11 14:23:08 2001 From: kalle@gnupung.net (Kalle Svensson) Date: Sat, 11 Aug 2001 15:23:08 +0200 Subject: [Tutor] Python function seem to have a memory ??? In-Reply-To: <01081114425000.07601@shinsekai>; from delirious@atchoo.be on Sat, Aug 11, 2001 at 02:42:50PM -0100 References: <01081114425000.07601@shinsekai> Message-ID: <20010811152308.A8358@gandalf> [Simon Vandemoortele] > > I am making my first contact with python through the means of the tutorial > (http://www.python.org/doc/current/tut/) and I would like some clarification > on the example: > > --- quote --- > Important warning: The default value is evaluated only once. This makes a > difference when the default is a mutable object such as a list or dictionary. > For example, the following function accumulates the arguments passed to it on > subsequent calls: > > def f(a, l = []): > l.append(a) > return l > print f(1) > print f(2) > print f(3) > > This will print > > [1] > [1, 2] > [1, 2, 3] > --- end quote --- > > One thing I find astonishing about this is the fact that python functions > seem to have memory; each call of f() leads to a different result ! Does this > mean that the variable 'l' keeps its content even after the function returns > ? This seems very strange to me as I have never seen it in other languages. This can indeed seem a little weird. The important thing to remember here is that 'l = []' is executed once, when the def statement is executed[1]. With immutable objects, this won't make any difference, as any operations on the object will result in a new object. Mutable objects, though, can be changed. As the default argument is the same every time the function is called, we see the "memory" effect. You may also notice that def g(): return [] def f(a, l = g()): l.append(a) return l print f(1), f(2), f(3) works, but def f(a, l = g()): l.append(a) return l def g(): return [] print f(1), f(2), f(3) doesn't. Confused? Good. Peace, Kalle [1] This is how it looks throught the dis module: def f(a, l): l.append(a) return l becomes: 3 SET_LINENO 3 6 LOAD_CONST 0 () 9 MAKE_FUNCTION 0 12 STORE_NAME 0 (f) def f(a, l = []): l.append(a) return l becomes: 15 SET_LINENO 7 18 BUILD_LIST 0 # <---------------- This is it... 21 LOAD_CONST 1 () 24 MAKE_FUNCTION 1 27 STORE_NAME 0 (f) -- [ kalle@gnupung.net ][ Thought control, brought to you by the WIPO! ] [ http://gnupung.net/ ][ http://anti-dmca.org/ http://eurorights.org/ ] From wrong@crosswinds.net Sat Aug 11 14:43:17 2001 From: wrong@crosswinds.net (charlie derr) Date: Sat, 11 Aug 2001 09:43:17 -0400 Subject: [Tutor] Hashing In-Reply-To: <3B74D3DD.296FED76@chello.nl> Message-ID: +> aren't these values supposed to be unique? +> + +Nope, + +They couldn't be. hash() should be (is) able map a potentially infinite +number of objects to the finite set of integers. Note that integers +(except -1, see Danny's reply) are their own hashes, which already uses +the set of all possible hash numbers once. + thanx very much to both you and Danny -- quite enlightening ~c From lkvam@venix.com Sat Aug 11 15:05:23 2001 From: lkvam@venix.com (Lloyd Kvam) Date: Sat, 11 Aug 2001 10:05:23 -0400 Subject: [Tutor] Python function seem to have a memory ??? References: <01081114425000.07601@shinsekai> Message-ID: <3B753BA3.258367E1@venix.com> The function definition needs to store the default value. In the common case that will be a reference to an immutable constant such as None or 2. This example sets the default to a container (a list). That container is not garbage collected so long as the function exists since the function's default is a reference to the container. Thus changes to the container will persist. The final wrinkle is to have the function modify the container - it changes its default value each time it is run. This seems very sneaky, yet delightfully useful at times. Simon Vandemoortele wrote: > > I am making my first contact with python through the means of the tutorial > (http://www.python.org/doc/current/tut/) and I would like some clarification > on the example: > > --- quote --- > Important warning: The default value is evaluated only once. This makes a > difference when the default is a mutable object such as a list or dictionary. > For example, the following function accumulates the arguments passed to it on > subsequent calls: > > def f(a, l = []): > l.append(a) > return l > print f(1) > print f(2) > print f(3) > > This will print > > [1] > [1, 2] > [1, 2, 3] > --- end quote --- > > One thing I find astonishing about this is the fact that python functions > seem to have memory; each call of f() leads to a different result ! Does this > mean that the variable 'l' keeps its content even after the function returns > ? This seems very strange to me as I have never seen it in other languages. > > Some explanation/comments/corrections ? > Thx, Simon > > -- > If you took all the students that felt asleep in class and laid them > end to end, they'd be a lot more comfortable. > -- "Graffiti in the Big Ten" > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From csmith@blakeschool.org Sat Aug 11 17:38:44 2001 From: csmith@blakeschool.org (Christopher Smith) Date: Sat, 11 Aug 2001 11:38:44 -0500 Subject: [Tutor] Re: Algebraic symbol manipulation program idea In-Reply-To: References: Message-ID: tutor@python.org writes: >From: Roeland Rengelink >To: tutor@python.org >Subject: Re: [Tutor] Re: Algebraic symbol manipulation program idea > >I'm interested in this stuff too, but I couldn't find the original >message you're >replying to. Do you have a link somewhere? > >Roeland Sorry about that...it was posted on pythonmac-sig. Date: Fri, 10 Aug 2001 12:33:23 +0100 From: Shelley Walsh To: Subject: [Pythonmac-SIG] Algebraic symbol manipulation program idea /c From tim.one@home.com Sat Aug 11 19:33:02 2001 From: tim.one@home.com (Tim Peters) Date: Sat, 11 Aug 2001 14:33:02 -0400 Subject: [Tutor] Windows, Python and me In-Reply-To: Message-ID: [Roman Suzi] > ... > 1. After installing Python under Windows, I can't just type "python" > in DOS-prompt to run scripts. What is the easy way for the novice to > set PATH correctly? ("> start python" works fine). What does "novice" mean to you? Windows is a GUI environment, and nothing involving a DOS box is suitable for a true novice (MS barely even documents that DOS boxes exist). How to set PATH varies across different flavors of Windows, and that operation isn't for novices either. Easiest is to open a DOS box and explicitly "cd" to the Python directory. > 2. Some tar.gz archives are using LF-line ends (and this is right > thing for UNIX or under IDLE). > > However, such scripts are not editable in NotePad which is fabulous > default Windows editor. I have a sister who still uses Notepad, but she's an extreme case . > What is the better choice: to get/provide CR-LF-ed text files or > (how?) make users decode text files for themselves? Most Windows users eventually get around to buying WinZip; by default, WinZip attempts to detect Unixish text files in tar files and convert them to Windows line end conventions by magic. But shipping a .tar file (.gz or not) pretty much rules out Windows novices from the start (Windows users expect .zip files with Windows line ends -- or a Windows installer). > ... > 3. What is the preferred way to run setup.py script? Until you redefine your target audience, this just gets more and more hopeless. If you want to target novices, you have to build a Windows installer. InnoSetup is free and easy to use: http://www.jrsoftware.org/isinfo.htm > ... > it makes feel like Python doesn't suit into Windows environment well). It doesn't, and no more than e.g. Perl does: command-line programs of any kind don't fit Windows well. The Windows audience is overwhelmingly non-programming end users of GUI apps, and a "power user" in the Windows world is someone who memorized a keyboard shortcut <0.7 wink>. If you can assume your target audience is composed of programmers, then you can assume they've already found solutions they can live with to the kinds of issues you're raising. From lkvam@venix.com Sat Aug 11 19:52:14 2001 From: lkvam@venix.com (Lloyd Kvam) Date: Sat, 11 Aug 2001 14:52:14 -0400 Subject: [Tutor] Windows, Python and me References: Message-ID: <3B757EDE.EE61ED19@venix.com> http://aspn.activestate.com/ASPN/Downloads/ActivePython/ ActiveState provides a Windows oriented Python distribution. It is easy to install. The .py scripts look OK in my Notepad (WinNT 4). Wordpad is better about dealing with LF oriented files, but you need to be careful about saving the file as a text file. Roman Suzi wrote: > > Hello, > > I am not sure if my question fits here, but I see lots > of such questions in c.l.p and probably this one could > gather expert answers, easily found later via google. > > Keywords: Python Win32 Windows DOS prompt path setup start run install > CRLF edit editor IDLE > > For more than 4 years already I am working with Linux. But in order to do > packaging of Python related material I need to make it "right" in Windows. > > And here I understand how difficult things in Windows are (compared to > Linux). Below I refer to Win98 SE. > > 1. After installing Python under Windows, I can't just type "python" in > DOS-prompt to run scripts. What is the easy way for the novice to set PATH > correctly? ("> start python" works fine). > > 2. Some tar.gz archives are using LF-line ends (and this is right thing > for UNIX or under IDLE). However, such scripts are not editable in NotePad > which is fabulous default Windows editor. What is the better choice: > to get/provide CR-LF-ed text files or (how?) make users decode text files > for themselves? > > The deadlock is: NotePad can't be used due to LF-ed py-files and IDLE > internal editor can't be used because IDLE doesn't support non-latin-1 > chars... I could suggest Emacs, but for beginners... They will be > pissed off not only for Emacs, but Python alltogether. This way or that > solution must be "freely distributable". > > 3. What is the preferred way to run setup.py script? (MS DOS prompt > doesn't work due to the problem no 1 above and if it works, how do I open > MS DOS prompt in the needed directory and not in the C:\WINDOWS> ? (using > cd or adding some bat or pif files to the directory with unzipped contents > is not an option: it makes feel like Python doesn't suit into Windows > environment well). Or do I need to get some freeware kind of Norton Editor > for such tasks? (What Windows "Explorer" is for, then?) > > * * * > > I think, these questions have impact on Python usability under Windows. > Probably, the best solution could be adding GUI to Distutils, so running > JUST setup.py without options will bring up a dialog with all available > options or at least a text-prompt for them (like this is done for Mac > which do not have command line). > > The reason I posted this to Tutor is that probably I need to learn more > about Windows+Python to resolve problems stated above. And yes, I have > read Distutils docs. (please, tell if I need to reread them). > > Thank you for answers! > > Sincerely yours, Roman Suzi > -- > _/ Russia _/ Karelia _/ Petrozavodsk _/ rnd@onego.ru _/ > _/ Saturday, August 11, 2001 _/ Powered by Linux RedHat 6.2 _/ > _/ "After a hard day, it's nice to come home to a warm cat." _/ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From sburr@mac.com Sat Aug 11 21:18:08 2001 From: sburr@mac.com (Steven Burr) Date: Sat, 11 Aug 2001 13:18:08 -0700 Subject: [Tutor] Help with vars() In-Reply-To: <00038b3e4785f725_mailit@mail.isis.de> Message-ID: <20010811201523.KJMW20799.femail32.sdc1.sfba.home.com@localhost> On Saturday, August 11, 2001, at 03:08 AM, Charlie Clark wrote: >> But if you really want to use vars, you can: >> >>>>> class Blank: >> ... pass >> ... >>>>> article = Blank() >>>>> article.headline = "Horoscope for Peter" >>>>> article.text = "Things are looking up!" >>>>> article.asterisk = "Aquarius" >>>>> print "\n%(headline)s* \n\n%(text)s\n----\n*%(asterisk)s" % >> vars(article) >> >> Horoscope for Peter* >> >> Things are looking up! >> ---- >> *Aquarius > so vars() acts like a dictionary type wrapper and as such isn't > necessary for > dictionaries themselves? I'm new to Python myself, so I'm not certain about the terminology and would welcome an explanation from one of the gurus. But first allow me to embarrass myself. Based on the context in which I've seen the term "wrapper" used, I had been thinking that it meant an object that includes and extends, or allows easier access to, another object. So for example, if you wrote a class using UserDict and added new methods for manipulating the dictionary, that would be a dictionary "wrapper." In 2.2, we'll be able to write class wrappers for dictionaries and lists without using UserDict or UserList. vars(), as I understand it, is a function that returns the __dict__ object for any object that contains one. Since a class instance includes a table of its variables and their values, and the table either is or can be translated into a dictionary (something else I'm uncertain about), calling vars on the instance yields the above result. I would not have thought of that as being a "wrapper," but I could very easily be all wet. it-wouldn't-be-the-first-time'ly yours, sburrious From dyoo@hkn.eecs.berkeley.edu Sat Aug 11 21:15:29 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 11 Aug 2001 13:15:29 -0700 (PDT) Subject: [Tutor] Python function seem to have a memory ??? In-Reply-To: <01081114425000.07601@shinsekai> Message-ID: On Sat, 11 Aug 2001, Simon Vandemoortele wrote: > > I am making my first contact with python through the means of the tutorial > (http://www.python.org/doc/current/tut/) and I would like some clarification > on the example: By the way, if you find the official tutorial a bit dense, you'll find the "Introductions" page on Python.org perhaps easier to digest: http://python.org/doc/Intros.html From sarnold@earthling.net Sun Aug 12 02:34:40 2001 From: sarnold@earthling.net (Steve Arnold) Date: Sat, 11 Aug 2001 18:34:40 -0700 Subject: [Tutor] Windows, Python and me References: Message-ID: <3B75DD30.6090007@earthling.net> Roman Suzi wrote: [snip] > 1. After installing Python under Windows, I can't just type "python" in > DOS-prompt to run scripts. What is the easy way for the novice to set PATH > correctly? ("> start python" works fine). Add the Python directory to the path in the autoexec.bat file. > 2. Some tar.gz archives are using LF-line ends (and this is right thing > for UNIX or under IDLE). However, such scripts are not editable in NotePad > which is fabulous default Windows editor. What is the better choice: > to get/provide CR-LF-ed text files or (how?) make users decode text files > for themselves? > > The deadlock is: NotePad can't be used due to LF-ed py-files and IDLE > internal editor can't be used because IDLE doesn't support non-latin-1 > chars... I could suggest Emacs, but for beginners... They will be > pissed off not only for Emacs, but Python alltogether. This way or that > solution must be "freely distributable". A really good free editor for win32 is PFE: http://www.lancs.ac.uk/people/cpaap/pfe/ It's simple yet powerful, and is actually designed with programming in mind. It handles both DOS and *nix style line-endings (and can convert between them). I'm not sure about the license or terms of distribution, but an even better programmer's editor would be vim. It runs on win32 and has cool stuff like color syntax highlighting. http://www.vim.org/ Then, as you said, there's emacs. I'd say one of those three should do it. > 3. What is the preferred way to run setup.py script? (MS DOS prompt > doesn't work due to the problem no 1 above and if it works, how do I open > MS DOS prompt in the needed directory and not in the C:\WINDOWS> ? (using > cd or adding some bat or pif files to the directory with unzipped contents > is not an option: it makes feel like Python doesn't suit into Windows > environment well). Or do I need to get some freeware kind of Norton Editor > for such tasks? (What Windows "Explorer" is for, then?) > > * * * > > I think, these questions have impact on Python usability under Windows. > Probably, the best solution could be adding GUI to Distutils, so running > JUST setup.py without options will bring up a dialog with all available > options or at least a text-prompt for them (like this is done for Mac > which do not have command line). > > The reason I posted this to Tutor is that probably I need to learn more > about Windows+Python to resolve problems stated above. And yes, I have > read Distutils docs. (please, tell if I need to reread them). > > Thank you for answers! > > Sincerely yours, Roman Suzi > From rob@jam.rr.com Sun Aug 12 05:30:33 2001 From: rob@jam.rr.com (Rob Andrews) Date: Sat, 11 Aug 2001 23:30:33 -0500 Subject: [Tutor] Windows, Python and me References: Message-ID: <3B760669.111A936E@jam.rr.com> Roman Suzi wrote: > > Hello, > > I am not sure if my question fits here, but I see lots > of such questions in c.l.p and probably this one could > gather expert answers, easily found later via google. > > Keywords: Python Win32 Windows DOS prompt path setup start run install > CRLF edit editor IDLE > > For more than 4 years already I am working with Linux. But in order to do > packaging of Python related material I need to make it "right" in Windows. > > And here I understand how difficult things in Windows are (compared to > Linux). Below I refer to Win98 SE. > Just as linux appears bafflingly complex to native Windows users. ;-) > 1. After installing Python under Windows, I can't just type "python" in > DOS-prompt to run scripts. What is the easy way for the novice to set PATH > correctly? ("> start python" works fine). > This is how to initiate an interactive Python session from the "DOS" command prompt: Microsoft(R) Windows 98 (C)Copyright Microsoft Corp 1981-1999. C:\robsrc\Assignments>python Python 2.1 (#15, Apr 16 2001, 18:25:49) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. >>> If you wish to add (for instance) c:\python21 to the PATH list of directories Windows searches for executable programs, the simplest thing to do is to back up c:\autoexec.bat and then add it to the PATH statement (creating a PATH statement, if necessary): PATH=d:\jbuilder4\bin\;e:\perl\bin;c:\python21; > 2. Some tar.gz archives are using LF-line ends (and this is right thing > for UNIX or under IDLE). However, such scripts are not editable in NotePad > which is fabulous default Windows editor. What is the better choice: > to get/provide CR-LF-ed text files or (how?) make users decode text files > for themselves? > Isn't there a handy utility to handle these conversions between *nix and Windows? WinZip is also great for handling such matters under Windows. > The deadlock is: NotePad can't be used due to LF-ed py-files and IDLE > internal editor can't be used because IDLE doesn't support non-latin-1 > chars... I could suggest Emacs, but for beginners... They will be > pissed off not only for Emacs, but Python alltogether. This way or that > solution must be "freely distributable". > > 3. What is the preferred way to run setup.py script? (MS DOS prompt > doesn't work due to the problem no 1 above and if it works, how do I open > MS DOS prompt in the needed directory and not in the C:\WINDOWS> ? (using > cd or adding some bat or pif files to the directory with unzipped contents > is not an option: it makes feel like Python doesn't suit into Windows > environment well). Or do I need to get some freeware kind of Norton Editor > for such tasks? (What Windows "Explorer" is for, then?) > Can't help you much on this one. I've never had any success with the few methods I've tried to make Python scripts more handily executable under Windows. > * * * > > I think, these questions have impact on Python usability under Windows. > Probably, the best solution could be adding GUI to Distutils, so running > JUST setup.py without options will bring up a dialog with all available > options or at least a text-prompt for them (like this is done for Mac > which do not have command line). > > The reason I posted this to Tutor is that probably I need to learn more > about Windows+Python to resolve problems stated above. And yes, I have > read Distutils docs. (please, tell if I need to reread them). > > Thank you for answers! > > Sincerely yours, Roman Suzi > -- Hope some of this is helpful, Rob -- As Useless as we wanna be.... Useless Python! http://www.lowerstandard.com/python From rnd@onego.ru Sun Aug 12 06:41:19 2001 From: rnd@onego.ru (Roman Suzi) Date: Sun, 12 Aug 2001 09:41:19 +0400 (MSD) Subject: [Tutor] Windows, Python and me In-Reply-To: <3B760669.111A936E@jam.rr.com> Message-ID: On Sat, 11 Aug 2001, Rob Andrews wrote: >Roman Suzi wrote: >> I am not sure if my question fits here, but I see lots >> of such questions in c.l.p and probably this one could >> gather expert answers, easily found later via google. >> >> Keywords: Python Win32 Windows DOS prompt path setup start run install >> CRLF edit editor IDLE >> >> For more than 4 years already I am working with Linux. But in order to do >> packaging of Python related material I need to make it "right" in Windows. >> >> And here I understand how difficult things in Windows are (compared to >> Linux). Below I refer to Win98 SE. > >Just as linux appears bafflingly complex to native Windows users. ;-) I could only guess... Large classic "serious" books also appear dull to small children. I read in some article that UNIX is for "verbal" language-oriented and Windows for others. >> 1. After installing Python under Windows, I can't just type "python" in >> DOS-prompt to run scripts. What is the easy way for the novice to set PATH >> correctly? ("> start python" works fine). >> > >This is how to initiate an interactive Python session from the "DOS" >command prompt: > >Microsoft(R) Windows 98 > (C)Copyright Microsoft Corp 1981-1999. > >C:\robsrc\Assignments>python >Python 2.1 (#15, Apr 16 2001, 18:25:49) [MSC 32 bit (Intel)] on win32 >Type "copyright", "credits" or "license" for more information. >>>> > >If you wish to add (for instance) c:\python21 to the PATH list of >directories Windows searches for executable programs, the simplest thing >to do is to back up c:\autoexec.bat and then add it to the PATH >statement (creating a PATH statement, if necessary): > >PATH=d:\jbuilder4\bin\;e:\perl\bin;c:\python21; And what could you say about adding python.bat to the C:/WINDOWS/COMMAND directory with proper python call and all arguments re-applied? (I am not sure what is the MS equivalent of bash's $*, though...) >> 2. Some tar.gz archives are using LF-line ends (and this is right thing >> for UNIX or under IDLE). However, such scripts are not editable in NotePad >> which is fabulous default Windows editor. What is the better choice: >> to get/provide CR-LF-ed text files or (how?) make users decode text files >> for themselves? >> > >Isn't there a handy utility to handle these conversions between *nix and >Windows? WinZip is also great for handling such matters under Windows. WinZip is not free. >> The deadlock is: NotePad can't be used due to LF-ed py-files and IDLE >> internal editor can't be used because IDLE doesn't support non-latin-1 >> chars... I could suggest Emacs, but for beginners... They will be >> pissed off not only for Emacs, but Python alltogether. This way or that >> solution must be "freely distributable". >> >> 3. What is the preferred way to run setup.py script? (MS DOS prompt >> doesn't work due to the problem no 1 above and if it works, how do I open >> MS DOS prompt in the needed directory and not in the C:\WINDOWS> ? (using >> cd or adding some bat or pif files to the directory with unzipped contents >> is not an option: it makes feel like Python doesn't suit into Windows >> environment well). Or do I need to get some freeware kind of Norton Editor >> for such tasks? (What Windows "Explorer" is for, then?) > >Can't help you much on this one. I've never had any success with the few >methods I've tried to make Python scripts more handily executable under >Windows. Thank you for answers! >Hope some of this is helpful, >Rob Yes, it is. It confirms that things are nearly as complex as my estimate was. Sincerely yours, Roman Suzi -- _/ Russia _/ Karelia _/ Petrozavodsk _/ rnd@onego.ru _/ _/ Sunday, August 12, 2001 _/ Powered by Linux RedHat 6.2 _/ _/ "Windows: From the people who brought you EDLIN!" _/ From xiaowp@chinaren.com Sun Aug 12 10:51:43 2001 From: xiaowp@chinaren.com (xiaowp) Date: Sun, 12 Aug 2001 17:51:43 +0800 Subject: [Tutor] How to let IIS support Python script? Message-ID: <200108120904.SAA17404@mh.bit.edu.cn> This is a multi-part message in MIME format. --=====002_Dragon155155764370_===== Content-Type: text/plain; charset="GB2312" Content-Transfer-Encoding: base64 SGVsbG8sDQpJIHdhbnQgdG8gd3JpdGUgQ0dJIHByb2dyYW1taW5nIHVzaW5nIFB5dGhvbiAod2Vi IHNlcnZlciBpcyBJSVMgNS4wKS4gSG93IHRvIGNvbmZpZ3VyZSBteSBJSVMgKG9yIEFwYWNoZSkg dG8gc3VwcG9ydCBQeXRob24gc2NyaXB0LiBJIGhhdmUgcmVhZCB0aGUgcmVsYXRlZCBwYXJhZ3Jh cGggb2YgICJMZWFybmluZyBQeXRob24iIChNYXJrIEx1dHogJiBEYXZpZCBBc2NiZXIsIE8nUmVp bGx5KSwgYnV0IEkgY2Fubm90IGZpbmQgdGhlIGFuc3dlci4NCg0KQmVzdCBSZWdhcmRzLA0KR2Fy eQ0K --=====002_Dragon155155764370_===== Content-Type: text/html; charset="GB2312" Content-Transfer-Encoding: base64 PEhUTUw+DQo8SEVBRD4NCjxtZXRhIGh0dHAtZXF1aXZlPSJDb250ZW50LVR5cGUiIGNvbnRlbnQ9 InRleHQvaHRtbDsgY2hhcnNldD1HQjIzMTIiPg0KPE1FVEEgTkFNRT0iR0VORVJBVE9SIiBDb250 ZW50PSJNaWNyb3NvZnQgREhUTUwgRWRpdGluZyBDb250cm9sIj4NCjxUSVRMRT48L1RJVExFPg0K PC9IRUFEPg0KPEJPRFk+DQo8RElWPkhlbGxvLDwvRElWPg0KPERJVj5JIHdhbnQgdG8gd3JpdGUg Q0dJIHByb2dyYW1taW5nIHVzaW5nIFB5dGhvbiAod2ViIHNlcnZlciBpcyBJSVMgNS4wKS4gSG93 IA0KdG8gY29uZmlndXJlIG15IElJUyAob3IgQXBhY2hlKSB0byBzdXBwb3J0IFB5dGhvbiBzY3Jp cHQuIEkgaGF2ZSByZWFkIHRoZSANCnJlbGF0ZWQmbmJzcDtwYXJhZ3JhcGgmbmJzcDtvZiAmbmJz cDsiTGVhcm5pbmcgUHl0aG9uIiAoTWFyayBMdXR6ICZhbXA7IERhdmlkIA0KQXNjYmVyLCBPJ1Jl aWxseSksIGJ1dCBJIGNhbm5vdCBmaW5kIHRoZSBhbnN3ZXIuPC9ESVY+DQo8RElWPiZuYnNwOzwv RElWPg0KPERJVj5CZXN0IFJlZ2FyZHMsPC9ESVY+DQo8RElWPkdhcnk8L0RJVj4NCjwvQk9EWT4N CjwvSFRNTD4NCg== --=====002_Dragon155155764370_=====-- From xiaowp@chinaren.com Sun Aug 12 11:29:19 2001 From: xiaowp@chinaren.com (xiaowp) Date: Sun, 12 Aug 2001 18:29:19 +0800 Subject: [Tutor] How to let IIS support Python script? Message-ID: <200108120941.SAA19447@mh.bit.edu.cn> SGVsbG8sDQpJIHdhbnQgdG8gd3JpdGUgQ0dJIHByb2dyYW1taW5nIHVzaW5nIFB5dGhvbiAod2Vi IHNlcnZlciBpcyBJSVMgNS4wKS4gSG93IHRvIGNvbmZpZ3VyZSBteSBJSVMgKG9yIEFwYWNoZSkg dG8gc3VwcG9ydCBQeXRob24gc2NyaXB0LiBJIGhhdmUgcmVhZCB0aGUgcmVsYXRlZCBwYXJhZ3Jh cGggb2YgICJMZWFybmluZyBQeXRob24iIChNYXJrIEx1dHogJiBEYXZpZCBBc2NiZXIsIE8nUmVp bGx5KSwgYnV0IEkgY2Fubm90IGZpbmQgdGhlIGFuc3dlci4NCg0KQmVzdCBSZWdhcmRzLA0KR2Fy eQ0K From xiaowp@chinaren.com Sun Aug 12 11:39:23 2001 From: xiaowp@chinaren.com (xiaowp) Date: Sun, 12 Aug 2001 18:39:23 +0800 Subject: [Tutor] How to let IIS support Python script? Message-ID: <200108120951.SAA19891@mh.bit.edu.cn> SGVsbG8sDQpJIHdhbnQgdG8gd3JpdGUgQ0dJIHByb2dyYW1taW5nIHVzaW5nIFB5dGhvbiAod2Vi IHNlcnZlciBpcyBJSVMgNS4wKS4gSG93IHRvIGNvbmZpZ3VyZSBteSBJSVMgKG9yIEFwYWNoZSkg dG8gc3VwcG9ydCBQeXRob24gc2NyaXB0LiBJIGhhdmUgcmVhZCB0aGUgcmVsYXRlZCBwYXJhZ3Jh cGggb2YgICJMZWFybmluZyBQeXRob24iIChNYXJrIEx1dHogJiBEYXZpZCBBc2NiZXIsIE8nUmVp bGx5KSwgYnV0IEkgY2Fubm90IGZpbmQgdGhlIGFuc3dlci4NCg0KQmVzdCBSZWdhcmRzLA0KR2Fy eQ0K From xiaowp@263.net Sun Aug 12 11:40:37 2001 From: xiaowp@263.net (xiaowp) Date: Sun, 12 Aug 2001 18:40:37 +0800 Subject: [Tutor] (no subject) Message-ID: <000f01c1231b$39912ff0$db0aa8c0@xiaowp> This is a multi-part message in MIME format. ------=_NextPart_000_000C_01C1235E.478FD0F0 Content-Type: text/plain; charset="gb2312" Content-Transfer-Encoding: base64 SGVsbG8sDQpJIHdhbnQgdG8gd3JpdGUgQ0dJIHByb2dyYW1taW5nIHVzaW5nIFB5dGhvbiAod2Vi IHNlcnZlciBpcyBJSVMgNS4wKS4gSG93IHRvIGNvbmZpZ3VyZSBteSBJSVMgKG9yIEFwYWNoZSkg dG8gc3VwcG9ydCBQeXRob24gc2NyaXB0LiBJIGhhdmUgcmVhZCB0aGUgcmVsYXRlZCBwYXJhZ3Jh cGggb2YgICJMZWFybmluZyBQeXRob24iIChNYXJrIEx1dHogJiBEYXZpZCBBc2NiZXIsIE8nUmVp bGx5KSwgYnV0IEkgY2Fubm90IGZpbmQgdGhlIGFuc3dlci4NCg0KQmVzdCBSZWdhcmRzLA0KR2Fy eQ0K ------=_NextPart_000_000C_01C1235E.478FD0F0 Content-Type: text/html; charset="gb2312" Content-Transfer-Encoding: base64 PCFET0NUWVBFIEhUTUwgUFVCTElDICItLy9XM0MvL0RURCBIVE1MIDQuMCBUcmFuc2l0aW9uYWwv L0VOIj4NCjxIVE1MPjxIRUFEPg0KPE1FVEEgaHR0cC1lcXVpdj1Db250ZW50LVR5cGUgY29udGVu dD0idGV4dC9odG1sOyBjaGFyc2V0PWdiMjMxMiI+DQo8TUVUQSBjb250ZW50PSJNU0hUTUwgNS41 MC40NTIyLjE4MDAiIG5hbWU9R0VORVJBVE9SPg0KPFNUWUxFPjwvU1RZTEU+DQo8L0hFQUQ+DQo8 Qk9EWSBiZ0NvbG9yPSNmZmZmZmY+DQo8RElWPjxGT05UIHNpemU9Mj5IZWxsbyw8QlI+SSB3YW50 IHRvIHdyaXRlIENHSSBwcm9ncmFtbWluZyB1c2luZyBQeXRob24gKHdlYiANCnNlcnZlciBpcyBJ SVMgNS4wKS4gSG93IHRvIGNvbmZpZ3VyZSBteSBJSVMgKG9yIEFwYWNoZSkgdG8gc3VwcG9ydCBQ eXRob24gDQpzY3JpcHQuIEkgaGF2ZSByZWFkIHRoZSByZWxhdGVkIHBhcmFncmFwaCBvZiZuYnNw OyAiTGVhcm5pbmcgUHl0aG9uIiAoTWFyayBMdXR6IA0KJmFtcDsgRGF2aWQgQXNjYmVyLCBPJ1Jl aWxseSksIGJ1dCBJIGNhbm5vdCBmaW5kIHRoZSBhbnN3ZXIuPC9GT05UPjwvRElWPg0KPERJVj4m bmJzcDs8L0RJVj4NCjxESVY+PEZPTlQgc2l6ZT0yPkJlc3QgUmVnYXJkcyw8QlI+R2FyeTwvRk9O VD48L0RJVj48L0JPRFk+PC9IVE1MPg0K ------=_NextPart_000_000C_01C1235E.478FD0F0-- From xiaowp@chinaren.com Sun Aug 12 11:44:17 2001 From: xiaowp@chinaren.com (xiaowp) Date: Sun, 12 Aug 2001 18:44:17 +0800 Subject: [Tutor] How to let IIS support Python script? Message-ID: <200108120956.SAA20180@mh.bit.edu.cn> Hello, I want to write CGI programming using Python (web server is IIS 5.0). How to configure my IIS (or Apache) to support Python script. I have read the related paragraph of "Learning Python" (Mark Lutz & David Ascber, O'Reilly), but I cannot find the answer. Best Regards, Gary From dyoo@hkn.eecs.berkeley.edu Sun Aug 12 18:03:39 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 12 Aug 2001 10:03:39 -0700 (PDT) Subject: [Tutor] How to let IIS support Python script? In-Reply-To: <200108120956.SAA20180@mh.bit.edu.cn> Message-ID: On Sun, 12 Aug 2001, xiaowp wrote: > I want to write CGI programming using Python (web server is IIS 5.0). > How to configure my IIS (or Apache) to support Python script. I have > read the related paragraph of "Learning Python" (Mark Lutz & David > Ascber, O'Reilly), but I cannot find the answer. [Completely off-topic warning: if you plan to run an IIS system, please make sure you have it patched to immunize it: http://www.eeye.com/html/Research/Advisories/AD20010618.html ] To get Apache to support Python as a CGI language, look for an "AddHandler cgi-script" line in your apache configuration line. It'll look something like this: # To use CGI scripts: AddHandler cgi-script .cgi .pl .py If we place ".py" in that line, then we'll be able to run '.py' Python CGI programs. Apache is set up by default to only run .cgi programs in a specific directory called 'cgi-bin', which can be found if we search around for the "ScriptAlias" directories in the Apache configuration file. For example, here's one typical entry on a Unix system: ScriptAlias /cgi-bin/ "/home/httpd/cgi-bin/" It should be very similar to an entry on a Windows system. You can add more ScriptAliases so that you can place cgi programs in other directories. I don't know personally how to set things up on IIS, but there's an entry in the FAQ wizard, which you can find here: http://www.python.org/cgi-bin/faqw.py Here's what the FAQ says about setting up IIS and Python: ### 8.1. Using Python for CGI on Microsoft Windows Setting up the Microsoft IIS Server/Peer Server: On the Microsoft IIS server or on the Win95 MS Personal Web Server you set up python in the same way that you would set up any other scripting engine. Run regedt32 and go to: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W3SVC\Parameters\ScriptMap and enter the following line (making any specific changes that your system may need) .py :REG_SZ: c:\\python.exe -u %s %s This line will allow you to call your script with a simple reference like: http://yourserver/scripts/yourscript.py provided "scripts" is an "executable" directory for your server (which it usually is by default). The "-u" flag specifies unbuffered and binary mode for stdin - needed when working with binary data In addition, it is recommended by people who would know that using ".py" may not be a good idea for the file extensions when used in this context (you might want to reserve *.py for support modules and use *.cgi or *.cgp for "main program" scripts). However, that issue is beyond this Windows FAQ entry. Netscape Servers: Information on this topic exists at: http://home.netscape.com/comprod/server_central/support/fasttrack_man/programs.htm#1010870 ### Hope this helps! From alan.gauld@bt.com Sat Aug 11 19:25:56 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sat, 11 Aug 2001 19:25:56 +0100 Subject: [Tutor] Object Oriented References? and a couple of question s <--LONG Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BE7F@mbtlipnt02.btlabs.bt.co.uk> > I'm trying to hack my way into the verdant valley that is > Pythonic Object Orientism. > Would anybody have any recommendations for info on the subject? As usual i'll recommend my tutor :-) http://www.crosswinds.net/~agauld Look for the OO topic then also read the OO section of the case study. > I've got a Cook who will scan a directory for ingredients, sift them > so that we are using only the ingredients we want, and then cook up a > bunch of Python Objects. Then I've got a Host who will deal with the > Diners and handle all of their requests and make sure > everyone gets what > they need. I've also got a number of Recipies (object templates) for > The Cook to use. This is how I'm thinking I'll lay things out, let me > know if this isn't the best OO way to do things. Thats a problem statement. Remember that in general "people" make bad objects. So try to avoid the Cook, Host and Diners as objects at least initially. They may have a role to play as "control" objects later. That leaves: ingredients, requests, recipies. > The Cook will first scan a directory, and make a list of all > the files. This will be his Pantry. Oh another object - the pantry. > He will then Sift through the pantry for the files required > by the Recipe. Better to get the pantry to do its own sifting - it owns the ingredients, it is responsible for operating on them - a key principle of OOD is he who owns the data does the work... Sometimes called "Responsibility Driven Design". > that will be refered to as the Ingredients. These Ingredients will be > used to Bake a bunch of objects that I plan to use later. Which objects? Meals maybe? Each meal knows how to bake itself maybe? > When I'm setting up the Cook class I'm thinking the gather(), sift(), > and bake() will be methods of the class, No these are methods of the other classes that the cook controls by calling on them. Thus cook = Cook() pantry = Pantry() cook.makeMeal() And the makeMeal method might look like this: class Cook: def makeMeal(meal) ingredients = pantry.gather() for item in ingredients item.sift() return meal.bake(ingredients) > I'm really foggy on how to properly use classes to create objects and > then use those objects. As you can see, I'm in dire need of > a good explanation. Try Timothy Budd's OO Programming. He uses 5 languages to explain the key principles of OO - showing how each language has its own foibles but the underlying principles are the same... HTH, Alan G From alan.gauld@bt.com Sat Aug 11 18:56:19 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sat, 11 Aug 2001 18:56:19 +0100 Subject: [Tutor] OOP book Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BE7E@mbtlipnt02.btlabs.bt.co.uk> Charlie, The digest got mangled hence the non tutor routed reply... If you have trouble with OO in Python its unlikely to be the python bits since if you know OO the Python implementation is very easy. Thus I recommend Timothy Budd's OO Programming book which teaches the fundamentals of OO accurately and clearly in 5 languages! Once yuou've seen those different approaches to OO come back to Python (or compare as you go) and it will all click into place I think. [You need 5 languages to be able to differentiate what is really an OO issue and what is just a particular languages implementation feature...] Alan Gauld From alan.gauld@bt.com Sat Aug 11 19:33:55 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sat, 11 Aug 2001 19:33:55 +0100 Subject: [Tutor] Hashing Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BE80@mbtlipnt02.btlabs.bt.co.uk> > >>> hash((-1,)) > 1660579479 > >>> hash((-2,)) > 1660579479 > > aren't these values supposed to be unique? No hashing produces a spread of values over a range. When two or more items et the same hash value they go into a list and the lookup accesses the hash, if its single value returns it, if not it "does something" with the list. What itv does depends on the designer of the hash! A good(ie readable) source of info on this is Kernighan & Pike's recent programming book - sorry forgotten the title for now... Something like the Practice of Programming. The idea is that the total time looking up the hash then searching the list is shorter than traversing a single long list. Alan G PS I've just noticed that Danny has (as uisual) given a more complete answer. I'll send this anyway coz of the book reference... From kojo@hal-pc.org Sun Aug 12 20:18:16 2001 From: kojo@hal-pc.org (Kojo Idrissa) Date: Sun, 12 Aug 2001 14:18:16 -0500 Subject: [Tutor] OOP book In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66BE7E@mbtlipnt02.btlabs .bt.co.uk> Message-ID: <5.1.0.14.0.20010812141335.00ae57f0@Pop3.norton.antivirus> Actually, according to Amazon, there's a new edition coming out October 1, 2001, that ups the language count to...{counts from web page} at least 9, including Python (yea!) and C# (uh, ok). Might be worth waiting for, if you have the time. At 06:56 PM 8/11/2001 +0100, alan.gauld@bt.com wrote: >Charlie, > > Thus I recommend Timothy Budd's OO Programming >book which teaches the fundamentals of OO accurately and >clearly in 5 languages! Once yuou've seen those different >approaches to OO come back to Python (or compare as you >go) and it will all click into place I think. > >[You need 5 languages to be able to differentiate what >is really an OO issue and what is just a particular languages >implementation feature...] > > >Alan Gauld > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor **************************** Kojo Idrissa kojo@hal-pc.org http://www.hal-pc.org/~kojo/ **************************** From alan.gauld@bt.com Sun Aug 12 22:17:47 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun, 12 Aug 2001 22:17:47 +0100 Subject: [Tutor] Python function seem to have a memory ??? Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BE81@mbtlipnt02.btlabs.bt.co.uk> > --- quote --- > Important warning: The default value is evaluated only once. This is the key statement > def f(a, l = []): > l.append(a) > return l So the default is a reference to an empty list > print f(1) and now we put a=1 into that list > print f(2) and now a=2 goes in. its the same list because python only evaluates the default once when the function is defined. This is rather like "closure" behaviour in other languages like perl or lisp. Indeed you can use this behaviour to make lambda functions more useful(you'll cover lambdas later ;-) > One thing I find astonishing about this is the fact that > python functions seem to have memory; Correct, it remembers the default and, as it is mutable, the content changes. This can be useful when you want it and infuriating when you don't! Alan G From alan.gauld@bt.com Sun Aug 12 22:35:37 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun, 12 Aug 2001 22:35:37 +0100 Subject: [Tutor] Windows, Python and me Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BE82@mbtlipnt02.btlabs.bt.co.uk> I'll jump in here - probably with both feet! > >> 1. After installing Python under Windows, I can't > >> just type "python" You should - provided you've done a reboot. I'm sure the official pythomn installeer sets both the path and the file association. If not you need to either set the PATH env var in autoexec.bat yourself(via the installer) or tell the user how... But they need the reboot to pick up the new setting! Once thats done they don't even need to type Python at the DOS prompt they can just double click the .py files in Windows Exploder > >This is how to initiate an interactive Python session from the "DOS" > >command prompt: Or indeed go to Start|Run and just type "python" ...or "foo.py" or whatever! > And what could you say about adding > > python.bat > > to the C:/WINDOWS/COMMAND > directory with proper python call and all arguments re-applied? Bad idea! For a start DOS BAT can only handle 9 arguments (%1...%9) ata time(like unix you can shift them but how could the script do that sensibly??? So if someone created a python script that took 9 it would fail since C:> python f.py 1 2 3 4 5 6 7 8 would internally call python.bat which would do python f.py 1 2 3 4 5 6 7 8 using python.exe but losing one arg in favor of the script name... > (I am not sure what is the MS equivalent of bash's $*, though...) There isn't one! You could of course create a WSH script that would work since WSH uses an "Arguments" COM collection... > >> 2. Some tar.gz archives are using LF-line ends Isn't there a default script in the python distro for converting Unix-SDOS line ends? crlf.py or something? > WinZip is not free. No but Zip Central is and is a winzip clone. Do a search or visit my tutor which has a web link. http://www.crosswinds.net/~agauld/ Alan G. From jstanley@start.com.au Sun Aug 12 23:04:40 2001 From: jstanley@start.com.au (Jordan Stanley) Date: Sun, 12 Aug 2001 23:04:40 +0100 Subject: [Tutor] Re: Tutor digest, Vol 1 #1015 - 1 msg Message-ID: I need to write a script to email me my ip address when it logs on or changes. i wonder if this would be easier to do with windows scripting functions or python? btw yes i am using winwk advanced server. thank you Original message from: tutor-request@python.org > >Send Tutor mailing list submissions to > tutor@python.org > >To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/tutor >or, via email, send a message with subject or body 'help' to > tutor-request@python.org > >You can reach the person managing the list at > tutor-admin@python.org > >When replying, please edit your Subject line so it is more specific >than "Re: Contents of Tutor digest..." > > >Today's Topics: > > 1. How to let IIS support Python script? (xiaowp) > >--__--__-- > >Message: 1 >Date: Sun, 12 Aug 2001 18:44:17 +0800 >From: xiaowp >To: "tutor@python.org" >Subject: [Tutor] How to let IIS support Python script? > >Hello, >I want to write CGI programming using Python (web server is IIS 5.0). How to configure my IIS (or Apache) to support Python script. I have read the related paragraph of "Learning Python" (Mark Lutz & David Ascber, O'Reilly), but I cannot find the answer. > >Best Regards, >Gary > > > > > >--__--__-- > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > >End of Tutor Digest >. > __________________________________________________________________ Get your free Australian email account at http://www.start.com.au From dsh8290@rit.edu Sun Aug 12 23:31:15 2001 From: dsh8290@rit.edu (dman) Date: Sun, 12 Aug 2001 18:31:15 -0400 Subject: [Tutor] Windows, Python and me In-Reply-To: ; from rnd@onego.ru on Sat, Aug 11, 2001 at 01:12:50PM +0400 References: Message-ID: <20010812183115.A4947@harmony.cs.rit.edu> On Sat, Aug 11, 2001 at 01:12:50PM +0400, Roman Suzi wrote: | Hello, | | I am not sure if my question fits here, but I see lots | of such questions in c.l.p and probably this one could | gather expert answers, easily found later via google. | | Keywords: Python Win32 Windows DOS prompt path setup start run install | CRLF edit editor IDLE | | For more than 4 years already I am working with Linux. But in order to do | packaging of Python related material I need to make it "right" in Windows. | | And here I understand how difficult things in Windows are (compared to | Linux). Below I refer to Win98 SE. Uh huh. I know what you mean (even though I learned DOS 3.3, Win 3.11, and Win95/98 before switching to linux). | 1. After installing Python under Windows, I can't just type "python" in | DOS-prompt to run scripts. What is the easy way for the novice to set PATH | correctly? ("> start python" works fine). If (I don't know if it does) the installer addes it to the PATH (via modifying c:\autoexec.bat) you need to reboot for it to take effect. In any case there is a shortcut in the Start menu to get a python shell. Also the installer sets up file associations so that if you just double click a .py file it runs it. Note, however, that .py files always have a DOS box while running. If you use .pyw instead (for the 'main()' file) you won't get the DOS box. A windows pecularity. | 2. Some tar.gz archives are using LF-line ends (and this is right thing | for UNIX or under IDLE). However, such scripts are not editable in NotePad | which is fabulous default Windows editor. What is the better choice: | to get/provide CR-LF-ed text files or (how?) make users decode text files | for themselves? | | The deadlock is: NotePad can't be used due to LF-ed py-files and IDLE | internal editor can't be used because IDLE doesn't support non-latin-1 | chars... I could suggest Emacs, but for beginners... They will be | pissed off not only for Emacs, but Python alltogether. This way or that | solution must be "freely distributable". Wordpad (also in the Start->Accesories folder) can handle LF line endings. Notepad can "handle" them, but it displays the line ending as a black box instead of going to the next line. Not really pretty. A python script to convert is really simple (basically s/\n/\r\n/). | 3. What is the preferred way to run setup.py script? (MS DOS prompt | doesn't work due to the problem no 1 above and if it works, how do I open | MS DOS prompt in the needed directory and not in the C:\WINDOWS> ? (using | cd or adding some bat or pif files to the directory with unzipped contents | is not an option: it makes feel like Python doesn't suit into Windows | environment well). Or do I need to get some freeware kind of Norton Editor | for such tasks? (What Windows "Explorer" is for, then?) Tell them to double click the .py file and it should run. The downside is that the DOS box goes away as soon as python exits so you may want to add raw_input( "Press Enter when done to close the window" ) to the end of the script. | I think, these questions have impact on Python usability under Windows. | Probably, the best solution could be adding GUI to Distutils, so running | JUST setup.py without options will bring up a dialog with all available | options or at least a text-prompt for them (like this is done for Mac | which do not have command line). Windows provides the text-prompt in the form of a DOS window. I think you are talking more about the usability of Windows than of the usability of Python on Windows <0.1 wink>. | The reason I posted this to Tutor is that probably I need to learn more | about Windows+Python to resolve problems stated above. And yes, I have | read Distutils docs. (please, tell if I need to reread them). Just try something (simple) and ask a non-programmer windows user if it makes sense to them. If not talk with them to see what they expect instead. Unfortunately they can't just 'apt-get your_python_app'. | Thank you for answers! You're welcome. BTW WinZip is free only if you ignore the nag screens. It can handle tarballs just fine though. Power Archiver is a similar program that is free (and handles tarballs) and I think it is better. A google search will find it quickly. The left-hand pane in Power Archiver allows you to easily browse through the filesystem or the directories in an archive similar to windows explorer. -D From dsh8290@rit.edu Sun Aug 12 23:36:09 2001 From: dsh8290@rit.edu (dman) Date: Sun, 12 Aug 2001 18:36:09 -0400 Subject: [Tutor] Python function seem to have a memory ??? In-Reply-To: <01081114425000.07601@shinsekai>; from delirious@atchoo.be on Sat, Aug 11, 2001 at 02:42:50PM -0100 References: <01081114425000.07601@shinsekai> Message-ID: <20010812183609.B4947@harmony.cs.rit.edu> Others have already explained why it works the way it does, but haven't given an example of how to get a default argument value of a new empty list each time the function is called. On Sat, Aug 11, 2001 at 02:42:50PM -0100, Simon Vandemoortele wrote: | --- quote --- | Important warning: The default value is evaluated only once. This makes a | difference when the default is a mutable object such as a list or dictionary. | For example, the following function accumulates the arguments passed to it on | subsequent calls: | | def f(a, l = []): | l.append(a) | return l | print f(1) | print f(2) | print f(3) | | This will print | | [1] | [1, 2] | [1, 2, 3] | --- end quote --- Try def f( a , l = None ) ; if l is None : l = [] l.append( a ) return l 'None' is an immutable object. This means it can't change and will always be the same. The first thing I do in the function is to see if 'l' has the default value. If it does I create a new local binding to a new empty list object called 'l'. Then I proceed to modify it and return it as before. This idiom will have the desired effect. HTH, -D From dsh8290@rit.edu Sun Aug 12 23:42:26 2001 From: dsh8290@rit.edu (dman) Date: Sun, 12 Aug 2001 18:42:26 -0400 Subject: [Tutor] Re: Tutor digest, Vol 1 #1015 - 1 msg In-Reply-To: ; from jstanley@start.com.au on Sun, Aug 12, 2001 at 11:04:40PM +0100 References: Message-ID: <20010812184226.C4947@harmony.cs.rit.edu> On Sun, Aug 12, 2001 at 11:04:40PM +0100, Jordan Stanley wrote: | I need to write a script to email me my ip address when it logs on or | changes. Have you seen ddt.sourceforge.org? They have a nice system to provide a FQDN to a machine with a dynamic IP address. | i wonder if this would be easier to do with windows scripting | functions or python? I think you are talking about "Windows Scripting Host" here. If so, it is not a language but rather a specification that any language can be made to meet, and Python can be used as a Windows Scripting Host language (AFAIK). The real trick is to try and get windows to execute some program/script whenever you get an IP address. On Linux it would be as easy as adding a script to /etc/ppp/ip-up for dialup connections or adding an "up " line to /etc/network/interfaces. I have no idea how to do that in windows. -D From sburr@mac.com Sun Aug 12 23:54:08 2001 From: sburr@mac.com (Steven Burr) Date: Sun, 12 Aug 2001 15:54:08 -0700 Subject: [Tutor] Object Oriented References? and a couple of question s <--LONG In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66BE7F@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <20010812225129.KVVZ25522.femail40.sdc1.sfba.home.com@localhost> On Saturday, August 11, 2001, at 11:25 AM, alan.gauld@bt.com wrote: [snip] > Thus > > cook = Cook() > pantry = Pantry() > cook.makeMeal() > > And the makeMeal method might look like this: > > class Cook: > def makeMeal(meal) > ingredients = pantry.gather() > for item in ingredients > item.sift() > return meal.bake(ingredients) Don't you lose polymorphism by hard-coding a call to a specific instance's method? Wouldn't it be more consistent with OO design to allow "makeMeal" to call the "gather" method of any object that implements it? For example: class Cook: def makeMeal(self, meal, supplier): ingredients = supplier.gather(meal) . . . cook1 = Cook() source1 = Pantry() lunch = cook1.makeMeal("tuna fish sandwich", source1) cook2 = Cook() source2 = CheeseShop() snack = cook2.makeMeal("camembert and crackers", source2) for-some-reason-i'm-feeling-a-might-peckish'ly yours, sburrious From tim.one@home.com Sun Aug 12 23:57:18 2001 From: tim.one@home.com (Tim Peters) Date: Sun, 12 Aug 2001 18:57:18 -0400 Subject: [Tutor] Windows, Python and me In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66BE82@mbtlipnt02.btlabs.bt.co.uk> Message-ID: [alan.gauld@bt.com] > You should - provided you've done a reboot. I'm sure the > official pythomn installeer sets both the path and the > file association. The PythonLabs installer never touches autoexec.bat. That's an exceedingly dangerous thing to do via program, and we redid the way we install Tcl/Tk to stop *its* installer from mucking with autoexec.bat too (the number of ways this can fail, and screw up a user's other programs as a result, is astonishing). We do set file associations, although I don't find them useful for Python on Win9x. Generally much better to use IDLE, or bring up a DOS box and cd to your Python directory (for that matter, if you drag a DOS-box icon to the desktop, you can tell it to always start in your Python directory by filling in the "Working:" box on the Program tab of the right-click Properties dialog). > If not you need to either set the PATH env var in autoexec.bat > yourself(via the installer) or tell the user how... > > But they need the reboot to pick up the new setting! If they change autoexec.bat, yes. File extensions are stored in the registry, though, and changes take effect immediately (without a reboot). > Once thats done they don't even need to type Python at > the DOS prompt they can just double click the .py files > in Windows Exploder The last has only to do with setting file associations; no change to the PATH is needed (or even relevant ) in the context of double-clicking on files. > Or indeed go to Start|Run and just type "python" > ...or "foo.py" or whatever! The former (Start|Run) has to do with a different registry setting, neither with PATH nor with file associations. The latter ("foo.py") has solely to do with file associations. Windows is very consistent . From sburr@mac.com Mon Aug 13 00:37:52 2001 From: sburr@mac.com (Steven Burr) Date: Sun, 12 Aug 2001 16:37:52 -0700 Subject: [Tutor] Windows, Python and me In-Reply-To: Message-ID: <20010812233513.LVIH25522.femail40.sdc1.sfba.home.com@localhost> On Saturday, August 11, 2001, at 10:41 PM, Roman Suzi wrote: > On Sat, 11 Aug 2001, Rob Andrews wrote: > >> Roman Suzi wrote: > > WinZip is not free. Aladdin Software has a free unzipping utility. (WinZip both zips and unzips.) I use it on my Win NT box at work, but I've never noticed whether it automatically converts line endings. The home page for Aladdin is http://www.aladdinsys.com. I would provide a more precise reference, but there seems to be a problem with the server. From dyoo@hkn.eecs.berkeley.edu Mon Aug 13 01:12:19 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 12 Aug 2001 17:12:19 -0700 (PDT) Subject: [Tutor] Python function seem to have a memory ??? In-Reply-To: <20010812183609.B4947@harmony.cs.rit.edu> Message-ID: On Sun, 12 Aug 2001, dman wrote: > Others have already explained why it works the way it does, but > haven't given an example of how to get a default argument value of a > new empty list each time the function is called. Ah! One technique that people use is to set the default argument to 'None'. Then, if we see that it's still None by the time the function's actually in motion, then we can create a new list. Here're an example: ### def SliceDiceList(my_sequence=None): "It slices, it dices, ..." if my_sequence == None: my_sequence = [] diced_list = [] for i in range(0, len(my_sequence), 2): diced_list.append(my_sequence[i]) return diced_list ### And a trial run through: ### >>> SliceDiceList("abcdefghijklmnopqrstuvwxyz") ['a', 'c', 'e', 'g', 'i', 'k', 'm', 'o', 'q', 's', 'u', 'w', 'y'] >>> SliceDiceList() [] >>> SliceDiceList([3, 1, 4, 1, 5, 9, 2, 6]) [3, 4, 5, 2] ### From dyoo@hkn.eecs.berkeley.edu Mon Aug 13 02:19:01 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 12 Aug 2001 18:19:01 -0700 (PDT) Subject: [Tutor] A recreational math problem for Useless Python Message-ID: Hiya everyone, I've been glancing at Donald Knuth's neat "Selected Papers on Computer Science" and ran across an interesting problem that he presents. It sounds like a lot of fun, and perhaps someone might be interested in trying their hand at it. Here's the challenge problem (any mispelings are due to frantic typing): """ "The numbers sqrt(1), sqrt(2), ..., sqrt(50) are to be partitioned into two parts whose sum is nearly equal; find the best such partition you can, using less than 10 seconds of computer time."" For example, it turns out to be possible to find the best partition of the smaller set of numbers [sqrt(1), sqrt(2), ... sqrt(30)] after only about one second of computer time; the answer is: sqrt(2) + sqrt(6) + sqrt(9) + sqrt(11) + sqrt(12) + sqrt(13) + sqrt(14) + sqrt(21) + sqrt(23) + sqrt(24) + sqrt(25) + sqrt(26) + sqrt(27) + sqrt(30) is approximately equal to 56.04142 25880 73351 85163 20826 and: sqrt(1) + sqrt(3) + sqrt(4) + sqrt(5) + sqrt(7) + sqrt(8) + sqrt(10) + sqrt(15) + sqrt(16) + sqrt(17) + sqrt(18) + sqrt(19) + sqrt(20) + sqrt(22) + sqrt(28) + sqrt(29) is approximately equal to 56.04142 26276 19557 30332 11496 Note that the two sums agree to nine significant digits. The problem with 50 instead of 30 is much more difficult, and it appears hopeless to find an absolutely optimum partition in only 10 seconds. This is one of the beautiful features of Floyd's problem, since it allows for a friendly competition between the members of the class (with a tie score very unlikely), and especially because it makes the problem typical of real life situations. We are often confronted with problems that cannot be solved exactly at reasonable cost, so we must do the best we can under finite limitations... The time restriction encourages us to think, not merely to compute! """ From clanoftheinsane@hotmail.com Mon Aug 13 02:21:57 2001 From: clanoftheinsane@hotmail.com (paul) Date: Sun, 12 Aug 2001 21:21:57 -0400 Subject: [Tutor] source code Message-ID: This is a multi-part message in MIME format. ------=_NextPart_000_000D_01C12374.D13B7DC0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable what exactly is the python source code? and where do i find it? = everyone says that it's available for download on the python website, = but where is it? i've searched for it on the search engine, and looked = about everywhere. i must just not know what it is. ------=_NextPart_000_000D_01C12374.D13B7DC0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
    what exactly is the python source = code?  and=20 where do i find it?  everyone says that it's available for download = on the=20 python website, but where is it?  i've searched for it on the = search=20 engine, and looked about everywhere.  i must just not know what it=20 is.
    ------=_NextPart_000_000D_01C12374.D13B7DC0-- From dsh8290@rit.edu Mon Aug 13 03:03:51 2001 From: dsh8290@rit.edu (dman) Date: Sun, 12 Aug 2001 22:03:51 -0400 Subject: [Tutor] source code In-Reply-To: ; from clanoftheinsane@hotmail.com on Sun, Aug 12, 2001 at 09:21:57PM -0400 References: Message-ID: <20010812220351.B5190@harmony.cs.rit.edu> On Sun, Aug 12, 2001 at 09:21:57PM -0400, paul wrote: | what exactly is the python source code? and where do i find it? | everyone says that it's available for download on the python | website, but where is it? i've searched for it on the search | engine, and looked about everywhere. i must just not know what it | is. The python source code is the source code that defines the python interpreter. The interpreter is written in C. The source for version 2.1.1 of the interpreter can be found at : http://www.python.org/ftp/python/2.1.1/Python-2.1.1.tgz and the current development version of the source can be found at : http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/python/dist/src/ HTH, -D From israel@lith.com Mon Aug 13 04:52:47 2001 From: israel@lith.com (Israel Evans) Date: Sun, 12 Aug 2001 20:52:47 -0700 Subject: [Tutor] Object Oriented Hulabaloo Message-ID: Thanks!!! That tutorial and your feedback most definitely helped. I was indeed stuck in a Roles paradigm and not an Object paradigm. I think I was trying to make Puppets, not Objects... Once I saw objects truly as data with methods, I was able to make great headway. It makes things so much easier as well! Now as far as UML goes... Is anyone here using it? I've heard that it's the largest standard as far as OO design goes, but I was wondering how happy people are with it and if it really helps them out. ~Israel~ From tim.one@home.com Mon Aug 13 08:27:45 2001 From: tim.one@home.com (Tim Peters) Date: Mon, 13 Aug 2001 03:27:45 -0400 Subject: [Tutor] A recreational math problem for Useless Python In-Reply-To: Message-ID: [Danny Yoo] > I've been glancing at Donald Knuth's neat "Selected Papers on Computer > Science" and ran across an interesting problem that he presents. It > sounds like a lot of fun, and perhaps someone might be interested in > trying their hand at it. Here's the challenge problem (any mispelings > are due to frantic typing): ... It's an excellent problem, although I wish he would have left square roots out of it (floating-point arithmetic complicates the problem to no good end). There's a large and difficult literature on the "subset sum" problem, of which this is an instance. That doesn't mean people should be scared away, it means an exact solution is *so* hard ("NP-hard" in the jargon) that *nobody* knows how to do it efficiently. So any stupid-ass trick you can dream up is fair game. A "stupid-ass trick" is known as a "heuristic" in the jargon, BTW, and finding good heuristics is a fascinating game. After playing with this for a few years , you might want to check out Bartosz Przydatek's 1998 subset-sum heuristic, available in a paper here: http://www.cs.cmu.edu/~bartosz/subset/ The ideas there are very simple (honest ), yet at the time it appeared to be the best efficient approach known. I don't know whether something better is known now. You may discover one! From kauphlyn@speakeasy.org Mon Aug 13 09:06:45 2001 From: kauphlyn@speakeasy.org (Daniel Coughlin) Date: Mon, 13 Aug 2001 01:06:45 -0700 (PDT) Subject: [Tutor] A recreational math problem for Useless Python In-Reply-To: Message-ID: Well I know this is not a very good solution - but it is my first attempt. I used the random module to create the number sets ad that can take a long time. Is there a better way of going about creating the sets? (I dont want to check the article yet - besides i doubt i will understand any of it ;-) The other problem I encountered which is probably soaking up time is that there is an unaccounted for runtime error that happens periodically. I handle this, but i know it still happens, and it is knawing at me... If anyone can figure out way that happens, I'd love to know. One thing you will notice is that you can change the level of precision by changing the string slice indexes. To get two decimal places over usually takes between 5 and 15 seconds. But sometimes it takes a while. BTW - I *really* like problems like this - If you have any others, I'd love to hear about them. Here's the script: #!/usr/bin/env python import math, random def begin(): nlist, alist = [], [] try: create(nlist, alist) except StandardError, s: begin() def create(newlist2, newlist3): if len(newlist2) == 0: newlist3 = [] for i in range(1, 51): newlist2.append(i) num = int(random.random() * len(newlist2)) newlist3.append(newlist2[num]) newlist2.remove(newlist2[num]) asum, nsum = 0, 0 for item in newlist3: asum = asum + math.sqrt(item) for item in newlist2: nsum = nsum + math.sqrt(item) newlist = [nsum, asum, newlist2, newlist3] n = str(newlist[0]) a = str(newlist[1]) if n[:5] == a[:5]: print newlist[0], newlist[2] print newlist[1], newlist[3] else: create(newlist[2], newlist[3]) print 'Searching..' begin() On Mon, 13 Aug 2001, Tim Peters wrote: > [Danny Yoo] > > I've been glancing at Donald Knuth's neat "Selected Papers on Computer > > Science" and ran across an interesting problem that he presents. It > > sounds like a lot of fun, and perhaps someone might be interested in > > trying their hand at it. Here's the challenge problem (any mispelings > > are due to frantic typing): ... > > It's an excellent problem, although I wish he would have left square roots > out of it (floating-point arithmetic complicates the problem to no good > end). > > There's a large and difficult literature on the "subset sum" problem, of > which this is an instance. That doesn't mean people should be scared away, > it means an exact solution is *so* hard ("NP-hard" in the jargon) that > *nobody* knows how to do it efficiently. So any stupid-ass trick you > can dream up is fair game. A "stupid-ass trick" is known as a "heuristic" > in the jargon, BTW, and finding good heuristics is a fascinating game. > > After playing with this for a few years , you might want to check out > Bartosz Przydatek's 1998 subset-sum heuristic, available in a paper here: > > http://www.cs.cmu.edu/~bartosz/subset/ > > The ideas there are very simple (honest ), yet at the time it appeared > to be the best efficient approach known. I don't know whether something > better is known now. You may discover one! > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld@bt.com Mon Aug 13 10:51:25 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon, 13 Aug 2001 10:51:25 +0100 Subject: [Tutor] Windows, Python and me Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BE83@mbtlipnt02.btlabs.bt.co.uk> Tim Peters wrote: > [alan.gauld@bt.com] > > You should - provided you've done a reboot. I'm sure the > > official pythomn installeer sets both the path and the > > file association. > > The PythonLabs installer never touches autoexec.bat. Ah. I must have done that manually at some point at because I always install to the same directory it has always worked... [Aside: I never understood why MS didn't have a registry key that got loaded from Autoexec instead of relying on PATH... Or maybe they do, in which case what is it? And shouldn't new apps set that instead? ] > We do set file associations, although I don't find them > useful for Python on Win9x. Really? I couldn't live without them. Its how I launch nearly all my python scripts - just double click the file oir type the name in Start|Run... > If they change autoexec.bat, yes. File extensions are stored in the > registry, though, and changes take effect immediately Yes, sorry my explanation wasn't unambiguous enough. > The last has only to do with setting file associations; Again yes because file associations take the fiull path of the executable. > The former (Start|Run) has to do with a different registry > setting, neither with PATH nor with file associations. Now that I didn't know! Which one? Is that set by the installer coz I must admit thats how I usually get a Python prompt rather than start a DOS box per se. Maybe thats why I assumed PATH was being set? > The latter ("foo.py") has solely to do with file associations. Thats the one I normally use. > Windows is very consistent . Consistently frustrating that's for sure :-) As a recent email dialog with Michael showed I am now in the pitiable state of being sufficiently immersed in Windoze to have forgotten much of my Unix knowledge but not enough into Windows to be an expert there - yet? Alan g From alan.gauld@bt.com Mon Aug 13 11:34:41 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon, 13 Aug 2001 11:34:41 +0100 Subject: [Tutor] Object Oriented References? and a couple of question s <--LONG Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BE87@mbtlipnt02.btlabs.bt.co.uk> > On Saturday, August 11, 2001, at 11:25 AM, alan.gauld@bt.com wrote: > > cook = Cook() > > pantry = Pantry() > > cook.makeMeal() > > > > And the makeMeal method might look like this: > > > > class Cook: > > def makeMeal(meal) > > ingredients = pantry.gather() > > for item in ingredients > > item.sift() > > return meal.bake(ingredients) > > Don't you lose polymorphism by hard-coding a call to a specific > instance's method? I'm not intending to limit it because pantry is set external to the method. It might in fact be an attribute of the Cook class (or maybe the Kitchen class within which the cook instance is currently working ;-). Thus whatever pantry is instantiated to - it could be a Cupboard or a Freezer or a JITDeliveryservice type of "pantry" the methods will polymorphically function correctly. It probably would be a bad idea to instantiate the pantry within the makeMeal method. > Wouldn't it be more consistent with OO design to > allow "makeMeal" to call the "gather" method of any object that > implements it? Thats what I did, I just didn't specify where/how the pantry should be set. > class Cook: > def makeMeal(self, meal, supplier): > ingredients = supplier.gather(meal) > . . . I would probably prefere to put supplier as an attribute of Cook set in the __init__ method say. But the principle is right. > lunch = cook1.makeMeal("tuna fish sandwich", source1) I'd suggest any intelligent cook should know where to find his ingredients, he wouldn't expect the diner to tell him! But there's no absolute in this without knowing an awful lot more about the requirements... Alan G. From rob@jam.rr.com Mon Aug 13 14:08:51 2001 From: rob@jam.rr.com (Rob Andrews) Date: Mon, 13 Aug 2001 08:08:51 -0500 Subject: [Tutor] A recreational math problem for Useless Python References: Message-ID: <3B77D163.1672DFE6@jam.rr.com> Danny Yoo wrote: > > Hiya everyone, > > I've been glancing at Donald Knuth's neat "Selected Papers on Computer > Science" and ran across an interesting problem that he presents. It > sounds like a lot of fun, and perhaps someone might be interested in > trying their hand at it. Here's the challenge problem (any mispelings are > due to frantic typing): > > """ > "The numbers sqrt(1), sqrt(2), ..., sqrt(50) are to be partitioned into > two parts whose sum is nearly equal; find the best such partition you can, > using less than 10 seconds of computer time."" > > For example, it turns out to be possible to find the best partition of the > smaller set of numbers [sqrt(1), sqrt(2), ... sqrt(30)] after only about > one second of computer time; the answer is: > > sqrt(2) + sqrt(6) + sqrt(9) + sqrt(11) + sqrt(12) + sqrt(13) + > sqrt(14) + sqrt(21) + sqrt(23) + sqrt(24) + sqrt(25) + sqrt(26) + > sqrt(27) + sqrt(30) > > is approximately equal to > > 56.04142 25880 73351 85163 20826 > > and: > > sqrt(1) + sqrt(3) + sqrt(4) + sqrt(5) + sqrt(7) + sqrt(8) + > sqrt(10) + sqrt(15) + sqrt(16) + sqrt(17) + sqrt(18) + > sqrt(19) + sqrt(20) + sqrt(22) + sqrt(28) + sqrt(29) > > is approximately equal to > > 56.04142 26276 19557 30332 11496 > > Note that the two sums agree to nine significant digits. The problem with > 50 instead of 30 is much more difficult, and it appears hopeless to find > an absolutely optimum partition in only 10 seconds. This is one of the > beautiful features of Floyd's problem, since it allows for a friendly > competition between the members of the class (with a tie score very > unlikely), and especially because it makes the problem typical of real > life situations. We are often confronted with problems that cannot be > solved exactly at reasonable cost, so we must do the best we can under > finite limitations... The time restriction encourages us to think, not > merely to compute! > """ If I can come up with a short way of describing this (or if someone with a better grasp of the problem than I have did so [hint, hint]), I'll cheerfully post it to Useless. I'm also about to post a link to the CPAN scripts archive on the Challenges page. I count 144 Perl scripts in their collection, and I'd say that Useless has at least about that many scripts (but they still earn respect for their massive module collection, of course). I'd imagine quite a few of these Perl scripts could be better written in Python. (No disrespect to Perl here, which has not been cruel to me at all. I just figure there's a reasonable likelihood that some of these could be used to demonstrate strengths of Python by comparison.) On the general subject of Perl/Python comparison, I notice from time to time, in places other than the Tutor List, comparisons of Python and Perl with a good bit of friendly competition. But I also notice that these comparisons are often based around someone's experiment in which they wrote a Perl script using regular expressions (which Perl is said to excel at) and claimed that Python is significantly slower than Perl. I really have no interest in provoking a (pointless) language debate. There are plenty enough of those already if someone wants to find them. What I do wonder is if Python has any niche areas comparable with the fame of Perl's regular expression capability. Python does seem to be the best language I've seen for CGI (by a very healthy margin), but *best* is obviously a really subjective statement. I just have a mild academic curiosity if the Python *underwater basket-weaving* module is considered extremely refined in comparison with other *underwater basket-weaving* approaches. I have seen some odd magic in Python, in any event. I have encountred anti-Python sentiment from some of my peers around here, but only before they actually have to modify someone else's Python code. As soon as they discover how readable it is, the complaints stop and Python book sales increment. I'd best get that second cup of coffee before I babble any further. Happy Monday, Rob -- The source code repository you didn't see coming... Useless Python! http://www.lowerstandard.com/python From alan.gauld@bt.com Mon Aug 13 14:59:38 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon, 13 Aug 2001 14:59:38 +0100 Subject: [Tutor] source code Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BE8C@mbtlipnt02.btlabs.bt.co.uk> ------_=_NextPart_001_01C12400.3106BE50 Content-type: text/plain; charset="iso-8859-1" what exactly is the python source code? and where do i find it? everyone says that it's available for download on the python website, but where is it? i've searched for it on the search engine, and looked about everywhere. i must just not know what it is. If you don't know what it is you probably don't nreed it! ie Unless you are fluent in C there's little point in having it. Alan G. ------_=_NextPart_001_01C12400.3106BE50 Content-type: text/html; charset="iso-8859-1"
    what exactly is the python source code?  and where do i find it?  everyone says that it's available for download on the python website, but where is it?  i've searched for it on the search engine, and looked about everywhere.  i must just not know what it is. 
     
    If you don't know what it is you probably don't nreed it!
    ie Unless you are fluent in C there's little point in having it.
     
    Alan G. 
    ------_=_NextPart_001_01C12400.3106BE50-- From alan.gauld@bt.com Mon Aug 13 15:02:42 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon, 13 Aug 2001 15:02:42 +0100 Subject: [Tutor] Object Oriented Hulabaloo Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BE8D@mbtlipnt02.btlabs.bt.co.uk> > Now as far as UML goes... Is anyone here using it? I do and have written a couple of articles(not related to Python tho') about UML on the informIT web site(free registration). http://www.informit.com Best suited to bigger projects IMHO - maybe in excess of 10 classes. UML is a "whole life cycle" notation so it has a lot more than OO stuff in it. For OO it covers most of what you need apoaet from the detailed design of methods. Alan G. From rnd@onego.ru Mon Aug 13 16:06:18 2001 From: rnd@onego.ru (Roman Suzi) Date: Mon, 13 Aug 2001 19:06:18 +0400 (MSD) Subject: [Tutor] source code In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66BE8C@mbtlipnt02.btlabs.bt.co.uk> Message-ID: On Mon, 13 Aug 2001 alan.gauld@bt.com wrote: > what exactly is the python source code? and where do i find it? everyone > says that it's available for download on the python website, but where is > it? i've searched for it on the search engine, and looked about everywhere. > i must just not know what it is. > > > If you don't know what it is you probably don't nreed it! > ie Unless you are fluent in C there's little point in having it. ;-) Source code is great. In source code for Python you can get many instersting things: Demo programs, first-hand Python Grammar. Source code is great educational resource, too. Sometimes, it is sufficient to look at C source for Python builtin functionas to understand what is inside. No deep knowledge of C is need, honest. Just common sense and file-contents search utilities or grep to find needed functions. Source code give experts total control of the situation. That is why Open Source/Freeware movement is so strong. If something is wrong, they can look into source and mend it or understand that my assumptions were wrong. > Alan G. Sincerely yours, Roman A.Suzi -- - Petrozavodsk - Karelia - Russia - mailto:rnd@onego.ru - From rnd@onego.ru Mon Aug 13 17:40:47 2001 From: rnd@onego.ru (Roman Suzi) Date: Mon, 13 Aug 2001 20:40:47 +0400 (MSD) Subject: [Tutor] Windows, Python and me In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66BE82@mbtlipnt02.btlabs.bt.co.uk> Message-ID: On Sun, 12 Aug 2001 alan.gauld@bt.com wrote: >If not you need to either set the PATH env var in autoexec.bat >yourself(via the installer) or tell the user how... Better to tell how... >> to the C:/WINDOWS/COMMAND >> directory with proper python call and all arguments re-applied? > >Bad idea! For a start DOS BAT can only handle 9 >arguments (%1...%9) ata time(like unix you can shift them but how could the >script do that sensibly??? I can add a decent shell too. Say, bash ;-) >> (I am not sure what is the MS equivalent of bash's $*, though...) > >There isn't one! Hard to believe, but possible. >Isn't there a default script in the python distro for >converting Unix-SDOS line ends? Python doesn't require conversion: under Windows it runs LF and CRLF. Text editor NotePad is not that smart :-( (I was thinking to include Emacs ;-) >crlf.py or something? It will not help, as it only converts one script at a time. And it is very easy to write one. (10-liner, including directory walking, I bet. Good excersize). >> WinZip is not free. > >No but Zip Central is and is a winzip clone. >Do a search or visit my tutor which has a web link. >http://www.crosswinds.net/~agauld/ I've found UltimateZip. Maybe ZipCentral is better, thanks! Sincerely yours, Roman Suzi -- _/ Russia _/ Karelia _/ Petrozavodsk _/ rnd@onego.ru _/ _/ Monday, August 13, 2001 _/ Powered by Linux RedHat 6.2 _/ _/ "I distinctly remember forgetting that." _/ From allan.crooks@btinternet.com Mon Aug 13 19:16:55 2001 From: allan.crooks@btinternet.com (Allan Crooks) Date: Mon, 13 Aug 2001 19:16:55 +0100 Subject: [Tutor] Problems with deleting dictionary keys. Message-ID: <3B7827A7.18429.1A4B971@localhost> Hi, I've got the following problem with dictionaries. The problem is, I get this error when I try to delete a key value with the __setitem__ method. I feel that the problem will be clearer if I give you example code. :) ------- Python 2.2a1 (#21, Jul 18 2001, 04:25:46) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. >>> class d2(dictionary): ... def __setitem__(self, key, value): ... if value==0: ... del self[key] ... else: ... print "Setting [%s] to %s." % (key, value) ... >>> d = d2() >>> d.update({'p': 1, 'l': 2, 'a': 3, 'i': 4, 'd': 5}) >>> d {'a': 3, 'p': 1, 'i': 4, 'd': 5, 'l': 2} >>> d['a']=10 Setting [a] to 10. >>> d['a']=0 Traceback (most recent call last): File "", line 1, in ? File "", line 4, in __setitem__ SystemError: NULL object passed to Py_BuildValue I seem to remember there being a problem in earlier versions of Python, where if you modify the dictionary while doing other things to it, it would crash the interpreter. So what I need to know is if this is a bug, or if I'm doing something wrong.... Oh, in case you're wondering what this is for, it's part of a data structure which is useful for seeing if you can derive certain words from a set of letters.... Well, it can do a few more things than that, but that's the gist of it. :) If anyone's interested in it, I'll post it when I get it working. But at the moment, this is the only thing holding me back. :( Thanks, Allan. From dsh8290@rit.edu Mon Aug 13 19:51:15 2001 From: dsh8290@rit.edu (dman) Date: Mon, 13 Aug 2001 14:51:15 -0400 Subject: [Tutor] Problems with deleting dictionary keys. In-Reply-To: <3B7827A7.18429.1A4B971@localhost>; from allan.crooks@btinternet.com on Mon, Aug 13, 2001 at 07:16:55PM +0100 References: <3B7827A7.18429.1A4B971@localhost> Message-ID: <20010813145115.A5618@harmony.cs.rit.edu> On Mon, Aug 13, 2001 at 07:16:55PM +0100, Allan Crooks wrote: | Hi, | | I've got the following problem with dictionaries. The problem is, I get | this error when I try to delete a key value with the __setitem__ | method. | | I feel that the problem will be clearer if I give you example code. :) | | ------- | | Python 2.2a1 (#21, Jul 18 2001, 04:25:46) [MSC 32 bit (Intel)] on | win32 | Type "copyright", "credits" or "license" for more information. | | >>> class d2(dictionary): | ... def __setitem__(self, key, value): | ... if value==0: | ... del self[key] | ... else: | ... print "Setting [%s] to %s." % (key, value) | ... | >>> d = d2() | >>> d.update({'p': 1, 'l': 2, 'a': 3, 'i': 4, 'd': 5}) | >>> d | {'a': 3, 'p': 1, 'i': 4, 'd': 5, 'l': 2} | >>> d['a']=10 | Setting [a] to 10. | >>> d['a']=0 | Traceback (most recent call last): | File "", line 1, in ? | File "", line 4, in __setitem__ | SystemError: NULL object passed to Py_BuildValue The problem is probably that you are destroying the key while at the same time "creating" it. Notice also that in your __setitem__ method you never actually set any items. If you tried to 'print d' after the 'd["a"]=10' line you would see that the value hadn't changed. | I seem to remember there being a problem in earlier versions of | Python, where if you modify the dictionary while doing other things | to it, it would crash the interpreter. Yeah, that was fixed in the new versions though. I think it was something like if you were iterating over the dictionary and removed a key it would have problems, or something like that. | So what I need to know is if this is a bug, or if I'm doing something | wrong.... I think you want something similar to UserDict : def __getitem__(self, key): return self.data[key] def __setitem__(self, key, item): self.data[key] = item def __delitem__(self, key): del self.data[key] Either you could write this yourself in your class or you could inherit from UserDict which is probably what you want. The proper way to delete a dictionary key is with the 'del' keyword : >>> d = {} >>> print d {} >>> d[ 'a' ] = 10 >>> print d {'a': 10} >>> del d[ 'a' ] >>> print d {} >>> >>> import UserDict >>> d2 = UserDict.UserDict() >>> print d2 {} >>> d2[ 'a' ] = 10 >>> print d2 {'a': 10} >>> del d2[ 'a' ] >>> print d2 {} >>> HTH, -D From printers@sendme.cz Mon Aug 13 21:45:07 2001 From: printers@sendme.cz (A) Date: Mon, 13 Aug 2001 22:45:07 +0200 Subject: [Tutor] Threads Message-ID: <3B785873.12539.9AFE1@localhost> Hi, I am a newbie with Python.I want to use threads in my application. Can you please let me know what is the best way of programming threads under Win32 systems? What modules shall I use? Is it better to use the thread module or the threading module or the stackless Python? What are differences? Can you please give any example? Thanks for help. Ladislav From w.richert@gmx.net Mon Aug 13 22:18:58 2001 From: w.richert@gmx.net (Willi Richert) Date: Mon, 13 Aug 2001 23:18:58 +0200 Subject: [Tutor] Threads Message-ID: <003901c1243d$91a68960$0500a8c0@willi> This is a multi-part message in MIME format. ------=_NextPart_000_0036_01C1244E.548780A0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi, no reading in threading with Python, but some experience (bad!) I had = with Win98 and Python: As I moved from SocketServer.TCPServer to = SocketServer.ThreadingTCPServer I got strange errors which showed that I got no socket connection in the ThreadingTCPServer-class. With SocketServer.TCPServer everything worked fine. Also under W2K everything worked. I tried my script using cygwin = and got: $ python gameserver.py Traceback (most recent call last): File "gameserver.py", line 438, in ? import threading File "/usr/lib/python2.1/threading.py", line 18, in ? _start_new_thread =3D thread.start_new_thread AttributeError: 'thread' module has no attribute 'start_new_thread' =3D=3D=3D=3D> So don't use Win98 to learn thread programming with = Python! Even W2K is not the best ;-( Play with Linux: If your script shows an error, you can only blame = yourself than - and learn ;-) willi PS: But for the hint's sake: Use threading instead of thread. ----- Original Message ----- From: A To: Cc: Sent: Monday, August 13, 2001 10:45 PM Subject: [Tutor] Threads > Hi, > > I am a newbie with Python.I want to use threads in my application. > Can you please let me know what is the best way of programming > threads under Win32 systems? > What modules shall I use? > Is it better to use the thread module or the threading module or the > stackless Python? What are differences? > Can you please give any example? > > Thanks for help. > Ladislav > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ------=_NextPart_000_0036_01C1244E.548780A0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
    Hi,

    no reading in threading with = Python, but=20 some experience (bad!) I had with
    Win98 and Python:
    As I moved = from =20 SocketServer.TCPServer to SocketServer.ThreadingTCPServer I
    got = strange=20 errors which showed that I got no socket connection in=20 the
    ThreadingTCPServer-class. With SocketServer.TCPServer everything=20 worked
    fine. Also under W2K everything worked. I tried my script = using cygwin=20 and
    got:

    $ python gameserver.py
    Traceback (most recent call = last):
      File "gameserver.py", line 438, in = ?
       =20 import threading
      File "/usr/lib/python2.1/threading.py", line = 18, in=20 ?
        _start_new_thread =3D=20 thread.start_new_thread
    AttributeError: 'thread' module has no = attribute=20 'start_new_thread'

    =3D=3D=3D=3D> So don't use Win98 to learn = thread=20 programming with Python! Even W2K
    is not the best ;-(
    Play with = Linux: If=20 your script shows an error, you can only blame yourself
    than  = - =20 and learn ;-)

    willi
    PS: But for the hint's sake: Use threading = instead=20 of thread.


    ----- Original Message -----
    From: A <printers@sendme.cz>
    To: = <tutor@python.org>
    Cc: <activepython@listse= rv.ActiveState.com>
    Sent:=20 Monday, August 13, 2001 10:45 PM
    Subject: [Tutor] = Threads


    >=20 Hi,
    >
    > I am a newbie with Python.I want to use threads in = my=20 application.
    > Can you please let me know what is the best way of=20 programming
    > threads under Win32 systems?
    > What modules = shall I=20 use?
    > Is it better to use the thread module or the threading = module or=20 the
    > stackless Python? What are differences?
    > Can you = please give=20 any example?
    >
    > Thanks for help.
    > = Ladislav
    >
    >=20 _______________________________________________
    > Tutor = maillist =20 -  Tutor@python.org
    > = http://mail.python= .org/mailman/listinfo/tutor
    >
    ------=_NextPart_000_0036_01C1244E.548780A0-- From rob@jam.rr.com Mon Aug 13 22:52:31 2001 From: rob@jam.rr.com (Rob Andrews) Date: Mon, 13 Aug 2001 16:52:31 -0500 Subject: [Tutor] Threads References: <3B785873.12539.9AFE1@localhost> Message-ID: <3B784C1F.74921BD0@jam.rr.com> A wrote: > > Hi, > > I am a newbie with Python.I want to use threads in my application. > Can you please let me know what is the best way of programming > threads under Win32 systems? > What modules shall I use? > Is it better to use the thread module or the threading module or the > stackless Python? What are differences? > Can you please give any example? > Take a look at these modules: -threading -thread You can find out about them here: http://www.python.org/doc/current/modindex.html Threads are discussed in some detail in *Programming Python, 2nd ed.* and in *Core Python Programming*, as well. Rob -- A {} is a terrible thing to waste. Useless Python! http://www.lowerstandard.com/python From allan.crooks@btinternet.com Tue Aug 14 02:07:30 2001 From: allan.crooks@btinternet.com (Allan Crooks) Date: Tue, 14 Aug 2001 02:07:30 +0100 Subject: [Tutor] Problems with deleting dictionary keys. In-Reply-To: <20010813145115.A5618@harmony.cs.rit.edu> References: <3B7827A7.18429.1A4B971@localhost>; from allan.crooks@btinternet.com on Mon, Aug 13, 2001 at 07:16:55PM +0100 Message-ID: <3B7887E2.12643.31CAFFB@localhost> On 13 Aug 2001, at 14:51, dman wrote: > The problem is probably that you are destroying the key while at the > same time "creating" it. OK, let me rewrite a different version of the code (and some different test output): >>> class d2(dictionary): ... def __setitem__(self, key, value): ... if value==0: ... del self[key] ... else: ... dictionary.__setitem__(self, key, value) ... >>> d = d2() >>> d.update({'a': 5}) >>> d {'a': 5} >>> d['a'] = 10 >>> d {'a': 10} >>> d['a'] = 0 Traceback (most recent call last): File "", line 1, in ? File "", line 4, in __setitem__ SystemError: NULL object passed to Py_BuildValue >>> As you can see, d['a'] already exists, hence I successfully turn it to 10. But why you should deleting an existing value cause this error? Besides, deleting a value which doesn't exist normally yields this: >>> del {}[2] Traceback (most recent call last): File "", line 1, in ? KeyError: 2 >>> I have the slightly unpleasant feeling that using deletion in the setitem method isn't a good idea, but I can't think how else to get around it. > Notice also that in your __setitem__ method > you never actually set any items. I was just using that for demonstration purposes more than anything. :) > I think you want something similar to UserDict : Is there really any need to? Since we've got the base 'dictionary' type, I thought it made UserDict redundant. But having said that, using UserDict instead of dictionary does work.... :) > The proper way to delete a dictionary key is with the 'del' keyword : Which is what the: del self[key] line is there for. But does this mean a dictionary (or rather a subclass of dictionary) cannot handle deleting items from itself? Thanks for your help, Allan. From dsh8290@rit.edu Tue Aug 14 03:45:19 2001 From: dsh8290@rit.edu (dman) Date: Mon, 13 Aug 2001 22:45:19 -0400 Subject: [Tutor] Problems with deleting dictionary keys. In-Reply-To: <3B7887E2.12643.31CAFFB@localhost>; from allan.crooks@btinternet.com on Tue, Aug 14, 2001 at 02:07:30AM +0100 References: <"from <20010813145115.A5618@harmony.cs.rit.edu> <3B7887E2.12643.31CAFFB@localhost> Message-ID: <20010813224519.C6136@harmony.cs.rit.edu> On Tue, Aug 14, 2001 at 02:07:30AM +0100, Allan Crooks wrote: | On 13 Aug 2001, at 14:51, dman wrote: | | | | > The problem is probably that you are destroying the key while at the | > same time "creating" it. | | OK, let me rewrite a different version of the code (and some | different test output): Ok. [...] | I have the slightly unpleasant feeling that using deletion in the | setitem method isn't a good idea, but I can't think how else to get | around it. Exactly! | > Notice also that in your __setitem__ method | > you never actually set any items. | | I was just using that for demonstration purposes more than | anything. :) Ok. | > I think you want something similar to UserDict : | | | | Is there really any need to? Since we've got the base 'dictionary' | type, I thought it made UserDict redundant. The difference is that dicts are a 'type' and UserDict is a 'class'. This means that you can inherit from UserDict in your class, but you can't inherit from a dict. The last I heard Guido was really working on some stuff to make types and classes the same and allow inheriting from a type. | But having said that, using UserDict instead of dictionary does | work.... :) Are you using aggregation or inheritance? I think, given the snippet you showed, that you want to create your own kind of dictionary which would be easiest with inheritance so you would only need to implement your special behavior and not the entire functionality of a dictionary. | > The proper way to delete a dictionary key is with the 'del' keyword : | | Which is what the: | | del self[key] | | line is there for. I am not sure, but I am wondering if you aren't getting yourself into some sort of nasty recursion or piece of python internal sanity checking or something when you try and delete a key inside of __setitem__. The (python) source will tell for sure, though, ;-). | But does this mean a dictionary (or rather a subclass of dictionary) | cannot handle deleting items from itself? No. The code snippet from UserDict shows how to do it. __setitem__ should *set* items, not destroy them. __delitem__ can (should) destroy the items you no longer want. See http://www.python.org/doc/current/ref/sequence-types.html#l2h-134 more more (though terse) information regarding the __setitem__, __delitem__ and __getitem__ methods. HTH, -D From r.b.rigilink@chello.nl Tue Aug 14 06:24:52 2001 From: r.b.rigilink@chello.nl (Roeland Rengelink) Date: Tue, 14 Aug 2001 07:24:52 +0200 Subject: [Tutor] Problems with deleting dictionary keys. References: <3B7827A7.18429.1A4B971@localhost> Message-ID: <3B78B624.FE4FAB07@chello.nl> Note to readers: This thread is only relevant in Python2.2. Python2.2a1 is the first alpha release of a new Python version that promises to make a start at healing the type/class dichotomy. This will allow you to inherit form built-in types (dictionaries/lists for now, in the future also strings and the rest). Some of this is pretty advanced stuff. See the announcements and references on the Python website. Nevertheless, I think Guido would love to see Python beginners experimenting with this stuff. So maybe you should give it a try. Report feedback/questions etc here, and I'm sure he'll have a look. Allan Crooks wrote: > > Hi, > > I've got the following problem with dictionaries. The problem is, I get > this error when I try to delete a key value with the __setitem__ > method. > > I feel that the problem will be clearer if I give you example code. :) > > ------- > > Python 2.2a1 (#21, Jul 18 2001, 04:25:46) [MSC 32 bit (Intel)] on > win32 > Type "copyright", "credits" or "license" for more information. > > >>> class d2(dictionary): > ... def __setitem__(self, key, value): > ... if value==0: > ... del self[key] > ... else: > ... print "Setting [%s] to %s." % (key, value) > ... > >>> d = d2() > >>> d.update({'p': 1, 'l': 2, 'a': 3, 'i': 4, 'd': 5}) > >>> d > {'a': 3, 'p': 1, 'i': 4, 'd': 5, 'l': 2} > >>> d['a']=10 > Setting [a] to 10. > >>> d['a']=0 > Traceback (most recent call last): > File "", line 1, in ? > File "", line 4, in __setitem__ > SystemError: NULL object passed to Py_BuildValue > > I seem to remember there being a problem in earlier versions of > Python, where if you modify the dictionary while doing other things > to it, it would crash the interpreter. > > So what I need to know is if this is a bug, or if I'm doing something > wrong.... > I think this is a known bug. Guido has stated that the new types don't support __delitem__ yet. I think you're seeing the consequences: For example: >>> class A(dictionary): ... def __setitem__(self, key, val): ... if val==0: ... dictionary.__delitem__(self, key) ... else: ... dictionary.__setitem__(self, key, val) ... >>> a = A() >>> a[1] = 1 >>> a {1: 1} >>> a[1] = 0 Traceback (most recent call last): File "", line 1, in ? File "", line 4, in __setitem__ AttributeError: type object 'dictionary' has no attribute '__delitem__' >>> dictionary.__delitem__ Traceback (most recent call last): File "", line 1, in ? AttributeError: type object 'dictionary' has no attribute '__delitem__' although this works: >>> b = dictionary() >>> b[1] = 1 >>> del b[1] and this too: >>> class B(dictionary): ... def delete_it(self, key): ... del self[key] ... >>> b = B() >>> b[1] = 1 >>> b.delete_it(1) so it's somewhat surprising that del self[key] doesn't work in __setitem__ You might want to report this as a bug. (If you don't want to, I can). SystemErrors are the Python equivalent of core dumps. Probably the absence of __delitem__ in dictionaries and the systemerror when using del self[a] in a __setitem__, are related. No idea how, though. Hope this helps, Roeland -- r.b.rigilink@chello.nl "Half of what I say is nonsense. Unfortunately I don't know which half" From sburr@mac.com Tue Aug 14 07:16:47 2001 From: sburr@mac.com (Steven Burr) Date: Mon, 13 Aug 2001 23:16:47 -0700 Subject: [Tutor] Object Oriented References? and a couple of question s <--LONG In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66BE87@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <20010814061402.HEOR155.femail37.sdc1.sfba.home.com@localhost> On Monday, August 13, 2001, at 03:34 AM, alan.gauld@bt.com wrote: >> On Saturday, August 11, 2001, at 11:25 AM, alan.gauld@bt.com wrote: >> Wouldn't it be more consistent with OO design to >> allow "makeMeal" to call the "gather" method of any object that >> implements it? Sheesh. In retrospect that has a pretty arrogant ring to it, coming from a dilettante like me. Sorry. I didn't intend it that way, and I appreciate the good-natured response. > > Thats what I did, I just didn't specify where/how the pantry > should be set. OK. I see that now. >> lunch = cook1.makeMeal("tuna fish sandwich", source1) > > I'd suggest any intelligent cook should know where to > find his ingredients, he wouldn't expect the diner to > tell him! We sometimes bring our ingredients with us, but I forget that not every family is as eccentric as ours. : ) Thanks again! From tescoil@irtc.net Tue Aug 14 08:03:40 2001 From: tescoil@irtc.net (Tesla Coil) Date: Tue, 14 Aug 2001 02:03:40 -0500 Subject: [Tutor] Q&D Uselessness: crossover.py Message-ID: <3B78CD4C.A1D41D6C@irtc.net> Remarkably, this returned accurate results. I don't expect this to last, as the reduce2songs function is rather crocky. Inviting modifications to make it more reliable in view of rronline's html (and/or improvements in any other respects). # crossover.py -- Grabs the Top 30 "Alternative," # "Active Rock" and "Rock" airplay charts from # *Radio & Records*, and compares them to see # how alternative "Alternative Rock" is lately. import urllib, re, sys def reduce2songs(rawchart): songs = [] for line in rawchart: if re.search('quot', line): songs.append(line) return songs def grabcharts(): radiorec = 'http://www.rronline.com/chartbytes/' charts = ['alt.htm', 'ar.htm', 'rock.htm'] [alt, ar, rock] = [[],[],[]] collected = [alt, ar, rock] try: for grab in range(3): collected[grab] = urllib.urlopen(radiorec+charts[grab]) collected[grab] = collected[grab].readlines() collected[grab] = reduce2songs(collected[grab]) except IOError, e: print e print "Maybe you're not connected to the internet (?)" sys.exit() return collected def comparecharts(reduced): [armatch, rockmatch, allmatch] = [0,0,0] for line in reduced[0]: if line in reduced[1]: armatch = armatch + 1 if line in reduced[2]: rockmatch = rockmatch + 1 if line in reduced[1] and line in reduced[2]: allmatch = allmatch + 1 print print "*Radio & Records* currently reports that:" print "Of the Top 30 songs on US Alternative radio" print armatch, "are Top 30 songs on US Active Rock radio," print rockmatch, "are Top 30 songs on US Rock radio, and" print allmatch, "are Top 30 songs in all three formats." print charts = grabcharts() comparecharts(charts) sys.exit() From dyoo@hkn.eecs.berkeley.edu Wed Aug 15 00:26:38 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 14 Aug 2001 16:26:38 -0700 (PDT) Subject: [Tutor] source code In-Reply-To: Message-ID: On Sun, 12 Aug 2001, paul wrote: > what exactly is the python source code? and where do i find it? > everyone says that it's available for download on the python website, > but where is it? i've searched for it on the search engine, and > looked about everywhere. i must just not know what it is. Out of curiosity, is there anything in particular you're searching for in the Python source code? From dyoo@hkn.eecs.berkeley.edu Wed Aug 15 00:30:33 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 14 Aug 2001 16:30:33 -0700 (PDT) Subject: [Tutor] A recreational math problem for Useless Python In-Reply-To: Message-ID: On Mon, 13 Aug 2001, Daniel Coughlin wrote: > Well I know this is not a very good solution - but it is my first > attempt. I used the random module to create the number sets ad that Your solution is a lot better than mine; I made mine especially Useless by using a genetic algorithm. The heuristic I'm using doesn't work well at all... *sigh* I'll post the code up to Rob later tonight after I clean up the code and don my bughunting cap. From lkvam@venix.com Wed Aug 15 01:15:35 2001 From: lkvam@venix.com (Lloyd Kvam) Date: Tue, 14 Aug 2001 20:15:35 -0400 Subject: [Tutor] Creating a Python Web Proxy using HTTP/1.1 Message-ID: <3B79BF27.75B34085@venix.com> I would like to create a web proxy program that supported HTTP/1.1. I looked at SimpleHTTPServer and BaseHTTPServer, but they use HTTP/1.0. Is there a module to support HTTP/1.1 or is the jump in complexity too great? -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From John.Kenyon@mail.idrive.com Wed Aug 15 01:42:32 2001 From: John.Kenyon@mail.idrive.com (John Kenyon) Date: Tue, 14 Aug 2001 17:42:32 -0700 Subject: [Tutor] question about removing items from a list Message-ID: Can anyone explain why the following works the way it does? >>>lista = ['a', 'b', 'c', 'd'] >>>for item in lista: ... lista.remove(item) ... >>>lista ['b', 'd'] thanks much, jck From lkvam@venix.com Wed Aug 15 01:56:52 2001 From: lkvam@venix.com (Lloyd Kvam) Date: Tue, 14 Aug 2001 20:56:52 -0400 Subject: [Tutor] question about removing items from a list References: Message-ID: <3B79C8D4.CFA4A391@venix.com> You are changing the list while you are stepping through the list in the for statement. for item in lista returns the 'a' - the first thing in the list. The processing then removes 'a' from lista. lista is now: 'b','c','d' for item in lista now returns the SECOND object which is 'c' It also gets removed, reducing lista to 'b','d' Now the for item in lista reaches for a THIRD object and hits the end of the list.... The moral is don't delete from a list from within the for statement that is processing that list. John Kenyon wrote: > > Can anyone explain why the following works the way it does? > > >>>lista = ['a', 'b', 'c', 'd'] > >>>for item in lista: > ... lista.remove(item) > ... > >>>lista > ['b', 'd'] > > thanks much, > > jck > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From allan.crooks@btinternet.com Wed Aug 15 01:57:01 2001 From: allan.crooks@btinternet.com (Allan Crooks) Date: Wed, 15 Aug 2001 01:57:01 +0100 Subject: [Tutor] question about removing items from a list In-Reply-To: Message-ID: <3B79D6ED.22611.3116FBD@localhost> On 14 Aug 2001, at 17:42, John Kenyon wrote: > Can anyone explain why the following works the way it does? > > >>>lista = ['a', 'b', 'c', 'd'] > >>>for item in lista: > ... lista.remove(item) > ... > >>>lista > ['b', 'd'] > This is happening because of the way the for loop works. It keeps on running until it gets to the end of the list. It keeps a counter (starting at 0), and increments it until it gets to the end of the list (or, more formally, until counter >= length of list). So what's happening? This is your list: lista = ['a', 'b', 'c', 'd'] The loop starts off, providing lista[0] as item. 0 is the counter. So we enter the loop, with the following information: lista = ['a', 'b', 'c', 'd'] internal_counter = 0 item = 'a' You then remove item from lista. When the loop has finished, this is the state of the objects. lista = ['b', 'c', 'd'] internal_counter = 0 item = 'a' Now the loop increments it's internal counter and checks that it hasn't gone past the last element in the list. The counter is 1, and the length of the list is 3, so everything is still OK. So at the beginning of the next loop, the list looks like this: lista = ['b', 'c', 'd'] internal_counter = 1 item = 'c' This might make things clearer. Since 'a' is gone, all the other elements have shifted up by one. However, the counter also increments, so we've skipped over 'b' and gone to 'c'. At the beginning of the next loop, the counter is incremented to 2, and the list has only got two elements left, 'b' and 'd' (which are indexed 0 and 1 respectively). Since 2 is larger than the last index, it quits the loop. So how might you want to write that code? A 'better' way would be like this: >>> lista = ['a', 'b', 'c', 'd'] >>> while lista: ... lista.pop(0) ... 'a' 'b' 'c' 'd' >>> lista [] An even better way would be like this: del lista[:] That would delete all items within the list. Doing 'del lista' would simply delete the list itself. HTH, Allan. From r.b.rigilink@chello.nl Wed Aug 15 05:28:07 2001 From: r.b.rigilink@chello.nl (Roeland Rengelink) Date: Wed, 15 Aug 2001 06:28:07 +0200 Subject: [Tutor] question about removing items from a list References: <3B79D6ED.22611.3116FBD@localhost> Message-ID: <3B79FA57.207CC4B1@chello.nl> Allan Crooks wrote: > > On 14 Aug 2001, at 17:42, John Kenyon wrote: > > > Can anyone explain why the following works the way it does? > > > > >>>lista = ['a', 'b', 'c', 'd'] > > >>>for item in lista: > > ... lista.remove(item) > > ... > > >>>lista > > ['b', 'd'] > > > > This is happening because of the way the for loop works. > > It keeps on running until it gets to the end of the list. It keeps a > counter (starting at 0), and increments it until it gets to the end of > the list (or, more formally, until counter >= length of list). > Well, if you want to be formal about it ;) It increments the counter, and breaks out of the loop when item = lista[counter] raises an IndexError. The effect is the same as comparing with the length of the list though. [snip] Roeland -- r.b.rigilink@chello.nl "Half of what I say is nonsense. Unfortunately I don't know which half" From pythonpython@hotmail.com Wed Aug 15 06:13:45 2001 From: pythonpython@hotmail.com (Python Snake) Date: Wed, 15 Aug 2001 14:13:45 +0900 Subject: [Tutor] question about removing items from a list References: Message-ID: Many thanks to Lloyd and Allan for explaining the tricks behind for loop. Anyway, if you really want to loop through the list and remove all the items one by one, you may try something like this: >>> lista = ['a', 'b', 'c', 'd'] >>> templist = lista[:] >>> for item in templist: ... lista.remove(item) ... >>> lista [] Regards, HY ----- Original Message ----- From: "John Kenyon" To: Sent: Wednesday, August 15, 2001 9:42 AM Subject: [Tutor] question about removing items from a list > Can anyone explain why the following works the way it does? > > >>>lista = ['a', 'b', 'c', 'd'] > >>>for item in lista: > ... lista.remove(item) > ... > >>>lista > ['b', 'd'] > > thanks much, > > jck > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From haiyang_yang@hotmail.com Wed Aug 15 07:10:55 2001 From: haiyang_yang@hotmail.com (Haiyang) Date: Wed, 15 Aug 2001 15:10:55 +0900 Subject: [Tutor] global statement? Message-ID: Could anyone please tell me WHY function B can't take globalized dictionary 'a' as a default value? How can I make it work? >>> def A(): ... global a ... a = {} ... a['happyface']=1 ... a['sadface']=99 ... >>> def B(b=a): ... for item in b: ... print b ... Traceback (most recent call last): File "", line 1, in ? NameError: name 'a' is not defined Thannks... HY From ak@silmarill.org Wed Aug 15 07:13:08 2001 From: ak@silmarill.org (Andrei Kulakov) Date: Wed, 15 Aug 2001 02:13:08 -0400 Subject: [Tutor] global statement? In-Reply-To: <"from haiyang_yang"@hotmail.com> References: Message-ID: <20010815021307.A1643@sill.silmarill.org> On Wed, Aug 15, 2001 at 03:10:55PM +0900, Haiyang wrote: > Could anyone please tell me WHY function B can't take globalized dictionary > 'a' as a default value? > How can I make it work? > > >>> def A(): > ... global a > ... a = {} > ... a['happyface']=1 > ... a['sadface']=99 > ... > >>> def B(b=a): > ... for item in b: > ... print b > ... > Traceback (most recent call last): > File "", line 1, in ? > NameError: name 'a' is not defined You didn't run A(), so a variable doesn't exist yet. If you run A(), you can then define B like this.. -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From dyoo@hkn.eecs.berkeley.edu Wed Aug 15 08:11:21 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 15 Aug 2001 00:11:21 -0700 (PDT) Subject: [Tutor] global statement? In-Reply-To: Message-ID: On Wed, 15 Aug 2001, Haiyang wrote: > Could anyone please tell me WHY function B can't take globalized dictionary > 'a' as a default value? > How can I make it work? > > >>> def A(): > ... global a > ... a = {} > ... a['happyface']=1 > ... a['sadface']=99 > ... > >>> def B(b=a): > ... for item in b: > ... print b > ... > Traceback (most recent call last): > File "", line 1, in ? > NameError: name 'a' is not defined > Try this: ### >>> def A(): ... global a ... a = {} ... a['happyface'] = 1 ... a['sadface'] = 99 ... >>> a = {} >>> def B(b=a): ... for item in b: ... print b ... >>> B() Traceback (most recent call last): File "", line 1, in ? File "", line 2, in B TypeError: loop over non-sequence ### In Python, we create variables by assigning to them. Although A() declares that somewhere, outside the function, there's a global variable called 'a', B doesn't know that. The error message is coming from the defintion of B: it's during function definition time that B will know that 'b' will be 'a'. Gosh, I feel like Ayn Rand for some odd reason. It's sorta similar to the behavior we saw a few messages ago: ### >>> def testMutableDefaultArg(mylist = []): ... mylist.append('B is B') ... return mylist ... >>> testMutableDefaultArg() ['B is B'] >>> testMutableDefaultArg() ['B is B', 'B is B'] >>> testMutableDefaultArg(['A is A']) ['A is A', 'B is B'] >>> testMutableDefaultArg() ['B is B', 'B is B', 'B is B'] ### If we define a default argument while mixing up a function, Python needs to know what that value is. Hope this helps! From toodles@yifan.net Wed Aug 15 09:50:24 2001 From: toodles@yifan.net (Andrew Wilkins) Date: Wed, 15 Aug 2001 16:50:24 +0800 Subject: [Tutor] Recursive combinations? Message-ID: Hi all, I'm trying to make combinations of 2 out of a set {1,2,3,...,n} I can do it for a predefined set where n=10 using the following: part1=[] for a in range(1,11): for b in range(a+1,11): part1.append((a,b)) Is there some way I can make a recursive function so this combination function can be extended where the amount of items in a combination could be larger? For example for 3 items I'd just add another nested loop: part1=[] for a in range(1,11): for b in range(a+1,11): for c in range(b+1,11) part1.append((a,b,c)) There's an obvious pattern, so that's why I thought of recursion. However I can't seem to get my head around recursion, even after going through and understanding Alan Gauld's tutorial on it. (By the way, _no_ this isn't for homework *grin*) Thanks, Andrew Wilkins From tim.one@home.com Wed Aug 15 10:27:06 2001 From: tim.one@home.com (Tim Peters) Date: Wed, 15 Aug 2001 05:27:06 -0400 Subject: [Tutor] Windows, Python and me In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66BE83@mbtlipnt02.btlabs.bt.co.uk> Message-ID: [alan.gauld@bt.com] > ... > [Aside: I never understood why MS didn't have a registry > key that got loaded from Autoexec instead of relying on > PATH... Or maybe they do, in which case what is it? > And shouldn't new apps set that instead? ] An app can set a PATH that *it* wants to use via fiddling the registry, but that doesn't help you find the app to begin with. In MS's current view, autoexec.bat shouldn't exist (e.g., you can't get an app certified for Windows if it touches autoexec.bat, and a little-known fact is that Win9X runs fine even if you don't have *any* autoexec.bat); and that command lines are an anachronism. So long as you launch every program by clicking on something, that "something" is supoosed to have the path to the executable more-or-less hardwired into it, invisible to users. >> We do set file associations, although I don't find them >> useful for Python on Win9x. > Really? Yes, but I'm old and am much more comfortable in a DOS box . > I couldn't live without them. Its how I launch nearly > all my python scripts - just double click the file oir type > the name in Start|Run... That's why I keep teaching our Windows installer how to set up the darned asssociations -- and I test that once per release . ... >> The former (Start|Run) has to do with a different registry >> setting, neither with PATH nor with file associations. > Now that I didn't know! Which one? The same one that gets looked up by magic if you do start python from a DOS prompt; it's under key HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\ App Paths\Python.exe The default value of that key is the path to the executable (and that's how Start|Run finds it). Peek (don't poke!) around in that part of the registry and you'll see other possibilities; for example, the way for an app to register its own PATH setting is to create a value named "Path" under that key, with string data giving the PATH setting it wants. > Is that set by the installer coz I must admit thats how I > usually get a Python prompt rather than start a DOS box > per se. Maybe thats why I assumed PATH was being set? Yes, I go through a lot of pain to set that up . Unfortunately, MS seemed to have the *start* of a good idea here but didn't follow through. >From a random DOS prompt, you can't generally get away with doing python whatever.py (if python isn't on your path), but you *can* get away with start python whatever.py (again thanks to the registry key above). Even better would be if you could get away with whatever.py or just plain whatever (and in NT and 2000, you can get close to the latter via setting the PATHEXT envar apprporiately). >> Windows is very consistent . > Consistently frustrating that's for sure :-) Yup. The more you learn about it, the more depressing it gets. > As a recent email dialog with Michael showed I am now in the > pitiable state of being sufficiently immersed in Windoze > to have forgotten much of my Unix knowledge but not enough > into Windows to be an expert there - yet? I'm not sure it's worth trying. *I'm* no Windows expert -- I'm not a Windows developer, I'm just a developer who, for business reasons, got stuck using Windows in '94. As an end-user, I actually like it a lot; but as a developer, it drives me nuts. A co-worker once explained it in terms that still ring true: Windows developement is like wading through a boundless ocean that's a quarter of an inch deep. That is, it's endless but very shallow -- you can wait for years to get the "aha!" kind of unifying experience you eventually get on, say, Unix, but it never comes. Instead it's the world's largest (outside of IBM, I guess ) random collection of endlessly layered backward compatibility hacks. For anything you want to do, you can find ten ways in the docs that *might* be appropriate, but you find out the hard way nine of them don't work, and eventually you find the one way that does work -- but you never understand why. I hope Windows XP catches on big, so that we can finally have some hope of leaving behind the worst of the DOS/Win3.1/Win9x legacy. Technologies like COM are really mondo cool; but it's hard to get to the point where you can appreciate them when you have to reboot the machine once an hour. ventingly y'rs - tim From Ecevit.Karakus@aprimus.de Wed Aug 15 11:18:30 2001 From: Ecevit.Karakus@aprimus.de (Karakus, Ecevit) Date: Wed, 15 Aug 2001 12:18:30 +0200 Subject: [Tutor] (no subject) Message-ID: Hello Hackers ! I need your Help for this Problem: I want to start with using Python for WebServer-Scripting. especialy Active-X Scripting. I use Active-State 2.1, and startred with the Examples: D:// ..... AcPython2.1\win32comext\axscript\demos\client\ie ... They all dont work, although I registrated the AXEngine with the script PYscript.py. In this context there is another Question: If I call The Python Com Reference of PythonWin and look on the ActiveX-Scripting Demos They all work in the Context of the Help-Viewer. But If I use the Same Html-Sides wich are used from the Help-Viewer with the Python-Scripts includes these dont work. There is something wrong with Path or Registration .... So what to do ?? From scarblac@pino.selwerd.nl Wed Aug 15 11:26:29 2001 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Wed, 15 Aug 2001 12:26:29 +0200 Subject: [Tutor] Recursive combinations? In-Reply-To: ; from toodles@yifan.net on Wed, Aug 15, 2001 at 04:50:24PM +0800 References: Message-ID: <20010815122629.A19518@pino.selwerd.nl> On 0, Andrew Wilkins wrote: > I'm trying to make combinations of 2 out of a set {1,2,3,...,n} > I can do it for a predefined set where n=10 using the following: > > part1=[] > > for a in range(1,11): > for b in range(a+1,11): > part1.append((a,b)) > > Is there some way I can make a recursive function so this combination > function can be extended where the amount of items in a combination could be > larger? For example for 3 items I'd just add another nested loop: > > part1=[] > > for a in range(1,11): > for b in range(a+1,11): > for c in range(b+1,11) > part1.append((a,b,c)) > > There's an obvious pattern, so that's why I thought of recursion. However I > can't seem to get my head around recursion, even after going through and > understanding Alan Gauld's tutorial on it. > > (By the way, _no_ this isn't for homework *grin*) In the case of n == 0, there is a single combination, (). The combinations of length n (n > 0) are just the combinations of length n-1, with to each added the numbers 1 to n (either at the beginning or the end). so something like (no error checking done on the input, not tested): def combinations(length, n): if length == 0: return [()] # Single combination, the empty one return [ (i,)+combination for combination in combinations(length-1, n) for i in range(1, n+1) ] Excuses for the overly functional style - though it's quite neat in this case :-). Hmm. I just thought of ways to write that as a lambda. And I've never even written Lisp, and no Haskell in years. Time to go write Python again :) (Hi all, was disinterested for a while because of being busy etc, think I'll be back now) -- Remco Gerlich From toodles@yifan.net Wed Aug 15 13:03:10 2001 From: toodles@yifan.net (Andrew Wilkins) Date: Wed, 15 Aug 2001 20:03:10 +0800 Subject: [Tutor] Recursive combinations? In-Reply-To: <20010815122629.A19518@pino.selwerd.nl> Message-ID: Thanks Remco! I tried it out - doesn't do _quite_ what I wanted, but with that (beautiful) code I can change it to do what I want! It just needs to remove reverse orders (eg. (1,2) and (2,1), and remove like elements in pairs (eg. (1,1)). > Excuses for the overly functional style - though it's quite neat in > this case :-). Well I love it :) > > Hmm. I just thought of ways to write that as a lambda. And I've never even > written Lisp, and no Haskell in years. Time to go write Python again :) > > (Hi all, was disinterested for a while because of being busy etc, think > I'll be back now) Welcome back! Andrew Wilkins From scarblac@pino.selwerd.nl Wed Aug 15 13:18:00 2001 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Wed, 15 Aug 2001 14:18:00 +0200 Subject: [Tutor] Recursive combinations? In-Reply-To: ; from toodles@yifan.net on Wed, Aug 15, 2001 at 08:03:10PM +0800 References: <20010815122629.A19518@pino.selwerd.nl> Message-ID: <20010815141800.A19745@pino.selwerd.nl> On 0, Andrew Wilkins wrote: > Thanks Remco! > I tried it out - doesn't do _quite_ what I wanted, but with that (beautiful) > code I can change it to do what I want! It just needs to remove reverse > orders (eg. (1,2) and (2,1), and remove like elements in pairs (eg. (1,1)). Oh, right. I'm immediately back to my old style of posting - almost, but not quite :) Both are easily remedied by generating only combinations that are in strictly ascending (or descending) order. That means using range(1, combination[0]), but unfortunately that needs an extra check for length == 1. def combinations(length, n): if length == 0: return [()] if length == 1: return [(i,) for i in range(1,n+1)] return [ (i,)+combination for combination in combinations(length-1, n) for i in range(1, combination[0]) ] -- Remco Gerlich From Charlie Clark Wed Aug 15 13:23:27 2001 From: Charlie Clark (Charlie Clark) Date: Wed, 15 Aug 2001 14:23:27 +0200 Subject: [Tutor] Re: Tutor digest, Vol 1 #1020 - 16 msgs References: Message-ID: <00038b90a01178fd_mailit@mail.isis.de> >I'm not sure it's worth trying. *I'm* no Windows expert -- I'm not a >Windows developer, I'm just a developer who, for business reasons, got stuck >using Windows in '94. As an end-user, I actually like it a lot; but as a >developer, it drives me nuts. have to agree with you there. The dos box just isn't a shell :-(( Double-clicking is nice but OS/2 always did it better. On second thoughts I don't even like using windows as end user. Maybe the interface won a prize for obfuscation on one of the perl websites? > A co-worker once explained it in terms that >still ring true: Windows developement is like wading through a boundless >ocean that's a quarter of an inch deep. You might add that it is a treacle ocean. >That is, it's endless but very >shallow -- you can wait for years to get the "aha!" kind of unifying >experience you eventually get on, say, Unix, but it never comes. Instead >it's the world's largest (outside of IBM, I guess ) random collection >of endlessly layered backward compatibility hacks. Hey, back to the future! Isn't that what Python 2.4's supposed to be ;-) At least IBM do document most of their hacks. >one way that does work -- but you never understand why. > >I hope Windows XP catches on big, so that we can finally have some hope of >leaving behind the worst of the DOS/Win3.1/Win9x legacy. Technologies like >COM are really mondo cool; but it's hard to get to the point where you can >appreciate them when you have to reboot the machine once an hour. sigh, maybe not but having to ask Microsoft's permission to switch the machine kind of weighs against it. Will there ever be compulsory registration for Python based on serial numbers of the various kinds of Spam in your cupboard and will our Spam have to be officially approved and certified? Whatever the weather I can do my Python development on an OS of my choice and know it will work on windows. Three cheers for Python. Charlie From alan.gauld@bt.com Wed Aug 15 14:29:20 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 15 Aug 2001 14:29:20 +0100 Subject: [Tutor] global statement? Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BE99@mbtlipnt02.btlabs.bt.co.uk> > > Could anyone please tell me WHY function B can't take > > globalized dictionary 'a' as a default value? > > How can I make it work? >>> def A(): ... global a ... a = {} ... # etc/... > You didn't run A(), so a variable doesn't exist yet. > If you run A(), you can then define B like this.. Now that's interesting. I didn't realize global would have that effect, I expected a name error on the assignment. Instead it simply creates a new name in the global namespace. I still don't like it as a matter of style but I'm interested that it does work and in fact creates new variables in the imported modules namespace if placed in a module... Now, is that better than doing import foo foo.a = 56 ??? I'm not sure. I'm off to ponder. Alan G > > -- > Cymbaline: intelligent learning mp3 player - python, linux, console. > get it at: cy.silmarill.org > > From lsloan@umich.edu Wed Aug 15 14:51:15 2001 From: lsloan@umich.edu (Lance E Sloan) Date: Wed, 15 Aug 2001 09:51:15 -0400 Subject: [Tutor] question about removing items from a list In-Reply-To: Your message of "Wed, 15 Aug 2001 01:57:01 BST." <3B79D6ED.22611.3116FBD@localhost> Message-ID: <200108151351.JAA29461@birds.us.itd.umich.edu> "Allan Crooks" wrote: > An even better way would be like this: > > del lista[:] > > That would delete all items within the list. Doing 'del lista' would > simply delete the list itself. What about: lista = [] That would give the intended effect, but I wonder what happens to the original list that lista pointed to. Does it hang around in memory, or does Python's garbage collection get rid of it as soon as nothing points to it any longer? -- Lance E Sloan Web Services, Univ. of Michigan: Full-service Web and database design, development, and hosting. Specializing in Perl & Python CGIs. http://websvcs.itd.umich.edu/ - "Putting U on the Web" From rob@jam.rr.com Wed Aug 15 15:23:17 2001 From: rob@jam.rr.com (Rob Andrews) Date: Wed, 15 Aug 2001 09:23:17 -0500 Subject: [Tutor] global statement? References: <5104D4DBC598D211B5FE0000F8FE7EB20E66BE99@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <3B7A85D5.83EE65D9@jam.rr.com> > Now that's interesting. I didn't realize global would have > that effect, I expected a name error on the assignment. > Instead it simply creates a new name in the global namespace. > > I still don't like it as a matter of style but I'm interested > that it does work and in fact creates new variables in the > imported modules namespace if placed in a module... > > Now, is that better than doing > > import foo > foo.a = 56 > > ??? I'm not sure. > I'm off to ponder. > > Alan G > *Learning Python* (pp. 99-105) points out that declaring globals from within functions is possible, and shows how. I'm trying to think of *why* one might want to declare or modify a global from within a function. A friend who knows quite a bit more than I do about the subject said "That's the first thing about python I've seen that really makes me go "yecchhh.". Global variables have to be declared outside the scope of any functions or methods in almost every langauge except Perl." stumped, Rob -- A {} is a terrible thing to waste. Useless Python! http://www.lowerstandard.com/python From urmost@europe.com Wed Aug 15 15:07:20 2001 From: urmost@europe.com (=?windows-1251?Q?=DE=F0=E8=E4=E8=F7=E5=F1=EA=E8=E9_=F6=E5=ED=F2=F0_=CC=CE=D1=D2?=) Date: Wed, 15 Aug 2001 18:07:20 +0400 Subject: [Tutor] =?windows-1251?Q?=CD=C0=CB=CE=C3=CE=C2=C0=DF_=CF=CE=CB=C8=D6=C8=DF_=CD=C5_=C4=D0=C5=CC=CB=C5=D2_!!!?= Message-ID: <25102001831514720469@Yang> ------=_NextPart_84815C5ABAF209EF376268C8 Content-type: text/plain; charset="windows-1251" Уважаемые господа! Вы работаете со своим предприятием более 2х лет? У вас есть задолженность перед бюджетом? Таким образом повышается вероятность проверки Вашего предприятия налоговой инспекцией, а возможно налоговой полицией. Требуется обязательное проведение дорогостоящей аудиторской проверки. ВЫХОД ЕСТЬ!!! Юридическая фирма «МОСТ» свидетельствует Вам свое почтение и имеет честь предложить Вам услуги по ликвидации предприятий. У Вас есть возможность выбрать наиболее приемлемый вариант. 1.Ликвидация сменой учредителей и руководства. Мы производим назначение нового директора, смену учредителей и перерегистрацию изменений в регистрационной палате, а также уведомление об этом ИМНС и фондов. Наш директор ЛИЧНО в вашем присутствии готов принять все документы Вашего предприятия по акту приема-передачи. Проблемы с задолженностью перед бюджетом могут вас не волновать. Если не сдавались балансы, то мы сделаем и сдадим их в ИМНС сами. Стоимость услуги - 400 дол. Срок исполнения - 1,5-2 мес. 2.Ликвидация слиянием. Ликвидация осуществляется слиянием Вашей фирмы с предприятием, зарегистрированным в г. Тверь, при этом права и обязанности Вашей фирмы переходят к вновь образованному юридическому лицу.Стоимость услуги - 550 дол. Срок исполнения - 5-7 мес. 3.Официальная ликвидация. Ликвидация юридического лица влечет его прекращение без перехода прав и обязанностей в порядке правопреемства к другим лицам. Этот вид ликвидации предприятия сопряжен со сдачей ликвидационного баланса и, как правило, с проверкой налоговой инспекции.Стоимость услуги - 1200 дол Срок исполнения работы - 5-7 мес. ЕСЛИ ВЫ ПРОИЗВОДИТЕ ТОВАРЫ И УСЛУГИ, ТО МЫ МОЖЕМ РАССМОТРЕТЬ ВАРИАНТ ОПЛАТЫ НАШИХ УСЛУГ ПРОИЗВОДИМЫМИ ВАМИ ТОВАРАМИ ИЛИ УСЛУГАМИ. Юридическая фирма "МОСТ" Ул. Кузнецкий Мост, д. 19, стр.1 Тел./факс (095) 105-75-85 (многоканальный), 928-22-25 928-45-88, 928-12-45, 921-56-17 E-mail: urmost@europe.com www.likvid.ru МЫ ВСЕ СДЕЛАЕМ ЗА ВАС! P.S. Если Вы не хотите в дальнейшем получать нашу информацию, то можете исключить свой адрес tutor@python.org из списка рассылки. Для этого нажмите на ссылку: http://www.likvid.ru/unsub2/index.php?email=tutor@python.org&SUBMIT=UnSubscr ibe ------=_NextPart_84815C5ABAF209EF376268C8 Content-Type: text/html; charset="windows-1251"
    Уважаемые господа!

    Вы работаете со своим предприятием более 2х лет?
    У вас есть задолженность перед бюджетом?
    Таким образом повышается вероятность проверки Вашего предприятия налоговой инспекцией, а возможно налоговой полицией. Требуется обязательное проведение дорогостоящей аудиторской проверки.

    ВЫХОД ЕСТЬ!!!

    Юридическая фирма «МОСТ» свидетельствует Вам свое почтение
    и имеет честь предложить Вам услуги по
    ликвидации предприятий.
    У Вас есть возможность выбрать наиболее приемлемый вариант.

    1.Ликвидация сменой учредителей и руководства. Мы производим назначение нового директора, смену учредителей и перерегистрацию изменений в регистрационной палате, а также уведомление об этом ИМНС и фондов. Наш директор ЛИЧНО в вашем присутствии готов принять все документы Вашего предприятия по акту приема-передачи.
    Проблемы с задолженностью перед бюджетом могут вас не волновать.
    Если не сдавались балансы, то мы сделаем и сдадим их в ИМНС сами.
    Стоимость услуги - 400 дол.
    Срок исполнения - 1,5-2 мес.

    2.Ликвидация слиянием. Ликвидация осуществляется слиянием Вашей фирмы с предприятием, зарегистрированным в г. Тверь, при этом права и обязанности Вашей фирмы переходят к вновь образованному юридическому лицу.
    Стоимость услуги - 550 дол.
    Срок исполнения - 5-7 мес.

    3.Официальная ликвидация. Ликвидация юридического лица влечет его прекращение без перехода прав и обязанностей в порядке правопреемства к другим лицам. Этот вид ликвидации предприятия сопряжен со сдачей ликвидационного баланса и, как правило, с проверкой налоговой инспекции.
    Стоимость услуги - 1200 дол
    Срок исполнения работы - 5-7 мес.

    ЕСЛИ ВЫ ПРОИЗВОДИТЕ ТОВАРЫ И УСЛУГИ, ТО МЫ МОЖЕМ
    РАССМОТРЕТЬ ВАРИАНТ ОПЛАТЫ НАШИХ УСЛУГ
    ПРОИЗВОДИМЫМИ ВАМИ ТОВАРАМИ ИЛИ УСЛУГАМИ.

    Юридическая фирма "МОСТ"
    Ул. Кузнецкий Мост, д. 19, стр.1
    Тел./факс (095) 105-75-85 (многоканальный), 928-22-25
    928-45-88, 928-12-45, 921-56-17

    E-mail: urmost@europe.com
    www.likvid.ru

    МЫ ВСЕ СДЕЛАЕМ ЗА ВАС!

    P.S. Если Вы не хотите в дальнейшем получать нашу информацию,
    то можете исключить свой адрес tutor@python.org из списка рассылки.
    Для этого нажмите на ссылку:

    http://www.likvid.ru/unsub2/index.php?email=tutor@python.org& SUBMIT=UnSubscribe ------=_NextPart_84815C5ABAF209EF376268C8-- From dsh8290@rit.edu Wed Aug 15 15:33:58 2001 From: dsh8290@rit.edu (dman) Date: Wed, 15 Aug 2001 10:33:58 -0400 Subject: [Tutor] question about removing items from a list In-Reply-To: <200108151351.JAA29461@birds.us.itd.umich.edu>; from lsloan@umich.edu on Wed, Aug 15, 2001 at 09:51:15AM -0400 References: <3B79D6ED.22611.3116FBD@localhost> <200108151351.JAA29461@birds.us.itd.umich.edu> Message-ID: <20010815103358.C9267@harmony.cs.rit.edu> On Wed, Aug 15, 2001 at 09:51:15AM -0400, Lance E Sloan wrote: | | "Allan Crooks" wrote: | > An even better way would be like this: | > | > del lista[:] | > | > That would delete all items within the list. Doing 'del lista' would | > simply delete the list itself. | | What about: | | lista = [] | | That would give the intended effect, but I wonder what happens to the | original list that lista pointed to. Does it hang around in memory, | or does Python's garbage collection get rid of it as soon as nothing | points to it any longer? It depends -- does any other binding refer to it? If not then it will be gc'd sooner or later. CPython happens to release it sooner (based on ref counting) but Jython must wait until the Java gc gets around to freeing the objects. The proper techinque (of the 3 given above) depends on what your intent is. -D From SBrunning@trisystems.co.uk Wed Aug 15 15:38:21 2001 From: SBrunning@trisystems.co.uk (Simon Brunning) Date: Wed, 15 Aug 2001 15:38:21 +0100 Subject: [Tutor] question about removing items from a list Message-ID: <31575A892FF6D1118F5800600846864D78BFB1@intrepid> > From: Lance E Sloan [SMTP:lsloan@umich.edu] > "Allan Crooks" wrote: > > An even better way would be like this: > > > > del lista[:] > > > > That would delete all items within the list. Doing 'del lista' would > > simply delete the list itself. > > What about: > > lista = [] Maybe - it isn't quite the same. Consider the following: >>> firstlist = [1, 2, 3] >>> secondlist = firstlist >>> del firstlist[:] >>> firstlist [] >>> secondlist [] versus: >>> firstlist = [1, 2, 3] >>> secondlist = firstlist >>> firstlist = [] >>> firstlist [] >>> secondlist [1, 2, 3] So, Allan's approach deleted all items from the existing list, whereas yours creates a new list, and binds the 'firstlist' name to it, but leaves the existing list intact. If you have no other references to the original list, then it doesn't make much difference, but it is worth bearing in mind. > That would give the intended effect, but I wonder what happens to the > original list that lista pointed to. Does it hang around in memory, > or does Python's garbage collection get rid of it as soon as nothing > points to it any longer? In CPython, it goes away immediately. (This is because it's reference count drops to zero rather than as a result of GC - CPython GC only picks up objects caught in cyclic references.) This is implementation dependant, though - in Jython, Java's GC *will* free up the memory used by the list. Eventually. Cheers, Simon Brunning TriSystems Ltd. sbrunning@trisystems.co.uk ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From allan.crooks@btinternet.com Wed Aug 15 15:52:38 2001 From: allan.crooks@btinternet.com (Allan Crooks) Date: Wed, 15 Aug 2001 15:52:38 +0100 Subject: [Tutor] question about removing items from a list In-Reply-To: <200108151351.JAA29461@birds.us.itd.umich.edu> References: Your message of "Wed, 15 Aug 2001 01:57:01 BST." <3B79D6ED.22611.3116FBD@localhost> Message-ID: <3B7A9AC6.17546.1B2EE5A@localhost> On 15 Aug 2001, at 9:51, Lance E Sloan wrote: > > "Allan Crooks" wrote: > > An even better way would be like this: > > > > del lista[:] > > > > That would delete all items within the list. Doing 'del lista' would > > simply delete the list itself. > > What about: > > lista = [] > > That would give the intended effect, but I wonder what happens to the > original list that lista pointed to. Does it hang around in memory, > or does Python's garbage collection get rid of it as soon as nothing > points to it any longer? The garbage collector deletes the old list right away. Initially I did this (and tried variations, like lista = lista[0:0}) as an attempt to remove all elements in the list, and both lists had the same id() address, but I then realised it was Python removing the old list and putting the new one in the same memory slot And then I remembered about the "del" command, and suggested that. :) Allan. From dsh8290@rit.edu Wed Aug 15 16:23:06 2001 From: dsh8290@rit.edu (dman) Date: Wed, 15 Aug 2001 11:23:06 -0400 Subject: [Tutor] global statement? In-Reply-To: <3B7A85D5.83EE65D9@jam.rr.com>; from rob@jam.rr.com on Wed, Aug 15, 2001 at 09:23:17AM -0500 References: <5104D4DBC598D211B5FE0000F8FE7EB20E66BE99@mbtlipnt02.btlabs.bt.co.uk> <3B7A85D5.83EE65D9@jam.rr.com> Message-ID: <20010815112306.A9461@harmony.cs.rit.edu> On Wed, Aug 15, 2001 at 09:23:17AM -0500, Rob Andrews wrote: | *Learning Python* (pp. 99-105) points out that declaring globals from | within functions is possible, and shows how. I'm trying to think of | *why* one might want to declare or modify a global from within a | function. | | A friend who knows quite a bit more than I do about the subject said | "That's the first thing about python I've seen that really makes me go | "yecchhh.". Global variables have to be declared outside the scope of | any functions or methods in almost every langauge except Perl." The only reason the 'global' statement exists is to allow _assignment_ to a global name. If the global statement is left out then the assignment will create a new _local_ binding that overshadows the global one. Reading a global variable requires no special syntax. Usually global variables will be created in their global context (ie at module level), but sometimes may need to be changed. I think that configuration options are a good example of this -- some module should have all the global configuration options and initially they will have a default value. Then a function (or more) may parse some config file and modify those global variable to contain their new values. Admittedly 'global' has limited usefulness in a well-designed program but it does have its place. HTH, -D From rob@jam.rr.com Wed Aug 15 16:27:22 2001 From: rob@jam.rr.com (Rob Andrews) Date: Wed, 15 Aug 2001 10:27:22 -0500 Subject: [Tutor] global statement? References: <5104D4DBC598D211B5FE0000F8FE7EB20E66BE99@mbtlipnt02.btlabs.bt.co.uk> <3B7A85D5.83EE65D9@jam.rr.com> <20010815112306.A9461@harmony.cs.rit.edu> Message-ID: <3B7A94DA.6AC7B992@jam.rr.com> dman wrote: > > On Wed, Aug 15, 2001 at 09:23:17AM -0500, Rob Andrews wrote: > > | *Learning Python* (pp. 99-105) points out that declaring globals from > | within functions is possible, and shows how. I'm trying to think of > | *why* one might want to declare or modify a global from within a > | function. > | > | A friend who knows quite a bit more than I do about the subject said > | "That's the first thing about python I've seen that really makes me go > | "yecchhh.". Global variables have to be declared outside the scope of > | any functions or methods in almost every langauge except Perl." > > The only reason the 'global' statement exists is to allow _assignment_ > to a global name. If the global statement is left out then the > assignment will create a new _local_ binding that overshadows the > global one. Reading a global variable requires no special syntax. > > Usually global variables will be created in their global context (ie > at module level), but sometimes may need to be changed. I think that > configuration options are a good example of this -- some module should > have all the global configuration options and initially they will have > a default value. Then a function (or more) may parse some config file > and modify those global variable to contain their new values. > Admittedly 'global' has limited usefulness in a well-designed program > but it does have its place. > > HTH, > -D > I can buy that, and it's about what I figured. But since I haven't had to use a global variable in any sophisticated way since Pascal (which for me was a number of years ago), I was uncertain. As Always, Thanks, Rob -- A {} is a terrible thing to waste. Useless Python! http://www.lowerstandard.com/python From alan.gauld@bt.com Wed Aug 15 17:51:46 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 15 Aug 2001 17:51:46 +0100 Subject: [Tutor] global statement? Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BE9D@mbtlipnt02.btlabs.bt.co.uk> > | "yecchhh.". Global variables have to be declared outside > | any functions or methods in almost every langauge except Perl." That was my initial reaction too. I was surprised global had the side effect of allowing creation of global variables from inside a function. But when you stop and think about how Pythons namespace mechanism works it makes sense. I still don't like it as a mettter of style. > The only reason the 'global' statement exists is to allow _assignment_ > to a global name. If the global statement is left out then the > assignment will create a new _local_ binding that overshadows the > global one. Reading a global variable requires no special syntax. Yes and thats what I thought global did - allowed assignment to an already existing variable declared external to the function. In fact it tells python that any references to the variable are interpreted in the context of the global namespace thus assignment will create a new variable. So: #### seta.py #### def setA(n): global a a = n ################# ### main.py ##### import seta # print seta.a # a name error, no a exists yet for j in range(10): seta.setA(j) print seta.a # now exists and set to 9 seta.a = "Now a string!" print seta.a # now set to the string ################# creates a new variable 'a' in the seta namespace. Sets it to the values from 0-9 The ability to create a new variable in seta via a call to a function could be used as a powerful form of data abstraction I guess. Almost a kind of data hiding - except its not really hidden! > Usually global variables will be created in their global context (ie > at module level), but sometimes may need to be changed. Yes that's fine > Admittedly 'global' has limited usefulness in a well-designed program > but it does have its place. No issue about global its the 'side-effect' of creating a new variable inside the call to the function. Effectively this makes the module stateful - definitely a mixed blessing. A bug or a feature? hmmm. Alan g. From dyoo@hkn.eecs.berkeley.edu Wed Aug 15 18:21:00 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 15 Aug 2001 10:21:00 -0700 (PDT) Subject: [Tutor] question about removing items from a list In-Reply-To: <200108151351.JAA29461@birds.us.itd.umich.edu> Message-ID: On Wed, 15 Aug 2001, Lance E Sloan wrote: > > "Allan Crooks" wrote: > > An even better way would be like this: > > > > del lista[:] > > > > That would delete all items within the list. Doing 'del lista' would > > simply delete the list itself. > > What about: > > lista = [] > > That would give the intended effect, but I wonder what happens to the > original list that lista pointed to. Does it hang around in memory, > or does Python's garbage collection get rid of it as soon as nothing > points to it any longer? Garbage collection: Python won't really delete things until they're inaccessable to us. >From one point of view, the really big difference between: del lista and lista = [] is that 'del' will also remove the name from our namespace: ### >>> lista = ['forth', 'eorlingas!'] >>> lista = [] >>> lista [] >>> lista = ['there', 'is', 'no', 'spoon'] >>> del lista >>> lista Traceback (most recent call last): File "", line 1, in ? NameError: name 'lista' is not defined ### So using 'del' depends on our expectation to use the name 'lista' later in the program. From W.JarrettCampbell Wed Aug 15 18:53:31 2001 From: W.JarrettCampbell (W.JarrettCampbell) Date: Wed, 15 Aug 2001 13:53:31 -0400 Subject: [Tutor] Sorting dictionary values Message-ID: > > I'm no longer subscribed to this list, but you guys were so helpful when I was learning Python a few months ago I thought I'd throw this one at you. Please respond to my email address directly in addition to any posts to the list since I'm no longer an active subscriber...thanks! > > > Problem: > ------ > I'm building a "Leader Board" application which tracks user names and displays the top 10 scores from a contest W. Jarrett Campbell, Ph.D. Member of Technical Staff Yield Dynamics, Inc. 5838 Balcones Drive, Suite 101 Austin, TX 78731 512.323.9149 phone 512.415.1078 mobile 512.257.9503 fax> > I'm using shelve/pickle for my persistence so basically what I'm confronted with is something that looks like this: > > userDB = {uniqueUserID:userData} > > where userData is itself a dictionary like > > userData = {"fname": "Jarrett", > "lname": "Campbell", > "email": "jarrett@ydyn.com", > "score":"98.8"} > > > What I need to do is find the 10 uniqueUserIDs from userDB where the value of "score" is the in the top 10 of all the records and sort them in order from highest to lowestW. Jarrett Campbell, Ph.D. > Member of Technical Staff > Yield Dynamics, Inc. > 5838 Balcones Drive, Suite 101 > Austin, TX 78731 > > 512.323.9149 phone > 512.415.1078 mobile > 512.257.9503 fax. Once that is done, I have a routine to display the leaderboard. > > > Any suggestions for an efficient way to do this? > > Jarrett Campbell > jarrett@ydyn.com > From dyoo@hkn.eecs.berkeley.edu Wed Aug 15 18:58:59 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 15 Aug 2001 10:58:59 -0700 (PDT) Subject: [Tutor] source code In-Reply-To: Message-ID: On Tue, 14 Aug 2001, paul wrote: > > On Sun, 12 Aug 2001, paul wrote: > > > > > what exactly is the python source code? and where do i find it? > > > everyone says that it's available for download on the python website, > > > but where is it? i've searched for it on the search engine, and > > > looked about everywhere. i must just not know what it is. > > > > Out of curiosity, is there anything in particular you're searching for in > > the Python source code? > > no, i'm just trying to turn my script into an executable program Ah! In this case, you might want to use Py2Exe instead: you won't need Python's source code to use Py2Exe: http://py2exe.sourceforge.net/ From dsh8290@rit.edu Wed Aug 15 19:03:06 2001 From: dsh8290@rit.edu (dman) Date: Wed, 15 Aug 2001 14:03:06 -0400 Subject: [Tutor] Sorting dictionary values In-Reply-To: ; from jarrett@ydyn.com on Wed, Aug 15, 2001 at 01:53:31PM -0400 References: Message-ID: <20010815140306.A9661@harmony.cs.rit.edu> On Wed, Aug 15, 2001 at 01:53:31PM -0400, W. Jarrett Campbell wrote: | > | > I'm no longer subscribed to this list, but you guys were so helpful | > when I was learning Python a few months ago I thought I'd throw this | > one at you. Please respond to my email address directly in addition | > to any posts to the list since I'm no longer an active | > subscriber...thanks! | > | > | > Problem: | > ------ | > I'm building a "Leader Board" application which tracks user names | > and displays the top 10 scores from a contest | | > I'm using shelve/pickle for my persistence so basically what I'm | > confronted with is something that looks like this: | > | > userDB = {uniqueUserID:userData} | > | > where userData is itself a dictionary like | > | > userData = {"fname": "Jarrett", | > "lname": "Campbell", | > "email": "jarrett@ydyn.com", | > "score":"98.8"} | > | > | > What I need to do is find the 10 uniqueUserIDs from userDB where the | > value of "score" is the in the top 10 of all the records and sort | > them in order from highest to lowest | | > Once that is done, I have a routine to display the leaderboard. | > | > Any suggestions for an efficient way to do this? Dictionaries can't be sorted because the keys are hashed instead. I think you need to iterate over your db and create a list of all the users, then sort them based on score. The easiest way would probably be to make a class for the userData instead of using a plain dictionary -- that way you can define the comparision to behave the way you want it (based on score). ex : class User : def __init__( self , fname , lname , email , score=0 ) : self.fname = fname self.lname = lname self.email = email self.score = score def __lt__( self , other ) : return self.score < other.score def __gt__( self , other ) : return self.score > other.score <...> # # 1) use an number, not a string for the score -- you want to do # numerical comparisions ) # # 2) build the list however you would normally do it # user_list = [ User( "Jarrett" , "Campbell" , "jarrett@ydyn.com" , 98.8 ) , User( "John" , "Doe" , "void@null.com" , 50 ) , ] user_list.sort() print "The top ten are :" print user_list[:10] HTH, -D From lsloan@umich.edu Wed Aug 15 19:11:42 2001 From: lsloan@umich.edu (Lance E Sloan) Date: Wed, 15 Aug 2001 14:11:42 -0400 Subject: [Tutor] .pyc files and executables? Message-ID: <200108151811.OAA20594@birds.us.itd.umich.edu> I'm using Python 2.0 on a UNIX machine (Solaris 2.6) to write some CGIs. I'm trying to find out more about .pyc files, because I think it may improve performance at least a little if I can get my CGIs saved as .pyc files. My Python CGIs start out with a line like this: #!/usr/local/python/bin/python I notice that .pyc files are not created for my main programs whether or not they have a .py extension. However, .pyc files are created for modules (all have .py extensions) that my programs import. Now, I've run Python interactively and created .pyc files for my main programs using the statement, "import myprogram.py". Now I have myprogram.pyc. It's not executable by itself, but I can run it if I use the command, "python myprogram.pyc". What I want to know is this: If I run myprogram.py, which starts up the interpreter, will Python see myprogram.pyc there and use it instead of reparsing the code in myprogram.py? -- Lance E Sloan Web Services, Univ. of Michigan: Full-service Web and database design, development, and hosting. Specializing in Perl & Python CGIs. http://websvcs.itd.umich.edu/ - "Putting U on the Web" From dyoo@hkn.eecs.berkeley.edu Wed Aug 15 19:21:03 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 15 Aug 2001 11:21:03 -0700 (PDT) Subject: [Tutor] Sorting dictionary values In-Reply-To: <20010815140306.A9661@harmony.cs.rit.edu> Message-ID: On Wed, 15 Aug 2001, dman wrote: > On Wed, Aug 15, 2001 at 01:53:31PM -0400, W. Jarrett Campbell wrote: > | > Problem: > | > ------ > | > I'm building a "Leader Board" application which tracks user names > | > and displays the top 10 scores from a contest > | > | > I'm using shelve/pickle for my persistence so basically what I'm > | > confronted with is something that looks like this: > | > > | > userDB = {uniqueUserID:userData} > | > > | > where userData is itself a dictionary like > | > > | > userData = {"fname": "Jarrett", > | > "lname": "Campbell", > | > "email": "jarrett@ydyn.com", > | > "score":"98.8"} > | > > | > > | > What I need to do is find the 10 uniqueUserIDs from userDB where the > | > value of "score" is the in the top 10 of all the records and sort > | > them in order from highest to lowest > | > | > Once that is done, I have a routine to display the leaderboard. [note: This message isn't quite about Python.] Your program is slowly sounding like a relational database. *grin* If you anticipate more complicated queries, you might find it useful to pick up a relational database and see if it would work well for you. There are a few free ones out there, such as MySQL: http://www.mysql.com/ Postgresql: http://postgresql.org/ and Gadfly: http://www.chordate.com/kwParsing/index.html One advantage of using a relational database is that it becomes very easy to ask different kinds of questions to our data. For example, your question: > | > What I need to do is find the 10 uniqueUserIDs from userDB where the > | > value of "score" is the in the top 10 of all the records and sort > | > them in order from highest to lowest could be translated into SQL almost directly: ### query = """select * from users order by score limit 10""" ### Take a look at relational databases: you might find them useful. From dsh8290@rit.edu Wed Aug 15 19:25:18 2001 From: dsh8290@rit.edu (dman) Date: Wed, 15 Aug 2001 14:25:18 -0400 Subject: [Tutor] Sorting dictionary values In-Reply-To: ; from dyoo@hkn.eecs.berkeley.edu on Wed, Aug 15, 2001 at 11:21:03AM -0700 References: <20010815140306.A9661@harmony.cs.rit.edu> Message-ID: <20010815142518.A9710@harmony.cs.rit.edu> On Wed, Aug 15, 2001 at 11:21:03AM -0700, Danny Yoo wrote: ... | Your program is slowly sounding like a relational database. *grin* If you | anticipate more complicated queries, you might find it useful to pick up a | relational database and see if it would work well for you. ... | could be translated into SQL almost directly: | | ### | query = """select * | from users | order by score | limit 10""" | ### Cool. This is a good way to explain _why_ one might want to use a database, other than for relief from creating and parsing custom files, and how it can be useful. Thanks, -D From rob@jam.rr.com Wed Aug 15 20:37:49 2001 From: rob@jam.rr.com (Rob Andrews) Date: Wed, 15 Aug 2001 14:37:49 -0500 Subject: [Tutor] .pyc files and executables? References: <200108151811.OAA20594@birds.us.itd.umich.edu> Message-ID: <3B7ACF8D.7CD928A1@jam.rr.com> Lance E Sloan wrote: > > I'm using Python 2.0 on a UNIX machine (Solaris 2.6) to write some > CGIs. I'm trying to find out more about .pyc files, because I think > it may improve performance at least a little if I can get my CGIs > saved as .pyc files. > > My Python CGIs start out with a line like this: > > #!/usr/local/python/bin/python > > I notice that .pyc files are not created for my main programs whether > or not they have a .py extension. However, .pyc files are created > for modules (all have .py extensions) that my programs import. > > Now, I've run Python interactively and created .pyc files for my > main programs using the statement, "import myprogram.py". Now I have > myprogram.pyc. It's not executable by itself, but I can run it if > I use the command, "python myprogram.pyc". > > What I want to know is this: If I run myprogram.py, which starts up > the interpreter, will Python see myprogram.pyc there and use it > instead of reparsing the code in myprogram.py? > If I'm not mistaken, that's precisely what will happen. If you invoke a python file myprogram.py, it will run myprogram.pyc if it's more recent than the .py version. If myprogram.py has been modified, presumably because you changed something, the interpreter will grab your new version. Rob -- A {} is a terrible thing to waste. Useless Python! http://www.lowerstandard.com/python From delirious@atchoo.be Thu Aug 16 00:10:20 2001 From: delirious@atchoo.be (Simon Vandemoortele) Date: Wed, 15 Aug 2001 22:10:20 -0100 Subject: [Tutor] How does python find the modules I install ??? Message-ID: <01081522102000.27002@shinsekai> This is probably trivial but hey ... I'm a newbie ! I installed Mysql-python and wondering how I am supposed to tell python w= here=20 the modules is. There's something in the FAQ about this=20 problem(http://www.python.org/cgi-bin/faqw.py?req=3Dshow&file=3Dfaq04.011= =2Ehtp)=20 but I'm not sure it really applies to my situation. Thank you for your help. Simon From rob@jam.rr.com Wed Aug 15 21:26:56 2001 From: rob@jam.rr.com (Rob Andrews) Date: Wed, 15 Aug 2001 15:26:56 -0500 Subject: [Tutor] How does python find the modules I install ??? References: <01081522102000.27002@shinsekai> Message-ID: <3B7ADB10.88A45C1D@jam.rr.com> Simon Vandemoortele wrote: > > This is probably trivial but hey ... I'm a newbie ! > > I installed Mysql-python and wondering how I am supposed to tell python where > the modules is. There's something in the FAQ about this > problem(http://www.python.org/cgi-bin/faqw.py?req=show&file=faq04.011.htp) > but I'm not sure it really applies to my situation. > Which Operating System are you using? Rob -- A {} is a terrible thing to waste. Useless Python! http://www.lowerstandard.com/python From delirious@atchoo.be Thu Aug 16 00:39:08 2001 From: delirious@atchoo.be (Simon Vandemoortele) Date: Wed, 15 Aug 2001 22:39:08 -0100 Subject: [Tutor] How does python find the modules I install ??? In-Reply-To: <3B7ADB10.88A45C1D@jam.rr.com> References: <01081522102000.27002@shinsekai> <3B7ADB10.88A45C1D@jam.rr.com> Message-ID: <01081522390800.27205@shinsekai> On Wednesday 15 August 2001 19:26, Rob Andrews wrote: > Simon Vandemoortele wrote: > > This is probably trivial but hey ... I'm a newbie ! > > > > I installed Mysql-python and wondering how I am supposed to tell pyth= on > > where the modules is. There's something in the FAQ about this > > problem(http://www.python.org/cgi-bin/faqw.py?req=3Dshow&file=3Dfaq04= =2E011.htp > >) but I'm not sure it really applies to my situation. > > Which Operating System are you using? > > Rob Sorry bout that ... Linux (SuSe) /:-) --=20 Get Revenge! Live long enough to be a problem for your children! From rob@jam.rr.com Wed Aug 15 21:57:35 2001 From: rob@jam.rr.com (Rob Andrews) Date: Wed, 15 Aug 2001 15:57:35 -0500 Subject: [Tutor] How does python find the modules I install ??? References: <01081522102000.27002@shinsekai> <3B7ADB10.88A45C1D@jam.rr.com> <01081522390800.27205@shinsekai> Message-ID: <3B7AE23F.B4236609@jam.rr.com> Simon Vandemoortele wrote: > > On Wednesday 15 August 2001 19:26, Rob Andrews wrote: > > Simon Vandemoortele wrote: > > > This is probably trivial but hey ... I'm a newbie ! > > > > > > I installed Mysql-python and wondering how I am supposed to tell python > > > where the modules is. There's something in the FAQ about this > > > problem(http://www.python.org/cgi-bin/faqw.py?req=show&file=faq04.011.htp > > >) but I'm not sure it really applies to my situation. > > > > Which Operating System are you using? > > > > Rob > > Sorry bout that ... Linux (SuSe) > > /:-) > I'm not sure what to check on SuSe, but you should have a login script that runs when you log into your linux session. Look for "set path", "PATH=", or similar. Make sure the path to your modules is listed here. Unless you meant something else entirely.... Rob -- A {} is a terrible thing to waste. Useless Python! http://www.lowerstandard.com/python From rob@jam.rr.com Wed Aug 15 22:25:38 2001 From: rob@jam.rr.com (Rob Andrews) Date: Wed, 15 Aug 2001 16:25:38 -0500 Subject: [Tutor] A recreational math problem for Useless Python References: Message-ID: <3B7AE8D2.BBBFA084@jam.rr.com> Daniel Coughlin wrote: > > Well I know this is not a very good solution - but it is my first attempt. > I used the random module to create the number sets ad that can take a long time. > Is there a better way of going about creating the sets? (I dont want to check > the article yet - besides i doubt i will understand any of it ;-) > The other problem I encountered which is probably soaking up time is that there > is an unaccounted for runtime error that happens periodically. I handle this, > but i know it still happens, and it is knawing at me... If anyone can > figure out way that happens, I'd love to know. > > One thing you will notice is that you can change the level of precision by > changing the string slice indexes. > > To get two decimal places over usually takes between 5 and 15 seconds. But > sometimes it takes a while. > BTW - I *really* like problems like this - If you have any others, I'd love to > hear about them. It took me long enough, but your solution has been posted to Useless Python. If you truly enjoy this sort of problem, take a look at some of the (hundreds of) ACM problems available: http://www.lowerstandard.com/python/acmcontest.html Thanks, Rob -- A {} is a terrible thing to waste. Useless Python! http://www.lowerstandard.com/python From lumbricus@gmx.net Wed Aug 15 23:52:09 2001 From: lumbricus@gmx.net (Joerg Woelke) Date: Thu, 16 Aug 2001 00:52:09 +0200 Subject: [Tutor] How does python find the modules I install ??? In-Reply-To: <3B7AE23F.B4236609@jam.rr.com>; from rob@jam.rr.com on Wed, Aug 15, 2001 at 03:57:35PM -0500 References: <01081522102000.27002@shinsekai> <3B7ADB10.88A45C1D@jam.rr.com> <01081522390800.27205@shinsekai> <3B7AE23F.B4236609@jam.rr.com> Message-ID: <20010816005209.A3340@Laplace.localdomain> On Wed, Aug 15, 2001 at 03:57:35PM -0500, Rob Andrews wrote: > Simon Vandemoortele wrote: > > > > On Wednesday 15 August 2001 19:26, Rob Andrews wrote: > > > Simon Vandemoortele wrote: > > > > This is probably trivial but hey ... I'm a newbie ! > > > > > > > > I installed Mysql-python and wondering how I am supposed to tell python > > > > where the modules is. There's something in the FAQ about this > > > > problem(http://www.python.org/cgi-bin/faqw.py?req=show&file=faq04.011.htp > > > >) but I'm not sure it really applies to my situation. > > > > > > Which Operating System are you using? > > > > > > Rob > > > > Sorry bout that ... Linux (SuSe) > > > > /:-) > > > > I'm not sure what to check on SuSe, but you should have a login script > that runs when you log into your linux session. Look for "set path", > "PATH=", or similar. Make sure the path to your modules is listed here. suse linux uses bash as default shell - so it should be $HOME/.bash_profile or /etc/profile (global - for all users) to set up environment with "PATH=blahfasel" But the modules are not in ${PATH} anyway :-) It's $PYTHONHOME or $PYTHONPATH Did you install the rpm? (then there shouldn't be any problems) > > Unless you meant something else entirely.... Or that :-) HTH n' LG J"o! :-) -- Mind your own business, Spock. I'm sick of your halfbreed interference. From tescoil@irtc.net Wed Aug 15 23:55:36 2001 From: tescoil@irtc.net (Tesla Coil) Date: Wed, 15 Aug 2001 17:55:36 -0500 Subject: [Tutor] How does python find the modules I install ??? References: <01081522102000.27002@shinsekai> Message-ID: <3B7AFDE8.DC354AEB@irtc.net> On 15 Aug 2001, Simon Vandemoortele wrote: > I installed Mysql-python and wondering how I am supposed > to tell python where the modules is. There's something > in the FAQ about this problem [...] but I'm not sure it > really applies to my situation. I haven't worked with Mysql-python, but the sourceforge rpm installs to /usr/lib/python1.5/site-packages, which doesn't work for SuSE >= 7.0. Then, sys.path will be looking at /usr/lib/python2.0/site-packages instead. But, it's said to be 2.0 compatible--the rpm is spec'd that way for Red Hat users, I'd guess. You could: import sys sys.path.append('/usr/lib/python1.5/site-packages') ...which is a runtime-only alteration, or, you can mv everything that was installed to 1.5 site-packages to 2.0 site-packages. Kinda blows rpm -e, but you can make a note of it. From dsh8290@rit.edu Thu Aug 16 00:45:08 2001 From: dsh8290@rit.edu (dman) Date: Wed, 15 Aug 2001 19:45:08 -0400 Subject: [Tutor] How does python find the modules I install ??? In-Reply-To: <01081522390800.27205@shinsekai>; from delirious@atchoo.be on Wed, Aug 15, 2001 at 10:39:08PM -0100 References: <01081522102000.27002@shinsekai> <3B7ADB10.88A45C1D@jam.rr.com> <01081522390800.27205@shinsekai> Message-ID: <20010815194508.A9966@harmony.cs.rit.edu> On Wed, Aug 15, 2001 at 10:39:08PM -0100, Simon Vandemoortele wrote: | On Wednesday 15 August 2001 19:26, Rob Andrews wrote: | > Simon Vandemoortele wrote: | > > This is probably trivial but hey ... I'm a newbie ! | > > | > > I installed Mysql-python and wondering how I am supposed to tell python | > > where the modules is. There's something in the FAQ about this | > > problem(http://www.python.org/cgi-bin/faqw.py?req=show&file=faq04.011.htp | > >) but I'm not sure it really applies to my situation. | > | > Which Operating System are you using? | | Sorry bout that ... Linux (SuSe) | | /:-) You only need to make sure that the modules are in $PYTHONPATH (which at runtime translates to sys.path). Usually the default directory is /usr/lib/python/lib so if you put the modules there it should work. (BTW the RPM should have put them there for you, if not it is a bug in the RPM and the maintainer should be bugged and you need to change it for your system). HTH, -D From sendme105@hotmail.com Thu Aug 16 04:05:50 2001 From: sendme105@hotmail.com (James) Date: Wed, 15 Aug 2001 20:05:50 -0700 Subject: [Tutor] Help with CGI login Message-ID: This is a multi-part message in MIME format. ------=_NextPart_000_000E_01C125C5.AE96FBC0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi, Thanks largely to the discussion and help on this list, I was able offer = my 'services' to help download the 25000 mssgs archived from another = list I belong to. Unfortunately, I couldn't get it going in time, and = these archives have since gone offline; they're only available to = listowners now. To get at them, I have to log on here: =20 http://www.listbot.com/cgi-bin/customer?Act=3DNULL I tried to login using my browser, then running my script to download = the mssgs, but it doesn't work. Idealy, I could just add some lines to = my script to login automatically, but I don't know how to do this. =20 Help! The archives go offline permanently on the 20th, so I only have a couple = days to rescue 25K emails from oblivion. =20 Thanks, James ------=_NextPart_000_000E_01C125C5.AE96FBC0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
    Hi,
     
    Thanks largely to the discussion and = help on this=20 list, I was able offer my 'services' to help download the 25000 = mssgs=20 archived from another list I belong to.  Unfortunately, I couldn't = get it=20 going in time, and these archives have since gone offline; they're = only=20 available to listowners now.  To get at them, I have to log on = here: 
     
    http://www.li= stbot.com/cgi-bin/customer?Act=3DNULL
     
    I tried to login using my browser, then = running my=20 script to download the mssgs, but it doesn't work.  Idealy, I could = just=20 add some lines to my script to login automatically, but I don't know how = to do=20 this. 
     
    Help!
     
    The archives go offline permanently on = the 20th, so=20 I only have a couple days to rescue 25K emails from oblivion. =20
     
    Thanks,
     
    James
    ------=_NextPart_000_000E_01C125C5.AE96FBC0-- From dsh8290@rit.edu Thu Aug 16 04:22:04 2001 From: dsh8290@rit.edu (dman) Date: Wed, 15 Aug 2001 23:22:04 -0400 Subject: [Tutor] Help with CGI login In-Reply-To: ; from sendme105@hotmail.com on Wed, Aug 15, 2001 at 08:05:50PM -0700 References: Message-ID: <20010815232204.A10158@harmony.cs.rit.edu> On Wed, Aug 15, 2001 at 08:05:50PM -0700, James wrote: | Hi, | | Thanks largely to the discussion and help on this list, I was able | offer my 'services' to help download the 25000 mssgs archived from | another list I belong to. Unfortunately, I couldn't get it going in | time, and these archives have since gone offline; they're only | available to listowners now. To get at them, I have to log on here: | | http://www.listbot.com/cgi-bin/customer?Act=NULL | | I tried to login using my browser, then running my script to | download the mssgs, but it doesn't work. Idealy, I could just add | some lines to my script to login automatically, but I don't know how | to do this. Login with your browser. Make a note of the URL that is used. That is, identify all form fields and their values. Forms are submitted in the URL. For example, with my DSL connection I need to login via a web form. A big PITA so instead I made a little python script that gets run when the interface is brought up. The core looks like this : urllib.urlopen( "http://www2.frontierdsl.com:9061/dashboard?fcn=serviceLogon&" + "service=frontiernet.dsl&username=myname&password=mypassword").read() I included the read() just so that the data is retrieved from the server, if it cares. HTH, -D From wilson@visi.com Thu Aug 16 04:33:44 2001 From: wilson@visi.com (Timothy Wilson) Date: Wed, 15 Aug 2001 22:33:44 -0500 (CDT) Subject: [Tutor] How does python find the modules I install ??? In-Reply-To: <20010815194508.A9966@harmony.cs.rit.edu> Message-ID: On Wed, 15 Aug 2001, dman wrote: > You only need to make sure that the modules are in $PYTHONPATH (which > at runtime translates to sys.path). Usually the default directory is > /usr/lib/python/lib so if you put the modules there it should > work. (BTW the RPM should have put them there for you, if not it is a > bug in the RPM and the maintainer should be bugged and you need to > change it for your system). I prefer to keep a directory for extra modules in my /home so it won't be blown away in a system upgrade (or other non-planned problem). Another alternative would be /usr/local/share if you have others on the system that would like to access the modules too. -Tim -- Tim Wilson | Visit Sibley online: | Check out: Henry Sibley HS | http://www.isd197.org | http://www.zope.com W. St. Paul, MN | | http://slashdot.org wilson@visi.com | | http://linux.com From dsh8290@rit.edu Thu Aug 16 04:57:39 2001 From: dsh8290@rit.edu (dman) Date: Wed, 15 Aug 2001 23:57:39 -0400 Subject: [Tutor] How does python find the modules I install ??? In-Reply-To: ; from wilson@visi.com on Wed, Aug 15, 2001 at 10:33:44PM -0500 References: <20010815194508.A9966@harmony.cs.rit.edu> Message-ID: <20010815235738.A10202@harmony.cs.rit.edu> On Wed, Aug 15, 2001 at 10:33:44PM -0500, Timothy Wilson wrote: | On Wed, 15 Aug 2001, dman wrote: | | > You only need to make sure that the modules are in $PYTHONPATH (which | > at runtime translates to sys.path). Usually the default directory is | > /usr/lib/python/lib so if you put the modules there it should | > work. (BTW the RPM should have put them there for you, if not it is a | > bug in the RPM and the maintainer should be bugged and you need to | > change it for your system). | | I prefer to keep a directory for extra modules in my /home so it won't be | blown away in a system upgrade (or other non-planned problem). Another | alternative would be /usr/local/share if you have others on the system that | would like to access the modules too. Simply add that directory to your $PYTHONPATH environment variable before running python or add the path to sys.path in a python script. -D From r.b.rigilink@chello.nl Thu Aug 16 06:14:39 2001 From: r.b.rigilink@chello.nl (Roeland Rengelink) Date: Thu, 16 Aug 2001 07:14:39 +0200 Subject: [Tutor] Sorting dictionary values References: Message-ID: <3B7B56BF.8427E246@chello.nl> Hi Jarrett, We can't sort dicts , but we can sort lists, so we have to transform the dictionary.items() into a list that we can sort. Two alternatives. 1. make a list in such a way that the standard sort function gives us the desired result tmplist = [(-data['score'], ID) for (ID, data) in userDB.items()] tmplist.sort() for score, ID in tmplist: print ID, userDB[ID] 2. use a comp function build to ccmaper a key, value tuple in suck a way that we get the desired result def cmp_score((ID1, data1), (ID2, data2)): '''compare scores in an ID, data tuple''' return -cmp(data1['score'], data2['score']) tmplist = userDB.items() tmplist.sort(cmp_score) for ID, data in tmplist: print ID, data Note the '-' in both the list comprehension an the cmp_function. They are there to make sure that tmplist sorts in descending order. By the way, You're probably better of if at some point you try to approach this in a more OO way. At least a class for the UserData (I wrote data.score automatically when I first wrote the code above. I was expecting score to be an attribute of an object). You may also want to consider some kind of real DB backend. Hope this helps, Roeland "W. Jarrett Campbell" wrote: > [snip] > > > > > > Problem: > > ------ > > I'm building a "Leader Board" application which tracks user names and displays the top 10 scores from a contest > W. Jarrett Campbell, Ph.D. > Member of Technical Staff > Yield Dynamics, Inc. > 5838 Balcones Drive, Suite 101 > Austin, TX 78731 > > 512.323.9149 phone > 512.415.1078 mobile > 512.257.9503 fax> > > I'm using shelve/pickle for my persistence so basically what I'm confronted with is something that looks like this: > > > > userDB = {uniqueUserID:userData} > > > > where userData is itself a dictionary like > > > > userData = {"fname": "Jarrett", > > "lname": "Campbell", > > "email": "jarrett@ydyn.com", > > "score":"98.8"} > > > > > > What I need to do is find the 10 uniqueUserIDs from userDB where the value of "score" is the in the top 10 of all the records and sort them in order from highest to lowestW. Jarrett Campbell, Ph.D. > > Member of Technical Staff > > Yield Dynamics, Inc. > > 5838 Balcones Drive, Suite 101 > > Austin, TX 78731 > > > > 512.323.9149 phone > > 512.415.1078 mobile > > 512.257.9503 fax. Once that is done, I have a routine to display the leaderboard. > > > > > > Any suggestions for an efficient way to do this? > > > > Jarrett Campbell > > jarrett@ydyn.com > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- r.b.rigilink@chello.nl "Half of what I say is nonsense. Unfortunately I don't know which half" From csmith@blakeschool.org Thu Aug 16 07:25:19 2001 From: csmith@blakeschool.org (Christopher Smith) Date: Thu, 16 Aug 2001 01:25:19 -0500 Subject: [Tutor] Re: Sorting dictionary values Message-ID: dman wrote: | | > Problem: | | > ------ | | > I'm building a "Leader Board" application which tracks user names | | > and displays the top 10 scores from a contest | | | | > I'm using shelve/pickle for my persistence so basically what I'm | | > confronted with is something that looks like this: | | > | | > userDB = {uniqueUserID:userData} | | > | | > where userData is itself a dictionary like | | > | | > userData = {"fname": "Jarrett", | | > "lname": "Campbell", | | > "email": "jarrett@ydyn.com", | | > "score":"98.8"} | | > | | > | | > What I need to do is find the 10 uniqueUserIDs from userDB where | the | > value of "score" is the in the top 10 of all the records and | sort | > them in order from highest to lowest | | | | > Once that is done, I have a routine to display the leaderboard. | | > | | > Any suggestions for an efficient way to do this? | | Dictionaries can't be sorted because the keys are hashed instead. I | think you need to iterate over your db and create a list of all the | users, then sort them based on score. The easiest way would probably | be to make a class for the userData instead of using a plain | dictionary -- that way you can define the comparision to behave the Here is another great use for the zip function: use it to create your own multipurpose sort function which behaves like reduce, map, and filter in that it applies the provided function to all the elements...the difference is that it creates a new list with this mapping, zips it onto the user specified list, and then sorts the user list and returns the sorted list unzipped from the original. e.g. sorted_keys=sort(lambda key:db[key]["score"], keys) The sort function, along with some code to test the database problem follow: #### def sort(func,l): '''Like reduce, map, and filter: provide a 1-arg function to use to determine the sort order. e.g. sort(len,l) will sort l according to the length of the elements. ''' l[:]=zip([func(li) for li in l],l) l.sort() l[:]=[li[1] for li in l] #--make some data from random import random as rnd db = {} for i in range(10): userid=int(10000*(rnd())) db[userid]={\ "first":"F"+str(userid),\ "last":"L"+str(userid),\ "email":"F.L@dom"+str(userid)+".com",\ "score":int(100*rnd())} #--show it k=db.keys() for ki in k: print "User",ki,"has score",db[ki]["score"] #--use sort to sort it according to the score criteria def score(ki): return db[ki]["score"] sort(score,k) # or in lambda form: sort(lambda ki:db[ki]["score"],k) #--show that we really got them sorted print print '--Top 3 in DB--' for ki in k[-3:]: print "User",ki,"with",db[ki]["score"] #### Output #User 6127 has score 49 #User 5661 has score 38 #User 8395 has score 44 #User 7978 has score 50 #User 7384 has score 78 #User 3620 has score 30 #User 7381 has score 98 #User 2964 has score 14 #User 9458 has score 77 #User 5584 has score 1 # #--Top 3 in DB-- #User 9458 with 77 #User 7384 with 78 #User 7381 with 98 #### I suppose you could even make a general db sorter like this: def dbsort(key,db): k=db.keys() sort(lambda ki,defkey=key:db[ki][defkey],k) return k by_email=dbsort("email",db) #keys sorted according to email addresses Happy DB'ing! /c From delirious@atchoo.be Thu Aug 16 11:45:18 2001 From: delirious@atchoo.be (Simon Vandemoortele) Date: Thu, 16 Aug 2001 09:45:18 -0100 Subject: [Tutor] How does python find the modules I install ??? In-Reply-To: <3B7AFDE8.DC354AEB@irtc.net> References: <01081522102000.27002@shinsekai> <3B7AFDE8.DC354AEB@irtc.net> Message-ID: <01081609451800.01388@shinsekai> > I haven't worked with Mysql-python, but the sourceforge > rpm installs to /usr/lib/python1.5/site-packages, which > doesn't work for SuSE >=3D 7.0. Then, sys.path will be > looking at /usr/lib/python2.0/site-packages instead. > But, it's said to be 2.0 compatible--the rpm is spec'd > that way for Red Hat users, I'd guess. > > You could: > > import sys > sys.path.append('/usr/lib/python1.5/site-packages') > > ...which is a runtime-only alteration, or, you can mv > everything that was installed to 1.5 site-packages to > 2.0 site-packages. Kinda blows rpm -e, but you can > make a note of it. Thx, I think that will solve my problem. Two remarks: 1 - Wouldn't it be a lot easier if python kept it's path in a file that c= an=20 be altered easily ??? 2 - Regarding your move solution: maybe I can avoid the rpm -e problem by= =20 putting a symlink instead of moving the files ??? Greetings from Belgium, Simon Vandemooortele --=20 A day for firm decisions!!!!! Or is it? From alan.gauld@bt.com Thu Aug 16 10:41:17 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Thu, 16 Aug 2001 10:41:17 +0100 Subject: [Tutor] .pyc files and executables? Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BEA1@mbtlipnt02.btlabs.bt.co.uk> > I'm using Python 2.0 on a UNIX machine (Solaris 2.6) to write some > CGIs. I'm trying to find out more about .pyc files, because I think > it may improve performance at least a little if I can get my CGIs > saved as .pyc files. I don't think it'll make much difference provided the module pyc files are all there. Using mod-py if its apache is more likely to help. But as in all things performance related test it and see, otherwise you can spend a lot of effort for no gain. Alan g. From alan.gauld@bt.com Thu Aug 16 10:45:13 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Thu, 16 Aug 2001 10:45:13 +0100 Subject: [Tutor] .pyc files and executables? Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BEA2@mbtlipnt02.btlabs.bt.co.uk> > > What I want to know is this: If I run myprogram.py, which starts up > > the interpreter, will Python see myprogram.pyc there and use it > > instead of reparsing the code in myprogram.py? > > > If I'm not mistaken, that's precisely what will happen. I don't think so, AFAIK it will always run the script you specify but if that script imports a module it will use the compiled module. I guess the definitive answer can only be found in the source again! I don't know if you can run pyc files directly, that might work... Alan G. From lonetwin Thu Aug 16 13:09:54 2001 From: lonetwin (lonetwin) Date: Thu, 16 Aug 2001 17:39:54 +0530 (IST) Subject: [Tutor] Finding duplicate files Message-ID: Greetings everybody, Here's something I wrote up b'coz I felt the need for it. This little script looks recursively for files with the same name (duplicate files), and prints the results on the console. One reason I'm posting this here, is that maybe someone has use for this (you'd be surprised by the amount of clutter I managed to trace in my download directory !!! :)), but more importantly, I'd like the gurus to comment on alternate techniques and clever tricks that might make this work better.....I'm sure I learn some thing :D !!! Peace Steve P.S.: If the gurus are too busy, for something as silly as this, it's OK ! code : ============================================================= #!/usr/bin/python import os def getFileList(lst, dirname, names): # Is used in os.path.walk() for x in names: if os.path.isfile(os.path.join(dirname, x)): lst.append(os.path.join(dirname, x)) return lst def findDup(lst): found = [] for x in range(len(lst)): for y in lst[x+1:]: if os.path.basename(lst[x]) == os.path.basename(y): found.append('%s and %s' % (y, p[x])) return found p = [] topdir = '/home/backups/Tarballs' # The top level directory for the search os.path.walk(topdir, getFileList, p) found = findDup(p) print '\n'.join([x for x in found]) ============================================================= Another P.S.: If nobody has any use for this I guess we all know where it belongs :) Rob hope this (or it's improvements) qualify. ---------------------------------------------------------------------------- You will pay for your sins. If you have already paid, please disregard this message. ---------------------------------------------------------------------------- From lsloan@umich.edu Thu Aug 16 14:08:21 2001 From: lsloan@umich.edu (Lance E Sloan) Date: Thu, 16 Aug 2001 09:08:21 -0400 Subject: [Tutor] .pyc files and executables? In-Reply-To: Your message of "Thu, 16 Aug 2001 10:45:13 BST." <5104D4DBC598D211B5FE0000F8FE7EB20E66BEA2@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <200108161308.JAA03919@birds.us.itd.umich.edu> alan.gauld@bt.com wrote: > > > What I want to know is this: If I run myprogram.py, which starts up > > > the interpreter, will Python see myprogram.pyc there and use it > > > instead of reparsing the code in myprogram.py? > > > > > If I'm not mistaken, that's precisely what will happen. > > I don't think so, AFAIK it will always run the script you specify but > if that script imports a module it will use the compiled module. > I guess the definitive answer can only be found in the source again! > > I don't know if you can run pyc files directly, that might work... I found that I can't run .pyc files directly from the UNIX commandline. They are not in an executable format. I think I did find the answer, though. Using Python's "-v" option proved very helpful. First, to set up the problem, I ran Python interactively, without any options, and imported myprogram.py in order to make myprogram.pyc. Then I exited the interpreter. Next, I ran myprogram, using this command: % python -v myprogram.py Among the output, I didn't see any mention of myprogram.pyc. I also tried this by adding "-v" to the end of the Python shebang (#!) line at the beginning of the program and running it directly. The results were the same. Finally, I ran Python interactively, with "-v" and imported my program. As with the previous experiment, there was lots of output, but I've edited most of it out here: % python -v [...] Python 2.0 (#1, Jan 8 2001, 10:18:58) [GCC egcs-2.91.66 19990314 (egcs-1.1.2 release)] on sunos5 Type "copyright", "credits" or "license" for more information. [...] >>> import myprogram # myprogram.pyc matches myprogram.py import myprogram # precompiled from myprogram.pyc hello from my program So, Alan, I believe you're correct. Python will use .pyc files for modules that are imported, but not for the main program. So, I might look into mod-python, if I can talk my webmasters into giving me access to their configured Apache code. I think I'll need that in order for the module to compile properly. -- Lance E Sloan Web Services, Univ. of Michigan: Full-service Web and database design, development, and hosting. Specializing in Python & Perl CGIs. http://websvcs.itd.umich.edu/ - "Putting U on the Web" From alan.gauld@bt.com Thu Aug 16 15:56:09 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Thu, 16 Aug 2001 15:56:09 +0100 Subject: [Tutor] .pyc files and executables? Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BEA5@mbtlipnt02.btlabs.bt.co.uk> > So, Alan, I believe you're correct. Python will use .pyc files for > modules that are imported, but not for the main program. Thats a relief, my recent track record hasn't been too good! > So, I might look into mod-python, if I can talk my webmasters into > giving me access to their configured Apache code. I think I'll need > that in order for the module to compile properly. The big gain in mod-py is not the compilation issue but the fact that the interpreter is already running - at least I assume thats the gain... For the comilation bit if your program consists of: #! /env/python import my_real_program my_real_program.main() Then the compilation overhead is minimal and it pulls in the pyc for the bulk of the program... But I suspect that compared to the startup time of python itself thats a minimal saving. Alan g From sheila@thinkspot.net Thu Aug 16 16:41:01 2001 From: sheila@thinkspot.net (Sheila King) Date: Thu, 16 Aug 2001 08:41:01 -0700 Subject: [Tutor] sockets broken on New Install??? Message-ID: <302CC483BCB@kserver.org> OK, so I *thought* I'd upgrade from 2.0 to 2.1.1. I have Linux host with shell account for my web site. I find my way around Linux with difficulty. (I'm really a Windows person .) So, I got Python-2.1.1.tgz on my site, unzipped it, and went to the top directory and types: ./configure --prefix=/big/dom/xthinkspot (that's the path to my top level directory) And that looked fine. Then I typed: make install and a bunch of stuff happened. And I now have a python2.1* executable in the /big/dom/xthinkspot/bin directory. And the python* points to it. (Fortunately, my python2.0* is still there, unaffected and functioning.) And all the Lib modules seem to have been copied to /big/dom/xthinkspot/lib/python2.1/* BUT when I ran the make test, I got error messages that indicate something is seriously wrong. 119 tests OK. 4 tests failed: test___all__ test_asynchat test_socket test_sundry 16 tests skipped: test_al test_cd test_cl test_dl test_gl test_imgfile test_largefile test_linuxaudiodev test_minidom test_nis test_pyexpat test_sax test_socketserver test_sunaudiodev test_winreg test_winsound make: *** [test] Error 1 Having sockets not work is a real problem. I brought up the 2.1.1 interpreter for an interactive session. I could import several different modules, such as os and string, but when I tried to import smtplib I get this error message: >>> import smtplib Traceback (most recent call last): File "", line 1, in ? File "/big/dom/xthinkspot/lib/python2.1/smtplib.py", line 42, in ? import socket File "/big/dom/xthinkspot/lib/python2.1/socket.py", line 41, in ? from _socket import * ImportError: /big/dom/xthinkspot/lib/python2.1/lib-dynload/_socket.so: undefined symbol: ERR_load_RSAREF_strings We just had a system upgrade last night. Went from an earlier Red Hat Linux to RH 6.2 and glibc went from glibc-2.0.7 to glibc-2.1.3, but I don't see why this should matter, since I'm recompiling and relinking from scratch? Please, help? -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From sheila@thinkspot.net Thu Aug 16 17:22:05 2001 From: sheila@thinkspot.net (Sheila King) Date: Thu, 16 Aug 2001 09:22:05 -0700 Subject: [Tutor] sockets broken on New Install??? In-Reply-To: <302CC483BCB@kserver.org> References: <302CC483BCB@kserver.org> Message-ID: <32850BB1E46@kserver.org> On Thu, 16 Aug 2001 08:41:01 -0700, Sheila King wrote about [Tutor] sockets broken on New Install???: :119 tests OK. :4 tests failed: test___all__ test_asynchat test_socket test_sundry :16 tests skipped: test_al test_cd test_cl test_dl test_gl test_imgfile :test_largefile test_linuxaudiodev test_minidom test_nis test_pyexpat :test_sax test_socketserver test_sunaudiodev test_winreg test_winsound :make: *** [test] Error 1 : :Having sockets not work is a real problem. Well, here is an additional clue. I checked the config.log file for "socket" and find this message: configure:3264: checking for socket in -lsocket configure:3283: gcc -o conftest -g -O2 conftest.c -lsocket -ldl -ldl 1>&5 /usr/bin/ld: cannot find -lsocket collect2: ld returned 1 exit status configure: failed program was: #line 3272 "configure" #include "confdefs.h" /* Override any gcc2 internal prototype to avoid an error. */ /* We use char because int might match the return type of a gcc2 builtin and then its argument prototype would still apply. */ char socket(); int main() { socket() ; return 0; } I guess I have to ask my admin where the lsocket is??? I dunno? -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From bsass@freenet.edmonton.ab.ca Thu Aug 16 18:00:19 2001 From: bsass@freenet.edmonton.ab.ca (Bruce Sass) Date: Thu, 16 Aug 2001 11:00:19 -0600 (MDT) Subject: [Tutor] sockets broken on New Install??? In-Reply-To: <32850BB1E46@kserver.org> Message-ID: Hi, Have a look in /Modules/Setup, search for "_socket" (and "EXPAT_DIR" to get the expat, minidom and sax stuff working)... you probably just need to edit a little and re-make. "locate" and "grep" are a couple of standard commands that will help with finding where the headers and libs for stuff lives ("find" is a good one to know about also). e.g,: ~$ locate openssl | grep include | less /usr/include/kde/kopenssl.h /usr/include/openssl /usr/include/openssl/asn1.h ... gives me a clue on how to edit the socket section in Setup. [probably no need to bother the sysadmin] - Bruce -- On Thu, 16 Aug 2001, Sheila King wrote: > On Thu, 16 Aug 2001 08:41:01 -0700, Sheila King > wrote about [Tutor] sockets broken on New Install???: > > :119 tests OK. > :4 tests failed: test___all__ test_asynchat test_socket test_sundry > :16 tests skipped: test_al test_cd test_cl test_dl test_gl test_imgfile > :test_largefile test_linuxaudiodev test_minidom test_nis test_pyexpat > :test_sax test_socketserver test_sunaudiodev test_winreg test_winsound > :make: *** [test] Error 1 > : > :Having sockets not work is a real problem. > > Well, here is an additional clue. I checked the config.log file for > "socket" and find this message: > > configure:3264: checking for socket in -lsocket > configure:3283: gcc -o conftest -g -O2 conftest.c -lsocket -ldl -ldl > 1>&5 > /usr/bin/ld: cannot find -lsocket > collect2: ld returned 1 exit status > configure: failed program was: > #line 3272 "configure" > #include "confdefs.h" > /* Override any gcc2 internal prototype to avoid an error. */ > /* We use char because int might match the return type of a gcc2 > builtin and then its argument prototype would still apply. */ > char socket(); > > int main() { > socket() > ; return 0; } > > > I guess I have to ask my admin where the lsocket is??? I dunno? > > -- > Sheila King > http://www.thinkspot.net/sheila/ > http://www.k12groups.org/ > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From lumbricus@gmx.net Thu Aug 16 18:05:54 2001 From: lumbricus@gmx.net (Joerg Woelke) Date: Thu, 16 Aug 2001 19:05:54 +0200 Subject: [Tutor] .pyc files and executables? In-Reply-To: <200108161308.JAA03919@birds.us.itd.umich.edu>; from lsloan@umich.edu on Thu, Aug 16, 2001 at 09:08:21AM -0400 References: <5104D4DBC598D211B5FE0000F8FE7EB20E66BEA2@mbtlipnt02.btlabs.bt.co.uk> <200108161308.JAA03919@birds.us.itd.umich.edu> Message-ID: <20010816190554.A4631@Laplace.localdomain> On Thu, Aug 16, 2001 at 09:08:21AM -0400, Lance E Sloan wrote: > > alan.gauld@bt.com wrote: > interactively, without any options, and imported myprogram.py in > order to make myprogram.pyc. Then I exited the interpreter. > > Next, I ran myprogram, using this command: > > % python -v myprogram.py BTW: You want to try the Options -d and/or -i HTH J"o! :-) -- You are the only person to ever get this message. From lumbricus@gmx.net Thu Aug 16 18:17:16 2001 From: lumbricus@gmx.net (Joerg Woelke) Date: Thu, 16 Aug 2001 19:17:16 +0200 Subject: [Tutor] sockets broken on New Install??? In-Reply-To: <32850BB1E46@kserver.org>; from sheila@thinkspot.net on Thu, Aug 16, 2001 at 09:22:05AM -0700 References: <302CC483BCB@kserver.org> <32850BB1E46@kserver.org> Message-ID: <20010816191716.B4631@Laplace.localdomain> On Thu, Aug 16, 2001 at 09:22:05AM -0700, Sheila King wrote: > On Thu, 16 Aug 2001 08:41:01 -0700, Sheila King > wrote about [Tutor] sockets broken on New Install???: > > :119 tests OK. [snip tests] > : > :Having sockets not work is a real problem. > > Well, here is an additional clue. I checked the config.log file for > "socket" and find this message: > > configure:3264: checking for socket in -lsocket > configure:3283: gcc -o conftest -g -O2 conftest.c -lsocket -ldl -ldl > 1>&5 > /usr/bin/ld: cannot find -lsocket fine - a usefull error message :-) > collect2: ld returned 1 exit status > configure: failed program was: > #line 3272 "configure" > #include "confdefs.h" > /* Override any gcc2 internal prototype to avoid an error. */ > /* We use char because int might match the return type of a gcc2 > builtin and then its argument prototype would still apply. */ > char socket(); > > int main() { > socket() > ; return 0; } > > > I guess I have to ask my admin where the lsocket is??? I dunno? > actually, the linker is looking for a file named libsocket.a or so. Perhaps you find the file yourself, then you can specify the path to it via the -L - option. "man gcc" gives more infos :-) HTH and Greetings J"o! :-) > -- > Sheila King > http://www.thinkspot.net/sheila/ > http://www.k12groups.org/ > -- You are the only person to ever get this message. From csmith@blakeschool.org Thu Aug 16 18:43:41 2001 From: csmith@blakeschool.org (Christopher Smith) Date: Thu, 16 Aug 2001 12:43:41 -0500 Subject: [Tutor] Re: Sorting dictionary values In-Reply-To: References: Message-ID: tutor@python.org writes: >I suppose you could even make a general db sorter like this: > >def dbsort(key,db): > k=db.keys() > sort(lambda ki,defkey=key:db[ki][defkey],k) > return k I noticed a lurking "shadow error" in my output window after sending this. You can get rid of it by writing the following instead: def dbsort(key,db): k=db.keys() sort(lambda ki,theKey=key,theDB=db: theDB[ki][theKey], k) return k Note, too, that the function you provide to "sort" can do anything with that one argument--it is the return value that will be used as the sorting criteria. /c From sheila@thinkspot.net Thu Aug 16 18:48:02 2001 From: sheila@thinkspot.net (Sheila King) Date: Thu, 16 Aug 2001 10:48:02 -0700 Subject: [Tutor] sockets broken on New Install??? In-Reply-To: References: <32850BB1E46@kserver.org> Message-ID: <37708D01866@kserver.org> On Thu, 16 Aug 2001 11:00:19 -0600 (MDT), Bruce Sass wrote about Re: [Tutor] sockets broken on New Install???: :Have a look in /Modules/Setup, search for "_socket" (and :"EXPAT_DIR" to get the expat, minidom and sax stuff working)... you :probably just need to edit a little and re-make. Right. I'm with you on the editing and re-make. :"locate" and "grep" are a couple of standard commands that will help :with finding where the headers and libs for stuff lives ("find" is a :good one to know about also). Thanks. I know I need to learn more *nix. (I've been getting by with whereis a lot...bash shell.) :e.g,: :~$ locate openssl | grep include | less :/usr/include/kde/kopenssl.h :/usr/include/openssl :/usr/include/openssl/asn1.h :... : :gives me a clue on how to edit the socket section in Setup. Well, I get something like this: [thinker@FQ-Nine:~ ]$ locate openssl | grep include | more /usr/local/ssl/include/openssl /usr/local/ssl/include/openssl/asn1_mac.h /usr/local/ssl/include/openssl/asn1.h /usr/local/ssl/include/openssl/blowfish.h /usr/local/ssl/include/openssl/bio.h /usr/local/ssl/include/openssl/buffer.h ... I wish I could say that gave ME a clue. I look in /Modules.Setup for _socket and find this: # for socket(2), without SSL support. #_socket socketmodule.c # Socket module compiled with SSL support; you must comment out the other # socket line above, and possibly edit the SSL variable: #SSL=/usr/local/ssl #_socket socketmodule.c \ # -DUSE_SSL -I$(SSL)/include -I$(SSL)/include/openssl \ # -L$(SSL)/lib -lssl -lcrypto And it looks to me like SSL = /usr/local/ssl is correct??? (Is that the part I would edit?) Do I need to change it to SSL=/usr/local/ssl/include/openssl ???? Plus, what's with all the # at the beginning of the lines. Looks like everything is commented out. Is this the normal way for it to look? (Confusing to me.) I think I figured out the expat part. In the /Modules/Setup file I changed the line #EXPAT_DIR=/usr/local/src/expat to #EXPAT_DIR=/usr/local/include/php/ext/xml/expat after getting these results from a commandline prompt: [thinker@FQ-Nine:~ ]$ locate expat | more /usr/local/include/php/ext/xml/expat /usr/local/include/php/ext/xml/expat/xmlparse /usr/local/include/php/ext/xml/expat/xmlparse/expat_hashtable.h /usr/local/include/php/ext/xml/expat/xmlparse/xmlparse.h /usr/local/include/php/ext/xml/expat/xmltok ... So, I think that I've got expat set to go, but I'm not sure about SSL/Socket, since my results from $locate openssl | grep include | more seem to indicate to me, that the Modules/Setup file has that directory set correctly??? -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From bsass@freenet.edmonton.ab.ca Thu Aug 16 19:20:11 2001 From: bsass@freenet.edmonton.ab.ca (Bruce Sass) Date: Thu, 16 Aug 2001 12:20:11 -0600 (MDT) Subject: [Tutor] sockets broken on New Install??? In-Reply-To: <37708D01866@kserver.org> Message-ID: On Thu, 16 Aug 2001, Sheila King wrote: > On Thu, 16 Aug 2001 11:00:19 -0600 (MDT), Bruce Sass <...> > Well, I get something like this: > > [thinker@FQ-Nine:~ ]$ locate openssl | grep include | more > /usr/local/ssl/include/openssl > /usr/local/ssl/include/openssl/asn1_mac.h > /usr/local/ssl/include/openssl/asn1.h > /usr/local/ssl/include/openssl/blowfish.h > /usr/local/ssl/include/openssl/bio.h > /usr/local/ssl/include/openssl/buffer.h > ... > > I wish I could say that gave ME a clue. looks like it did... > I look in /Modules.Setup for _socket and find this: > > # for socket(2), without SSL support. > #_socket socketmodule.c > > # Socket module compiled with SSL support; you must comment out the > other > # socket line above, and possibly edit the SSL variable: > #SSL=/usr/local/ssl > #_socket socketmodule.c \ > # -DUSE_SSL -I$(SSL)/include -I$(SSL)/include/openssl \ > # -L$(SSL)/lib -lssl -lcrypto > > And it looks to me like > SSL = /usr/local/ssl > is correct??? (Is that the part I would edit?) ...yes (yes)... > Do I need to change it to > SSL=/usr/local/ssl/include/openssl > ???? ...nope... > Plus, what's with all the # at the beginning of the lines. Looks like > everything is commented out. Is this the normal way for it to look? > (Confusing to me.) ...just uncomment the whole section. The "$(SSL)" bits will be substituted with the value of SSL, so... -I$(SSL)/include/openssl becomes -I/usr/local/ssl/include/openssl which is where "locate" found the headers. When you've finished re-make-ing, test it with: ./python ./Lib/test/test_socketserver.py > I think I figured out the expat part. > In the /Modules/Setup file I changed the line > #EXPAT_DIR=/usr/local/src/expat > to > #EXPAT_DIR=/usr/local/include/php/ext/xml/expat > > after getting these results from a commandline prompt: > [thinker@FQ-Nine:~ ]$ locate expat | more > /usr/local/include/php/ext/xml/expat > /usr/local/include/php/ext/xml/expat/xmlparse > /usr/local/include/php/ext/xml/expat/xmlparse/expat_hashtable.h > /usr/local/include/php/ext/xml/expat/xmlparse/xmlparse.h > /usr/local/include/php/ext/xml/expat/xmltok > ... Hmmm, you can try it, but it might be PHP stuff that just has the same names as what you want. I keep running into this because I don't have all the headers (probably missing a -dev package). However, I did notice that the Amaya source installed what I needed because it now does xml stuff; the line ended up looking like: EXPAT_DIR=/usr/local/src/libwww/modules/expat If the PHP location doesn't work, http://www.w3.org/amaya ... Amaya is worth playing with (WYSIWYG (X)HTML editor.browser). > So, I think that I've got expat set to go, but I'm not sure about > SSL/Socket, since my results from > $locate openssl | grep include | more > > seem to indicate to me, that the Modules/Setup file has that directory > set correctly??? ...except for being commented out. :) - Bruce From sheila@thinkspot.net Thu Aug 16 21:50:07 2001 From: sheila@thinkspot.net (Sheila King) Date: Thu, 16 Aug 2001 13:50:07 -0700 Subject: [Tutor] sockets broken on New Install??? In-Reply-To: References: <37708D01866@kserver.org> Message-ID: <41DBA581567@kserver.org> On Thu, 16 Aug 2001 12:20:11 -0600 (MDT), Bruce Sass wrote about Re: [Tutor] sockets broken on New Install???: :On Thu, 16 Aug 2001, Sheila King wrote: :> I wish I could say that gave ME a clue. : :looks like it did... : :> I look in /Modules.Setup for _socket and find this: :> :> # for socket(2), without SSL support. :> #_socket socketmodule.c :> :> # Socket module compiled with SSL support; you must comment out the :> other :> # socket line above, and possibly edit the SSL variable: :> #SSL=/usr/local/ssl :> #_socket socketmodule.c \ :> # -DUSE_SSL -I$(SSL)/include -I$(SSL)/include/openssl \ :> # -L$(SSL)/lib -lssl -lcrypto :> :> And it looks to me like :> SSL = /usr/local/ssl :> is correct??? (Is that the part I would edit?) : :...yes (yes)... : :> Do I need to change it to :> SSL=/usr/local/ssl/include/openssl :> ???? : :...nope... : :> Plus, what's with all the # at the beginning of the lines. Looks like :> everything is commented out. Is this the normal way for it to look? :> (Confusing to me.) : :...just uncomment the whole section. Well, I'm just having a wonderful time. NOT. :( I gave up on the expat thing. It seems the system I'm using doesn't have the necessary files already installed, and I'm not doing XML right now, so I'm not going to worry about it for now. But sockets...gotta have those. I've completely deleted all of the Python-2.1.1 files and directories and started over with a fresh install a few times, now. (I also inadvertently deleted my python2.0* binary so now my website is really broken. :( When I uncomment the three lines for SSL enable sockets, I do make install, and then I try make test (this is a fresh install, since I started over). The make test command gets almost nowhere. I get the following message: [thinker@FQ-Nine:/big/dom/xthinkspot/Python/Python-2.1.1 ]$ make test gcc -Xlinker -export-dynamic -o python \ Modules/python.o \ libpython2.1.a -lpthread -ldl -lutil -L/usr/local/ssl/lib -lssl -lcrypto -lm /usr/local/ssl/lib/libcrypto.a(rsa_lib.o): In function `RSA_new_method': rsa_lib.o(.text+0x20): undefined reference to `RSA_PKCS1_RSAref' /usr/local/ssl/lib/libcrypto.a(err_all.o): In function `ERR_load_crypto_strings' : err_all.o(.text+0x3d): undefined reference to `ERR_load_RSAREF_strings' collect2: ld returned 1 exit status make: *** [python] Error 1 I have no python executable. I went to the Python.org site FAQ, section 3 for common problems, and it indicates that Linux sometimes has trouble finding the crypt libraries, so in Modules/Setup, I uncommted the line crypt cryptmodule.c -lcrypt # crypt(3); needs -lcrypt on some systems did make clean and then make install and make test. Got the same error messages. I'm beside myself, now. -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From sheila@thinkspot.net Thu Aug 16 22:18:01 2001 From: sheila@thinkspot.net (Sheila King) Date: Thu, 16 Aug 2001 14:18:01 -0700 Subject: [Tutor] sockets broken on New Install??? In-Reply-To: <41DBA581567@kserver.org> References: <37708D01866@kserver.org> <41DBA581567@kserver.org> Message-ID: <4374BC808E9@kserver.org> On Thu, 16 Aug 2001 13:50:07 -0700, Sheila King wrote about Re: [Tutor] sockets broken on New Install???: :When I uncomment the three lines for SSL enable sockets, I do make :install, and then I try make test (this is a fresh install, since I :started over). The make test command gets almost nowhere. I get the :following message: : : :[thinker@FQ-Nine:/big/dom/xthinkspot/Python/Python-2.1.1 ]$ make test :gcc -Xlinker -export-dynamic -o python \ : Modules/python.o \ : libpython2.1.a -lpthread -ldl -lutil :-L/usr/local/ssl/lib -lssl : -lcrypto -lm :/usr/local/ssl/lib/libcrypto.a(rsa_lib.o): In function `RSA_new_method': :rsa_lib.o(.text+0x20): undefined reference to `RSA_PKCS1_RSAref' :/usr/local/ssl/lib/libcrypto.a(err_all.o): In function :`ERR_load_crypto_strings' :: :err_all.o(.text+0x3d): undefined reference to `ERR_load_RSAREF_strings' :collect2: ld returned 1 exit status :make: *** [python] Error 1 I finally gave up on the idea of SSL enabled sockets, and uncommented out the line above that in the Setup file for sockets without SSL support. I got compile. After make test I get this message: 123 tests OK. 16 tests skipped: test_al test_cd test_cl test_dl test_gl test_imgfile test_largefile test_linuxaudiodev test_minidom test_nis test_pyexpat test_sax test_socketserver test_sunaudiodev test_winreg test_winsound So, I guess this is OK. I don't understand why I can't get SSL support for my sockets, but I guess that is a topic for another day. At least, now, I should be able to put my scripts back up. Thank you to everyone for their suggestions. -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From tescoil@irtc.net Thu Aug 16 22:51:43 2001 From: tescoil@irtc.net (Tesla Coil) Date: Thu, 16 Aug 2001 16:51:43 -0500 Subject: [Tutor] How does python find the modules I install ??? References: <01081522102000.27002@shinsekai> <3B7AFDE8.DC354AEB@irtc.net> <01081609451800.01388@shinsekai> Message-ID: <3B7C406F.349CBE31@irtc.net> On 16 August 2001, Simon Vandemoortele wrote: > Thx, I think that will solve my problem. Two remarks: > 1 - Wouldn't it be a lot easier if python kept it's > path in a file that can be altered easily ??? Let's consider the immediate situation: MySQL-python is 2.0 compatible. You are 2.0 compatible. That's the Python of it, as far as that's concerned, you shouldn't *need* to alter your path. The problem is the rpm build. More essentially, the problem is that Red Hat 7.1 remains system dependent on 1.5.2 at the expense of their users' ability to do an easy upgrade of the interpreter, and the MySQL-python rpm is built to accommodate that anachronism. This would be a Nice Gesture Maybe if the net result were not to turn the main advantage of rpm upside down. This rpm is provided to make it easy *not* to upgrade, with no such reward for being more up to speed and running SuSE. > 2 - Regarding your move solution: maybe I can avoid > the rpm -e problem by putting a symlink instead of > moving the files ??? On reflection, I'd sooner take a crash course and build a proper rpm. Hmm... From andy@dustman.net Thu Aug 16 23:00:04 2001 From: andy@dustman.net (Andy Dustman) Date: Thu, 16 Aug 2001 18:00:04 -0400 (EDT) Subject: [Tutor] How does python find the modules I install ??? In-Reply-To: <3B7C406F.349CBE31@irtc.net> Message-ID: I only just came in on this thread, but if you get the MySQL-python sources, enter it's root directory, and run: python2 setup.py bdist_rpm --python=/usr/bin/python2 you will get nice RPMS for python2 (adjust paths). Red Hat's use of 1.5.2 with 7.1 is due to two things, as I understand: 1) 2.0 and 2.1 had a license declared by the FSF to be conflicting with the GPL. (2.0.1 and 2.1.1 do not have this problem, I expect to see 2.1.1 in Red Hat 7.2.) 2) 2.0 probably broke some of their python libraries (the Red Hat Network stuff is all python, as is the anaconda installer, and some other stuff). On Thu, 16 Aug 2001, Tesla Coil wrote: > On 16 August 2001, Simon Vandemoortele wrote: > > Thx, I think that will solve my problem. Two remarks: > > 1 - Wouldn't it be a lot easier if python kept it's > > path in a file that can be altered easily ??? > > Let's consider the immediate situation: MySQL-python > is 2.0 compatible. You are 2.0 compatible. That's the > Python of it, as far as that's concerned, you shouldn't > *need* to alter your path. The problem is the rpm build. > More essentially, the problem is that Red Hat 7.1 remains > system dependent on 1.5.2 at the expense of their users' > ability to do an easy upgrade of the interpreter, and the > MySQL-python rpm is built to accommodate that anachronism. > > This would be a Nice Gesture Maybe if the net result were > not to turn the main advantage of rpm upside down. This > rpm is provided to make it easy *not* to upgrade, with no > such reward for being more up to speed and running SuSE. > > > 2 - Regarding your move solution: maybe I can avoid > > the rpm -e problem by putting a symlink instead of > > moving the files ??? > > On reflection, I'd sooner take a crash course and build > a proper rpm. Hmm... > -- Andy Dustman PGP: 0xC72F3F1D @ .net http://dustman.net/andy I'll give spammers one bite of the apple, but they'll have to guess which bite has the razor blade in it. From bsass@freenet.edmonton.ab.ca Fri Aug 17 00:09:01 2001 From: bsass@freenet.edmonton.ab.ca (Bruce Sass) Date: Thu, 16 Aug 2001 17:09:01 -0600 (MDT) Subject: [Tutor] sockets broken on New Install??? In-Reply-To: <41DBA581567@kserver.org> Message-ID: On Thu, 16 Aug 2001, Sheila King wrote: > On Thu, 16 Aug 2001 12:20:11 -0600 (MDT), Bruce Sass > :On Thu, 16 Aug 2001, Sheila King wrote: <...the text version of Sheila trearing her hair out...> > I'm beside myself, now. iirc, this system has a Python-1.5 installed... are there /usr/lib/python1.5/config/Setup* files, do they contain the proper paths for includes and libraries. Generally, I've been able to do ./configure && make && make test && make install then go back and do a series of edit Setup -> make -> manual testing cycles, with a final "make install" when I get tired or have gotten as far as I can get. There should be no need to trash previous work (fight your Windows heritage :-). - Bruce From sheila@thinkspot.net Fri Aug 17 00:25:18 2001 From: sheila@thinkspot.net (Sheila King) Date: Thu, 16 Aug 2001 16:25:18 -0700 Subject: [Tutor] sockets broken on New Install??? In-Reply-To: References: <41DBA581567@kserver.org> Message-ID: <4ABF1975CAF@kserver.org> On Thu, 16 Aug 2001 17:09:01 -0600 (MDT), Bruce Sass wrote about Re: [Tutor] sockets broken on New Install???: :On Thu, 16 Aug 2001, Sheila King wrote: :> On Thu, 16 Aug 2001 12:20:11 -0600 (MDT), Bruce Sass :> :On Thu, 16 Aug 2001, Sheila King wrote: :<...the text version of Sheila trearing her hair out...> Yeah, well I've been meaning to get it cut. Now I don't have to! :> I'm beside myself, now. : :iirc, this system has a Python-1.5 installed... Hot dang, you have a memory. I'm fully impressed. Yes, they do have 1.5 installed. :are there /usr/lib/python1.5/config/Setup* files, do they contain the :proper paths for includes and libraries. I grabbed their Setup file for 1.5 and here are the pertinent lines from that file: socket socketmodule.c # socket(2); not on ancient System V #_socket socketmodule.c # socket(2); use this one for BeOS sockets errno errnomodule.c # posix (UNIX) errno values # The crypt module is now disabled by default because it breaks builds # on many systems (where -lcrypt is needed), e.g. Linux (I believe). crypt cryptmodule.c -lcrypt # crypt(3); needs -lcrypt on some systems As you can see, they haven't installed sockets with the SSL enabled. :Generally, I've been able to do : : ./configure && make && make test && make install : :then go back and do a series of edit Setup -> make -> manual testing :cycles, with a final "make install" when I get tired or have gotten as :far as I can get. There should be no need to trash previous work :(fight your Windows heritage :-). LOL. Thanks. After a day like today, I needed a good laugh. Actually, I did learn some really nice *nix things today. I think I understand grep a little better, and that locate tool is handy, too. I'm going to ask the sysadmin about the whole sockets/SSL issue. Given that all the libraries seem to be there and available for use, I can't understand why it won't compile. (The directory paths all seem to what the Python installer would expect, too.) Thanks for your help, -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From pobrien@orbtech.com Fri Aug 17 01:43:26 2001 From: pobrien@orbtech.com (Patrick K. O'Brien) Date: Thu, 16 Aug 2001 19:43:26 -0500 Subject: [Tutor] ANN: PythonCard Prototype 0.4.1 Message-ID: I'm sending this on behalf of the PythonCard project. Enjoy. --- Patrick K. O'Brien Orbtech "I am, therefore I think." PythonCard is a software construction kit (in the spirit of Apple's HyperCard) written in Python. You can download the latest release at: http://sourceforge.net/project/showfiles.php?group_id=19015 Samples included in the latest release: conversions, dialogs, findfiles, minimal, proof, searchexplorer, sounds, SourceForgeTracker, tictactoe, turtle, widgets, worldclock To see screenshots of some of the samples, visit: http://pythoncard.sourceforge.net/samples.html PythonCard home page http://pythoncard.sourceforge.net/ SourceForge summary page http://sourceforge.net/projects/pythoncard/ Mailing list http://groups.yahoo.com/group/pythoncard/ PythonCard requires Python 2.1 or later and wxPython 2.3.x. wxPython is available at http://www.wxpython.org/ PythonCard relies on wxPython, it will support the Macintosh once wxPython has been ported to the Mac. PyCrust 0.5.2 PyCrust by Patrick K. O'Brien is included as part of the PythonCardPrototype releases. If you would like to find our more about PyCrust or get a separate distribution, please visit the home page at http://sourceforge.net/projects/pycrust/ ---------------------------- Changes since release 0.3.1 (2001-08-07): The Property Editor is still only able to display widget attributes, you'll have to use the Shell to actually change an attribute. The Property Editor will work in the next release, and this time I mean it. :) Release 0.4.1 2001-08-16 updated debug.py and pycrustrc.py to support PyCrust 0.5.2 due to changes between PyCrust 0.5.2 and earlier versions you must use the latest version of Pycrust with PythonCard, which is included in the release .zip for convenience added 'border' attribute to TextField and its subclasses to support a 'none' wxNO_BORDER option. updated worldclock and test_widgets.py to show TextField with a border of 'none' used in place of StaticText added empty bitmap support. Image and ImageButton now use the Bitmap class rather than an explicit wxBitmap. the convention is that if the file is '' then an empty bitmap is created. see SourceForgeTracker for an example of the use of empty bitmaps if the layout doesn't look right on Linux or Solaris, you can use the SourceForgeTracker.original.rsrc.py file by renaming it to SourceForgeTracker.rsrc.py fixed worldclock and tictactoe samples to use Bitmap Release 0.4 2001-08-14 added components dictionary find/findByName, createWidget, and deleteWidget were replaced by a dictionary, so that widgets on a background can be accessed as: self.components.button1 see the samples for numerous examples of the new usage. widgets now use dot notation to access their attributes print button1.label # get button1.label = 'hello' # set This was a major revision to widget.py that also impacted many other parts of the framework, so if you have any samples of your own done with release 0.3.1 or earlier, you'll need to update your code. updated all samples to use the new dot notation all widget attributes that can only be set at initialization will now throw an AttributeError if you try and change them. for example button1.name = 'bob' is not legal so you get: 'AttributeError: name attribute is read-only' *** note that while updating all the widget attributes to dot notation I realized that we had never cleaned up the 'selected' attribute for List, RadioGroup, and Choice, so be aware that the name and behavior of 'selected' will probably change in the next release PyCrust is now included as a separate package numerous changes were made to the PyCrust shell, see the PyCrust docs for more information. fixed backgroundColor and foregroundColor in class Background the widgets sample has a button to change the backgroundColor to show off this fix. added pycrustrc.py files whatever python code is in these files will be executed when the shell is first launched. there is a default pycrustrc.py in the package directory. there is another example in the turtle sample directory. changed pythoncard.config.py added options to set the position and size of all the "debug" windows: Message Watcher, Property Editor, Shell added pythoncard.user.config.py this file will override pythoncard.config.py if it exists you should copy pythoncard.user.config.py and update the position of each window for your own screen dimensions; you can update the shell size too added defaultStackPosition option you can add a key:value line to pythoncard.user.config.py to override the stack position that a PythonCard app may or may not specify. The most common would be something like 'defaultStackPosition':(5, 5), to force the window to the top-left of the screen (I prefer this over (0, 0) myself. added 'Debug' menu if any of the 'debug' windows are requested when an application is started, then all of the windows will be created, but only the requested ones will be shown initially. you can choose the window name from the Debug menu to show/hide the window. added an About PythonCard... menu item to the Debug menu displays version numbers and PythonCard project info added SourceForgeTracker sample downloads XML from SourceForge tracker database to display Bug Reports and Feature Requests for the following projects: PyChecker, PyCrust, Python, PythonCard, wxPython. Additional projects can be added. added conversions sample does Fahrenheit <-> Celsius and English <-> Morse Code conversions with a generic framework, so other conversions can be added added tutorial.txt to docs applications can now use the .pyw extension if you don't want an application to have a console window, then rename the application to .pyw, but don't change the file reference in the .rsrc.py file, leave that as .py as an example, you can change worldclock.py to worldclock.pyw ka --- Kevin Altis altis@semi-retired.com _______________________________________________ wxpython-users mailing list wxpython-users@lists.wxwindows.org http://lists.wxwindows.org/mailman/listinfo/wxpython-users From tbrauch@mindless.com Fri Aug 17 01:48:40 2001 From: tbrauch@mindless.com (Timothy M. Brauch) Date: Thu, 16 Aug 2001 20:48:40 -0400 Subject: [Tutor] Yahtzee-like Program Message-ID: <3B7C69E8.73503D92@mindless.com> I've written a small program that is a lot like Yahtzee, without the pretty graphics. It's more of a command line style game. It works and obeys all the standard rules. However, I know that my 250+ line code is horribly ugly. But, it is the only way I know how to write it. I would like it if someone would look at it and give me some pointers to help clean my code, but I am hesitant to post all of it on the Tutor list. If you want to look at it, it is available at Or, if someone wants, I can post the whole code to the Tutor. I also realize how boring it would be to look over someone's code and try to critque it, but I would really like to learn to write cleaner code, and that is the only way I can learn, right? - Tim P.S. Once my code has been looked at, I think Useless might get a posting. From sendme105@hotmail.com Fri Aug 17 02:09:55 2001 From: sendme105@hotmail.com (James) Date: Thu, 16 Aug 2001 18:09:55 -0700 Subject: [Tutor] Help with CGI login References: Message-ID: >>http://www.listbot.com/cgi-bin/customer?Act=3DNULL > Login with your browser. Make a note of the URL that is used. That > is, identify all form fields and their values. Forms are submitted in > the URL. For example, with my DSL connection I need to login via a > web form. A big PITA so instead I made a little python script that > gets run when the interface is brought up. The core looks like this : > > urllib.urlopen( > "http://www2.frontierdsl.com:9061/dashboard?fcn=serviceLogon&" > + "service=frontiernet.dsl&username=myname&password=mypassword").read() I tried this, but the fields seem to be hidden from view when logging in. I've been trying to figure out the fields from the html source for the page, but haven't got it right yet. Here's some snips of the relevant (i think) html source:

    ... Lost yours? ... I'm trying things like http://www.listbot.com/cgi-bin/customer?Act=login&customer_e_mail_login=emai l@addy.com&customer_password_login=mypass= manually with my browsers address bar. Could the @ be a special character that would normally require a '\' in python? (as in '\\' or '\%') Thanks, James. From rdsteph@earthlink.net Thu Aug 16 02:32:00 2001 From: rdsteph@earthlink.net (Ron Stephens) Date: Wed, 15 Aug 2001 21:32:00 -0400 Subject: [Tutor] Pythonpath question Message-ID: <3B7B228F.C342F89E@earthlink.net> Could someoen give me a quick and brief tutorail on pythonpath, how to set it for windows 98 etc???? ;-))) Sorry to be so braindead.... From shalehperry@home.com Fri Aug 17 03:32:44 2001 From: shalehperry@home.com (Sean 'Shaleh' Perry) Date: Thu, 16 Aug 2001 19:32:44 -0700 (PDT) Subject: [Tutor] anecdote in the workplace about try,except clause Message-ID: So, thought i would pass this on. A coworker who is a long time perl'er is learning python and asking me questions now and then. Today he was writing a file parser and did the following: for line in file: try: data, garbage = string.split(line, ':') except ValueError: pass print 'Data: %s' % data His rationale was that some lines lack the ':' so he would just let the exception hide the 'annoying' python exception assuming that data would be assigned the whole line in that case. What he failed to realize is that when the except clause is triggered items in the try clause go out of scope. So data would not exist. I of course helped him to write this in a more sane way. From dyoo@hkn.eecs.berkeley.edu Fri Aug 17 03:43:08 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 16 Aug 2001 19:43:08 -0700 (PDT) Subject: [Tutor] anecdote in the workplace about try,except clause In-Reply-To: Message-ID: On Thu, 16 Aug 2001, Sean 'Shaleh' Perry wrote: > A coworker who is a long time perl'er is learning python and asking me > questions now and then. Today he was writing a file parser and did > the following: > > for line in file: > try: > data, garbage = string.split(line, ':') > except ValueError: > pass > > print 'Data: %s' % data > > > His rationale was that some lines lack the ':' so he would just let the > exception hide the 'annoying' python exception assuming that data would be > assigned the whole line in that case. > > What he failed to realize is that when the except clause is triggered > items in the try clause go out of scope. So data would not exist. Or, at least, the very last data will be the only thing printed out. Your friend probably meant to write it like this: ### for line in file: try: data, garbage = string.split(line, ':') print 'Data: %s' % data except ValueError: pass ### Feel free to direct your coworker to us; we'd be happy to meet them! *grin* From sendme105@hotmail.com Fri Aug 17 03:51:56 2001 From: sendme105@hotmail.com (James) Date: Thu, 16 Aug 2001 19:51:56 -0700 Subject: [Tutor] Help with CGI login Message-ID: >From studying the suggestion offered combined with trial and error, I managed to get something working in the browser address bar: login_url=r'http://www.listbot.com/cgi-bin/customer?login=customer_login&' \ 'js_test=new&customer_e_mail_login=addy@email.net&customer_password_login=ap ass' #using the above I tried the following: login=urllib.urlopen(login_url) print 'connected, attempting to download...' for i in range(start, 24954): source_url= 'http://www.listbot.com/cgi-bin/customer?Act=view_message&list_id=' \ 'thelistname&msg_num=%i&start_num=' % (i) usock = urllib.urlopen(source_url) destfile=open(r'c:\super\msg%i.html' % (i), 'w') for line in usock.readlines(): # (here I edit out some of the html and save the file locally) usock.close() destfile.close() login.close() This didn't work, I ended up downloading webpages asking me to log in again. I then tried to combine the source_url args and login_url args into one big url. This works to retrieve the desired page on my browser, but my script only downloads messages saying I require cookie support for access. ? Suggestions? Thanks again, James. From dyoo@hkn.eecs.berkeley.edu Fri Aug 17 04:29:45 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 16 Aug 2001 20:29:45 -0700 (PDT) Subject: [Tutor] My shot at the partitioning problem Message-ID: This message is in MIME format. The first part should be readable text, while the remaining parts are likely unreadable without MIME-aware tools. Send mail to mime@docserver.cac.washington.edu for more info. --545289610-1136917903-998018985=:19828 Content-Type: TEXT/PLAIN; charset=US-ASCII Ok, here's my contribution to the partitioning problem. I can only get it to 2 decimal places too, so I'm sure that someone can do much better! Sample output: ### Our best choice (00001010010001100011101001110110000101010110110101) has a value of 119.516797799 Difference between it and our target: 0.00110250314594 Ok, done computing. Our best choice, sqrt(5) + sqrt(7) + sqrt(10) + sqrt(14) + sqrt(15) + sqrt(19) + sqrt(20) + sqrt(21) + sqrt(23) + sqrt(26) + sqrt(27) + sqrt(28) + sqrt(30) + sqrt(31) + sqrt(36) + sqrt(38) + sqrt(40) + sqrt(42) + sqrt(43) + sqrt(45) + sqrt(46) + sqrt(48) + sqrt(50) is THIS close to our target: 0.00110250314594 ### Actually, the program is a bit long. I'll attach it to this message instead, and send it off to Useless Python. I'd have to say that this approach was much more Useless than I had anticipated... *grin*. --545289610-1136917903-998018985=:19828 Content-Type: TEXT/PLAIN; charset=US-ASCII; name="genetic.py" Content-Transfer-Encoding: BASE64 Content-ID: Content-Description: Content-Disposition: attachment; filename="genetic.py" IyEvdXNyL2Jpbi9lbnYgcHl0aG9uDQoNCmZyb20gX19mdXR1cmVfXyBpbXBv cnQgbmVzdGVkX3Njb3Blcw0KDQoiIiJnZW5ldGljLnB5IC0tLSBhIHRveSBn ZW5ldGljIGFsZ29yaXRobSBmcmFtZXdvcmsgZm9yIFB5dGhvbi4NCg0KRGFu bnkgWW9vIChkeW9vQGhrbi5lZWNzLmJlcmtlbGV5LmVkdSkNCg0KVGhpcyBp cyBjb2RlIHRoYXQgZXhwbG9yZXMgaG93IGdlbmV0aWMgYWxnb3JpdGhtcyB3 b3JrLiAgVGhlIGlkZWEgaXMNCnRvIHNpbXVsYXRlIGV2b2x1dGlvbmFyeSBw cmVzc3VyZTogd2UgYWxsb3cgYSBwb3B1bGF0aW9uIG9mIHNvbHV0aW9ucw0K dG8gZ3JvdyBhbmQgZXZvbHZlLiAgQWZ0ZXIgZWFjaCBjeWNsZSwgd2UgY2hv b3NlIGEgcG9wdWxhdGlvbiBiYXNlZCBvbg0KdGhlIHBlcmZvcm1hbmNlIG9m IHRoZSBpbmRpdmlkdWFscywgbWF0ZSB0aGVtLCBhbmQgc3RhcnQgYWdhaW4u ICBUaGUNCnRoZW9yeSBzdWdnZXN0cyB0aGF0IGlmIG91ciBmaXRuZXNzIGZ1 bmN0aW9uIGlzIGEgZ29vZCBvbmUsIHdlDQpncmFkdWFsbHkgcmFpc2UgdGhl IG92ZXJhbGwgZml0bmVzcyBvZiB0aGUgcG9wdWxhdGlvbi4NCg0KQSBmaXRu ZXNzIGZ1bmN0aW9uIHRha2VzIGluIHR3byBhcmd1bWVudHMsICdpbmRpdmlk dWFsJyBhbmQgJ3BlZXJzJzoNCg0KICAgIGluZGl2aWR1YWw6IHRoZSBpbmRp dmlkdWFsIHRoYXQgaXMgYmVpbmcgZXZhbHVhdGVkLCB0aGF0IGlzLCBhDQog ICAgc2luZ2xlIGVsZW1lbnQgb2YgdGhlIHBvcHVsYXRpb24uDQogICAgDQog ICAgcGVlcnM6IHRoZSByZXN0IG9mIHRoZSBwb3B1bGF0aW9uLg0KDQoiIiIN Cg0KaW1wb3J0IG9wZXJhdG9yDQppbXBvcnQgcmFuZG9tDQoNCg0KIyMjIyMj IyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMj IyMjIyMjIyMjIyMjIyMjIyMjIw0KY2xhc3MgR2VuZXRpY0FsZ29yaXRobToN CiAgICBkZWYgX19pbml0X18oc2VsZiwgaW5pdGlhbF9wb3B1bGF0aW9uLCBm aXRuZXNzX2Z1bmN0aW9uLA0KICAgICAgICAgICAgICAgICBjcm9zc292ZXJf ZnVuY3Rpb24sIG11dGF0aW9uX2Z1bmN0aW9uPU5vbmUpOg0KICAgICAgICAi IiJJbml0aWFsaXplIHRoZSBlbnZpcm9ubWVudCB3aXRoIGFuIGluaXRpYWwg cG9wdWxhdGlvbiwgdGhlDQogICAgICAgIHByZXNzdXJlIG9mIGEgZml0bmVz c19mdW5jdGlvbiwgYW5kIGEgY3Jvc3NvdmVyX2Z1bmN0aW9uLiIiIg0KICAg ICAgICBzZWxmLnBvcHVsYXRpb24gPSBpbml0aWFsX3BvcHVsYXRpb24NCiAg ICAgICAgc2VsZi5maXRuZXNzX2YgPSBmaXRuZXNzX2Z1bmN0aW9uDQogICAg ICAgIHNlbGYuY3Jvc3NvdmVyX2YgPSBjcm9zc292ZXJfZnVuY3Rpb24NCiAg ICAgICAgc2VsZi5tdXRhdGlvbl9mID0gbXV0YXRpb25fZnVuY3Rpb24NCiAg ICAgICAgc2VsZi5jeWNsZXNfc2ltdWxhdGVkID0gMA0KDQoNCiAgICBkZWYg c2ltdWxhdGUoc2VsZik6DQogICAgICAgICIiIlBlcmZvcm0gb25lIGN5Y2xl IG9mIHRoZSBnZW5ldGljIGFsZ29yaXRobToNCg0KICAgICAgICAxLiAgRXZh bHVhdGUgdGhlIGZpdG5lc3Mgb2YgZXZlcnkgbWVtYmVyIG9mIG91ciBwb3B1 bGF0aW9uLg0KICAgICAgICAyLiAgQ3JlYXRlIGEgbmV3IHBvcHVsYXRpb24g YnkgcGlja2luZyBwYWlycyBhbmQgY3Jvc3NpbmcgdGhlbS4NCiAgICAgICAg IiIiDQogICAgICAgIG5ld19wb3B1bGF0aW9uID0gW10NCiAgICAgICAgZml0 bmVzc2VzID0gW3NlbGYuZml0bmVzc19mKHgsIHNlbGYucG9wdWxhdGlvbikN CiAgICAgICAgICAgICAgICAgICAgIGZvciB4IGluIHNlbGYucG9wdWxhdGlv bl0NCiAgICAgICAgd2hpbGUgbGVuKG5ld19wb3B1bGF0aW9uKSA8IGxlbihz ZWxmLnBvcHVsYXRpb24pOg0KICAgICAgICAgICAgcGFyZW50MSA9IHNlbGYu cG9wdWxhdGlvbltyb3VsZXR0ZVNlbGVjdChmaXRuZXNzZXMpXQ0KICAgICAg ICAgICAgcGFyZW50MiA9IHNlbGYucG9wdWxhdGlvbltyb3VsZXR0ZVNlbGVj dChmaXRuZXNzZXMpXQ0KICAgICAgICAgICAgY2hpbGQgPSBzZWxmLmNyb3Nz b3Zlcl9mKHBhcmVudDEsIHBhcmVudDIpDQogICAgICAgICAgICBpZiBzZWxm Lm11dGF0aW9uX2Y6IGNoaWxkID0gc2VsZi5tdXRhdGlvbl9mKGNoaWxkKQ0K ICAgICAgICAgICAgbmV3X3BvcHVsYXRpb24uYXBwZW5kKGNoaWxkKQ0KICAg ICAgICBzZWxmLnBvcHVsYXRpb24gPSBuZXdfcG9wdWxhdGlvbg0KICAgICAg ICBzZWxmLmN5Y2xlc19zaW11bGF0ZWQgKz0gMQ0KDQoNCiAgICBkZWYgZ2V0 UG9wdWxhdGlvbihzZWxmKToNCiAgICAgICAgcmV0dXJuIHNlbGYucG9wdWxh dGlvbg0KIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMj IyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIw0KDQoiIiJBIGZldyB1 dGlsaXR5IGZ1bmN0aW9ucy4iIiINCg0KZGVmIHJvdWxldHRlU2VsZWN0KHJv dWxldHRlX3dlaWdodHMpOg0KICAgICIiIkdpdmVuIGEgbGlzdCBvZiBwb3Np dGl2ZSByb3VsZXR0ZV93ZWlnaHRzLCByZXR1cm4gdGhlIGluZGV4IG9mDQog ICAgdGhlIGVsZW1lbnQgY2hvc2VuLiIiIg0KICAgIHN1bSA9IGxpc3RTdW0o cm91bGV0dGVfd2VpZ2h0cykNCiAgICBjaG9pY2UgPSByYW5kb20ucmFuZG9t KCkgKiBzdW0NCiAgICBmb3IgaSBpbiByYW5nZShsZW4ocm91bGV0dGVfd2Vp Z2h0cykpOg0KICAgICAgICBhc3NlcnQgcm91bGV0dGVfd2VpZ2h0c1tpXSA+ PSAwDQogICAgICAgIGlmIGNob2ljZSA8IHJvdWxldHRlX3dlaWdodHNbaV06 DQogICAgICAgICAgICByZXR1cm4gaQ0KICAgICAgICBlbHNlOg0KICAgICAg ICAgICAgY2hvaWNlIC09IHJvdWxldHRlX3dlaWdodHNbaV0NCiAgICByZXR1 cm4gLTENCiAgICAjIyBUaGlzIGxhc3QgcmV0dXJuIHN0YXRlbWVudCBzaG91 bGQgbm90IGJlIG5lY2Vzc2FyeSwgYWNjb3JkaW5nDQogICAgIyMgdG8gcHJv YmFiaWxpdHkgdGhlb3J5LiAgU3RpbGwsIGl0IG1pZ2h0IGJlIGEgZ29vZCBp ZGVhIHRvDQogICAgIyMgcHJvZ3JhbSBkZWZlbnNpdmVseS4NCg0KDQpkZWYg bm9ybWFsaXplKEwpOg0KICAgICIiIkdpdmVuIGEgbGlzdCBvZiBudW1iZXJz LCBtYWtlIGV2ZXJ5dGhpbmcgZ28gZnJvbSAwIHRvIDEuIiIiDQogICAgcGFz cw0KDQoNCmRlZiBsaXN0U3VtKEwpOg0KICAgICIiIkdpdmVuIGEgbGlzdCBv ZiB0aGluZ3MsIHJldHVybnMgdGhlaXIgdG90YWwgc3VtLiIiIg0KICAgIHJl dHVybiByZWR1Y2Uob3BlcmF0b3IuYWRkLCBMKQ0KDQoNCmRlZiBzdHJpbmdD cm9zc292ZXIoczEsIHMyLCBwcm9iYWJpbGl0eT0wLjUpOg0KICAgICIiIkEg c2ltcGxlIGNyb3Nzb3ZlciBvcGVyYXRvciBvbiBzdHJpbmdzIHMxIGFuZCBz Mi4iIiINCiAgICBmb3IgaSBpbiByYW5nZShsZW4oczEpKToNCiAgICAgICAg aWYgcmFuZG9tLnJhbmRvbSgpIDwgcHJvYmFiaWxpdHk6DQogICAgICAgICAg ICByZXR1cm4gczFbOmldICsgczJbaTpdDQogICAgcmV0dXJuIHMxDQoNCg0K ZGVmIG1ha2VCaW5hcnlTdHJpbmdNdXRhdG9yKHJhZGlhdGlvbik6DQogICAg ZGVmIG11dGF0b3Iocyk6DQogICAgICAgIGxldHRlcnMgPSBsaXN0KHMpDQog ICAgICAgIG5ld2xldHRlcnMgPSBbXQ0KICAgICAgICBmb3IgbCBpbiBsZXR0 ZXJzOg0KICAgICAgICAgICAgaWYgcmFuZG9tLnJhbmRvbSgpIDwgcmFkaWF0 aW9uOg0KICAgICAgICAgICAgICAgIGlmIGwgPT0gJzAnOiBuZXdsZXR0ZXJz LmFwcGVuZCgnMScpDQogICAgICAgICAgICAgICAgZWxzZTogbmV3bGV0dGVy cy5hcHBlbmQoJzAnKQ0KICAgICAgICAgICAgZWxzZToNCiAgICAgICAgICAg ICAgICBuZXdsZXR0ZXJzLmFwcGVuZChsKQ0KICAgICAgICByZXR1cm4gJycu am9pbihuZXdsZXR0ZXJzKQ0KICAgIHJldHVybiBtdXRhdG9yDQo= --545289610-1136917903-998018985=:19828 Content-Type: TEXT/PLAIN; charset=US-ASCII; name="partition50.py" Content-Transfer-Encoding: BASE64 Content-ID: Content-Description: Content-Disposition: attachment; filename="partition50.py" IyEvdXNyL2Jpbi9lbnYgcHl0aG9uDQppbXBvcnQgcmFuZG9tDQppbXBvcnQg b3BlcmF0b3INCmZyb20gbWF0aCBpbXBvcnQgc3FydCwgc2luDQpmcm9tIGdl bmV0aWMgaW1wb3J0IEdlbmV0aWNBbGdvcml0aG0sIHN0cmluZ0Nyb3Nzb3Zl ciwgbWFrZUJpbmFyeVN0cmluZ011dGF0b3INCmZyb20gcHByaW50IGltcG9y dCBwcHJpbnQNCg0KIiIiDQpBIGdlbmV0aWMgYWxnb3JpdGhtIHRoYXQgdHJp ZXMgc29sdmluZyB0aGUgcGFydGl0aW9uaW5nLXNxcnQtNTANCnByb2JsZW0g bWVudGlvbmVkIG9uIFB5dGhvbi10dXRvcjoNCg0KICAgIGh0dHA6Ly9tYWls LnB5dGhvbi5vcmcvcGlwZXJtYWlsL3R1dG9yLzIwMDEtQXVndXN0LzAwNzk3 My5odG1sDQoNCkRhbm55IFlvbyAoZHlvb0Boa24uZWVjcy5iZXJrZWxleS5l ZHUpDQoNCkhlcmUncyBhIHBhcnRpY3VsYXJseSBVc2VsZXNzIGFwcHJvYWNo IHRvIHNvbHZpbmcgdGhlIHBhcnRpdGlvbmluZw0KcHJvYmxlbS4gIEkgaG9w ZSB5b3UgZW5qb3kgaXQuICAqZ3JpbioNCg0KDQpBbiAiaW5kaXZpZHVhbCIg aXMgYSBiaW5hcnkgc3RyaW5nIG9mIGxlbmd0aCA1MC4gIEhlcmUgYXJlIGEg ZmV3DQpwZW9wbGUgaW4gYSBzYW1wbGUgcG9wdWxhdGlvbjoNCg0KICAgICIw MTEwMTAwMTEwMDAwMTAwMDEwMDExMTEwMDExMDAxMDExMDAwMDAxMDExMTEw MDExMSINCiAgICAiMTAxMDAxMDAwMTExMDAxMDAwMTAwMDAxMTEwMDExMDEx MTAxMDAxMDAxMDExMDAxMTEiDQoNClRoZSB3YXkgdGhpcyB3b3JrcyBpcyB0 aGF0IHdlIHRyeSAiYnJlZWRpbmciIHNvbHV0aW9ucyB0aGF0IHNlZW0gdG8N CmFkZCB1cCB0byByb290X3N1bS8yIC0tLSBpZiB3ZSBnZXQgaXQgZXhhY3Rs eSwgdGhlbiBvdXIgcGFydGl0aW9uIHdpbGwNCmRpdmlkZSByb290X3N1bSBj b21wbGV0ZWx5LiAgT2YgY291cnNlLCB3ZSdyZSBub3QgdGhhdCBvcHRpbWlz dGljLi4uDQoNClRoaXMgYXBwcm9hY2ggd29ya3Mgb24gdGhlIGlkZWEgdGhh dCBnb29kIHNvbHV0aW9ucyBzaGFyZSBjZXJ0YWluDQpjaGFyYWN0ZXJpc3Rp Y3Mgd2l0aCBvdGhlcnM7IHRoZWlyIGJpdCBwYXR0ZXJzIHdpbGwgc2hhcmUg Y29tbW9uDQplbGVtZW50cyB0aGF0IHdpbGwgc3Vydml2ZSBvbiBnZW5ldGlj IGNyb3Nzb3Zlci4gIFNlZSBNZWxhbmllDQpNaXRjaGVsbCdzIGJvb2ssICJB biBJbnRyb2R1Y3Rpb24gdG8gR2VuZXRpYyBBbGdvcml0aG1zIiwgZm9yIGEg bmljZQ0KaW50cm9kdWN0aW9uIGludG8gdGhpcyB3YWNreSB0b3BpYy4NCg0K IiIiDQoNCiMgR2xvYmFsIHZhcmlhYmxlcw0Kc3F1YXJlX3Jvb3RzID0gW3Nx cnQoeCkgZm9yIHggaW4gcmFuZ2UoMSwgNTEpXQ0Kcm9vdF9zdW0gPSByZWR1 Y2Uob3BlcmF0b3IuYWRkLCBzcXVhcmVfcm9vdHMpDQptYWdpYyA9IDQyDQoN Cg0KZGVmIG1ha2VSYW5kb21CaW5hcnlTdHJpbmcobik6DQogICAgIiIiUmV0 dXJuIGEgcmFuZG9tICJiaW5hcnkiIHN0cmluZyBvZiBsZW5ndGggbi4gIFdl IGdldCBjYW4gZ2V0DQogICAgc3RyaW5ncyBsaWtlICIwMDAxMCIgZnJvbSB0 aGlzLg0KDQogICAgKE5vdGUgdGhhdCB3aGF0IHdlIGdldCBiYWNrIGlzIGEg UHl0aG9uIHN0cmluZywgYW5kIG5vdCBhDQogICAgYmluYXJ5LXBhY2tlZCBz dHJpbmcuKSIiIg0KICAgIGxldHRlcnMgPSBbXQ0KICAgIGZvciBpIGluIHJh bmdlKG4pOg0KICAgICAgICBpZiByYW5kb20ucmFuZGludCgwLCAxKSA9PSAw Og0KICAgICAgICAgICAgbGV0dGVycy5hcHBlbmQoJzAnKQ0KICAgICAgICBl bHNlOg0KICAgICAgICAgICAgbGV0dGVycy5hcHBlbmQoJzEnKQ0KICAgIHJl dHVybiAnJy5qb2luKGxldHRlcnMpDQoNCg0KZGVmIGNsb3NlVG9aZXJvbmVz cyh4KToNCiAgICAiIiJUaGlzIGZ1bmN0aW9uIGdldHMgY2xvc2UgdG8gMSBu ZWFyIHplcm8sIGFuZCB0cmllcyB0byBkZWNheQ0KICAgIGZyb20gdGhlcmUu Li4gQXMgeW91IGNhbiB0ZWxsLCB0aGlzIGlzIGEgaGV1cmlzdGljLCBhbmQg SSBuZWVkIHRvDQogICAgZml4IGl0LiIiIg0KICAgIGlmIGFicyh4KSA+IDM6 IHJldHVybiAwDQogICAgeCA9IHggLyAxMC4wDQogICAgcmV0dXJuIGFicygx MCAqIHNpbih4KS94KSAgICAgICAgICAgICAgICAgIyMgZml4bWUNCg0KDQpk ZWYgZXZhbHVhdGVQZXJzb24ocCk6DQogICAgIiIiR2l2ZW4gYSBwZXJzb24g aW4gb3VyIHBvcHVsYXRpb24sIHJldHVybiB0aGVpciAidmFsdWUiLiIiIg0K ICAgIHN1bSA9IDANCiAgICBmb3IgaSBpbiByYW5nZShsZW4ocCkpOg0KICAg ICAgICBpZiBwW2ldID09ICcwJzogcGFzcw0KICAgICAgICBlbHNlOg0KICAg ICAgICAgICAgc3VtICs9IHNxdWFyZV9yb290c1tpXQ0KICAgIHJldHVybiBz dW0NCg0KDQpkZWYgZml0bmVzc0Z1bmN0aW9uKGluZGl2aWR1YWwsIHBlZXJz KToNCiAgICAiIiJUaGlzIGZpdG5lc3MgZnVuY3Rpb24gZHJhd3MgYW4gYWJz b2x1dGUgbGluZSBvZiBmaXRuZXNzOiBhbg0KICAgIGluZGl2aWR1YWwgaXMg Zml0IGlmIGhlIG9yIHNoZSAiYWRkcyIgdXAgY2xvc2UgdG8gdGhlIHN1bSBv ZiBhbg0KICAgIGlkZWFsIHBhcnRpdGlvbmluZy4gIFdlJ2xsIGlnbm9yZSBv dXIgcGVlcnMgZm9yIG5vdy4iIiINCiAgICBzdW0gPSBldmFsdWF0ZVBlcnNv bihpbmRpdmlkdWFsKQ0KICAgIHJldHVybiBjbG9zZVRvWmVyb25lc3MoYWJz KHN1bSAtIHJvb3Rfc3VtLzIpKQ0KDQoNCmRlZiBjaG9vc2VCZXN0KHBvcHVs YXRpb24pOg0KICAgICIiIlJldHVybiB0aGUgImJlc3QiIHBlcnNvbiBpbiB0 aGUgcG9wdWxhdGlvbiwgdGhhdCBpcywgdGhlIHBlcnNvbg0KICAgIHdobydz IHZhbHVlIGlzIGNsb3Nlc3QgdG8gcm9vdF9zdW0vMi4iIiINCiAgICBhc3Nl cnQgbGVuKHBvcHVsYXRpb24pID4gMA0KICAgIGJlc3RfY2hvaWNlID0gcG9w dWxhdGlvblswXQ0KICAgIGZvciBwIGluIHBvcHVsYXRpb25bMTpdOg0KICAg ICAgICBpZiAoYWJzKGV2YWx1YXRlUGVyc29uKHApIC0gcm9vdF9zdW0vMikg PA0KICAgICAgICAgICAgYWJzKGV2YWx1YXRlUGVyc29uKGJlc3RfY2hvaWNl KSAtIHJvb3Rfc3VtLzIpKToNCiAgICAgICAgICAgIGJlc3RfY2hvaWNlID0g cA0KICAgIHJldHVybiBiZXN0X2Nob2ljZQ0KDQoNCmRlZiBkZXNjcmliZVBl cnNvbihwZXJzb24pOg0KICAgIHNxcnRzID0gWyJzcXJ0KCVzKSIgJSAoYml0 KzEpIGZvciBiaXQgaW4gcmFuZ2UobGVuKHBlcnNvbikpDQogICAgICAgICAg ICAgaWYgcGVyc29uW2JpdF0gPT0gJzEnXQ0KICAgIHJldHVybiAnICsgJy5q b2luKHNxcnRzKQ0KDQoNCmRlZiBtYWluKCk6DQogICAgcG9wdWxhdGlvbiA9 IFttYWtlUmFuZG9tQmluYXJ5U3RyaW5nKDUwKSBmb3IgaSBpbiByYW5nZSgx MCldDQogICAgYWxnb3JpdGhtID0gR2VuZXRpY0FsZ29yaXRobShpbml0aWFs X3BvcHVsYXRpb249cG9wdWxhdGlvbiwNCiAgICAgICAgICAgICAgICAgICAg ICAgICAgICAgICAgIGZpdG5lc3NfZnVuY3Rpb249Zml0bmVzc0Z1bmN0aW9u LA0KICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgY3Jvc3NvdmVy X2Z1bmN0aW9uPXN0cmluZ0Nyb3Nzb3ZlciwNCiAgICAgICAgICAgICAgICAg ICAgICAgICAgICAgICAgIG11dGF0aW9uX2Z1bmN0aW9uPW1ha2VCaW5hcnlT dHJpbmdNdXRhdG9yKDAuMDQyKSkNCiAgICBiZXN0X2Nob2ljZSA9ICcwJyAq IDUwDQogICAgZm9yIGkgaW4gcmFuZ2UoNTAwKToNCiAgICAgICAgYWxnb3Jp dGhtLnNpbXVsYXRlKCkNCiAgICAgICAgYmVzdF9jaG9pY2UgPSBjaG9vc2VC ZXN0KGFsZ29yaXRobS5nZXRQb3B1bGF0aW9uKCkgKyBbYmVzdF9jaG9pY2Vd KQ0KICAgICAgICBwcmludCAiSXRlcmF0aW9uICVkIiAlIGkNCiAgICAgICAg cHJpbnQgIk91ciBiZXN0IGNob2ljZSAoJXMpIiAlIGJlc3RfY2hvaWNlDQog ICAgICAgIHByaW50ICJoYXMgYSB2YWx1ZSBvZiAlcyIgJSBldmFsdWF0ZVBl cnNvbihiZXN0X2Nob2ljZSkNCiAgICAgICAgcHJpbnQgIkRpZmZlcmVuY2Ug YmV0d2VlbiBpdCBhbmQgb3VyIHRhcmdldDogJXMiICUgXA0KICAgICAgICAg ICAgICBhYnMoZXZhbHVhdGVQZXJzb24oYmVzdF9jaG9pY2UpIC0gcm9vdF9z dW0vMikNCiAgICBwcmludCAiT2ssIGRvbmUgY29tcHV0aW5nLiAgT3VyIGJl c3QgY2hvaWNlLCINCiAgICBwcmludCBkZXNjcmliZVBlcnNvbihiZXN0X2No b2ljZSkNCiAgICBwcmludCAiaXMgVEhJUyBjbG9zZSB0byBvdXIgdGFyZ2V0 OiIsIChhYnMoZXZhbHVhdGVQZXJzb24oYmVzdF9jaG9pY2UpDQogICAgICAg ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgLSBy b290X3N1bS8yKSkNCg0KDQppZiBfX25hbWVfXyA9PSAnX19tYWluX18nOg0K ICAgIG1haW4oKQ0K --545289610-1136917903-998018985=:19828-- From jessefw@loop.com Fri Aug 17 04:32:11 2001 From: jessefw@loop.com (Jesse F. W) Date: Thu, 16 Aug 2001 20:32:11 -0700 Subject: [Tutor] Yahtzee-like Program In-Reply-To: <3B7C69E8.73503D92@mindless.com> Message-ID: <3B7C2DCC.17843.1A404D16@localhost> Dear Tim, et all, Timothy M. Brauch wrote: > I've written a small program that is a lot like Yahtzee, without the > pretty graphics. It's more of a command line style game. It works > and obeys all the standard rules. > > However, I know that my 250+ line code is horribly ugly. But, it is > the only way I know how to write it. I would like it if someone would > look at it and give me some pointers to help clean my code, but I am > hesitant to post all of it on the Tutor list. I am looking over, and commenting on ;-), your code now. It looks pretty good. Right now I am trying to hack up a better dice saving input checker than you had. When I finish, I will post it on my site(see below) for further editing by others if that is alright with you. Or I can send it to you, and you can post in on your site. > If you want to look at it, it is available at > > > Or, if someone wants, I can post the whole code to the Tutor. > > I also realize how boring it would be to look over someone's code and > try to critque it, but I would really like to learn to write cleaner > code, and that is the only way I can learn, right? > > - Tim > > P.S. Once my code has been looked at, I think Useless might get a > posting. From tim.one@home.com Fri Aug 17 05:51:29 2001 From: tim.one@home.com (Tim Peters) Date: Fri, 17 Aug 2001 00:51:29 -0400 Subject: [Tutor] My shot at the partitioning problem In-Reply-To: Message-ID: Here's something to goad you to greater heights. As dumb as possible: just generate random permutations of the inputs, and for each one do the dumbest possible thing with it to try to get close to the goal. No intelligence, just brute force -- but lots of it . Here's a *poor* run (btw, it stops itself after 10 seconds -- and this is a pretty fast machine, and with a version of Python quicker than 2.1.1): Did 11790 trials in 10.05 seconds. Sum 119.51764944760885, distance from target 0.00025085415153114354. This is the sum of the sqrts of [1, 2, 3, 5, 6, 10, 11, 12, 14, 16, 17, 18, 19, 20, 21, 23, 24, 26, 28, 29, 36, 38, 40, 42, 46, 48, 50] A more typical run gets within 6e-5 of the target. Here's an exceptionally (but not supernaturally) good run: Did 11702 trials in 10 seconds. Sum 119.51789179229621, distance from target 8.5094641661953574e-006. This is the sum of the sqrts of [1, 2, 5, 6, 12, 13, 15, 16, 17, 18, 21, 23, 27, 29, 31, 32, 34, 35, 39, 41, 42, 43, 45, 47, 48] When it comes to computer searches, doing a stupid thing quickly but many times is often more effective than doing an intelligent thing slowly -- that's one of the surprising lessons learned from computer chess, but is due in part to that writing a *truly* intelligent thing is much more difficult than is first imagined. There are several ways to improve this stupid algorithm by making it a *little* more intelligent, but not *too* intelligent -- if you make it smart enough that it runs, say, 10x slower per trial, then it had better be *so* much smarter that it makes up for running it 10x less often. That's a difficult thing to judge in advance! So don't even bother: Just Try It, *whatever* you think of. Then think of something else, and try that too. Repeat until you stumble into a Major Breakthrough . import math import random import time N = 50 roots = [(i, math.sqrt(i)) for i in range(1, N+1)] sum = 0.0 for i, root in roots: sum += root target = sum / 2 # Return a subset of vector and its sum (<= target). def greedy(vector, target): result = [] sum = 0.0 for i, value in vector: newsum = sum + value if newsum <= target: sum = newsum result.append((i, value)) return result, sum start_time = time.time() best_sum = -1.0 best_subset = None ntrials = 0 while time.time() - start_time < 10.0: ntrials += 1 random.shuffle(roots) subset, sum = greedy(roots, target) if sum > best_sum: best_sum = sum best_subset = subset print "Did %d trials in %g seconds." % (ntrials, time.time() - start_time) print "Sum %r, distance from target %r." % (best_sum, target - best_sum) best_subset.sort() print "This is the sum of the sqrts of" print " ", [i for (i, value) in best_subset] in-the-end-a-billion-mindless-insects-can-devour-anyone-ly y'rs - tim From pobrien@orbtech.com Fri Aug 17 06:08:37 2001 From: pobrien@orbtech.com (Patrick K. O'Brien) Date: Fri, 17 Aug 2001 00:08:37 -0500 Subject: [Tutor] Pythonpath question In-Reply-To: <3B7B228F.C342F89E@earthlink.net> Message-ID: Follow the thread that starts here: http://aspn.activestate.com/ASPN/Mail/Message/557565 --- Patrick K. O'Brien Orbtech "I am, therefore I think." -----Original Message----- From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of Ron Stephens Sent: Wednesday, August 15, 2001 8:32 PM To: tutor@python.org Subject: [Tutor] Pythonpath question Could someoen give me a quick and brief tutorail on pythonpath, how to set it for windows 98 etc???? ;-))) Sorry to be so braindead.... _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From shalehperry@home.com Fri Aug 17 07:40:29 2001 From: shalehperry@home.com (Sean 'Shaleh' Perry) Date: Thu, 16 Aug 2001 23:40:29 -0700 (PDT) Subject: [Tutor] anecdote in the workplace about try,except clause In-Reply-To: Message-ID: > > Or, at least, the very last data will be the only thing printed out. Danny's mailer misread where the print fell. Each iteration of the loop would try to print, but in this case the first line of the file would trigger the exception and thus cause data to be undefined. From scarblac@pino.selwerd.nl Fri Aug 17 07:58:37 2001 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Fri, 17 Aug 2001 08:58:37 +0200 Subject: [Tutor] anecdote in the workplace about try,except clause In-Reply-To: ; from shalehperry@home.com on Thu, Aug 16, 2001 at 07:32:44PM -0700 References: Message-ID: <20010817085837.A23610@pino.selwerd.nl> On 0, Sean 'Shaleh' Perry wrote: > So, thought i would pass this on. > > A coworker who is a long time perl'er is learning python and asking me > questions now and then. Today he was writing a file parser and did the > following: > > for line in file: > try: > data, garbage = string.split(line, ':') > except ValueError: > pass > > print 'Data: %s' % data > > > His rationale was that some lines lack the ':' so he would just let the > exception hide the 'annoying' python exception assuming that data would be > assigned the whole line in that case. > > What he failed to realize is that when the except clause is triggered items in > the try clause go out of scope. So data would not exist. try: doesn't have it's own scope, so data doesn't go out of scope. But it was never assigned to in that loop. I'd expect the print to print the data from the previous run through the loop. -- Remco Gerlich From sburr@home.com Fri Aug 17 08:17:02 2001 From: sburr@home.com (Steven Burr) Date: Fri, 17 Aug 2001 00:17:02 -0700 Subject: [Tutor] Dumb Luck with the Partitioning Problem Message-ID: <20010817071411.NOCA14739.femail46.sdc1.sfba.home.com@localhost> --Apple-Mail-1476058108-1 Content-Transfer-Encoding: 7bit Content-Type: text/plain; format=flowed; charset=us-ascii My bright idea on the partitioning problem was to try to arrive at a quick approximation of the best result, and then massage the resulting data sets to get closer to the target. (It occurred to me later that this approach probably makes no sense, because for all I know the set of integers yielding the best result and the set yielding the next best result are completely different.) So anyway, I decided that splitting the set of the integers from 1 to 50 into evens and odds might be a good first approximation of the best result. I then wrote an algorithm that found the combination of two numbers, one from each set, that would yield the greatest reduction in the difference between the sum of the squares. Just these first two steps produced the following results: First list: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 29, 31, 33, 35, 37, 39, 41, 43, 45, 46, 47, 49] Sum of square roots = 119.517524702 Second list: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 27, 28, 30, 32, 34, 36, 38, 40, 42, 44, 48, 50] Sum of square roots = 119.518275902 Distance from target = 0.000375600114126 Total time = 0.02 These results are actually better than those produced by Danny's method, which I can't even begin to understand, and not too far off from those produced by Tim's "brute force" approach. I probably don't need to tell you, however, that this was pure, dumb (literally) luck. I tried the same approach on other sets of integers, and the results are not nearly as impressive. Every attempt I made to massage to the numbers further either went horribly wrong or made no progress. At about 2:00 a.m. on the night Danny posted the problem, I tossed in the towel. (Thanks so much, Danny. : ) My opus is attached for your amusement. If there were a web site called "senseless python," I would make a submission. -- third from the bottom http://www.adeq.state.az.us/lead/staff.html --Apple-Mail-1476058108-1 Content-Type: multipart/mixed; boundary=Apple-Mail-96379525-2 --Apple-Mail-96379525-2 Content-Transfer-Encoding: 7bit Content-Type: text/plain; charset=us-ascii; format=flowed My bright idea on the partitioning problem was to try to arrive at a quick approximation of the best result, and then massage the resulting data sets to get closer to the target. (It occurred to me later that this approach probably makes no sense, because for all I know the set of integers yielding the best result and the set yielding the next best result are completely different.) So anyway, I decided that splitting the set of the integers from 1 to 50 into evens and odds might be a good first approximation of the best result. I then wrote an algorithm that found the combination of two numbers, one from each set, that would yield the greatest reduction in the difference between the sum of the squares. Just these first two steps produced the following results: First list: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 29, 31, 33, 35, 37, 39, 41, 43, 45, 46, 47, 49] Sum of square roots = 119.517524702 Second list: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 27, 28, 30, 32, 34, 36, 38, 40, 42, 44, 48, 50] Sum of square roots = 119.518275902 Distance from target = 0.000375600114126 Total time = 0.02 These results are actually better than those produced by Danny's method, which I can't even begin to understand, and not too far off from those produced by Tim's "brute force" approach. I probably don't need to tell you, however, that this was pure, dumb (literally) luck. I tried the same approach on other sets of integers, and the results are not nearly as impressive. Every attempt I made to massage to the numbers further either went horribly wrong or made no progress. At about 2:00 a.m. on the night Danny posted the problem, I tossed in the towel. (Thanks so much, Danny. : ) My opus is attached for your amusement. If there were a web site called "senseless python," I would make a submission. -- third from the bottom http://www.adeq.state.az.us/lead/staff.html --Apple-Mail-96379525-2 Content-Disposition: attachment; filename="practice.py" Content-Type: application/octet-stream; name="practice.py"; x-unix-mode=0644 Content-Transfer-Encoding: 7bit #-----PRELIMINARIES-----# # Set the constant N = 31 # Imports from math import sqrt from operator import add import time # Start the timer start = time.clock() # Func to find difference between sum of sqrts def finddiff(first, second): return ( reduce(add, [t[1] for t in first]) - reduce(add, [t[1] for t in second]) ) / 2 #-----APPROXIMATE BEST RESULT-----# # Dividing between odds and evens seems like a good initial # guess first = [(x, sqrt(x)) for x in range(1, N, 2)] second = [(x, sqrt(x)) for x in range(2, N, 2)] # Find best result from switching two numbers diff = finddiff(first, second) bestresult = abs(diff) for x in first: for y in second: currdiff = abs(x[1] - y[1] - diff) if currdiff < bestresult: bestresult = currdiff ind1 = first.index(x) ind2 = second.index(y) # Change the lists to reflect approximation first[ind1], second[ind2] = second[ind2], first[ind1] first.sort() second.sort() sum1 = reduce(add, [t[1] for t in first]) sum2 = reduce(add, [t[1] for t in second]) target = reduce(add, [sqrt(x) for x in range(1, N)]) / 2 #-----GET CLOSER-----# # Dismal failures deleted #-----PRINT RESULT-----# print "First list: ", [i[0] for i in first] print "Sum of square roots = ", sum1 print "Second list: ", [i[0] for i in second] print "Sum of square roots = ", sum2 print "Distance from target = ", max([sum1, sum2]) - target print "Total time = ", time.clock() - start --Apple-Mail-96379525-2-- --Apple-Mail-1476058108-1-- From SBrunning@trisystems.co.uk Fri Aug 17 09:16:00 2001 From: SBrunning@trisystems.co.uk (Simon Brunning) Date: Fri, 17 Aug 2001 09:16:00 +0100 Subject: [Tutor] anecdote in the workplace about try,except clause Message-ID: <31575A892FF6D1118F5800600846864D78BFC3@intrepid> > From: Remco Gerlich [SMTP:scarblac@pino.selwerd.nl] > > for line in file: > > try: > > data, garbage = string.split(line, ':') > > except ValueError: > > pass > > > > print 'Data: %s' % data > > > > What he failed to realize is that when the except clause is triggered > items in > > the try clause go out of scope. So data would not exist. > > try: doesn't have it's own scope, so data doesn't go out of scope. But it > was never assigned to in that loop. > > I'd expect the print to print the data from the previous run through the > loop. Unless it failed first time through, in which case he would get a NameError. Perhaps this is what makes Sean think that data is going 'out of scope'? Cheers, Simon Brunning TriSystems Ltd. sbrunning@trisystems.co.uk ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From tescoil@irtc.net Fri Aug 17 09:50:47 2001 From: tescoil@irtc.net (Tesla Coil) Date: Fri, 17 Aug 2001 03:50:47 -0500 Subject: [Tutor] Dumb Luck with the Partitioning Problem References: <20010817071411.NOCA14739.femail46.sdc1.sfba.home.com@localhost> Message-ID: <3B7CDAE7.51E9AFA0@irtc.net> On 17 Aug 2001, Steven Burr wrote: > If there were a web site called "senseless python," > I would make a submission. That's not necessary. Useless accepts *all* the latest advances in self-deprecating Python source! From tescoil@irtc.net Fri Aug 17 09:37:14 2001 From: tescoil@irtc.net (Tesla Coil) Date: Fri, 17 Aug 2001 03:37:14 -0500 Subject: [Tutor] How does python find the modules I install ??? References: Message-ID: <3B7CD7BA.F6812BCA@irtc.net> On 16 August 2001, Andy Dustman wrote: > I only just came in on this thread, That's fair. I didn't even have in mind to install MySQL-python when I dropped in here. :} > but if you get the MySQL-python sources, enter > it's root directory, and run: > > python2 setup.py bdist_rpm --python=/usr/bin/python2 > > you will get nice RPMS for python2 (adjust paths). Snappy, and does a great job. On SuSE >=7.1, the command should be directed to python2.0, and if one has the Personal Edition, python-devel.rpm will need to be ftp'd and installed in addition to the obvious MySQL rpms. Thanks. You really should visit us more often... From alan.gauld@bt.com Fri Aug 17 14:02:46 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri, 17 Aug 2001 14:02:46 +0100 Subject: [Tutor] Pythonpath question Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BEA8@mbtlipnt02.btlabs.bt.co.uk> > Could someoen give me a quick and brief tutorail on pythonpath, how to > set it for windows 98 etc???? ;-))) Open notepad File|Open C:\>autoexec.bat Go to the end of the file and add the line: SET PYTHONPATH=C:\PYTHON\MyModules using the full path of wherever you keep your "missing" modules. Now save and close the file. Reboot. To add another location edit the same line to ook like: SET PYTHONPATH=C:\PYTHON\MyModules;D:\Project\modules Thats it. Reboot for changes to take effect (you could just run autoexec.bat from an open dos box as a short term fix) Alan G From lsloan@umich.edu Fri Aug 17 14:48:25 2001 From: lsloan@umich.edu (Lance E Sloan) Date: Fri, 17 Aug 2001 09:48:25 -0400 Subject: [Tutor] Help with CGI login In-Reply-To: Your message of "Thu, 16 Aug 2001 18:09:55 PDT." Message-ID: <200108171348.JAA24315@birds.us.itd.umich.edu> "James" wrote: > I tried this, but the fields seem to be hidden from view when logging in. > I've been trying to figure out the fields from the html source for the page, > but haven't got it right yet. > > Here's some snips of the relevant (i think) html source: >

    What does the JavaScript test_js() do? You should look at that, it may be important, seeing as there's a hidden field in the form with "js_test" as the name. > value="subscriber_login"> [...] > > > > I would try adding all these hidden fields to your URL. > value="Login" alt="Login" border=0> I can't remember how this input would look when it's submitted. It has no "name" attribute, so it might not be submitted at all. Who knows? > I'm trying things like > http://www.listbot.com/cgi-bin/customer?Act=login&customer_e_mail_login=emai > l@addy.com&customer_password_login=mypass= > manually with my browsers address bar. Be sure to add those hidden fields! -- Lance E Sloan Web Services, Univ. of Michigan: Full-service Web and database design, development, and hosting. Specializing in Python & Perl CGIs. http://websvcs.itd.umich.edu/ - "Putting U on the Web" From rob@jam.rr.com Fri Aug 17 15:12:10 2001 From: rob@jam.rr.com (Rob Andrews) Date: Fri, 17 Aug 2001 09:12:10 -0500 Subject: [Tutor] Dumb Luck with the Partitioning Problem References: <20010817071411.NOCA14739.femail46.sdc1.sfba.home.com@localhost> <3B7CDAE7.51E9AFA0@irtc.net> Message-ID: <3B7D263A.DA427533@jam.rr.com> Tesla Coil wrote: > > On 17 Aug 2001, Steven Burr wrote: > > If there were a web site called "senseless python," > > I would make a submission. > > That's not necessary. Useless accepts *all* the > latest advances in self-deprecating Python source! > This is true. We've never turned any submissions down for any reason,even the useful ones. Besides, your code is actually a solution to a Useless Python Challenge problem. I'm trying to arrange to have a Useless Python exhibit at Python 10, BTW. Anyone else planning on attending the Conference? As much love labor as the Python Tutor crew has put into Useless so far, I want to show off a bit. Besides, we have the closest thing to a Python programming contest I've seen. Rob -- A {} is a terrible thing to waste. Useless Python! http://www.lowerstandard.com/python From kev@sat.net Fri Aug 17 15:14:23 2001 From: kev@sat.net (Kevin McCormick) Date: Fri, 17 Aug 2001 09:14:23 -0500 Subject: [Tutor] Using dictionaries to call functione Message-ID: <3B7D26BF.2DDA0A8A@sat.net> I have seen several examples of using dictionaries to call functions. I believe the function name is the dictionary key, and its values are the associated arguments. Yet, I find this method difficult to understand. For example, I would like to pass a list of words and parameters to a function, and for each word in the list, call word(parameter1, parameter2, ...) referenced in a dictionary which somehow calls the associated function (called a "dispatch table", I think). What are the basic concepts of this method? From dsh8290@rit.edu Fri Aug 17 15:40:34 2001 From: dsh8290@rit.edu (dman) Date: Fri, 17 Aug 2001 10:40:34 -0400 Subject: [Tutor] Using dictionaries to call functione In-Reply-To: <3B7D26BF.2DDA0A8A@sat.net>; from kev@sat.net on Fri, Aug 17, 2001 at 09:14:23AM -0500 References: <3B7D26BF.2DDA0A8A@sat.net> Message-ID: <20010817104034.A12987@harmony.cs.rit.edu> On Fri, Aug 17, 2001 at 09:14:23AM -0500, Kevin McCormick wrote: | I have seen several examples of using dictionaries to call functions. I | believe the function name is the dictionary key, and its values are the | associated arguments. Yet, I find this method difficult to understand. | For example, I would like to pass a list of words and parameters to a | function, and for each word in the list, call word(parameter1, | parameter2, ...) referenced in a dictionary which somehow calls the | associated function (called a "dispatch table", I think). What are the | basic concepts of this method? In python, functions are objects just like everything else. This means that they can be stored in a dictionary. The key can be anything you want it to be, but is often a string or integer that is directly related to some input. The value is just a reference to the function. The client would retrieve that function object from the dictionary then call it just as it would any other function. The only trick is to make sure that the client knows what sort of arguments the function expects. Here is an example : def func1( p1 , p2 ) : print "func1 called : %s , %s" % (p1 , p2) def func2( p1 , p2 ) : print "func2 called : %s , %s" % (p1 , p2) dispatch_table = { "hello" : func1 , "bye" : func2 } if __name__ == "__main__" : import sys if not dispatch_table.has_key( sys.argv[1] ) : print "Unkown command '%s'" % sys.argv[1] sys.exit( 1 ) if len( sys.argv ) != 4 : print "Not enough arguments!" sys.exit( 1 ) the_func = dispatch_table[ sys.argv[1] ] the_func( sys.argv[2] , sys.argv[3] ) Here is a demonstration of how this script could be used : $ ./dispatch_demo.py fubar Unkown command 'fubar' $ ./dispatch_demo.py hello arg1 arg2 func1 called : arg1 , arg2 $ ./dispatch_demo.py bye spam eggs func2 called : spam , eggs $ HTH, -D From shalehperry@home.com Fri Aug 17 16:16:52 2001 From: shalehperry@home.com (Sean 'Shaleh' Perry) Date: Fri, 17 Aug 2001 08:16:52 -0700 (PDT) Subject: [Tutor] anecdote in the workplace about try,except clause In-Reply-To: <20010817085837.A23610@pino.selwerd.nl> Message-ID: > > try: doesn't have it's own scope, so data doesn't go out of scope. But it > was never assigned to in that loop. > > I'd expect the print to print the data from the previous run through the > loop. > you are right of course. The problem as I explained in another mail was that the first line in the file triggered the exception. So data was never assigned to and therefore when the print statement is reached does not exist and the NameError occurs. From rfbrenar@cs.uchicago.edu Fri Aug 17 19:10:24 2001 From: rfbrenar@cs.uchicago.edu (robert frank brenart) Date: Fri, 17 Aug 2001 13:10:24 -0500 (CDT) Subject: [Tutor] Reading from a file Message-ID: I'm reading in from a file line by line and splitting up the information based on commas... however, the last item in every line has an /012 attached to it... i.e. "CVR",1,2 comes out as ['"CVR"', '7', '3\012'] Just wondering how I can get rid of that \012. -Rob From dyoo@hkn.eecs.berkeley.edu Fri Aug 17 19:17:07 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 17 Aug 2001 11:17:07 -0700 (PDT) Subject: [Tutor] Using dictionaries to call functione In-Reply-To: <20010817104034.A12987@harmony.cs.rit.edu> Message-ID: On Fri, 17 Aug 2001, dman wrote: > On Fri, Aug 17, 2001 at 09:14:23AM -0500, Kevin McCormick wrote: > | I have seen several examples of using dictionaries to call functions. I > | believe the function name is the dictionary key, and its values are the > | associated arguments. Yet, I find this method difficult to understand. > | For example, I would like to pass a list of words and parameters to a > | function, and for each word in the list, call word(parameter1, > | parameter2, ...) referenced in a dictionary which somehow calls the > | associated function (called a "dispatch table", I think). What are the > | basic concepts of this method? > > In python, functions are objects just like everything else. This > means that they can be stored in a dictionary. The key can be > anything you want it to be, but is often a string or integer that is > directly related to some input. The value is just a reference to the > function. The client would retrieve that function object from the > dictionary then call it just as it would any other function. The only > trick is to make sure that the client knows what sort of arguments the > function expects. Here is an example : > > def func1( p1 , p2 ) : > print "func1 called : %s , %s" % (p1 , p2) > > def func2( p1 , p2 ) : > print "func2 called : %s , %s" % (p1 , p2) > > > dispatch_table = { > "hello" : func1 , > "bye" : func2 > } We can also write this so that the dispatcher doesn't even think about how many arguments each function takes in: ### def callFunction(function_name, arguments): the_func = dispatch_table[function_name] the_func(*arguments) if __name__ == "__main__" : import sys if not dispatch_table.has_key( sys.argv[1] ) : print "Unknown command '%s'" % sys.argv[1] sys.exit( 1 ) callFunction(sys.argv[1], sys.argv[2:]) ### The star in front of 'arguments' is what tells Python to send off the elements of 'arguments' to the_func(). Although this simplifies the code a little, now the program will die if we give the function too many arguments, or not enough. That's where exception handling comes in: we can put the code in a try/except block that knows what to do when the user doesn't give enough arguments. Here's another example that demonstrates a little bit of exception handling as well as the dispatch approach: ### """This is a small example of dispatch-based programming. Danny Yoo (dyoo@hkn.eecs.berkeley.edu) """ import sys def addCommand(*args): sum = 0 for thing in args: sum += float(thing) print "The sum is", sum def uppercaseCommand(*args): for thing in args: print thing.upper(), print def quitCommand(*args): print "Goodbye!" sys.exit(0) def helpCommand(*args): print "Here are your available commands: " for key in DISPATCH_TABLE.keys(): description, function = DISPATCH_TABLE[key] print "\t%s: %s" % (key, description) """Our dispatch table has function names as the keys, with (description, function) tuples as values.""" DISPATCH_TABLE = { 'add' : ('Add numbers together.', addCommand), 'uc' : ('Uppercase arguments.', uppercaseCommand), 'quit' : ('Quit.', quitCommand), 'help' : ('You are looking at it.', helpCommand) } def evaluate(command_line): try: function_name, arguments = (command_line.split()[0], command_line.split()[1:]) if DISPATCH_TABLE.has_key(function_name): description, function = DISPATCH_TABLE[function_name] function(*arguments) else: print "I don't know about '%s'." % function_name print "Try typing 'help' at the prompt.\n" except SystemExit: raise SystemExit except (Exception), e: print "Ooops: %s" % e if __name__ == "__main__" : while 1: sys.stdout.write("Command me >>> ") sys.stdout.flush() try: line = raw_input() except EOFError: evaluate("quit") if line: evaluate(line) ### And a sample run: ### [dyoo@tesuque dyoo]$ python dispatcher.py Command me >>> hello I don't know about 'hello'. Try typing 'help' at the prompt. Command me >>> help Here are your available commands: uc: Uppercase arguments help: You are looking at it. add: Add numbers together quit: Quit Command me >>> uc this is a test of the emergency broadcast system THIS IS A TEST OF THE EMERGENCY BROADCAST SYSTEM Command me >>> add 3 4 5 6 7 The sum is 25.0 Command me >>> add three one four one five nine two six Ooops: invalid literal for float(): three Command me >>> quit Goodbye! ### From israel@lith.com Fri Aug 17 19:21:05 2001 From: israel@lith.com (Israel Evans) Date: Fri, 17 Aug 2001 11:21:05 -0700 Subject: [Tutor] Reading from a file Message-ID: this may not be the best way to do it but it seems to work... I'm rather new to this to. >>> line = """"CVR",1,2""" >>> info = line.split(',') >>> info ['"CVR"', '1', '2'] >>> info.remove(info[len(info)-1]) >>> info ['"CVR"', '1'] I'm just removing the last item in the list. The /012 is probably some sort of line ending like \n? I'm guessing. -----Original Message----- From: robert frank brenart [mailto:rfbrenar@cs.uchicago.edu] Sent: Friday, August 17, 2001 11:10 AM To: tutor@python.org Subject: [Tutor] Reading from a file I'm reading in from a file line by line and splitting up the information based on commas... however, the last item in every line has an /012 attached to it... i.e. "CVR",1,2 comes out as ['"CVR"', '7', '3\012'] Just wondering how I can get rid of that \012. -Rob _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From dsh8290@rit.edu Fri Aug 17 19:43:00 2001 From: dsh8290@rit.edu (dman) Date: Fri, 17 Aug 2001 14:43:00 -0400 Subject: [Tutor] Reading from a file In-Reply-To: ; from rfbrenar@cs.uchicago.edu on Fri, Aug 17, 2001 at 01:10:24PM -0500 References: Message-ID: <20010817144300.A13264@harmony.cs.rit.edu> On Fri, Aug 17, 2001 at 01:10:24PM -0500, robert frank brenart wrote: | I'm reading in from a file line by line and splitting up the information | based on commas... however, the last item in every line has an /012 | attached to it... i.e. | | "CVR",1,2 | | comes out as | | ['"CVR"', '7', '3\012'] | | Just wondering how I can get rid of that \012. The \0 part means that that character is being displayed in its octal format. 012 is '\n' or NL. What OS created the files and what OS are you reading them on? You could strip that character off the string before you split it. for line in file.xreadlines() : line = line.strip() print line.split( "," ) HTH, -D From israel@lith.com Fri Aug 17 19:47:41 2001 From: israel@lith.com (Israel Evans) Date: Fri, 17 Aug 2001 11:47:41 -0700 Subject: [Tutor] Reading from a file Message-ID: That's what I was thinking.. How about: >>> import re >>> pat = re.compile('\012') >>> line = """"CVR",1,2\012""" >>> info = re.sub(pat, '',line) >>> finalanswer = info.split(',') >>> finalanswer ['"CVR"', '1', '2'] -----Original Message----- From: dman [mailto:dsh8290@rit.edu] Sent: Friday, August 17, 2001 11:43 AM To: tutor@python.org Subject: Re: [Tutor] Reading from a file On Fri, Aug 17, 2001 at 01:10:24PM -0500, robert frank brenart wrote: | I'm reading in from a file line by line and splitting up the information | based on commas... however, the last item in every line has an /012 | attached to it... i.e. | | "CVR",1,2 | | comes out as | | ['"CVR"', '7', '3\012'] | | Just wondering how I can get rid of that \012. The \0 part means that that character is being displayed in its octal format. 012 is '\n' or NL. What OS created the files and what OS are you reading them on? You could strip that character off the string before you split it. for line in file.xreadlines() : line = line.strip() print line.split( "," ) HTH, -D _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From rfbrenar@cs.uchicago.edu Fri Aug 17 19:55:41 2001 From: rfbrenar@cs.uchicago.edu (robert frank brenart) Date: Fri, 17 Aug 2001 13:55:41 -0500 (CDT) Subject: [Tutor] Reading from a file In-Reply-To: <20010817144300.A13264@harmony.cs.rit.edu> Message-ID: And we have a winner... thanks a bunch. -Rob > > The \0 part means that that character is being displayed in its octal > format. 012 is '\n' or NL. What OS created the files and what OS > are you reading them on? You could strip that character off the > string before you split it. > > > for line in file.xreadlines() : > line = line.strip() > print line.split( "," ) > > HTH, > -D > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From dsh8290@rit.edu Fri Aug 17 19:57:55 2001 From: dsh8290@rit.edu (dman) Date: Fri, 17 Aug 2001 14:57:55 -0400 Subject: [Tutor] Reading from a file In-Reply-To: ; from israel@lith.com on Fri, Aug 17, 2001 at 11:47:41AM -0700 References: Message-ID: <20010817145755.A13306@harmony.cs.rit.edu> On Fri, Aug 17, 2001 at 11:47:41AM -0700, Israel Evans wrote: | That's what I was thinking.. | | How about: | | >>> import re | >>> pat = re.compile('\012') | >>> line = """"CVR",1,2\012""" | >>> info = re.sub(pat, '',line) | >>> finalanswer = info.split(',') | >>> finalanswer | ['"CVR"', '1', '2'] It might be faster to do a string.replace() since your regex is just a literal character. Since this character is considered as whitespace the string.strip() works also. -D From dsh8290@rit.edu Fri Aug 17 19:59:25 2001 From: dsh8290@rit.edu (dman) Date: Fri, 17 Aug 2001 14:59:25 -0400 Subject: [Tutor] Reading from a file In-Reply-To: ; from rfbrenar@cs.uchicago.edu on Fri, Aug 17, 2001 at 01:55:41PM -0500 References: <20010817144300.A13264@harmony.cs.rit.edu> Message-ID: <20010817145925.B13306@harmony.cs.rit.edu> On Fri, Aug 17, 2001 at 01:55:41PM -0500, robert frank brenart wrote: | And we have a winner... thanks a bunch. You're welcome. I'm still interested in the answer to the OS question. At first I was expecting \012 to be CR since I first assumed it was a 'doze file being read on a *nix system, but checked the ascii table before I posted. -D From rfbrenar@cs.uchicago.edu Fri Aug 17 20:49:23 2001 From: rfbrenar@cs.uchicago.edu (robert frank brenart) Date: Fri, 17 Aug 2001 14:49:23 -0500 (CDT) Subject: [Tutor] Reading from a file In-Reply-To: <20010817145925.B13306@harmony.cs.rit.edu> Message-ID: OS answer... well, it's a SPSS data file created by someone in Thailand, converted to a CSV file by stattransfer under Windows 2000 On Fri, 17 Aug 2001, dman wrote: > On Fri, Aug 17, 2001 at 01:55:41PM -0500, robert frank brenart wrote: > | And we have a winner... thanks a bunch. > > You're welcome. I'm still interested in the answer to the OS > question. At first I was expecting \012 to be CR since I first > assumed it was a 'doze file being read on a *nix system, but checked > the ascii table before I posted. > > -D > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From tim.one@home.com Sat Aug 18 05:48:01 2001 From: tim.one@home.com (Tim Peters) Date: Sat, 18 Aug 2001 00:48:01 -0400 Subject: [Tutor] Dumb Luck with the Partitioning Problem In-Reply-To: <20010817071411.NOCA14739.femail46.sdc1.sfba.home.com@localhost> Message-ID: This is a multi-part message in MIME format. ------=_NextPart_000_0008_01C1277F.6EAF5A00 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: 7bit Hmm. Dumb brute force is still winning? OK, so let's go to the other extreme . The attached implements the Karmarkar-Karp heuristic for this problem. It's very, very, very clever, and runs in an eyeblink. I won't try to explain it in full. Suffice it to say that at each step it decides to put the two largest numbers remaining into different sets -- but doesn't decide *which* sets until the very end! To a first approximation, this isn't entirely unlike the effect Steven got by splitting the numbers according to even-or-odd indices (which split the two largest numbers from the start). For N=50, it prints Set 1 sum 119.51791973220098 Set 2 sum 119.51788087131982 difference 3.8860881161895122e-005 and the "distance to target" measure is half of the last number printed, a bit less than 2e-5. A truly remarkable property of KK is that it does better the *larger* the input set. Run it with N=3000, for example, and after a few seconds it prints Set 1 sum 54785.845251704624 Set 2 sum 54785.845251704624 difference 0.0 An interesting online paper about this approach is korf-ckk.pdf (or .ps), at http://www.cs.pdx.edu/~bart/cs510cs/papers/ Note that dumb brute force *still* did better than KK, although it took a lot more computer time to find something better. On the other hand, dumb brute force was very easy to program, easy to dream up, and easy to get right the first time. I made several errors while implementing KK, its inventors must have spent days dreaming it up, and it took at least an hour of my time to get the bugs out. Is two minutes of computer time worth an hour of mine? Sure -- but only when it's just for fun <0.9 wink>. ------=_NextPart_000_0008_01C1277F.6EAF5A00 Content-Type: text/plain; name="Karp.py" Content-Transfer-Encoding: 7bit Content-Disposition: attachment; filename="Karp.py" from __future__ import nested_scopes import bisect class _Num: def __init__(self, value, index): self.value = value self.i = index def __lt__(self, other): return self.value < other.value # This implements the Karmarkar-Karp heuristic for partitioning a set # in two, i.e. into two disjoint subsets s.t. their sums are # approximately equal. It produces only one result, in O(N*log N) # time. A remarkable property is that it loves large sets: in # general, the more numbers you feed it, the better it does. class Partition: def __init__(self, nums): self.nums = nums sorted = [_Num(nums[i], i) for i in range(len(nums))] sorted.sort() self.sorted = sorted def run(self): sorted = self.sorted[:] N = len(sorted) connections = [[] for i in range(N)] while len(sorted) > 1: bigger = sorted.pop() smaller = sorted.pop() # Force these into different sets, by "drawing a # line" connecting them. i, j = bigger.i, smaller.i connections[i].append(j) connections[j].append(i) diff = bigger.value - smaller.value assert diff >= 0 bisect.insort(sorted, _Num(diff, i)) # Now sorted contains only 1 element x, and x.value is # the difference between the subsets' sums. # Theorem: The connections matrix represents a spanning tree # on the set of index nodes, and any tree can be 2-colored. # 2-color this one (with "colors" 0 and 1). index2color = [None] * N def color(i, c): if index2color[i] is not None: assert index2color[i] == c return index2color[i] = c for j in connections[i]: color(j, 1-c) color(0, 0) # Partition the indices by their colors. subsets = [[], []] for i in range(N): subsets[index2color[i]].append(i) return subsets N = 50 import math x = [math.sqrt(i) for i in range(1, N+1)] p = Partition(x) s, t = p.run() sum1 = 0L sum2 = 0L for i in s: sum1 += x[i] for i in t: sum2 += x[i] print "Set 1 sum", repr(sum1) print "Set 2 sum", repr(sum2) print "difference", repr(abs(sum1 - sum2)) ------=_NextPart_000_0008_01C1277F.6EAF5A00-- From r.b.rigilink@chello.nl Sat Aug 18 08:49:55 2001 From: r.b.rigilink@chello.nl (Roeland Rengelink) Date: Sat, 18 Aug 2001 09:49:55 +0200 Subject: [Tutor] My shot at the partitioning problem References: Message-ID: <3B7E1E23.B12E6D51@chello.nl> Hi Danny, I'm also curious about GA (Genetic Algorithm) approaches to searching. However, thinking this problem over a bit, I concluded that this problem is unsuitable for GA algorithms. Here's my thinking on the suitability. GA relies on three mechanisms to produce potentially better offspring from the most suitable parents: inheritance, crossover and mutation, with inheritance and crossover usually combined in one function. I think the basic assumption in GA algorithms is that the phenotypic distance to an optimal solution is proportional to the genotypic distance to an optimal solution. That is, if a particular string of DNA encodes a close to optimal solution, then that string will be very similar to the string of DNA encoding _the_ optimal solution. Looking at mutations we see that in this case that assumption doesn't hold. We have: Goal: Divide [sqrt(i) for i in range(1,51)] in two sets, S1 and S2, such that the sum of the values in each set are as close to each other as possible. Phenotypic Distance: distance = abs(sum(S1)-sum(S2)) A one-point mutation moves one element from S1 to S2, or vv. Suppose that the current distance is <0.5, then any one-point mutation will increase the distance. Best case is moving the smallest element from the set with the largest sum. But that element is always greater than 1, hence, the distance will increase. So, the minimum distance change for a one point mutation is 1. Similarly the minimum distance change for a two-point mutation is sqrt(50)-srtq(49) = 0.071 (exchange of two elements). The minimum distance change for a three element mutation is 0.0014 (sqrt(50)-sqrt(12)-sqrt(13)) (There are three-point mutations that don't change the distance). Finding the minimum distance change for a four-point mutation is left as an exercise for the reader. The conclusion is that the closer you are to an optimal solution, the more mutations you need to improve that solution -> Not suitable for GA. I find it difficult to see exactly what inheritance does here. Given two parents with small distances, then there are two possibilities: 1. Parents are very similar -> child is very similar to both parents which doesn't help here. 2. Parents are very differents -> child may be very different from both parents, which previous analysis showed may be exactly what you want. But I can't show that given the fitness of both parents this child will be fit. I think that this may in fact be a requirement of the reproduction function in GA. One note on your code. You have: def stringCrossover(s1, s2, probability=0.5): """A simple crossover operator on strings s1 and s2.""" for i in range(len(s1)): if random.random() < probability: return s1[:i] + s2[i:] return s1 ie. 50 % s1[:0]+s2[0:] 25 % s1[:1]+s2[1:] 12.5% s1[:2]+s2[2:] etc. Is that really what you want? I thought more something like: def stringCrossover(s1, s2): """A simple crossover operator on strings s1 and s2.""" i = random.randrange(len(s1)) return s1[:i]+s2[i:] Any thoughts? Roeland Danny Yoo wrote: > > Ok, here's my contribution to the partitioning problem. I can only get it > to 2 decimal places too, so I'm sure that someone can do much better! > > Sample output: > > ### > Our best choice (00001010010001100011101001110110000101010110110101) > has a value of 119.516797799 > Difference between it and our target: 0.00110250314594 > Ok, done computing. Our best choice, > sqrt(5) + sqrt(7) + sqrt(10) + sqrt(14) + sqrt(15) + sqrt(19) + sqrt(20) + > sqrt(21) + sqrt(23) + sqrt(26) + sqrt(27) + sqrt(28) + sqrt(30) + > sqrt(31) + sqrt(36) + sqrt(38) + sqrt(40) + sqrt(42) + sqrt(43) + > sqrt(45) + sqrt(46) + sqrt(48) + > sqrt(50) > is THIS close to our target: 0.00110250314594 > ### > > Actually, the program is a bit long. I'll attach it to this message > instead, and send it off to Useless Python. I'd have to say that this > approach was much more Useless than I had anticipated... *grin*. > > ------------------------------------------------------------------------ > Name: genetic.py > genetic.py Type: Plain Text (TEXT/PLAIN) > Encoding: BASE64 > > Name: partition50.py > partition50.py Type: Plain Text (TEXT/PLAIN) > Encoding: BASE64 -- r.b.rigilink@chello.nl "Half of what I say is nonsense. Unfortunately I don't know which half" From koen@behindthesofa.dhs.org Sat Aug 18 10:17:18 2001 From: koen@behindthesofa.dhs.org (Koen Bossers) Date: Sat, 18 Aug 2001 11:17:18 +0200 Subject: [Tutor] Tkinter image with "hyperregions" Message-ID: <3B7E329E.9060208@behindthesofa.dhs.org> Hi everybody, I'm trying some stuff with Tkinter. Right now, I'm writing a class MakeMap that displays an image. The user can select different regions within that image and assign functions to them. Makemap then writes a class that contains the image with the "hyperregions" and its corresponding function calls as event bindings (OK this might be a bit unclear, imagine a picture of a calculator. the user selects a square around the "1" button and assigns a function to it). If I use Canvas Rectangles for example for the region selection, I can use canvas.find_overlapping() to determine which rectangle is clicked. Unfortunately, this only works if the rectangle is visible, for example a rectangle with transparent fill and outline will NOT work with this method. To avoid this, I wrote a funtion that determines if the mouse click is in a "hyperregion", knowing the positions and sizes of the rectangles that make up the "hyperregions". This is easy for rectangles and probably also for ellipses, but I also like to add functionality for polygons. I have no idea how to determine all the pixels that make up the polygon, so I don't know whether a user clicked on the polygon or not. So the question is, is there another method of determining if a user clicked a canvas.rectangle than canvas.find_overlapping(), or is there a way to determine all the pixels that a polygon contains, or is there a way to use a COMPLETELY transparent canvas.rectangle so that canvas.find_overlapping() works? Sorry for the long ang probably unclear questions. Hope somebody can help.... Cheers, Koen Bossers From dyoo@hkn.eecs.berkeley.edu Sat Aug 18 10:18:40 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 18 Aug 2001 02:18:40 -0700 (PDT) Subject: [Tutor] My shot at the partitioning problem In-Reply-To: <3B7E1E23.B12E6D51@chello.nl> Message-ID: On Sat, 18 Aug 2001, Roeland Rengelink wrote: > One note on your code. You have: > > def stringCrossover(s1, s2, probability=0.5): > """A simple crossover operator on strings s1 and s2.""" > for i in range(len(s1)): > if random.random() < probability: > return s1[:i] + s2[i:] > return s1 > > ie. > > 50 % s1[:0]+s2[0:] > 25 % s1[:1]+s2[1:] > 12.5% s1[:2]+s2[2:] > etc. > > Is that really what you want? Oh no! You're right: As it's written, the crossover function is biased towards crossing string over near the beginning of the string! That's definitely not what I had in mind: it would be better if it could cross over anywhere with equal probability. > I thought more something like: > > def stringCrossover(s1, s2): > """A simple crossover operator on strings s1 and s2.""" > i = random.randrange(len(s1)) > return s1[:i]+s2[i:] Yes, your version of stringCrossover makes much more sense. I believe I was writing the string mutating function at the same time as stringCrossover(), and had gotten those two functions confused in my head. I'll make this correction and see if it improves the search, although from your analysis, this still sounds like a dead end. I must admit that I've just started reading an introductory text on genetic algorithms; I have a lot of reading to do. Thanks again! From dyoo@hkn.eecs.berkeley.edu Sat Aug 18 10:29:07 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 18 Aug 2001 02:29:07 -0700 (PDT) Subject: [Tutor] Reading from a file In-Reply-To: Message-ID: On Fri, 17 Aug 2001, Israel Evans wrote: > this may not be the best way to do it but it seems to work... I'm rather new > to this to. > > >>> line = """"CVR",1,2""" > >>> info = line.split(',') > >>> info > ['"CVR"', '1', '2'] > > >>> info.remove(info[len(info)-1]) > >>> info > ['"CVR"', '1'] > > I'm just removing the last item in the list. The /012 is probably > some sort of line ending like \n? I'm guessing. Here's a sample interpreter session, annotated for your amusement: ### >>> ord('\n') 10 # Hmm... I expected to see 12. >>> ord('\r') # Maybe it's the carriage return character 13 # Nope! # ... oh, silly me. # [thunk on the head] >>> 012 # I forgot \012 was in octal... 10 # Ah, that's better. ### So yes, '\012' is the newline '\n' character. In older versions of Python, unusual ASCII characters would be repr()esented in octal notation. Here's the paragraph from the "What's New in Python 2.1" document, http://www.amk.ca/python/2.1/ that talks about this: """Applying repr() to strings previously used octal escapes for non-printable characters; for example, a newline was '\012'. This was a vestigial trace of Python's C ancestry, but today octal is of very little practical use. Ka-Ping Yee suggested using hex escapes instead of octal ones, and using the \n, \t, \r escapes for the appropriate characters, and implemented this new formatting.""" From allan.crooks@btinternet.com Sat Aug 18 13:09:36 2001 From: allan.crooks@btinternet.com (Allan Crooks) Date: Sat, 18 Aug 2001 13:09:36 +0100 Subject: [Tutor] Yahtzee-like Program In-Reply-To: <3B7C69E8.73503D92@mindless.com> Message-ID: <3B7E6910.31243.A0B19F@localhost> > I've written a small program that is a lot like Yahtzee, without the > pretty graphics. It's more of a command line style game. It works > and obeys all the standard rules. > > However, I know that my 250+ line code is horribly ugly. But, it is > the only way I know how to write it. I would like it if someone would > look at it and give me some pointers to help clean my code, but I am > hesitant to post all of it on the Tutor list. > > If you want to look at it, it is available at > Well, there quite a few ways it could be improved (by which, I mean "shortened"). :) You could put in the following method: def score_single_helper (self, val, cat, letters): self.score_single(val=val, cat=cat) for letter in letters: self.scored.append (letter) Then the "if option in Aa, elif option in Bb" and so on would be a lot smaller. :) Also, I'd also encourage you to use the % operator for strings (so put %s in the string itself). That way, you can get out of putting all the messy "...+str(x)+..." code. You might want to split the self.score values into two dictionaries (maybe more), one containing the ones - sixes, and the other one for the rest. Then the following code: sum=(self.score['ones']+self.score['twos']... can become: def score_top_bonus(self): import operators sum = reduce (operators.add, self.score.values()) Another point is that if you have an if statement, you don't need to put "else: pass", you can just omit that. It's not always necessary to have an else statement. The following line: option=raw_input('Please choose [A-M] ') could be changed to: option = raw_input('Please choose [A-M] ').lower() That will convert the string to lower case. That way, you don't have to worry about adding 'M' and 'm' to 'scores'. Note that I haven't actually run the program, I'm just saying how I'd make it smaller. :) Allan. From lha2@columbia.edu Sat Aug 18 14:54:55 2001 From: lha2@columbia.edu (Lloyd Hugh Allen) Date: Sat, 18 Aug 2001 09:54:55 -0400 Subject: [Tutor] Reading from a file References: Message-ID: <3B7E73AF.20701934@mail.verizon.net> On Fri, 17 Aug 2001 13:10:24 -0500 (CDT), robert frank brenart wrote: I'm reading in from a file line by line and splitting up the information based on commas... however, the last item in every line has an /012 attached to it... i.e. "CVR",1,2 comes out as ['"CVR"', '7', '3\012'] Just wondering how I can get rid of that \012. -Rob ============ There is a string method "replace" which will do the trick nicely (make sure you run it before you split the string, as it's a string method, not a list method): >>> mystring = "Hi there I'm a string" >>> mystring.replace('e', '') "Hi thr I'm a string" only instead of using the arguments ('e', ''), you'll use ("\012",''). Windows translates \012 to \n, suggesting that the .strip method may also be of service (and may be more generalizable if you tend get other weird "junk" characters). I take it that you do not want to retain the original line splits...if you do, you may want to split using the separator "\012" initially. -LHA From alan.gauld@bt.com Sat Aug 18 22:07:19 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sat, 18 Aug 2001 22:07:19 +0100 Subject: [Tutor] Using dictionaries to call functione Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BEAC@mbtlipnt02.btlabs.bt.co.uk> > For example, I would like to pass a list of words and parameters to a > function, and for each word in the list, call word(parameter1, > parameter2, ...) referenced in a dictionary which somehow calls the > associated function (called a "dispatch table", I think). You mean something like this: val = (word, p1,p2,p3) # the data dict[word](p1,p2,p3) # the call via a dict? If so you set up the dict with the key being a string equal to the functions name and the va;lue being a reference to the function object Something like: # define 3 functions def foo(a): return a def bar(a,b): return a+b def baz(c): return `c` # create dictionary keyed by function name dict = {'foo':foo, 'bar':bar, 'baz':baz} Now you have to know what params are needed for each function. Things like apply and **args etc might alleviate that pain. Does that help? Alan g From alan.gauld@bt.com Sat Aug 18 21:59:04 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sat, 18 Aug 2001 21:59:04 +0100 Subject: [Tutor] anecdote in the workplace about try,except clause Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BEAB@mbtlipnt02.btlabs.bt.co.uk> Since we have established that data doesn't go out of scope... > > > for line in file: > > > try: > > > data, garbage = string.split(line, ':') > > > except ValueError: data = line should fix it, no? The comment about data going out of scope confused me but now that thats been cleared up the simple fix above should work (my trivial tests so far suggest it does...) Alan g From ylee12@uiuc.edu Sun Aug 19 01:35:03 2001 From: ylee12@uiuc.edu (Young-Jin Lee) Date: Sat, 18 Aug 2001 17:35:03 -0700 Subject: [Tutor] [Q] Python and path? Message-ID: <004101c12846$c9a378c0$95757e82@visit2> This is a multi-part message in MIME format. ------=_NextPart_000_003E_01C1280C.1D33D7E0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi, I have a question on Python and path. How can I tell Python to search a python source file in a specify = directory? I created a python test code in my working directory and I lauchched the Python interpreter from the desktop shortcut. I need to be able to = specify the path (similar to Java's classpath), but I don't know how. Thanks in advance. YL ------=_NextPart_000_003E_01C1280C.1D33D7E0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
    Hi, I have a question on Python and = path.
    How=20 can I tell Python to search a python source file in a specify = directory?
    I=20 created a python test code in my working directory and I lauchched = the
    Python=20 interpreter from the desktop shortcut. I need to be able to = specify
    the path=20 (similar to Java's classpath), but I don't know how.
    Thanks in=20 advance.

    YL

    ------=_NextPart_000_003E_01C1280C.1D33D7E0-- From dyoo@hkn.eecs.berkeley.edu Sun Aug 19 00:42:39 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 18 Aug 2001 16:42:39 -0700 (PDT) Subject: [Tutor] [Q] Python and path? In-Reply-To: <004101c12846$c9a378c0$95757e82@visit2> Message-ID: On Sat, 18 Aug 2001, Young-Jin Lee wrote: > Hi, I have a question on Python and path. How can I tell Python to > search a python source file in a specify directory? I created a python > test code in my working directory and I lauchched the Python > interpreter from the desktop shortcut. I need to be able to specify > the path (similar to Java's classpath), but I don't know how. Python's equivalent to Java's 'CLASSPATH' variable is the 'PYTHONPATH' variable. On Win2k or WinNT, you should be able to find environmental variables through the Control Panel on windows system. On a Win98 system, you can add an entry in your autoexec.bat that looks sorta like this: ### set PYTHONPATH=C:\personal\python ### Good luck to you. From dyoo@hkn.eecs.berkeley.edu Sun Aug 19 08:14:15 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 19 Aug 2001 00:14:15 -0700 (PDT) Subject: [Tutor] Re: Algebraic symbol manipulation program idea In-Reply-To: Message-ID: On Fri, 10 Aug 2001, Christopher Smith wrote: > When given 2*3+2^2/3 Pythonica returns: > > in FullForm: Divide[Plus[Times[2,3],Power[2,2]],3] > evaluates to: 3.33333333333 > > but it should probably be something like: > > Plus[Times[2,3],Divide[Power[2,2],3]] > > and evaluate to 7.33333333333 [I'm not quite sure if my message is appropriate on tutor, but perhaps someone is interested in recursive descent parsing. Recursive descent parsing is a technique that's used to try converting arithmetic expressions into a form that's supposedly easy to work with. *grin*] Pythonica seems pretty interesting! I'm taking a closer look at this now. Does anyone have a formal context free grammar for Pythonica or Mathematica? I'm working on a Pythonica recursive descent parser now to fix this bug. Here's the link to what I have so far: http://hkn.eecs.berkeley.edu/~dyoo/python/pythonica/ As a warning, this is ROUGH code; it doesn't even connect to Pythonica yet. For now, PythonicaParser.py can only build the parse tree for simple arithmetic expressions. Here's a sample run: ### dyoo@einfall:~/pythonica$ python PythonicaParser.py >>> 3 * 4 + 5 * (foo + bar) ['Expression', ['Term', ['Factor', 'NUMBER', '3'], ['Term1', '*', ['Factor', 'NUMBER', '4'], None]], ['Expression1', '+', ['Term', ['Factor', 'NUMBER', '5'], ['Term1', '*', ['Factor', 'GROUP', ['Expression', ['Term', ['Factor', 'IDENTIFIER', 'foo'], None], ['Expression1', '+', ['Term', ['Factor', 'IDENTIFIER', 'bar'], None], None]]], None]], None]] None ### I'll see if I can coax it to handle more interesting things like exponentiation tonight. *grin* From shalehperry@home.com Sun Aug 19 09:42:55 2001 From: shalehperry@home.com (Sean 'Shaleh' Perry) Date: Sun, 19 Aug 2001 01:42:55 -0700 (PDT) Subject: [Tutor] anecdote in the workplace about try,except clause In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66BEAB@mbtlipnt02.btlabs.bt.co.uk> Message-ID: On 18-Aug-2001 alan.gauld@bt.com wrote: > Since we have established that data doesn't go out of scope... > >> > > for line in file: >> > > try: >> > > data, garbage = string.split(line, ':') >> > > except ValueError: > data = line > > should fix it, no? > > The comment about data going out of scope confused me but > now that thats been cleared up the simple fix above should > work (my trivial tests so far suggest it does...) > the more proper approach in my opinion would be to test if there is a colon to be begin with. Which is what I suggested he do. The actual application was a summer which read a file and sum the statistics on each line. The first N lines were header and other info. From r.b.rigilink@chello.nl Sun Aug 19 11:01:06 2001 From: r.b.rigilink@chello.nl (Roeland Rengelink) Date: Sun, 19 Aug 2001 12:01:06 +0200 Subject: [Tutor] Re: Algebraic symbol manipulation program idea References: Message-ID: <3B7F8E62.2D06193A@chello.nl> Danny Yoo wrote: > > Pythonica seems pretty interesting! I'm taking a closer look at this now. > Does anyone have a formal context free grammar for Pythonica or > Mathematica? I'm working on a Pythonica recursive descent parser now to > fix this bug. Here's the link to what I have so far: > > http://hkn.eecs.berkeley.edu/~dyoo/python/pythonica/ > [snip] Hi Danny, Somewhat coincidentally I'm working at something similar. My own Symbolic package. I wrote a tokenizer/parser that turns an expression given in a string, into an expression object. Basically something like: '1+2' -> Add(Number(1), Number(2)) 'cos(3*x)' -> Cos(Multiply(Number(3), Variable('x')) The class hierarchy for this is something like: Expression # abstract +--BinaryFunction | +--Add | +--Subtract | +--Multiply | +--Divide | +--Power | +--UnaryFunction | +--Minus | +--Sin | +--Cos | +--Log | +--... | +--Atom +--Number +--Variable Basically, an Expression is a tree of Expression objects where BinaryFunctions have two children and UnaryFunctions have one child. The leaves of the tree are Atoms As I said. the tokenizer/parser works. But, since it is not based on a formal grammar, it is rather uninteresting (i.e. not reusable) The interesting thing is of course the symbolic manipulation of the expression themselves. For example differentiation, which can be handled by recursive decent: class Add(BinaryFunction): def differentiate(self, var): return Add(self.lhs.differentiate(var), self.rhs.differentiate(var)) class Variable(Atom): def differentiate(self, var): if self is var: return ONE # Number(1) else: return ZERO # Number(0) I've got that implemented. Another interesting one is integration, which is of course in many cases not solvable at all, and for the cases that are solvable, you have to rely on trying a number of different heuristics. This has gotten me stumped, but I expected that. Another problem, which is much harder than I expected, is rewriting expression. For example: Add(Add(Number(1), Variable(x)), Number(2)) -> Add(Add(Number(1), Number(2)), Variable(x)) -> Add(Number(3), Variable(x)) which you have to do in order to meaningfully compare expressions. For example, it's easy to see that: Subtract(Variable(x), Variable(x)) -> Number(0) using something like: class Subtract(BinaryFunction): def rewrite(self): if self.lhs == self.rhs: return ZERO ...other rewrite rules skipped... However, this one in itself doesn't deal with (easy notation): (1+x)-(x+1) Unless I make the comparison function really smart. One rewriting heuristic may be: (1+x)-(x+1) --> (1+x)-(1+x) --> 0 , but what rule tells us that we should change the order of terms in the second term? Well, I tried putting some rewriting heuristics in the Expression classes, and basically ran into more and more special cases that needed extra code. In other words, I'm stuck. As far as I can tell expression rewriting and integration can only really be handled by looking at the Expression tree as a whole. Something I would have liked to avoid. Still, I like this problem a lot. One reason is that I am quite happy with some of the solutions I did find. I've therefore considered cleaning up the code that I do have (including documentation) and submitting it to Useless Python. However, I've now decided to use this problem as the basis for a tutorial on OO design, illustrating incremental development of code, refactoring techniques and unittest practices. No idea where it will lead yet. But I'm having fun writing that. In the mean time, anybody that's interested should drop me a line, and I'll send them the code I have. Cheers, Roeland -- r.b.rigilink@chello.nl "Half of what I say is nonsense. Unfortunately I don't know which half" From alan.gauld@bt.com Sun Aug 19 17:07:50 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun, 19 Aug 2001 17:07:50 +0100 Subject: [Tutor] anecdote in the workplace about try,except clause Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BEB0@mbtlipnt02.btlabs.bt.co.uk> > >> > > for line in file: > >> > > try: > >> > > data, garbage = string.split(line, ':') > >> > > except ValueError: > > data = line > > the more proper approach in my opinion would be to test if > there is a colon to begin with. The snag with that is that you potentially test every character in the string twice: once to see if a colon exists and again to split the line. The approach above ensures that you only read it once. Potentially doubling performance if there is little post split processing! Alan G From kev@sat.net Sun Aug 19 22:58:12 2001 From: kev@sat.net (Kevin McCormick) Date: Sun, 19 Aug 2001 16:58:12 -0500 Subject: [Tutor] Using dictionaries to call functions (Thanks) Message-ID: <3B803674.C2F48836@sat.net> The explanations given were very helpful. I have been trying to learn some GUI stuff with Tkinter and the Grayson book. He gives lots of great example programs, but I'm not getting a good idea of how to use classes and function calls from menu items. He had a "dispatch table" in one of the examples and now it is clear. Anyone who wants to explain how the Grayson example "AppShell.py" (page 155) is used would be appreciated. Later in the book, he uses it with classes that are subclasses of AppShell, like Draw.py on page 238. Here, the Draw class is "class Draw(AppShell.AppShell):" However, how does one build from the top down, i.e. instead of the widget calling the AppShell, how does the AppShell call the widget? From alan.gauld@bt.com Sun Aug 19 18:00:06 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun, 19 Aug 2001 18:00:06 +0100 Subject: [Tutor] Off topic musings Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BEB2@mbtlipnt02.btlabs.bt.co.uk> Some time ago I posted the following musings to my work colleagues and a few of us chased it around for a while. I came across it recently and thought the ideas might be of some interest to the members of these lists. If anyone knows of resources please let me know... ----------- Included text --------------- I read a collection of papers on Software Engineering recently published by the IEEE and edited by Professor Richard Thayer (and his friend). One recurring theme in these "State of the Practice" papers was the lack of a fundamental theoretical basis for computing. i.e. there's nothing comparable to the laws of physics in software engineering. I started thinking and doodling about what the fundamentals are and came up with several notions (ideas would imply something far too well formed!) These are based around the concept that software manipulates data or more correctly "information"(no surprises there! :). However most information theory (Shannon et al) relates to bits. Far too low level to be useful. That started me thinking about levels of information and I came up with 3 layers of information - rather like an OSI comms model: 1/ Physical - bits/bytes, defined by the machine architecture operations are CPU specific, include bitwise OR/AND/NOT and binary arithmetic... 2/ Implementation/Environment - data types defined by the programming environment - object in Smallktalk; int, float, char in C etc... Operations include built in operators for arithmetic, boolean logic and I/O. [Question: Where do collections: arrays, lists etc fit into the layer proposal?] 3/ Application - User defined data types - records, files, RDBMS Tables etc Operations are user defined functions/procedures etc. Other candidate layers include "Standard libraries" etc, but I rejected these as a subset of either Implementation or Application layers. To be useful any fundamental basis of software would have to express concepts which applied with equal validity across all layers. - ie not be dependant on data format, or semantics but simply relate to *relative* information content. Operations would need to be expressable in terms of data transforms across and within layers. I could go on (onto the nature of operations!) but that's probably enough for now. Now the big question is: Since I am sure this isn't original, who has done this stuff before? - Where can I get papers or books on fundamental information representation/transformation theory? I assume there must be something? somewhere? [ Note: I am not talking about Knowledge Engineering which has more to do with how information is stored and processed than what information is, its empirical qualities etc... ] Alan Gauld BT computing partners Tel : 0141 220 8795 Fax : 0141 248 1284 From dyoo@hkn.eecs.berkeley.edu Mon Aug 20 02:50:42 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 19 Aug 2001 18:50:42 -0700 (PDT) Subject: [Tutor] Off topic musings In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66BEB2@mbtlipnt02.btlabs.bt.co.uk> Message-ID: On Sun, 19 Aug 2001 alan.gauld@bt.com wrote: > One recurring theme in these "State of the Practice" papers > was the lack of a fundamental theoretical basis for computing. > i.e. there's nothing comparable to the laws of physics in > software engineering. [some text cut] > Since I am sure this isn't original, who has done this stuff > before? - Where can I get papers or books on fundamental > information representation/transformation theory? I assume > there must be something? somewhere? David Gries has written a book called "The Science of Programming" which states a framework for writing mathematicaly correct programs. I bought it after seeing Jon Bentley's recommendation in "Programming Pearls". As is typical with me, I haven't really gotten past Chapter One yet. *grin* Still, from what I can glean, Gries uses the power of logic and assertions to show how people can be confident in a program's correctness. There's also a chapter on "inverting" programs which looks like a lot of fun. From israel@lith.com Mon Aug 20 05:53:17 2001 From: israel@lith.com (Israel Evans) Date: Sun, 19 Aug 2001 21:53:17 -0700 Subject: [Tutor] [opinions?] Web development... (kind of long) Message-ID: Hello everyone... I'm in a bit of a quandry. I have a number of websites that I'm working on, mostly personal non professional jobs, but a few of them need to be of that caliber. I am very interested in using Python to automate a lot of the creation of individual pages and taking care of the tedious task of updating a frequently updated site. I've looked at a number of options, but none of them have filled me with glee as of yet. I'm calling out to this wonderful list to see if any of you with web development experience have any resounding opinions on the web publishing options available to us pythonistas(or fledgling pythonistas as the case may be). I've looked at Zope but it seems to be a very greedy paradigm. Everything must be fed to the great Zope management interface, registered, methodized and otherwise recreated. It feels as if I'm no longer following the standards of the w3c and creating html, xhtml, xml and so on. I was hoping Webware would be a more relaxed lightweight alternative, but I was having trouble getting everything working. This may have to wait until I upgrade my pc later this year. Python Server Pages sounds great, but it's a Java/Jython thing and I just seem to have this prejudice against using java when I have Python. I know it's not the same thing. I know I'm actually writing in Python and the Java part only comes in as the final form of the code in much the same way that C Python ends up being C somewhere down the line. My goals are as follows; I'd like to create a number of templates for the look and feel for all pages in a site. I'd like to create a number of ways the site would be updated automatically whenever new content is added to either a database or the directories of which the site is made of. It would be great if I could do this on the client, but the Server Side is nice as well. I'd like the content to be dynamically loaded in as it is requested by the user. I come from a land of strict XHTML couple with CSS and Javascript. I'm only now getting into the crazy world of Server Side web applications, persistent data, and python programming. I'd like to create documents that adhere to the standards of XHTML, XML and so on and still have something like server side includes to carry out the programming parts of things. I'd also like to at least have those documents remain inviolated by the code. The Code should be able to grab what files it needs, do the things it is supposed to do and publish it as standards compliant documents. It just creeps me out to have things mingle too much. Anyway.. Sorry about the rambling. I know there are many folks out there with much more experience than I and I hope to hear from these kind and knowing souls to help me resolve my quandry. Thanks a bunch, ~Israel~ From ak@silmarill.org Mon Aug 20 06:14:03 2001 From: ak@silmarill.org (Andrei Kulakov) Date: Mon, 20 Aug 2001 01:14:03 -0400 Subject: [Tutor] [opinions?] Web development... (kind of long) In-Reply-To: References: Message-ID: <20010820011402.A11721@sill.silmarill.org> On Sun, Aug 19, 2001 at 09:53:17PM -0700, Israel Evans wrote: > Hello everyone... > > > I'm in a bit of a quandry. I have a number of websites that I'm working on, > mostly personal non professional jobs, but a few of them need to be of that > caliber. I am very interested in using Python to automate a lot of the > creation of individual pages and taking care of the tedious task of updating > a frequently updated site. I've looked at a number of options, but none of > them have filled me with glee as of yet. I'm calling out to this wonderful > list to see if any of you with web development experience have any > resounding opinions on the web publishing options available to us > pythonistas(or fledgling pythonistas as the case may be). > > I've looked at Zope but it seems to be a very greedy paradigm. Everything > must be fed to the great Zope management interface, registered, methodized > and otherwise recreated. It feels as if I'm no longer following the > standards of the w3c and creating html, xhtml, xml and so on. > > I was hoping Webware would be a more relaxed lightweight alternative, but I > was having trouble getting everything working. This may have to wait until > I upgrade my pc later this year. > > Python Server Pages sounds great, but it's a Java/Jython thing and I just > seem to have this prejudice against using java when I have Python. I know > it's not the same thing. I know I'm actually writing in Python and the Java > part only comes in as the final form of the code in much the same way that C > Python ends up being C somewhere down the line. > > My goals are as follows; > I'd like to create a number of templates for the look and feel for all pages > in a site. > I'd like to create a number of ways the site would be updated automatically > whenever new content is added to either a database or the directories of > which the site is made of. > It would be great if I could do this on the client, but the Server Side is > nice as well. > I'd like the content to be dynamically loaded in as it is requested by the > user. > > I come from a land of strict XHTML couple with CSS and Javascript. I'm only > now getting into the crazy world of Server Side web applications, persistent > data, and python programming. I'd like to create documents that adhere to > the standards of XHTML, XML and so on and still have something like server > side includes to carry out the programming parts of things. I'd also like > to at least have those documents remain inviolated by the code. The Code > should be able to grab what files it needs, do the things it is supposed to > do and publish it as standards compliant documents. It just creeps me out > to have things mingle too much. > > Anyway.. Sorry about the rambling. I know there are many folks out there > with much more experience than I and I hope to hear from these kind and > knowing souls to help me resolve my quandry. > > Thanks a bunch, > > ~Israel~ What about PMZ, poor man's zope? I didn't use it myself but it might be good. Then again, you can just write a bunch of cgi scripts.. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From ignacio@openservices.net Mon Aug 20 06:18:14 2001 From: ignacio@openservices.net (Ignacio Vazquez-Abrams) Date: Mon, 20 Aug 2001 01:18:14 -0400 (EDT) Subject: [Tutor] [opinions?] Web development... (kind of long) In-Reply-To: Message-ID: On Sun, 19 Aug 2001, Israel Evans wrote: > Hello everyone... > > > I'm in a bit of a quandry. I have a number of websites that I'm working on, > [ Dont mind me ;) SNIP ] > > Anyway.. Sorry about the rambling. I know there are many folks out there > with much more experience than I and I hope to hear from these kind and > knowing souls to help me resolve my quandry. > > Thanks a bunch, > > ~Israel~ If you want to keep everything fairly low-level Python and still use templates, you have at least two very good options: 1) HTMLgen and a dictionary containing the content of each page, or 2) XSLT on a generated XML document via libxml/libxslt or 4Suite -- Ignacio Vazquez-Abrams From rob@jam.rr.com Mon Aug 20 06:27:38 2001 From: rob@jam.rr.com (Rob Andrews) Date: Mon, 20 Aug 2001 00:27:38 -0500 Subject: [Tutor] [opinions?] Web development... (kind of long) References: Message-ID: <3B809FCA.34822DF6@jam.rr.com> Israel Evans wrote: > > Hello everyone... > > I'm in a bit of a quandry. I have a number of websites that I'm working on, > mostly personal non professional jobs, but a few of them need to be of that > caliber. I am very interested in using Python to automate a lot of the > creation of individual pages and taking care of the tedious task of updating > a frequently updated site. I've looked at a number of options, but none of > them have filled me with glee as of yet. I'm calling out to this wonderful > list to see if any of you with web development experience have any > resounding opinions on the web publishing options available to us > pythonistas(or fledgling pythonistas as the case may be). > > I've looked at Zope but it seems to be a very greedy paradigm. Everything > must be fed to the great Zope management interface, registered, methodized > and otherwise recreated. It feels as if I'm no longer following the > standards of the w3c and creating html, xhtml, xml and so on. > > I was hoping Webware would be a more relaxed lightweight alternative, but I > was having trouble getting everything working. This may have to wait until > I upgrade my pc later this year. > > Python Server Pages sounds great, but it's a Java/Jython thing and I just > seem to have this prejudice against using java when I have Python. I know > it's not the same thing. I know I'm actually writing in Python and the Java > part only comes in as the final form of the code in much the same way that C > Python ends up being C somewhere down the line. > > My goals are as follows; > I'd like to create a number of templates for the look and feel for all pages > in a site. > I'd like to create a number of ways the site would be updated automatically > whenever new content is added to either a database or the directories of > which the site is made of. > It would be great if I could do this on the client, but the Server Side is > nice as well. > I'd like the content to be dynamically loaded in as it is requested by the > user. > > I come from a land of strict XHTML couple with CSS and Javascript. I'm only > now getting into the crazy world of Server Side web applications, persistent > data, and python programming. I'd like to create documents that adhere to > the standards of XHTML, XML and so on and still have something like server > side includes to carry out the programming parts of things. I'd also like > to at least have those documents remain inviolated by the code. The Code > should be able to grab what files it needs, do the things it is supposed to > do and publish it as standards compliant documents. It just creeps me out > to have things mingle too much. > > Anyway.. Sorry about the rambling. I know there are many folks out there > with much more experience than I and I hope to hear from these kind and > knowing souls to help me resolve my quandry. > > Thanks a bunch, > > ~Israel~ > I'm looking at a lot of the same issues as I work toward automating Useless Python. There are a number of solutions, as you've already noticed, and any of them will require deciphering, setup, and maintenance. How large are these sites expected to be? Do you expect/hope to dish out your web pages from databases of content? How frequently do you expect to have to manually change things about the site? Try to anticipate what you will need your websites to do six months from now (at least), even though that is far easier said than done. We had no idea back at the start of the year that Useless Python would see so much activity. It appears now that what this site needs most right now is for the people who contribute content to the site to be able to post and update material without having to wait for me to get around to doing it manually (and to see thier page hit statistics). It would also be great to give people options on how to browse the content, along the lines of search-engine-styel queries maybe. I still haven't decided exactly how to get around all the details of everything without a security nightmare. okay, I'm through babbling for a minute, Rob -- A {} is a terrible thing to waste. Useless Python! http://www.lowerstandard.com/python From dyoo@hkn.eecs.berkeley.edu Mon Aug 20 07:42:24 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 19 Aug 2001 23:42:24 -0700 (PDT) Subject: [Tutor] [opinions?] Web development... (kind of long) [ACS?] In-Reply-To: <3B809FCA.34822DF6@jam.rr.com> Message-ID: On Mon, 20 Aug 2001, Rob Andrews wrote: > I'm looking at a lot of the same issues as I work toward automating > Useless Python. There are a number of solutions, as you've already > noticed, and any of them will require deciphering, setup, and > maintenance. [ some text cut ] > We had no idea back at the start of the year that Useless Python would > see so much activity. It appears now that what this site needs most > right now is for the people who contribute content to the site to be > able to post and update material without having to wait for me to get > around to doing it manually (and to see thier page hit statistics). It > would also be great to give people options on how to browse the content, > along the lines of search-engine-styel queries maybe. I still haven't > decided exactly how to get around all the details of everything without > a security nightmare. Phil Greenspun has an online book about this which I'm enjoying a lot called "Phil and Alex's Guide to Web Publishing": http://www.arsdigita.com/books/panda/ The author is very opinionated, and this gives the book a quirky personality. More importantly, the book contains valuable "war stories" on building these sorts of web sites --- he talks about database management, privacy, and tips on where to tread carefully. Nice pictures too. Perhaps most useful is his ACS toolkit that does a lot of the heavy lifing in collaborative web sites. Although its current incarnation is in Java, some people split off and formed the "OpenACS": http://openacs.org which is in Tcl. Fortunately, there are Python bindings: http://pywx.idyll.org/ I don't know if it's worth the effort to use the software, but it might be useful to glean some of its ideas. Hope this helps! From sheila@thinkspot.net Mon Aug 20 07:52:38 2001 From: sheila@thinkspot.net (Sheila King) Date: Sun, 19 Aug 2001 23:52:38 -0700 Subject: [Tutor] [opinions?] Web development... (kind of long) [ACS?] In-Reply-To: References: <3B809FCA.34822DF6@jam.rr.com> Message-ID: <753C5C92027@kserver.org> On Sun, 19 Aug 2001 23:42:24 -0700 (PDT), Danny Yoo wrote about Re: [Tutor] [opinions?] Web development... (kind of long) [ACS?]: :Perhaps most useful is his ACS toolkit that does a lot of the heavy lifing :in collaborative web sites. Although its current incarnation is in Java, :some people split off and formed the "OpenACS": : : http://openacs.org : :which is in Tcl. Fortunately, there are Python bindings: : : http://pywx.idyll.org/ : : :I don't know if it's worth the effort to use the software, but it might be :useful to glean some of its ideas. Hope this helps! Boy, you really caught my attention with this post (I'm also reading Phil & Alex's Guide to Web Programming right now...I sprung for the printed version. The pictures are VERY nice. My four-year old likes to look at the book with me. ;) ) However, I see that one must run AOLserver (not surprised, actually). I just wish there were something along those lines already available that would run on Apache. The book IS chock full of ideas, though. Actually, for the person who started this thread, if he has the option to choose his own web server, and since there is a Python front end for scripting AOLserver, I'd emphatically recommend reading Phil's book and seriously considering that approach. -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From alan.gauld@bt.com Mon Aug 20 10:44:11 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon, 20 Aug 2001 10:44:11 +0100 Subject: [Tutor] Off topic musings Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BEB5@mbtlipnt02.btlabs.bt.co.uk> > > One recurring theme in these "State of the Practice" papers > > was the lack of a fundamental theoretical basis for computing. > > i.e. there's nothing comparable to the laws of physics in > > software engineering. > > David Gries has written a book called "The Science of > Programming" which states a framework for writing mathematicaly correct > programs. Yes, there are many books and papers on programming correctness but few on the nature of information. Specifically I am intereted in any work on layering of information structures. Looking at how information itself is structured and operated upon. This is different to programming which is only one very narrow subset ofg information processing. Alan g. From xiaowp@chinaren.com Mon Aug 20 14:32:00 2001 From: xiaowp@chinaren.com (Gary) Date: Mon, 20 Aug 2001 21:32:0 +0800 Subject: [Tutor] How to insert Chinese into Tkinter Text widget? Message-ID: <200108201244.VAA09398@mh.bit.edu.cn> SGVsbG8sIGFsbDoNCiAgIEkgaGF2ZSBhIHF1ZXN0aW9uIGFib3V0IFRraW50ZXIuIEluIG15IFB5 dGhvbiBzY3JpcHQsIEkgdXNlIGEgDQpUa2ludGVyIFRleHQgd2lkZ2V0IGFuZCBJIHdhbnQgdG8g aW5zZXJ0IGEgQ2hpbmVzZSBzdHJpbmcgaW50byANCml0LiBJIHdyaXRlIGl0IGxpa2UgdGhpczoN Cgl0ZXh0Lmluc2VydChFTkQsICBDaGluZXNlLXN0cikNCkhlcmUgJ3RleHQnIGlzIGEgVGV4dCB3 aWRnZXQgYW5kIHRoZSAnQ2hpbmVzZS1zdHInIGlzIHRoZSBzdHJpbmcgSQ0Kd2FudCB0byBkaXNw bGF5LiBUbyBteSBzdXByaXNlLCBpdCBkb2Vzbid0IHdvcmsuIFNob3VsZCBJIHVzZSANClVOSUNP REU/IEknbSByZWFsbHkgYSBmcmVzaG1hbiwgcGxlYXNlIGhlbHAgbWUuIFRoYW5rcyBhaGVhZC4N Cg0KDQpCZXN0IFJlZ2FyZHMsDQpHYXJ5DQoNCj09PT09PT09PT09PT09PT09PT09PT09DQp4aWFv d3BAY2hpbmFyZW4uY29tDQoyMDAxLTA4LTIwDQo9PT09PT09PT09PT09PT09PT09PT09PT0NCg== From aschmidt@nv.cc.va.us Mon Aug 20 15:06:46 2001 From: aschmidt@nv.cc.va.us (Schmidt, Allen J.) Date: Mon, 20 Aug 2001 10:06:46 -0400 Subject: [Tutor] Simple text transform with an RE Message-ID: <5CDFEBB60E7FD311B9E30000F6D6090608CB8C4D@novamail2.nv.cc.va.us> Hello all... I need to learn more about regular expressions. A quick answer to this should help... I have a text file of database field names - about 90 of them - one on a line ended with a line break. I need to build something with an RE to read each field from the file, then add parts to each field like "ALTER TABLE ADD ....field_name " at the beginning and other things to the end of the field name. So, I am trying to build a SQL statement from the list of field names. A few have to be changed by hand but not a big deal. Also needed...a link to RE examples. Its one thing to read the syntax and quite another to gleam actual uses from them. Real world examples really help and anything offered would be greatly appreciated. Thanks Allen From ignacio@openservices.net Mon Aug 20 15:42:25 2001 From: ignacio@openservices.net (Ignacio Vazquez-Abrams) Date: Mon, 20 Aug 2001 10:42:25 -0400 (EDT) Subject: [Tutor] Simple text transform with an RE In-Reply-To: <5CDFEBB60E7FD311B9E30000F6D6090608CB8C4D@novamail2.nv.cc.va.us> Message-ID: On Mon, 20 Aug 2001, Schmidt, Allen J. wrote: > Hello all... > > I need to learn more about regular expressions. A quick answer to this > should help... > > I have a text file of database field names - about 90 of them - one on a > line ended with a line break. > I need to build something with an RE to read each field from the file, then > add parts to each field like "ALTER TABLE ADD ....field_name " at the > beginning and other things to the end of the field name. So, I am trying to > build a SQL statement from the list of field names. A few have to be changed > by hand but not a big deal. REs are _beyond_ overkill for this: mapping={ 'badtable':'goodtable' } file=open('myfile.txt','r') lines=file.readlines() file.close() for i in lines: if i[-1:]=='\n': t=i[:-2] else t=i if mapping.has_key(t): t=mapping[t] print 'ALTER TABLE %s ADD changed timestamp' % (t, ) > Also needed...a link to RE examples. Its one thing to read the syntax and > quite another to gleam actual uses from them. Real world examples really > help and anything offered would be greatly appreciated. Hmm... Online I don't know about. I do know the O'Reilly's book,, _Mastering Regular Expressions_ is decent, though. > Thanks > > Allen -- Ignacio Vazquez-Abrams From csmith@blakeschool.org Mon Aug 20 16:14:42 2001 From: csmith@blakeschool.org (Christopher Smith) Date: Mon, 20 Aug 2001 10:14:42 -0500 Subject: [Tutor] Re: Recursive Combinations? Message-ID: Remco Gerlich wrote: | | On 0, Andrew Wilkins wrote: | > Thanks Remco! | > I tried it out - doesn't do _quite_ what I wanted, but with that | > (beautiful) code I can change it to do what I want! It just needs to | > remove reverse orders (eg. (1,2) and (2,1), and remove like elements | in pairs (eg. (1,1)). | | Oh, right. I'm immediately back to my old style of posting - almost, | but not quite :) | | Both are easily remedied by generating only combinations that are in | strictly ascending (or descending) order. | | That means using range(1, combination[0]), but unfortunately that | needs an extra check for length == 1. | | def combinations(length, n): | if length == 0: | return [()] | if length == 1: | return [(i,) for i in range(1,n+1)] | | return [ (i,)+combination for combination in combinations(length-1,n) | for i in range(1, combination[0]) ] | | -- | Remco Gerlich | Hats off to you, Remco. :-) Now that I see the answer it seems simple, but I really had a hard time coming up with a recursive combination generator on my own. /c From dsh8290@rit.edu Mon Aug 20 16:40:35 2001 From: dsh8290@rit.edu (dman) Date: Mon, 20 Aug 2001 11:40:35 -0400 Subject: [Tutor] Simple text transform with an RE In-Reply-To: ; from ignacio@openservices.net on Mon, Aug 20, 2001 at 10:42:25AM -0400 References: <5CDFEBB60E7FD311B9E30000F6D6090608CB8C4D@novamail2.nv.cc.va.us> Message-ID: <20010820114035.B17944@harmony.cs.rit.edu> On Mon, Aug 20, 2001 at 10:42:25AM -0400, Ignacio Vazquez-Abrams wrote: | On Mon, 20 Aug 2001, Schmidt, Allen J. wrote: | | > Hello all... | > | > I need to learn more about regular expressions. A quick answer to this | > should help... | > | > I have a text file of database field names - about 90 of them - one on a | > line ended with a line break. | > I need to build something with an RE to read each field from the file, then | > add parts to each field like "ALTER TABLE ADD ....field_name " at the | > beginning and other things to the end of the field name. So, I am trying to | > build a SQL statement from the list of field names. A few have to be changed | > by hand but not a big deal. If you can show us what the data looks like and how you want it parsed, it can help in building an re for it. Right now I can't suggest anything for parsing the data because I don't know how the data looks. | > Also needed...a link to RE examples. Its one thing to read the syntax and | > quite another to gleam actual uses from them. Real world examples really | > help and anything offered would be greatly appreciated. | | Hmm... | | Online I don't know about. I do know the O'Reilly's book,, _Mastering Regular | Expressions_ is decent, though. I second the recommendation of the O'Reilly book. I have it and it is excellent (though the python specific section is out-of-date). It is what I learned regexes from. -D From dutch@lilrc.org Mon Aug 20 16:56:33 2001 From: dutch@lilrc.org (Dutch) Date: Mon, 20 Aug 2001 11:56:33 -0400 (EDT) Subject: [Tutor] modification Message-ID: going through 'Core python programming' and modified an example to see what would happen. Well, errors happen. I wanted it to ask me for a number then loop that many time and finally report to me what my number was. This is what I typed that made the erros: num = raw_input ('What shall I count to? ') counter = 0 while counter <= num: print 'loop #%d' %(counter) counter = counter + 1 print 'Your number was: %d', %num -Dutch ______________________________________________________________________ David van Popering "It has been established that having a really user friendly interface makes it much too easy for aliens to take over the Enterprise." From koen@behindthesofa.dhs.org Mon Aug 20 16:57:39 2001 From: koen@behindthesofa.dhs.org (Koen Bossers) Date: Mon, 20 Aug 2001 17:57:39 +0200 Subject: [Tutor] modification References: Message-ID: <3B813373.3020808@behindthesofa.dhs.org> Dutch wrote: >going through 'Core python programming' and modified an example to see >what would happen. Well, errors happen. > >I wanted it to ask me for a number then loop that many time and finally >report to me what my number was. This is what I typed that made the >erros: > >num = raw_input ('What shall I count to? ') >counter = 0 >while counter <= num: > print 'loop #%d' %(counter) > counter = counter + 1 >print 'Your number was: %d', %num > 'num' in your example is a string, not an integer! Use this instead: while counter <= int(num): and you're set! Cheers, Koen From ignacio@openservices.net Mon Aug 20 16:58:43 2001 From: ignacio@openservices.net (Ignacio Vazquez-Abrams) Date: Mon, 20 Aug 2001 11:58:43 -0400 (EDT) Subject: [Tutor] modification In-Reply-To: Message-ID: On Mon, 20 Aug 2001, Dutch wrote: > going through 'Core python programming' and modified an example to see > what would happen. Well, errors happen. > > I wanted it to ask me for a number then loop that many time and finally > report to me what my number was. This is what I typed that made the > erros: > > num = raw_input ('What shall I count to? ') > counter = 0 > while counter <= num: > print 'loop #%d' %(counter) > counter = counter + 1 > print 'Your number was: %d', %num > > > -Dutch It seems that you have neglected to tell us: 1) What error you're getting, and 2) What version of Python you're using When I run this under Python 1.5.2 it loops forever because for each number x and any string y, the comparison x<=y is always true. -- Ignacio Vazquez-Abrams From alan.gauld@bt.com Mon Aug 20 17:07:43 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon, 20 Aug 2001 17:07:43 +0100 Subject: [Tutor] Simple text transform with an RE Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BEBD@mbtlipnt02.btlabs.bt.co.uk> > I need to learn more about regular expressions. A quick answer to this > should help... I wrote an article on informIT.com about how to use them. It includes a few simple examples but nothing super complex. (Its basicaly the RE chapter in my book without the case study). There's also a python program available somewhere that allows you to type in REs and test them. I think I have a copy somewhere if you need to I can probably dig it out.... Its called recon.py, heres the header: #!/usr/bin/env python # Regular expression test console # By Brent Burley, 2001, erburley@ix.netcom.com # This software is placed into the public domain It's 15K long. > Also needed...a link to RE examples. Its one thing to read > the syntax and quite another to gleam actual uses from them. > Real world examples really help and anything offered would > be greatly appreciated. The O'Reilly book is the vbest place to go, the definitive guide to REs IMHO. Lots of real world examples including a massive one to test for a canonical RFC822 compliant email address! Alan g. From alan.gauld@bt.com Mon Aug 20 17:12:05 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon, 20 Aug 2001 17:12:05 +0100 Subject: [Tutor] modification Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BEBE@mbtlipnt02.btlabs.bt.co.uk> > num = raw_input ('What shall I count to? ') reads a character string from the user and stores it in num > counter = 0 > while counter <= num: compares the integer valued 'counter' with the string valued 'num' convert num to an integer with: num = int(num) before the while. Or more simply but less efficiently: while counter <= int(num): Should fix it., Alan g From rob@jam.rr.com Mon Aug 20 17:25:42 2001 From: rob@jam.rr.com (Rob Andrews) Date: Mon, 20 Aug 2001 11:25:42 -0500 Subject: [Tutor] modification References: Message-ID: <3B813A06.C72FA99A@jam.rr.com> Dutch wrote: > > going through 'Core python programming' and modified an example to see > what would happen. Well, errors happen. > > I wanted it to ask me for a number then loop that many time and finally > report to me what my number was. This is what I typed that made the > erros: > > num = raw_input ('What shall I count to? ') > counter = 0 > while counter <= num: > print 'loop #%d' %(counter) > counter = counter + 1 > print 'Your number was: %d', %num > > -Dutch I noticed a few things: # use input instead of raw_input num = input('What shall I count to? ') counter=0 while counter <= num: print 'loop #%d' % (counter) counter = counter + 1 # check your % syntax. Notice the differences in the way you used # commas and parentheses on lines 4 and 6 of your script? print 'your number was: %d' % (num) Rob -- A {} is a terrible thing to waste. Useless Python! http://www.lowerstandard.com/python From ylee12@uiuc.edu Mon Aug 20 19:49:29 2001 From: ylee12@uiuc.edu (Young-Jin Lee) Date: Mon, 20 Aug 2001 11:49:29 -0700 Subject: [Tutor] [Q] How to run a Python file from Windows 2000 folder Message-ID: <012a01c129a8$d7c37500$95757e82@visit2> This is a multi-part message in MIME format. ------=_NextPart_000_0127_01C1296E.2B4C0BF0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi, all. I have a problem running a python file from windows 2000 folder. I expected my python file to be executed when I double-clicked it, but I = got "Program Not Found" error dialog box which required me to find where = "Program.exe" is located. I guess it might be a window registry = problem.... I manually assigned Python.exe to *py file in a property menu of the my = python source file, but it didn't work. What should I do to execute a python source file by double-clicking it? Thanks in advance. Young-Jin Lee ------=_NextPart_000_0127_01C1296E.2B4C0BF0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
    Hi, all.
    I have a problem running a python file = from windows=20 2000 folder.
    I expected my python file to be = executed when=20 I double-clicked it, but I got "Program Not Found" error dialog box = which=20 required me to find where = "Program.exe" is=20 located. I guess it might be a window registry problem....
    I manually assigned Python.exe to *py = file in a=20 property menu of the my python source file, but it didn't = work.
     
    What should I do to execute a python = source file by=20 double-clicking it?
     
    Thanks in advance.
     
    Young-Jin = Lee
    ------=_NextPart_000_0127_01C1296E.2B4C0BF0-- From tescoil@irtc.net Mon Aug 20 18:02:14 2001 From: tescoil@irtc.net (Tesla Coil) Date: Mon, 20 Aug 2001 12:02:14 -0500 Subject: [Tutor] Simple text transform with an RE References: <5CDFEBB60E7FD311B9E30000F6D6090608CB8C4D@novamail2.nv.cc.va.us> Message-ID: <3B814296.E8152DCE@irtc.net> On 20 Aug 2001, Allen J. Schmidt wrote: > Also needed...a link to RE examples. Its one thing to > read the syntax and quite another to gleam actual uses > from them. Real world examples really help and anything > offered would be greatly appreciated. Here's one... http://www.naplesfl.net/~tbates/gravity/reexamp.html We could get a "Recent Regexes I Wrote" thread going. Here's one in progress. Trying to match references to RGB values in an HTML document--you might hear more about how I'm trying to use this one shortly: '[=][\s]?["|\']?[#]?[\d|A-F|a-f]{6}["|\']?' From pythonpython@hotmail.com Mon Aug 20 18:14:19 2001 From: pythonpython@hotmail.com (Python Snake) Date: Tue, 21 Aug 2001 02:14:19 +0900 Subject: [Tutor] [Q] How to run a Python file from Windows 2000 folder References: <012a01c129a8$d7c37500$95757e82@visit2> Message-ID: Download and install ActivePython from www.activestate.com. HY ----- Original Message ----- From: Young-Jin Lee To: tutor@python.org Sent: Tuesday, August 21, 2001 3:49 AM Subject: [Tutor] [Q] How to run a Python file from Windows 2000 folder Hi, all. I have a problem running a python file from windows 2000 folder. I expected my python file to be executed when I double-clicked it, but I got "Program Not Found" error dialog box which required me to find where "Program.exe" is located. I guess it might be a window registry problem.... I manually assigned Python.exe to *py file in a property menu of the my python source file, but it didn't work. What should I do to execute a python source file by double-clicking it? Thanks in advance. Young-Jin Lee From israel@lith.com Mon Aug 20 18:36:28 2001 From: israel@lith.com (Israel Evans) Date: Mon, 20 Aug 2001 10:36:28 -0700 Subject: [Tutor] [opinions?] Web development... (kind of long) Message-ID: Yeah, that sounds great! It also sounds like a Useless Python entry. :) http://www.lowerstandard.com/python/index.html ~israel~ -----Original Message----- From: Jesse F. W [mailto:jessefw@loop.com] Sent: Monday, August 20, 2001 10:14 AM To: Israel Evans Subject: Re: [Tutor] [opinions?] Web development... (kind of long) to all good tutorians, Israel Evans wrote: > Hello everyone... > > My goals are as follows; > I'd like to create a number of templates for the look and feel for all > pages in a site. I'd like to create a number of ways the site would > be updated automatically whenever new content is added to either a > database or the directories of which the site is made of. It would be > great if I could do this on the client, but the Server Side is nice as > well. I'd like the content to be dynamically loaded in as it is > requested by the user. I don't know if this would be any use to you, but I have setup a pretty simple script which allows me to copy files from my local computer to my webserver(using FTP) with many fewer clicks and typeing than before. If you are interested I would be glad to post it on the list. Jesse F. Weinstein From israel@lith.com Mon Aug 20 18:41:46 2001 From: israel@lith.com (Israel Evans) Date: Mon, 20 Aug 2001 10:41:46 -0700 Subject: [Tutor] [opinions?] Web development... (kind of long) [ACS?] Message-ID: Thank you all! The suggestions offered were great. I'm now reading Philip and Alex's Guide to Web Publishing and it seems to offer some great suggestions. Though I shy away from anything that has the Captial letters AOL right next to each other due to some horrible experiences in my childhood I'm still going to therapy for:). I like the idea of generated xml docs served up as xslt-ified xhtml. Even though the XML world is a crazy forest of specifications, it does have potential to do what I need to do in the way that I like to do it. My feeling is that I want to create my content, in whatever format is best for that content and use Python to dynamically collect and compile it into whatever presentable format I need, be it print or the web. It seems XML and all of it's insane children coupled with a nice big database for all of them to live in with Python in the lead playing sweet tunes that hypnotize them all into behaving properly. in response to Rob.. I've got websites that go from the personal "look at my daughter being cute", to the Five county newsletter that will probably have to deal with a lot of the same issues as Useless Python. I'm thinking: Mailing list Article Submissions Calendar, with submissions searchable directories of related businesses, instructors, and personalities. reviews of venues and so on.... -----Original Message----- From: Sheila King [mailto:sheila@thinkspot.net] Sent: Sunday, August 19, 2001 11:53 PM To: Danny Yoo Cc: Rob Andrews; Israel Evans; 'tutor@python.org' Subject: Re: [Tutor] [opinions?] Web development... (kind of long) [ACS?] On Sun, 19 Aug 2001 23:42:24 -0700 (PDT), Danny Yoo wrote about Re: [Tutor] [opinions?] Web development... (kind of long) [ACS?]: :Perhaps most useful is his ACS toolkit that does a lot of the heavy lifing :in collaborative web sites. Although its current incarnation is in Java, :some people split off and formed the "OpenACS": : : http://openacs.org : :which is in Tcl. Fortunately, there are Python bindings: : : http://pywx.idyll.org/ : : :I don't know if it's worth the effort to use the software, but it might be :useful to glean some of its ideas. Hope this helps! Boy, you really caught my attention with this post (I'm also reading Phil & Alex's Guide to Web Programming right now...I sprung for the printed version. The pictures are VERY nice. My four-year old likes to look at the book with me. ;) ) However, I see that one must run AOLserver (not surprised, actually). I just wish there were something along those lines already available that would run on Apache. The book IS chock full of ideas, though. Actually, for the person who started this thread, if he has the option to choose his own web server, and since there is a Python front end for scripting AOLserver, I'd emphatically recommend reading Phil's book and seriously considering that approach. -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From sheila@thinkspot.net Mon Aug 20 18:53:28 2001 From: sheila@thinkspot.net (Sheila King) Date: Mon, 20 Aug 2001 10:53:28 -0700 Subject: [Tutor] [opinions?] Web development... (kind of long) [ACS?] In-Reply-To: References: Message-ID: <9B0DFA86238@kserver.org> On Mon, 20 Aug 2001 10:41:46 -0700, Israel Evans wrote about RE: [Tutor] [opinions?] Web development... (kind of long) [ACS?]: :I'm now reading Philip and Alex's Guide :to Web Publishing and it seems to offer some great suggestions. :Though I shy away from anything that has the Captial letters AOL right next :to each other due to some horrible experiences in my childhood I'm still :going to therapy for:). I think that you will find, as you read Philip's book, that he makes it clear that: AOLserver is very different from AOL It was originally a product written by another company. AOL liked the product so much, they bought the company in order to use it for their own services. I guess part of the purchase agreement was that it continue to be a free product. Hmm. I don't recall. Anyhow, he just glows on AOLserver. If I were running my own web server, I would seriously consider using AOLserver as the web server software, based on his recommendations. (I'm on chapter 13 right now...I've been reading it at a sort of leisurely pace.) The problem for me is, I'm small time $$$ (personal/hobby) and can't really afford colocation, or my own pipe to my house. So, I sort of need to use a shared community server. And so I'm with FutureQuest.net, best community hosting company on the net. But they run Apache. -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From jessefw@loop.com Mon Aug 20 18:53:54 2001 From: jessefw@loop.com (Jesse F. W) Date: Mon, 20 Aug 2001 10:53:54 -0700 Subject: [Tutor] [opinions?] Web development... (kind of long) Message-ID: <3B80EC42.28789.F6AA1F7@localhost> Sorry about the messup. This is the message Israel was replying to. It got sent to him, instead of the list. to all good tutorians, Israel Evans wrote: > Hello everyone... > > My goals are as follows; > I'd like to create a number of templates for the look and feel for all > pages in a site. I'd like to create a number of ways the site would > be updated automatically whenever new content is added to either a > database or the directories of which the site is made of. It would be > great if I could do this on the client, but the Server Side is nice as > well. I'd like the content to be dynamically loaded in as it is > requested by the user. I don't know if this would be any use to you, but I have setup a pretty simple script which allows me to copy files from my local computer to my webserver(using FTP) with many fewer clicks and typeing than before. If you are interested I would be glad to post it on the list. Jesse F. Weinstein From dsh8290@rit.edu Mon Aug 20 18:57:18 2001 From: dsh8290@rit.edu (dman) Date: Mon, 20 Aug 2001 13:57:18 -0400 Subject: [Tutor] modification In-Reply-To: <3B813A06.C72FA99A@jam.rr.com>; from rob@jam.rr.com on Mon, Aug 20, 2001 at 11:25:42AM -0500 References: <3B813A06.C72FA99A@jam.rr.com> Message-ID: <20010820135718.A18009@harmony.cs.rit.edu> On Mon, Aug 20, 2001 at 11:25:42AM -0500, Rob Andrews wrote: # use input instead of raw_input Rob, why do you suggest using input() instead of raw_input()? Using input() can be potentially harmful if the user is knowledgeable and malicious. Suppose, for example, instead of entering a number the user enters in open( "some_file" , "w" ) In this case the file will be opened in write mode (which truncates its contents to nothing) and the file handle returned. The program will not operate correctly because it still expects an int, not a file. The best technique, IMO, is to use raw_input() for the input, and then use the proper conversion function (in this case int()) inside a try-except block to handle any errors. HTH, -D From delza@alliances.org Mon Aug 20 19:00:04 2001 From: delza@alliances.org (Dethe Elza) Date: Mon, 20 Aug 2001 11:00:04 -0700 Subject: [Tutor] Re: [Edu-sig] Off topic musings References: <5104D4DBC598D211B5FE0000F8FE7EB20E66BEB2@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <3B815024.6070403@alliances.org> For the OSI-like model you might want to break it up a bit further: 1 / Physical - bits and bytes defined by machine architecture. 2 / Machine-specific - this is the actual instruction set for a given machine 3 / Implementation - this includes data primitives of the given language. 4 / Implementation Groupings - collections, arrays, lists and structured types which are built into the language. 5 / Application - Developer-defined data types and tie-ins with other systems (RDBMS, etc). 6 / Extensions - Plugins or enhancements which are not part of the original program, but operate within it's context and add additional information structure. (Would XML go here?) 7 / User-defined - Some programs allow the user to extend the data set (by embedding Python, say). Hmmm. I probably should have numbered from zero, my bad %-) --Dethe 1/ Physical - bits/bytes, defined by the machine architecture operations are CPU specific, include bitwise OR/AND/NOT and binary arithmetic... 2/ Implementation/Environment - data types defined by the programming environment - object in Smallktalk; int, float, char in C etc... Operations include built in operators for arithmetic, boolean logic and I/O. [Question: Where do collections: arrays, lists etc fit into the layer proposal?] 3/ Application - User defined data types - records, files, RDBMS Tables etc Operations are user defined functions/procedures etc. (Alan, sorry about the duplicate, I keep forgetting that reply doesn't go to the group on this list). -- Dethe Elza (delza@burningtiger.com) Chief Mad Scientist Burning Tiger Technologies (http://burningtiger.com) -- Dethe Elza (delza@burningtiger.com) Chief Mad Scientist Burning Tiger Technologies (http://burningtiger.com) From delza@alliances.org Mon Aug 20 19:01:29 2001 From: delza@alliances.org (Dethe Elza) Date: Mon, 20 Aug 2001 11:01:29 -0700 Subject: [Tutor] Re: [Edu-sig] Off topic musings References: <5104D4DBC598D211B5FE0000F8FE7EB20E66BEB2@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <3B815079.10404@alliances.org> Related to the discussion of the "levels of information." There is a "levels of abstraction: Class - a group of related data and functionality Property - data belonging to a class/object which may be a variable or the result of a computation Pattern - a generalization of a recurring problem and its solution set Idiom - a pattern within the context of a given language Framework - a collection of related idioms packaged into a standalone unit Aspect - A cross-section of one consideration in a program (say, Security), factored out to make it modular Module - Some amount of functionality which is packaged as a standalone unit Component - A class or collection of classes which are packaged as a standalone unit and can be swapped in and out of a system. Library - A collection of functionality packaged for re-use Distributed Component - A component which spreads its functionality across multiple computers. Guideline - A recommendation for use, more specific than a pattern. Style Guideline - Standards for presenting code for maintenance. Documentation - Details about the documented system, high-level programs for human metacomputers. Pattern Language - A group of patterns which are mutually supporting or related Don't know how useful this is to anyone. Most of these relate to the tenets of pattern design and OO: * Seperate what changes from what stays the same (or things which change with different frequencies). * Solve problems by adding a layer of abstraction * Work at as high a level as possible to promote clarity. Clarity is the key for maintainable and extensible systems. -- Dethe Elza (delza@burningtiger.com) Chief Mad Scientist Burning Tiger Technologies (http://burningtiger.com) From dsh8290@rit.edu Mon Aug 20 19:07:16 2001 From: dsh8290@rit.edu (dman) Date: Mon, 20 Aug 2001 14:07:16 -0400 Subject: [Tutor] [Q] How to run a Python file from Windows 2000 folder In-Reply-To: <012a01c129a8$d7c37500$95757e82@visit2>; from ylee12@uiuc.edu on Mon, Aug 20, 2001 at 11:49:29AM -0700 References: <012a01c129a8$d7c37500$95757e82@visit2> Message-ID: <20010820140716.B18009@harmony.cs.rit.edu> On Mon, Aug 20, 2001 at 11:49:29AM -0700, Young-Jin Lee wrote: | Hi, all. | | I have a problem running a python file from windows 2000 folder. | | I expected my python file to be executed when I double-clicked it, | but I got "Program Not Found" error dialog box which required me to | find where "Program.exe" is located. I guess it might be a window | registry problem.... | | I manually assigned Python.exe to *py file in a property menu of the | my python source file, but it didn't work. | | What should I do to execute a python source file by double-clicking it? If you installed python from python.org then it should have set the file associations properly. In any case you can set it by hand using the following steps : 1) open explorer (the disk kind, not the internet kind) 2) click Tools->Folder Options 3) select the "File Types" tab in the dialog that appears 4) scroll down until you find the .py extension (if it doesn't exist yet, click the "New" button below the scroll pane, enter the extension and click "Ok") 5) click the "Advanced" button near the bottom 6) create/edit the "Open" operation -- the command is \python.exe "%1" 7) set the default operation to be "Open" 8) click "Ok" numerous times (to close the numerous dialogs) 9) test it by double clicking on a .py file 10) do the same thing for .pyw files, but specify "pythonw.exe" instead of python.exe for the command. I don't know why MS thinks that is easier than "#!/usr/bin/env python" at the top of the file and "chmod u+x "! -D From rob@jam.rr.com Mon Aug 20 19:06:58 2001 From: rob@jam.rr.com (Rob Andrews) Date: Mon, 20 Aug 2001 13:06:58 -0500 Subject: [Tutor] modification References: <3B813A06.C72FA99A@jam.rr.com> <20010820135718.A18009@harmony.cs.rit.edu> Message-ID: <3B8151C2.725FEED8@jam.rr.com> dman wrote: > > On Mon, Aug 20, 2001 at 11:25:42AM -0500, Rob Andrews wrote: > > # use input instead of raw_input > > Rob, why do you suggest using input() instead of raw_input()? > > Using input() can be potentially harmful if the user is knowledgeable > and malicious. Suppose, for example, instead of entering a number the > user enters in > > open( "some_file" , "w" ) > > In this case the file will be opened in write mode (which truncates > its contents to nothing) and the file handle returned. The program > will not operate correctly because it still expects an int, not a > file. > I would've never guessed that one. Thanks for the tip. Rob -- A {} is a terrible thing to waste. Useless Python! http://www.lowerstandard.com/python From bsass@freenet.edmonton.ab.ca Mon Aug 20 19:24:41 2001 From: bsass@freenet.edmonton.ab.ca (Bruce Sass) Date: Mon, 20 Aug 2001 12:24:41 -0600 (MDT) Subject: [Tutor] Off topic musings In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66BEB5@mbtlipnt02.btlabs.bt.co.uk> Message-ID: On Mon, 20 Aug 2001 alan.gauld@bt.com wrote: <...> > Yes, there are many books and papers on programming correctness but > few on the nature of information. Specifically I am intereted in > any work on layering of information structures. Looking at how > information itself is structured and operated upon. This is different > to programming which is only one very narrow subset ofg information > processing. I think the Philosophy of Language section in the library would be the place to start. Unless I'm completely misunderstanding you, you are interested in how information becomes data, gets manipulated, then spit out as information again... which seems analagous to what we do everyday when we look at something in the world, extract those features we think are important, then express the result of our machinations in terms that relate them to some other concern. - Bruce From dsh8290@rit.edu Mon Aug 20 20:29:19 2001 From: dsh8290@rit.edu (dman) Date: Mon, 20 Aug 2001 15:29:19 -0400 Subject: [Tutor] modification In-Reply-To: <3B8151C2.725FEED8@jam.rr.com>; from rob@jam.rr.com on Mon, Aug 20, 2001 at 01:06:58PM -0500 References: <3B813A06.C72FA99A@jam.rr.com> <20010820135718.A18009@harmony.cs.rit.edu> <3B8151C2.725FEED8@jam.rr.com> Message-ID: <20010820152919.B18531@harmony.cs.rit.edu> On Mon, Aug 20, 2001 at 01:06:58PM -0500, Rob Andrews wrote: | dman wrote: | I would've never guessed that one. Thanks for the tip. You're welcome. BTW, I got that info from either this list or python-list once upon a time. -D From dyoo@hkn.eecs.berkeley.edu Mon Aug 20 23:06:35 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 20 Aug 2001 15:06:35 -0700 (PDT) Subject: [Tutor] [opinions?] Web development... In-Reply-To: <9B0DFA86238@kserver.org> Message-ID: On Mon, 20 Aug 2001, Sheila King wrote: > AOLserver is very different from AOL It was originally a product > written by another company. AOL liked the product so much, they bought > the company in order to use it for their own services. I guess part of > the purchase agreement was that it continue to be a free product. Hmm. > I don't recall. There's more introductory information on AOLServer (formerly called "NaviServer") that is linked up from philg's "Web Tools Review" web site: http://philip.greenspun.com/wtr/ http://philip.greenspun.com/wtr/aolserver/introduction-1.html http://philip.greenspun.com/wtr/aolserver/introduction-2.html > now...I've been reading it at a sort of leisurely pace.) The problem > for me is, I'm small time $$$ (personal/hobby) and can't really afford > colocation, or my own pipe to my house. So, I sort of need to use a > shared community server. And so I'm with FutureQuest.net, best > community hosting company on the net. But they run Apache. There's actually a very neat way to get Apache to identify certain URLs and transparently redirect them to another server by using the "mod_proxy" module. I'm flirting with this right now to integrate AOLServer into an existing Apache setup. I'll include the entry I added to do this proxying. Perhaps someone can take a look at my httpd.conf entry and see if I opened a severe security hole in the process... *grin*: ### # Within Apache's httpd.conf: ProxyRequests On ## Let's get an /aolserver/'ish URL to direct to port 8080 ProxyPass /aolserver/ http://einfall:8080/ Order allow,deny Deny from none Allow from all Order deny,allow Deny from all Allow from none ### From clanoftheinsane@hotmail.com Mon Aug 20 23:14:45 2001 From: clanoftheinsane@hotmail.com (paul) Date: Mon, 20 Aug 2001 18:14:45 -0400 Subject: [Tutor] py2exe and modules Message-ID: ok, i know how to use py2exe to turn a basic program into an executable. but, i wrote a program using Tkinter, and when i ran py2exe to convert it to executable, it gave me a list of modules that it could not find. i know i'm supposed to do something with these modules, like copy them into some directory, am i correct? if i am correct, though, there are some modules that i cannot find. for example, the list of modules was as follows: win32api riscosenviron ce riscos riscospath i can only find riscosenviron and riscospath. can someone help? From dyoo@hkn.eecs.berkeley.edu Mon Aug 20 23:30:28 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 20 Aug 2001 15:30:28 -0700 (PDT) Subject: [Tutor] py2exe and modules In-Reply-To: Message-ID: On Mon, 20 Aug 2001, paul wrote: > ok, i know how to use py2exe to turn a basic program into an executable. > but, i wrote a program using Tkinter, and when i ran py2exe to convert it to > executable, it gave me a list of modules that it could not find. i know i'm > supposed to do something with these modules, like copy them into some > directory, am i correct? if i am correct, though, there are some modules > that i cannot find. for example, the list of modules was as follows: > > win32api > riscosenviron > ce > riscos > riscospath > > > i can only find riscosenviron and riscospath. It sounds like you'll need to get the win32 extensions, which can be found here: http://starship.python.net/crew/mhammond/ A more direct link is here: http://aspn.activestate.com/ASPN/Downloads/ActivePython/Extensions/Win32all However, I'm not quite sure about the 'ce' module (WinCE?). Does anyone know why py2exe is asking for this module? Good luck to you! From dyoo@hkn.eecs.berkeley.edu Tue Aug 21 01:16:57 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 20 Aug 2001 17:16:57 -0700 (PDT) Subject: [Tutor] py2exe and modules (fwd) Message-ID: Dear Paul, I don't have experience with py2exe unfortunately. However, let me forward this to the other tutors, and hopefully someone there can help you with it. Good luck! ---------- Forwarded message ---------- Date: Mon, 20 Aug 2001 19:11:02 -0400 From: paul To: Danny Yoo Subject: Re: [Tutor] py2exe and modules alright, i downloaded the win32 extensions, and then i ran py2exe again. i also found the riscospath and the riscoenviron in the python source files (which i downloaded earlier). so i pasted those into the directory where my program is. but, i still can't find the "ce" modeule that py2exe called for. also, am i correct in pasting the riscosenviron and riscospath files directly into the folder? From tescoil@irtc.net Tue Aug 21 01:50:08 2001 From: tescoil@irtc.net (Tesla Coil) Date: Mon, 20 Aug 2001 19:50:08 -0500 Subject: [Tutor] Mad Villain Seeks Source Review. Message-ID: <3B81B040.220C9F9E@irtc.net> Phase One of My Diabolical Plan to Reduce the World Wide Web to 256 Grayscale seems to have been delayed... import re def namedict(): namedcolors = {'maroon' : '262626', 'green' : '4b4b4b', 'red' : '4c4c4c', 'navy' : '0e0e0e', 'purple' : '343434', 'lime' : '969696', 'blue' : '1c1c1c', 'magenta' : '686868', 'olive' : '717171', 'yellow' : 'e2e2e2', 'teal' : '595959', 'cyan' : 'b2b2b2',} return namedcolors def namerepl( match ): # Adjusts various forms that may be taken # by a match in the following function so # as to return the dictionary value. # Works. namedcolors = namedict() match = match.lower() catch ="" for sstr in match: if sstr.isalpha(): catch = catch+sstr return namedcolors[catch] def firstpass(line): # Reduce dictionary keys into a regex and # substitute using preceding function. # Attribute Error: lower. Hmph. Now I'll # have to settle for hijacking a spacecraft. namedcolors = namedict() colors = namedcolors.keys() crush = lambda x,y: x+'|'+ y colorsearch = reduce(crush, colors) colorsearch = '[=][\s]?['+colorsearch+']' colorsearch = re.compile(colorsearch, re.I) line = re.sub(colorsearch, namerepl, line) return line teststring = "" firstpass(teststring) --- James Bond Villain Personality Test: http://www.physics.usyd.edu.au/~mar/villain.html From tescoil@irtc.net Tue Aug 21 02:11:03 2001 From: tescoil@irtc.net (Tesla Coil) Date: Mon, 20 Aug 2001 20:11:03 -0500 Subject: [Tutor] Mad Villain Seeks Source Review. References: <3B81B040.220C9F9E@irtc.net> Message-ID: <3B81B527.D2E43B13@irtc.net> The dictionary entries would need to be prefixed with '= #' regardless: def namedict(): namedcolors = {'maroon' : '= #262626', 'green' : '= #4b4b4b', # etc. From ignacio@openservices.net Tue Aug 21 02:17:29 2001 From: ignacio@openservices.net (Ignacio Vazquez-Abrams) Date: Mon, 20 Aug 2001 21:17:29 -0400 (EDT) Subject: [Tutor] Mad Villain Seeks Source Review. In-Reply-To: <3B81B040.220C9F9E@irtc.net> Message-ID: On Mon, 20 Aug 2001, Tesla Coil wrote: > Phase One of My Diabolical Plan to Reduce the > World Wide Web to 256 Grayscale seems to have > been delayed... > > [snip] > colorsearch = '[=][\s]?['+colorsearch+']' That RE is _Wrong_. Try "'=\s?\'(%s)\'' % colorsearch". -- Ignacio Vazquez-Abrams From ignacio@openservices.net Tue Aug 21 03:12:25 2001 From: ignacio@openservices.net (Ignacio Vazquez-Abrams) Date: Mon, 20 Aug 2001 22:12:25 -0400 (EDT) Subject: [Tutor] Mad Villain Seeks Source Review. In-Reply-To: Message-ID: On Mon, 20 Aug 2001, Ignacio Vazquez-Abrams wrote: > On Mon, 20 Aug 2001, Tesla Coil wrote: > > > Phase One of My Diabolical Plan to Reduce the > > World Wide Web to 256 Grayscale seems to have > > been delayed... > > > > [snip] > > colorsearch = '[=][\s]?['+colorsearch+']' > > That RE is _Wrong_. Try "'=\s?\'(%s)\'' % colorsearch". Turns out that that wasn't the only problem. Here, have fun. --- #! /usr/bin/python2 import re namedcolors={ 'maroon' : '262626', 'green' : '4b4b4b', 'red' : '4c4c4c', 'navy' : '0e0e0e', 'purple' : '343434', 'lime' : '969696', 'blue' : '1c1c1c', 'magenta' : '686868', 'olive' : '717171', 'yellow' : 'e2e2e2', 'teal' : '595959', 'cyan' : 'b2b2b2', } def namerepl(match): global namedcolors a,b,c,d=match.group(1,2,3,4) t=d or c return "='#%s'" % namedcolors[t.lower()] def firstpass(line): global namedcolors colors='|'.join(namedcolors.keys()) colorsearch='=\s*((\'(%s)\')|(%s))' % (colors, colors) colorre=re.compile(colorsearch, re.I) line=colorre.sub(namerepl, line) return line teststring = "" print firstpass(teststring) --- Here's a link to a complete set of color names in case you needed it: http://developer.netscape.com/docs/manuals/htmlguid/colortab.htm -- Ignacio Vazquez-Abrams From rob@jam.rr.com Tue Aug 21 03:36:21 2001 From: rob@jam.rr.com (Rob Andrews) Date: Mon, 20 Aug 2001 21:36:21 -0500 Subject: [Tutor] partition problem source posted on Useless Message-ID: <3B81C925.96F184EC@jam.rr.com> Half a page dedicated to that one problem... Cool. Here's the record of the action. Hopefully I got it all right: http://www.lowerstandard.com/python/uselesspython10.html For those of you who have "worked so hard" to make useless & obfuscated Python scripts, there's a page of graphics you can swipe. If nothing else, you should like the *Danny Yoo Clinic for Tutor List Addiction* logos: http://www.lowerstandard.com/python/uselesslogos.html heh, Rob -- A {} is a terrible thing to waste. Useless Python! http://www.lowerstandard.com/python From tescoil@irtc.net Tue Aug 21 03:45:23 2001 From: tescoil@irtc.net (Tesla Coil) Date: Mon, 20 Aug 2001 21:45:23 -0500 Subject: [Tutor] Mad Villain Seeks Source Review. References: Message-ID: <3B81CB43.F2B87B06@irtc.net> On 20 August 2001, Ignacio Vazquez-Abrams wrote: >>> colorsearch = '[=][\s]?['+colorsearch+']' >> >> That RE is _Wrong_. Try "'=\s?\'(%s)\'' % colorsearch". > > Turns out that that wasn't the only problem. Here, have fun. I was beginning to see that. Altering the original just to account for quotation marks appears only to grab up to the first alphabetic character (?) >>> import re >>> def namedict(): >>> # snip >>> >>> def firstpass(line): ... namedcolors = namedict() ... colors = namedcolors.keys() ... crush = lambda x,y: x+'|'+ y ... colorsearch = reduce(crush, colors) ... colorsearch = '[=][\s]?["|\']?['+colorsearch+']["|\']?' ... colorsearch = re.compile(colorsearch, re.I) ... hits = re.findall(colorsearch, line) ... print hits ... >>> firstpass("") ["='M", '= y'] This is a radical enough overhaul to be somewhat demoralizing: > def namerepl(match): > global namedcolors > a,b,c,d=match.group(1,2,3,4) > t=d or c > return "='#%s'" % namedcolors[t.lower()] > > def firstpass(line): > global namedcolors > colors='|'.join(namedcolors.keys()) > colorsearch='=\s*((\'(%s)\')|(%s))' % (colors, colors) > colorre=re.compile(colorsearch, re.I) > line=colorre.sub(namerepl, line) > return line And this is thoroughly depressing... > http://developer.netscape.com/docs/manuals/htmlguid/colortab.htm *Sigh*, If it were simply a matter of rgb values: def grayscale(rgbstring): r = rgbstring[0:2] g = rgbstring[2:4] b = rgbstring[4:6] hexcon = lambda x: float(eval('0x'+x)) vl = map(hexcon, [r,g,b]) grayrgb = int((0.3*vl[0])+(0.59*vl[1])+(0.11*vl[2])) grayrgb = str(hex(grayrgb)) grayrgb = grayrgb[2:]*3 return grayrgb From ignacio@openservices.net Tue Aug 21 04:02:51 2001 From: ignacio@openservices.net (Ignacio Vazquez-Abrams) Date: Mon, 20 Aug 2001 23:02:51 -0400 (EDT) Subject: [Tutor] Mad Villain Seeks Source Review. In-Reply-To: <3B81CB43.F2B87B06@irtc.net> Message-ID: On Mon, 20 Aug 2001, Tesla Coil wrote: > This is a radical enough overhaul to be > somewhat demoralizing: Sorry, I didn't mean anything personal by it. I just write very dense programs. > *Sigh*, If it were simply a matter of rgb values: Wait a minute, you're telling me that it isn't? :) file:///usr/X11R6/lib/X11/rgb.txt http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/~checkout~/vim/vim/runtime/rgb.txt?rev=1.1&content-type=text/plain -- Ignacio Vazquez-Abrams From fleet@teachout.org Tue Aug 21 04:16:45 2001 From: fleet@teachout.org (fleet@teachout.org) Date: Mon, 20 Aug 2001 23:16:45 -0400 (EDT) Subject: [Tutor] Your dog Scope bit me! Message-ID: I'm trying to create a function that will retrieve a pickled dictionary. Python doesn't complain about the following; but I don't "get" anything and no "upc" is listed in dir(). def get_upc(): """retrieves upc dictionary as upc""" import pickle f=open("upc.dict") upc=pickle.load(f) f.close() print "UPC Dictionary retrieved" I'm assuming I have a scope problem. Guess I don't understand all I should about scopes. How do I run this from an interactive session so that I'm able to use the dictionary? Entering each of the lines in an interactive session retrieves the dictionary; but then I'm not in the "scope" of the function. - fleet - From ignacio@openservices.net Tue Aug 21 04:21:16 2001 From: ignacio@openservices.net (Ignacio Vazquez-Abrams) Date: Mon, 20 Aug 2001 23:21:16 -0400 (EDT) Subject: [Tutor] Your dog Scope bit me! In-Reply-To: Message-ID: On Mon, 20 Aug 2001 fleet@teachout.org wrote: > I'm trying to create a function that will retrieve a pickled dictionary. > Python doesn't complain about the following; but I don't "get" anything > and no "upc" is listed in dir(). > > def get_upc(): > """retrieves upc dictionary as upc""" > import pickle > f=open("upc.dict") > upc=pickle.load(f) > f.close() > print "UPC Dictionary retrieved" > > I'm assuming I have a scope problem. Guess I don't understand all I > should about scopes. How do I run this from an interactive session so > that I'm able to use the dictionary? > > Entering each of the lines in an interactive session retrieves the > dictionary; but then I'm not in the "scope" of the function. > > - fleet - Two options: --- upc=None def get_upc(): global upc ... --- --- def get_upc(): ... return upc ... upc=get_upc() --- Either make it a global variable or return if from the function. -- Ignacio Vazquez-Abrams From fleet@teachout.org Tue Aug 21 04:26:03 2001 From: fleet@teachout.org (fleet@teachout.org) Date: Mon, 20 Aug 2001 23:26:03 -0400 (EDT) Subject: [Tutor] image sizes Message-ID: I'm really pushing the topic limits here; but I want to be able to obtain image sizes (height and width of .GIF files) from within a Python script. I know about PIL; but is this necessary to accomplish what I want? And will it accomplish what I want? (I haven't a clue how to go about this outside of Python either!) And if it's needed - RH 7.1 and Python 1.5.2. - fleet - From sheila@thinkspot.net Tue Aug 21 04:27:29 2001 From: sheila@thinkspot.net (Sheila King) Date: Mon, 20 Aug 2001 20:27:29 -0700 Subject: [Tutor] Your dog Scope bit me! In-Reply-To: References: Message-ID: On Mon, 20 Aug 2001 23:16:45 -0400 (EDT), wrote about [Tutor] Your dog Scope bit me!: :def get_upc(): : """retrieves upc dictionary as upc""" : import pickle : f=open("upc.dict") : upc=pickle.load(f) : f.close() : print "UPC Dictionary retrieved" : :I'm assuming I have a scope problem. Guess I don't understand all I :should about scopes. How do I run this from an interactive session so :that I'm able to use the dictionary? How about adding a last line to your function: return upc And then call it in your main code like this: dict = get_upc() -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From ak@silmarill.org Tue Aug 21 04:35:29 2001 From: ak@silmarill.org (Andrei Kulakov) Date: Mon, 20 Aug 2001 23:35:29 -0400 Subject: [Tutor] [opinions?] Web development... (kind of long) [ACS?] In-Reply-To: References: Message-ID: <20010820233529.A532@sill.silmarill.org> On Mon, Aug 20, 2001 at 10:41:46AM -0700, Israel Evans wrote: > Thank you all! > > The suggestions offered were great. I'm now reading Philip and Alex's Guide > to Web Publishing and it seems to offer some great suggestions. > Though I shy away from anything that has the Captial letters AOL right next > to each other due to some horrible experiences in my childhood I'm still > going to therapy for:). Well, AOL is, you know.. not techie, but AOLserver is perfectly fine. I don't remember exactly, but I think they aquired it and it originally was created on BSD or some other UNIX.. -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From ignacio@openservices.net Tue Aug 21 04:39:19 2001 From: ignacio@openservices.net (Ignacio Vazquez-Abrams) Date: Mon, 20 Aug 2001 23:39:19 -0400 (EDT) Subject: [Tutor] image sizes In-Reply-To: Message-ID: On Mon, 20 Aug 2001 fleet@teachout.org wrote: > I'm really pushing the topic limits here; but I want to be able to obtain > image sizes (height and width of .GIF files) from within a Python script. > I know about PIL; but is this necessary to accomplish what I want? And > will it accomplish what I want? > > (I haven't a clue how to go about this outside of Python either!) > > And if it's needed - RH 7.1 and Python 1.5.2. > > - fleet - You could use PIL. Or you could use PythonMagick (http://starship.python.net/crew/zack/pymagick/). Or you could handle it all yourself (http://www.dcs.ed.ac.uk/home/mxr/gfx/2d-hi.html). I suggest using PIL or PythonMagick. If you have a large variety of formats to handle then PythonMagick might be a better choice. -- Ignacio Vazquez-Abrams From tescoil@irtc.net Tue Aug 21 05:26:53 2001 From: tescoil@irtc.net (Tesla Coil) Date: Mon, 20 Aug 2001 23:26:53 -0500 Subject: [Tutor] Mad Villain Seeks Source Review. References: Message-ID: <3B81E30D.E5AA8EBF@irtc.net> On 20 August 2001, Ignacio Vazquez-Abrams wrote: >> This is a radical enough overhaul to be >> somewhat demoralizing: > > Sorry, I didn't mean anything personal by it. > I just write very dense programs. That's okay, I'm studying it. I'll benefit from any different rendition anyone has to offer. If someone wants to say "here's how I'd do it OO," all the better. >> *Sigh*, If it were simply a matter of rgb values: > > Wait a minute, you're telling me that it isn't? :) > > file:///usr/X11R6/lib/X11/rgb.txt Hmm, lists on the web that tell the hex values for all the Netscape and IE named colors (wonder how much those two agree). Still be a *huge* regex going on behind the scenes... From dyoo@hkn.eecs.berkeley.edu Tue Aug 21 05:46:22 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 20 Aug 2001 21:46:22 -0700 (PDT) Subject: [Tutor] Your dog Scope bit me! In-Reply-To: Message-ID: On Mon, 20 Aug 2001 fleet@teachout.org wrote: > I'm trying to create a function that will retrieve a pickled dictionary. > Python doesn't complain about the following; but I don't "get" anything > and no "upc" is listed in dir(). > > def get_upc(): > """retrieves upc dictionary as upc""" > import pickle > f=open("upc.dict") > upc=pickle.load(f) > f.close() > print "UPC Dictionary retrieved" > > I'm assuming I have a scope problem. Guess I don't understand all I > should about scopes. How do I run this from an interactive session so > that I'm able to use the dictionary? All functions by default will "return" a None value: ### >>> def hello(): ... print "I still return None!" ... >>> x = hello() I still return None! >>> x >>> type(x) >>> ### To have the function return something more interesting, we should tell Python what exactly to return back to the caller. In get_upc(), the 'upc' variable looks like our target: ### def get_upc(): """retrieves upc dictionary as upc""" import pickle f = open("upc.dict") upc = pickle.load(f) f.close() print "UPC Dictionary retrieved" return upc ### Good luck! From ignacio@openservices.net Tue Aug 21 06:08:33 2001 From: ignacio@openservices.net (Ignacio Vazquez-Abrams) Date: Tue, 21 Aug 2001 01:08:33 -0400 (EDT) Subject: [Tutor] Mad Villain Seeks Source Review. In-Reply-To: <3B81E30D.E5AA8EBF@irtc.net> Message-ID: On Mon, 20 Aug 2001, Tesla Coil wrote: > Hmm, lists on the web that tell the hex values > for all the Netscape and IE named colors (wonder > how much those two agree). Still be a *huge* > regex going on behind the scenes... Well, why don't you try searching by attribute name instead of color name? That way you would only have to deal with 'color=\s*("([^" ]+)"|\'([^\' ]+)\'|([^"' ]+))' instead. -- Ignacio Vazquez-Abrams From tescoil@irtc.net Tue Aug 21 06:44:12 2001 From: tescoil@irtc.net (Tesla Coil) Date: Tue, 21 Aug 2001 00:44:12 -0500 Subject: [Tutor] Mad Villain Seeks Source Review. References: Message-ID: <3B81F52C.7FE82353@irtc.net> > Well, why don't you try searching by attribute name > instead of color name? That way you would only have > to deal with > 'color=\s*("([^" ]+)"|\'([^\' ]+)\'|([^"' ]+))' > instead. Hadn't considered that--but I'm even less certain what attribute names might be encountered. Some would have 'color' followed by intervening alphabetic characters prior to the possible space (can't afford to be greedy there) and '=', eg., bordercolordark, bordercolorlight. Then there's 'text' and, who knows what all else? OTOH, a Diabolical Plan to Reduce the World Wide Web to 256 Grayscale would be much less in order if page source were not such an unpredictable mess. <0.5 wink> From scarblac@pino.selwerd.nl Tue Aug 21 07:25:02 2001 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Tue, 21 Aug 2001 08:25:02 +0200 Subject: [Tutor] image sizes In-Reply-To: ; from fleet@teachout.org on Mon, Aug 20, 2001 at 11:26:03PM -0400 References: Message-ID: <20010821082502.A31998@pino.selwerd.nl> On 0, fleet@teachout.org wrote: > I'm really pushing the topic limits here; but I want to be able to obtain > image sizes (height and width of .GIF files) from within a Python script. > I know about PIL; but is this necessary to accomplish what I want? And > will it accomplish what I want? > > (I haven't a clue how to go about this outside of Python either!) > > And if it's needed - RH 7.1 and Python 1.5.2. Yes, I'd use PIL. With PIL, it is *very* simple: import Image pic = Image.open("mypicture.gif") width, height = pic.size This code immediately works for almost all other types of image as well. PIL is just so extremely neat, I wish everything had an interface as simple as that :) [consider the code for converting a .gif to .jpg: Image.load("mypic.gif").save("mypic.jpg") ] -- Remco Gerlich From content-management@high-tech-communcations.com Tue Aug 21 08:08:54 2001 From: content-management@high-tech-communcations.com (Victor Black) Date: Tue, 21 Aug 2001 00:08:54 -0700 Subject: [Tutor] New web utility Message-ID: <200108210708.f7L78sF02011@mail.high-tech-communications.com>

    I noticed your email address on a list serve related to technology and web development.  With your permission, we
    would like to send you information regarding new web tools and utilities based on your interests.  Please click the
    following link and opt-in to our product updates and e-newsletter, click here:
    http://216.133.228.90/cm/

    Cordially,

    Victor Black
    High-Tech-Communications.com

    If you would like to be removed from our database, please click here: http://216.133.228.90/cm/remove.cgi

     

    From printers@sendme.cz Tue Aug 21 07:59:46 2001 From: printers@sendme.cz (A) Date: Tue, 21 Aug 2001 08:59:46 +0200 Subject: [Tutor] *args, **kwargs Message-ID: <3B822302.19667.173323@localhost> Hi, I am a newbie with Python. Can you please let me know what is a difference between *args and **kwargs and how I can use them? Thanks. Ladislav From dyoo@hkn.eecs.berkeley.edu Tue Aug 21 08:31:40 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 21 Aug 2001 00:31:40 -0700 (PDT) Subject: [Tutor] Mad Villain Seeks Source Review. In-Reply-To: <3B81F52C.7FE82353@irtc.net> Message-ID: On Tue, 21 Aug 2001, Tesla Coil wrote: > > > Well, why don't you try searching by attribute name > > instead of color name? That way you would only have > > to deal with > > 'color=\s*("([^" ]+)"|\'([^\' ]+)\'|([^"' ]+))' > > instead. > > Hadn't considered that--but I'm even less certain what > attribute names might be encountered. Some would have > 'color' followed by intervening alphabetic characters > prior to the possible space (can't afford to be greedy > there) and '=', eg., bordercolordark, bordercolorlight. > Then there's 'text' and, who knows what all else? > > OTOH, a Diabolical Plan to Reduce the World Wide Web > to 256 Grayscale would be much less in order if page > source were not such an unpredictable mess. <0.5 wink> Hmmm... so would this diabolical plan only wrap its terrible tendrils around HTML? If so, you might be able to avoid the parsing issue altogether by using the HTMLParser class from htmllib. Here is the darkness that is the BlackHoleParser.py: ### """BlackHoleParser.py: another demonstration of sgmllib. Sucks the color right out of a page. Danny Yoo (dyoo@hkn.eecs.berkeley.edu) Note: I need to use sgmllib: if I use htmllib, not all the tags get intercepted by unknown_starttag(). Just feed() in a page into this parser, and then getPage() it to recover the digested remains. """ import sgmllib from formatter import NullFormatter class BlackHoleParser(sgmllib.SGMLParser): def __init__(self): sgmllib.SGMLParser.__init__(self, NullFormatter()) self.content = [] def getPage(self): """Returns the blackened and charred remains of the document as a string.""" return ''.join(self.content) def handle_data(self, data): self.content.append(data) def handle_comment(self, comment): self.content.append('' % comment) def unknown_starttag(self, tag, attrs): """We intercept all start tags, and attack all color attributes.""" new_attrs = [] for name, value in attrs: if name in ('color', 'bgcolor'): value = "#000000" new_attrs.append( (name, value) ) attr_str = makeAttributeString(new_attrs) if attr_str: new_starttag = '<%s %s>' % (tag.upper(), attr_str ) else: new_starttag = '<%s>' % tag.upper() self.content.append(new_starttag) def unknown_endtag(self, tag): self.content.append("" % tag) def unknown_charref(self, ref): self.content.append(ref) def unknown_entityref(self, ref): self.content.append(ref) def makeAttributeString(attributes): joined_tags = [] for name, value in attributes: joined_tags.append('%s="%s"' % (name.upper(), value)) return ' '.join(joined_tags) if __name__ == '__main__': import urllib import sys blackhole = BlackHoleParser() spacecraft = urllib.urlopen(sys.argv[1]).read() blackhole.feed(spacecraft) print blackhole.getPage() ### It eats color attributes for lunch. We can see a blow by blow account of what it does to http://python.org: ### dyoo@coffeetable:~$ python BlackHoleParser.py http://python.org [... oops. Hmmm... Let's skip some lines.] [ more lines skipped ] Special topics Topic Guides Python 2.2 ### So it appears to work. It shouldn't be too hard to tone down its harshness to emit shades of gray. Hope this helps! From dyoo@hkn.eecs.berkeley.edu Tue Aug 21 08:45:32 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 21 Aug 2001 00:45:32 -0700 (PDT) Subject: [Tutor] Mad Villain Seeks Source Review. In-Reply-To: Message-ID: On Tue, 21 Aug 2001, Danny Yoo wrote: > Hmmm... so would this diabolical plan only wrap its terrible tendrils > around HTML? If so, you might be able to avoid the parsing issue > altogether by using the HTMLParser class from htmllib. Here is the > darkness that is the BlackHoleParser.py: Sorry, meant to say 'sgmllib'. There are some reasons why htmllib would be messier: htmllib automatically handles several kinds of tags, and those too would need to be redefined if I were to use htmllib. sgmllib is a clean slate. From bsass@freenet.edmonton.ab.ca Tue Aug 21 08:57:20 2001 From: bsass@freenet.edmonton.ab.ca (Bruce Sass) Date: Tue, 21 Aug 2001 01:57:20 -0600 (MDT) Subject: [Tutor] *args, **kwargs In-Reply-To: <3B822302.19667.173323@localhost> Message-ID: On Tue, 21 Aug 2001, A wrote: > Hi, > I am a newbie with Python. Can you please let me know what is a > difference between *args and **kwargs and how I can use them? Playing with the interpreter is the best way to get a feel for what they do... >>> def test(pos, *arg, **keyed): ... print pos ... print arg ... print keyed ... >>> test('positional', 'an argument', key='value') positional ('an argument',) {'key': 'value'} >>> test(1, 2, 3, four=4, five=5) 1 (2, 3) {'five': 5, 'four': 4} ...* collects non-positional arguments into a tuple named , ** collects keyword arguments into a dictionary named . Section 4.7 of the Tutorial gives a good introduction. - Bruce From SBrunning@trisystems.co.uk Tue Aug 21 09:27:48 2001 From: SBrunning@trisystems.co.uk (Simon Brunning) Date: Tue, 21 Aug 2001 09:27:48 +0100 Subject: [Tutor] py2exe and modules Message-ID: <31575A892FF6D1118F5800600846864D78BFEB@intrepid> > From: paul [SMTP:clanoftheinsane@hotmail.com] > ok, i know how to use py2exe to turn a basic program into an executable. > but, i wrote a program using Tkinter, and when i ran py2exe to convert it > to > executable, it gave me a list of modules that it could not find. i know > i'm > supposed to do something with these modules, like copy them into some > directory, am i correct? if i am correct, though, there are some modules > that i cannot find. for example, the list of modules was as follows: > > win32api > riscosenviron > ce > riscos > riscospath > > > i can only find riscosenviron and riscospath. > > can someone help? py2exe sends out a fair number of messages, many of them warnings. So, the question is: is an exe created, and does it work. If so, don't worry about the messages. Cheers, Simon Brunning TriSystems Ltd. sbrunning@trisystems.co.uk ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From tescoil@irtc.net Tue Aug 21 09:55:50 2001 From: tescoil@irtc.net (Tesla Coil) Date: Tue, 21 Aug 2001 03:55:50 -0500 Subject: [Tutor] Mad Villain Seeks Source Review. References: Message-ID: <3B822216.5A620543@irtc.net> On 21 August 2001, Danny Yoo wrote: > Hmmm... so would this diabolical plan only wrap > its terrible tendrils around HTML? If so, you > might be able to avoid the parsing issue altogether > by using the HTMLParser class from htmllib. Here > is the darkness that is the BlackHoleParser.py: Beautiful! I expect it will have its part as is. Suitably deployed upon nuisance pages such as: http://developer.netscape.com/docs/manuals/htmlguid/colortab.htm > blackhole.feed(spacecraft) Lines like that are a Drax or Blofeld on the Bond Villain Personality Test, I'd imagine... I was about to say that my initial design had failed to appreciate enough what Tim Peters said only a few days ago: "When it comes to computer searches, doing a stupid thing quickly but many times is often more effective than doing an intelligent thing slowly [...] due in part to that writing a *truly* intelligent thing is much more difficult than is first imagined." Which suggests grab *everything* that follows a '=', strip whitespace and quotations, lowercase it, and test to see if it's among named colors. Unless there's an even dumber application of brute force. But I will be looking at sgmllib. Oh, grayscale function I posted earlier is crocked. Here's the quick fix: def grayscale(rgbstring): r = rgbstring[0:2] g = rgbstring[2:4] b = rgbstring[4:6] hexcon = lambda x: float(eval('0x'+x)) vl = map(hexcon, [r,g,b]) grayrgb = int((0.3*vl[0])+(0.59*vl[1])+(0.11*vl[2])) if grayrgb <= 15: grayrgb = str(hex(grayrgb)) grayrgb = ('0'+ grayrgb[-1])*3 else: grayrgb = str(hex(grayrgb)) grayrgb = grayrgb[2:]*3 return grayrgb From smorris@cereva.com Tue Aug 21 15:26:16 2001 From: smorris@cereva.com (Morris, Steve) Date: Tue, 21 Aug 2001 10:26:16 -0400 Subject: [Edu-sig] RE: [Tutor] Off topic musings Message-ID: <8010912471E0D41189930090278D4E48E154FB@SPAWN> > On 20 Aug 01, at 22:06, Morris, Steve wrote: > > Maybe. Really I'm just interested in what exactly a > > theoretical basis for software engineering would look like. I think my problem with this discussion, and the cause of the different approaches, is that you ask your question in ambiguous terms. You ask for a "theory of everything" in the generic category of software engineering. Software engineering is not a science but a discipline, or perhaps a skill, or maybe just programming. The term 'software engineering" usually refers to the process of writing programs with the imputation that these programs match some standard; whether it be correctness, or matching the specs, or merely being useful. It is thus not suprising that we keep getting lost in the process and techniques of programming. That statement is almost a tautology. What else would a theory of "software engineering" address. I would like you to restate your query with a better idea of the specific questions you are trying to answer. I know what specific questions a "unified field theory" is trying to answer. What question are you trying to answer? From ylee12@uiuc.edu Tue Aug 21 19:07:41 2001 From: ylee12@uiuc.edu (Young-Jin Lee) Date: Tue, 21 Aug 2001 11:07:41 -0700 Subject: [Tutor] [Q] Newbie's question on Python graphics Message-ID: <005c01c12a6c$2bb01880$95757e82@visit2> This is a multi-part message in MIME format. ------=_NextPart_000_0059_01C12A31.7F38D680 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi, all. I'm new to Python and I have a question on the Python graphics. Most of the document I read doesn't tell much about graphics = programming. I need a kind of 2D drawing functionality, drawing a line, = circle, and oval, translate them, and rotate them. Is there a good = tutorial or whatever for this topic? I also need to know if a Java application can call these drawing method = through the imbedded Python (Jython module). I heard if the drawing = routine or any Python routine is dependent on any C API, a Java = application cannot use it through the imbedded Python.=20 Thanks in advance.=20 Young-Jin Lee ------=_NextPart_000_0059_01C12A31.7F38D680 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
    Hi, all. I'm new to Python and I have a = question on=20 the Python graphics.
    Most of the document I read doesn't = tell much about=20 graphics programming. I need a kind of 2D drawing functionality, drawing = a line,=20 circle, and oval, translate them, and rotate them. Is there a good = tutorial or=20 whatever for this topic?
    I also need to know if a Java = application can call=20 these drawing method through the imbedded Python (Jython module). I = heard if the=20 drawing routine or any Python routine is dependent on any C API, a Java=20 application cannot use it through the imbedded Python. =
     
    Thanks in advance.
     
    Young-Jin = Lee
    ------=_NextPart_000_0059_01C12A31.7F38D680-- From ak@silmarill.org Tue Aug 21 17:13:43 2001 From: ak@silmarill.org (Andrei Kulakov) Date: Tue, 21 Aug 2001 12:13:43 -0400 Subject: [Tutor] [Q] Newbie's question on Python graphics In-Reply-To: <005c01c12a6c$2bb01880$95757e82@visit2> References: <005c01c12a6c$2bb01880$95757e82@visit2> Message-ID: <20010821121343.A6802@sill.silmarill.org> On Tue, Aug 21, 2001 at 11:07:41AM -0700, Young-Jin Lee wrote: > Hi, all. I'm new to Python and I have a question on the Python graphics. > Most of the document I read doesn't tell much about graphics programming. I need a kind of 2D drawing functionality, drawing a line, circle, and oval, translate them, and rotate them. Is there a good tutorial or whatever for this topic? > I also need to know if a Java application can call these drawing method through the imbedded Python (Jython module). I heard if the drawing routine or any Python routine is dependent on any C API, a Java application cannot use it through the imbedded Python. > > Thanks in advance. > > Young-Jin Lee I never done this so someone more knowledgeable will probably give a better answer soon, but fwiw, check out PIL (google for it). -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From proudsoul@hotmail.com Tue Aug 21 17:31:24 2001 From: proudsoul@hotmail.com (Proud Newbie) Date: Wed, 22 Aug 2001 01:31:24 +0900 Subject: [Tutor] How do I run other Windows application in a Python script? Message-ID: Hello there, How can I run other Windows applications in a Python script? (for example, I want to ask Notepad to display a .txt file) Thanks a lot. Proud Newbie :-) From ak@silmarill.org Tue Aug 21 17:31:04 2001 From: ak@silmarill.org (Andrei Kulakov) Date: Tue, 21 Aug 2001 12:31:04 -0400 Subject: [Tutor] How do I run other Windows application in a Python script? In-Reply-To: References: Message-ID: <20010821123104.A7044@sill.silmarill.org> On Wed, Aug 22, 2001 at 01:31:24AM +0900, Proud Newbie wrote: > Hello there, > > How can I run other Windows applications in a Python script? > (for example, I want to ask Notepad to display a .txt file) > > > Thanks a lot. > > Proud Newbie > :-) os.system("notepad myfile.txt") > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From dsh8290@rit.edu Tue Aug 21 17:50:57 2001 From: dsh8290@rit.edu (dman) Date: Tue, 21 Aug 2001 12:50:57 -0400 Subject: [Tutor] [Q] Newbie's question on Python graphics In-Reply-To: <005c01c12a6c$2bb01880$95757e82@visit2>; from ylee12@uiuc.edu on Tue, Aug 21, 2001 at 11:07:41AM -0700 References: <005c01c12a6c$2bb01880$95757e82@visit2> Message-ID: <20010821125057.B22548@harmony.cs.rit.edu> On Tue, Aug 21, 2001 at 11:07:41AM -0700, Young-Jin Lee wrote: | Hi, all. I'm new to Python and I have a question on the Python | graphics. It depends on what you mean by "graphics". | Most of the document I read doesn't tell much about graphics | programming. I need a kind of 2D drawing functionality, drawing a | line, circle, and oval, translate them, and rotate them. Is there a | good tutorial or whatever for this topic? This sounds like you are talking about GUI toolkit functionality, rather than graphic (ie JPEG) manipulation. Most python docs won't talk much about GUIs because there are many different toolkits that can be used from Python. | I also need to know if a Java application can call these drawing | method through the imbedded Python (Jython module). I heard if the | drawing routine or any Python routine is dependent on any C API, a | Java application cannot use it through the imbedded Python. If you are using Jython then you can only use stuff that is pure python or accessible from Java. Most of python's extensions (and most GUI toolkits too) depend on some C stuff and aren't naturally accessible from Java. The most natural GUI toolkit to use from Java/Jython is Swing. See http://java.sun.com/j2se/1.3/docs/api/index.html http://developer.java.sun.com/developer/onlineTraining/GUI/Swing1/shortcourse.html for more details on swing. HTH, -D From dsh8290@rit.edu Tue Aug 21 18:00:03 2001 From: dsh8290@rit.edu (dman) Date: Tue, 21 Aug 2001 13:00:03 -0400 Subject: [Tutor] [opinions?] Web development... (kind of long) In-Reply-To: ; from israel@lith.com on Sun, Aug 19, 2001 at 09:53:17PM -0700 References: Message-ID: <20010821130003.C22548@harmony.cs.rit.edu> On Sun, Aug 19, 2001 at 09:53:17PM -0700, Israel Evans wrote: | Python Server Pages sounds great, but it's a Java/Jython thing and I just | seem to have this prejudice against using java when I have Python. I know | it's not the same thing. I know I'm actually writing in Python and the Java | part only comes in as the final form of the code in much the same way that C | Python ends up being C somewhere down the line. Actually, Python Server Pages (PSP) was just a python CGI script the last time I looked at it. I allows you to embed python in your HTML (with certain tags to identify it). The cgi script executes your python stuff and inserts the output in place of it before it gets sent back to the client. (The name is just similar to a Sun/Java product that offeres similar capabilities) Another interesting solution is PyHTML. This is a modified python parser that takes input like Hello world <body> print "hello world!" and transforms that to HTML and executes the embedded python code. It follows python's indentation is significant structure. I haven't installed it or played with it yet, but it looks very interesting. Then, of course, there are plain CGI scripts if you don't like any of the existing frameworks. HTH, -D From sheila@thinkspot.net Tue Aug 21 18:09:50 2001 From: sheila@thinkspot.net (Sheila King) Date: Tue, 21 Aug 2001 10:09:50 -0700 Subject: [Tutor] [opinions?] Web development... (kind of long) In-Reply-To: <20010821130003.C22548@harmony.cs.rit.edu> References: <AF020C5FC551DD43A4958A679EA16A15017B3D3A@mailcluster.lith.com> <20010821130003.C22548@harmony.cs.rit.edu> Message-ID: <EAE331C049F@kserver.org> On Tue, 21 Aug 2001 13:00:03 -0400, dman <dsh8290@rit.edu> wrote about Re: [Tutor] [opinions?] Web development... (kind of long): :Actually, Python Server Pages (PSP) was just a python CGI script the :last time I looked at it. I allows you to embed python in your HTML :(with certain tags to identify it). Actually, there are something like three different projects right now, referring to themselves as Python Server Pages. One of them is a cgi. One of them does, apparently, use Java. >From this page: http://www.paul.boddie.net/Python/web_modules.html I quote: """ The PSP Confusion Several parties have introduced modules, frameworks and components referring to "Python server pages" and have named them similarly. It is advised that developers be attentive to the origin of such software as well as the name in order to avoid confusion over the different *SP systems available to Python developers. """ Also on that same page are links to several of these different 'PSP' projects. -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From israel@lith.com Tue Aug 21 18:19:24 2001 From: israel@lith.com (Israel Evans) Date: Tue, 21 Aug 2001 10:19:24 -0700 Subject: [Tutor] [opinions?] Web development... (kind of long) Message-ID: <AF020C5FC551DD43A4958A679EA16A15017B3D44@mailcluster.lith.com> Oh That site is great... Something that will point me to all the different options so that I can compare and contrast! Thanks! -----Original Message----- From: Sheila King [mailto:sheila@thinkspot.net] Sent: Tuesday, August 21, 2001 10:10 AM To: dman Cc: 'tutor@python.org' Subject: Re: [Tutor] [opinions?] Web development... (kind of long) On Tue, 21 Aug 2001 13:00:03 -0400, dman <dsh8290@rit.edu> wrote about Re: [Tutor] [opinions?] Web development... (kind of long): :Actually, Python Server Pages (PSP) was just a python CGI script the :last time I looked at it. I allows you to embed python in your HTML :(with certain tags to identify it). Actually, there are something like three different projects right now, referring to themselves as Python Server Pages. One of them is a cgi. One of them does, apparently, use Java. >From this page: http://www.paul.boddie.net/Python/web_modules.html I quote: """ The PSP Confusion Several parties have introduced modules, frameworks and components referring to "Python server pages" and have named them similarly. It is advised that developers be attentive to the origin of such software as well as the name in order to avoid confusion over the different *SP systems available to Python developers. """ Also on that same page are links to several of these different 'PSP' projects. -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From dsh8290@rit.edu Tue Aug 21 18:26:00 2001 From: dsh8290@rit.edu (dman) Date: Tue, 21 Aug 2001 13:26:00 -0400 Subject: [Tutor] [opinions?] Web development... (kind of long) In-Reply-To: <EAE331C049F@kserver.org>; from sheila@thinkspot.net on Tue, Aug 21, 2001 at 10:09:50AM -0700 References: <AF020C5FC551DD43A4958A679EA16A15017B3D3A@mailcluster.lith.com> <20010821130003.C22548@harmony.cs.rit.edu> <EAE331C049F@kserver.org> Message-ID: <20010821132600.A22660@harmony.cs.rit.edu> On Tue, Aug 21, 2001 at 10:09:50AM -0700, Sheila King wrote: | On Tue, 21 Aug 2001 13:00:03 -0400, dman <dsh8290@rit.edu> wrote about | Re: [Tutor] [opinions?] Web development... (kind of long): | | :Actually, Python Server Pages (PSP) was just a python CGI script the | :last time I looked at it. I allows you to embed python in your HTML | :(with certain tags to identify it). | | Actually, there are something like three different projects right now, | referring to themselves as Python Server Pages. One of them is a cgi. | One of them does, apparently, use Java. Oh, ok. It's good to know that, but the names really should be different in some way =p. At least there is a choice :-). -D From alan.gauld@freenet.co.uk Tue Aug 21 18:28:15 2001 From: alan.gauld@freenet.co.uk (alan.gauld@freenet.co.uk) Date: Tue, 21 Aug 2001 18:28:15 +0100 Subject: [Edu-sig] RE: [Tutor] Off topic musings In-Reply-To: <8010912471E0D41189930090278D4E48E154FB@SPAWN> Message-ID: <17360250031353@mailth4.freenet.co.uk> On 21 Aug 01, at 10:26, Morris, Steve wrote: > > On 20 Aug 01, at 22:06, Morris, Steve wrote: > > > Maybe. Really I'm just interested in what exactly a > > > theoretical basis for software engineering would look like. > > I think my problem with this discussion, and the cause of the different > approaches, is that you ask your question in ambiguous terms. You ask for a > "theory of everything" in the generic category of software engineering. Sure but as Insaid in another pist thats because the SOTA papers I was reading were headed "Software Engineering". It is the generally used term, although I note that there does seem to be a trend to other names such as Infomatics. This is probably a good thing, where SE is a subset of Infomatics. > Software engineering is not a science but a discipline, or perhaps a skill, > or maybe just programming. With this I disagree however. The original concept of SE was to get away from that view, to industrialise the production of software, eventually to automate it in the sameway that other engineering disciplines automate production. When an electrical engineer takes a basic requirement and transforms it into a soecification which in turn is synthesised as a circuit the entire process is built on a fundamental understanding of the nature of the raw materials. The point made in the papers was that in SE we do not have that basic understanding. We do not really know the materials with which we work. > the process of writing programs with the imputation that these programs > match some standard; whether it be correctness, or matching the specs, or > merely being useful. That is one aspect but it neglects areas such as the study of softawre entropy, maintenance, performance and automatic production. Arguably these are related to software production, but they are much more than just writing programs. > What else would a theory of "software engineering" address. Indeed, thats why I probably should be saying CS or Infomatics. But the basic question remains valid. > I would like you to restate your query with a better idea of the specific > questions you are trying to answer. OK, I'll try again. Basically I was asking two questions: 1) Given the SOTA papers repeated insistence that to make further significant progress we need a better understanding of xxxx where xxxx is whatever fundamental subject matter underpins CS. I therefore ask, What would xxx look like so that we might study it? 2) My personal guess is that xxx is "information" and that one approach would be to model it ina layered fashion. Has anyone else done this? OIf so where can I get a reerence? Is that any clearer? Alan g From israel@lith.com Tue Aug 21 18:54:13 2001 From: israel@lith.com (Israel Evans) Date: Tue, 21 Aug 2001 10:54:13 -0700 Subject: [Tutor] [opinions?] Web development... (kind of long) Message-ID: <AF020C5FC551DD43A4958A679EA16A15017B3D46@mailcluster.lith.com> Yeah, having multiple projects all calling themselves similarly is just asking for a holy war ;)... I'm PSP No I'm PSP We are the Only true PSPers! Nu-uh! Uh Huh! THPPPPPT! -----Original Message----- From: dman [mailto:dsh8290@rit.edu] Sent: Tuesday, August 21, 2001 10:26 AM To: 'tutor@python.org' Subject: Re: [Tutor] [opinions?] Web development... (kind of long) On Tue, Aug 21, 2001 at 10:09:50AM -0700, Sheila King wrote: | On Tue, 21 Aug 2001 13:00:03 -0400, dman <dsh8290@rit.edu> wrote about | Re: [Tutor] [opinions?] Web development... (kind of long): | | :Actually, Python Server Pages (PSP) was just a python CGI script the | :last time I looked at it. I allows you to embed python in your HTML | :(with certain tags to identify it). | | Actually, there are something like three different projects right now, | referring to themselves as Python Server Pages. One of them is a cgi. | One of them does, apparently, use Java. Oh, ok. It's good to know that, but the names really should be different in some way =p. At least there is a choice :-). -D _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From stappers@macwheel.xs4all.nl Tue Aug 21 20:23:21 2001 From: stappers@macwheel.xs4all.nl (Geert Stappers) Date: Tue, 21 Aug 2001 21:23:21 +0200 Subject: [Tutor] [Q] Newbie's question on Python graphics In-Reply-To: <20010821125057.B22548@harmony.cs.rit.edu> References: <005c01c12a6c$2bb01880$95757e82@visit2>; from ylee12@uiuc.edu on Tue, Aug 21, 2001 at 11:07:41AM -0700 <005c01c12a6c$2bb01880$95757e82@visit2> Message-ID: <v04003a16b7a8653316c2@[172.24.0.6]> At 18:50 +0200 8/21/01, dman wrote: >On Tue, Aug 21, 2001 at 11:07:41AM -0700, Young-Jin Lee wrote: >| Hi, all. I'm new to Python and I have a question on the Python >| graphics. > >It depends on what you mean by "graphics". > >| Most of the document I read doesn't tell much about graphics >| programming. I need a kind of 2D drawing functionality, drawing a >| line, circle, and oval, translate them, and rotate them. Is there a >| good tutorial or whatever for this topic? > >This sounds like you are talking about GUI toolkit functionality, >rather than graphic (ie JPEG) manipulation. Most python docs won't >talk much about GUIs because there are many different toolkits that >can be used from Python. > >| I also need to know if a Java application can call these drawing >| method through the imbedded Python (Jython module). I heard if the >| drawing routine or any Python routine is dependent on any C API, a >| Java application cannot use it through the imbedded Python. > >If you are using Jython then you can only use stuff that is pure >python or accessible from Java. Most of python's extensions (and most >GUI toolkits too) depend on some C stuff and aren't naturally >accessible from Java. The most natural GUI toolkit to use from >Java/Jython is Swing. See > > http://java.sun.com/j2se/1.3/docs/api/index.html > >http://developer.java.sun.com/developer/onlineTraining/GUI/Swing1/shortcourse.ht >ml > >for more details on swing. > A few days ago there was here a pointer to wxpython check out http://www.wxpython.org/wxpshots.php Groet Geert Stappers --------------------- Hit the right key to continue From alan.gauld@freenet.co.uk Tue Aug 21 21:49:09 2001 From: alan.gauld@freenet.co.uk (alan.gauld@freenet.co.uk) Date: Tue, 21 Aug 2001 21:49:09 +0100 Subject: [Edu-sig] RE: [Tutor] Off topic musings In-Reply-To: <17360250031353@mailth4.freenet.co.uk> References: <8010912471E0D41189930090278D4E48E154FB@SPAWN> Message-ID: <20563493757340@mailth4.freenet.co.uk> On 21 Aug 01, at 18:28, alan.gauld@freenet.co.uk wrote: > approach would be to model it ina layered fashion. Has anyone > else done this? OIf so where can I get a reerence? 3 typos in two lines - Doh! My new mail client has a spell checker, I really must get used to using it before I send. Sorry for that. Alan G From dsh8290@rit.edu Tue Aug 21 22:13:23 2001 From: dsh8290@rit.edu (dman) Date: Tue, 21 Aug 2001 17:13:23 -0400 Subject: [Tutor] [Q] Newbie's question on Python graphics In-Reply-To: <v04003a16b7a8653316c2@[172.24.0.6]>; from stappers@macwheel.xs4all.nl on Tue, Aug 21, 2001 at 09:23:21PM +0200 References: <"from <005c01c12a6c$2bb01880$95757e82@visit2> <20010821125057.B22548@harmony.cs.rit.edu> <v04003a16b7a8653316c2@[172.24.0.6]> Message-ID: <20010821171323.B22871@harmony.cs.rit.edu> On Tue, Aug 21, 2001 at 09:23:21PM +0200, Geert Stappers wrote: ... | A few days ago there was here a pointer to wxpython | check out http://www.wxpython.org/wxpshots.php wxPython is nice, but it is a set of C++ extensions to Python to wrap the C++ written wxWindows toolkit and isn't accessible from Jython or Java unless you write JNI to wrap wxWindows (or use RPC of some sort, or ILU or something else). -D From billferreira@compuserve.com Mon Aug 20 03:27:14 2001 From: billferreira@compuserve.com (Bill Ferreira) Date: Sun, 19 Aug 2001 20:27:14 -0600 Subject: [Tutor] Problem with copy Message-ID: <5.1.0.14.2.20010819201700.00a739e8@pop.compuserve.com> "copy" is not making a copy until I change the source value so I guess I'm doing something wrong, any suggestions? >>> import copy >>> x=1 >>> ix=copy.copy(x) >>> ix is x 1 My understanding is that the purpose of copy is to insure that the target object (ix in this case) is a different object than the source object (x). If I follow up the above code with the following: >>> x = 2 >>> x is ix 0 It certainly seems to me that the "is" operator should have returned 0 in both cases. And now: >>> x = 1 >>> x is ix 1 What's going on here? Thanks, Bill From billferreira@compuserve.com Tue Aug 21 23:32:09 2001 From: billferreira@compuserve.com (Bill Ferreira) Date: Tue, 21 Aug 2001 16:32:09 -0600 Subject: [Tutor] Problem with copy Message-ID: <5.1.0.14.2.20010821163201.00b17618@pop.compuserve.com> "copy" is not making a copy until I change the source value so I guess I'm doing something wrong, any suggestions? >>> import copy >>> x=1 >>> ix=copy.copy(x) >>> ix is x 1 My understanding is that the purpose of copy is to insure that the target object (ix in this case) is a different object than the source object (x). If I follow up the above code with the following: >>> x = 2 >>> x is ix 0 It certainly seems to me that the "is" operator should have returned 0 in both cases. And now: >>> x = 1 >>> x is ix 1 What's going on here? Thanks, Bill From tescoil@irtc.net Tue Aug 21 23:48:20 2001 From: tescoil@irtc.net (Tesla Coil) Date: Tue, 21 Aug 2001 17:48:20 -0500 Subject: [Tutor] Problem with copy References: <5.1.0.14.2.20010821163201.00b17618@pop.compuserve.com> Message-ID: <3B82E534.1E6287FA@irtc.net> 21 Aug 2001, Bill Ferreira wrote: > My understanding is that the purpose of copy is to > insure that the target object (ix in this case) is > a different object than the source object (x). copy.copy is a shallow copy. >>> import copy >>> x=1 >>> ix = copy.deepcopy(x) >>> ix is x 1 >>> x = 2 >>> x is ix 0 From lsloan@umich.edu Wed Aug 22 00:14:31 2001 From: lsloan@umich.edu (Lance E Sloan) Date: Tue, 21 Aug 2001 19:14:31 -0400 Subject: [Tutor] Re: [opinions?] Web development... (kind of long) In-Reply-To: Your message of "Tue, 21 Aug 2001 13:00:03 EDT." <20010821130003.C22548@harmony.cs.rit.edu> Message-ID: <200108212314.TAA05265@birds.us.itd.umich.edu> dman wrote: > Then, of course, there are plain CGI scripts if you don't like any of > the existing frameworks. I'll second that suggestion! I'm fairly new to Python, I've only been using it for about four months. I write CGIs for other departments around the Univ. of Michigan. I've had a very good first experience with Python when my boss assigned me to a project to write scheduling CGIs for our hospital. The doctor in charge requested that it be done in Python and even agreed to spend more time and money for that feature. I started with some trepidation, but I can now say that Python is my language of choice. My Python CGI development kit is pretty simple. I use a fairly recent verson of Python (v2.0), DCOracle module, DocumentTemplate module (ripped from Zope), and vi. It beats the pants off of using a similar kit I assembled for development with Perl. I probably should have jumped right into using Zope entirely, but I will have to work my way up to that. In addition to my own comfort of writing CGIs for a webserver and having trouble making myself develop object orientedly, I didn't get much support from our webmasters to install Zope on their servers. I'm working on it. My favorite part of this kit has to be DocumentTemplate. It's very powerful, similar in some ways to PyHTML, according to dman's description. -- Lance E Sloan Web Services, Univ. of Michigan: Full-service Web and database design, development, and hosting. Specializing in Python & Perl CGIs. http://websvcs.itd.umich.edu/ - "Putting U on the Web" From bill-bell@bill-bell.hamilton.on.ca Wed Aug 22 00:17:28 2001 From: bill-bell@bill-bell.hamilton.on.ca (Bill Bell) Date: Tue, 21 Aug 2001 19:17:28 -0400 Subject: [Tutor] Re: [Q] Newbie's question on Python graphics In-Reply-To: <E15ZK4z-0001u9-00@mail.python.org> Message-ID: <3B82B3C8.5200.10963D7@localhost> "Young-Jin Lee" <ylee12@uiuc.edu> wrote, in part: > ... and I have a question on the Python graphics. ... I need a kind > of 2D drawing functionality, drawing a line, circle, and oval, > translate them, and rotate them. Is there a good tutorial or > whatever for this topic? You mention only geometric objects (not user interface objects such as listboxes and buttons). One possibility you might consider is called VPython. I have not built anything using it myself. However, VPython does seem to produce some startling graphics for very little coding. From israel@lith.com Wed Aug 22 00:24:45 2001 From: israel@lith.com (Israel Evans) Date: Tue, 21 Aug 2001 16:24:45 -0700 Subject: [Tutor] Re: Web development... Message-ID: <AF020C5FC551DD43A4958A679EA16A15017B3D4C@mailcluster.lith.com> In my search for web dev stuff, I found Skunkweb, an extensible, scalable and easy to use application server written in Python. http://skunkweb.sourceforge.net/about.html >From the literature, it seems nicer than Zope, and even cooler than webware. It's a *nux biased setup, but it seems pretty cool. I haven't actualy used it, but the makers say that it's really cool. Since I've talked to people on their mailing list, it seems I can start doing things the way I wanted to start doing things. I've also been looking at OpenACS ( http://openacs.org/index.adp ) for the newsletter/community site I wanted to set up. It's like ArsDigita's ACS but it's set up so that it can be run with PostGres and on a *nix Box rather than being constrained to Solaris and Windows 2000. The only scary thing is Java and I don't know if that's really a scary thing. Especially if I can write Jython. The AOLServer does use TCL but I've heard that there are Python bindings even for that. -----Original Message----- From: Lance E Sloan [mailto:lsloan@umich.edu] Sent: Tuesday, August 21, 2001 4:15 PM To: 'tutor@python.org' Subject: [Tutor] Re: [opinions?] Web development... (kind of long) dman wrote: > Then, of course, there are plain CGI scripts if you don't like any of > the existing frameworks. I'll second that suggestion! I'm fairly new to Python, I've only been using it for about four months. I write CGIs for other departments around the Univ. of Michigan. I've had a very good first experience with Python when my boss assigned me to a project to write scheduling CGIs for our hospital. The doctor in charge requested that it be done in Python and even agreed to spend more time and money for that feature. I started with some trepidation, but I can now say that Python is my language of choice. My Python CGI development kit is pretty simple. I use a fairly recent verson of Python (v2.0), DCOracle module, DocumentTemplate module (ripped from Zope), and vi. It beats the pants off of using a similar kit I assembled for development with Perl. I probably should have jumped right into using Zope entirely, but I will have to work my way up to that. In addition to my own comfort of writing CGIs for a webserver and having trouble making myself develop object orientedly, I didn't get much support from our webmasters to install Zope on their servers. I'm working on it. My favorite part of this kit has to be DocumentTemplate. It's very powerful, similar in some ways to PyHTML, according to dman's description. -- Lance E Sloan Web Services, Univ. of Michigan: Full-service Web and database design, development, and hosting. Specializing in Python & Perl CGIs. http://websvcs.itd.umich.edu/ - "Putting U on the Web" _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From scarblac@pino.selwerd.nl Wed Aug 22 00:20:38 2001 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Wed, 22 Aug 2001 01:20:38 +0200 Subject: [Tutor] Problem with copy In-Reply-To: <5.1.0.14.2.20010819201700.00a739e8@pop.compuserve.com>; from billferreira@compuserve.com on Sun, Aug 19, 2001 at 08:27:14PM -0600 References: <5.1.0.14.2.20010819201700.00a739e8@pop.compuserve.com> Message-ID: <20010822012038.A1523@pino.selwerd.nl> On 0, Bill Ferreira <billferreira@compuserve.com> wrote: > "copy" is not making a copy until I change the source value so I guess I'm > doing something wrong, any suggestions? > > >>> import copy > >>> x=1 > >>> ix=copy.copy(x) > >>> ix is x > 1 > > My understanding is that the purpose of copy is to insure that the target > object (ix in this case) is a different object than the source object (x). > If I follow up the above code with the following: > > >>> x = 2 > >>> x is ix > 0 > > It certainly seems to me that the "is" operator should have returned 0 in > both cases. And now: > > >>> x = 1 > >>> x is ix > 1 > > What's going on here? In short, all object in your program that are the integer 1 will be the same object. It's cached. This is true for all numbers -1 to 100, if I recall correctly, in the current version. It's also true for interned strings, and other exceptional immutable values. This is never a problem - since integers are immutable, it doesn't matter if two variables that have value 1 happen to refer to the same object. copy() is meant to be used on more complex data structures, like lists; so that changing the new list doesn't change the old one. Immutables like integers can't be changed anyway, so copying isn't very useful on integers, it just takes extra memory space. Without knowing what you're trying to do, I can't give more than this kind of general comment... -- Remco Gerlich From dyoo@hkn.eecs.berkeley.edu Wed Aug 22 00:52:22 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 21 Aug 2001 16:52:22 -0700 (PDT) Subject: [Tutor] Problem with copy In-Reply-To: <5.1.0.14.2.20010821163201.00b17618@pop.compuserve.com> Message-ID: <Pine.LNX.4.21.0108211634120.11605-100000@hkn.eecs.berkeley.edu> On Tue, 21 Aug 2001, Bill Ferreira wrote: > "copy" is not making a copy until I change the source value so I guess I'm > doing something wrong, any suggestions? > > >>> import copy > >>> x=1 > >>> ix=copy.copy(x) > >>> ix is x > 1 > > My understanding is that the purpose of copy is to insure that the target > object (ix in this case) is a different object than the source object (x). [Note: this question is fraught with trickiness.] Try the copy.deepcopy() function instead: it does what you're thinking of. copy.copy() does a shallow copy, which only copies the toplevel part of the structure. It's shallow because the inner structure is still shared. The distinction between shallow copying and deep copying only comes up in nested structures, like lists within lists. What you're running into is something slightly different. Let's look: > If I follow up the above code with the following: > > >>> x = 2 > >>> x is ix > 0 > > It certainly seems to me that the "is" operator should have returned 0 in > both cases. And now: Try a larger number greater than 101. Python will automatically cache integers less that or equal to 101 to save space: ### >>> for i in range(150): ... x1 = i + 0 ... x2 = i + 0 ... if x1 is not x2: ... print "Hey, no more cache starting from", x1 ... break ... Hey, no more cache starting from 100 ### My mistake: it stops caching the numbers at 100. Here's what I think Python's doing: on integer addition, it actually does construct a whole new number. However, it then checks to see if it's between 0 and 99. If so, it abandons that value, and returns one out of the cache. However, your test with copy.copy() obscures one very tricky point: copy.copy() already knows that numbers are immutable, and so it can optimize by not copying at all! Let's take a look at some of the code in copy.copy(): ### def copy(x): """Shallow copy operation on arbitrary Python objects. See the module's __doc__ string for more info. """ try: copierfunction = _copy_dispatch[type(x)] ... ### Here's an example of dispatch-based programming based on type. We know that we're copying integers, so let's take a look at the copier for integers: ### # slightly edited for presentation def _copy_atomic(x): return x d[types.IntType] = _copy_atomic ### That is, copy.copy() doesn't do anything if it sees an "atomic" immutable type like an integer. We can test this empirically: ### >>> for i in range(150): ... x = copy.copy(i) ... if i is not x: ... print "Hey, no more caching behavior, starting from", x ... break ... >>> # Hey, nothing happened! ### That was very very tricky. *grin* Hope this helps! From proudsoul@hotmail.com Wed Aug 22 08:28:13 2001 From: proudsoul@hotmail.com (Proud Newbie) Date: Wed, 22 Aug 2001 16:28:13 +0900 Subject: [Tutor] How can use Windows Exlporer's browse file method in a python script (Tkinter)? Message-ID: <LAW2-OE37G9IVirrvcL000028cb@hotmail.com> How can use Windows Exlporer's browse file method in a python script (Tkinter)? Say, I want to use Windows Exlporer's browse file method to let users browse and locate a file. How do I do that? Thanks a million. SN From xiaowp@chinaren.com Wed Aug 22 13:54:10 2001 From: xiaowp@chinaren.com (Gary) Date: Wed, 22 Aug 2001 20:54:10 +0800 Subject: [Tutor] How to insert Chinese into Tkinter Text widget? Message-ID: <200108221206.f7MC6fa12124@mh.bit.edu.cn> Hello, all: I have a question about Tkinter. In my Python script, I use a Tkinter Text widget and I want to insert a Chinese string into it. I write it like this: text.insert(END, Chinese-str) Here 'text' is a Text widget and the 'Chinese-str' is the string I want to display. To my suprise, it doesn't work. Should I use UNICODE? I'm really a freshman, please help me. Thanks ahead. Best Regards, Gary ======================= xiaowp@chinaren.com 2001-08-21 ======================== From alan.gauld@bt.com Wed Aug 22 17:56:59 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 22 Aug 2001 17:56:59 +0100 Subject: [Tutor] How can use Windows Exlporer's browse file method in a python script (Tkinter)? Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BECA@mbtlipnt02.btlabs.bt.co.uk> > How can use Windows Exlporer's browse file method in a python script > (Tkinter)? You can do it via the PythonWin package which gives access to the win32 API via MFC but I'm not sure why you';d want to? Whats wrong with the built in Tkinter filebrowser? It will be easier to inrtegrate with the rest of your Tkinter program IMHO. Alan g From alan.gauld@bt.com Wed Aug 22 17:58:53 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 22 Aug 2001 17:58:53 +0100 Subject: [Tutor] How to insert Chinese into Tkinter Text widget? Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BECB@mbtlipnt02.btlabs.bt.co.uk> > I have a question about Tkinter. In my Python script, I use a > Tkinter Text widget and I want to insert a Chinese string into > it. I have no idea, but its probably a Tk issue rather than Tkinter so I'd browse the Tk web sites and newsgroups as a first port of call. Translate the answer into Tkinter once you kow how Tk does it... Alan G From sheila@thinkspot.net Thu Aug 23 00:16:13 2001 From: sheila@thinkspot.net (Sheila King) Date: Wed, 22 Aug 2001 16:16:13 -0700 Subject: [Tutor] map, filter and lambda functions Message-ID: <1521065D5D75@kserver.org> I feel so smart, today! I finally figured out a situation where those map, lambda and filter functions come in handy, and they are making sense to me, now! I am running a script on my website, to screen my incoming e-mail. I have a textfile on the site, that has e-mail addresses in it, and I read them into a list and compare parts of the message headers against the list to see if I want the e-mail or not. (That's a simplified explanation, but the essential idea.) Anyhow, I think I have really improved the code, by removing some lookups on the list, and some loops and stuff. Here is an earlier version of a part of the code: checklist = string.split(filetext, "\n") for item in checklist: if item != '': itemIdx = checklist.index(item) item = string.strip(item) item = string.upper(item) checklist[itemIdx] = item else: checklist.remove(item) Here's the new, shorter version: checklist = string.split(filetext, "\n") checklist = filter(lambda x: x != '', checklist) checklist = map(lambda x: string.strip(x), checklist) checklist = map(lambda x: string.upper(x), checklist) The thing is, I can't use list comprehensions in this script, since my webhost is only running Python 1.5.2. Given this restriction, is my second version the best (most efficient) way of handling such a code block? Is there a way to do this without lambda functions, or are they pretty much needed in this case? -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From allan.crooks@btinternet.com Thu Aug 23 01:01:58 2001 From: allan.crooks@btinternet.com (Allan Crooks) Date: Thu, 23 Aug 2001 01:01:58 +0100 Subject: [Tutor] map, filter and lambda functions In-Reply-To: <1521065D5D75@kserver.org> Message-ID: <3B845606.22195.2F590AD@localhost> On 22 Aug 2001, at 16:16, Sheila King wrote: > Here's the new, shorter version: > > checklist = string.split(filetext, "\n") > checklist = filter(lambda x: x != '', checklist) > checklist = map(lambda x: string.strip(x), checklist) > checklist = map(lambda x: string.upper(x), checklist) > > The thing is, I can't use list comprehensions in this script, since my > webhost is only running Python 1.5.2. Given this restriction, is my > second version the best (most efficient) way of handling such a code > block? My opinion is, the best version is the one which makes you smile more. :) Out of the two, I like the second one more. > Is there a way to do this without lambda functions, or are they > pretty much needed in this case? You don't need to put lambda functions, you can just provide string.strip and string.upper without using lambda what-so-ever. I would personally, however, write this: checklist = map (lambda x: x.strip().upper(), checklist) or, if Python 1.5.2 doesn't like that: checklist = map (lambda x: string.upper(string.strip(x)), checklist) Which reduces it down to one line. But you might not want that. You could also replace the lambda function that's used in filter with "None". IIRC, that will only return objects which have a positive truth value (in the case of strings, this would only be non-empty strings). If you were really daring, you could put all that into one large function: checklist = map (string.upper, map (string.strip, filter (None, string.split(filetext, "\n")))) That *might* work, I can't be bothered to test it. :) Use whatever version you are happiest with. I'd go with whatever version is easier to understand when you read it, which, out of the two you've given us, would be the second one. Allan. From bill-bell@bill-bell.hamilton.on.ca Thu Aug 23 01:58:43 2001 From: bill-bell@bill-bell.hamilton.on.ca (Bill Bell) Date: Wed, 22 Aug 2001 20:58:43 -0400 Subject: [Tutor] Re: How can use Windows Exlporer's browse file method in a python script (Tkinter)? In-Reply-To: <E15ZaRH-0006A6-00@mail.python.org> Message-ID: <3B841D03.105.C2B831@localhost> "Proud Newbie" <proudsoul@hotmail.com> wrote, in part: > How can use Windows Exlporer's browse file method in a python script > (Tkinter)? Say, I want to use Windows Exlporer's browse file method to > let users browse and locate a file. How do I do that? import win32ui SAVEAS = 0 OPEN = 1 dlg = win32ui.CreateFileDialog( SAVEAS ) dlg.DoModal() For a less rarified example, take a look at C:\Python21\win32\scripts\regsetup.py or search your Python21 folder for 'CreateFileDialog'. Documentation is available by searching the ActiveState doc on the same term. Bill From dyoo@hkn.eecs.berkeley.edu Thu Aug 23 02:02:41 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 22 Aug 2001 18:02:41 -0700 (PDT) Subject: [Tutor] map, filter and lambda functions In-Reply-To: <1521065D5D75@kserver.org> Message-ID: <Pine.LNX.4.21.0108221800510.1360-100000@hkn.eecs.berkeley.edu> > Here is an earlier version of a part of the code: > > checklist = string.split(filetext, "\n") > for item in checklist: > if item != '': > itemIdx = checklist.index(item) > item = string.strip(item) > item = string.upper(item) > checklist[itemIdx] = item > else: > checklist.remove(item) > > > Here's the new, shorter version: > > checklist = string.split(filetext, "\n") > checklist = filter(lambda x: x != '', checklist) > checklist = map(lambda x: string.strip(x), checklist) > checklist = map(lambda x: string.upper(x), checklist) Yes, this looks good! Glad it clicks now! From sheila@thinkspot.net Thu Aug 23 04:59:25 2001 From: sheila@thinkspot.net (Sheila King) Date: Wed, 22 Aug 2001 20:59:25 -0700 Subject: [Tutor] map, filter and lambda functions In-Reply-To: <3B845606.22195.2F590AD@localhost> References: <1521065D5D75@kserver.org> <3B845606.22195.2F590AD@localhost> Message-ID: <1623A278005B@kserver.org> On Thu, 23 Aug 2001 01:01:58 +0100, "Allan Crooks" <allan.crooks@btinternet.com> wrote about Re: [Tutor] map, filter and lambda functions: :On 22 Aug 2001, at 16:16, Sheila King wrote: : :> Here's the new, shorter version: :> :> checklist = string.split(filetext, "\n") :> checklist = filter(lambda x: x != '', checklist) :> checklist = map(lambda x: string.strip(x), checklist) :> checklist = map(lambda x: string.upper(x), checklist) :My opinion is, the best version is the one which makes you smile :more. :) Out of the two, I like the second one more. Well, I really was asking for an outside opinion, and someone who knew a bit more about optimizing the code. :> Is there a way to do this without lambda functions, or are they :> pretty much needed in this case? : :You don't need to put lambda functions, you can just provide :string.strip and string.upper without using lambda what-so-ever. Are you sure that you can do this without lambda? I tried today, and couldn't get it to work without lambda. >>> mylist ['a', 'b', 'c', ''] >>> mylist = map(string.upper(x), mylist) Traceback (most recent call last): File "<pyshell#6>", line 1, in ? mylist = map(string.upper(x), mylist) NameError: name 'x' is not defined >>> mylist = map(string.upper(), mylist) Traceback (most recent call last): File "<pyshell#7>", line 1, in ? mylist = map(string.upper(), mylist) TypeError: upper() takes exactly 1 argument (0 given) >>> If I do it with no argument, it complains that it requires an argument. If I put an argument there, it complains that it has never heard of that variable before. That's what prompted me to try the lambda functions. I figured, I could thereby (essentially) declare the variable x before I used it. :I would personally, however, write this: : :checklist = map (lambda x: x.strip().upper(), checklist) : :or, if Python 1.5.2 doesn't like that: No, 1.5.2 requires the string module to do string functions. :checklist = map (lambda x: string.upper(string.strip(x)), checklist) : :Which reduces it down to one line. But you might not want that. Not too readable, IMO. :You could also replace the lambda function that's used in filter with :"None". IIRC, that will only return objects which have a positive :truth value (in the case of strings, this would only be non-empty :strings). Hmm. That seems to work: >>> mylist ['a', 'b', 'c', ''] >>> filter(None, mylist) ['a', 'b', 'c'] >>> Now I'm curious as to *why* it works. 'None' doesn't strike me as a function that returns a value. Although, it says in the documentation somewhere, that None on map works as the identity function. This didn't bother me, though. It seemed like "No map...gives you same thing you started with." :If you were really daring, you could put all that into one large :function: : :checklist = map (string.upper, map (string.strip, filter (None, :string.split(filetext, "\n")))) : :That *might* work, I can't be bothered to test it. :) OK, two remarks on this: First of all, does putting it all in one line make it run faster or more efficiently? My intuition says, "No". Secondly, it's definitely harder to follow. I would be very disinclined to writing it like that. Having the code be compressed into a single line really isn't that appealing. :Use whatever version you are happiest with. I'd go with whatever :version is easier to understand when you read it, which, out of the :two you've given us, would be the second one. That's an interesting remark. Until today, I wouldn't have found those filter and map, or lambda functions easy to read and understand. Something clicked today, and now I'm fine with them. But before, I would have preferred the nested loop stuff I had originally. -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From ignacio@openservices.net Thu Aug 23 05:27:17 2001 From: ignacio@openservices.net (Ignacio Vazquez-Abrams) Date: Thu, 23 Aug 2001 00:27:17 -0400 (EDT) Subject: [Tutor] map, filter and lambda functions In-Reply-To: <1623A278005B@kserver.org> Message-ID: <Pine.LNX.4.33.0108230024550.14247-100000@terbidium.openservices.net> On Wed, 22 Aug 2001, Sheila King wrote: > Are you sure that you can do this without lambda? I tried today, and > couldn't get it to work without lambda. > > >>> mylist > ['a', 'b', 'c', ''] > >>> mylist = map(string.upper(x), mylist) > Traceback (most recent call last): > File "<pyshell#6>", line 1, in ? > mylist = map(string.upper(x), mylist) > NameError: name 'x' is not defined > >>> mylist = map(string.upper(), mylist) > Traceback (most recent call last): > File "<pyshell#7>", line 1, in ? > mylist = map(string.upper(), mylist) > TypeError: upper() takes exactly 1 argument (0 given) > >>> > > If I do it with no argument, it complains that it requires an argument. > If I put an argument there, it complains that it has never heard of that > variable before. That's because the first argument to map has to be a function object; you'd have to use map(string.upper, mylist). -- Ignacio Vazquez-Abrams <ignacio@openservices.net> From sheila@thinkspot.net Thu Aug 23 05:35:09 2001 From: sheila@thinkspot.net (Sheila King) Date: Wed, 22 Aug 2001 21:35:09 -0700 Subject: [Tutor] map, filter and lambda functions In-Reply-To: <Pine.LNX.4.33.0108230024550.14247-100000@terbidium.openservices.net> References: <1623A278005B@kserver.org> <Pine.LNX.4.33.0108230024550.14247-100000@terbidium.openservices.net> Message-ID: <16441BC80BD4@kserver.org> On Thu, 23 Aug 2001 00:27:17 -0400 (EDT), Ignacio Vazquez-Abrams <ignacio@openservices.net> wrote about Re: [Tutor] map, filter and lambda functions: :On Wed, 22 Aug 2001, Sheila King wrote: :> >>> mylist :> ['a', 'b', 'c', ''] :> >>> mylist = map(string.upper(x), mylist) :> Traceback (most recent call last): :> File "<pyshell#6>", line 1, in ? :> mylist = map(string.upper(x), mylist) :> NameError: name 'x' is not defined :> >>> mylist = map(string.upper(), mylist) :> Traceback (most recent call last): :> File "<pyshell#7>", line 1, in ? :> mylist = map(string.upper(), mylist) :> TypeError: upper() takes exactly 1 argument (0 given) :> >>> :> :> If I do it with no argument, it complains that it requires an argument. :> If I put an argument there, it complains that it has never heard of that :> variable before. : :That's because the first argument to map has to be a function object; you'd :have to use map(string.upper, mylist). Ah, thanks. That's what I was missing. It certainly wasn't clear to me from anything that I had read, that it was supposed to be a function OBJECT as opposed to a function invocation. For example, from the Python docs: 2.3 Built-in Functions filter(function, list) Construct a list from those elements of list for which function returns true. If list is a string or a tuple, the result also has that type; otherwise it is always a list. If function is None, the identity function is assumed, i.e. all elements of list that are false (zero or empty) are removed. Maybe I should have picked up on that. But I certainly didn't. -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From allan.crooks@btinternet.com Thu Aug 23 05:55:55 2001 From: allan.crooks@btinternet.com (Allan Crooks) Date: Thu, 23 Aug 2001 05:55:55 +0100 Subject: [Tutor] map, filter and lambda functions In-Reply-To: <1623A278005B@kserver.org> References: <3B845606.22195.2F590AD@localhost> Message-ID: <3B849AEB.28396.402B905@localhost> On 22 Aug 2001, at 20:59, Sheila King wrote: > :> checklist = string.split(filetext, "\n") > :> checklist = filter(lambda x: x != '', checklist) > :> checklist = map(lambda x: string.strip(x), checklist) > :> checklist = map(lambda x: string.upper(x), checklist) > > :My opinion is, the best version is the one which makes you smile > :more. :) Out of the two, I like the second one more. > > Well, I really was asking for an outside opinion, and someone who knew > a bit more about optimizing the code. The way I see it, the code is fairly optimal. If you want it more optimal, you'd probably have to write it in C. :) > Are you sure that you can do this without lambda? I tried today, and > couldn't get it to work without lambda. > > >>> mylist > ['a', 'b', 'c', ''] > >>> mylist = map(string.upper(x), mylist) > Traceback (most recent call last): > File "<pyshell#6>", line 1, in ? > mylist = map(string.upper(x), mylist) > NameError: name 'x' is not defined > >>> mylist = map(string.upper(), mylist) > Traceback (most recent call last): > File "<pyshell#7>", line 1, in ? > mylist = map(string.upper(), mylist) > TypeError: upper() takes exactly 1 argument (0 given) > >>> Let me show you this little code fragment: >>> mylist = ['a', 'b', 'c', ''] >>> import string >>> map (string.upper, mylist) ['A', 'B', 'C', ''] >>> As you can see, it does work. map takes a function and a sequence. It then takes each element in the sequence and then attempts to call that function with the element as an argument. string.upper() doesn't work, because you're trying to run the function with no arguments (as it says). string.upper(x) doesn't work either, because x isn't defined anywhere (as it says again). string.upper works, because map needs to be passed a function which it can use. So, general rule is, if you have a function f: a = f # a holds the function f b = f(..someargs...) # b holds the result of running f with some args It's a common mistake that is made, people mean to pass a function around, but accidently end up executing the function itself. > :checklist = map (lambda x: string.upper(string.strip(x)), checklist) > : :Which reduces it down to one line. But you might not want that. > > Not too readable, IMO. Agreed. But it's a great way of doing things if we were programming in a functional language. :) > Hmm. That seems to work: > > >>> mylist > ['a', 'b', 'c', ''] > >>> filter(None, mylist) > ['a', 'b', 'c'] > >>> > > Now I'm curious as to *why* it works. 'None' doesn't strike me as a > function that returns a value. Although, it says in the documentation > somewhere, that None on map works as the identity function. This > didn't bother me, though. It seemed like "No map...gives you same > thing you started with." *Why* it works? Just because filter is designed to work that way. Initially I was going to suggest a way of doing that, but instead of None, I was going to suggest the truth function from the operator module. None certainly isn't a function though. > > :If you were really daring, you could put all that into one large > :function: : :checklist = map (string.upper, map (string.strip, filter > (None, :string.split(filetext, "\n")))) : :That *might* work, I can't > be bothered to test it. :) > > OK, two remarks on this: > First of all, does putting it all in one line make it run faster or > more efficiently? My intuition says, "No". It might make it ever so slightly faster, but by "slightly faster", I mean that *technically* it might be faster, but you wouldn't notice it. You only make one assignment to checklist, instead of four. Technically, there's the overhead of assigning a value to a name, but it's far from noticable. > Secondly, it's definitely harder to follow. I would be very > disinclined to writing it like that. Having the code be compressed > into a single line really isn't that appealing. I completely agree with you there. Just because you can do something, doesn't mean you should. :) Besides, considering Python code is meant to be readable, it would be a bad idea anyway. But I was showing you another way of putting it, "just because I could". :) > :Use whatever version you are happiest with. I'd go with whatever > :version is easier to understand when you read it, which, out of the > :two you've given us, would be the second one. > > That's an interesting remark. Until today, I wouldn't have found those > filter and map, or lambda functions easy to read and understand. > Something clicked today, and now I'm fine with them. But before, I > would have preferred the nested loop stuff I had originally. It's just something that comes with practice I suppose. The nested loop version was a lot harder to read, but the second version is a lot easier to understand, and a lot shorter too. I know that it's also fairly satisfying when it just "clicks" into place. :) Allan. From allan.crooks@btinternet.com Thu Aug 23 05:55:55 2001 From: allan.crooks@btinternet.com (Allan Crooks) Date: Thu, 23 Aug 2001 05:55:55 +0100 Subject: [Tutor] map, filter and lambda functions In-Reply-To: <1623A278005B@kserver.org> References: <3B845606.22195.2F590AD@localhost> Message-ID: <3B849AEB.28396.402B905@localhost> On 22 Aug 2001, at 20:59, Sheila King wrote: > :> checklist = string.split(filetext, "\n") > :> checklist = filter(lambda x: x != '', checklist) > :> checklist = map(lambda x: string.strip(x), checklist) > :> checklist = map(lambda x: string.upper(x), checklist) > > :My opinion is, the best version is the one which makes you smile > :more. :) Out of the two, I like the second one more. > > Well, I really was asking for an outside opinion, and someone who knew > a bit more about optimizing the code. The way I see it, the code is fairly optimal. If you want it more optimal, you'd probably have to write it in C. :) > Are you sure that you can do this without lambda? I tried today, and > couldn't get it to work without lambda. > > >>> mylist > ['a', 'b', 'c', ''] > >>> mylist = map(string.upper(x), mylist) > Traceback (most recent call last): > File "<pyshell#6>", line 1, in ? > mylist = map(string.upper(x), mylist) > NameError: name 'x' is not defined > >>> mylist = map(string.upper(), mylist) > Traceback (most recent call last): > File "<pyshell#7>", line 1, in ? > mylist = map(string.upper(), mylist) > TypeError: upper() takes exactly 1 argument (0 given) > >>> Let me show you this little code fragment: >>> mylist = ['a', 'b', 'c', ''] >>> import string >>> map (string.upper, mylist) ['A', 'B', 'C', ''] >>> As you can see, it does work. map takes a function and a sequence. It then takes each element in the sequence and then attempts to call that function with the element as an argument. string.upper() doesn't work, because you're trying to run the function with no arguments (as it says). string.upper(x) doesn't work either, because x isn't defined anywhere (as it says again). string.upper works, because map needs to be passed a function which it can use. So, general rule is, if you have a function f: a = f # a holds the function f b = f(..someargs...) # b holds the result of running f with some args It's a common mistake that is made, people mean to pass a function around, but accidently end up executing the function itself. > :checklist = map (lambda x: string.upper(string.strip(x)), checklist) > : :Which reduces it down to one line. But you might not want that. > > Not too readable, IMO. Agreed. But it's a great way of doing things if we were programming in a functional language. :) > Hmm. That seems to work: > > >>> mylist > ['a', 'b', 'c', ''] > >>> filter(None, mylist) > ['a', 'b', 'c'] > >>> > > Now I'm curious as to *why* it works. 'None' doesn't strike me as a > function that returns a value. Although, it says in the documentation > somewhere, that None on map works as the identity function. This > didn't bother me, though. It seemed like "No map...gives you same > thing you started with." *Why* it works? Just because filter is designed to work that way. Initially I was going to suggest a way of doing that, but instead of None, I was going to suggest the truth function from the operator module. None certainly isn't a function though. > > :If you were really daring, you could put all that into one large > :function: : :checklist = map (string.upper, map (string.strip, filter > (None, :string.split(filetext, "\n")))) : :That *might* work, I can't > be bothered to test it. :) > > OK, two remarks on this: > First of all, does putting it all in one line make it run faster or > more efficiently? My intuition says, "No". It might make it ever so slightly faster, but by "slightly faster", I mean that *technically* it might be faster, but you wouldn't notice it. You only make one assignment to checklist, instead of four. Technically, there's the overhead of assigning a value to a name, but it's far from noticable. > Secondly, it's definitely harder to follow. I would be very > disinclined to writing it like that. Having the code be compressed > into a single line really isn't that appealing. I completely agree with you there. Just because you can do something, doesn't mean you should. :) Besides, considering Python code is meant to be readable, it would be a bad idea anyway. But I was showing you another way of putting it, "just because I could". :) > :Use whatever version you are happiest with. I'd go with whatever > :version is easier to understand when you read it, which, out of the > :two you've given us, would be the second one. > > That's an interesting remark. Until today, I wouldn't have found those > filter and map, or lambda functions easy to read and understand. > Something clicked today, and now I'm fine with them. But before, I > would have preferred the nested loop stuff I had originally. It's just something that comes with practice I suppose. The nested loop version was a lot harder to read, but the second version is a lot easier to understand, and a lot shorter too. I know that it's also fairly satisfying when it just "clicks" into place. :) Allan. From allan.crooks@btinternet.com Thu Aug 23 05:55:55 2001 From: allan.crooks@btinternet.com (Allan Crooks) Date: Thu, 23 Aug 2001 05:55:55 +0100 Subject: [Tutor] map, filter and lambda functions In-Reply-To: <1623A278005B@kserver.org> References: <3B845606.22195.2F590AD@localhost> Message-ID: <3B849AEB.28396.402B905@localhost> On 22 Aug 2001, at 20:59, Sheila King wrote: > :> checklist = string.split(filetext, "\n") > :> checklist = filter(lambda x: x != '', checklist) > :> checklist = map(lambda x: string.strip(x), checklist) > :> checklist = map(lambda x: string.upper(x), checklist) > > :My opinion is, the best version is the one which makes you smile > :more. :) Out of the two, I like the second one more. > > Well, I really was asking for an outside opinion, and someone who knew > a bit more about optimizing the code. The way I see it, the code is fairly optimal. If you want it more optimal, you'd probably have to write it in C. :) > Are you sure that you can do this without lambda? I tried today, and > couldn't get it to work without lambda. > > >>> mylist > ['a', 'b', 'c', ''] > >>> mylist = map(string.upper(x), mylist) > Traceback (most recent call last): > File "<pyshell#6>", line 1, in ? > mylist = map(string.upper(x), mylist) > NameError: name 'x' is not defined > >>> mylist = map(string.upper(), mylist) > Traceback (most recent call last): > File "<pyshell#7>", line 1, in ? > mylist = map(string.upper(), mylist) > TypeError: upper() takes exactly 1 argument (0 given) > >>> Let me show you this little code fragment: >>> mylist = ['a', 'b', 'c', ''] >>> import string >>> map (string.upper, mylist) ['A', 'B', 'C', ''] >>> As you can see, it does work. map takes a function and a sequence. It then takes each element in the sequence and then attempts to call that function with the element as an argument. string.upper() doesn't work, because you're trying to run the function with no arguments (as it says). string.upper(x) doesn't work either, because x isn't defined anywhere (as it says again). string.upper works, because map needs to be passed a function which it can use. So, general rule is, if you have a function f: a = f # a holds the function f b = f(..someargs...) # b holds the result of running f with some args It's a common mistake that is made, people mean to pass a function around, but accidently end up executing the function itself. > :checklist = map (lambda x: string.upper(string.strip(x)), checklist) > : :Which reduces it down to one line. But you might not want that. > > Not too readable, IMO. Agreed. But it's a great way of doing things if we were programming in a functional language. :) > Hmm. That seems to work: > > >>> mylist > ['a', 'b', 'c', ''] > >>> filter(None, mylist) > ['a', 'b', 'c'] > >>> > > Now I'm curious as to *why* it works. 'None' doesn't strike me as a > function that returns a value. Although, it says in the documentation > somewhere, that None on map works as the identity function. This > didn't bother me, though. It seemed like "No map...gives you same > thing you started with." *Why* it works? Just because filter is designed to work that way. Initially I was going to suggest a way of doing that, but instead of None, I was going to suggest the truth function from the operator module. None certainly isn't a function though. > > :If you were really daring, you could put all that into one large > :function: : :checklist = map (string.upper, map (string.strip, filter > (None, :string.split(filetext, "\n")))) : :That *might* work, I can't > be bothered to test it. :) > > OK, two remarks on this: > First of all, does putting it all in one line make it run faster or > more efficiently? My intuition says, "No". It might make it ever so slightly faster, but by "slightly faster", I mean that *technically* it might be faster, but you wouldn't notice it. You only make one assignment to checklist, instead of four. Technically, there's the overhead of assigning a value to a name, but it's far from noticable. > Secondly, it's definitely harder to follow. I would be very > disinclined to writing it like that. Having the code be compressed > into a single line really isn't that appealing. I completely agree with you there. Just because you can do something, doesn't mean you should. :) Besides, considering Python code is meant to be readable, it would be a bad idea anyway. But I was showing you another way of putting it, "just because I could". :) > :Use whatever version you are happiest with. I'd go with whatever > :version is easier to understand when you read it, which, out of the > :two you've given us, would be the second one. > > That's an interesting remark. Until today, I wouldn't have found those > filter and map, or lambda functions easy to read and understand. > Something clicked today, and now I'm fine with them. But before, I > would have preferred the nested loop stuff I had originally. It's just something that comes with practice I suppose. The nested loop version was a lot harder to read, but the second version is a lot easier to understand, and a lot shorter too. I know that it's also fairly satisfying when it just "clicks" into place. :) Allan. From r.b.rigilink@chello.nl Thu Aug 23 06:23:50 2001 From: r.b.rigilink@chello.nl (Roeland Rengelink) Date: Thu, 23 Aug 2001 07:23:50 +0200 Subject: [Tutor] map, filter and lambda functions References: <1521065D5D75@kserver.org> Message-ID: <3B849366.BEA77AEB@chello.nl> Sheila King wrote: [snip] > > Here's the new, shorter version: > > checklist = string.split(filetext, "\n") > checklist = filter(lambda x: x != '', checklist) > checklist = map(lambda x: string.strip(x), checklist) > checklist = map(lambda x: string.upper(x), checklist) > > The thing is, I can't use list comprehensions in this script, since my > webhost is only running Python 1.5.2. Given this restriction, is my > second version the best (most efficient) way of handling such a code > block? Is there a way to do this without lambda functions, or are they > pretty much needed in this case?> Hi Sheila, Two things, - map can take any function object as its first argument - filter may take None as its first argument, in which case it will return the sequence of items that evaluate to true. So: checklist = string.split(filetext, '\n') checklist = filter(None, checklist) checklist = map(string.strip, checklist) checklist = map(string.upper, checklist) If checklist is rather long, the last two may be written mor efficiently as: checklist = map(lambda x:string.upper(string.strip(x)), checklist) Hope this helps, Roeland -- r.b.rigilink@chello.nl "Half of what I say is nonsense. Unfortunately I don't know which half" From jodell2@tsn.cc Thu Aug 23 07:29:40 2001 From: jodell2@tsn.cc (Jason O'Dell) Date: Thu, 23 Aug 2001 16:29:40 +1000 Subject: [Tutor] Tkinter canvas movement question... Message-ID: <000801c12b9c$fee07520$a6a616ca@rumpus> This is a multi-part message in MIME format. ------=_NextPart_000_0005_01C12BF0.CEE8E740 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Fellow list users, I JeSo (long time reader, first time poster) come = bearing problems... Ok, using Tkinter, I have the following code, class dude: def __init__(self): self.physical =3D screen.create_oval(30,270,60,300, = fill=3D'white', outline=3D'white') def left(self): screen.move(self.physical, 5, 5) (screen is earlier defined as a Tkinter Canvas widget) and elsewhere i have, circle =3D dude() root.bind_all('<Left>', circle.left()) ...Any ideas why that wont work? It simply draws up everything, with the = object already moved once, without any pressing of left, and future = pressings of left have no effect. Any help on this lil problem would be = appreciated... Also, any suggestions on how I could best put that = binding inside the class itself? Thankyou all... JeSo = -------------------------------------------------------------------------= ----------------------- "You love to hate me, but you wont kill me" - Slayer - Love to Hate. ------=_NextPart_000_0005_01C12BF0.CEE8E740 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML><HEAD> <META content=3D"text/html; charset=3Diso-8859-1" = http-equiv=3DContent-Type> <META content=3D"MSHTML 5.00.2614.3500" name=3DGENERATOR> <STYLE></STYLE> </HEAD> <BODY bgColor=3D#ffffff> <DIV><FONT face=3DArial size=3D2>Fellow list users, I JeSo (long time = reader, first=20 time poster) come bearing problems...</FONT></DIV> <DIV><FONT face=3DArial size=3D2>Ok, using Tkinter, I have the following = code,</FONT></DIV> <DIV><FONT face=3DArial size=3D2></FONT> </DIV> <DIV><FONT face=3DArial size=3D2>class dude:<BR>    def=20 __init__(self):<BR>        = self.physical =3D=20 screen.create_oval(30,270,60,300, fill=3D'white',=20 outline=3D'white')<BR>    def=20 left(self):<BR>       =20 screen.move(self.physical, 5, 5)</FONT></DIV> <DIV><FONT face=3DArial size=3D2> <DIV><FONT face=3DArial size=3D2></FONT> </DIV> <DIV><FONT face=3DArial size=3D2>(screen is earlier defined as a Tkinter = Canvas=20 widget)</FONT></DIV></FONT></DIV> <DIV><FONT face=3DArial size=3D2></FONT> </DIV> <DIV><FONT face=3DArial size=3D2>and elsewhere i have,</FONT></DIV> <DIV><FONT face=3DArial size=3D2></FONT> </DIV> <DIV><FONT face=3DArial size=3D2>circle =3D dude()</FONT></DIV> <DIV><FONT face=3DArial size=3D2>root.bind_all('<Left>',=20 circle.left())</FONT></DIV> <DIV><FONT face=3DArial size=3D2></FONT> </DIV> <DIV><FONT face=3DArial size=3D2>...Any ideas why that wont work? It = simply draws up=20 everything, with the object already moved once, without any pressing of = left,=20 and future pressings of left have no effect. Any help on this lil = problem would=20 be appreciated...  Also, any suggestions on how I could best put = that=20 binding inside the class itself?</FONT></DIV> <DIV><FONT face=3DArial size=3D2>   Thankyou = all...</FONT></DIV> <DIV><FONT face=3DArial size=3D2>      =20 JeSo</FONT></DIV> <DIV> </DIV> <DIV><FONT face=3DArial=20 size=3D2> ----------------------------------------------------------= --------------------------------------</FONT></DIV> <DIV><FONT face=3DArial size=3D2>"You love to hate me, but you wont kill = me" -=20 Slayer - Love to Hate.</FONT></DIV></BODY></HTML> ------=_NextPart_000_0005_01C12BF0.CEE8E740-- From koen@behindthesofa.dhs.org Thu Aug 23 07:45:32 2001 From: koen@behindthesofa.dhs.org (Koen Bossers) Date: Thu, 23 Aug 2001 08:45:32 +0200 Subject: [Tutor] How can use Windows Exlporer's browse file method in a python script (Tkinter)? References: <LAW2-OE37G9IVirrvcL000028cb@hotmail.com> Message-ID: <3B84A68C.9090800@behindthesofa.dhs.org> I know this is not the Windows Explorer browse method, but take a good look at tkFileDialog >>> from tkFileDialog import askopenfile >>> askopenfile() check out the webpage http://web.lfw.org/python/htmldoc/tkFileDialog.html Cheers, Koen Proud Newbie wrote: >How can use Windows Exlporer's browse file method in a python script >(Tkinter)? >Say, I want to use Windows Exlporer's browse file method to let users browse >and locate a file. How do I do that? >Thanks a million. > > >SN > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > From dyoo@hkn.eecs.berkeley.edu Thu Aug 23 08:30:16 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 23 Aug 2001 00:30:16 -0700 (PDT) Subject: [Tutor] map, filter and lambda functions [filter can take None] In-Reply-To: <3B849AEB.28396.402B905@localhost> Message-ID: <Pine.LNX.4.21.0108230001510.6321-100000@hkn.eecs.berkeley.edu> > > Now I'm curious as to *why* it works. 'None' doesn't strike me as a > > function that returns a value. Although, it says in the documentation > > somewhere, that None on map works as the identity function. This > > didn't bother me, though. It seemed like "No map...gives you same > > thing you started with." > > *Why* it works? Just because filter is designed to work that way. > Initially I was going to suggest a way of doing that, but instead of > None, I was going to suggest the truth function from the operator > module. > > None certainly isn't a function though. [Note: skip if you're not interested in looking at Python icky C internals.] Feeding 'None' as a "function" is a special case that's particular only to Python's implementation of filter(), that is, this is hardcoded to recognize this unusual input. It certainly doesn't do it for a human-intuitive reason. *grin* If we're interested in looking at C code, we can glance at the relevant code in the 'bltinmodule.c' file under the function "builtin_filter()": ### ## Somewhere in Python/bltinmodule.c /* Warning: this is adulterated code: I've chopped off the reference counting and error trapping code from this block. You may want to look at the real thing at your leisure. In Python 2.1, this is around line 214 of the file "bltinmodule.c". */ if (func == Py_None) { good = item; } else { good = PyEval_CallObject(func, arg); } ok = PyObject_IsTrue(good); if (ok) { ... /* let's stop here */ ### I dunno if it's a blemish or not that filter() behaves this way. My understanding is that the designers felt that testing an element for trueness was such a common case that it deserved to be optimized, even at the cost of some obviousness. Personally, I've always opted for: filter(lambda x: x, some_list_of_things) rather than filter(None, some_list_of_things) but taking advantage of the None shortcut does make it more efficient for the machine. From dyoo@hkn.eecs.berkeley.edu Thu Aug 23 09:03:07 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 23 Aug 2001 01:03:07 -0700 (PDT) Subject: [Tutor] Tkinter canvas movement question... In-Reply-To: <000801c12b9c$fee07520$a6a616ca@rumpus> Message-ID: <Pine.LNX.4.21.0108230053440.6321-100000@hkn.eecs.berkeley.edu> On Thu, 23 Aug 2001, Jason O'Dell wrote: > Fellow list users, I JeSo (long time reader, first time poster) come > bearing problems... Ok, using Tkinter, I have the following code, > > class dude: > def __init__(self): > self.physical = screen.create_oval(30,270,60,300, fill='white', outline='white') > def left(self): > screen.move(self.physical, 5, 5) > > (screen is earlier defined as a Tkinter Canvas widget) > > and elsewhere i have, > > circle = dude() > root.bind_all('<Left>', circle.left()) Try: root.bind_all('<Left>', circle.left) (without the parentheses) (Hey, that was self-referential advice! *grin*) What you had before, > root.bind_all('<Left>', circle.left()) already calls circle.left() as a function; instead, what we want is just to pass circle.left off as a function. Here's a small example to demonstrate the idea: ### >>> def balloon(): ... print "Boom!" ... >>> balloon <function balloon at 0x80e7774> ### Just as long as we don't put parens at the end, the function doesn't get called. It's just a function thing that we can pass around, hot potato style: ### >>> basket = [balloon] >>> story = ('red_riding_hood', basket) >>> b = story[1][0] >>> b <function balloon at 0x80e7774> >>> b() Boom! ### And it's this function itself that we want to pass to bind_all(), and not the result of calling that function. Hope this helps! From Kerim Borchaev" <warkid@storm.ru Thu Aug 23 09:02:17 2001 From: Kerim Borchaev" <warkid@storm.ru (Kerim Borchaev) Date: Thu, 23 Aug 2001 12:02:17 +0400 Subject: Re[2]: [Tutor] map, filter and lambda functions In-Reply-To: <3B849366.BEA77AEB@chello.nl> References: <3B849366.BEA77AEB@chello.nl> Message-ID: <3501.010823@storm.ru> Thursday, August 23, 2001, 9:23:50 AM, you wrote: RR> checklist = string.split(filetext, '\n') RR> checklist = filter(None, checklist) RR> checklist = map(string.strip, checklist) RR> checklist = map(string.upper, checklist) RR> If checklist is rather long, the last two may be written mor efficiently RR> as: RR> checklist = map(lambda x:string.upper(string.strip(x)), checklist) About efficiency - running the script below i get this: 2.01 1.32 2.01 1.32 no luck for lambda... ------------- import time l=[str(x) for x in range(1000)] num_iter=100 import string start = time.clock() for i in range(num_iter): checklist=l checklist = map(string.strip, checklist) checklist = map(string.upper, checklist) stend = time.clock() print "%.2f"%(stend-start) start = time.clock() for i in range(num_iter): checklist=l checklist = map(lambda x:string.upper(string.strip(x)), checklist) stend = time.clock() print "%.2f"%(stend-start) start = time.clock() for i in range(num_iter): checklist=l checklist = map(string.strip, checklist) checklist = map(string.upper, checklist) stend = time.clock() print "%.2f"%(stend-start) start = time.clock() for i in range(num_iter): checklist=l checklist = map(lambda x:string.upper(string.strip(x)), checklist) stend = time.clock() print "%.2f"%(stend-start) ------------- Best regards, Kerim mailto:warkid@storm.ru From hanna@chagford.com Thu Aug 23 21:17:07 2001 From: hanna@chagford.com (Hanna Joo) Date: Thu, 23 Aug 2001 22:17:07 +0200 Subject: [Tutor] How to import one function from another program (not as header) Message-ID: <00ac01c12c10$981e3560$0801a8c0@chagford> Hi I have two programs. I would like to import a function from another program but want to pass name of the function as a variable. Is this possible? prog a: def something(modulename, funcName): module = __import__(modulename) func = module.funcName ( == doesn't work.. complains that module has no attribute 'funcName') I would like to keep funcName as a variable.. How can I do this? Any help will be appreciated. TIA Hanna From scarblac@pino.selwerd.nl Thu Aug 23 09:34:26 2001 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Thu, 23 Aug 2001 10:34:26 +0200 Subject: [Tutor] How to import one function from another program (not as header) In-Reply-To: <00ac01c12c10$981e3560$0801a8c0@chagford>; from hanna@chagford.com on Thu, Aug 23, 2001 at 10:17:07PM +0200 References: <00ac01c12c10$981e3560$0801a8c0@chagford> Message-ID: <20010823103426.A3885@pino.selwerd.nl> On 0, Hanna Joo <hanna@chagford.com> wrote: > I have two programs. I would like to import a function from another program > but want to pass name of the function as a variable. Is this possible? > > prog a: > > def something(modulename, funcName): > module = __import__(modulename) > func = module.funcName ( == doesn't work.. complains that module has > no attribute 'funcName') > > I would like to keep funcName as a variable.. How can I do this? > Any help will be appreciated. func = getattr(module, funcName) -- Remco Gerlich From hnowak@cuci.nl Thu Aug 23 09:58:07 2001 From: hnowak@cuci.nl (Hans Nowak) Date: Thu, 23 Aug 2001 10:58:07 +0200 Subject: [Tutor] map, filter and lambda functions Message-ID: <3B876B81@twigger.nl> >===== Original Message From "Kerim Borchaev" <warkid@storm.ru> ===== >Thursday, August 23, 2001, 9:23:50 AM, you wrote: > >RR> checklist = string.split(filetext, '\n') >RR> checklist = filter(None, checklist) >RR> checklist = map(string.strip, checklist) >RR> checklist = map(string.upper, checklist) > >RR> If checklist is rather long, the last two may be written mor efficiently >RR> as: > >RR> checklist = map(lambda x:string.upper(string.strip(x)), checklist) > >About efficiency - running the script below i get this: > >2.01 >1.32 >2.01 >1.32 > >no luck for lambda... On my box, these two are faster: print "trial 5:", def popo(x): return x.strip().upper() start = time.clock() for i in range(num_iter): checklist=l checklist = map(popo, checklist) stend = time.clock() print "%.2f"%(stend-start) print "trial 6:", start = time.clock() for i in range(num_iter): checklist=l checklist = [x.strip().upper() for x in checklist] stend = time.clock() print "%.2f"%(stend-start) I'm on an overloaded NT box right now, and the results vary horribly for each run, but 5 and 6 are consistently faster than the rest. Mzzl, --Hans Nowak From hnowak@cuci.nl Thu Aug 23 10:11:04 2001 From: hnowak@cuci.nl (Hans Nowak) Date: Thu, 23 Aug 2001 11:11:04 +0200 Subject: [Tutor] How to import one function from another program (not as header) Message-ID: <3B877E8E@twigger.nl> >===== Original Message From "Hanna Joo" <hanna@chagford.com> ===== >Hi > >I have two programs. I would like to import a function from another program >but want to pass name of the function as a variable. Is this possible? > >prog a: > >def something(modulename, funcName): > module = __import__(modulename) > func = module.funcName ( == doesn't work.. complains that module has >no attribute 'funcName') > >I would like to keep funcName as a variable.. How can I do this? >Any help will be appreciated. Well, you can use getattr: def something(modulename, funcname): mod = __import__(modulename) return getattr(mod, funcname) HTH, --Hans Nowak From alan.gauld@bt.com Thu Aug 23 09:58:00 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Thu, 23 Aug 2001 09:58:00 +0100 Subject: [Tutor] map, filter and lambda functions Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BECF@mbtlipnt02.btlabs.bt.co.uk> > Here's the new, shorter version: > > checklist = string.split(filetext, "\n") > checklist = filter(lambda x: x != '', checklist) > checklist = map(lambda x: string.strip(x), checklist) > checklist = map(lambda x: string.upper(x), checklist) I like it better, to me its clearer whats going on. > The thing is, I can't use list comprehensions in this script I'm not convinced comprehensions are better in every case. They compress a lot of code into one line but not necesarily in a maintainable form... IMHO of course. > second version the best (most efficient) way of handling such a code > block? Time them and see... It removes the guesswork! > Is there a way to do this without lambda functions, or are they > pretty much needed in this case? You could define functions: def isNotEmpty(x): return x != '' def stripitem(x): return string.strip(x) def upperitem(x): return string.upper(x) and use them as in: checklist = reduce(isNotEmpty, checklist) checklist = map(stripitem,checklist) checklist = map(upperitem,checklist) You can always replace a lambda with a function in Python, but in this case the lambda is probably clearer by putting the action explicitly in the operation. The function approach is better if you were using the same lambda in multiple places. Alan G From scarblac@pino.selwerd.nl Thu Aug 23 10:01:34 2001 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Thu, 23 Aug 2001 11:01:34 +0200 Subject: [Tutor] map, filter and lambda functions In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66BECF@mbtlipnt02.btlabs.bt.co.uk>; from alan.gauld@bt.com on Thu, Aug 23, 2001 at 09:58:00AM +0100 References: <5104D4DBC598D211B5FE0000F8FE7EB20E66BECF@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <20010823110133.A3960@pino.selwerd.nl> On 0, alan.gauld@bt.com wrote: > > Here's the new, shorter version: > > > > checklist = string.split(filetext, "\n") > > checklist = filter(lambda x: x != '', checklist) > > checklist = map(lambda x: string.strip(x), checklist) > > checklist = map(lambda x: string.upper(x), checklist) The last two lambdas are just identity functions applied to another function, and thus redundant. (snip) > You could define functions: > def isNotEmpty(x): return x != '' > def stripitem(x): return string.strip(x) > def upperitem(x): return string.upper(x) Same for the last two here. You might as well write stripitem = string.upper Or just pass string.upper into the map in the first place :) > You can always replace a lambda with a function in Python, > but in this case the lambda is probably clearer by putting > the action explicitly in the operation. Except that the lambda does no action it all, so it's obfuscating :) -- Remco Gerlich From scarblac@pino.selwerd.nl Thu Aug 23 10:03:55 2001 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Thu, 23 Aug 2001 11:03:55 +0200 Subject: [Tutor] map, filter and lambda functions In-Reply-To: <16441BC80BD4@kserver.org>; from sheila@thinkspot.net on Wed, Aug 22, 2001 at 09:35:09PM -0700 References: <1623A278005B@kserver.org> <Pine.LNX.4.33.0108230024550.14247-100000@terbidium.openservices.net> <16441BC80BD4@kserver.org> Message-ID: <20010823110355.B3960@pino.selwerd.nl> On 0, Sheila King <sheila@thinkspot.net> wrote: > Ah, thanks. That's what I was missing. It certainly wasn't clear to me > from anything that I had read, that it was supposed to be a function > OBJECT as opposed to a function invocation. If you give a function invocation as an argument, like say: somefunc(otherfunc(x), y) What happens is that otherfunc(x) is called, and its *result* is passed to somefunc. That's true for all Python expressions, and therefore for map() as well. Map() needs to have some object it can call, usually a function object, it can fill in the arguments by itself. It couldn't do much with only the result for some x. -- Remco Gerlich From Kerim Borchaev" <warkid@storm.ru Thu Aug 23 10:15:15 2001 From: Kerim Borchaev" <warkid@storm.ru (Kerim Borchaev) Date: Thu, 23 Aug 2001 13:15:15 +0400 Subject: Re[2]: [Tutor] map, filter and lambda functions In-Reply-To: <3B876B81@twigger.nl> References: <3B876B81@twigger.nl> Message-ID: <10552.010823@storm.ru> Yep. On my W2k/PII450 these are much faster too. And here's a classical "optimization anecdote" that worth to read if one want's to know more about "what is efficient" : http://www.python.org/doc/essays/list2str.html Best regards, Kerim mailto:warkid@storm.ru Thursday, August 23, 2001, 12:58:07 PM, you wrote: >>===== Original Message From "Kerim Borchaev" <warkid@storm.ru> ===== >>Thursday, August 23, 2001, 9:23:50 AM, you wrote: >> >>RR> checklist = string.split(filetext, '\n') >>RR> checklist = filter(None, checklist) >>RR> checklist = map(string.strip, checklist) >>RR> checklist = map(string.upper, checklist) >> >>RR> If checklist is rather long, the last two may be written mor efficiently >>RR> as: >> >>RR> checklist = map(lambda x:string.upper(string.strip(x)), checklist) >> >>About efficiency - running the script below i get this: >> >>2.01 >>1.32 >>2.01 >>1.32 >> >>no luck for lambda... HN> On my box, these two are faster: HN> print "trial 5:", HN> def popo(x): HN> return x.strip().upper() HN> start = time.clock() HN> for i in range(num_iter): HN> checklist=l HN> checklist = map(popo, checklist) HN> stend = time.clock() HN> print "%.2f"%(stend-start) HN> print "trial 6:", HN> start = time.clock() HN> for i in range(num_iter): HN> checklist=l HN> checklist = [x.strip().upper() for x in checklist] HN> stend = time.clock() HN> print "%.2f"%(stend-start) HN> I'm on an overloaded NT box right now, and the results vary horribly for each HN> run, but 5 and 6 are consistently faster than the rest. HN> Mzzl, HN> --Hans Nowak HN> _______________________________________________ HN> Tutor maillist - Tutor@python.org HN> http://mail.python.org/mailman/listinfo/tutor From alan.gauld@bt.com Thu Aug 23 10:02:31 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Thu, 23 Aug 2001 10:02:31 +0100 Subject: [Tutor] map, filter and lambda functions Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BED0@mbtlipnt02.btlabs.bt.co.uk> > :You don't need to put lambda functions, you can just provide > :string.strip and string.upper without using lambda what-so-ever. > > Are you sure that you can do this without lambda? I tried today, and > couldn't get it to work without lambda. > > >>> mylist > ['a', 'b', 'c', ''] > >>> mylist = map(string.upper(x), mylist) Try: mylist = map(string.upper, mylist) Its like function pointers in C (Since I know you know C :-) in that you just use the name - no parens. It is after all a pointer to a function that you are passing (actually a reference to a callable object to be pedantic...) Alan G From relic@isl.is Thu Aug 23 18:24:09 2001 From: relic@isl.is (=?iso-8859-1?Q?=D3l=F6f_og_Gylfi?=) Date: Thu, 23 Aug 2001 10:24:09 -0700 Subject: [Tutor] confirmation of subsription Message-ID: <001b01c12bf8$6bb6a420$0a00000a@KANE> This is a multi-part message in MIME format. ------=_NextPart_000_0018_01C12BBD.BED46B50 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable ------=_NextPart_000_0018_01C12BBD.BED46B50 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML><HEAD> <META content=3D"text/html; charset=3Diso-8859-1" = http-equiv=3DContent-Type> <META content=3D"MSHTML 5.00.3315.2870" name=3DGENERATOR> <STYLE></STYLE> </HEAD> <BODY bgColor=3D#ffffff> <DIV> </DIV></BODY></HTML> ------=_NextPart_000_0018_01C12BBD.BED46B50-- From varistor@cngoldline.com Thu Aug 23 14:29:30 2001 From: varistor@cngoldline.com (Lin Cang) Date: Thu, 23 Aug 2001 21:29:30 +0800 Subject: [Tutor] Metal Oxide Varistor Message-ID: <E15ZuUE-0005E7-00@mail.python.org> Dear Sir / Madam, I am pleased to introduce our company(Guangdong Kestar Electronic Co.Ltd.) and our main products. Guangdong Kestar Electronic Co.Ltd. is a professional manufcturer on Varistors ,located in Guangdong province mainland China. With 10 years experience in producing Metal Oxide Varistors ,It is equipped with a complete set of advanced machinery,possessed high abilities of development & exploitation.. Our main seven series varistors are WYG current varistor, MYL lihtningproof varistor,MYE high load varistor,MYA minitype varistor,MYP squareness varistor,MYR highly reliable&varistor,low-pressure power supply lightning arrester.. The Varistors conform to ISO9002 .The products have passed several international authentication.such as UL. if you are interested in our products, please contact us without hesitate. yours truely Lin Cang. Guangdong Kestar Electronic Co.Ltd Tel: Јє86-757-2271139 2718755 Fax: 86-757-2261563 E-mail:varistor@cngoldline.com Website:http://www.kestar.com.cn Contact person: Mr Lin From varistor@cngoldline.com Thu Aug 23 14:29:30 2001 From: varistor@cngoldline.com (Lin Cang) Date: Thu, 23 Aug 2001 21:29:30 +0800 Subject: [Tutor] Metal Oxide Varistor Message-ID: <E15ZuUF-0005EL-00@mail.python.org> Dear Sir / Madam, I am pleased to introduce our company(Guangdong Kestar Electronic Co.Ltd.) and our main products. Guangdong Kestar Electronic Co.Ltd. is a professional manufcturer on Varistors ,located in Guangdong province mainland China. With 10 years experience in producing Metal Oxide Varistors ,It is equipped with a complete set of advanced machinery,possessed high abilities of development & exploitation.. Our main seven series varistors are WYG current varistor, MYL lihtningproof varistor,MYE high load varistor,MYA minitype varistor,MYP squareness varistor,MYR highly reliable&varistor,low-pressure power supply lightning arrester.. The Varistors conform to ISO9002 .The products have passed several international authentication.such as UL. if you are interested in our products, please contact us without hesitate. yours truely Lin Cang. Guangdong Kestar Electronic Co.Ltd Tel: Јє86-757-2271139 2718755 Fax: 86-757-2261563 E-mail:varistor@cngoldline.com Website:http://www.kestar.com.cn Contact person: Mr Lin From rob@jam.rr.com Thu Aug 23 16:13:47 2001 From: rob@jam.rr.com (Rob Andrews) Date: Thu, 23 Aug 2001 10:13:47 -0500 Subject: [Tutor] time question Message-ID: <3B851DAB.AE4B2633@jam.rr.com> Okay, I'll admit my ignorance. (It's pretty well documented by now. heehee) I'm working on an application to track the progress of someone who has quit smoking (or to provide info for someone thinking of quitting), and the whole application is based around the passage of time for its calculations. If anyone wishes to risk going blind by actually reading this alpha-release-wannabe source file, it's located here: http://www.lowerstandard.com/python/pyQuit.py But fortunately I have a nice, specific question. After user input, I have the quit time stored thusly: >>> import time >>> quitTime (2001, 8, 22, 9, 45, -1, -1, -1, -1) I then convert this to a float, and determine the difference between the current time and the quitting time: >>> quitTime1 = time.mktime(quitTime) >>> currentTime = time.time() >>> quitTime1 998491499.0 >>> currentTime 998578178.33000004 >>> timeDifference = currentTime - quitTime1 >>> timeDifference 86679.330000042915 At this point, I face the slightly tedious task of converting this time difference (expressed in seconds) into something more tangible. I'd like to report "You have been nicotine free for 6 weeks, 5 hours, and 4 minutes." (for example). So far, this means a several-step process of dividing the seconds down into years, then the remainder down to (lunar) months, then to weeks, days, and minutes. Does anyone know a way to do this more directly, elegantly, or briefly? Rob -- A mind is a terrible thing. And it must be stopped. Before it kills someone. Useless Python! http://www.lowerstandard.com/python From lkvam@venix.com Thu Aug 23 16:26:45 2001 From: lkvam@venix.com (Lloyd Kvam) Date: Thu, 23 Aug 2001 11:26:45 -0400 Subject: [Tutor] time question References: <3B851DAB.AE4B2633@jam.rr.com> Message-ID: <3B8520B5.3F9F13A3@venix.com> Is there any reason for not using MxDateTime? http://www.lemburg.com/files/python/mxDateTime.html It may be overkill for your purposes, but I would think that's generally better than the alternatives. Rob Andrews wrote: > > Okay, I'll admit my ignorance. (It's pretty well documented by now. > heehee) > > I'm working on an application to track the progress of someone who has > quit smoking (or to provide info for someone thinking of quitting), and > the whole application is based around the passage of time for its > calculations. > > If anyone wishes to risk going blind by actually reading this > alpha-release-wannabe source file, it's located here: > > http://www.lowerstandard.com/python/pyQuit.py > > But fortunately I have a nice, specific question. After user input, I > have the quit time stored thusly: > > >>> import time > >>> quitTime > (2001, 8, 22, 9, 45, -1, -1, -1, -1) > > I then convert this to a float, and determine the difference between the > current time and the quitting time: > > >>> quitTime1 = time.mktime(quitTime) > >>> currentTime = time.time() > >>> quitTime1 > 998491499.0 > >>> currentTime > 998578178.33000004 > >>> timeDifference = currentTime - quitTime1 > >>> timeDifference > 86679.330000042915 > > At this point, I face the slightly tedious task of converting this time > difference (expressed in seconds) into something more tangible. I'd like > to report "You have been nicotine free for 6 weeks, 5 hours, and 4 > minutes." (for example). So far, this means a several-step process of > dividing the seconds down into years, then the remainder down to (lunar) > months, then to weeks, days, and minutes. > > Does anyone know a way to do this more directly, elegantly, or briefly? > > Rob > -- > A mind is a terrible thing. And it must be stopped. Before it kills > someone. > Useless Python! > http://www.lowerstandard.com/python > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From kalle@gnupung.net Thu Aug 23 16:40:19 2001 From: kalle@gnupung.net (Kalle Svensson) Date: Thu, 23 Aug 2001 17:40:19 +0200 Subject: [Tutor] time question In-Reply-To: <3B851DAB.AE4B2633@jam.rr.com>; from rob@jam.rr.com on Thu, Aug 23, 2001 at 10:13:47AM -0500 References: <3B851DAB.AE4B2633@jam.rr.com> Message-ID: <20010823174019.B15167@gandalf> [Rob Andrews] > But fortunately I have a nice, specific question. After user input, I > have the quit time stored thusly: [time juggling] > Does anyone know a way to do this more directly, elegantly, or briefly? You could use time.localtime() to get a tuple and then compare the tuples. Extremely crude example: >>> import time >>> quitTime = (2001, 8, 22, 9, 45, -1, -1, -1, -1) >>> for field, index in zip(["years", "months", "days", "hours", "minutes"], ... range(5)): ... print field, time.localtime(time.time())[index] - quitTime[index] ... years 0 months 0 days 1 hours 8 minutes -13 >>> Don't know if it's better... Peace, Kalle -- [ kalle@gnupung.net ][ Thought control, brought to you by the WIPO! ] [ http://gnupung.net/ ][ http://anti-dmca.org/ http://eurorights.org/ ] From alan.gauld@bt.com Thu Aug 23 16:55:51 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Thu, 23 Aug 2001 16:55:51 +0100 Subject: [Tutor] Tkinter canvas movement question... Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BED2@mbtlipnt02.btlabs.bt.co.uk> ------_=_NextPart_001_01C12BEC.157463B0 Content-type: text/plain; charset="ISO-8859-1" Hi welcome to the posting community :-) class dude: def __init__(self): self.physical = screen.create_oval(30,270,60,300, fill='white', outline='white') def left(self): screen.move(self.physical, 5, 5) circle = dude() root.bind_all('<Left>', circle.left()) Try: root.bind_all('<Left>',circle.left) Although I've never used bind_all and I'm not entirely convinced about assigning a bound method like this, I'm not sure what gets passed as the self argument.. ...Any ideas why that wont work? It doesn't work because of the parens. You are calling the method instead of passing it as an object. Thats also why the circle has already moved left... HTH, Alan g ------_=_NextPart_001_01C12BEC.157463B0 Content-type: text/html; charset="ISO-8859-1" <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML><HEAD> <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=ISO-8859-1"> <META content="MSHTML 5.00.3013.2600" name=GENERATOR> <STYLE></STYLE> </HEAD> <BODY bgColor=#ffffff> <DIV><FONT color=#0000ff face="Courier New" size=2><SPAN class=140005415-23082001>Hi welcome to the posting community :-)</SPAN></FONT></DIV> <BLOCKQUOTE style="BORDER-LEFT: #0000ff 2px solid; MARGIN-LEFT: 5px; MARGIN-RIGHT: 0px; PADDING-LEFT: 5px"> <DIV><FONT face=Arial size=2>class dude:<BR>    def __init__(self):<BR>        self.physical = screen.create_oval(30,270,60,300, fill='white', outline='white')<BR>    def left(self):<BR>        screen.move(self.physical, 5, 5)</FONT></DIV> <DIV><FONT size=2><FONT face=Arial><SPAN class=140005415-23082001><FONT color=#0000ff face="Courier New"> </FONT></SPAN></FONT></FONT></DIV> <DIV><FONT size=2><FONT face=Arial><SPAN class=140005415-23082001> </SPAN>circle = dude()</FONT></FONT></DIV> <DIV><FONT face=Arial size=2>root.bind_all('<Left>', circle.left())</FONT></DIV> <DIV><FONT face=Arial size=2></FONT> </DIV></BLOCKQUOTE> <DIV><FONT size=2><FONT color=#0000ff><FONT face="Courier New"><SPAN class=140005415-23082001> </SPAN><SPAN class=140005415-23082001> Try:</SPAN></FONT></FONT></FONT></DIV> <DIV><FONT size=2><FONT color=#0000ff><FONT face="Courier New"><SPAN class=140005415-23082001></SPAN></FONT></FONT></FONT> </DIV> <DIV><FONT size=2><FONT color=#0000ff><FONT face="Courier New"><SPAN class=140005415-23082001>root.bind_all('<Left>',circle.left)</SPAN></FONT></FONT></FONT></DIV> <DIV><FONT size=2><FONT color=#0000ff><FONT face="Courier New"><SPAN class=140005415-23082001></SPAN></FONT></FONT></FONT> </DIV> <DIV><FONT size=2><FONT color=#0000ff><FONT face="Courier New"><SPAN class=140005415-23082001>Although I've never used bind_all and I'm not entirely convinced about</SPAN></FONT></FONT></FONT></DIV> <DIV><FONT size=2><FONT color=#0000ff><FONT face="Courier New"><SPAN class=140005415-23082001>assigning a bound method like this, I'm not sure what gets passed </SPAN></FONT></FONT></FONT></DIV> <DIV><FONT size=2><FONT color=#0000ff><FONT face="Courier New"><SPAN class=140005415-23082001>as the self argument.. </SPAN></FONT></FONT></FONT> </DIV> <BLOCKQUOTE style="BORDER-LEFT: #0000ff 2px solid; MARGIN-LEFT: 5px; MARGIN-RIGHT: 0px; PADDING-LEFT: 5px"> <DIV><FONT face=Arial size=2>...Any ideas why that wont work? <SPAN class=140005415-23082001><FONT color=#0000ff face="Courier New"> </FONT></SPAN></FONT></DIV> <DIV><FONT face=Arial size=2><SPAN class=140005415-23082001></SPAN></FONT> </DIV></BLOCKQUOTE> <DIV><FONT color=#0000ff face="Courier New" size=2><SPAN class=140005415-23082001>It doesn't work because of the parens. You are calling the </SPAN></FONT></DIV> <DIV><FONT color=#0000ff face="Courier New" size=2><SPAN class=140005415-23082001>method instead of passing it as an object. Thats also why </SPAN></FONT></DIV> <DIV><FONT color=#0000ff face="Courier New" size=2><SPAN class=140005415-23082001>the circle has already moved left...</SPAN></FONT></DIV> <DIV><FONT color=#0000ff face="Courier New" size=2><SPAN class=140005415-23082001></SPAN></FONT> </DIV> <DIV><FONT color=#0000ff face="Courier New" size=2><SPAN class=140005415-23082001>HTH,</SPAN></FONT></DIV> <DIV><FONT color=#0000ff face="Courier New" size=2><SPAN class=140005415-23082001></SPAN></FONT> </DIV> <DIV><FONT color=#0000ff face="Courier New" size=2><SPAN class=140005415-23082001>Alan g</SPAN></FONT></DIV></BODY></HTML> ------_=_NextPart_001_01C12BEC.157463B0-- From printers@sendme.cz Thu Aug 23 15:14:41 2001 From: printers@sendme.cz (A) Date: Thu, 23 Aug 2001 16:14:41 +0200 Subject: [Tutor] How to extract cookies? Message-ID: <3B852BF1.32482.17C928B@localhost> Hi, I use httplib module to POST to a website.From the response( header) I need to extract cookies. Can you advise me how I can do that please? The header I receive looks like Server: Microsoft-IIS/5.0 Date: Thu, 23 Aug 2001 12:24:33 GMT Location: MemberPortfolio.asp Connection: Keep-Alive Content-Length: 140 Content-Type: text/html Set-Cookie: ECEurope=Password=&Email=leads%40sendme%2Ecz; expires=Sun, 21-Oct-2001 23:00:00 GMT; path=/ Set-Cookie: ASPSESSIONIDQQQGQLQO=ABNGDCNBDOIEFJEEPJAOJDKE; path=/ Cache-control: private Thank you for help Ladislav From alan.gauld@bt.com Thu Aug 23 17:05:06 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Thu, 23 Aug 2001 17:05:06 +0100 Subject: [Tutor] How to import one function from another program (not as header) Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BED3@mbtlipnt02.btlabs.bt.co.uk> First if you know modulename and funcname you should be able to just call them, but assuming you may be reading them dynamically... > def something(modulename, funcName): > module = __import__(modulename) > func = module.funcName eval('func = '+modulename+'.'+funcname) return func foo = something('sys','exit') foo() # should exit! I think. Alan G From alan.gauld@bt.com Thu Aug 23 17:06:24 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Thu, 23 Aug 2001 17:06:24 +0100 Subject: [Tutor] How to import one function from another program (not as header) Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BED4@mbtlipnt02.btlabs.bt.co.uk> > > func = getattr(module, funcName) OOh yes, better still. I should have remembered that it came up quite recently. Alan G From alan.gauld@bt.com Thu Aug 23 17:17:56 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Thu, 23 Aug 2001 17:17:56 +0100 Subject: [Tutor] map, filter and lambda functions Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BED5@mbtlipnt02.btlabs.bt.co.uk> > > You could define functions: > > def stripitem(x): return string.strip(x) > > def upperitem(x): return string.upper(x) > > Same for the last two here. You might as well write > > stripitem = string.upper Sure, I was just making the point that in general foo = lambda x: <expr> can be replaced by def foo(x): return <expr> THe case where <expr> is a standard function just happens to be a special case where the def is done for you. > > You can always replace a lambda with a function in Python, > > but in this case the lambda is probably clearer by putting > > the action explicitly in the operation. > > Except that the lambda does no action it all, so it's obfuscating :) Its still less obfuscating than passing a user defined function might be. Despite the friendly name 'upperitem' we don't really know whether its a wrapper for string.upper or math.ceil or something we wrote ourselves. At least the lambda in this case exposes the function used. Which, again, was the gerneral point I was trying to make about the use of lambdas. Alan G From rob@jam.rr.com Thu Aug 23 17:59:33 2001 From: rob@jam.rr.com (Rob Andrews) Date: Thu, 23 Aug 2001 11:59:33 -0500 Subject: [Tutor] time question References: <3B851DAB.AE4B2633@jam.rr.com> <3B8520B5.3F9F13A3@venix.com> Message-ID: <3B853675.6C715C32@jam.rr.com> Lloyd Kvam wrote: > > Is there any reason for not using MxDateTime? > http://www.lemburg.com/files/python/mxDateTime.html > > It may be overkill for your purposes, but I would think that's generally better than the alternatives. > This does look like an interesting package, worth further experimentation. For this application, I do want to stick with the standard-issue library components for now, though. I also like Kalle's idea: >>> import time >>> quitTime = (2001, 8, 22, 9, 45, -1, -1, -1, -1) >>> for field, index in zip(["years", "months", "days", "hours", "minutes"], ... range(5)): ... print field, time.localtime(time.time())[index] - quitTime[index] ... years 0 months 0 days 1 hours 8 minutes -13 It seems to have the benefit of simplicity. I'm currently playing with the idea of stepping through it with divmod() to extract years, .. minutes. It seems roughly equivalent in human effort to the process of preventing trouble from output such as "minutes -13". This is why I love programming. One can spend hours determining the *best* way to do something that could be coded roughly in a few minutes. Rob -- A {} is a terrible thing to waste. Useless Python! http://www.lowerstandard.com/python From jessefw@loop.com Thu Aug 23 18:42:33 2001 From: jessefw@loop.com (Jesse F. W) Date: Thu, 23 Aug 2001 10:42:33 -0700 Subject: [Tutor] Tkinter canvas movement question... In-Reply-To: <000801c12b9c$fee07520$a6a616ca@rumpus> Message-ID: <3B84DE19.30174.2A5E06A@localhost> Jason O'Dell wrote: > Fellow list users, I JeSo (long time reader, first time poster) come = > bearing problems... Ok, using Tkinter, I have the following code, > > class dude: > def __init__(self): > self.physical =3D screen.create_oval(30,270,60,300, = > fill=3D'white', outline=3D'white') > def left(self): > screen.move(self.physical, 5, 5) > > (screen is earlier defined as a Tkinter Canvas widget) > > and elsewhere i have, > > circle =3D dude() > root.bind_all('<Left>', circle.left()) Besides the passing of the results of the function insted of the function, I think there is another problem. When you use any of the bind commands in Tkinter, the function you pass must accept an extra argument(normally called 'event') when it is called in response to the bound action(in your case, pressing the left arrow) Your left command must take two arguments: self(because it's a method) AND event(because it's being called by a bind statement. I also don't think you need to use bind_all for keyboard events. Bind_all will bind all the widgets in the window. As far as I know, only the root window gets key input, so it would be allright to just bind to the root window, not to the canvas(and whatever else you have in your code) too. > ...Any ideas why that wont work? It simply draws up everything, with > the = object already moved once, without any pressing of left, and > future = pressings of left have no effect. Any help on this lil > problem would be = appreciated... Also, any suggestions on how I > could best put that = binding inside the class itself? > Thankyou all... > JeSo Yourverywelcome, JeWe-> Jesse F. W From John.Kenyon@mail.idrive.com Thu Aug 23 22:17:22 2001 From: John.Kenyon@mail.idrive.com (John Kenyon) Date: Thu, 23 Aug 2001 14:17:22 -0700 Subject: [Tutor] problem with re reaching maximum recursions Message-ID: <B1F282D5B226D411B8B900E08110486F02E3B5ED@sweetness.idrive.com> Hello all, Have problem maybe somebody can give me some ideas on. I have a script that goes through a bunch of files and strips the comments out of them - it looks for '//', checks to see that it is not preceeded by ':' and then grabs to the end of the line. A second regex then goes through and looks for other forms of comments, i.e., "/**". The regex I am having a problem with is as follows: slashComment = re.compile('(?<!:)\/\/.*(\n)') The problem is that when it hits too large a file (not sure exactly how big) it throws a runtime exception -- "maximum recursion limit exceeded." As far as I can tell in doing a Google search, this is a bug in 2.0 that did not exist in 1.5. I tried importing pre instead but it seems to have a problem with the negative look back (does anybody know if this was not a part of the 1.5 implementation?). I have thought about breaking the file up into smaller parts, but I am not sure quite how to do that and in any case it would be tricky to make sure that it wasn't split across a comment. Any ideas about how to approach this problem, maybe a more efficient regex? Thanks in advance, jck From John.Kenyon@mail.idrive.com Thu Aug 23 22:22:06 2001 From: John.Kenyon@mail.idrive.com (John Kenyon) Date: Thu, 23 Aug 2001 14:22:06 -0700 Subject: [Tutor] RE: problem with re reaching maximum recursions Message-ID: <B1F282D5B226D411B8B900E08110486F02E3B5EE@sweetness.idrive.com> So, immediately after posting this I realized that I could do the search line-by-line for the first pass and then stick it all back together for the second pass. Ugly and slow, but it should work. Anybody have any other ideas? jck > -----Original Message----- > From: John Kenyon > Sent: Thursday, August 23, 2001 2:17 PM > To: 'tutor@python.org' > Subject: problem with re reaching maximum recursions > > Hello all, > > > Have problem maybe somebody can give me some ideas on. I have a script > that goes through a bunch of files and strips the comments out of them - > it looks for '//', checks to see that it is not preceeded by ':' and then > grabs to the end of the line. A second regex then goes through and looks > for other forms of comments, i.e., "/**". > > The regex I am having a problem with is as follows: slashComment = > re.compile('(?<!:)\/\/.*(\n)') > > The problem is that when it hits too large a file (not sure exactly how > big) it throws a runtime exception -- "maximum recursion limit exceeded." > > As far as I can tell in doing a Google search, this is a bug in 2.0 that > did not exist in 1.5. I tried importing pre instead but it seems to have a > problem with the negative look back (does anybody know if this was not a > part of the 1.5 implementation?). I have thought about breaking the file > up into smaller parts, but I am not sure quite how to do that and in any > case it would be tricky to make sure that it wasn't split across a > comment. Any ideas about how to approach this problem, maybe a more > efficient regex? > > Thanks in advance, > > jck From John.Kenyon@mail.idrive.com Thu Aug 23 22:45:46 2001 From: John.Kenyon@mail.idrive.com (John Kenyon) Date: Thu, 23 Aug 2001 14:45:46 -0700 Subject: [Tutor] RE: problem with re reaching maximum recursions Message-ID: <B1F282D5B226D411B8B900E08110486F02E3B5EF@sweetness.idrive.com> OK, I've narrowed the problem down a little, and I seem to have found a fix. It turns out the problem was not with the negative lookback, but with a later sub that I do. So now I am importing both pre and re, using the latter for the negative lookback and the former for the sub. Really ugly, but it seems to work. If there are other ways to do this, I would love to hear them. thanks again, jck > -----Original Message----- > From: John Kenyon > Sent: Thursday, August 23, 2001 2:22 PM > To: 'tutor@python.org' > Subject: RE: problem with re reaching maximum recursions > > So, immediately after posting this I realized that I could do the search > line-by-line for the first pass and then stick it all back together for > the second pass. Ugly and slow, but it should work. Anybody have any other > ideas? > > jck > > -----Original Message----- > From: John Kenyon > Sent: Thursday, August 23, 2001 2:17 PM > To: 'tutor@python.org' > Subject: problem with re reaching maximum recursions > > Hello all, > > > Have problem maybe somebody can give me some ideas on. I have a > script that goes through a bunch of files and strips the comments out of > them - it looks for '//', checks to see that it is not preceeded by ':' > and then grabs to the end of the line. A second regex then goes through > and looks for other forms of comments, i.e., "/**". > > The regex I am having a problem with is as follows: slashComment = > re.compile('(?<!:)\/\/.*(\n)') > > The problem is that when it hits too large a file (not sure exactly > how big) it throws a runtime exception -- "maximum recursion limit > exceeded." > > As far as I can tell in doing a Google search, this is a bug in 2.0 > that did not exist in 1.5. I tried importing pre instead but it seems to > have a problem with the negative look back (does anybody know if this was > not a part of the 1.5 implementation?). I have thought about breaking the > file up into smaller parts, but I am not sure quite how to do that and in > any case it would be tricky to make sure that it wasn't split across a > comment. Any ideas about how to approach this problem, maybe a more > efficient regex? > > Thanks in advance, > > jck From jstanley@start.com.au Thu Aug 23 23:44:48 2001 From: jstanley@start.com.au (Jordan Stanley) Date: Thu, 23 Aug 2001 23:44:48 +0100 Subject: [Tutor] IP Address Message-ID: <B3009021098@i01sv4161.i01rd0002.ids1.intelonline.com> am trying to implement a script to have my server email me my ip address every time it changes. any thoughts? suggestions? you think I should use windoze scripting functions. by the way, my server is running Win 2000 Advanced Server at the moment. Jordan __________________________________________________________________ Get your free Australian email account at http://www.start.com.au From clanoftheinsane@hotmail.com Thu Aug 23 23:42:42 2001 From: clanoftheinsane@hotmail.com (paul) Date: Thu, 23 Aug 2001 18:42:42 -0400 Subject: [Tutor] Tkinter help Message-ID: <OE74F5x3MgPWk8RisBi000127d9@hotmail.com> This is a multi-part message in MIME format. ------=_NextPart_000_000B_01C12C03.6448C820 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable When using Tkinter, i want to have a window within my GUI program that = will show the output that you normally see in the python interpreter = window. for example, i want to have a button display a list of data, = but instead of that data being displayed in the interpreter, i want it = to appear in my actual program in a widget. any ideas? thanks, paul ------=_NextPart_000_000B_01C12C03.6448C820 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML><HEAD> <META content=3D"text/html; charset=3Diso-8859-1" = http-equiv=3DContent-Type> <META content=3D"MSHTML 5.00.2314.1000" name=3DGENERATOR> <STYLE></STYLE> </HEAD> <BODY bgColor=3D#ffffff> <DIV><FONT face=3DArial size=3D2>When using Tkinter, i want to have a = window within=20 my GUI program that will show the output that you normally see in the = python=20 interpreter window.  for example, i want to have a button display a = list of=20 data, but instead of that data being displayed in the interpreter, i = want it to=20 appear in my actual program in a widget.  any ideas?</FONT></DIV> <DIV> </DIV> <DIV><FONT face=3DArial size=3D2>thanks,</FONT></DIV> <DIV><FONT face=3DArial size=3D2>paul</FONT></DIV></BODY></HTML> ------=_NextPart_000_000B_01C12C03.6448C820-- From sheila@thinkspot.net Fri Aug 24 00:09:47 2001 From: sheila@thinkspot.net (Sheila King) Date: Thu, 23 Aug 2001 16:09:47 -0700 Subject: [Tutor] Tkinter help In-Reply-To: <OE74F5x3MgPWk8RisBi000127d9@hotmail.com> References: <OE74F5x3MgPWk8RisBi000127d9@hotmail.com> Message-ID: <1AD89995DB5@kserver.org> On Thu, 23 Aug 2001 18:42:42 -0400, "paul" <clanoftheinsane@hotmail.com> wrote about [Tutor] Tkinter help: :When using Tkinter, i want to have a window within my GUI program that will show the output that you normally see in the python interpreter window. for example, i want to have a button display a list of data, but instead of that data being displayed in the interpreter, i want it to appear in my actual program in a widget. any ideas? : :thanks, :paul Use a widget, such as a text widget, and get the output from sys.stdout and send it to the text widget. It looks like you could use the text.insert command for inserting the output from sys.stdout into the text widget. -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From ginokuo@veriomail.com Fri Aug 24 02:39:32 2001 From: ginokuo@veriomail.com (Gino Kuo) Date: Thu, 23 Aug 2001 18:39:32 -0700 Subject: [Tutor] a newbie question Message-ID: <000001c12c3d$a171c6e0$f64ab43f@oemcomputer> Hi, all I am learning Python as my first computer programming language. So I hope this question is worth your time. I tried to run program stored in the interpreter under window 98. Here is the path, C:\DownLoad\practice python\p17.py >>>execfile(C:\DownLoad\practice python\p17.py) It is a SyntexError. How do I fix it? From kauphlyn@speakeasy.org Fri Aug 24 02:50:30 2001 From: kauphlyn@speakeasy.org (Daniel Coughlin) Date: Thu, 23 Aug 2001 18:50:30 -0700 (PDT) Subject: [Tutor] a newbie question In-Reply-To: <000001c12c3d$a171c6e0$f64ab43f@oemcomputer> Message-ID: <Pine.LNX.4.33L2.0108231846200.25826-100000@grace.speakeasy.net> try this: >>> execfile("c:\\download\\practice python\\p17.py") note the quoatation marks and two backslashes. backslash is a special character; so, you need to use two to tell python that they are there. hope this helps! Daniel On Thu, 23 Aug 2001, Gino Kuo wrote: > Hi, all > I am learning Python as my first computer programming language. So I hope > this question is worth your time. > I tried to run program stored in the interpreter under window 98. Here is > the path, C:\DownLoad\practice python\p17.py > >>>execfile(C:\DownLoad\practice python\p17.py) > It is a SyntexError. How do I fix it? > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From dyoo@hkn.eecs.berkeley.edu Fri Aug 24 04:31:34 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 23 Aug 2001 20:31:34 -0700 (PDT) Subject: [Tutor] problem with re reaching maximum recursions In-Reply-To: <B1F282D5B226D411B8B900E08110486F02E3B5ED@sweetness.idrive.com> Message-ID: <Pine.LNX.4.21.0108232023520.2255-100000@hkn.eecs.berkeley.edu> On Thu, 23 Aug 2001, John Kenyon wrote: > Hello all, > > > Have problem maybe somebody can give me some ideas on. I have a script that > goes through a bunch of files and strips the comments out of them - it looks > for '//', checks to see that it is not preceeded by ':' and then grabs to > the end of the line. A second regex then goes through and looks for other > forms of comments, i.e., "/**". > > The regex I am having a problem with is as follows: slashComment = > re.compile('(?<!:)\/\/.*(\n)') > > The problem is that when it hits too large a file (not sure exactly how big) > it throws a runtime exception -- "maximum recursion limit exceeded." I do remember hearing about this error message a while back; I believe the Python implementers fixed this in the more recent versions. At least, the comments in the bug-tracking section on sourceforge imply this: http://sourceforge.net/tracker/?group_id=5470&atid=105470&func=detail&aid=418626 Can you check to see if the same error occurs under Python 2.1.1? If so, then this is something we should bring to the attention of the Python developers. From dyoo@hkn.eecs.berkeley.edu Fri Aug 24 04:56:36 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 23 Aug 2001 20:56:36 -0700 (PDT) Subject: [Tutor] a newbie question [identifiers can't contain colons] In-Reply-To: <Pine.LNX.4.33L2.0108231846200.25826-100000@grace.speakeasy.net> Message-ID: <Pine.LNX.4.21.0108232032310.2255-100000@hkn.eecs.berkeley.edu> On Thu, 23 Aug 2001, Daniel Coughlin wrote: > try this: > > >>> execfile("c:\\download\\practice python\\p17.py") > > note the quoatation marks and two backslashes. backslash is a special > character; so, you need to use two to tell python that they are there. Also, it should be ok to use forward slashes to separate your directories: execfile("c:/download/practice python/p17.py") We need the quotes around "c:/download/practice python/p17.py" because we need to tell Python to take that the whole thing as a piece of quoted string, and not really look into it for some hidden meaning. Otherwise, Python will go into contortions trying to figure out what we mean. Let's take a closer look: ### >>> c:\\download\\practice python\\p17.py File "<stdin>", line 1 c:\\download\\practice python\\p17.py ^ SyntaxError: invalid syntax ### When we type an unquoted name into Python, Python assumes that we're trying to evoke the name of a variable or function, or do some other funky thing. In this case, Python will think it's seeing the beginning of a name. That's why it's underlining the colon: names can't contain colons. ### >>> colon = "colon" # "colon" can be a name >>> : = "colon" # but not ":". File "<stdin>", line 1 : = "colon" ^ SyntaxError: invalid syntax ## Later, you'll find out that ':' has a special meaning in Python: we use it when we begin to "indent" inner blocks in our code. Here's an example: ### if question == "What is the meaning of life?": print "42" ### Hope this explains why Python gave that particular SyntaxError. Good luck! From dyoo@hkn.eecs.berkeley.edu Fri Aug 24 05:04:17 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 23 Aug 2001 21:04:17 -0700 (PDT) Subject: [Tutor] IP Address In-Reply-To: <B3009021098@i01sv4161.i01rd0002.ids1.intelonline.com> Message-ID: <Pine.LNX.4.21.0108232057100.2255-100000@hkn.eecs.berkeley.edu> On Thu, 23 Aug 2001, Jordan Stanley wrote: > am trying to implement a script to have my server email me my ip > address every time it changes. > > any thoughts? suggestions? One way to do this is to do a "busy waiting" approach: have your program check every so often if your IP has changed or not. If it has, send off the message. Otherwise, wait for a while, and try again. Here's some pseudocode: ### def monitorAndReportIPChanges(): ip = getIP() while 1: new_ip = getIP() if ip != new_ip: reportThatTheIpChanged() else: waitForSomeTime() ### If you do it this way, you may find the time.sleep() function: http://www.python.org/doc/lib/module-time.html#l2h-1298 and the smtplib email module: http://www.python.org/doc/lib/module-smtplib.html useful for you. Hope this helps! From dyoo@hkn.eecs.berkeley.edu Fri Aug 24 05:10:11 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 23 Aug 2001 21:10:11 -0700 (PDT) Subject: [Tutor] How to import one function from another program (not as header) In-Reply-To: <00ac01c12c10$981e3560$0801a8c0@chagford> Message-ID: <Pine.LNX.4.21.0108232106220.2255-100000@hkn.eecs.berkeley.edu> On Thu, 23 Aug 2001, Hanna Joo wrote: > I have two programs. I would like to import a function from another program > but want to pass name of the function as a variable. Is this possible? > > prog a: > > def something(modulename, funcName): > module = __import__(modulename) > func = module.funcName ( == doesn't work.. complains that module has > no attribute 'funcName') > > I would like to keep funcName as a variable.. How can I do this? Any > help will be appreciated. Remco mentioned that getattr() is a good way to grab the function out of a module, given that all we have is its name in a string. Out of curiosity, what sort of program are you writing? Perhaps there might be an easier way to do what you're trying to do. Talk to you later! From sburr@mac.com Fri Aug 24 06:40:47 2001 From: sburr@mac.com (Steven Burr) Date: Thu, 23 Aug 2001 22:40:47 -0700 Subject: [Tutor] map, filter and lambda functions In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66BECF@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <20010824053750.XWKY19181.femail35.sdc1.sfba.home.com@localhost> On Thursday, August 23, 2001, at 01:58 AM, alan.gauld@bt.com wrote: >> Here's the new, shorter version: >> >> checklist = string.split(filetext, "\n") >> checklist = filter(lambda x: x != '', checklist) >> checklist = map(lambda x: string.strip(x), checklist) >> checklist = map(lambda x: string.upper(x), checklist) > > I like it better, to me its clearer whats going on. > >> The thing is, I can't use list comprehensions in this script > > I'm not convinced comprehensions are better in every case. > They compress a lot of code into one line but not necesarily in > a maintainable form... IMHO of course. You're surely right that list comprehensions aren't better in every case. In this case, though, it's really too bad (or at least it seems so to me) that Sheila doesn't have access to them: >>> filetext = """lower case string ... with trailing white space and ... ... a blank line """ >>> checklist = [s.strip().upper() for s in filetext.split('\n') if s] >>> checklist ['LOWER CASE STRING', 'WITH TRAILING WHITE SPACE AND', 'A BLANK LINE'] From alan.gauld@bt.com Fri Aug 24 09:45:07 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri, 24 Aug 2001 09:45:07 +0100 Subject: [Tutor] Tkinter help Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BEDB@mbtlipnt02.btlabs.bt.co.uk> ------_=_NextPart_001_01C12C79.1374EF20 Content-type: text/plain; charset="iso-8859-1" When using Tkinter, i want to have a window within my GUI program that will show the output that you normally see in the python interpreter window. for example, i want to have a button display a list of data, but instead of that data being displayed in the interpreter, i want it to appear in my actual program in a widget. any ideas? Its an idea, no more... reassign sys.stdout to a file. After every print call a function that copies that file to a text widget. it might work... There is an example of this in Graysons book I think, but I dont have access to it just now. Alan G ------_=_NextPart_001_01C12C79.1374EF20 Content-type: text/html; charset="iso-8859-1" <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML><HEAD> <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1"> <META content="MSHTML 5.00.3013.2600" name=GENERATOR> <STYLE></STYLE> </HEAD> <BODY bgColor=#ffffff> <BLOCKQUOTE style="BORDER-LEFT: #0000ff 2px solid; MARGIN-LEFT: 5px; MARGIN-RIGHT: 0px; PADDING-LEFT: 5px"> <DIV><FONT size=2><FONT face=Arial>When using Tkinter, i want to have a window within my GUI program that will show the output that you normally see in the python interpreter window.  for example, i want to have a button display a list of data, but instead of that data being displayed in the interpreter, i want it to appear in my actual program in a widget.  any ideas?<FONT color=#0000ff face="Courier New"><SPAN class=640474508-24082001> </SPAN></FONT></FONT></FONT></DIV></BLOCKQUOTE> <DIV><FONT size=2><FONT face=Arial><FONT color=#0000ff face="Courier New"><SPAN class=640474508-24082001>Its an idea, no more...</SPAN></FONT></FONT></FONT></DIV> <DIV><FONT size=2><FONT face=Arial><FONT color=#0000ff face="Courier New"><SPAN class=640474508-24082001></SPAN></FONT></FONT></FONT> </DIV> <DIV><FONT size=2><FONT face=Arial><FONT color=#0000ff face="Courier New"><SPAN class=640474508-24082001>reassign sys.stdout to a file.</SPAN></FONT></FONT></FONT></DIV> <DIV><FONT size=2><FONT face=Arial><FONT color=#0000ff face="Courier New"><SPAN class=640474508-24082001>After every print call a function that copies that file to a </SPAN></FONT></FONT></FONT></DIV> <DIV><FONT size=2><FONT face=Arial><FONT color=#0000ff face="Courier New"><SPAN class=640474508-24082001>text widget.</SPAN></FONT></FONT></FONT></DIV> <DIV> </DIV> <DIV><FONT size=2><FONT face=Arial><FONT color=#0000ff face="Courier New"><SPAN class=640474508-24082001>it might work...</SPAN></FONT></FONT></FONT></DIV> <DIV><FONT size=2><FONT face=Arial><FONT color=#0000ff face="Courier New"><SPAN class=640474508-24082001></SPAN></FONT></FONT></FONT> </DIV> <DIV><FONT size=2><FONT face=Arial><FONT color=#0000ff face="Courier New"><SPAN class=640474508-24082001>There is an example of this in Graysons book I think, but I </SPAN></FONT></FONT></FONT></DIV> <DIV><FONT size=2><FONT face=Arial><FONT color=#0000ff face="Courier New"><SPAN class=640474508-24082001>dont have access to it just now. </SPAN></FONT></FONT></FONT></DIV> <DIV><FONT size=2><FONT face=Arial><FONT color=#0000ff face="Courier New"><SPAN class=640474508-24082001></SPAN></FONT></FONT></FONT> </DIV> <DIV><FONT size=2><FONT face=Arial><FONT color=#0000ff face="Courier New"><SPAN class=640474508-24082001>Alan G</SPAN></FONT></FONT></FONT></DIV></BODY></HTML> ------_=_NextPart_001_01C12C79.1374EF20-- From tanguy.vincent@laposte.net Fri Aug 24 09:52:02 2001 From: tanguy.vincent@laposte.net (Tanguy Vincent) Date: Fri, 24 Aug 2001 10:52:02 +0200 Subject: [Tutor] python and vtk Message-ID: <00bd01c12c7a$0b0b3280$185b29d5@ausy.fr> C'est un message de format MIME en plusieurs parties. ------=_NextPart_000_00BA_01C12C8A.CE50DF00 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hello, I'm a beginner in Python and vtk. I'm looking for websites with tutorial = and/or examples of the use of vtk with Python. Can somebody help me ? Tanguy ------=_NextPart_000_00BA_01C12C8A.CE50DF00 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML><HEAD> <META content=3D"text/html; charset=3Diso-8859-1" = http-equiv=3DContent-Type> <META content=3D"MSHTML 5.00.2919.6307" name=3DGENERATOR> <STYLE></STYLE> </HEAD> <BODY bgColor=3D#ffffff> <DIV><FONT face=3DArial size=3D2>Hello,</FONT></DIV> <DIV> </DIV> <DIV><FONT face=3DArial size=3D2>I'm a beginner in Python and vtk. I'm = looking for=20 websites with tutorial and/or examples of the use of vtk with=20 Python.</FONT></DIV> <DIV> </DIV> <DIV><FONT face=3DArial size=3D2>Can somebody help me ?</FONT></DIV> <DIV> </DIV> <DIV><FONT face=3DArial size=3D2>Tanguy</FONT></DIV></BODY></HTML> ------=_NextPart_000_00BA_01C12C8A.CE50DF00-- From alan.gauld@bt.com Fri Aug 24 09:49:43 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri, 24 Aug 2001 09:49:43 +0100 Subject: [Tutor] a newbie question Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BEDC@mbtlipnt02.btlabs.bt.co.uk> > I tried to run program stored in the interpreter under window > 98. Here is the path, C:\DownLoad\practice python\p17.py > >>>execfile(C:\DownLoad\practice python\p17.py) Try putting the filename in quotes? I think execfile takes a string as its argument. But why are you doing this? There are some valid situations to use execfile but they are rare. Usually you just execute a python script from a DOS prompt by typing C:\> C:\Download\practice\p17.py OR if file associations are not set: C:\> python C:\Download\practice\p17.py HTH, Alan G From sendme105@hotmail.com Fri Aug 24 11:39:33 2001 From: sendme105@hotmail.com (James) Date: Fri, 24 Aug 2001 03:39:33 -0700 Subject: [Tutor] Re: How to extract cookies? (A) References: <E15a86d-00059A-00@mail.python.org> Message-ID: <OE53rblZz02H67yRLVb000056e0@hotmail.com> > Message: 1 > From: "A" <discuss@sendme.cz> > To: printers@sendme.cz > Date: Thu, 23 Aug 2001 16:14:41 +0200 > Reply-to: printers@sendme.cz > Subject: [Tutor] How to extract cookies? > > Hi, > I use httplib module to POST to a website.From the response( > header) > I need to extract cookies. Can you advise me how I can do that > please? > > > The header I receive looks like > > Server: Microsoft-IIS/5.0 > Date: Thu, 23 Aug 2001 12:24:33 GMT > Location: MemberPortfolio.asp > Connection: Keep-Alive > Content-Length: 140 > Content-Type: text/html > Set-Cookie: > ECEurope=Password=&Email=leads%40sendme%2Ecz; > expires=Sun, 21-Oct-2001 23:00:00 GMT; path=/ > Set-Cookie: > ASPSESSIONIDQQQGQLQO=ABNGDCNBDOIEFJEEPJAOJDKE; > path=/ > Cache-control: private > > Thank you for help > Ladislav I had a similar problem a week or two ago, and based the following entirely on a suggestion found via google/deja: This is prolly all you want: from urllib import * from mimetools import Message myurl= urlopen(source_url) headers=myurl.info() cookie = headers.getheader("set-cookie") Here's how I used the info above to urlopen some pages that required cookie support: import os, string from urllib import * from mimetools import Message #redefine (override?) urlopen to enable cookie sending def urlopen(url, data=None, headers=None): u = FancyURLopener() if headers: if type(headers) == type({}): headers = headers.items() for kw, val in headers: u.addheader(kw, val) return u.open(url, data) temppage= urlopen(source_url) headers=temppage.info() cookie = headers.getheader("set-cookie") clist = string.split(cookie, ';') temppage.close() # The above gets the cookie info I need... # to successfully open the page: page = urlopen(source_url, headers=[('Cookie', clist[0])]) ######## Note: I'm new to programming... From lsloan@umich.edu Fri Aug 24 13:14:11 2001 From: lsloan@umich.edu (Lance E Sloan) Date: Fri, 24 Aug 2001 08:14:11 -0400 Subject: [Tutor] Re: How to extract cookies? In-Reply-To: Your message of "Thu, 23 Aug 2001 16:14:41 +0200." <3B852BF1.32482.17C928B@localhost> Message-ID: <200108241214.IAA29806@birds.us.itd.umich.edu> "A" wrote: > I use httplib module to POST to a website.From the response(header) I > need to extract cookies. Can you advise me how I can do that please? > > The header I receive looks like Well, your example headers were cut off from your message, but I suspect you need to use the Cookie module. (Just a guess. :) -- Lance E Sloan Web Services, Univ. of Michigan: Full-service Web and database design, development, and hosting. Specializing in Python & Perl CGIs. http://websvcs.itd.umich.edu/ - "Putting U on the Web" From lsloan@umich.edu Fri Aug 24 14:09:04 2001 From: lsloan@umich.edu (Lance E Sloan) Date: Fri, 24 Aug 2001 09:09:04 -0400 Subject: [Tutor] map & lambda to create dictionary from lists? Message-ID: <200108241309.JAA00571@birds.us.itd.umich.edu> The recent discussion of map and lambda coupled with a bit of ugly code I wrote recently inspired me to learn more about these things. What I've got are two sequences. The first is a sequence of strings that I want to use as the keys of a dictionary. The second is a sequence of objects (strings, numbers, whatever) that I want to use as the values in the dictionary. Of course, the two sequences have a one-to-one correspondence. Here's what I've come up with using map and lambda so far and I want to know if it's Good: Python 2.0 (#1, Jan 8 2001, 10:18:58) [GCC egcs-2.91.66 19990314 (egcs-1.1.2 release)] on sunos5 Type "copyright", "credits" or "license" for more information. >>> d = {} >>> keys = ('name', 'age', 'food') >>> values = ('Monty', 42, 'spam') >>> junk = map(lambda k, v: d.update({k: v}), keys, values) >>> junk [None, None, None] >>> d {'name': 'Monty', 'age': 42, 'food': 'spam'} Okay, so it works. The list returned by map isn't all that useful, other than maybe for finding out how many pairs were processed. I feel like I'm not using map the way it was intended. Is this a Bad Thing? More importantly, is there a better way to do this? I'd rather not reinvent the wheel with this. What I'm actually going to use this for is to turn a row of data fetched from an Oracle database using DCOracle's fetchone into a dictionary. DCOracle's cursor object has a description attribute that's a tuple of tuples. Each inner tuple contains the name of a column, its data type, and other stuff. So, I would probably invoke map like this: junk = map(lambda k, v: d.update({k[0]: v}), csr.description, row) I use k[0] because the very first element of the inner tuple is the name of the column that I want to use as the key. -- Lance E Sloan Web Services, Univ. of Michigan: Full-service Web and database design, development, and hosting. Specializing in Python & Perl CGIs. http://websvcs.itd.umich.edu/ - "Putting U on the Web" From pythonpython@hotmail.com Fri Aug 24 17:31:56 2001 From: pythonpython@hotmail.com (HY) Date: Sat, 25 Aug 2001 01:31:56 +0900 Subject: [Tutor] How to set a default value for Tkinter.Entry ? Message-ID: <OE61GYdRGy9tCx1Dy3r0000b4c2@hotmail.com> This is a multi-part message in MIME format. ------=_NextPart_000_0019_01C12D05.BA1F89C0 Content-Type: text/plain; charset="gb2312" Content-Transfer-Encoding: quoted-printable Is there a way to set a default value for Tkinter.Entry? I mean can you do somethig to Tkinter.Entry like setting the default = text value for text field in HTML's form? Thanks a lot. HY ------=_NextPart_000_0019_01C12D05.BA1F89C0 Content-Type: text/html; charset="gb2312" Content-Transfer-Encoding: quoted-printable <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML><HEAD> <META http-equiv=3DContent-Type content=3D"text/html; charset=3Dgb2312"> <META content=3D"MSHTML 5.50.4134.100" name=3DGENERATOR> <STYLE></STYLE> </HEAD> <BODY bgColor=3D#ffffff> <DIV><FONT face=3DArial>Is there a way to set a default value for=20 Tkinter.Entry?</FONT></DIV> <DIV><FONT face=3DArial>I mean can you do somethig to = Tkinter.Entry like=20 setting the default text value for text field in HTML's=20 form?</FONT></DIV> <DIV><FONT face=3DArial></FONT> </DIV> <DIV><FONT face=3DArial>Thanks a lot.</FONT></DIV> <DIV><FONT face=3DArial></FONT> </DIV> <DIV><FONT face=3DArial>HY</FONT></DIV></BODY></HTML> ------=_NextPart_000_0019_01C12D05.BA1F89C0-- From dyoo@hkn.eecs.berkeley.edu Fri Aug 24 17:36:57 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 24 Aug 2001 09:36:57 -0700 (PDT) Subject: [Tutor] map & lambda to create dictionary from lists? In-Reply-To: <200108241309.JAA00571@birds.us.itd.umich.edu> Message-ID: <Pine.LNX.4.21.0108240926350.12581-100000@hkn.eecs.berkeley.edu> On Fri, 24 Aug 2001, Lance E Sloan wrote: > The recent discussion of map and lambda coupled with a bit of ugly code > I wrote recently inspired me to learn more about these things. > > What I've got are two sequences. The first is a sequence of strings > that I want to use as the keys of a dictionary. The second is a > sequence of objects (strings, numbers, whatever) that I want to use as > the values in the dictionary. Of course, the two sequences have a > one-to-one correspondence. > > Here's what I've come up with using map and lambda so far and I want to > know if it's Good: > > Python 2.0 (#1, Jan 8 2001, 10:18:58) > [GCC egcs-2.91.66 19990314 (egcs-1.1.2 release)] on sunos5 > Type "copyright", "credits" or "license" for more information. > >>> d = {} > >>> keys = ('name', 'age', 'food') > >>> values = ('Monty', 42, 'spam') > >>> junk = map(lambda k, v: d.update({k: v}), keys, values) > >>> junk > [None, None, None] > >>> d > {'name': 'Monty', 'age': 42, 'food': 'spam'} > > Okay, so it works. The list returned by map isn't all that useful, > other than maybe for finding out how many pairs were processed. I feel > like I'm not using map the way it was intended. Is this a Bad Thing? > More importantly, is there a better way to do this? I'd rather not > reinvent the wheel with this. I'm not sure if this is better; tell me what you think of this approach: ### def itemsToDict(items): dict = {} for key, value in items: dict[key] = value keys = ('name', 'age', 'foo') values = ('Monty', 42, 'spam') zipped_up_values = zip(keys, values) dict = itemsToDict(zipped_up_values) ### itemsToDict() seems to be a useful function; I use it all the time, but I always have lingering doubts that I've reinvented the wheel somehow. As a somewhat related note: map(), too, is special cased to do "zipping" if we give it None in the function argument. ### >>> map(None, [1, 2, 3], [4, 5, 6]) [(1, 4), (2, 5), (3, 6)] ### Hope this helps! From sheila@thinkspot.net Fri Aug 24 18:00:24 2001 From: sheila@thinkspot.net (Sheila King) Date: Fri, 24 Aug 2001 10:00:24 -0700 Subject: [Tutor] How to set a default value for Tkinter.Entry ? In-Reply-To: <OE61GYdRGy9tCx1Dy3r0000b4c2@hotmail.com> References: <OE61GYdRGy9tCx1Dy3r0000b4c2@hotmail.com> Message-ID: <581C48234DD@kserver.org> On Sat, 25 Aug 2001 01:31:56 +0900, "HY" <pythonpython@hotmail.com> wrote about [Tutor] How to set a default value for Tkinter.Entry ?: :Is there a way to set a default value for Tkinter.Entry? :I mean can you do somethig to Tkinter.Entry like setting the default text value for text field in HTML's form? : :Thanks a lot. : :HY This is something my son and I were working on yesterday. You probably want the insert method for the Entry widget. Here is a handy Tkinter reference: http://www.pythonware.com/library/tkinter/introduction/index.htm Looking at the Entry methods: http://www.pythonware.com/library/tkinter/introduction/x3960-methods.htm It looks like, if input = Entry(root) is your Entry widget, then input.insert(0, "My default text here") should work??? -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From kev@sat.net Fri Aug 24 18:56:22 2001 From: kev@sat.net (Kevin McCormick) Date: Fri, 24 Aug 2001 12:56:22 -0500 Subject: [Tutor] time question References: <3B851DAB.AE4B2633@jam.rr.com> Message-ID: <3B869546.CA85E5B7@sat.net> Rob Andrews wrote: > > Okay, I'll admit my ignorance. (It's pretty well documented by now. > heehee) > > I'm working on an application to track the progress of someone who has > quit smoking (or to provide info for someone thinking of quitting), and > the whole application is based around the passage of time for its > calculations. > > If anyone wishes to risk going blind by actually reading this > alpha-release-wannabe source file, it's located here: > > http://www.lowerstandard.com/python/pyQuit.py > > But fortunately I have a nice, specific question. After user input, I > have the quit time stored thusly: > > >>> import time > >>> quitTime > (2001, 8, 22, 9, 45, -1, -1, -1, -1) > > I then convert this to a float, and determine the difference between the > current time and the quitting time: > > >>> quitTime1 = time.mktime(quitTime) > >>> currentTime = time.time() > >>> quitTime1 > 998491499.0 > >>> currentTime > 998578178.33000004 > >>> timeDifference = currentTime - quitTime1 > >>> timeDifference > 86679.330000042915 > > At this point, I face the slightly tedious task of converting this time > difference (expressed in seconds) into something more tangible. I'd like > to report "You have been nicotine free for 6 weeks, 5 hours, and 4 > minutes." (for example). So far, this means a several-step process of > dividing the seconds down into years, then the remainder down to (lunar) > months, then to weeks, days, and minutes. > > Does anyone know a way to do this more directly, elegantly, or briefly? > > Rob > -- > A mind is a terrible thing. And it must be stopped. Before it kills > someone. > Useless Python! > http://www.lowerstandard.com/python > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor It seems to me that you need some way to identify the start time as a number and the end time as a larger number. I have copied my "dateSerial" functions for your review. If you assign the "dateSerial" as the start date, plus the seconds from midnight, and also "dateSerial" the end date, minus the seconds until midnight (or the day before plus seconds), you could perform your calculation. Python has modules that do similar things, but I'm just a long-time newbie. import string import math from types import * #============= dytmoD = {'M1':0, 'M2':31, 'M3':59, 'M4':90, 'M5':120, 'M6':151, 'M7':181, 'M8':212, 'M9':243, 'M10':273, 'M11':304, 'M12':334 } dayNames = ((2, 'Mon', 'Monday'), (3, 'Tue', 'Tuesday'), (4, 'Wed', 'Wednesday'), (5, 'Thur', 'Thursday'), (6, 'Fri', 'Friday'),(7, 'Sat', 'Saturday'), (1, 'Sun', 'Sunday'),(2, 'Mon', 'Monday')) moNames = {'M1':(1, 'J', 'Jan', 'January', 31, 0), 'M2':(2, 'F', 'Feb', 'February', 28, 31), 'M3':(3, 'M', 'Mar', 'March', 31, 59), 'M4':(4, 'A', 'Apr', 'April', 30, 90), 'M5':(5, 'M', 'May', 'May', 31, 120), 'M6':(6, 'J', 'Jun', 'June', 30, 151), 'M7':(7, 'J', 'Jul', 'July', 31, 181), 'M8':(8, 'A', 'Aug', 'August', 31, 212), 'M9':(9, 'S', 'Sep', 'September', 30, 243), 'M10':(10, 'O', 'Oct', 'October', 31, 273), 'M11':(11, 'N', 'Nov', 'November', 30, 304), 'M12':(12, 'D', 'Dec', 'December', 31, 334)} #============ def MakeDate(YYYYMMDD, listItems=0): """ takes a date string in the YYYYMMDD format and parses out the year, month, and day calls dateSerial(yr, mo, dy) to get the serial number date calls DayOfWeek(serial) to get the day of the week return value: if listItems = 0 -> only serial is returned as a single item if listItems > 0,...4 -> returns a tuple of (serial, tickDate, wkDay, strDate, tplDate) """ yr = int(YYYYMMDD[:2]) if yr < 35: yr = yr + 2000 else: yr = yr + 1900 mo = int(YYYYMMDD[2:4]) dy = int(YYYYMMDD[4:]) tplDate = (yr, mo, dy) strDate = '%d/%d/%d' % (mo, dy, yr) tickDate = moNames['M%d' % mo][1] + '%d' % dy serial = dateSerial(yr, mo, dy) wkDay = DayOfWeek(serial) lVal = (serial, tickDate, wkDay, strDate, tplDate) if listItems > 4: return lVal else: return lval[listItems - 1] #============ def isLeapYear(yr): return (0 == (yr % 4)) #============ def dateSerial(yr, mo, dy): moId = 'M%d' % mo baseYear = 1900 # assume base year of 1900 so that 1-1-1900 is day 1 sy = (yr - baseYear) * 365 # 365 days to a year # Leap Year occurs every four years, except for years ending in 00, # in which case only if the year is divisible by 400. # for any year add: - (yr/100 - baseYear/100) + (yr/400 - baseYear/400) # but since this is for centuries 1900 to 2000, it is superfluous sly = (yr - baseYear) / 4 # sm = dytmoD[moId] if isLeapYear(yr) and mo < 3: sm = sm - 1 return sy + sly + sm + dy + 1 #============ def DayOfWeek(dSerial, Onum1abrev2word=0): """ Argument is a serial number date. Onum1abrev2word -> 0=integer, 1=abbreviation, 2=word which is taken from the dayNames=((1, 'Sun', 'Sunday'),(2, 'Mon', 'Monday'),...) tuple Returns the day of the week where Sunday=1, Monday=2, ..., Saturday = 7 """ try: rt = int(Onum1abrev2word) except ValueError: 'Onum1abrev2word: %d must be 0, 1, or 2' % Onum1abrev2word try: dNum = int(dSerial) except ValueError: 'dSerial: %s must be an integer as from dateSerial()' % dSerial # assuming that 1/1/1900 was a Monday --verified with '$ cal 1, 1900 if dSerial < 7: dw = dNum - 1 else: dw = (dNum % 7) - 2 # in order to correctly access dayNames[] tuple #print dSerial, dw, dayNames[dw] return dayNames[dw][rt] From r.b.rigilink@chello.nl Fri Aug 24 19:27:48 2001 From: r.b.rigilink@chello.nl (Roeland Rengelink) Date: Fri, 24 Aug 2001 20:27:48 +0200 Subject: [Tutor] map & lambda to create dictionary from lists? References: <200108241309.JAA00571@birds.us.itd.umich.edu> Message-ID: <3B869CA4.54D881F4@chello.nl> Hi Lance, Lance E Sloan wrote: > > The recent discussion of map and lambda coupled with a bit of ugly code > I wrote recently inspired me to learn more about these things. > > What I've got are two sequences. The first is a sequence of strings > that I want to use as the keys of a dictionary. The second is a > sequence of objects (strings, numbers, whatever) that I want to use as > the values in the dictionary. Of course, the two sequences have a > one-to-one correspondence. > > Here's what I've come up with using map and lambda so far and I want to > know if it's Good: > Hmm, No, it isn't ;) Relying on side-effects is generally a bad idea. Two months from now you'll read that code and wonder why you're building a list of junk. How about this: def dict_from_items(items) '''Build dict from list of items''' dict = {} for key, val in items: dict[key] = value return dict d = dict_from_items(zip(key_list, value_list)) A nice little function that does exactly what it says it does. About your DB example. It's probably a good idea to spend some time to do try some more advanced approaches. How about something like: class DBEntry: def __init__(self, *args): ...assign args to appropriate attributes... def process(self): ...process myself... processed_entry_list for data in cursor.fetch_all(): entry_list.append(DBEntry(*data).process()) Use several different DBEntry classes, usually one for each different csr_description signature in your code. You can then put the code that you'll write to process entries in methods of each DBEntry class. Before you know it you'll be on your to full-fledged OO programming. Believe me Pythons OO programming paradigm is much more powerful than its functional programming paradigm. Hope this helps, Roeland -- r.b.rigilink@chello.nl "Half of what I say is nonsense. Unfortunately I don't know which half" From sheila@thinkspot.net Fri Aug 24 20:07:34 2001 From: sheila@thinkspot.net (Sheila King) Date: Fri, 24 Aug 2001 12:07:34 -0700 Subject: [Tutor] os.name to check before file locking Message-ID: <5F6550B1BC4@kserver.org> I'm working on writing a cross-platform file locking object to wrap file locking calls on posix and windows platforms. (It really is a big complaint of mine about the lack of support for file locking in Python, but anyhow, I'm just going to deal with it and write my own...) I'm using, for the posix platforms, Mark Lutz' examples from Programming Python 2nd ed, Chapter 14 as a guide. Very nice stuff he has there. I think I've figured out how to use the msvcrt module to lock files for Windows machines. And so, here's my question: I will have to test for what platform/os my code is running on, in order to know which libraries to use (i.e. fcntl or msvcrt). I notice that in the os module, we have the os.name command, which (according to the docs) returns one of the following: 'posix', 'nt', 'dos', 'mac', 'os2', 'ce', 'java' 'nt' is for any windows, including win98 and so on. 'posix' is for all unix type machines. Alternatively, under the sys module, there is the command sys.platform. The docs don't give a complete list of what output this might produce, but a sample: 'sunos5' or 'linux1'. This can be used to append platform-specific components to path, for instance. I think that all I will need to use here, is os.name, to check for which module to use. Let's face it, if fcntl won't do what I need on the Unix-type platforms, then I really have no idea how to handle it, so my code simply won't run on such a machine. I guess I'm just trying to get some advice, or make sure that I only want to use os.name and not mess with sys.platform. -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From bsass@freenet.edmonton.ab.ca Fri Aug 24 21:27:36 2001 From: bsass@freenet.edmonton.ab.ca (Bruce Sass) Date: Fri, 24 Aug 2001 14:27:36 -0600 (MDT) Subject: [Tutor] os.name to check before file locking In-Reply-To: <5F6550B1BC4@kserver.org> Message-ID: <Pine.LNX.4.33.0108241417490.10494-100000@bms> Hi, On Fri, 24 Aug 2001, Sheila King wrote: <...> > I guess I'm just trying to get some advice, or make sure that I only > want to use os.name and not mess with sys.platform. Ya, that's the right idea. If it turns out you need to use sys.platform 'cause of a quirk somewhere... <shrug> and hope you don't need to re-code too much. :) - Bruce From clanoftheinsane@hotmail.com Fri Aug 24 21:30:36 2001 From: clanoftheinsane@hotmail.com (paul) Date: Fri, 24 Aug 2001 16:30:36 -0400 Subject: [Tutor] Tkinter help References: <5104D4DBC598D211B5FE0000F8FE7EB20E66BEDB@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <OE378wSA1XvpFVjCRGr00012e9d@hotmail.com> This is a multi-part message in MIME format. ------=_NextPart_000_0008_01C12CBA.1AD09120 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable ok, can somebody give me an example of how to assign sys.stdout to a = file and then print it into a text box? i think i'm missing something. ----- Original Message -----=20 From: alan.gauld@bt.com=20 To: clanoftheinsane@hotmail.com ; tutor@python.org=20 Sent: Friday, August 24, 2001 4:45 AM Subject: RE: [Tutor] Tkinter help When using Tkinter, i want to have a window within my GUI program = that will show the output that you normally see in the python = interpreter window. for example, i want to have a button display a list = of data, but instead of that data being displayed in the interpreter, i = want it to appear in my actual program in a widget. any ideas?=20 Its an idea, no more... =20 reassign sys.stdout to a file. After every print call a function that copies that file to a=20 text widget. it might work... =20 There is an example of this in Graysons book I think, but I=20 dont have access to it just now.=20 =20 Alan G ------=_NextPart_000_0008_01C12CBA.1AD09120 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML><HEAD> <META content=3D"text/html; charset=3Diso-8859-1" = http-equiv=3DContent-Type> <META content=3D"MSHTML 5.00.2314.1000" name=3DGENERATOR> <STYLE></STYLE> </HEAD> <BODY bgColor=3D#ffffff> <DIV><FONT face=3DArial size=3D2>ok, can somebody give me an example of = how to=20 assign sys.stdout to a file and then print it into a text box?  i = think i'm=20 missing something.</FONT></DIV> <DIV> </DIV> <DIV> </DIV> <DIV> </DIV> <DIV> </DIV> <DIV> </DIV> <DIV> </DIV> <BLOCKQUOTE=20 style=3D"BORDER-LEFT: #000000 2px solid; MARGIN-LEFT: 5px; MARGIN-RIGHT: = 0px; PADDING-LEFT: 5px; PADDING-RIGHT: 0px"> <DIV style=3D"FONT: 10pt arial">----- Original Message ----- </DIV> <DIV=20 style=3D"BACKGROUND: #e4e4e4; FONT: 10pt arial; font-color: = black"><B>From:</B>=20 <A href=3D"mailto:alan.gauld@bt.com"=20 title=3Dalan.gauld@bt.com>alan.gauld@bt.com</A> </DIV> <DIV style=3D"FONT: 10pt arial"><B>To:</B> <A=20 href=3D"mailto:clanoftheinsane@hotmail.com"=20 title=3Dclanoftheinsane@hotmail.com>clanoftheinsane@hotmail.com</A> ; = <A=20 href=3D"mailto:tutor@python.org" = title=3Dtutor@python.org>tutor@python.org</A>=20 </DIV> <DIV style=3D"FONT: 10pt arial"><B>Sent:</B> Friday, August 24, 2001 = 4:45=20 AM</DIV> <DIV style=3D"FONT: 10pt arial"><B>Subject:</B> RE: [Tutor] Tkinter = help</DIV> <DIV><BR></DIV> <BLOCKQUOTE=20 style=3D"BORDER-LEFT: #0000ff 2px solid; MARGIN-LEFT: 5px; = MARGIN-RIGHT: 0px; PADDING-LEFT: 5px"> <DIV><FONT size=3D2><FONT face=3DArial>When using Tkinter, i want to = have a=20 window within my GUI program that will show the output that you = normally see=20 in the python interpreter window.  for example, i want to have = a button=20 display a list of data, but instead of that data being displayed in = the=20 interpreter, i want it to appear in my actual program in a = widget.  any=20 ideas?<FONT color=3D#0000ff face=3D"Courier New"><SPAN=20 = class=3D640474508-24082001> </SPAN></FONT></FONT></FONT></DIV></BLOC= KQUOTE> <DIV><FONT size=3D2><FONT face=3DArial><FONT color=3D#0000ff=20 face=3D"Courier New"><SPAN class=3D640474508-24082001>Its an idea, no=20 more...</SPAN></FONT></FONT></FONT></DIV> <DIV><FONT size=3D2><FONT face=3DArial><FONT color=3D#0000ff=20 face=3D"Courier New"><SPAN=20 class=3D640474508-24082001></SPAN></FONT></FONT></FONT> </DIV> <DIV><FONT size=3D2><FONT face=3DArial><FONT color=3D#0000ff=20 face=3D"Courier New"><SPAN class=3D640474508-24082001>reassign = sys.stdout to a=20 file.</SPAN></FONT></FONT></FONT></DIV> <DIV><FONT size=3D2><FONT face=3DArial><FONT color=3D#0000ff=20 face=3D"Courier New"><SPAN class=3D640474508-24082001>After every = print call a=20 function that copies that file to a </SPAN></FONT></FONT></FONT></DIV> <DIV><FONT size=3D2><FONT face=3DArial><FONT color=3D#0000ff=20 face=3D"Courier New"><SPAN class=3D640474508-24082001>text=20 widget.</SPAN></FONT></FONT></FONT></DIV> <DIV> </DIV> <DIV><FONT size=3D2><FONT face=3DArial><FONT color=3D#0000ff=20 face=3D"Courier New"><SPAN class=3D640474508-24082001>it might=20 work...</SPAN></FONT></FONT></FONT></DIV> <DIV><FONT size=3D2><FONT face=3DArial><FONT color=3D#0000ff=20 face=3D"Courier New"><SPAN=20 class=3D640474508-24082001></SPAN></FONT></FONT></FONT> </DIV> <DIV><FONT size=3D2><FONT face=3DArial><FONT color=3D#0000ff=20 face=3D"Courier New"><SPAN class=3D640474508-24082001>There is an = example of this=20 in Graysons book I think, but I </SPAN></FONT></FONT></FONT></DIV> <DIV><FONT size=3D2><FONT face=3DArial><FONT color=3D#0000ff=20 face=3D"Courier New"><SPAN class=3D640474508-24082001>dont have access = to it just=20 now. </SPAN></FONT></FONT></FONT></DIV> <DIV><FONT size=3D2><FONT face=3DArial><FONT color=3D#0000ff=20 face=3D"Courier New"><SPAN=20 class=3D640474508-24082001></SPAN></FONT></FONT></FONT> </DIV> <DIV><FONT size=3D2><FONT face=3DArial><FONT color=3D#0000ff=20 face=3D"Courier New"><SPAN class=3D640474508-24082001>Alan=20 G</SPAN></FONT></FONT></FONT></DIV></BLOCKQUOTE></BODY></HTML> ------=_NextPart_000_0008_01C12CBA.1AD09120-- From dyoo@hkn.eecs.berkeley.edu Fri Aug 24 21:44:59 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 24 Aug 2001 13:44:59 -0700 (PDT) Subject: [Tutor] map & lambda to create dictionary from lists? In-Reply-To: <Pine.LNX.4.21.0108240926350.12581-100000@hkn.eecs.berkeley.edu> Message-ID: <Pine.LNX.4.21.0108241323150.16782-100000@hkn.eecs.berkeley.edu> On Fri, 24 Aug 2001, Danny Yoo wrote: > I'm not sure if this is better; tell me what you think of this approach: > > ### > def itemsToDict(items): > dict = {} > for key, value in items: > dict[key] = value Doh! That's what I get for not checking my code. I meant to write: ### def itemsToDict(items): dict = {} for key, value in items: dict[key] = value return dict ### I had forgotten to return the dictionary back to the user. Sorry about that. From dyoo@hkn.eecs.berkeley.edu Fri Aug 24 21:49:58 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 24 Aug 2001 13:49:58 -0700 (PDT) Subject: [Tutor] [Edu-sig] Simple frame buffer module (fwd) Message-ID: <Pine.LNX.4.21.0108241347270.17187-100000@hkn.eecs.berkeley.edu> Hiya everyone, Apologies in advance for being forward about forwarding a message. The following message might be just the thing for people who want to play around with animation and graphical drawing: ---------- Forwarded message ---------- Date: 24 Aug 2001 20:42:19 +0200 From: David Pettersson <dave@whatever.nu> To: edu-sig@python.org Subject: [Edu-sig] Simple frame buffer module Hi, I'd like to announce the simple frame buffer module that I wacked together after being fed up with having to create a GUI every time I wanted to illustrate something simple in Python (such as the iterative improvement of some problem). A short sample: import fb # import module f = fb.FrameBuffer() # create an instance f.open(200, 200, "demo") # open a window named "demo" for i in range(10, 190): # simple loop f.fg = (i, i, i) # set fg colour f.plot(i, i) # plot f.flip() # flip buffers raw_input('enter to quit') # wait for keypress f.close() # close window Could be useful if you want students to be able to create simple graphics without having to teach them a GUI. The extension uses SDL to manage the graphics. The extension is available at http://dave.whatever.nu/python/fb/ Comments, suggestions and bug reports are all very welcome :). Sincerely, -- David Pettersson dave@whatever.nu _______________________________________________ Edu-sig mailing list Edu-sig@python.org http://mail.python.org/mailman/listinfo/edu-sig From dyoo@hkn.eecs.berkeley.edu Fri Aug 24 22:04:55 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 24 Aug 2001 14:04:55 -0700 (PDT) Subject: [Tutor] Tkinter help In-Reply-To: <OE378wSA1XvpFVjCRGr00012e9d@hotmail.com> Message-ID: <Pine.LNX.4.21.0108241356130.17187-100000@hkn.eecs.berkeley.edu> On Fri, 24 Aug 2001, paul wrote: > ok, can somebody give me an example of how to assign sys.stdout to a > file and then print it into a text box? i think i'm missing > something. This might help: Here's an interpreter session that that traps everything coming at sys.stdout into a StringIO object: ### >>> import StringIO >>> io = StringIO.StringIO() >>> import sys >>> sys.stdout = io >>> print "Hello" >>> print "This is a test." >>> io.seek(0) >>> sys.stderr.write(io.read()) ## You can replace this with the ## textbox insert() stuff. Hello This is a test. ### When we use StringIO, we shouldn't forget to seek() the file object to the beginning before we read() it: otherwise, we'll be holding the empty string in our hands. From clanoftheinsane@hotmail.com Fri Aug 24 23:12:26 2001 From: clanoftheinsane@hotmail.com (paul) Date: Fri, 24 Aug 2001 18:12:26 -0400 Subject: [Tutor] Making my program an executable/distributable Message-ID: <OE45hAj5p1Fjxe0ymQ1000084a3@hotmail.com> This is a multi-part message in MIME format. ------=_NextPart_000_0009_01C12CC8.548A0FA0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hello all, i have asked this question before, about a week or so ago, but i just = want to re-ask it in case anyone missed it. i have written a python = program including Tkinter, and when i used py2exe to convert it to an = executable, it called for the riscosenviron, riscos, riscospath, and ce = modules. is this because of my using Tkinter in my script? does py2exe = not support Tkinter? i'm just curious. i finally finished my program, = and i just want to be able to distribute it. please help?!?! thanks a lot, paul brown ------=_NextPart_000_0009_01C12CC8.548A0FA0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML><HEAD> <META content=3D"text/html; charset=3Diso-8859-1" = http-equiv=3DContent-Type> <META content=3D"MSHTML 5.00.2314.1000" name=3DGENERATOR> <STYLE></STYLE> </HEAD> <BODY bgColor=3D#ffffff> <DIV><FONT face=3DArial size=3D2>Hello all,</FONT></DIV> <DIV><FONT face=3DArial size=3D2>i have asked this question before, = about a week or=20 so ago, but i just want to re-ask it in case anyone missed it.  i = have=20 written a python program including Tkinter, and when i used py2exe to = convert it=20 to an executable, it called for the riscosenviron, riscos, riscospath, = and ce=20 modules.  is this because of my using Tkinter in my script?  = does=20 py2exe not support Tkinter?  i'm just curious.  i finally = finished my=20 program, and i just want to be able to distribute it.  please=20 help?!?!</FONT></DIV> <DIV> </DIV> <DIV><FONT face=3DArial size=3D2>thanks a lot,</FONT></DIV> <DIV><FONT face=3DArial size=3D2>paul brown</FONT></DIV></BODY></HTML> ------=_NextPart_000_0009_01C12CC8.548A0FA0-- From Brad.Reisfeld@carrier.utc.com Sat Aug 25 12:30:01 2001 From: Brad.Reisfeld@carrier.utc.com (Reisfeld, Brad CAR) Date: Sat, 25 Aug 2001 07:30:01 -0400 Subject: [Tutor] map & lambda to create dictionary from lists? Message-ID: <590E1FF8B6A4D4118CB200508B63D23E020A6C01@carussyrmb01.carrier.utc.com> Hi, My preferred method for accomplishing this is quite simple: >>> d={} >>> keys = ('name', 'age', 'food') >>> values = ('Monty', 42, 'spam') >>> map(d.setdefault, keys, values) ['Monty', 42, 'spam'] >>> d {'name': 'Monty', 'age': 42, 'food': 'spam'} -Brad ================================= What I've got are two sequences. The first is a sequence of strings that I want to use as the keys of a dictionary. The second is a sequence of objects (strings, numbers, whatever) that I want to use as the values in the dictionary. Of course, the two sequences have a one-to-one correspondence. Here's what I've come up with using map and lambda so far and I want to know if it's Good: Python 2.0 (#1, Jan 8 2001, 10:18:58) [GCC egcs-2.91.66 19990314 (egcs-1.1.2 release)] on sunos5 Type "copyright", "credits" or "license" for more information. >>> d = {} >>> keys = ('name', 'age', 'food') >>> values = ('Monty', 42, 'spam') >>> junk = map(lambda k, v: d.update({k: v}), keys, values) >>> junk [None, None, None] >>> d {'name': 'Monty', 'age': 42, 'food': 'spam'} From lha2@columbia.edu Sat Aug 25 15:40:05 2001 From: lha2@columbia.edu (Lloyd Hugh Allen) Date: Sat, 25 Aug 2001 10:40:05 -0400 Subject: [Tutor] time question References: <E15Zwuo-0004T0-00@mail.python.org> Message-ID: <3B87B8C5.326D4C99@mail.verizon.net> Here's something strange: ----code follows---- >>> quitTime = (2001, 8, 22, 9, 45, -1, -1, -1, -1) >>> import time >>> nowTime = time.localtime(time.time()) >>> nowTime (2001, 8, 25, 10, 0, 54, 5, 237, 1) >>> theDiff = [] >>> for foo in range(len(nowTime)): theDiff.append(nowTime[foo]-quitTime[foo]) >>> theDiff [0, 0, 3, 1, -45, 55, 6, 238, 2] >>> theDiff = tuple(theDiff) >>> theDiff (0, 0, 3, 1, -45, 55, 6, 238, 2) >>> time.localtime(time.mktime(theDiff)) (1999, 12, 2, 23, 15, 55, 3, 336, 0) ----end code------- I had been hoping that time.mktime and time.localtime would intelligently handle the -45 minutes. Seems not to be the case. I trust that with well-formed times they are in fact inverse functions? Here's my go at a real solution: -----code starts---- >>> def convertTime(theDiff): """Returns a time tuple with strictly positive elements. Note that this function does not intelligently handle months, but assumes that all months are 28 days long.""" offSet = [0, 12, 28, 24, 60] theDiff = list(theDiff) for foo in range(len(theDiff)-1, 0, -1): if theDiff[foo]<0: theDiff[foo] = theDiff[foo] + offSet[foo] theDiff[foo-1] = theDiff[foo-1] - 1 theDiff = tuple(theDiff) return theDiff ----end code-------- -LHA From dyoo@hkn.eecs.berkeley.edu Sat Aug 25 19:22:55 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 25 Aug 2001 11:22:55 -0700 (PDT) Subject: [Tutor] Making my program an executable/distributable In-Reply-To: <OE45hAj5p1Fjxe0ymQ1000084a3@hotmail.com> Message-ID: <Pine.LNX.4.21.0108251118030.30673-100000@hkn.eecs.berkeley.edu> On Fri, 24 Aug 2001, paul wrote: > i have asked this question before, about a week or so ago, but i just > want to re-ask it in case anyone missed it. i have written a python > program including Tkinter, and when i used py2exe to convert it to an > executable, it called for the riscosenviron, riscos, riscospath, and > ce modules. is this because of my using Tkinter in my script? does > py2exe not support Tkinter? i'm just curious. i finally finished my > program, and i just want to be able to distribute it. please help?!?! According to the py2exe web site, http://starship.python.net/crew/theller/py2exe/ py2exe should fully support Tkinter programs. Let's see... can you show us both your script and the Setup.py file you've set up? I personally don't have Windows, but many people on the list do, so one us should be able to investigate this. Good luck to you! From clanoftheinsane@hotmail.com Sat Aug 25 19:50:57 2001 From: clanoftheinsane@hotmail.com (paul) Date: Sat, 25 Aug 2001 14:50:57 -0400 Subject: [Tutor] Making my program an executable/distributable References: <Pine.LNX.4.21.0108251118030.30673-100000@hkn.eecs.berkeley.edu> Message-ID: <OE63ZTHfyQgeDKvPEkG000002a4@hotmail.com> This is a multi-part message in MIME format. ------=_NextPart_000_0007_01C12D75.5927F920 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: 7bit > > i have asked this question before, about a week or so ago, but i just > > want to re-ask it in case anyone missed it. i have written a python > > program including Tkinter, and when i used py2exe to convert it to an > > executable, it called for the riscosenviron, riscos, riscospath, and > > ce modules. is this because of my using Tkinter in my script? does > > py2exe not support Tkinter? i'm just curious. i finally finished my > > program, and i just want to be able to distribute it. please help?!?! > > According to the py2exe web site, > > http://starship.python.net/crew/theller/py2exe/ > > py2exe should fully support Tkinter programs. Let's see... can you show > us both your script and the Setup.py file you've set up? I personally > don't have Windows, but many people on the list do, so one us should be > able to investigate this. > > Good luck to you! ok, my files are attached to this email ------=_NextPart_000_0007_01C12D75.5927F920 Content-Type: text/plain; name="guifun.py" Content-Transfer-Encoding: quoted-printable Content-Disposition: attachment; filename="guifun.py" from Tkinter import * import sys import StringIO io=3DStringIO.StringIO() sys.stdout=3Dio def list(): global ListFrame ListFrame=3DFrame(master, relief=3D"ridge", bd=3D2, height=3D400, = width=3D300) ListFrame.grid(columnspan=3D4, row=3D2, pady=3D3) f=3Dopen("C:/python20/forlist.py") b=3Df.readlines() numberOfBooks=3Dlen(b) print "\nBooks:" for i in range(0,numberOfBooks): e=3Db[i].split(',') print e[0] done=3D1 io.seek(0) t=3DText(ListFrame, height=3D20, width=3D40) t.grid() t.insert(INSERT, io.read()) quitButton=3DButton(ListFrame, text=3D"Done", command=3DQuitList) quitButton.grid(row=3D1) io.seek(2) def QuitList(): ListFrame.destroy() #Book View def viewABook(): global ViewFrame ViewFrame=3DFrame(master, relief=3D"ridge", bd=3D2, height=3D400, = width=3D300) ViewFrame.grid(columnspan=3D4, row=3D2, pady=3D3) =20 global bookEntry bookLabel=3DLabel(ViewFrame, text=3D"Book: ") bookLabel.grid(row=3D0, column=3D0) bookEntry=3DEntry(ViewFrame, width=3D40) bookEntry.grid(row=3D0, column=3D1, columnspan=3D2) bookButton=3DButton(ViewFrame, text=3D"Finish", = command=3DfinishView) bookButton.grid(row=3D1, column=3D1) quitButton=3DButton(ViewFrame, text=3D"Done", = command=3DViewFrame.destroy) quitButton.grid(row=3D1, column=3D2) =20 def finishView(): bookWanted=3DbookEntry.get() f=3Dopen("C:/python20/forlist.py") b=3Df.readlines() numberOfBooks=3Dlen(b) for i in range(0,numberOfBooks): e=3Db[i].split(',') c=3Dlen(e) if bookWanted=3D=3De[0]: print """ ------------Keywords for: %s ------------Author: %s""" %(e[0], e[1]) =20 for i in range(c-3): print "-------------", e[i+2].lstrip() done=3D1 =20 #Search Suite def search(): global SearchFrame SearchFrame=3DFrame(master, relief=3D"ridge", bd=3D2, height=3D400, = width=3D400) SearchFrame.grid(columnspan=3D4, row=3D2, pady=3D3) byAuthor=3DButton(SearchFrame, text=3D"By Author", = command=3DbyAuthorView) byTitle=3DButton(SearchFrame, text=3D"By Title", = command=3DbyTitleView) byKeyword=3DButton(SearchFrame, text=3D"By Keyword", = command=3DbyKeywordView) byAuthor.grid(row=3D0, column=3D0, padx=3D3) byTitle.grid(row=3D0, column=3D1, padx=3D3) byKeyword.grid(row=3D0, column=3D2, padx=3D3) Finishbutton=3DButton(SearchFrame, text=3D"Finish Search", = command=3DallFinish) Finishbutton.grid(row=3D0, column=3D3) def allFinish(): SearchFrame.destroy() def byAuthorView(): global authorEntry global authorLabel global finishButton global quitButton authorLabel=3DLabel(SearchFrame, text=3D"Author: ") authorLabel.grid(row=3D1, column=3D0) authorEntry=3DEntry(SearchFrame, width=3D36) authorEntry.grid(row=3D1, column=3D1, columnspan=3D3, pady=3D2) finishButton=3DButton(SearchFrame, text=3D"Finish", = command=3DbyAuthor) finishButton.grid(row=3D2, column=3D1) quitButton=3DButton(SearchFrame, text=3D"Quit", = command=3DbyAuthorQuit) quitButton.grid(row=3D2, column=3D2) =20 def byAuthor(): authWanted=3DauthorEntry.get() f=3Dopen("C:/python20/forlist.py") b=3Df.readlines() numberOfBooks=3Dlen(b) for i in range(0,numberOfBooks): e=3Db[i].split(',') c=3Dlen(e) if authWanted=3D=3De[1]: print "\n-------Author: ",e[1] print "---------Book: ",e[0] for i in range (c-3): print "-----Keywords: ",e[i+2] authorEntry.delete(0,40) done=3D1 def byAuthorQuit(): authorEntry.destroy() authorLabel.destroy() finishButton.destroy() quitButton.destroy() =20 def byTitleView(): global titleEntry global titleLabel global finishButton global quitButton titleLabel=3DLabel(SearchFrame, text=3D"Title: ") titleLabel.grid(row=3D1, column=3D0) titleEntry=3DEntry(SearchFrame, width=3D36) titleEntry.grid(row=3D1, column=3D1, columnspan=3D3, pady=3D2) finishButton=3DButton(SearchFrame, text=3D"Finish", = command=3DbyTitle) finishButton.grid(row=3D2, column=3D1) quitButton=3DButton(SearchFrame, text=3D"Quit", = command=3DbyTitleQuit) quitButton.grid(row=3D2, column=3D2) def byTitle(): titleWanted=3DtitleEntry.get() f=3Dopen("C:/python20/forlist.py") b=3Df.readlines() numberOfBooks=3Dlen(b) for i in range(0,numberOfBooks): e=3Db[i].split(',') c=3Dlen(e) if titleWanted=3D=3De[0]: print "\n-------Author: ",e[1] print "---------Book: ",e[0] for i in range (c-3): print "-----Keywords: ",e[i+2] done=3D1 def byTitleQuit(): titleEntry.destroy() titleLabel.destroy() finishButton.destroy() quitButton.destroy() def byKeywordView(): global keywordEntry global keywordLabel global finishButton global quitButton keywordLabel=3DLabel(SearchFrame, text=3D"Keyword: ") keywordLabel.grid(row=3D1, column=3D0) keywordEntry=3DEntry(SearchFrame, width=3D36) keywordEntry.grid(row=3D1, column=3D1, columnspan=3D3, pady=3D2) finishButton=3DButton(SearchFrame, text=3D"Finish", = command=3DbyKeyword) finishButton.grid(row=3D2, column=3D1) quitButton=3DButton(SearchFrame, text=3D"Quit", = command=3DbyKeywordQuit) quitButton.grid(row=3D2, column=3D2) def byKeyword(): kwWanted=3DkeywordEntry.get() f=3Dopen("C:/python20/forlist.py") b=3Df.readlines() numberOfBooks=3Dlen(b) for i in range(0,numberOfBooks): e=3Db[i].split(',') c=3Dlen(e) if kwWanted in e[2:]: print "\n-------Author: ",e[1] print "---------Book: ",e[0] for i in range (c-3): print "-----Keywords: ",e[i+2] done=3D1 def byKeywordQuit(): keywordEntry.destroy() keywordLabel.destroy() finishButton.destroy() quitButton.destroy() =20 #Add an Entry def addview(): global AddFrame AddFrame=3DFrame(master, relief=3D"ridge", bd=3D2, height=3D400, = width=3D300) AddFrame.grid(columnspan=3D4, row=3D2, pady=3D3) global authorLabel global titleLabel global keywordLabel authorLabel=3DLabel(AddFrame, text=3D"Author: ") titleLabel=3DLabel(AddFrame, text=3D"Title: ") keywordLabel=3DLabel(AddFrame, text=3D"Keywords: ") authorLabel.grid(row=3D1, column=3D0, pady=3D2) titleLabel.grid(row=3D2, column=3D0) keywordLabel.grid(row=3D3, column=3D0) global authorEntry global titleEntry global keywordEntry authorEntry=3DEntry(AddFrame, width=3D37) titleEntry=3DEntry(AddFrame, width=3D37) keywordEntry=3DEntry(AddFrame, width=3D37) authorEntry.grid(row=3D1, column=3D1, columnspan=3D3) titleEntry.grid(row=3D2, column=3D1, columnspan=3D3) keywordEntry.grid(row=3D3, column=3D1, columnspan=3D3) enterButton=3DButton(AddFrame, text=3D"Add Book", command=3Dadd) enterButton.grid(row=3D4, column=3D2) quitButton=3DButton(AddFrame, text=3D"Done", command=3DaddQuit) quitButton.grid(row=3D4, column=3D3) def add(): title=3DtitleEntry.get() author=3DauthorEntry.get() keyword=3DkeywordEntry.get() a=3Dkeyword.split(',') b=3Dlen(a) for i in range(b): a[i].strip() f=3Dopen("C:/Python20/forlist.py", 'a') f.write("%s,%s," %(title, author)) for i in range(b): f.write("%s," %(a[i])) f.write("\n") titleEntry.delete(0,37) authorEntry.delete(0,37) keywordEntry.delete(0,37) def addQuit(): AddFrame.destroy() #About the Application def about(): bottomFrame=3DFrame(master, relief=3D"ridge", bd=3D3, height=3D400, = width=3D300) bottomFrame.grid(row=3D2, pady=3D3) global AboutFrame AboutFrame=3DFrame(master, relief=3D"ridge", bd=3D2, height=3D400, = width=3D300) AboutFrame.grid(columnspan=3D4, row=3D2, pady=3D3) aboutLabel1=3DLabel(AboutFrame, text=3D"BookDB version 0.6") aboutLabel2=3DLabel(AboutFrame, text=3D"Developed by Paul Brown") aboutLabel1.grid() aboutLabel2.grid() aboutQuitButton=3DButton(AboutFrame, text=3D"Quit", = command=3DaboutQuit) aboutQuitButton.grid() def aboutQuit(): AboutFrame.destroy() master=3DTk() master.geometry('500x450') newFrame=3DFrame(master, relief=3D"ridge", bd=3D3) newFrame.grid(pady=3D2, row=3D0) HruleFm=3DFrame(master, relief=3D"ridge", bd=3D1, height=3D3, = width=3D500) HruleFm.grid(row=3D1) ListButton=3DButton(newFrame, text=3D"List Books", command=3Dlist) ListButton.grid(column=3D0, row=3D0, pady=3D1, padx=3D1) KeywordButton=3DButton(newFrame, text=3D"Book Keywords", = command=3DviewABook) KeywordButton.grid(column=3D1, row=3D0, pady=3D1, padx=3D1) SearchButton=3DButton(newFrame, text=3D"Search", command=3Dsearch) SearchButton.grid(column=3D2, row=3D0, pady=3D1, padx=3D1) AddButton=3DButton(newFrame, text=3D"Add Entry", command=3Daddview) AddButton.grid(column=3D3, row=3D0, pady=3D1, padx=3D1) AboutButton=3DButton(newFrame, text=3D"About BookDB", command=3Dabout) AboutButton.grid(column=3D4, row=3D0, pady=3D1, padx=3D1) ExitButton=3DButton(newFrame, text=3D"Exit Program", = command=3Dmaster.destroy) ExitButton.grid(column=3D5, row=3D0) bottomFrame=3DFrame(master, relief=3D"ridge", bd=3D3, height=3D400, = width=3D300) bottomFrame.grid(row=3D2, pady=3D3) ------=_NextPart_000_0007_01C12D75.5927F920 Content-Type: text/plain; name="setup.py" Content-Transfer-Encoding: 7bit Content-Disposition: attachment; filename="setup.py" from distutils.core import setup import py2exe setup(name="BookDB", scripts=["guifun.py"]) ------=_NextPart_000_0007_01C12D75.5927F920-- From kstoner@netins.net Sat Aug 25 20:14:11 2001 From: kstoner@netins.net (Katharine Stoner) Date: Sat, 25 Aug 2001 14:14:11 -0500 Subject: [Tutor] unsubscribing Message-ID: <001e01c12d9b$4b23c220$8152b1cf@oemcomputer> This is a multi-part message in MIME format. ------=_NextPart_000_0007_01C12D70.369F9660 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Dear all, If anyone here can take me off the python tutor group much would be = apreciated. I forgot my password and so cannot do it myself. -thanks Cameron ------=_NextPart_000_0007_01C12D70.369F9660 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML><HEAD> <META content=3D"text/html; charset=3Diso-8859-1" = http-equiv=3DContent-Type> <META content=3D"MSHTML 5.00.2614.3500" name=3DGENERATOR> <STYLE></STYLE> </HEAD> <BODY bgColor=3D#ffffff> <DIV><FONT face=3DArial size=3D2>Dear all,</FONT></DIV> <DIV> </DIV> <DIV><FONT face=3DArial size=3D2>If anyone here can take me off the = python tutor=20 group much would be apreciated.  I forgot my password and so cannot = do it=20 myself.</FONT></DIV> <DIV> </DIV> <DIV><FONT face=3DArial size=3D2>-thanks</FONT></DIV> <DIV><FONT face=3DArial size=3D2>Cameron</FONT></DIV> <DIV> </DIV></BODY></HTML> ------=_NextPart_000_0007_01C12D70.369F9660-- From rob@jam.rr.com Sat Aug 25 20:39:36 2001 From: rob@jam.rr.com (Rob Andrews) Date: Sat, 25 Aug 2001 14:39:36 -0500 Subject: [Tutor] unsubscribing References: <001e01c12d9b$4b23c220$8152b1cf@oemcomputer> Message-ID: <3B87FEF8.3FE94D4E@jam.rr.com> Katharine Stoner wrote: > > Part 1.1 Type: Plain Text (text/plain) > Encoding: quoted-printable Sorry to see you go. It wasn't our breath, was it? -- A {} is a terrible thing to waste. Useless Python! http://www.lowerstandard.com/python From python tutor" <tutor@python.org Sun Aug 26 00:36:08 2001 From: python tutor" <tutor@python.org (Tim Peters) Date: Sat, 25 Aug 2001 19:36:08 -0400 Subject: [Tutor] unsubscribing In-Reply-To: <001e01c12d9b$4b23c220$8152b1cf@oemcomputer> Message-ID: <LNBBLJKPBEHFEDALKOLCOEAPLIAA.tim.one@home.com> > If anyone here can take me off the python tutor group much would be > apreciated. I forgot my password and so cannot do it myself. Then go to http://mail.python.org/mailman/options/tutor/kstoner--at--netins.net and click the "Email My Password To Me" button. We can't remove you, because we have no way to know that you're you <wink>. From allan.crooks@btinternet.com Sun Aug 26 03:14:35 2001 From: allan.crooks@btinternet.com (Allan Crooks) Date: Sun, 26 Aug 2001 03:14:35 +0100 Subject: [Tutor] map, filter and lambda functions [filter can take None] In-Reply-To: <Pine.LNX.4.21.0108230001510.6321-100000@hkn.eecs.berkeley.edu> References: <3B849AEB.28396.402B905@localhost> Message-ID: <3B88699B.30252.391F011@localhost> > > *Why* it works? Just because filter is designed to work that way. > > Initially I was going to suggest a way of doing that, but instead of > > None, I was going to suggest the truth function from the operator > > module. > > > > None certainly isn't a function though. > > [Note: skip if you're not interested in looking at Python icky C > internals.] > > > Feeding 'None' as a "function" is a special case that's particular > only to Python's implementation of filter(), that is, this is > hardcoded to recognize this unusual input. It certainly doesn't do it > for a human-intuitive reason. *grin* > > If we're interested in looking at C code, we can glance at the > relevant code in the 'bltinmodule.c' file under the function > "builtin_filter()": <snip> And yet again, a question that could only be solved by looking at the C code is answered by Danny. Only he would wade through the source, make it understandable and explain it for us, so I'll take this opportunity to thank him for it. :) And while I'm at it, I'll thank him for his explanation of how hashing works, as well as a request from a long time ago about what buffers were. Thank you very much Danny. :) Oh, and I think you spend too much time looking through Python's source than can possibly be healthy, but I reckon you knew that already. :))) Allan. From sheila@thinkspot.net Sun Aug 26 03:39:04 2001 From: sheila@thinkspot.net (Sheila King) Date: Sat, 25 Aug 2001 19:39:04 -0700 Subject: [Tutor] map, filter and lambda functions [filter can take None] In-Reply-To: <3B88699B.30252.391F011@localhost> References: <3B849AEB.28396.402B905@localhost> <Pine.LNX.4.21.0108230001510.6321-100000@hkn.eecs.berkeley.edu> <3B88699B.30252.391F011@localhost> Message-ID: <4208C970413@kserver.org> On Sun, 26 Aug 2001 03:14:35 +0100, "Allan Crooks" <allan.crooks@btinternet.com> wrote about Re: [Tutor] map, filter and lambda functions [filter can take None]: :And yet again, a question that could only be solved by looking at :the C code is answered by Danny. Only he would wade through the :source, make it understandable and explain it for us, so I'll take :this opportunity to thank him for it. :) Yes, thank-you, Danny! -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From tim.one@home.com Sun Aug 26 04:31:08 2001 From: tim.one@home.com (Tim Peters) Date: Sat, 25 Aug 2001 23:31:08 -0400 Subject: [Tutor] map, filter and lambda functions [filter can take None] In-Reply-To: <3B88699B.30252.391F011@localhost> Message-ID: <LNBBLJKPBEHFEDALKOLCMEBFLIAA.tim.one@home.com> [Danny Yoo] > ... > Feeding 'None' as a "function" is a special case that's particular > only to Python's implementation of filter(), that is, this is > hardcoded to recognize this unusual input. It certainly doesn't do it > for a human-intuitive reason. *grin* [Allan Crooks] > And yet again, a question that could only be solved by looking at > the C code is answered by Danny. Only he would wade through the > source, make it understandable and explain it for us, so I'll take > this opportunity to thank him for it. :) At some point after thanking him, you might try reading the docs too <wink>. The special behavior of None when fed to filter() has been documented for years: http://www.python.org/doc/current/lib/built-in-funcs.html In fact, a great way to learn a lot about Python is to play with the docs for the builtin functions, trying them one at a time. From jstanley@start.com.au Sun Aug 26 04:46:56 2001 From: jstanley@start.com.au (Jordan Stanley) Date: Sun, 26 Aug 2001 4:46:56 +0100 Subject: [Tutor] py2exe Tkinter Message-ID: <B3009339017@i01sv4161.i01rd0002.ids1.intelonline.com> >From: "paul" <clanoftheinsane@hotmail.com> >To: <tutor@python.org> >Date: Fri, 24 Aug 2001 18:12:26 -0400 >Subject: [Tutor] Making my program an executable/distributable > >Hello all, >i have asked this question before, about a week or so ago, but i just = >want to re-ask it in case anyone missed it. i have written a python = >program including Tkinter, and when i used py2exe to convert it to an = >executable, it called for the riscosenviron, riscos, riscospath, and ce = >modules. is this because of my using Tkinter in my script? does py2exe = >not support Tkinter? i'm just curious. i finally finished my program, = >and i just want to be able to distribute it. please help?!?! > >thanks a lot, >paul brown > I not even remotely an expert. but it seems to me that you have not set some paths for where python et al can find files it needs to function. __________________________________________________________________ Get your free Australian email account at http://www.start.com.au From allan.crooks@btinternet.com Sun Aug 26 06:39:18 2001 From: allan.crooks@btinternet.com (Allan Crooks) Date: Sun, 26 Aug 2001 06:39:18 +0100 Subject: [Tutor] map, filter and lambda functions [filter can take None] In-Reply-To: <LNBBLJKPBEHFEDALKOLCMEBFLIAA.tim.one@home.com> References: <3B88699B.30252.391F011@localhost> Message-ID: <3B889996.11296.A239BB@localhost> On 25 Aug 2001, at 23:31, Tim Peters wrote: > At some point after thanking him, you might try reading the docs too > <wink>. In my defence, I'll say that Danny, instead of heading to the docs, delved straight into the C code without a second thought. So I'm not the only one to forget about the docs. :) Allan. From revo630@hotmail.com Sun Aug 26 13:55:56 2001 From: revo630@hotmail.com (revo 630) Date: Sun, 26 Aug 2001 15:55:56 +0300 Subject: [Tutor] (no subject) Message-ID: <F2235b6KZmcK8r6beUz0000d0a9@hotmail.com> Hi Just newbie in this program, can i used Linux & microsoft windows in the same hard disk, if this will crash my hard disk because of the OS? Thanks. jam _________________________________________________________________ Get your FREE download of MSN Explorer at http://explorer.msn.com/intl.asp From toodles@yifan.net Sun Aug 26 14:23:02 2001 From: toodles@yifan.net (Andrew Wilkins) Date: Sun, 26 Aug 2001 21:23:02 +0800 Subject: [Tutor] (no subject) In-Reply-To: <F2235b6KZmcK8r6beUz0000d0a9@hotmail.com> Message-ID: <FPEHJJPEEOIPMAHOADBKAEGECFAA.toodles@yifan.net> > Hi Hi > Just newbie in this program, can i used Linux & microsoft windows in the > same hard disk, if this will crash my hard disk because of the OS? Okay first of all, this has nothing whatsoever to do with Python, but I'll be a kind soul and answer the question anyway. You can use a dual-boot program to run both Linux and MS Windows on the same hard disk. I've never tried it, but a friend of mine has and he recommends BootMagic by PowerQuest Corporation. http://www.bootmagic.com > Thanks. No worries, but please keep to the topic of Python. > > > jam > > _________________________________________________________________ > Get your FREE download of MSN Explorer at http://explorer.msn.com/intl.asp > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From epoch7@charter.net Sun Aug 26 16:24:16 2001 From: epoch7@charter.net (epoch7) Date: Sun, 26 Aug 2001 11:24:16 -0400 Subject: [Tutor] Callable? Whats callable? Message-ID: <002001c12e43$2b37faa0$92b1f018@p3550> This is a multi-part message in MIME format. ------=_NextPart_000_001D_01C12E21.A4064F80 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable I'm new to programming, python, and even this list! So hopefullt someone = could give me a hand with my first program. import re file1 =3D raw_input("Name of file to convert: ") file2 =3D raw_input("Name of file to output to: ") in_file =3D open(file1, "r") out_file =3D open(file2, "w") x =3D in_file.read() y =3D """%s""" (x) text =3D re.compile('url=3D(\w*)&', re.IGNORECASE) text.findall(y) in_file.close() out_file.close() thats it. it's the latest incantation of this program, ive been trying = really hard to get this workin'. here's the error i get:=20 Traceback (most recent call last): File "F:\Python21\reusage.py", line 10, in ? y =3D """%s""" (x) TypeError: object of type 'string' is not callable And for those of you just wondering what im trying to do, its supposed = to search out for strings of text between to strings("url=3D" and "&"). and then output the list of = strings to a file. Seems simple enough but I guess i really bit off more than i could chew = for my first real program! :( will ------=_NextPart_000_001D_01C12E21.A4064F80 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML><HEAD> <META content=3D"text/html; charset=3Diso-8859-1" = http-equiv=3DContent-Type> <META content=3D"MSHTML 5.00.3315.2870" name=3DGENERATOR> <STYLE></STYLE> </HEAD> <BODY bgColor=3D#ffffff> <DIV><FONT face=3DArial size=3D2>I'm new to programming, python, and = even this list!=20 So hopefullt someone could give me a hand with my first = program.</FONT></DIV> <DIV> </DIV> <DIV><FONT face=3DArial size=3D2>import re<BR></FONT></DIV> <DIV><FONT face=3DArial size=3D2>file1 =3D raw_input("Name of file to = convert:=20 ")<BR>file2 =3D raw_input("Name of file to output to: ")<BR>in_file =3D = open(file1,=20 "r")<BR>out_file =3D open(file2, "w")<BR>x =3D = in_file.read()<BR>y =3D=20 """%s""" (x)<BR>text =3D re.compile('url=3D(\w*)&',=20 re.IGNORECASE)<BR>text.findall(y)<BR>in_file.close()<BR>out_file.close()<= /FONT></DIV> <DIV> </DIV> <DIV><FONT face=3DArial size=3D2>thats it. it's the latest incantation = of this=20 program, ive been trying really hard to get this workin'.</FONT></DIV> <DIV><FONT face=3DArial size=3D2>here's the error i get: </FONT></DIV> <DIV> </DIV> <DIV><FONT face=3DArial size=3D2>Traceback (most recent call = last):<BR>  File=20 "F:\Python21\reusage.py", line 10, in ?<BR>    y =3D = """%s"""=20 (x)<BR>TypeError: object of type 'string' is not callable</FONT></DIV> <DIV> </DIV> <DIV><FONT face=3DArial size=3D2>And for those of you just wondering = what im=20 trying to do, its supposed to search out for strings of = text</FONT></DIV> <DIV><FONT face=3DArial size=3D2>between to strings("url=3D" and = "&").  and=20 then output the list of strings to a file.</FONT></DIV> <DIV> </DIV> <DIV><FONT face=3DArial size=3D2>Seems simple enough but I guess i = really bit off=20 more than i could chew for my first real program! :(</FONT></DIV> <DIV> </DIV> <DIV><FONT face=3DArial size=3D2>will</FONT></DIV></BODY></HTML> ------=_NextPart_000_001D_01C12E21.A4064F80-- From alan.gauld@bt.com Sun Aug 26 16:23:38 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun, 26 Aug 2001 16:23:38 +0100 Subject: [Tutor] Tkinter help Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BEE2@mbtlipnt02.btlabs.bt.co.uk> > This might help: Here's an interpreter session that that > traps everything coming at sys.stdout into a StringIO object: > ### > >>> import StringIO > >>> io = StringIO.StringIO() > >>> import sys > >>> sys.stdout = io Neat Danny, I'd forgotten about stringIO in Python. Better than clunking around opening and closing temp files etc. I like it! :-) Alan G From sheila@thinkspot.net Sun Aug 26 16:27:48 2001 From: sheila@thinkspot.net (Sheila King) Date: Sun, 26 Aug 2001 08:27:48 -0700 Subject: [Tutor] Callable? Whats callable? In-Reply-To: <002001c12e43$2b37faa0$92b1f018@p3550> References: <002001c12e43$2b37faa0$92b1f018@p3550> Message-ID: <20F66B28CB@kserver.org> On Sun, 26 Aug 2001 11:24:16 -0400, "epoch7" <epoch7@charter.net> wrote about [Tutor] Callable? Whats callable?: :Traceback (most recent call last): : File "F:\Python21\reusage.py", line 10, in ? : y = """%s""" (x) :TypeError: object of type 'string' is not callable : try changing this line: y = """%s""" (x) to this: y = """%s""" % x At least the program runs now. I don't know if it does what you want, but it won't give that error any more... -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From rob@jam.rr.com Sun Aug 26 16:28:53 2001 From: rob@jam.rr.com (Rob Andrews) Date: Sun, 26 Aug 2001 10:28:53 -0500 Subject: [Tutor] Callable? Whats callable? References: <002001c12e43$2b37faa0$92b1f018@p3550> Message-ID: <3B8915B5.CF6F1FD@jam.rr.com> > epoch7 wrote: > > I'm new to programming, python, and even this list! So hopefullt > someone could give me a hand with my first program. > > import re > file1 = raw_input("Name of file to convert: ") > file2 = raw_input("Name of file to output to: ") > in_file = open(file1, "r") > out_file = open(file2, "w") > x = in_file.read() > y = """%s""" (x) > text = re.compile('url=(\w*)&', re.IGNORECASE) > text.findall(y) > in_file.close() > out_file.close() > > thats it. it's the latest incantation of this program, ive been trying > really hard to get this workin'. > here's the error i get: > > Traceback (most recent call last): > File "F:\Python21\reusage.py", line 10, in ? > y = """%s""" (x) > TypeError: object of type 'string' is not callable > > And for those of you just wondering what im trying to do, its supposed > to search out for strings of text > between to strings("url=" and "&"). and then output the list of > strings to a file. > > Seems simple enough but I guess i really bit off more than i could > chew for my first real program! :( > > will I saved your source as somedudesfile.py and ran it from within IDLE. Here's what happened: Python 2.1.1 (#20, Jul 26 2001, 11:38:51) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. IDLE 0.8 -- press F1 for help >>> import somedudesfile Name of file to convert: C:\someletters.txt Name of file to output to: C:\someletters2.txt Traceback (most recent call last): File "<pyshell#0>", line 1, in ? import somedudesfile File "E:\Python21\somedudesfile.py", line 8, in ? y = """%s""" (x) TypeError: object of type 'string' is not callable Then I went into the source file and changed this line: y = """%s""" (x) to this line: y = """%s""" % (x) After saving the file, it reloads without error. >>> import somedudesfile >>> reload(somedudesfile) Name of file to convert: C:\someletters.txt Name of file to output to: C:\someletters2.txt <module 'somedudesfile' from 'E:\Python21\somedudesfile.py'> >>> You were almost there, it looks like. And your first program seems to be more impressive than my first Python program: print 'hello world' Rob -- A {} is a terrible thing to waste. Useless Python! http://www.lowerstandard.com/python From epoch7@charter.net Sun Aug 26 16:40:34 2001 From: epoch7@charter.net (epoch7) Date: Sun, 26 Aug 2001 11:40:34 -0400 Subject: [Tutor] Callable? Whats callable? References: <002001c12e43$2b37faa0$92b1f018@p3550> <20F66B28CB@kserver.org> Message-ID: <000e01c12e45$72aff5c0$92b1f018@p3550> > :Traceback (most recent call last): > : File "F:\Python21\reusage.py", line 10, in ? > : y = """%s""" (x) > :TypeError: object of type 'string' is not callable > : > > try changing this line: > y = """%s""" (x) > > to this: > y = """%s""" % x > > > At least the program runs now. I don't know if it does what you want, > but it won't give that error any more... True enough, now i try to call it(CALLable, i was thinking of it like CALable, must have shorted out a braincell) and i get no list, and i tried to print y and it locked up python. From lha2@columbia.edu Sun Aug 26 16:41:31 2001 From: lha2@columbia.edu (Lloyd Hugh Allen) Date: Sun, 26 Aug 2001 11:41:31 -0400 Subject: [Tutor] Callable? Whats callable? References: <E15b1gk-0004VU-00@mail.python.org> Message-ID: <3B8918AB.1149F826@mail.verizon.net> "epoch7" on Sun, 26 Aug 2001 11:24:16 wrote: > I'm new to programming, python, and even this list! So hopefullt someone = > could give me a hand with my first program. > >.... >(program) > y =3D """%s""" (x) >(more program) >.... > > here's the error i get:=20 > Traceback (most recent call last): > File "F:\Python21\reusage.py", line 10, in ? > y =3D """%s""" (x) > TypeError: object of type 'string' is not callable If you want %s to have the value of x formatted as a string, use y = """%s""" %x or y = """%s""" %(x) Since this string fits on one line, feel free to use single " or ' instead of triple. If you want to reference the xth character of a string, then you use square brackets (that's not what it looks that you're trying to call """%s""" as a function, which you can't do, because it's not a function. Please, please, please do not post as html. It junks up the messages with garbage characters for we folks who read the list in digest form (as well as possible some of those *nix folk). Thanks, good luck. -LHA From sheila@thinkspot.net Sun Aug 26 16:44:52 2001 From: sheila@thinkspot.net (Sheila King) Date: Sun, 26 Aug 2001 08:44:52 -0700 Subject: [Tutor] Callable? Whats callable? In-Reply-To: <000e01c12e45$72aff5c0$92b1f018@p3550> References: <002001c12e43$2b37faa0$92b1f018@p3550> <20F66B28CB@kserver.org> <000e01c12e45$72aff5c0$92b1f018@p3550> Message-ID: <30986C4227@kserver.org> On Sun, 26 Aug 2001 11:40:34 -0400, "epoch7" <epoch7@charter.net> wrote about Re: [Tutor] Callable? Whats callable?: :> try changing this line: :> y = """%s""" (x) :> :> to this: :> y = """%s""" % x :> :> :> At least the program runs now. I don't know if it does what you want, :> but it won't give that error any more... : :True enough, now i try to call it(CALLable, i was thinking of it like :CALable, must have shorted out a braincell) :and i get no list, and i tried to print y and it locked up python. Well, I ran this code: import re file1 = raw_input("Name of file to convert: ") file2 = raw_input("Name of file to output to: ") in_file = open(file1, "r") out_file = open(file2, "w") x = in_file.read() y = """%s""" % x text = re.compile('url=(\w*)&', re.IGNORECASE) text.findall(y) in_file.close() out_file.close() and I got no reported errors. I'm no good at the regular expressions stuff, so I can't help you there. But you might try adding some print statements into the code, so you can see what is going on in the program. You know, like after x = in_file.read() do a print x and after y = '''%s''' % x do a print y and so on. This might help you to track down where any errors are occurring. -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From alan.gauld@bt.com Sun Aug 26 16:39:26 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun, 26 Aug 2001 16:39:26 +0100 Subject: [Tutor] (no subject) Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BEE3@mbtlipnt02.btlabs.bt.co.uk> > Just newbie in this program, can i used Linux & microsoft > windows in the same hard disk, if this will crash my hard > disk because of the OS? This isn't even remotely connected to Python but to answer anyway... Yes you can put Linux and Windows on the same disk, in fact I'd guess most Linux desktops work that way. You will need to partition your disk to do this but most Linux distributions include a tool(eg fips or maybe Partition Magic) for doing this (take a backup first!). Then install Linux into the newly created partions. At the end of the install process you will be asked if you want to install LILO, say yes. After everything is installed and you reboot you will get a lilo: prompt. Hit tab and you should see a text list of options. type linux or win98 depending on which one you want to run. You can even set it up so that Linux programs can see your Windows partition(but not the other way around I think). Having said all that its probably preferrable to use a completely separate disk for Linux, but just to keep things simple not because 1 disk won't work. Finally, just to justiofy the post, one of the great things about Python is that you can install it on both Windows and Linux and most of the time the programs will work on both OS without change... HTH, Alan g (Who is just about to reinstall Linux after a 6 month gap...:-) From alan.gauld@bt.com Sun Aug 26 16:45:00 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun, 26 Aug 2001 16:45:00 +0100 Subject: [Tutor] Callable? Whats callable? Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BEE4@mbtlipnt02.btlabs.bt.co.uk> ------_=_NextPart_001_01C12E46.1084C690 Content-type: text/plain; charset="ISO-8859-1" I'm new to programming, python, and even this list! Looks like your doing all the right things so far, welcome :-) import re file1 = raw_input("Name of file to convert: ") file2 = raw_input("Name of file to output to: ") in_file = open(file1, "r") out_file = open(file2, "w") x = in_file.read() OK down to here, you now have the contents of file1 stored as a long string in x... y = """%s""" (x) You meant to do: y="%s" % x The triple quotes aren't needed and the parens are only needed if theres several items to insert into the format string. The reason you got the callable error was you had parens after the string so But why are you copying the string in x into y? I can't see the reason for doing it. text = re.compile('url=(\w*)&', re.IGNORECASE) text.findall(y) in_file.close() out_file.close() thats it. it's the latest incantation of this program, ive been trying really hard to get this workin'. here's the error i get: Traceback (most recent call last): File "F:\Python21\reusage.py", line 10, in ? y = """%s""" (x) TypeError: object of type 'string' is not callable And for those of you just wondering what im trying to do, its supposed to search out for strings of text between to strings("url=" and "&"). and then output the list of strings to a file. Seems simple enough but I guess i really bit off more than i could chew for my first real program! :( will ------_=_NextPart_001_01C12E46.1084C690 Content-type: text/html; charset="ISO-8859-1" <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML><HEAD> <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=ISO-8859-1"> <META content="MSHTML 5.00.3013.2600" name=GENERATOR> <STYLE></STYLE> </HEAD> <BODY bgColor=#ffffff> <BLOCKQUOTE style="BORDER-LEFT: #0000ff 2px solid; MARGIN-LEFT: 5px; MARGIN-RIGHT: 0px; PADDING-LEFT: 5px"> <DIV><FONT face=Arial size=2>I'm new to programming, python, and even this list! <SPAN class=170524315-26082001><FONT color=#0000ff face="Courier New"> </FONT></SPAN></FONT></DIV></BLOCKQUOTE> <DIV><FONT color=#0000ff face="Courier New" size=2><SPAN class=170524315-26082001>Looks like your doing all the right things so far, welcome :-)</SPAN></FONT></DIV> <BLOCKQUOTE style="BORDER-LEFT: #0000ff 2px solid; MARGIN-LEFT: 5px; MARGIN-RIGHT: 0px; PADDING-LEFT: 5px"> <DIV><FONT face=Arial size=2>import re<BR></FONT></DIV> <DIV><FONT face=Arial size=2>file1 = raw_input("Name of file to convert: ")<BR>file2 = raw_input("Name of file to output to: ")<BR>in_file = open(file1, "r")<BR>out_file = open(file2, "w")<BR>x = in_file.read()<BR><SPAN class=170524315-26082001><FONT color=#0000ff face="Courier New"> </FONT></SPAN></FONT></DIV></BLOCKQUOTE> <DIV><FONT color=#0000ff face="Courier New" size=2><SPAN class=170524315-26082001>OK down to here, you now have the contents of file1 stored as </SPAN></FONT></DIV> <DIV><FONT color=#0000ff face="Courier New" size=2><SPAN class=170524315-26082001>a long string in x...</SPAN></FONT></DIV> <BLOCKQUOTE style="BORDER-LEFT: #0000ff 2px solid; MARGIN-LEFT: 5px; MARGIN-RIGHT: 0px; PADDING-LEFT: 5px"> <DIV><FONT face=Arial size=2><SPAN class=170524315-26082001></SPAN></FONT> </DIV> <DIV><FONT size=2><FONT face=Arial><SPAN class=170524315-26082001> </SPAN>y = """%s""" (x)<SPAN class=170524315-26082001><FONT color=#0000ff face="Courier New"> </FONT></SPAN></FONT></FONT></DIV> <DIV><FONT size=2><FONT face=Arial><SPAN class=170524315-26082001></SPAN></FONT></FONT> </DIV></BLOCKQUOTE> <DIV><FONT color=#0000ff face="Courier New" size=2><SPAN class=170524315-26082001>You meant to do:</SPAN></FONT></DIV> <DIV><FONT color=#0000ff face="Courier New" size=2><SPAN class=170524315-26082001></SPAN></FONT> </DIV> <DIV><FONT color=#0000ff face="Courier New" size=2><SPAN class=170524315-26082001></SPAN></FONT><FONT color=#0000ff face="Courier New" size=2><SPAN class=170524315-26082001>y="%s" % x</SPAN></FONT><FONT color=#0000ff face="Courier New" size=2><SPAN class=170524315-26082001></SPAN></FONT></DIV> <DIV><FONT color=#0000ff face="Courier New" size=2><SPAN class=170524315-26082001></SPAN></FONT> </DIV> <DIV><FONT color=#0000ff face="Courier New" size=2><SPAN class=170524315-26082001>The triple quotes aren't needed and the parens are only needed </SPAN></FONT></DIV> <DIV><FONT color=#0000ff face="Courier New" size=2><SPAN class=170524315-26082001></SPAN></FONT><FONT color=#0000ff face="Courier New" size=2><SPAN class=170524315-26082001>if theres several items to insert into the format string.</SPAN></FONT></DIV> <DIV><FONT color=#0000ff face="Courier New" size=2><SPAN class=170524315-26082001></SPAN></FONT> </DIV> <DIV><FONT color=#0000ff face="Courier New" size=2><SPAN class=170524315-26082001>The reason you got the callable error was you had parens after the string so</SPAN></FONT></DIV> <DIV><FONT color=#0000ff face="Courier New" size=2><SPAN class=170524315-26082001></SPAN></FONT> </DIV> <DIV><FONT color=#0000ff face="Courier New" size=2><SPAN class=170524315-26082001>But why are you copying the string in x into y? I can't see the </SPAN></FONT></DIV> <DIV><FONT color=#0000ff face="Courier New" size=2><SPAN class=170524315-26082001>reason for doing it.</SPAN></FONT></DIV> <BLOCKQUOTE style="BORDER-LEFT: #0000ff 2px solid; MARGIN-LEFT: 5px; MARGIN-RIGHT: 0px; PADDING-LEFT: 5px"> <DIV><FONT color=#0000ff face="Courier New" size=2><SPAN class=170524315-26082001></SPAN></FONT> </DIV> <DIV><FONT size=2><FONT face=Arial><SPAN class=170524315-26082001> </SPAN><BR>text = re.compile('url=(\w*)&', re.IGNORECASE)<BR>text.findall(y)<BR>in_file.close()<BR>out_file.close()</FONT></FONT></DIV> <DIV> </DIV> <DIV><FONT face=Arial size=2>thats it. it's the latest incantation of this program, ive been trying really hard to get this workin'.</FONT></DIV> <DIV><FONT face=Arial size=2>here's the error i get: </FONT></DIV> <DIV> </DIV> <DIV><FONT face=Arial size=2>Traceback (most recent call last):<BR>  File "F:\Python21\reusage.py", line 10, in ?<BR>    y = """%s""" (x)<BR>TypeError: object of type 'string' is not callable</FONT></DIV> <DIV> </DIV> <DIV><FONT face=Arial size=2>And for those of you just wondering what im trying to do, its supposed to search out for strings of text</FONT></DIV> <DIV><FONT face=Arial size=2>between to strings("url=" and "&").  and then output the list of strings to a file.</FONT></DIV> <DIV> </DIV> <DIV><FONT face=Arial size=2>Seems simple enough but I guess i really bit off more than i could chew for my first real program! :(</FONT></DIV> <DIV> </DIV> <DIV><FONT face=Arial size=2>will</FONT></DIV></BLOCKQUOTE></BODY></HTML> ------_=_NextPart_001_01C12E46.1084C690-- From alan.gauld@bt.com Sun Aug 26 16:47:04 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun, 26 Aug 2001 16:47:04 +0100 Subject: [Tutor] Callable? Whats callable? Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BEE5@mbtlipnt02.btlabs.bt.co.uk> ------_=_NextPart_001_01C12E46.5A93D230 Content-type: text/plain; charset="ISO-8859-1" Aplogies all, I hit CTRL ENTER which send the message in Lookout... Most of it was already written so I'm not going to redo it all, just say sorry... Alan G I'm new to programming, python, and even this list! So hopefullt someone could give me a hand with my first program. x = in_file.read() y = """%s""" (x) text = re.compile('url=(\w*)&', re.IGNORECASE) Traceback (most recent call last): File "F:\Python21\reusage.py", line 10, in ? y = """%s""" (x) TypeError: object of type 'string' is not callable ------_=_NextPart_001_01C12E46.5A93D230 Content-type: text/html; charset="ISO-8859-1" <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML><HEAD> <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=ISO-8859-1"> <META content="MSHTML 5.00.3013.2600" name=GENERATOR> <STYLE></STYLE> </HEAD> <BODY bgColor=#ffffff> <DIV><FONT color=#0000ff face="Courier New" size=2><SPAN class=280234815-26082001>Aplogies all, I hit CTRL ENTER which send the message in Lookout...</SPAN></FONT></DIV> <DIV><FONT color=#0000ff face="Courier New" size=2><SPAN class=280234815-26082001></SPAN></FONT> </DIV> <DIV><FONT color=#0000ff face="Courier New" size=2><SPAN class=280234815-26082001>Most of it was already written so I'm not going to redo it all,</SPAN></FONT></DIV> <DIV><FONT color=#0000ff face="Courier New" size=2><SPAN class=280234815-26082001>just say sorry...</SPAN></FONT></DIV> <DIV><FONT color=#0000ff face="Courier New" size=2><SPAN class=280234815-26082001></SPAN></FONT> </DIV> <DIV><FONT color=#0000ff face="Courier New" size=2><SPAN class=280234815-26082001>Alan G</SPAN></FONT></DIV> <BLOCKQUOTE style="BORDER-LEFT: #0000ff 2px solid; MARGIN-LEFT: 5px; MARGIN-RIGHT: 0px; PADDING-LEFT: 5px"> <DIV><FONT face=Arial size=2>I'm new to programming, python, and even this list! So hopefullt someone could give me a hand with my first program.</FONT></DIV> <DIV> </DIV> <DIV><FONT face=Arial><FONT size=2>x = in_file.read()<BR>y = """%s""" (x)<BR>text = re.compile('url=(\w*)&', re.IGNORECASE)<FONT color=#0000ff></FONT><FONT size=2><FONT face="Courier New"><SPAN class=280234815-26082001> </SPAN></FONT></FONT></FONT></FONT></DIV> <DIV><FONT face=Arial><FONT color=#0000ff><FONT size=2><FONT face="Courier New"><SPAN class=280234815-26082001> </SPAN><BR></FONT></FONT></FONT></FONT><FONT face=Arial size=2>Traceback (most recent call last):<BR>  File "F:\Python21\reusage.py", line 10, in ?<BR>    y = """%s""" (x)<BR>TypeError: object of type 'string' is not callable</FONT></DIV> <DIV> </DIV> <DIV> </DIV></BLOCKQUOTE></BODY></HTML> ------_=_NextPart_001_01C12E46.5A93D230-- From epoch7@charter.net Sun Aug 26 17:13:16 2001 From: epoch7@charter.net (epoch7) Date: Sun, 26 Aug 2001 12:13:16 -0400 Subject: [Tutor] Callable? Whats callable? References: <5104D4DBC598D211B5FE0000F8FE7EB20E66BEE4@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <004f01c12e4a$0464d860$92b1f018@p3550> alright. so i fixed the error in y. originally i started putting in the read()s and stuff to be able to fix an error/find a workaround. i was getting, here's how i got that error: import re file1 = raw_input("Name of file to convert: ") file2 = raw_input("Name of file to output to: ") in_file = open(file1, "r") out_file = open(file2, "w") x = in_file.read() text = re.compile('url=(\w*)&', re.IGNORECASE) y = text.findall(x) y.write(text) in_file.close() out_file.close() and here's the error Traceback (most recent call last): File "F:\Python21\reusage.py", line 11, in ? y.write(text) AttributeError: write im sure you all know what im doing wrong... will. p.s. i threw print x in there after x = in_file.read() and yes its working ok up to that point. that was a good idea, i wish i thought of it earlier. From sheila@thinkspot.net Sun Aug 26 17:54:07 2001 From: sheila@thinkspot.net (Sheila King) Date: Sun, 26 Aug 2001 09:54:07 -0700 Subject: [Tutor] Callable? Whats callable? In-Reply-To: <004f01c12e4a$0464d860$92b1f018@p3550> References: <5104D4DBC598D211B5FE0000F8FE7EB20E66BEE4@mbtlipnt02.btlabs.bt.co.uk> <004f01c12e4a$0464d860$92b1f018@p3550> Message-ID: <7002AA0F8C@kserver.org> On Sun, 26 Aug 2001 12:13:16 -0400, "epoch7" <epoch7@charter.net> wrote about Re: [Tutor] Callable? Whats callable?: OK, you have a few problems here, which mostly have to do with mixing together "types" that don't go together. For example, if you have an open file, then you can do: file1.read() ... if you opened it for reading or file2.write() ... if you opened it for writing. But, if x is a string, then you can't do x.write() or x.read() Because .read() and .write() are file methods. They don't work on strings, or on regular expression patterns and such. (Well, when you get a bit more advanced, there are things that aren't *strictly* files, that have file-like methods, but let's not get into that today.) :alright. so i fixed the error in y. originally i started putting in the :read()s and stuff to be able to fix an error/find a workaround. :i was getting, here's how i got that error: : :import re : :file1 = raw_input("Name of file to convert: ") :file2 = raw_input("Name of file to output to: ") :in_file = open(file1, "r") :out_file = open(file2, "w") :x = in_file.read() :text = re.compile('url=(\w*)&', re.IGNORECASE) :y = text.findall(x) :y.write(text) :in_file.close() :out_file.close() : :and here's the error : :Traceback (most recent call last): : File "F:\Python21\reusage.py", line 11, in ? : y.write(text) :AttributeError: write At first I was going to suggest that you change the line y.write(text) to out_file.write(text) But, if you do, you will get this error: Traceback (most recent call last): File "C:\My Documents\temp.py", line 12, in ? out_file.write(text) TypeError: argument must be string or read-only character buffer, not SRE_Pattern The point is, y.write(text) isn't going to work, because y isn't a file, and .write() is a file method. Now, if you try out_file.write(text) at least out_file is a file. So this is a bit better. HOWEVER, text isn't a string. And when you try to write stuff to a file, it has to be a string. I looked up the findall() command (since I'm not familiar with it) and it says that findall() returns a list of all non-overlapping matches of pattern in string. Well, there's a problem. text is a list, not a string. I'm not sure how to advise you on this, exactly, since I don't know the regular expression stuff. You write that you are trying to do this: :And for those of you just wondering what im trying to do, its supposed to search out for strings of text :between to strings("url=" and "&"). and then output the list of strings to a file. It is possible to do this with just string operations. If you'd like to try that, see: http://www.python.org/doc/current/lib/string-methods.html I hope some of this explanation helped. -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From sheila@thinkspot.net Sun Aug 26 18:03:56 2001 From: sheila@thinkspot.net (Sheila King) Date: Sun, 26 Aug 2001 10:03:56 -0700 Subject: [Tutor] Callable? Whats callable? In-Reply-To: <7002AA0F8C@kserver.org> References: <5104D4DBC598D211B5FE0000F8FE7EB20E66BEE4@mbtlipnt02.btlabs.bt.co.uk> <004f01c12e4a$0464d860$92b1f018@p3550> <7002AA0F8C@kserver.org> Message-ID: <78ECE55A03@kserver.org> On Sun, 26 Aug 2001 09:54:07 -0700, Sheila King <sheila@thinkspot.net> wrote about Re: [Tutor] Callable? Whats callable?: :Traceback (most recent call last): : File "C:\My Documents\temp.py", line 12, in ? : out_file.write(text) :TypeError: argument must be string or read-only character buffer, not :SRE_Pattern : :The point is, y.write(text) isn't going to work, because y isn't a file, :and .write() is a file method. : :Now, if you try : :out_file.write(text) :at least out_file is a file. So this is a bit better. HOWEVER, text :isn't a string. And when you try to write stuff to a file, it has to be :a string. : :I looked up the findall() command (since I'm not familiar with it) and :it says that findall() returns a list of all non-overlapping matches of :pattern in string. Well, there's a problem. text is a list, not a :string. Oops. I should have checked the compile() function from the re module. In any case, text is an SRE object resulting from using compile(). -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From dyoo@hkn.eecs.berkeley.edu Sun Aug 26 21:05:24 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 26 Aug 2001 13:05:24 -0700 (PDT) Subject: [Tutor] map, filter and lambda functions [filter can take None] In-Reply-To: <3B889996.11296.A239BB@localhost> Message-ID: <Pine.LNX.4.21.0108261251240.15545-100000@hkn.eecs.berkeley.edu> On Sun, 26 Aug 2001, Allan Crooks wrote: > On 25 Aug 2001, at 23:31, Tim Peters wrote: > > > At some point after thanking him, you might try reading the docs too > > <wink>. > > In my defence, I'll say that Danny, instead of heading to the docs, > delved straight into the C code without a second thought. So I'm not > the only one to forget about the docs. :) My apologies! Sometimes, I think I get too caught up in the details. *grin* From bsass@freenet.edmonton.ab.ca Sun Aug 26 21:10:59 2001 From: bsass@freenet.edmonton.ab.ca (Bruce Sass) Date: Sun, 26 Aug 2001 14:10:59 -0600 (MDT) Subject: [Tutor] Callable? Whats callable? In-Reply-To: <004f01c12e4a$0464d860$92b1f018@p3550> Message-ID: <Pine.LNX.4.33.0108261336350.10756-100000@bms> On Sun, 26 Aug 2001, epoch7 wrote: > alright. so i fixed the error in y. originally i started putting in the > read()s and stuff to be able to fix an error/find a workaround. > i was getting, here's how i got that error: > > import re > > file1 = raw_input("Name of file to convert: ") > file2 = raw_input("Name of file to output to: ") > in_file = open(file1, "r") > out_file = open(file2, "w") > x = in_file.read() > text = re.compile('url=(\w*)&', re.IGNORECASE) ...ok... > y = text.findall(x) > y.write(text) ...but that bit ain't right. ----- re.findall() example ----- >>> import re >>> instring = """ ... Just some text, any text, ... the more text the better... ... It needn't be good text. ... """ >>> target = re.compile('text') >>> print re.findall(target,instring) ['text', 'text', 'text', 'text'] ----- end example ----- Maybe what you want is... import string out_file.write(string.join(re.findall(text,x),"\n")) ...or, if you prefer... y = re.findall(text,x) y = string.join(y,'\n') out_file.write(y) > in_file.close() > out_file.close() > > and here's the error > > Traceback (most recent call last): > File "F:\Python21\reusage.py", line 11, in ? > y.write(text) > AttributeError: write > > im sure you all know what im doing wrong... ...not playing with the interpreter enough. ;-) - Bruce From bill-bell@bill-bell.hamilton.on.ca Sun Aug 26 21:32:16 2001 From: bill-bell@bill-bell.hamilton.on.ca (Bill Bell) Date: Sun, 26 Aug 2001 16:32:16 -0400 Subject: [Tutor] Re: Callable? Whats callable? In-Reply-To: <E15b1gk-0004VU-00@mail.python.org> Message-ID: <3B892490.126.442E208@localhost> "epoch7" <epoch7@charter.net> wrote, in part: <snip> > y =3D """%s""" (x) A 'callable' thing is a section of program code that can be used (called) by another program to do some work for the callER. Let me first duplicate the message you saw. I can tell that your name 'x' points to a string that you read from a file. I'll just make 'x' point to an arbitrary string, to avoid the carry-on of reading from a file. >>> x = 'Fourty-two' >>> y = """%s""" (x) Traceback (most recent call last): File "<interactive input>", line 1, in ? TypeError: object is not callable: '%s' In this case, when Python sees '(x)' in your line of code it concludes that the object preceding it must be 'callable', ie, a function, say. It examines that object, which happens to be '%s', compares it with the kinds of objects that can be called (or used if you will) by other programs, finds that it's a string, however, and makes the rude complaint that you see. So, what to do, eh? My guess is that you want to convert the object to which 'x' points to a string and then make 'y' point to the converted object. If I have guessed correctly then you need to write, >>> y = "%s" % (x) rather than what you did. Or, IOW, just insert the '%' operator in your statement. Now when Python examines this statement it understands that you want to convert the content of 'x' using the specification '%s' and it complaineth no more. Incidentally I haven't examined any of the rest of your script. I assume that if you wanted us to comment about that you would have asked us. :o) Good luck! Bill Bill Bell, Software Developer From dyoo@hkn.eecs.berkeley.edu Sun Aug 26 21:40:30 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 26 Aug 2001 13:40:30 -0700 (PDT) Subject: [Tutor] Callable? Whats callable? In-Reply-To: <004f01c12e4a$0464d860$92b1f018@p3550> Message-ID: <Pine.LNX.4.21.0108261320200.15545-100000@hkn.eecs.berkeley.edu> On Sun, 26 Aug 2001, epoch7 wrote: > alright. so i fixed the error in y. originally i started putting in the > read()s and stuff to be able to fix an error/find a workaround. > i was getting, here's how i got that error: > > import re > > file1 = raw_input("Name of file to convert: ") > file2 = raw_input("Name of file to output to: ") > in_file = open(file1, "r") > out_file = open(file2, "w") > x = in_file.read() > text = re.compile('url=(\w*)&', re.IGNORECASE) > y = text.findall(x) > y.write(text) > in_file.close() > out_file.close() [Warning: Some subjective and preachy comments in this message.] It might be better to call 'x' your 'text' instead; I got confused for a moment by: > x = in_file.read() > text = re.compile('url=(\w*)&', re.IGNORECASE) > y = text.findall(x) Renaming the variable takes more typing, but it might help: ### file_text = in_file.read() regex = re.compile('url=(\w*)&', re.IGNORECASE) matches = regex.findall(file_text) ### When we use descriptive names, then sometimes it's easier to catch bugs later on in the code. For example, with the code: > y = text.findall(x) > y.write(text) if we substitute with slightly different variable names: ### matches = regex.findall(file_text) regex.write(matches) ### then it's a lot clearer that there's something wacky happening here: instead of writing our result into the file, we're telling writing it back into the regular expression. That's not "write": we want to write it into our out_file instead. Hope this helps! From epoch7@charter.net Sun Aug 26 23:35:29 2001 From: epoch7@charter.net (epoch7) Date: Sun, 26 Aug 2001 18:35:29 -0400 Subject: Epoch7: programmer newbie from hell.(formerly Re: [Tutor] Callable? What's Callable?) References: <Pine.LNX.4.21.0108261320200.15545-100000@hkn.eecs.berkeley.edu> Message-ID: <007201c12e7f$690bf480$92b1f018@p3550> i decided to chance the topic cause i got so many posts and cc's i could hardly keep track. i hope no one else posts as many questions as i do cause if they do my mailbox will always be full, but then again i might learn something. ive taken the suggestions of everyone here and redid alot of the code with varying levels of success, why not take a look: import re import string file1 = raw_input("Name of file to convert: ") file2 = raw_input("Name of file to output to: ") in_file = open(file1, "r") out_file = open(file2, "w") file_text = in_file.read() regex = re.compile('url=(\w*)&', re.IGNORECASE) matches = re.findall(regex,file_text) out_file.write(string.join(re.findall(regex,file_text),"\n")) in_file.close() out_file.close() alright this code is looking mighty hardcore for me at the moment. and i thank you for all your help, but now i have to ask one more question: why when i run the program do i get no output? i don't get any errors, but now i get a 0kb txt file when it finishes. is there something wrong in the compile function(it is a function right?)? From chikitychina@home.com Mon Aug 27 00:58:12 2001 From: chikitychina@home.com (Pablo Manzanera) Date: Sun, 26 Aug 2001 19:58:12 -0400 Subject: [Tutor] help References: <E15afrv-0000GQ-00@mail.python.org> Message-ID: <3B898D14.29287795@home.com> tutor-request@python.org wrote: > > Send Tutor mailing list submissions to > tutor@python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request@python.org > > You can reach the person managing the list at > tutor-admin@python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > Today's Topics: > > 1. Making my program an executable/distributable (paul) > 2. Re: map & lambda to create dictionary from lists? (Reisfeld, Brad CAR) > 3. Re: time question (Lloyd Hugh Allen) > > --__--__-- > > Message: 1 > From: "paul" <clanoftheinsane@hotmail.com> > To: <tutor@python.org> > Date: Fri, 24 Aug 2001 18:12:26 -0400 > Subject: [Tutor] Making my program an executable/distributable > > This is a multi-part message in MIME format. > > ------=_NextPart_000_0009_01C12CC8.548A0FA0 > Content-Type: text/plain; > charset="iso-8859-1" > Content-Transfer-Encoding: quoted-printable > > Hello all, > i have asked this question before, about a week or so ago, but i just = > want to re-ask it in case anyone missed it. i have written a python = > program including Tkinter, and when i used py2exe to convert it to an = > executable, it called for the riscosenviron, riscos, riscospath, and ce = > modules. is this because of my using Tkinter in my script? does py2exe = > not support Tkinter? i'm just curious. i finally finished my program, = > and i just want to be able to distribute it. please help?!?! > > thanks a lot, > paul brown > > ------=_NextPart_000_0009_01C12CC8.548A0FA0 > Content-Type: text/html; > charset="iso-8859-1" > Content-Transfer-Encoding: quoted-printable > > <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> > <HTML><HEAD> > <META content=3D"text/html; charset=3Diso-8859-1" = > http-equiv=3DContent-Type> > <META content=3D"MSHTML 5.00.2314.1000" name=3DGENERATOR> > <STYLE></STYLE> > </HEAD> > <BODY bgColor=3D#ffffff> > <DIV><FONT face=3DArial size=3D2>Hello all,</FONT></DIV> > <DIV><FONT face=3DArial size=3D2>i have asked this question before, = > about a week or=20 > so ago, but i just want to re-ask it in case anyone missed it.  i = > have=20 > written a python program including Tkinter, and when i used py2exe to = > convert it=20 > to an executable, it called for the riscosenviron, riscos, riscospath, = > and ce=20 > modules.  is this because of my using Tkinter in my script?  = > does=20 > py2exe not support Tkinter?  i'm just curious.  i finally = > finished my=20 > program, and i just want to be able to distribute it.  please=20 > help?!?!</FONT></DIV> > <DIV> </DIV> > <DIV><FONT face=3DArial size=3D2>thanks a lot,</FONT></DIV> > <DIV><FONT face=3DArial size=3D2>paul brown</FONT></DIV></BODY></HTML> > > ------=_NextPart_000_0009_01C12CC8.548A0FA0-- > > --__--__-- > > Message: 2 > From: "Reisfeld, Brad CAR" <Brad.Reisfeld@carrier.utc.com> > To: "'tutor@python.org'" <tutor@python.org> > Subject: Re: [Tutor] map & lambda to create dictionary from lists? > Date: Sat, 25 Aug 2001 07:30:01 -0400 > > Hi, > My preferred method for accomplishing this is quite simple: > > >>> d={} > >>> keys = ('name', 'age', 'food') > >>> values = ('Monty', 42, 'spam') > >>> map(d.setdefault, keys, values) > ['Monty', 42, 'spam'] > >>> d > {'name': 'Monty', 'age': 42, 'food': 'spam'} > > -Brad > > ================================= > > What I've got are two sequences. The first is a sequence of strings > that I want to use as the keys of a dictionary. The second is a > sequence of objects (strings, numbers, whatever) that I want to use as > the values in the dictionary. Of course, the two sequences have a > one-to-one correspondence. > > Here's what I've come up with using map and lambda so far and I want to > know if it's Good: > > Python 2.0 (#1, Jan 8 2001, 10:18:58) > [GCC egcs-2.91.66 19990314 (egcs-1.1.2 release)] on sunos5 > Type "copyright", "credits" or "license" for more information. > >>> d = {} > >>> keys = ('name', 'age', 'food') > >>> values = ('Monty', 42, 'spam') > >>> junk = map(lambda k, v: d.update({k: v}), keys, values) > >>> junk > [None, None, None] > >>> d > {'name': 'Monty', 'age': 42, 'food': 'spam'} > > --__--__-- > > Message: 3 > Date: Sat, 25 Aug 2001 10:40:05 -0400 > From: Lloyd Hugh Allen <vze2f978@verizon.net> > Reply-To: lha2@columbia.edu > To: tutor@python.org > Subject: Re: [Tutor] time question > > Here's something strange: > > ----code follows---- > >>> quitTime = (2001, 8, 22, 9, 45, -1, -1, -1, -1) > >>> import time > >>> nowTime = time.localtime(time.time()) > >>> nowTime > (2001, 8, 25, 10, 0, 54, 5, 237, 1) > >>> theDiff = [] > >>> for foo in range(len(nowTime)): > theDiff.append(nowTime[foo]-quitTime[foo]) > > > >>> theDiff > [0, 0, 3, 1, -45, 55, 6, 238, 2] > >>> theDiff = tuple(theDiff) > >>> theDiff > (0, 0, 3, 1, -45, 55, 6, 238, 2) > >>> time.localtime(time.mktime(theDiff)) > (1999, 12, 2, 23, 15, 55, 3, 336, 0) > ----end code------- > > I had been hoping that time.mktime and time.localtime would > intelligently handle the -45 minutes. Seems not to be the case. I trust > that with well-formed times they are in fact inverse functions? > > Here's my go at a real solution: > -----code starts---- > >>> def convertTime(theDiff): > """Returns a time tuple with strictly positive elements. > > Note that this function does not intelligently handle months, > but assumes that all months are 28 days long.""" > offSet = [0, 12, 28, 24, 60] > theDiff = list(theDiff) > for foo in range(len(theDiff)-1, 0, -1): > if theDiff[foo]<0: > theDiff[foo] = theDiff[foo] + offSet[foo] > theDiff[foo-1] = theDiff[foo-1] - 1 > theDiff = tuple(theDiff) > return theDiff > ----end code-------- > > -LHA > > --__--__-- > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > End of Tutor Digest From clanoftheinsane@hotmail.com Mon Aug 27 01:44:50 2001 From: clanoftheinsane@hotmail.com (paul) Date: Sun, 26 Aug 2001 20:44:50 -0400 Subject: [Tutor] sorry about the HTML Message-ID: <OE20SkpBxo7VOutadvU000008f4@hotmail.com> hello all you pythonians, i just want to say that i'm sorry for all those miserably hard to understand HTML email messages that i've been sending out. i'm using Outlook Express, and i dont always remember to change the format, and i just noticed this when reading my messages in other people's messages. so, whenever anyone responds to my emails again, and my message is in HTML, just give a quick reminder to me to change that. i'll finally catch on after a while. sorry, paul brown From rob@jam.rr.com Mon Aug 27 01:55:14 2001 From: rob@jam.rr.com (Rob Andrews) Date: Sun, 26 Aug 2001 19:55:14 -0500 Subject: [Tutor] sorry about the HTML References: <OE20SkpBxo7VOutadvU000008f4@hotmail.com> Message-ID: <3B899A72.45AC7C8@jam.rr.com> paul wrote: > > hello all you pythonians, > i just want to say that i'm sorry for all those miserably hard to > understand HTML email messages that i've been sending out. i'm using > Outlook Express, and i dont always remember to change the format, and i just > noticed this when reading my messages in other people's messages. so, > whenever anyone responds to my emails again, and my message is in HTML, just > give a quick reminder to me to change that. i'll finally catch on after a > while. sorry, > > paul brown > Dah, must be careful. I made the same mistake and was sentenced to maintaining Useless Python without hope of parole! 3;-> Rob -- A {} is a terrible thing to waste. Useless Python! http://www.lowerstandard.com/python From ignacio@openservices.net Mon Aug 27 05:58:33 2001 From: ignacio@openservices.net (Ignacio Vazquez-Abrams) Date: Mon, 27 Aug 2001 00:58:33 -0400 (EDT) Subject: [Tutor] What is Ellipsis for? Message-ID: <Pine.LNX.4.33.0108270054520.28253-100000@terbidium.openservices.net> I came across Ellipsis a while ago, and when I did, I just ignored it. However, now I just finally have to know: What the hell is it for? I've tried reading the last paragraph of section 5.3.3 over and over again and it just doesn't make sense now matter how I push it around in the interpreter. Can anyone explain its purpose to me please? -- Ignacio Vazquez-Abrams <ignacio@openservices.net> From dyoo@hkn.eecs.berkeley.edu Mon Aug 27 07:12:47 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 26 Aug 2001 23:12:47 -0700 (PDT) Subject: [Tutor] Re: Epoch7: programmer newbie from hell.(formerly Re: [Tutor] Callable? What's Callable?) In-Reply-To: <007201c12e7f$690bf480$92b1f018@p3550> Message-ID: <Pine.LNX.4.21.0108262237180.22025-100000@hkn.eecs.berkeley.edu> On Sun, 26 Aug 2001, epoch7 wrote: > import re > import string > > file1 = raw_input("Name of file to convert: ") > file2 = raw_input("Name of file to output to: ") > in_file = open(file1, "r") > out_file = open(file2, "w") > file_text = in_file.read() > regex = re.compile('url=(\w*)&', re.IGNORECASE) > matches = re.findall(regex,file_text) > out_file.write(string.join(re.findall(regex,file_text),"\n")) It'll simplify things a little if you write the last line as: ### out_file.write(string.join(matches, '\n')) ### instead; otherwise, the computer isn't taking advantage of the 'matches' variable that we made in the previous line. > in_file.close() > out_file.close() Otherwise, the code looks good. Here is an example run through your program with the following file1.txt test file: ### this is a small file with an url=python& notice, though, that it the url=doesn't allow& punctuation. whurl=pool& ### ### dyoo@coffeetable:~$ python test.py Name of file to convert: file1.txt Name of file to output to: file1.output dyoo@coffeetable:~$ cat file1.output python pool ### So it does appear to be working. > alright this code is looking mighty hardcore for me at the moment. and > i thank you for all your help, but now i have to ask one more > question: why when i run the program do i get no output? i don't get > any errors, but now i get a 0kb txt file when it finishes. is there > something wrong in the compile function(it is a function right?)? If you could show us what kind of test file you're using, that might help pinpoint the bug; perhaps the pattern used is too strict. '\w*' will only match up "word" characters, and that doesn't include any sort of punctuation or spacing. What kind of file are you planning to run your program over? I'm just trying to think of all the situations that might cause us to get no result. Hmmmm.... also, be careful that in_file isn't the same as out_file. Otherwise, you'll get something very unexpected: ### pooldyoo@coffeetable:~$ python test.py Name of file to convert: file1.txt Name of file to output to: file1.txt dyoo@coffeetable:~$ ls -l file1.txt -rw-r--r-- 1 dyoo dyoo 0 Aug 26 23:05 file1.txt ### The reason it doesn't find anything in this case is because of the ordering of the program lines here: > in_file = open(file1, "r") > out_file = open(file2, "w") > file_text = in_file.read() which tells Python "Ok, let's open up the file1 as in_file. Let's open up file2 to write into it... and if there's stuff in file2 already, let's clear it out. Ok, now let's look at in_file's contents." Imagine what happens when file1 is file2, and you might see a small problem here. If you have more questions, feel free to ask. Good luck! From dyoo@hkn.eecs.berkeley.edu Mon Aug 27 08:56:59 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 27 Aug 2001 00:56:59 -0700 (PDT) Subject: [Tutor] Making my program an executable/distributable In-Reply-To: <OE63ZTHfyQgeDKvPEkG000002a4@hotmail.com> Message-ID: <Pine.LNX.4.21.0108270042380.23441-100000@hkn.eecs.berkeley.edu> On Sat, 25 Aug 2001, paul wrote: > > > i have asked this question before, about a week or so ago, but i just > > > want to re-ask it in case anyone missed it. i have written a python > > > program including Tkinter, and when i used py2exe to convert it to an > > > executable, it called for the riscosenviron, riscos, riscospath, and > > > ce modules. is this because of my using Tkinter in my script? does > > > py2exe not support Tkinter? i'm just curious. i finally finished my > > > program, and i just want to be able to distribute it. please help?!?! Ok, I finally got off my lazy butt and rebooted. *grin* I believe you can ignore the warnings. You'll still see an executable get created, so I wouldn't worry about it too much. Take a look: ### E:\tmp4>python setup.py py2exe [lots of output flies by the screen] warning: py2exe: * The following modules were not found: warning: py2exe: * win32api warning: py2exe: * riscosenviron warning: py2exe: * ce warning: py2exe: * riscos warning: py2exe: * riscospath warning: py2exe: *************************************************************** ********** removing 'build\bdist.win32\winexe\collect\guifun' (and everything under it) removing 'build\bdist.win32\winexe' (and everything under it) E:\tmp4>dir Volume in drive E is DISK 2 Volume Serial Number is 2854-B3CA Directory of E:\tmp4 08/26/2001 11:17p <DIR> . 08/26/2001 11:17p <DIR> .. 08/26/2001 11:17p 8,850 guifun.py 08/26/2001 11:17p 96 setup.py 08/26/2001 11:17p 99 #setup.py# 08/27/2001 12:25a <DIR> build 08/27/2001 12:25a <DIR> dist 08/27/2001 12:28a 18,876 results.log 4 File(s) 27,921 bytes 4 Dir(s) 209,354,752 bytes free E:\tmp4>cd dist\guifun E:\tmp4\dist\guifun>dir Volume in drive E is DISK 2 Volume Serial Number is 2854-B3CA Directory of E:\tmp4\dist\guifun 08/27/2001 12:25a <DIR> . 08/27/2001 12:25a <DIR> .. 08/27/2001 12:25a <DIR> tcl 08/27/2001 12:44a 191,941 guifun.exe 07/20/2001 01:19a 708,668 python21.dll 07/20/2001 01:20a 49,208 _sre.pyd 07/20/2001 01:20a 28,732 _tkinter.pyd 08/08/2000 01:54p 928,768 tk83.dll 08/08/2000 01:48p 619,520 tcl83.dll 6 File(s) 2,526,837 bytes 3 Dir(s) 209,354,752 bytes free ### Can you check to see if the guifun.exe file is there for you too? If you're going to send this to your friends, make sure to send the whole guifun directory over. However, when I run your program, nothing appears on my screen. Don't forget to do a 'mainloop()' at the very end of your program: otherwise, the program will exit even before it waits for your user to use your GUI. Also, since your program appears to depends on "C:/python20/forlist.py", you might want to include that file along with your program somehow. Good luck! From dyoo@hkn.eecs.berkeley.edu Mon Aug 27 09:20:26 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 27 Aug 2001 01:20:26 -0700 (PDT) Subject: [Tutor] Re: Epoch7: programmer newbie from hell.(formerly Re: [Tutor] Callable? What's Callable?) In-Reply-To: <007201c12e7f$690bf480$92b1f018@p3550> Message-ID: <Pine.LNX.4.21.0108270115070.23750-100000@hkn.eecs.berkeley.edu> On Sun, 26 Aug 2001, epoch7 wrote: > i decided to chance the topic cause i got so many posts and cc's i > could hardly keep track. i hope no one else posts as many questions as > i do cause if they do my mailbox will always be full, but then again i Ha! By the way, if you do feel overwhelmed, there's a "digest" option that you can select in the mailing list settings. Digest mode will bundle several messages at a time from tutor to make it less stressful on your mailbox. You can visit: http://mail.python.org/mailman/listinfo/tutor and go down a bit to the "Edit Options" form to make that change. Anyway, keep us posted on your progress, and don't worry about sending too many questions. Best of wishes! From ak@silmarill.org Mon Aug 27 10:28:58 2001 From: ak@silmarill.org (Andrei Kulakov) Date: Mon, 27 Aug 2001 05:28:58 -0400 Subject: [Tutor] What is Ellipsis for? In-Reply-To: <Pine.LNX.4.33.0108270054520.28253-100000@terbidium.openservices.net> References: <Pine.LNX.4.33.0108270054520.28253-100000@terbidium.openservices.net> Message-ID: <20010827052857.A2400@sill.silmarill.org> On Mon, Aug 27, 2001 at 12:58:33AM -0400, Ignacio Vazquez-Abrams wrote: > I came across Ellipsis a while ago, and when I did, I just ignored it. > However, now I just finally have to know: What the hell is it for? I've tried > reading the last paragraph of section 5.3.3 over and over again and it just section 5.3.3 of what? > doesn't make sense now matter how I push it around in the interpreter. Can > anyone explain its purpose to me please? > > -- > Ignacio Vazquez-Abrams <ignacio@openservices.net> > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From rnd@onego.ru Mon Aug 27 10:48:10 2001 From: rnd@onego.ru (Roman Suzi) Date: Mon, 27 Aug 2001 13:48:10 +0400 (MSD) Subject: [Tutor] What is Ellipsis for? In-Reply-To: <Pine.LNX.4.33.0108270054520.28253-100000@terbidium.openservices.net> Message-ID: <Pine.LNX.4.21.BCL.0108271343080.869-100000@suzi.com.onego.ru> On Mon, 27 Aug 2001, Ignacio Vazquez-Abrams wrote: > I came across Ellipsis a while ago, and when I did, I just ignored it. > However, now I just finally have to know: What the hell is it for? I've tried > reading the last paragraph of section 5.3.3 over and over again and it just > doesn't make sense now matter how I push it around in the interpreter. Can > anyone explain its purpose to me please? Ellipsis is a special object to specify "..." in slices. It is not used in Python itself but by some extensions, like Numeric, to specify arbitrary number of dimension indices. For example: >>> import Numeric >>> a = Numeric.array([[1,2],[3,4]]) >>> a[...] array([[1, 2], [3, 4]]) >>> a[...,1] array([2, 4]) >>> The object itself could be seen if we create object handling getslice: >>> class A: ... def __getitem__(self, slice): print slice ... >>> a=A() >>> a[...] Ellipsis Or in newer Python: Python 2.0 (#1, Oct 16 2000, 18:10:03) [GCC 2.95.2 19991024 (release)] on linux2 Type "copyright", "credits" or "license" for more information. >>> class A: ... def __getitem__(self, x): print x ... >>> a=A() >>> a[...] Ellipsis Sincerely yours, Roman A.Suzi -- - Petrozavodsk - Karelia - Russia - mailto:rnd@onego.ru - From tzuming@sanbi.ac.za Mon Aug 27 11:19:26 2001 From: tzuming@sanbi.ac.za (Tzu-Ming Chern) Date: Mon, 27 Aug 2001 12:19:26 +0200 (SAST) Subject: [Tutor] Sim4 output parser Message-ID: <Pine.BSF.4.21.0108271218090.25372-100000@fling.sanbi.ac.za> Hi, Do you have any advice on how to start parsing sim4 output files? Specifically, I'd like to extract the start and end points of one of the matching pairs. thank you, tzuming ****************************************************************************** Tzu-Ming Chern South African National Bioinformatics Institute University of Western Cape PO box X17 Bellville Cape Town South Africa Tel#:27-21-959-3908/3645 Fax:27-21-959-2512 Email:tzuming@fling.sanbi.ac.za ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ From ignacio@openservices.net Mon Aug 27 11:30:40 2001 From: ignacio@openservices.net (Ignacio Vazquez-Abrams) Date: Mon, 27 Aug 2001 06:30:40 -0400 (EDT) Subject: [Tutor] Sim4 output parser In-Reply-To: <Pine.BSF.4.21.0108271218090.25372-100000@fling.sanbi.ac.za> Message-ID: <Pine.LNX.4.33.0108270623440.28253-100000@terbidium.openservices.net> On Mon, 27 Aug 2001, Tzu-Ming Chern wrote: > Hi, > > Do you have any advice on how to start parsing sim4 output > files? Specifically, I'd like to extract the start and end points of one > of the matching pairs. > > thank you, > > tzuming Heh. Um, what is the sim4 file format? Where can we find a description? How are matching pairs identified? I'm certain that most people here don't have any experience with that genetics software, and Google seems to not be finding much, so please provide more information. -- Ignacio Vazquez-Abrams <ignacio@openservices.net> From alan.gauld@bt.com Mon Aug 27 12:48:05 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon, 27 Aug 2001 12:48:05 +0100 Subject: Epoch7: programmer newbie from hell. (formerly Re: [Tutor] Ca llable? What's Callable?) Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BEE7@mbtlipnt02.btlabs.bt.co.uk> > alright this code is looking mighty hardcore for me at the > moment. Its not bad for a first program :-) > one more question: why when i run the program do i get no > output? i don't get any errors, but now i get a 0kb txt file Probably something wrong with the regex. Try substituting the regex for a simple string and check that it works. If so then crank up the interpreter and experiment with the regex until it does what you want. As someone already suggested, the interpreter is your friend, experiment there till you know how all the parts wull work then start gluing them together. This kind of hands-on interactive programming is one of Pythons most powerful features, use it to the full. Alan G. From alan.gauld@bt.com Mon Aug 27 13:10:06 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon, 27 Aug 2001 13:10:06 +0100 Subject: [Tutor] What is Ellipsis for? Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BEE8@mbtlipnt02.btlabs.bt.co.uk> > I came across Ellipsis a while ago, and when I did, I just ignored it. > However, now I just finally have to know: What the hell is it > for? I've tried reading the last paragraph of section 5.3.3 over and over > again and it just doesn't make sense now matter how I push it around Me too. I've hunted for examples of "extended slicing" in the tutor and in the other docs but other than the language lawyer stuff its a black hole. Now I'm curious, what is extended slicing? And where do ellipses come into it? Alan g From theresident@rocketmail.com Mon Aug 27 19:03:29 2001 From: theresident@rocketmail.com (Justin Ko) Date: Tue, 28 Aug 2001 02:03:29 +0800 Subject: [Tutor] The __setattr__ method Message-ID: <5.1.0.14.2.20010828015118.00b2f888@mail.andover.edu> Hey everyone. I am working on a module to provide access to an mp3 file's ID3 tags. A class seemed to be the best way to represent the information represented in an ID3 tag's fields. However, i would like to be able to tell when the information in the tag is changed so that the information can be written back into the ID3 tag. This is my dilemma. The __init__ method reads the information from the file. def __init__(self, filename = ""): "Initialize things to default values or read them from a file" if filename != "": try: file = open(filename, "r") file.seek(-128, 2) if file.read(3) == "TAG": self.filename = filename self.title = file.read(30) self.artist = file.read(30) self.album = file.read(30) self.year = file.read(4) self.comment = file.read(30) self.genre = self.genres[ord(file.read(1))] self.modified = 0 The __setattr__ method tells me when something is changed def __setattr__(self, name, value): "Set class attributes" self.__dict__[name] = value self.__dict__['modified'] = 1 However, the statements in the __init__ method cause __setattr__ to be called. So this is my question. How do I set a classes attributes without calling __setattr__ ? I guess it would be possible to replace all the self.variable = file.read( ) statements with something like self.__dict__[variable] = file.read( ), but that seems rather inelegant and ugly. I hope there is a better solution to this problem. - Justin Ko _________________________________________________________ Do You Yahoo!? Get your free @yahoo.com address at http://mail.yahoo.com From ak@silmarill.org Mon Aug 27 19:10:19 2001 From: ak@silmarill.org (Andrei Kulakov) Date: Mon, 27 Aug 2001 14:10:19 -0400 Subject: [Tutor] The __setattr__ method In-Reply-To: <5.1.0.14.2.20010828015118.00b2f888@mail.andover.edu> References: <5.1.0.14.2.20010828015118.00b2f888@mail.andover.edu> Message-ID: <20010827141019.A6637@sill.silmarill.org> On Tue, Aug 28, 2001 at 02:03:29AM +0800, Justin Ko wrote: > > Hey everyone. I am working on a module to provide access to an mp3 file's > ID3 tags. A class seemed to be the best way to represent the information > represented in an ID3 tag's fields. However, i would like to be able to > tell when the information in the tag is changed so that the information can > be written back into the ID3 tag. This is my dilemma. > > The __init__ method reads the information from the file. > > def __init__(self, filename = ""): > "Initialize things to default values or read them from a file" > if filename != "": > try: > file = open(filename, "r") > file.seek(-128, 2) > if file.read(3) == "TAG": > self.filename = filename > self.title = file.read(30) > self.artist = file.read(30) > self.album = file.read(30) > self.year = file.read(4) > self.comment = file.read(30) > self.genre = self.genres[ord(file.read(1))] > self.modified = 0 > > The __setattr__ method tells me when something is changed > > def __setattr__(self, name, value): > "Set class attributes" > self.__dict__[name] = value > self.__dict__['modified'] = 1 > > However, the statements in the __init__ method cause __setattr__ to be > called. > So this is my question. How do I set a classes attributes without calling > __setattr__ ? I guess it would be possible to replace all the self.variable > = file.read( ) statements with something like self.__dict__[variable] = > file.read( ), but that seems rather inelegant and ugly. I hope there is a > better solution to this problem. > > - Justin Ko > > > _________________________________________________________ > Do You Yahoo!? > Get your free @yahoo.com address at http://mail.yahoo.com > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor There are two modules that do that, already - ID3.py and mp3.py. The latter one is the most complete, and I fixed a serious bug in it and packaged it with cymbaline (in sig). The version on vaults still has this bug, afaik. -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From dell2100@prodigy.net Mon Aug 27 19:20:57 2001 From: dell2100@prodigy.net (David L. Lerner) Date: Mon, 27 Aug 2001 14:20:57 -0400 Subject: [Tutor] Getting the highest numbers from a list Message-ID: <008001c12f25$0651bcc0$508dc540@prodigy.net> Is there a simple way to get the _n_ highest numbers from an unordered list? I have a long list that I randomly generated. I need the five highest numbers. I have another long list, also randomly generated, from which I need the _sum_ of the five highest numbers I know max(start_list) will give me the single highest number in the list "start_list". How do I get the five highest numbers? Here's my solution, but it's ugly. ----------------------------- start_list=[7, 6, 6, 15, 9, 0, 9, 10, 12, 10, 11, 15, 2, 8, 0, 4, 10, 1, 3, 14] ## start_list is the original version of the first list. high_list=[] ## high_list will be a list of the five highest numbers in start_list start_list2=[2, 13, 0, 10, 10, 3, 3, 5, 9, 11, 10, 5, 9, 14, 4, 6, 5, 3, 11, 11, 9] ## start_list2 is the original version of the second list high_list2=[] ## high_list2 will be a list of the five highest numbers in start_list2. I only use it to find the last five. high_sum= 0 ## high_sum will be the sum of the five highest numbers in start_list2 print 'The first list:', start_list print 'The second list:', start_list2 start_list.sort() for r in range (-1,-6,-1): high_list.append (start_list[r]) high_list.reverse() start_list2.sort() for r in range (-1,-6,-1): high_list2.append (start_list2[r]) high_sum = high_sum + (start_list2[r]) print 'The five highest numbers in the first list:', high_list print 'The sum of the five highest numbers in the second list:', high_sum ----------------------------- Thank you David L. Lerner dell2100@prodigy.net Often, the most striking and innovative solutions come from realizing that your concept of the problem was wrong. Eric Steven Raymond From ak@silmarill.org Mon Aug 27 19:28:05 2001 From: ak@silmarill.org (Andrei Kulakov) Date: Mon, 27 Aug 2001 14:28:05 -0400 Subject: [Tutor] Getting the highest numbers from a list In-Reply-To: <008001c12f25$0651bcc0$508dc540@prodigy.net> References: <008001c12f25$0651bcc0$508dc540@prodigy.net> Message-ID: <20010827142805.A6753@sill.silmarill.org> On Mon, Aug 27, 2001 at 02:20:57PM -0400, David L. Lerner wrote: > Is there a simple way to get the _n_ highest numbers from an unordered list? [snip] How about getting highest number, removing it, getting next highest number, etc? If you want to keep the list intact, make a copy of it. > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From ignacio@openservices.net Mon Aug 27 20:05:04 2001 From: ignacio@openservices.net (Ignacio Vazquez-Abrams) Date: Mon, 27 Aug 2001 15:05:04 -0400 (EDT) Subject: [Tutor] Getting the highest numbers from a list In-Reply-To: <008001c12f25$0651bcc0$508dc540@prodigy.net> Message-ID: <Pine.LNX.4.33.0108271459070.15105-100000@terbidium.openservices.net> On Mon, 27 Aug 2001, David L. Lerner wrote: > Is there a simple way to get the _n_ highest numbers from an unordered list? > > I have a long list that I randomly generated. I need the five highest > numbers. I have another long list, also randomly generated, from which I > need the _sum_ of the five highest numbers > > I know max(start_list) will give me the single highest number in the list > "start_list". How do I get the five highest numbers? > > > Here's my solution, but it's ugly. Here are my changes: > ----------------------------- import operator > start_list=[7, 6, 6, 15, 9, 0, 9, 10, 12, 10, 11, 15, 2, 8, 0, 4, 10, 1, 3, > 14] > ## start_list is the original version of the first list. > > start_list2=[2, 13, 0, 10, 10, 3, 3, 5, 9, 11, 10, 5, 9, 14, 4, 6, 5, 3, 11, > 11, 9] > ## start_list2 is the original version of the second list # in start_list2. I only use it to find the last five. > > print 'The first list:', start_list > print 'The second list:', start_list2 > > start_list.sort() high_list=start_list[-5:] > high_list.reverse() > > start_list2.sort() high_list2=start_list2[-5:] high_sum=reduce(operator.add, high_list2) > print 'The five highest numbers in the first list:', high_list > print 'The sum of the five highest numbers in the second list:', high_sum > > ----------------------------- > Thank you > > David L. Lerner > dell2100@prodigy.net > Often, the most striking and innovative solutions come from realizing that > your concept of the problem was wrong. > Eric Steven Raymond Better? :) -- Ignacio Vazquez-Abrams <ignacio@openservices.net> From dsh8290@rit.edu Mon Aug 27 20:12:28 2001 From: dsh8290@rit.edu (dman) Date: Mon, 27 Aug 2001 15:12:28 -0400 Subject: [Tutor] Getting the highest numbers from a list In-Reply-To: <008001c12f25$0651bcc0$508dc540@prodigy.net>; from dell2100@prodigy.net on Mon, Aug 27, 2001 at 02:20:57PM -0400 References: <008001c12f25$0651bcc0$508dc540@prodigy.net> Message-ID: <20010827151228.A2539@harmony.cs.rit.edu> On Mon, Aug 27, 2001 at 02:20:57PM -0400, David L. Lerner wrote: | Is there a simple way to get the _n_ highest numbers from an unordered list? | | I have a long list that I randomly generated. I need the five highest | numbers. I have another long list, also randomly generated, from which I | need the _sum_ of the five highest numbers How about : the_list = <random list> the_list.sort() top5 = the_list[-5:] sum = 0 for item in top5 : sum += item ? -D From jessw@loop.com Mon Aug 27 20:20:34 2001 From: jessw@loop.com (Jesse W) Date: Mon, 27 Aug 2001 12:20:34 -0700 Subject: [Tutor] Getting the highest numbers from a list In-Reply-To: <008001c12f25$0651bcc0$508dc540@prodigy.net> Message-ID: <3B8A3B12.18638.1799DA9F@localhost> David L. Lerner wrote: > Is there a simple way to get the _n_ highest numbers from an unordered > list? Here is one way: import random,operator #random to make the lists, operator to sum l2. l1=[ random.randint(0, 200) for x in range(20) ] l2=[ random.randint(0, 200) for x in range(20) ] #change the range to make shorter or longer lists, change the args to randint #to make more or less varying lists. def highest(list, num): """Return a list of the num highest items in list.""" list.sort() tmp=list[-num:] tmp.reverse() return tmp print highest(l1, 5), reduce(operator.add, highest(l2, 5)) #now, generate the high lists, and use reduce(operator.add) to sum the #second list. #Credit for the operator.add trick goes to Ignacio Vazquez-Abrams. Hope you like it, Jesse W From Brmfq@aol.com Mon Aug 27 21:02:25 2001 From: Brmfq@aol.com (Brmfq@aol.com) Date: Mon, 27 Aug 2001 16:02:25 EDT Subject: [Tutor] Re: newbie question re execfile("\\") Message-ID: <156.b957.28bc0151@aol.com> Dear Mr. Gauld, I accidentally deleted a post by you from around 8/26. I think it was replying to a question re running a file to the interpreter from Windows. If you would re-post or email it, I would appreciate it. From dyoo@hkn.eecs.berkeley.edu Tue Aug 28 01:27:57 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 27 Aug 2001 17:27:57 -0700 (PDT) Subject: [Tutor] Sim4 output parser In-Reply-To: <Pine.BSF.4.21.0108271218090.25372-100000@fling.sanbi.ac.za> Message-ID: <Pine.LNX.4.21.0108271719110.6567-100000@hkn.eecs.berkeley.edu> On Mon, 27 Aug 2001, Tzu-Ming Chern wrote: > Do you have any advice on how to start parsing sim4 output files? > Specifically, I'd like to extract the start and end points of one of > the matching pairs. You might want to talk with the BioPython folks, http://biopython.org/ and see if they've written a sim4 parser already. I've looked, but haven't been able to find it myself yet. If you can point us toward the sim4 output specification, we might be able to cook something up that will work for you. There is a sim4 parser for BioPerl under the Bio::Tools::Sim4, so if you're pressed for time, you can probably use BioPerl: http://bioperl.org/ Good luck to you! From r.b.rigilink@chello.nl Tue Aug 28 08:06:03 2001 From: r.b.rigilink@chello.nl (Roeland Rengelink) Date: Tue, 28 Aug 2001 09:06:03 +0200 Subject: [Tutor] The __setattr__ method References: <5.1.0.14.2.20010828015118.00b2f888@mail.andover.edu> Message-ID: <3B8B42DB.9082CFB7@chello.nl> Justin Ko wrote: > > Hey everyone. I am working on a module to provide access to an mp3 file's > ID3 tags. A class seemed to be the best way to represent the information > represented in an ID3 tag's fields. However, i would like to be able to > tell when the information in the tag is changed so that the information can > be written back into the ID3 tag. This is my dilemma. > > The __init__ method reads the information from the file. > > def __init__(self, filename = ""): > "Initialize things to default values or read them from a file" > if filename != "": > try: > file = open(filename, "r") > file.seek(-128, 2) > if file.read(3) == "TAG": > self.filename = filename > self.title = file.read(30) > self.artist = file.read(30) > self.album = file.read(30) > self.year = file.read(4) > self.comment = file.read(30) > self.genre = self.genres[ord(file.read(1))] > self.modified = 0 > > The __setattr__ method tells me when something is changed > > def __setattr__(self, name, value): > "Set class attributes" > self.__dict__[name] = value > self.__dict__['modified'] = 1 > > However, the statements in the __init__ method cause __setattr__ to be > called. > So this is my question. How do I set a classes attributes without calling > __setattr__ ? I guess it would be possible to replace all the self.variable > = file.read( ) statements with something like self.__dict__[variable] = > file.read( ), but that seems rather inelegant and ugly. I hope there is a > better solution to this problem. > Assigning to self.__dict__ directly is indeed the standard idiom to bypass the __setattr__ method. Note that you only need to do self.__dict__['modified'] = 0 in the __init__. You can safely let the other assignments call __setitem__. Hope this helps Roeland -- r.b.rigilink@chello.nl "Half of what I say is nonsense. Unfortunately I don't know which half" From csmith@blakeschool.org Tue Aug 28 08:04:44 2001 From: csmith@blakeschool.org (Christopher Smith) Date: Tue, 28 Aug 2001 02:04:44 -0500 Subject: [Tutor] class uncertainty Message-ID: <fc.004c4b6b00796104004c4b6b00796104.796134@blakeschool.org> I've created a class which keeps track of the uncertainty in a number and subsequent calculations performed with that number. It works like this: u=uncertainty #shorten the name # define physical measurements # with +/-1 in last digit by default p=u('1.0') R=u('.0821') T=u('298') # define a physical measurement witha larger uncertainty n=u('1.0,.15') #do the calculation and look at results v=n*R*T/p print v print v[0] print v[1] #results are # 24 +/- 9 # 24.4658 # 9.31980083228 I am in need of some advice now regarding two things: 1) I want to be able to use the math functions on the class. Should I do this as methods, e.g. x.log(), or should I redefine the math functions so that when the module is loaded you now have def log(x): if type(x)==<the type of my class>: return uncertain.log(x) return math.log(x) I would prefer the latter so the operation is as seamless as possible. That's where I need the advise, though. 2) Along the same lines, I would prefer not to have to explicitly create my class. Is there a way to overload the "=" like the algebraic operators? Once you load the class it would treat all numbers as strings and make them into class instances unless, for example, they were followed by 'x' which would denote 'exact'. My guess this is not the way to go. Would another approach be to write an evaluator which would work like this: #### #put the whole 'calculation in triple quotes res=uevaluate(''' p=1.0 R=0.0821 T=298.15 n=1.0,.15 v=n*R*T/p print v in=3.0 print in*2.54x #the x denotes an exact value ''' # and now see the results for ri in res: print ri 24 +/- 9 7.6 +/- 0.3 #### Thanks for any advice. /c From scarblac@pino.selwerd.nl Tue Aug 28 08:03:24 2001 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Tue, 28 Aug 2001 09:03:24 +0200 Subject: [Tutor] Getting the highest numbers from a list In-Reply-To: <008001c12f25$0651bcc0$508dc540@prodigy.net>; from dell2100@prodigy.net on Mon, Aug 27, 2001 at 02:20:57PM -0400 References: <008001c12f25$0651bcc0$508dc540@prodigy.net> Message-ID: <20010828090324.A13327@pino.selwerd.nl> On 0, "David L. Lerner" <dell2100@prodigy.net> wrote: > Is there a simple way to get the _n_ highest numbers from an unordered list? > > I have a long list that I randomly generated. I need the five highest > numbers. I have another long list, also randomly generated, from which I > need the _sum_ of the five highest numbers > > I know max(start_list) will give me the single highest number in the list > "start_list". How do I get the five highest numbers? I tried to think up a few clever ways, but they turned out to be more complicated than I thought at first. The simple way is to sort the list and take the last five numbers. Go with the simplest way until you're certain that is too slow (you'd need *huge* lists before some other way becomes faster). start_list = ... start_list.sort() return start_list[-5:] -- Remco Gerlich From hnowak@cuci.nl Tue Aug 28 08:47:18 2001 From: hnowak@cuci.nl (Hans Nowak) Date: Tue, 28 Aug 2001 09:47:18 +0200 Subject: [Tutor] class uncertainty Message-ID: <3B8BA66F@twigger.nl> >===== Original Message From "Christopher Smith" <csmith@blakeschool.org> ===== >I've created a class which keeps track of the uncertainty in a number and >subsequent calculations performed with that number. It works like this: > >u=uncertainty #shorten the name > ># define physical measurements ># with +/-1 in last digit by default >p=u('1.0') >R=u('.0821') >T=u('298') > ># define a physical measurement witha larger uncertainty >n=u('1.0,.15') > >#do the calculation and look at results >v=n*R*T/p >print v >print v[0] >print v[1] > >#results are ># 24 +/- 9 ># 24.4658 ># 9.31980083228 Looks neat... why is u() taking strings, though? >I am in need of some advice now regarding two things: > >1) I want to be able to use the math functions on the class. >Should I do this as methods, e.g. x.log(), or should I redefine >the math functions so that when the module is loaded you now have > >def log(x): > if type(x)==<the type of my class>: > return uncertain.log(x) > return math.log(x) > >I would prefer the latter so the operation is as seamless as possible. >That's where I need the advise, though. Redefining existing functions is usually a bad idea, but in this case you're preserving the original behavior of math.log for objects other than your class, so I guess it's not as bad. This is more of a design question than anything else... will the users of your class expect methods or functions? This may be simplified to: are they coming from an OO background, or a functional programming one? I don't think there's much to say to give one a significant benefit over the other, except maybe that <your_class>.log() would be less ambiguous than using a log function. There's another possibility, though... I don't know if this makes sense for your class, but you can define the __float__ method, and have it return the float value you're trying to take the log() of. A trivial example: >>> class Foo: def __init__(self, x): self.x = x def __float__(self): try: return float(self.x) except: return 1.0 >>> f = Foo(99) >>> math.log(f) 4.5951198501345898 >>> g = Foo("bla") >>> math.log(g) 0.0 I haven't tested this thoroughly, but I think it might be a solution for your problem. >2) Along the same lines, I would prefer not to have to explicitly create >my class. Is there a way to overload the "=" like the algebraic operators? Nope. :) >Once you load the class it would treat all numbers as strings and make them >into class instances unless, for example, they were followed by 'x' which >would denote 'exact'. My guess this is not the way to go. > >Would another approach be to write an evaluator which would work like this: > >#### >#put the whole 'calculation in triple quotes >res=uevaluate(''' >p=1.0 >R=0.0821 >T=298.15 >n=1.0,.15 > >v=n*R*T/p >print v > >in=3.0 >print in*2.54x #the x denotes an exact value >''' ># and now see the results >for ri in res: > print ri > >24 +/- 9 >7.6 +/- 0.3 >#### Ouch... this last approach would require you to parse the code, find all (?) numbers, and replace them with u() instances. I think your original approach was just fine... at least people reading the code would know you are dealing with uncertainty objects. This is better than implicit conversions, IMHO. HTH, --Hans Nowak From r.b.rigilink@chello.nl Tue Aug 28 08:56:00 2001 From: r.b.rigilink@chello.nl (Roeland Rengelink) Date: Tue, 28 Aug 2001 09:56:00 +0200 Subject: [Tutor] class uncertainty References: <fc.004c4b6b00796104004c4b6b00796104.796134@blakeschool.org> Message-ID: <3B8B4E90.3DEA1270@chello.nl> Christopher Smith wrote: > > I've created a class which keeps track of the uncertainty in a number and > subsequent calculations performed with that number. It works like this: > Neat > u=uncertainty #shorten the name > > # define physical measurements > # with +/-1 in last digit by default > p=u('1.0') > R=u('.0821') > T=u('298') > > # define a physical measurement witha larger uncertainty > n=u('1.0,.15') > > #do the calculation and look at results > v=n*R*T/p > print v > print v[0] > print v[1] > > #results are > # 24 +/- 9 > # 24.4658 > # 9.31980083228 > > I am in need of some advice now regarding two things: > I may be making an ass of myself, but according to my quick calculations this should be closer to: 24 +/- 4 24.4658 4.4115 > 1) I want to be able to use the math functions on the class. > Should I do this as methods, e.g. x.log(), or should I redefine > the math functions so that when the module is loaded you now have > > def log(x): > if type(x)==<the type of my class>: > return uncertain.log(x) > return math.log(x) > > I would prefer the latter so the operation is as seamless as possible. > That's where I need the advise, though. > I think this is a good solution. > 2) Along the same lines, I would prefer not to have to explicitly create > my class. Is there a way to overload the "=" like the algebraic operators? > Once you load the class it would treat all numbers as strings and make them > into class instances unless, for example, they were followed by 'x' which > would denote 'exact'. My guess this is not the way to go. > You cant't overload =. In Python asignment is a statement not an operator. Also, in the following: radius = uncertainty(3.0, 0.2) circumference = 2*3.1415*radius you dont't want 2 and 3.1415 be treated as uncertain numbers. So, it is in fact good that you have to explicit about making a numeric literal an uncertain number. But you already noticed that. So, why are you opposed to writing u(1) for an uncertain number but willing to write 1x for an exact number? > Would another approach be to write an evaluator which would work like this: > > #### > #put the whole 'calculation in triple quotes > res=uevaluate(''' > p=1.0 > R=0.0821 > T=298.15 > n=1.0,.15 > > v=n*R*T/p > print v > > in=3.0 > print in*2.54x #the x denotes an exact value > ''' > # and now see the results > for ri in res: > print ri > > 24 +/- 9 > 7.6 +/- 0.3 > #### > Yep. This could be an approach. Basically, if you want to write your own language, you have to write your own parser/evaluator. This may turn out to be much harder than you think though. Why do that if you already have a beautiful language (Python), that is perfectly willing to deal with uncertain numbers, as long as you properly instantiate them? Hope this helps, Roeland -- r.b.rigilink@chello.nl "Half of what I say is nonsense. Unfortunately I don't know which half" From r.b.rigilink@chello.nl Tue Aug 28 09:30:41 2001 From: r.b.rigilink@chello.nl (Roeland Rengelink) Date: Tue, 28 Aug 2001 10:30:41 +0200 Subject: [Tutor] class uncertainty References: <fc.004c4b6b00796104004c4b6b00796104.796134@blakeschool.org> <3B8B4E90.3DEA1270@chello.nl> Message-ID: <3B8B56B1.13A4C532@chello.nl> Roeland Rengelink wrote: > > Christopher Smith wrote: > > > > I've created a class which keeps track of the uncertainty in a number and > > subsequent calculations performed with that number. It works like this: [snip] > > > > def log(x): > > if type(x)==<the type of my class>: > > return uncertain.log(x) > > return math.log(x) > > > > I would prefer the latter so the operation is as seamless as possible. > > That's where I need the advise, though. > > > > I think this is a good solution. > Where I was assuming you meant something like: def log(x): if isinstance(x, uncertain): return x.log() else: return math.log(x) with class uncertain: ... def log(self): ...return uncertain log... So that module uncertain provides - a log function that can take both exact and uncertain numbers as argument - an uncertain class that knows how to do a log of an uncertain number. Hope this helps, Roeland -- r.b.rigilink@chello.nl "Half of what I say is nonsense. Unfortunately I don't know which half" From melvin2001@earthlink.net Tue Aug 28 09:58:03 2001 From: melvin2001@earthlink.net (melvin2001) Date: Tue, 28 Aug 2001 04:58:03 -0400 Subject: [Tutor] calculator Message-ID: <000f01c12f9f$a09af560$1a00a0c0@matt> This is a multi-part message in MIME format. ------=_NextPart_000_000A_01C12F7E.047D7480 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable well......im 15 years old and i just started messing with python a few = days ago so obviously im not gonna be very good :op but i wrote a little = program that does basic calculations and its not done yet i add to it = just about every day. just wanted to show you guys to see what you think = maybe help me out a little too. test =3D 1 print "alright now for some real math" print while test =3D=3D 1: print "please choose an option" print print "1. circle area" print "2. square area" print "3. rectangle area" print "4. square root" print "5. add numbers" shape =3D input("> ") if shape =3D=3D 1: print "would you like to input radius or diameter?" print "1. radius" print "2. diameter" question =3D input ("> ") if question =3D=3D 1: print "what is the radius?" radius =3D input("> ") radius =3D 3.14*radius**2 print radius elif question =3D=3D 2: print "what is the diameter?" diameter =3D input ("> ") diameter =3D diameter/2 diameter =3D diameter**2 * 3.14 print diameter else: print print "whoops thats not good" print elif shape =3D=3D 2: print "what is the length of a side?" side =3D input("> ") side =3D side*4 print side elif shape =3D=3D 3: print "what is the length?" length =3D input("> ") print "what is the height?" height =3D input("> ") height =3D height*length print height elif shape =3D=3D 4: lauren =3D 0 print "what number do you need the square root for?" number =3D input("> ") guess =3D 1.0 while lauren !=3D guess: lauren =3D (number / guess + guess)/2 guess =3D (number / lauren + lauren)/2 print guess elif shape =3D=3D 5: krysten =3D input("first number to add> ") add =3D input("second number to add> ") equals =3D add + krysten print "is that all?" print "1. yes" print "2. no" all =3D input("> ") if all =3D=3D 1: print equals if all =3D=3D 2: while all =3D=3D 2: third =3D input("next number to add> ") equals =3D equals + third print "is that all?" print "1. yes" print "2. no" all =3D input("> ") print equals else: print print "whoops thats not good" print ------=_NextPart_000_000A_01C12F7E.047D7480 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML><HEAD> <META http-equiv=3DContent-Type content=3D"text/html; = charset=3Diso-8859-1"> <META content=3D"MSHTML 5.50.4134.100" name=3DGENERATOR> <STYLE></STYLE> </HEAD> <BODY bgColor=3D#ffffff> <DIV><FONT face=3DArial size=3D2>well......im 15 years old and i just = started=20 messing with python a few days ago so obviously im not gonna be very = good :op=20 but i wrote a little program that does basic calculations and its not = done yet i=20 add to it just about every day. just wanted to show you guys to see what = you=20 think maybe help me out a little too.</FONT></DIV> <DIV><FONT face=3DArial size=3D2></FONT> </DIV> <DIV><FONT face=3DArial size=3D2>test =3D 1<BR>print "alright now for = some real=20 math"<BR>print<BR>while test =3D=3D 1:<BR>    print = "please choose an=20 option"<BR>    print<BR>    print "1. = circle=20 area"<BR>    print "2. square area"<BR>    = print=20 "3. rectangle area"<BR>    print "4. square=20 root"<BR>    print "5. add numbers"<BR>    = shape =3D=20 input("> ")<BR>    if shape =3D=3D=20 1:<BR>        print "would you like = to input=20 radius or diameter?"<BR>        print = "1.=20 radius"<BR>        print "2.=20 diameter"<BR>        question =3D = input (">=20 ")<BR>        if question =3D=3D=20 1:<BR>            = print=20 "what is the=20 radius?"<BR>          &= nbsp;=20 radius =3D input(">=20 ")<BR>            = radius=20 =3D=20 3.14*radius**2<BR>         &= nbsp; =20 print radius<BR>        elif question = =3D=3D=20 2:<BR>            = print=20 "what is the=20 diameter?"<BR>          = ; =20 diameter =3D input (">=20 ")<BR>            = diameter =3D=20 diameter/2<BR>          = ; =20 diameter =3D diameter**2 *=20 3.14<BR>           = ; print=20 diameter<BR>       =20 else:<BR>          &nbs= p;=20 print<BR>          &nbs= p;=20 print "whoops thats not=20 good"<BR>          &nbs= p;=20 print<BR>    elif shape =3D=3D=20 2:<BR>        print "what is the = length of a=20 side?"<BR>        side =3D = input(">=20 ")<BR>        side =3D=20 side*4<BR>        print=20 side<BR>    elif shape =3D=3D=20 3:<BR>        print "what is the=20 length?"<BR>        length =3D = input(">=20 ")<BR>        print "what is the=20 height?"<BR>        height =3D = input(">=20 ")<BR>        height =3D=20 height*length<BR>        print=20 height<BR>    elif shape =3D=3D 4:<BR> lauren =3D = 0<BR> print=20 "what number do you need the square root for?"<BR> number =3D = input(">=20 ")<BR> guess =3D 1.0<BR> while lauren !=3D = guess:<BR>  lauren =3D=20 (number / guess + guess)/2<BR>  guess =3D (number / lauren +=20 lauren)/2<BR> print guess<BR>    elif shape =3D=3D=20 5:<BR>        krysten =3D = input("first number=20 to add> ")<BR>        add =3D = input("second=20 number to add> ")<BR>        = equals =3D add=20 + krysten<BR>        print "is that=20 all?"<BR>        print "1.=20 yes"<BR>        print "2.=20 no"<BR>        all =3D input(">=20 ")<BR> if all =3D=3D=20 1:<BR>            = print=20 equals<BR>        if all =3D=3D=20 2:<BR>            = while=20 all =3D=3D=20 2:<BR>           &= nbsp;   =20 third =3D input("next number to add>=20 ")<BR>           &= nbsp;   =20 equals =3D equals +=20 third<BR>          &nbs= p;    =20 print "is that all?"<BR>         =  print "1. yes"<BR>         =  print "2. no"<BR>        =20  all =3D input("> = ")<BR>        print=20 equals<BR>    = else:<BR>       =20 print<BR>        print "whoops thats = not=20 good"<BR>       =20 print</FONT></DIV></BODY></HTML> ------=_NextPart_000_000A_01C12F7E.047D7480-- From Charlie@begeistert.org Tue Aug 28 10:36:25 2001 From: Charlie@begeistert.org (Charlie Clark) Date: Tue, 28 Aug 2001 11:36:25 +0200 Subject: [Tutor] Help converting strings to numbers In-Reply-To: <E15bdZZ-0008El-00@mail.python.org> Message-ID: <998991385_PM_BeOS.Charlie@begeistert.org> Dear all, I'm getting a whole set of values and putting them in a dictionary like this {'preis': '2.029,00', 'marktpreis':'3.399,00'} from which I need to generate a third price 'saving' which is ('preis' / 'marktpreis') * 100 but I don't know how to convert the string prices to floats to do the maths - it's an invalid literal. Please reply to me directly as I'm currently subscribed to the digest. Thanx Charlie From lumbricus@gmx.net Tue Aug 28 10:49:37 2001 From: lumbricus@gmx.net (Joerg Woelke) Date: Tue, 28 Aug 2001 11:49:37 +0200 Subject: [Tutor] calculator In-Reply-To: <000f01c12f9f$a09af560$1a00a0c0@matt>; from melvin2001@earthlink.net on Tue, Aug 28, 2001 at 04:58:03AM -0400 References: <000f01c12f9f$a09af560$1a00a0c0@matt> Message-ID: <20010828114937.A2023@Laplace.localdomain> On Tue, Aug 28, 2001 at 04:58:03AM -0400, melvin2001 wrote: > well......im 15 years old and i just started messing with python a few days ago so obviously im not gonna be very good :op but i wrote a little program that does basic calculations and its not done yet i add to it just about every day. just wanted to show you guys to see what you think maybe help me out a little too. > > test = 1 > print "alright now for some real math" > print > while test == 1: Am i missing something or is this equivalent to "while 1:" where are the breaks? > print "please choose an option" > print > print "1. circle area" > print "2. square area" > print "3. rectangle area" > print "4. square root" > print "5. add numbers" > shape = input("> ") How about error checking? try: shape=int(raw_input("> ")) # because users like to enter nonesense ;-) except ValueError: print "Need number" ... > if shape == 1: > print "would you like to input radius or diameter?" > print "1. radius" > print "2. diameter" > question = input ("> ") > if question == 1: > print "what is the radius?" > radius = input("> ") > radius = 3.14*radius**2 > print radius > elif question == 2: > print "what is the diameter?" > diameter = input ("> ") > diameter = diameter/2 > diameter = diameter**2 * 3.14 You want to pack thing like that in functions. > print diameter > else: > print > print "whoops thats not good" > print > elif shape == 2: > print "what is the length of a side?" > side = input("> ") > side = side*4 > print side > elif shape == 3: > print "what is the length?" > length = input("> ") > print "what is the height?" > height = input("> ") > height = height*length > print height > elif shape == 4: > lauren = 0 > print "what number do you need the square root for?" > number = input("> ") > guess = 1.0 > while lauren != guess: > lauren = (number / guess + guess)/2 > guess = (number / lauren + lauren)/2 > print guess > elif shape == 5: > krysten = input("first number to add> ") > add = input("second number to add> ") > equals = add + krysten > print "is that all?" > print "1. yes" > print "2. no" > all = input("> ") > if all == 1: > print equals > if all == 2: > while all == 2: > third = input("next number to add> ") > equals = equals + third > print "is that all?" > print "1. yes" > print "2. no" > all = input("> ") > print equals > else: > print > print "whoops thats not good" > print Good luck! HTH, HAND J"o! :-) -- Q: What do Winnie the Pooh and John the Baptist have in common? A: The same middle name. From hnowak@cuci.nl Tue Aug 28 11:12:02 2001 From: hnowak@cuci.nl (Hans Nowak) Date: Tue, 28 Aug 2001 12:12:02 +0200 Subject: [Tutor] Help converting strings to numbers Message-ID: <3B8D379D@twigger.nl> >===== Original Message From Charlie@begeistert.org ===== >Dear all, > >I'm getting a whole set of values and putting them in a dictionary like >this > >{'preis': '2.029,00', 'marktpreis':'3.399,00'} > >from which I need to generate a third price 'saving' which is ('preis' / >'marktpreis') * 100 but I don't know how to convert the string prices to >floats to do the maths - it's an invalid literal. > >Please reply to me directly as I'm currently subscribed to the digest. Not sure if there is a function for this in the standard library, but you can easily roll your own: >>> import string >>> s = '2.029,33' >>> s = string.replace(s, ".", "") >>> s '2029,33' >>> s = string.replace(s, ",", ".") >>> s '2029.33' >>> float(s) 2029.3299999999999 HTH, --Hans Nowak From Charlie@begeistert.org Tue Aug 28 11:12:50 2001 From: Charlie@begeistert.org (Charlie Clark) Date: Tue, 28 Aug 2001 12:12:50 +0200 Subject: [Tutor] Help converting strings to numbers In-Reply-To: <3B8D379D@twigger.nl> Message-ID: <998993570_PM_BeOS.Charlie@begeistert.org> >Not sure if there is a function for this in the standard library, but you can >easily roll your own: > >>>> import string >>>> s = '2.029,33' >>>> s = string.replace(s, ".", "") >>>> s >'2029,33' >>>> s = string.replace(s, ",", ".") >>>> s >'2029.33' oh, okay. Not elegant but functional and seeing as what I'm doing is insane anyway that will do fine From lumbricus@gmx.net Tue Aug 28 11:20:14 2001 From: lumbricus@gmx.net (Joerg Woelke) Date: Tue, 28 Aug 2001 12:20:14 +0200 Subject: [Tutor] Help converting strings to numbers In-Reply-To: <998991385_PM_BeOS.Charlie@begeistert.org>; from Charlie@begeistert.org on Tue, Aug 28, 2001 at 11:36:25AM +0200 References: <E15bdZZ-0008El-00@mail.python.org> <998991385_PM_BeOS.Charlie@begeistert.org> Message-ID: <20010828122014.B2023@Laplace.localdomain> On Tue, Aug 28, 2001 at 11:36:25AM +0200, Charlie Clark wrote: > Dear all, > > I'm getting a whole set of values and putting them in a dictionary like > this > > {'preis': '2.029,00', 'marktpreis':'3.399,00'} > > >from which I need to generate a third price 'saving' which is ('preis' / > 'marktpreis') * 100 but I don't know how to convert the string prices to > floats to do the maths - it's an invalid literal. > preis='2.029,00' import re p=re.compile('^\d') rp=re.sub(p,'',preis) print rp Hint: Calculate in "Pfennige". So you avoid floating point arithmetics with its problems. int(rp) > Please reply to me directly as I'm currently subscribed to the digest. > > Thanx HTH, HAND J"o! :-) > > Charlie > -- Huh? From Charlie@begeistert.org Tue Aug 28 13:11:26 2001 From: Charlie@begeistert.org (Charlie Clark) Date: Tue, 28 Aug 2001 14:11:26 +0200 Subject: [Tutor] Web-spider & urllib Message-ID: <999000686_PM_BeOS.Charlie@begeistert.org> For my sins I've been writing some web-spiders to collect some information. One of them collects information from around 260 pages and seems to hang every now and then without providing any errors - interrupting it with ctrl+c indicates its waiting on a socket. I've double-checked to make sure all url's are closed once the contents have been collected and it's easy to see the sockets being reallocated in netstat The basic loops just call the parsing functions: # Collect the pages with the links, 25 links per page articles = [] for i in range (0, 150, 25): src = base_url + index + str(i) print "getting ", src src = urllib.urlopen(src) articles += (munig.get_articles(src)) # print articles # Collect all pages found in the links places = [] for article in articles: src = urllib.urlopen(base_url + article['link']) print "getting ", article['headline'] place = munig.party(src) place['headline'] = article['headline'] places.append(place) What's the best way to go about finding what's the problem? (It seems worse when running behind the firewall) What are possible work arounds? Is it possible to "flush" the connection Thanx Charlie From printers@sendme.cz Tue Aug 28 13:18:54 2001 From: printers@sendme.cz (A) Date: Tue, 28 Aug 2001 14:18:54 +0200 Subject: [Tutor] Questions about threads Message-ID: <3B8BA84E.12547.1408A1A@localhost> Hi, Can anybody please answer my questions? 1. In my application I need one function to run in threads. The number of threads is chosen by user and numbers of threads can not be higher at one time. This function writes to a file also.How can I prevent other threads from writting to this file when the file is open by another thread ? 2. How can one process control another? For example: my program tries to connect to a server over phone. I want to cancel dial up connection if there is timeout. How can that be done in Python? Thank you very much for help. Ladislav From printers@sendme.cz Tue Aug 28 13:18:54 2001 From: printers@sendme.cz (A) Date: Tue, 28 Aug 2001 14:18:54 +0200 Subject: [Tutor] Py2exe and wxPython Message-ID: <3B8BA84E.4003.1408A42@localhost> Hi, Does anyone have any experience with Py2exe converting python source into exe if there is wxPython used in source? Thanks for reply Ladislav From ak@silmarill.org Tue Aug 28 13:29:09 2001 From: ak@silmarill.org (Andrei Kulakov) Date: Tue, 28 Aug 2001 08:29:09 -0400 Subject: [Tutor] Questions about threads In-Reply-To: <3B8BA84E.12547.1408A1A@localhost> References: <3B8BA84E.12547.1408A1A@localhost> Message-ID: <20010828082908.A2365@sill.silmarill.org> On Tue, Aug 28, 2001 at 02:18:54PM +0200, A wrote: > Hi, > Can anybody please answer my questions? > > 1. In my application I need one function to run in threads. The > number of threads is chosen by user and numbers of threads can > not be higher at one time. > This function writes to a file also.How can I prevent other threads > from writting to this file when the file is open by another thread ? I never done this, but I guess you should 'lock' the file, that is, set a global var file_locked to 1, then open file, write to it, then set file_locked to 0. There may be some gotchas here, I'm not sure if this is bullet-proof. > > 2. How can one process control another? For example: my > program tries to connect to a server over phone. I want to cancel > dial up connection if there is timeout. How can that be done in > Python? Through global variables, like in above example. > > Thank you very much for help. > Ladislav > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From lonetwin@yahoo.com Tue Aug 28 13:46:17 2001 From: lonetwin@yahoo.com (steve) Date: Tue, 28 Aug 2001 18:16:17 +0530 Subject: [Tutor] The __setattr__ method In-Reply-To: <5.1.0.14.2.20010828015118.00b2f888@mail.andover.edu> References: <5.1.0.14.2.20010828015118.00b2f888@mail.andover.edu> Message-ID: <01082818161701.20724@mercury.in.cqsl.com> Hi there, On Monday 27 August 2001 23:33, you wrote: > Hey everyone. I am working on a module to provide access to an mp3 file= 's > ID3 tags. A class seemed to be the best way to represent the informatio= n > represented in an ID3 tag's fields. However, i would like to be able to > tell when the information in the tag is changed so that the information= can > be written back into the ID3 tag. This is my dilemma. > ..... > ..... > <snip> Thought I'd just mention it,....I've written a similar module, you can h= ave=20 a look at it at the Useless Python site: http://www.lowerstandard.com/python/uselesspython12.html I have used a UserDict to represent the IDTag data, like so: =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D class mp3file(UserDict): tagDataMap =3D { "title" : ( 3, 33, stripnulls), "artist" : ( 33, 63, stripnulls), "album" : ( 63, 93, stripnulls), "year" : ( 93, 97, stripnulls), "comment" : ( 96, 126, stripnulls), "genre" : (127, 128, ord) } def __init__(self, flname =3D None): UserDict.__init__(self) self["name"] =3D flname self.__parse() self.dir, file =3D os.path.split(flname) self["new_name"] =3D file def __parse(self): try: fl =3D open(self["name"], "r") try: fl.seek(-128, 2) tagdata =3D fl.read() finally: fl.close() if tagdata[:3] =3D=3D 'TAG': for tag, (start, end, func) in self.tagDataMap.items(): self[tag] =3D func(tagdata[start:end]) else: for tag in self.tagDataMap.keys(): self[tag] =3D '' except IOError,msg: raise BigBooBoo("Error opening file %s\n%s" % (flname, ms= g)) =20 def __setitem__(self, key, item): if key in [ "title", "artist", "album", "comment" ]: item =3D item[:30] elif key =3D=3D "year": item =3D item[:4] elif key =3D=3D "genre": item =3D self.getGenre(item) self.data[key] =3D item =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D It might not be all that clear b'cos I have no comments within the file a= bout=20 why I do what I do, but if you have questions about anything you could al= ways=20 ask. Hope you find it interesting Peace Steve =20 -------------------------------------------------------------------------= --- You will pay for your sins. If you have already paid, please disregard this message. -------------------------------------------------------------------------= --- From csmith@blakeschool.org Tue Aug 28 14:06:32 2001 From: csmith@blakeschool.org (Christopher Smith) Date: Tue, 28 Aug 2001 08:06:32 -0500 Subject: [Tutor] class uncertainty In-Reply-To: <3B8BA66F@twigger.nl> References: <3B8BA66F@twigger.nl> Message-ID: <fc.004c4b6b007965213b9aca00e90a555c.796525@blakeschool.org> hnowak@cuci.nl writes: >>===== Original Message From "Christopher Smith" <csmith@blakeschool.org> >===== >>I've created a class which keeps track of the uncertainty in a number and >>subsequent calculations performed with that number. It works like this: >> >>u=uncertainty #shorten the name >> >># define physical measurements >># with +/-1 in last digit by default >>p=u('1.0') >>R=u('.0821') >>T=u('298') >> >># define a physical measurement witha larger uncertainty >>n=u('1.0,.15') >> >>#do the calculation and look at results >>v=n*R*T/p >>print v >>print v[0] >>print v[1] >> >>#results are >># 24 +/- 9 >># 24.4658 >># 9.31980083228 > >Looks neat... why is u() taking strings, though? To avoid missing an intended trailing 0 (5.00) looking like 5.0) or excessive digits b/c of floating representation issues (5.1 looking like 5.09999999996 to the function). /c > From ignacio@openservices.net Tue Aug 28 14:39:20 2001 From: ignacio@openservices.net (Ignacio Vazquez-Abrams) Date: Tue, 28 Aug 2001 09:39:20 -0400 (EDT) Subject: [Tutor] Questions about threads In-Reply-To: <3B8BA84E.12547.1408A1A@localhost> Message-ID: <Pine.LNX.4.33.0108280937040.5290-100000@terbidium.openservices.net> On Tue, 28 Aug 2001, A wrote: > Hi, > Can anybody please answer my questions? > > 1. In my application I need one function to run in threads. The > number of threads is chosen by user and numbers of threads can > not be higher at one time. > This function writes to a file also.How can I prevent other threads > from writting to this file when the file is open by another thread ? Use a threading.Lock or treading.Semaphore to control access to it. > 2. How can one process control another? For example: my > program tries to connect to a server over phone. I want to cancel > dial up connection if there is timeout. How can that be done in > Python? It depends on the process. If it's pppd, then sending it a SIGHUP should do. > Thank you very much for help. > Ladislav -- Ignacio Vazquez-Abrams <ignacio@openservices.net> From dsh8290@rit.edu Tue Aug 28 16:13:19 2001 From: dsh8290@rit.edu (dman) Date: Tue, 28 Aug 2001 11:13:19 -0400 Subject: [Tutor] Help converting strings to numbers In-Reply-To: <998991385_PM_BeOS.Charlie@begeistert.org>; from Charlie@begeistert.org on Tue, Aug 28, 2001 at 11:36:25AM +0200 References: <E15bdZZ-0008El-00@mail.python.org> <998991385_PM_BeOS.Charlie@begeistert.org> Message-ID: <20010828111319.F5737@harmony.cs.rit.edu> On Tue, Aug 28, 2001 at 11:36:25AM +0200, Charlie Clark wrote: | Dear all, | | I'm getting a whole set of values and putting them in a dictionary like | this | | {'preis': '2.029,00', 'marktpreis':'3.399,00'} You Europeans just can't do anything right, can you <wink>? It would certainly be useful if someone wrote a Euro<=>US literal float converter and if the float() function could handle both notations. The easiest is probably just to mangle the string to match the US notation and then use float() to convert (or strip the decimal point and use int()). -D From dsh8290@rit.edu Tue Aug 28 16:23:10 2001 From: dsh8290@rit.edu (dman) Date: Tue, 28 Aug 2001 11:23:10 -0400 Subject: [Tutor] calculator In-Reply-To: <000f01c12f9f$a09af560$1a00a0c0@matt>; from melvin2001@earthlink.net on Tue, Aug 28, 2001 at 04:58:03AM -0400 References: <000f01c12f9f$a09af560$1a00a0c0@matt> Message-ID: <20010828112310.G5737@harmony.cs.rit.edu> On Tue, Aug 28, 2001 at 04:58:03AM -0400, melvin2001 wrote: | well......im 15 years old and i just started messing with python a | few days ago so obviously im not gonna be very good :op but i wrote | a little program that does basic calculations and its not done yet i | add to it just about every day. just wanted to show you guys to see | what you think maybe help me out a little too. It looks operational, but I think it is now time for you to study functions and try breaking this massively long loop and conditional statement into some smaller, reusable, functions. A dictionary that has strings as keys and functions for values is a good way to implement the "if" you have. For example, options = { "1" : circle_area , "2" : square_area , "3" : rectangle area , "4" : square root , "5" : add numbers , } Then you would have the following for your "main" loop : print "alright now for some real math\n" while : print "please choose an option" print print "1. circle area" print "2. square area" print "3. rectangle area" print "4. square root" print "5. add numbers" # use raw_input() instead of input() -- there are various security # holes and issues with using input() in a production environment # (it is fine for quick-n-dirty testing/prototyping though) shape = raw_input("> ") # now get the function that handles this operation and let it do # the real work, be sure to check for errors first if not options.has_key( shape ) : print "Error -- %s is not a valid option" % shape continue # go on with the next iteration of the loop options[ shape ]() The body of each 'if' block will be moved into a separation function. If you see code that is repeated in more than one function, come up with a way to generalize it and make it another function. Then each of your shape functions can call that function. This makes the code easier to read and maintain. This reminds me of the programs I first wrote (in GWBASIC) many years ago. It is a good start. If you want some more concrete examples of how to break that 'if' into separate functions, ask and I (or someone else) will provide them when I get the time. HTH, -D From ignacio@openservices.net Tue Aug 28 16:30:12 2001 From: ignacio@openservices.net (Ignacio Vazquez-Abrams) Date: Tue, 28 Aug 2001 11:30:12 -0400 (EDT) Subject: [Tutor] Help converting strings to numbers In-Reply-To: <20010828111319.F5737@harmony.cs.rit.edu> Message-ID: <Pine.LNX.4.33.0108281128330.5290-100000@terbidium.openservices.net> On Tue, 28 Aug 2001, dman wrote: > On Tue, Aug 28, 2001 at 11:36:25AM +0200, Charlie Clark wrote: > | Dear all, > | > | I'm getting a whole set of values and putting them in a dictionary like > | this > | > | {'preis': '2.029,00', 'marktpreis':'3.399,00'} > > You Europeans just can't do anything right, can you <wink>? > > It would certainly be useful if someone wrote a Euro<=>US literal > float converter and if the float() function could handle both > notations. The easiest is probably just to mangle the string to match > the US notation and then use float() to convert (or strip the decimal > point and use int()). > > -D Actually, there is such a converter; it's in the locale module. Just set the locale to something appropriate using locale.setlocale(), then use locale.atof() to convert it. -- Ignacio Vazquez-Abrams <ignacio@openservices.net> From dyoo@hkn.eecs.berkeley.edu Tue Aug 28 18:13:05 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 28 Aug 2001 10:13:05 -0700 (PDT) Subject: [Tutor] calculator [using functions] In-Reply-To: <000f01c12f9f$a09af560$1a00a0c0@matt> Message-ID: <Pine.LNX.4.21.0108280943510.18637-100000@hkn.eecs.berkeley.edu> On Tue, 28 Aug 2001, melvin2001 wrote: > well......im 15 years old and i just started messing with python a few > days ago so obviously im not gonna be very good :op but i wrote a No problem, and don't worry about it. Congrats on starting to learn programming! > little program that does basic calculations and its not done yet i add > to it just about every day. just wanted to show you guys to see what > you think maybe help me out a little too. I read your program, and it looks ok. I agree with dman that using functions will improve your program. When we make our own functions, programs usually get easier to read because there's less to read at one time. In some sense, functions act like paragraphs on a page. Since the program gives the user five choices: > print "1. circle area" > print "2. square area" > print "3. rectangle area" > print "4. square root" > print "5. add numbers" we can probably make up 5 separate functions to take care of each shape. For example, to pull the "circle area" function into a function, we could do something like this: ### def doCircleArea(): print "would you like to input radius or diameter?" print "1. radius" print "2. diameter" question = input ("> ") if question == 1: print "what is the radius?" radius = input("> ") radius = 3.14*radius**2 print radius elif question == 2: print "what is the diameter?" diameter = input ("> ") diameter = diameter/2 diameter = diameter**2 * 3.14 print diameter else: print print "whoops thats not good" print ### and we could do the same thing for the other four shapes. One side benefit is that we don't need to indent as much, since we pulled the shape calculations out of the inner while loop. Another is that when we want to add additional stuff (maybe to calculate triangle area), it's a lot easier to see where to add code. If we use functions, the main program might look like this: ### test = 1 print "alright now for some real math" print while test == 1: print "please choose an option" print print "1. circle area" print "2. square area" print "3. rectangle area" print "4. square root" print "5. add numbers" shape = input("> ") if shape == 1: doCircleArea() elif shape == 2: doSquareArea() elif shape == 3: doRectangleArea() elif shape == 4: doSquareRoot() elif share == 5: doAddNumbers() else: print print "whoops thats not good" print ### If you have more questions, please feel free to ask. Good luck to you! From ignacio@openservices.net Tue Aug 28 18:43:36 2001 From: ignacio@openservices.net (Ignacio Vazquez-Abrams) Date: Tue, 28 Aug 2001 13:43:36 -0400 (EDT) Subject: [Tutor] calculator In-Reply-To: <000f01c12f9f$a09af560$1a00a0c0@matt> Message-ID: <Pine.LNX.4.33.0108281326170.5290-100000@terbidium.openservices.net> Something else you can do, in conjunction with all the other really good suggestions you've received so far, is to code your main menu (and in fact all of your menus) similar to this: --- def circlearea(): ... def squarearea(): ... def rectanglearea(): ... def squareroot(): ... def addnumbers(): ... menuoptions={'1':circlearea, '2':squarearea, '3':rectanglearea, '4':squareroot, '5':addnumbers} while 1: while 1: print "please choose an option" print print "1. circle area" print "2. square area" print "3. rectangle area" print "4. square root" print "5. add numbers" shape = input("> ") if not menuoptions.has_key(shape) print print "whoops thats not good" print else: break menuoptions[choice]() --- That way finding the option is a matter of a lookup in a dictionary. If you wanted to be REALLY clever you could do the following: --- menuoptions={'1':(circlearea, 'circle area'), '2':(squarearea, 'square area'), '3':(rectanglearea, 'rectangle area'), '4':(squareroot, 'square root', '5':(addnumbers, 'add numbers')} while 1: while 1: print "please choose an option" print for i in menuoptions.keys(): print "%s. %s" % (i, menuoptions[i][1]) shape = input("> ") if not menuoptions.has_key(shape) print print "whoops thats not good" print else: break menuoptions[choice][0]() --- That way you get not only the valid inputs and the functions to call from the dictionary, but also the descriptions to print in the menu. And adding new functions is simply a matter of adding entries to the dictionary. -- Ignacio Vazquez-Abrams <ignacio@openservices.net> From ignacio@openservices.net Tue Aug 28 18:49:31 2001 From: ignacio@openservices.net (Ignacio Vazquez-Abrams) Date: Tue, 28 Aug 2001 13:49:31 -0400 (EDT) Subject: [Tutor] calculator In-Reply-To: <Pine.LNX.4.33.0108281326170.5290-100000@terbidium.openservices.net> Message-ID: <Pine.LNX.4.33.0108281348160.5290-100000@terbidium.openservices.net> On Tue, 28 Aug 2001, Ignacio Vazquez-Abrams wrote: > dictionary, but also the descriptions to print in the menu. And adding new > functions is simply a matter of adding entries to the dictionary. ^^^^^^^^^ Sigh. I meant to say 'features'. You'll still have to use 'def <name>:' to add new functions ;) -- Ignacio Vazquez-Abrams <ignacio@openservices.net> From ak@silmarill.org Tue Aug 28 18:51:35 2001 From: ak@silmarill.org (Andrei Kulakov) Date: Tue, 28 Aug 2001 13:51:35 -0400 Subject: [Tutor] calculator In-Reply-To: <Pine.LNX.4.33.0108281326170.5290-100000@terbidium.openservices.net> References: <000f01c12f9f$a09af560$1a00a0c0@matt> <Pine.LNX.4.33.0108281326170.5290-100000@terbidium.openservices.net> Message-ID: <20010828135135.A5498@sill.silmarill.org> On Tue, Aug 28, 2001 at 01:43:36PM -0400, Ignacio Vazquez-Abrams wrote: > Something else you can do, in conjunction with all the other really good > suggestions you've received so far, is to code your main menu (and in fact all > of your menus) similar to this: > > --- > def circlearea(): > ... > > def squarearea(): > ... > > def rectanglearea(): > ... > > def squareroot(): > ... > > def addnumbers(): > ... > > menuoptions={'1':circlearea, '2':squarearea, '3':rectanglearea, > '4':squareroot, '5':addnumbers} > > while 1: > while 1: > print "please choose an option" > print > print "1. circle area" > print "2. square area" > print "3. rectangle area" > print "4. square root" > print "5. add numbers" > shape = input("> ") > if not menuoptions.has_key(shape) > print > print "whoops thats not good" > print > else: > break > menuoptions[choice]() Is it just me, or are alphanumeric menus much nicer, i.e.: menu = { 'c': circlearea, 'a': squarearea, 'r': rectanglearea, 'o': squareroot, 'a': addnumbers } And that letter is colorized in the menu? This is very easy to do and much friendlier UI - gtk and qt, take a hike ;P. [snip] -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From ignacio@openservices.net Tue Aug 28 19:07:22 2001 From: ignacio@openservices.net (Ignacio Vazquez-Abrams) Date: Tue, 28 Aug 2001 14:07:22 -0400 (EDT) Subject: [Tutor] calculator In-Reply-To: <20010828135135.A5498@sill.silmarill.org> Message-ID: <Pine.LNX.4.33.0108281404290.5290-100000@terbidium.openservices.net> On Tue, 28 Aug 2001, Andrei Kulakov wrote: > Is it just me, or are alphanumeric menus much nicer, i.e.: > > menu = { > 'c': circlearea, > 'a': squarearea, > 'r': rectanglearea, > 'o': squareroot, > 'a': addnumbers > } > > And that letter is colorized in the menu? This is very easy > to do and much friendlier UI - gtk and qt, take a hike ;P. Oh, I absolutely agree that letters are better; I was just trying to work within the framework that had been created. As for coloured letters... if somebody's still using numbers in their menu, then I doubt that they're ready for curses ;) -- Ignacio Vazquez-Abrams <ignacio@openservices.net> From melvin2001@earthlink.net Tue Aug 28 19:07:01 2001 From: melvin2001@earthlink.net (melvin2001) Date: Tue, 28 Aug 2001 14:07:01 -0400 Subject: [Tutor] (no subject) Message-ID: <001c01c12fec$4b8550a0$4e59b23f@matt> This is a multi-part message in MIME format. ------=_NextPart_000_0019_01C12FCA.B54B6140 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable ahhh i thought dman was the only one that was gonna respond for awile so = i guess i'll just post a follow up like this (even though i already sent = it to dman) i think i figured out the whole function thing check it out = lemme know if im a fruit def circle_area(): print "would you like to input radius or diameter?" print "1. radius" print "2. diameter" question =3D input ("> ") if question =3D=3D 1: print "what is the radius?" radius =3D input("> ") radius =3D 3.14*radius**2 print radius elif question =3D=3D 2: print "what is the diameter?" diameter =3D input ("> ") diameter =3D diameter/2 diameter =3D diameter**2 * 3.14 print diameter options =3D { "1" : circle_area , #"2" : square_area , #"3" : rectangle_area , #"4" : square_root , #"5" : add_numbers , } #Then you would have the following for your "main" loop : print "alright now for some real math\n" while 1: print "please choose an option" print print "1. circle area" print "2. square area" print "3. rectangle area" print "4. square root" print "5. add numbers" # use raw_input() instead of input() -- there are various security # holes and issues with using input() in a production environment # (it is fine for quick-n-dirty testing/prototyping though) shape =3D raw_input("> ") # now get the function that handles this operation and let it do # the real work, be sure to check for errors first if not options.has_key( shape ) : print "Error -- %s is not a valid option" % shape continue # go on with the next iteration of the loop options[ shape ]() i commented out a few of the options because i didn't want to take the = time to define them yet and i'm gonna add a menu option for exit next = :-) and im gonna try that little menu thing thanks to ignacio.....you = guys are great thanks for the help lol i'll be sure to ask you guys lots = of questions=20 ------=_NextPart_000_0019_01C12FCA.B54B6140 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML><HEAD> <META http-equiv=3DContent-Type content=3D"text/html; = charset=3Diso-8859-1"> <META content=3D"MSHTML 5.50.4134.100" name=3DGENERATOR> <STYLE></STYLE> </HEAD> <BODY bgColor=3D#ffffff> <DIV><FONT face=3DArial size=3D2>ahhh i thought dman was the only one = that was gonna=20 respond for awile so i guess i'll just post a follow up like this (even = though i=20 already sent it to dman) i think i figured out the whole function thing = check it=20 out lemme know if im a fruit</FONT></DIV> <DIV><FONT face=3DArial size=3D2></FONT> </DIV> <DIV><FONT face=3DArial size=3D2></FONT> </DIV> <DIV><FONT face=3DArial size=3D2>def = circle_area():<BR>    print=20 "would you like to input radius or diameter?"<BR>    = print "1.=20 radius"<BR>    print "2. diameter"<BR>    = question=20 =3D input ("> ")<BR>    if question =3D=3D=20 1:<BR>        print "what is the=20 radius?"<BR>        radius =3D = input(">=20 ")<BR>        radius =3D=20 3.14*radius**2<BR>        print=20 radius<BR>    elif question =3D=3D=20 2:<BR>        print "what is the=20 diameter?"<BR>        diameter =3D = input (">=20 ")<BR>        diameter =3D=20 diameter/2<BR>        diameter =3D = diameter**2=20 * 3.14<BR>        print = diameter</FONT></DIV> <DIV> </DIV> <DIV><FONT face=3DArial size=3D2>options =3D {<BR>    "1" = : circle_area=20 ,<BR>    #"2" : square_area ,<BR>    #"3" = :=20 rectangle_area ,<BR>    #"4" : square_root=20 ,<BR>    #"5" : add_numbers ,<BR>   =20 }</FONT></DIV> <DIV> </DIV><FONT face=3DArial size=3D2> <DIV><BR>#Then you would have the following for your "main" loop :</DIV> <DIV> </DIV> <DIV>print "alright now for some real math\n"<BR>while = 1:<BR>   =20 print "please choose an option"<BR>   =20 print<BR>    print "1. circle area"<BR>    = print=20 "2. square area"<BR>    print "3. rectangle=20 area"<BR>    print "4. square root"<BR>    = print=20 "5. add numbers"</DIV> <DIV> </DIV> <DIV>    # use raw_input() instead of input() -- there = are=20 various security<BR>    # holes and issues with using = input() in=20 a production environment<BR>    # (it is fine for = quick-n-dirty=20 testing/prototyping though)<BR>    shape =3D = raw_input(">=20 ")</DIV> <DIV> </DIV> <DIV>    # now get the function that handles this = operation and=20 let it do<BR>    # the real work, be sure to check for = errors=20 first<BR>    if not options.has_key( shape )=20 :<BR>        print "Error -- %s is = not a=20 valid option" % shape<BR>        = continue #=20 go on with the next iteration of the loop</DIV> <DIV> </DIV> <DIV>    options[ shape ]()<BR></DIV> <DIV> </DIV> <DIV> </DIV> <DIV> </DIV> <DIV> </DIV> <DIV> </DIV> <DIV>i commented out a few of the options because i didn't want to take = the time=20 to define them yet and i'm gonna add a menu option for exit next :-) and = im=20 gonna try that little menu thing thanks to ignacio.....you guys are = great thanks=20 for the help lol i'll be sure to ask you guys lots of questions=20 </DIV></FONT></BODY></HTML> ------=_NextPart_000_0019_01C12FCA.B54B6140-- From ak@silmarill.org Tue Aug 28 19:16:17 2001 From: ak@silmarill.org (Andrei Kulakov) Date: Tue, 28 Aug 2001 14:16:17 -0400 Subject: [Tutor] calculator In-Reply-To: <Pine.LNX.4.33.0108281404290.5290-100000@terbidium.openservices.net> References: <20010828135135.A5498@sill.silmarill.org> <Pine.LNX.4.33.0108281404290.5290-100000@terbidium.openservices.net> Message-ID: <20010828141617.A5671@sill.silmarill.org> On Tue, Aug 28, 2001 at 02:07:22PM -0400, Ignacio Vazquez-Abrams wrote: > On Tue, 28 Aug 2001, Andrei Kulakov wrote: > > > Is it just me, or are alphanumeric menus much nicer, i.e.: > > > > menu = { > > 'c': circlearea, > > 'a': squarearea, > > 'r': rectanglearea, > > 'o': squareroot, > > 'a': addnumbers > > } > > > > And that letter is colorized in the menu? This is very easy > > to do and much friendlier UI - gtk and qt, take a hike ;P. > > Oh, I absolutely agree that letters are better; I was just trying to work > within the framework that had been created. > > As for coloured letters... if somebody's still using numbers in their menu, > then I doubt that they're ready for curses ;) No need for 'em :-) Here's a lil function I cooked up: (colorize("red", "Test") prints Test in red, colorize(("red", "yellow"),"Test") uses yellow background). enable_color = 1 if sys.environ["TERM"] == "xterm": xterm = 1 def colorize(color, text): """Return colorized text""" col_dict = { "black" : "30m", "red" : "31m", "green" : "32m", "brown" : "33m", "blue" : "34m", "purple" : "35m", "cyan" : "36m", "lgray" : "37m", "gray" : "1;30m", "lred" : "1;31m", "lgreen" : "1;32m", "yellow" : "1;33m", "lblue" : "1;34m", "pink" : "1;35m", "lcyan" : "1;36m", "white" : "1;37m", } bg = "0m" if type(color) == type(""): # In xterm, brown comes out as yellow.. if xterm and color == "yellow": color = "brown" fg = col_dict[color] elif type(color) == type(()): f, b = color[0], color[1] if f == "yellow" and xterm: f = "brown" if b == "yellow": b = "brown" fg = col_dict[f] try: bg = col_dict[b].replace('3', '4', 1) except KeyError: pass if enable_color: return "\033[%s\033[%s%s\033[0m" % (bg, fg, text) else: return text > > -- > Ignacio Vazquez-Abrams <ignacio@openservices.net> > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From dsh8290@rit.edu Tue Aug 28 19:28:54 2001 From: dsh8290@rit.edu (dman) Date: Tue, 28 Aug 2001 14:28:54 -0400 Subject: [Tutor] calculator In-Reply-To: <20010828141617.A5671@sill.silmarill.org>; from sill@optonline.net on Tue, Aug 28, 2001 at 02:16:17PM -0400 References: <20010828135135.A5498@sill.silmarill.org> <Pine.LNX.4.33.0108281404290.5290-100000@terbidium.openservices.net> <20010828141617.A5671@sill.silmarill.org> Message-ID: <20010828142853.C6011@harmony.cs.rit.edu> On Tue, Aug 28, 2001 at 02:16:17PM -0400, Andrei Kulakov wrote: | On Tue, Aug 28, 2001 at 02:07:22PM -0400, Ignacio Vazquez-Abrams wrote: | > As for coloured letters... if somebody's still using numbers in their menu, | > then I doubt that they're ready for curses ;) | | No need for 'em :-) Here's a lil function I cooked up: | ... | return "\033[%s\033[%s%s\033[0m" % (bg, fg, text) Just FYI -- the escape codes don't work in all shells. For example with cygwin the default prompt has escape codes to colorize it. They look great in bash, but ash doesn't understand it and just displays the escapes codes. -D From ignacio@openservices.net Tue Aug 28 20:28:03 2001 From: ignacio@openservices.net (Ignacio Vazquez-Abrams) Date: Tue, 28 Aug 2001 15:28:03 -0400 (EDT) Subject: [Tutor] (no subject) In-Reply-To: <001c01c12fec$4b8550a0$4e59b23f@matt> Message-ID: <Pine.LNX.4.33.0108281523440.5290-100000@terbidium.openservices.net> On Tue, 28 Aug 2001, melvin2001 wrote: > i commented out a few of the options because i didn't want to take the time to define them yet and i'm gonna add a menu option for exit next :-) and im gonna try that little menu thing thanks to ignacio.....you guys are great thanks for the help lol i'll be sure to ask you guys lots of questions Instead of commenting them out, you can define the functions as follows: --- def square_area(): pass --- That way you can do a search for "pass" in your editor and find really quickly what functions need to be fleshed out. Also, if you're going to ask more questions, please send the message as text-only. If it's good enough for the Python interpreter, then it's good enough for you ;) -- Ignacio Vazquez-Abrams <ignacio@openservices.net> From jessefw@loop.com Tue Aug 28 22:11:06 2001 From: jessefw@loop.com (Jesse F. W) Date: Tue, 28 Aug 2001 14:11:06 -0700 Subject: [Tutor] class uncertainty In-Reply-To: <fc.004c4b6b00796104004c4b6b00796104.796134@blakeschool.org> Message-ID: <3B8BA67A.26667.1D25A299@localhost> Dear Chris, Christopher Smith wrote: > I've created a class which keeps track of the uncertainty in a number > and subsequent calculations performed with that number. It works like > this: As has been said before, Neat! :-) Can we see it? Would you give us a URL for it, or post it on the list? I would really like to try it out. Jesse W From chikitychina@home.com Wed Aug 29 02:22:42 2001 From: chikitychina@home.com (The Chinese Chicken) Date: Tue, 28 Aug 2001 21:22:42 -0400 Subject: [Tutor] NT/2000 Administration Message-ID: <3B8C43E2.66BE04F1@home.com> Hey all, This question isn't really a request for help but more for advice. I am trying to learn a scripting language to automate some NT administration tasks across a domain (Installing applications, copying files, registry edits, managing user accounts and such). The ability to compile these scripts into tamper-proof .exe's is very important. I have taken a hard look at a few different languages (Win Batch, VBScript, Perl, and others), and because of the amount of time it will take to learn any one of them, I would like to ask whether anyone uses Python in this reqard and what they think about it. Please help me make an educated decision, Pablo Manzanera From dutch@lilrc.org Wed Aug 29 04:23:52 2001 From: dutch@lilrc.org (Dutch) Date: Tue, 28 Aug 2001 23:23:52 -0400 (EDT) Subject: [Tutor] Functions ! In-Reply-To: <20010828142853.C6011@harmony.cs.rit.edu> Message-ID: <Pine.SOL.3.96.1010828232214.24245B-100000@lilrc1> I have a question about functions. I hope I can ask this clearly (and get a clear answer too!) The last programming I did was in basic on my Commoidore 64 and functions almost seem like what I remember as "subroutines"... Im following a pretty good online tutorial called "Non-Programmers Tutorial For Python " (http://www.honors.montana.edu/~jjc/easytut/easytut/easytut.html). Anyway, Im reading through and typing in the examples. Below is one such example and it works fine... I dont understand the variables "c_temp" or "f_temp" since they are not used anywhere else. 1. I am -guessing- that the part of the program that calls on the function is sending a variable to be processed in the function and it is getting dumped in c_temp or f_temp. If thats the case, they why is it that the original variable is not used, in this case "temp"? 2. I'm guessing here too that many parts of a program with all their different variables can call the funtion so no one absolute vaiable can be used so this "dummy" (c_temp or f_temp) is used and I must therefore be careful not to use the same label (variable) anywhere else in my program. Im trying to follow the program (reading it) and understand what is happening. It just wasnt clear where this 2 new lables came from and how the program "knows" what is to be used there. ...Are my guess at least close? And would addeding "exit" at the end be helpful in anyway? #converts temperature to fahrenheit or celsius def print_options(): print "Options:" print " 'p' print options" print " 'c' convert from celsius" print " 'f' convert from fahrenheit" print " 'q' quit the program" def celsius_to_fahrenheit(c_temp): return 9.0/5.0*c_temp+32 def fahrenheit_to_celsius(f_temp): return (f_temp - 32.0)*5.0/9.0 choice = "p" while choice != "q": if choice == "c": temp = input("Celsius temperature:") print "Fahrenheit:",celsius_to_fahrenheit(temp) elif choice == "f": temp = input("Fahrenheit temperature:") print "Celsius:",fahrenheit_to_celsius(temp) elif choice != "q": print_options() choice = raw_input("option:") -Dutch ______________________________________________________________________ David van Popering Running slackware & Window Maker "It has been established that having a really user friendly interface makes it much too easy for aliens to take over the Enterprise." From ignacio@openservices.net Wed Aug 29 04:39:00 2001 From: ignacio@openservices.net (Ignacio Vazquez-Abrams) Date: Tue, 28 Aug 2001 23:39:00 -0400 (EDT) Subject: [Tutor] Functions ! In-Reply-To: <Pine.SOL.3.96.1010828232214.24245B-100000@lilrc1> Message-ID: <Pine.LNX.4.33.0108282337020.18216-100000@terbidium.openservices.net> On Tue, 28 Aug 2001, Dutch wrote: > 1. > I am -guessing- that the part of the program that calls on the function is > sending a variable to be processed in the function and it is getting > dumped in c_temp or f_temp. If thats the case, they why is it that the > original variable is not used, in this case "temp"? For clarity. 'temp' can still be used, but '[cf]_temp' is clearer. > 2. > I'm guessing here too that many parts of a program with all their > different variables can call the funtion so no one absolute vaiable can be > used so this "dummy" (c_temp or f_temp) is used and I must therefore be > careful not to use the same label (variable) anywhere else in my program. Wrong. The variable only exists within the function. -- Ignacio Vazquez-Abrams <ignacio@openservices.net> From dyoo@hkn.eecs.berkeley.edu Wed Aug 29 05:28:54 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 28 Aug 2001 21:28:54 -0700 (PDT) Subject: [Tutor] Functions ! [argument passing / local scope] In-Reply-To: <Pine.SOL.3.96.1010828232214.24245B-100000@lilrc1> Message-ID: <Pine.LNX.4.21.0108282032590.994-100000@hkn.eecs.berkeley.edu> On Tue, 28 Aug 2001, Dutch wrote: > I have a question about functions. I hope I can ask this clearly (and > get a clear answer too!) We'll try. *grin* However, remember that you can always stop us when we start babbling; this is certainly not a "final answer" situation... [As a warning, some of the below is a simplification, and ignores some details. But why complicate matters? *grin*] > I dont understand the variables "c_temp" or "f_temp" since they are not > used anywhere else. > > 1. > I am -guessing- that the part of the program that calls on the > function is sending a variable to be processed in the function and it > is getting dumped in c_temp or f_temp. If thats the case, they why is > it that the original variable is not used, in this case "temp"? Yes, the "caller" is sending off a single value off to the temperature conversion functions. What's important to realize is that, as far as the conversion function is concerned, this value could have come from anywhere. I'd better clarify what that means: For example, we can just "plug it in" and pass values directly to a function: ### print "Fahrenheit 451 is actually" print fahrenheit_to_celsius(451), "in the celsius scale." ### So we don't need to always pass a variable to a function. What happens is that fahrenheit_to_celsius() will do the calculation, and, isolated within that function, f_temp will equal 451. In short: we're not passing "names" to functions, but their "values". When our program does this: ### print "Celsius:",fahrenheit_to_celsius(temp) ### Python will first grab the value of "temp", and once it has that value, Python will pass that value off to fahrenheit_to_celsius(). Here's another example: ### >>> def square(thing): ... return thing * thing ... >>> some_number = 42 >>> square(some_number * some_number) 3111696 >>> def quadrify(thing): ... return(square(thing) * square(thing)) ... >>> quadrify(some_number) 3111696 ### See if it the above makes any sense; it touches some of the questions you're asking. > 2. > I'm guessing here too that many parts of a program with all their > different variables can call the funtion so no one absolute vaiable > can be used so this "dummy" (c_temp or f_temp) is used and I must > therefore be careful not to use the same label (variable) anywhere > else in my program. Actually, it's ok to use the name "c_temp" or "f_temp" in other places in your program. Let's take a closer look at your program for a sec: ### def celsius_to_fahrenheit(c_temp): return 9.0/5.0*c_temp+32 def fahrenheit_to_celsius(f_temp): return (f_temp - 32.0)*5.0/9.0 ### It turns out that we could have written the two functions above as: ### def celsius_to_fahrenheit(temperature): return 9.0/5.0*temperature+32 def fahrenheit_to_celsius(temperature): return (temperature - 32.0)*5.0/9.0 ### which could be paraphrased in English as "To celsius_to_fahrenheit() some 'temperature' that we're given, here's what we do..." and "To fahrenheit_to_celsius() some 'temperature' that we're given, here's what we do..." In both functions, the name "temperature" is a _placeholder_ for whatever value we give to the functions when we do some calculations. In technical terms, we'd say that "temperature" is "local" to the function. If we have a variable named "temperature" outside these functions, we can still relax because the "temperature" inside is not the same thing as the "temperature" outside. Better give an example: ### >>> temperature = "HOT!" >>> >>> def describe(temperature): ... temperature = temperature*3 ... print "Wow, the temperature is", temperature ... >>> describe(temperature) Wow, the temperature is HOT!HOT!HOT! >>> temperature 'HOT!' ### This "local"ity is usually a good thing because it allows us to draw "boxes" around each function: we can think that each function works in isolation of the others, so a messup in one function stays isolated in that function. To get functions to communicate to the "outside world", we can use the "return" keyword. Looking at one of the functions again: ### def fahrenheit_to_celsius(temperature): return (temperature - 32.0)*5.0/9.0 ### we can see that the only thing coming out --- being "returned" --- from the function is the result of that particular calculation. There are ways of breaking down the doors: we can explicitly say that a variable is "global", but let's avoid that topic for today. *grin* > Im trying to follow the program (reading it) and understand what is > happening. It just wasnt clear where this 2 new lables came from and > how the program "knows" what is to be used there. It is positional: the first thing we pass to the function will be tied to the first name in the argument list. I'm not sure if you've encountered functions that take in more than one thing, so here's an example of such a beast: ### >>> def makeFriends(friend1, friend2): ... return friend1 + " and " + friend2 ... >>> makeFriends("bill", "ted") 'bill and ted' >>> makeFriends("ted", "bill") 'ted and bill' ### We usually try to keep the number of arguments that a function takes in down: most of the functions in Python take in one argument to make it hard to accidently reverse the order. If any of this doesn't make sense, please feel free to holler. *grin* From dsh8290@rit.edu Wed Aug 29 05:44:22 2001 From: dsh8290@rit.edu (dman) Date: Wed, 29 Aug 2001 00:44:22 -0400 Subject: [Tutor] Functions ! In-Reply-To: <Pine.SOL.3.96.1010828232214.24245B-100000@lilrc1>; from dutch@lilrc.org on Tue, Aug 28, 2001 at 11:23:52PM -0400 References: <20010828142853.C6011@harmony.cs.rit.edu> <Pine.SOL.3.96.1010828232214.24245B-100000@lilrc1> Message-ID: <20010829004422.D6563@harmony.cs.rit.edu> On Tue, Aug 28, 2001 at 11:23:52PM -0400, Dutch wrote: | I have a question about functions. I hope I can ask this clearly (and get | a clear answer too!) | | The last programming I did was in basic on my Commoidore 64 and functions | almost seem like what I remember as "subroutines"... They are similar. I never did enough BASIC programming to really call it programming, but from other posts on this list I believe that BASIC subroutines have no local variables or arguments -- everything is global instead. This is significantly different from functions in Python (and C and C++ and Java and Eiffel, etc). Any variable created inside a function (using the '=' operator) exists only inside that function. No other code can see it. It also "magically" goes away when the function returns. Local variables are essential for modularity. The other main difference is arguments, which is what you are asking about below. | Im following a pretty good online tutorial called "Non-Programmers | Tutorial For Python | " (http://www.honors.montana.edu/~jjc/easytut/easytut/easytut.html). | | Anyway, Im reading through and typing in the examples. Below is one such | example and it works fine... | | I dont understand the variables "c_temp" or "f_temp" since they are not | used anywhere else. | | 1. | I am -guessing- that the part of the program that calls on the function is | sending a variable to be processed in the function and it is getting | dumped in c_temp or f_temp. If thats the case, they why is it that the | original variable is not used, in this case "temp"? Basically yes. The caller tells the function which variable to use. However, inside the function you don't know the name of the caller's variable and you don't have access to it anyways if it isn't a global variable. The solution adopted by many Algol-ish languages (python included) is what you see below. When defining the function you list the formal parameters of the function. That is, you put a name of your own choosing in the list of arguments that the function is supposed to take. Then, once inside the function, you know that that name will be bound to the corresponding concrete paramter that is specified by the caller. You use the name you specified in the formal parameter list to reference the variable. The interpreter (or compiler) will make the association for you. | 2. | I'm guessing here too that many parts of a program with all their | different variables can call the funtion so no one absolute vaiable can be | used so this "dummy" (c_temp or f_temp) is used and I must therefore be | careful not to use the same label (variable) anywhere else in my program. This is an issue if you only have global variables, and it is a major problem in any large project. There is no name clash issues here because those names only exist inside the scope of the function. They have no effect on other functions. | Im trying to follow the program (reading it) and understand what is | happening. It just wasnt clear where this 2 new lables came from and how | the program "knows" what is to be used there. When a function is called, the interpreter binds all the names in the function's formal parameter list to the objects specified by the caller, but the name gets bound in the function's local scope. Thus in the following : def func( an_arg ) : # 1 print an_arg # 2 def main() : # 3 foo = "Hello World. I'm learning functions!" # 4 func( foo ) # 5 main() Lines 1 and 2 define the function. Line 1 specifies the name of the function ('func') and that it will take exactly 1 argument. It also says that, inside the function, that argument will have the name "an_arg". On line 5 I call the function. In calling the function I must specify which object should be used as the argument in this invocation. I specified the object whose name in the current scope is "foo". The interpreter then creates the name "an_arg" in "func"'s local scope and binds it to the same object that "foo" referred to. In this example, "foo" is a local variable inside the "main" function so it is not directly accessible by func. It can only be accessed through its argument. | ...Are my guess at least close? And would addeding "exit" at the end be | helpful in anyway? You could call exit at the end if you wanted to explicitly terminate the program's operation. In this example it makes little difference. If you were writing a GUI application then you would certainly need to call exit when the "exit" button or menu item was selected. The other main use in calling exit is when an error has occurred and you want to report it back to whoever ran the program. This is mostly useful in shell scripts so that the script knows whether your program succeeded or not. In Python the exit function is in the sys module so you would first need to import it. Example : import sys sys.exit() # no argument, defaults to EXIT_SUCCESS (which is a C # constant that is equal to zero) sys.exit( 1 ) # a single integer argument, the meaning is # application-dependent, normally zero=>success and # non-zero=>failure. HTH, -D From dyoo@hkn.eecs.berkeley.edu Wed Aug 29 05:53:07 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 28 Aug 2001 21:53:07 -0700 (PDT) Subject: [Tutor] (no subject) In-Reply-To: <001c01c12fec$4b8550a0$4e59b23f@matt> Message-ID: <Pine.LNX.4.21.0108282143340.1493-100000@hkn.eecs.berkeley.edu> On Tue, 28 Aug 2001, melvin2001 wrote: > ahhh i thought dman was the only one that was gonna respond for awile > so i guess i'll just post a follow up like this (even though i already [some code cut] In your circle_area() function: ### def circle_area(): print "would you like to input radius or diameter?" print "1. radius" print "2. diameter" question = input ("> ") if question == 1: print "what is the radius?" radius = input("> ") radius = 3.14*radius**2 print radius elif question == 2: print "what is the diameter?" diameter = input ("> ") diameter = diameter/2 diameter = diameter**2 * 3.14 print diameter ### in the second case, since you're dividing the diameter by 2, it's perfectly ok to call that result the radius. ### # ... elif question == 2: print "what is the diameter?" diameter = input ("> ") radius = diameter/2 area = radius**2 * 3.14 print area ### Likewise, we can call the thing that holds the area the variable name: "area". You don't need to reuse "diameter" as a variable if it no longer represents the diameter. Electrons are still in abundant supply, despite the power crisis here. *grin* In short: it's perfectly ok to be a little indulgent with variable names if we're in a function. > i commented out a few of the options because i didn't want to take the > time to define them yet and i'm gonna add a menu option for exit next > :-) and im gonna try that little menu thing thanks to ignacio.....you > guys are great thanks for the help lol i'll be sure to ask you guys > lots of questions Your code looks good. Keep the questions coming! From ignacio@openservices.net Wed Aug 29 06:08:12 2001 From: ignacio@openservices.net (Ignacio Vazquez-Abrams) Date: Wed, 29 Aug 2001 01:08:12 -0400 (EDT) Subject: [OT] BASIC Factoid (was Re: [Tutor] Functions !) In-Reply-To: <20010829004422.D6563@harmony.cs.rit.edu> Message-ID: <Pine.LNX.4.33.0108290104560.18216-100000@terbidium.openservices.net> On Wed, 29 Aug 2001, dman wrote: > On Tue, Aug 28, 2001 at 11:23:52PM -0400, Dutch wrote: > | I have a question about functions. I hope I can ask this clearly (and get > | a clear answer too!) > | > | The last programming I did was in basic on my Commoidore 64 and functions > | almost seem like what I remember as "subroutines"... > > They are similar. I never did enough BASIC programming to really call There's actually a reason for that. All versions of BASIC on early PCs were written by, licensed from, and "maintained" by Microsoft. And you thought BASIC was public domain :P It still doesn't count as a Microsoft innovation, however, because they ripped it off someone else :) -- Ignacio Vazquez-Abrams <ignacio@openservices.net> From sheila@thinkspot.net Wed Aug 29 06:32:33 2001 From: sheila@thinkspot.net (Sheila King) Date: Tue, 28 Aug 2001 22:32:33 -0700 Subject: [Tutor] fcntl: Blocking or non-blocking Message-ID: <D71BEDD64CF@kserver.org> OK, I've been pestering the python-list/comp.lang.python with my questions about file locking, and now that I'm down to some more elementary concepts (that illustrate my fundamental cluelessness with *nix systems), I've decided to give them a break and pester you kind-hearted and patient folks. ;) Here's the deal: I'm writing a module that will perform file locking. I want it to work on both Windows and Unix. This requires platform specific stuff, so I write two separate modules, and then wrap them in one cross-platform module with a common interface. OK, I've got that all down, now, I think. But one question remains: On Unix I have a choice of using blocking or non-blocking calls to fcntl to get the file lock. Blocking obviously saves me the effort of having to code retries (which I have to do for the Windows version, anyhow). But I have a concern: what if I try for a blocking call, and the process never acquires the lock? (Maybe I should specify, that these are for CGI scripts, anyhow. So, I guess eventually the process will time out and die.) Should I just code the blocking calls? Or should I code non-blocking and have retries with sleep in there? I can't see any easy way in Python to use the fcntl.lockf command and get a blocking call to time out. Anyone interested in the 50+ messages on this topic in comp.lang.python, can look at the two threads that start with these messages: http://groups.google.com/groups?q=hl=en&selm=djsfotomogdeba70gp1cuogjbt5ii3chrb%404ax.com http://groups.google.com/groups?hl=en&selm=bo2ootg61vmposfvsg8gvrks6eqiuss940%404ax.com -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From ignacio@openservices.net Wed Aug 29 06:50:18 2001 From: ignacio@openservices.net (Ignacio Vazquez-Abrams) Date: Wed, 29 Aug 2001 01:50:18 -0400 (EDT) Subject: [Tutor] fcntl: Blocking or non-blocking In-Reply-To: <D71BEDD64CF@kserver.org> Message-ID: <Pine.LNX.4.33.0108290144380.18216-100000@terbidium.openservices.net> On Tue, 28 Aug 2001, Sheila King wrote: > OK, I've been pestering the python-list/comp.lang.python with my > questions about file locking, and now that I'm down to some more > elementary concepts (that illustrate my fundamental cluelessness with > *nix systems), I've decided to give them a break and pester you > kind-hearted and patient folks. ;) > > Here's the deal: > I'm writing a module that will perform file locking. I want it to work > on both Windows and Unix. This requires platform specific stuff, so I > write two separate modules, and then wrap them in one cross-platform > module with a common interface. > > OK, I've got that all down, now, I think. > But one question remains: > > On Unix I have a choice of using blocking or non-blocking calls to fcntl > to get the file lock. > > Blocking obviously saves me the effort of having to code retries (which > I have to do for the Windows version, anyhow). > > But I have a concern: what if I try for a blocking call, and the process > never acquires the lock? (Maybe I should specify, that these are for CGI > scripts, anyhow. So, I guess eventually the process will time out and > die.) Should I just code the blocking calls? Or should I code > non-blocking and have retries with sleep in there? I can't see any easy > way in Python to use the fcntl.lockf command and get a blocking call to > time out. Blocking in general is Evil unless you know exactly what you're doing. In fact, it is SO Evil that Unix developed the select() function (replicated in the select module) specifically for getting around blocking calls. So I would say that you should raise an exception or return None instead of ever blocking. > Anyone interested in the 50+ messages on this topic in comp.lang.python, > can look at the two threads that start with these messages: > > http://groups.google.com/groups?q=hl=en&selm=djsfotomogdeba70gp1cuogjbt5ii3chrb%404ax.com > > http://groups.google.com/groups?hl=en&selm=bo2ootg61vmposfvsg8gvrks6eqiuss940%404ax.com Oh don't worry, it'll keep going strong there too ;) > -- > Sheila King > http://www.thinkspot.net/sheila/ > http://www.k12groups.org/ -- Ignacio Vazquez-Abrams <ignacio@openservices.net> From scarblac@pino.selwerd.nl Wed Aug 29 07:04:12 2001 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Wed, 29 Aug 2001 08:04:12 +0200 Subject: [Tutor] Functions ! In-Reply-To: <Pine.SOL.3.96.1010828232214.24245B-100000@lilrc1>; from dutch@lilrc.org on Tue, Aug 28, 2001 at 11:23:52PM -0400 References: <20010828142853.C6011@harmony.cs.rit.edu> <Pine.SOL.3.96.1010828232214.24245B-100000@lilrc1> Message-ID: <20010829080412.A14829@pino.selwerd.nl> On 0, Dutch <dutch@lilrc.org> wrote: > I have a question about functions. I hope I can ask this clearly (and get > a clear answer too!) > The last programming I did was in basic on my Commoidore 64 and functions > almost seem like what I remember as "subroutines"... They're similar, but better. You couldn't give parameters to subroutines. > Anyway, Im reading through and typing in the examples. Below is one such > example and it works fine... > > I dont understand the variables "c_temp" or "f_temp" since they are not > used anywhere else. That is the point. You can call these functions with one argument, like celsius_to_fahrenheit(24), and then c_temp will have the value 24 *inside the function*. It's used inside the function, then not needed again. It's invisible outside. > 1. > I am -guessing- that the part of the program that calls on the function is > sending a variable to be processed in the function and it is getting > dumped in c_temp or f_temp. If thats the case, they why is it that the > original variable is not used, in this case "temp"? It would have worked, until you changed the program. If you turn the code that calls it into a function as well, then its "temp" is invisible to the outside (and celsius_to_fahrenheit is outside). And worse, what if you want to call the function from many different places, all using different names for a variable like "temp"? So you pass in the number as an argument (celsius_to_fahrenheit(temp)), and the little function doesn't have to know anything about what is calling it. That is a good thing. You want to make bits of code that don't care about the exact way the other bits of code work. > 2. > I'm guessing here too that many parts of a program with all their > different variables can call the funtion so no one absolute vaiable can be > used so this "dummy" (c_temp or f_temp) is used and I must therefore be > careful not to use the same label (variable) anywhere else in my program. You can use it at other places just fine. It's only used inside this function, and is totally invisible everywhere else. You can have many functions using the same local variable names, Python won't get confused. > Im trying to follow the program (reading it) and understand what is > happening. It just wasnt clear where this 2 new lables came from and how > the program "knows" what is to be used there. > def celsius_to_fahrenheit(c_temp): > return 9.0/5.0*c_temp+32 It "knows" what to use because in the first line, you give a name to the variable. "def celsius_to_fahrenheit(c_temp)" means "define a function, to be named celsius_to_fahrenheit, that takes one argument, and call that argument c_temp inside this function". > ...Are my guess at least close? And would addeding "exit" at the end be > helpful in anyway? It exits at the end anyway. -- Remco Gerlich From sheila@thinkspot.net Wed Aug 29 07:09:26 2001 From: sheila@thinkspot.net (Sheila King) Date: Tue, 28 Aug 2001 23:09:26 -0700 Subject: [Tutor] fcntl: Blocking or non-blocking In-Reply-To: <Pine.LNX.4.33.0108290144380.18216-100000@terbidium.openservices.net> References: <D71BEDD64CF@kserver.org> <Pine.LNX.4.33.0108290144380.18216-100000@terbidium.openservices.net> Message-ID: <D9350DD51DD@kserver.org> On Wed, 29 Aug 2001 01:50:18 -0400 (EDT), Ignacio Vazquez-Abrams <ignacio@openservices.net> wrote about Re: [Tutor] fcntl: Blocking or non-blocking: :On Tue, 28 Aug 2001, Sheila King wrote: :> But I have a concern: what if I try for a blocking call, and the process :> never acquires the lock? (Maybe I should specify, that these are for CGI :> scripts, anyhow. So, I guess eventually the process will time out and :> die.) Should I just code the blocking calls? Or should I code :> non-blocking and have retries with sleep in there? I can't see any easy :> way in Python to use the fcntl.lockf command and get a blocking call to :> time out. : :Blocking in general is Evil unless you know exactly what you're doing. Well, that leaves me out. I guess that answers that question. :In fact, it is SO Evil that Unix developed the select() function (replicated in :the select module) specifically for getting around blocking calls. So I would :say that you should raise an exception or return None instead of ever :blocking. :> Anyone interested in the 50+ messages on this topic in comp.lang.python, :> can look at the two threads that start with these messages: :> :> http://groups.google.com/groups?q=hl=en&selm=djsfotomogdeba70gp1cuogjbt5ii3chrb%404ax.com :> :> http://groups.google.com/groups?hl=en&selm=bo2ootg61vmposfvsg8gvrks6eqiuss940%404ax.com : :Oh don't worry, it'll keep going strong there too ;) LOL. Great. Glad to know I haven't tired you out, yet. ;) -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From r.b.rigilink@chello.nl Wed Aug 29 07:33:53 2001 From: r.b.rigilink@chello.nl (Roeland Rengelink) Date: Wed, 29 Aug 2001 08:33:53 +0200 Subject: [Tutor] fcntl: Blocking or non-blocking References: <D71BEDD64CF@kserver.org> Message-ID: <3B8C8CD1.2440C2C6@chello.nl> Sheila King wrote: > [snip] > > On Unix I have a choice of using blocking or non-blocking calls to fcntl > to get the file lock. > > Blocking obviously saves me the effort of having to code retries (which > I have to do for the Windows version, anyhow). > > But I have a concern: what if I try for a blocking call, and the process > never acquires the lock? (Maybe I should specify, that these are for CGI > scripts, anyhow. So, I guess eventually the process will time out and > die.) Should I just code the blocking calls? Or should I code > non-blocking and have retries with sleep in there? I can't see any easy > way in Python to use the fcntl.lockf command and get a blocking call to > time out. > It seems to me you answered your own question. If you're worried about blocking, you better deal with the possibility. Of course you are the only one who can make the judgement whether the worry is realistic. I gather you're trying to build a general solution. That's probably good enough reason to choose non blocking calls, with a mechanism to do retries until some specified timeout occurs. Good luck, Roeland -- r.b.rigilink@chello.nl "Half of what I say is nonsense. Unfortunately I don't know which half" From ignacio@openservices.net Wed Aug 29 07:37:01 2001 From: ignacio@openservices.net (Ignacio Vazquez-Abrams) Date: Wed, 29 Aug 2001 02:37:01 -0400 (EDT) Subject: [Tutor] fcntl: Blocking or non-blocking In-Reply-To: <D9350DD51DD@kserver.org> Message-ID: <Pine.LNX.4.33.0108290227380.18216-100000@terbidium.openservices.net> On Tue, 28 Aug 2001, Sheila King wrote: > :Blocking in general is Evil unless you know exactly what you're doing. > > Well, that leaves me out. I guess that answers that question. It's not so much for you as it is for the users of your module. In fact, = you might want to give them the option between blocking and non-blocking so t= hat the self-foot-shooting transfers from you to them ;) Also,=A0I recommend not doing non-block retries at a level that is invisi= ble to casual users of your code. There is no point in using non-blocking code i= f it appears as though the code blocks _anyway_. Certainly you can provide sam= ple code on how to do retries in _their_ code properly, but don't let people = think your code is less functional than it actually is. Less-intelligent people might appreciate it, but it will just frustrate the hell out of anyone wh= o can see it for what it is. Besides, if you give them a choice, the less-intelligent people will use = the blocking calls anyways, so there's no point in doing extra work for peopl= e on POSIX-compliant systems when there is a code-free alternative available. --=20 Ignacio Vazquez-Abrams <ignacio@openservices.net> From Charlie@begeistert.org Wed Aug 29 08:45:01 2001 From: Charlie@begeistert.org (Charlie Clark) Date: Wed, 29 Aug 2001 09:45:01 +0200 Subject: [Tutor] Re: Help converting strings to floats In-Reply-To: <E15blIa-0002Yr-00@mail.python.org> Message-ID: <999071101_PM_BeOS.Charlie@begeistert.org> >> You Europeans just can't do anything right, can you <wink>? OT: The English still haven't adpated successfully to the metric system 20 years after switching... long term I would expect the "European" system to dominate... >> -D > >Actually, there is such a converter; it's in the locale module. Just set the >locale to something appropriate using locale.setlocale(), then use >locale.atof() to convert it. I thought there might be. Bummer that it doesn't work on the BeOS version which is what I am using for development but thanx anyway. Charlie From ignacio@openservices.net Wed Aug 29 09:06:22 2001 From: ignacio@openservices.net (Ignacio Vazquez-Abrams) Date: Wed, 29 Aug 2001 04:06:22 -0400 (EDT) Subject: [Tutor] Re: Help converting strings to floats In-Reply-To: <999071101_PM_BeOS.Charlie@begeistert.org> Message-ID: <Pine.LNX.4.33.0108290404470.18216-100000@terbidium.openservices.net> On Wed, 29 Aug 2001, Charlie Clark wrote: > >Actually, there is such a converter; it's in the locale module. Just > set the > >locale to something appropriate using locale.setlocale(), then use > >locale.atof() to convert it. > I thought there might be. Bummer that it doesn't work on the BeOS > version which is what I am using for development but thanx anyway. > > Charlie Gah! THAT bites. What's wrong with it? -- Ignacio Vazquez-Abrams <ignacio@openservices.net> From alan.gauld@bt.com Wed Aug 29 11:56:25 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 29 Aug 2001 11:56:25 +0100 Subject: [Tutor] calculator Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BEEC@mbtlipnt02.btlabs.bt.co.uk> > suggestions you've received so far, is to code your main menu > (and in fact all of your menus) similar to this: And I'll add some more menu maintenance code... > menuoptions={'1':circlearea, '2':squarearea, '3':rectanglearea, > '4':squareroot, '5':addnumbers} def getMenuItem(): shape = 0 while shape not in '12345': # validate the choice print "please choose an option" print print "1. circle area" # or use loop/dictionary trick here print "2. square area" print "3. rectangle area" print "4. square root" print "5. add numbers" shape = raw_input("> ") # safer than input() return shape choice = getMenuItem() menuoptions[choice]() If you combine that with the trick of printing out the menu choices from the dictionary and pass the dictionary into the getMenuItem function then you have a reusable menu function... However ISTR that Python already provides stuff for doing all of this in the cmd module... :-) Alan g. From ignacio@openservices.net Wed Aug 29 12:07:25 2001 From: ignacio@openservices.net (Ignacio Vazquez-Abrams) Date: Wed, 29 Aug 2001 07:07:25 -0400 (EDT) Subject: [Tutor] calculator In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66BEEC@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <Pine.LNX.4.33.0108290701480.18216-100000@terbidium.openservices.net> On Wed, 29 Aug 2001 alan.gauld@bt.com wrote: > > suggestions you've received so far, is to code your main menu > > (and in fact all of your menus) similar to this: > > And I'll add some more menu maintenance code... > > > menuoptions={'1':circlearea, '2':squarearea, '3':rectanglearea, > > '4':squareroot, '5':addnumbers} > > def getMenuItem(): > shape = 0 > while shape not in '12345': # validate the choice Mmm. No, I don't like. Use 'not menuoptions.has_key(shape)' instead. Using in will allow silly things like '12' and '234' through. While you're at it, initialize shape with None instead. It just looks more professional ;) > print "please choose an option" > print > print "1. circle area" # or use loop/dictionary trick here > print "2. square area" > print "3. rectangle area" > print "4. square root" > print "5. add numbers" > shape = raw_input("> ") # safer than input() > return shape > > choice = getMenuItem() > menuoptions[choice]() > > If you combine that with the trick of printing out the > menu choices from the dictionary and pass the dictionary > into the getMenuItem function then you have a reusable > menu function... > > However ISTR that Python already provides stuff for doing > all of this in the cmd module... :-) Bah! There's nothing wrong with first principles ;) > Alan g. -- Ignacio Vazquez-Abrams <ignacio@openservices.net> From alan.gauld@bt.com Wed Aug 29 12:07:51 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 29 Aug 2001 12:07:51 +0100 Subject: [Tutor] NT/2000 Administration Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BEED@mbtlipnt02.btlabs.bt.co.uk> > trying to learn a scripting language to automate some NT > tasks across a domain (Installing applications, copying > files, registry edits, managing user accounts and such). I assume you've looked at WSH which is Microsofts solution for this and comes 'out of the box' with NT etc? > The ability to compile these > scripts into tamper-proof .exe's is very important. NT includes an encrypted script facility - not an exe but the WSH interpreter can execute encrypted scripts... > VBScript, Perl, and others), WSH can work with VBScrip and JScript out of the box and Perl and Python can be added. > take to learn any one of them, I would like to ask whether > anyone uses Python in this reqard and what they think about it. Lots of people do although I suspect most without using the exe option. Do you really need that? py2exe will do it but its not trivial and the vast majority of sys admins work without encrypting scripts - just remove the write privileges on the .py file!(*) If you do go the Python route then you really should buy a copy of Mark Hammond's book on using Python on Win32 - published by O'Reilly. Alan G (*) another way is to write the functionality in a module then the main program becomes: import myprog if __name__ == "__main__" : myprog.run() That way you only distribute the two lines of source shown plus the precompiled myprog.pyc file. The latter is easily decompiled by an experienced user but at least its harder to tamper with. From alan.gauld@bt.com Wed Aug 29 12:17:14 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 29 Aug 2001 12:17:14 +0100 Subject: [Tutor] Functions ! Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BEEE@mbtlipnt02.btlabs.bt.co.uk> > The last programming I did was in basic on my Commodore 64 > and functions almost seem like what I remember as "subroutines"... Absolutely correct. Except they return values wheras subroutines stored the results in global variables. > Im following a pretty good online tutorial called "Non-Programmers > Tutorial For Python > " (http://www.honors.montana.edu/~jjc/easytut/easytut/easytut.html). > > Anyway, Im reading through and typing in the examples. Below > is one such example and it works fine... Josh's tutor is fine, It might be worth comparing similar topics in Jeff Elkners "How to think..." or my "Learn to Program..." tutors too for clarification when in doubt.. In particular mine uses QBASIC examples in addition to Python so these should be slightly more familiar looking. > I dont understand the variables "c_temp" or "f_temp" since > they are not used anywhere else. You are correct, they are like temporary variables that exist during the life of the function call. See http://www.crosswinds.net/~agauld/tutfunc.htm For a more detailed explanation. > I'm guessing here too that many parts of a program with all their > different variables can call the funtion so no one absolute Thats right. but > careful not to use the same label (variable) anywhere else in > my program. this isn't. You can use the same names because the 'parameter' names are only seen insoide the function. For a description of naming issuers see: http://www.crosswinds.net/~agauld/tutnames.htm > the program "knows" what is to be used there. When you call the function you pass in values(called 'arguments') which are assigned to the parameters for the duration of the call. Take a look at the two urls above and see if it makes sense. Alan G. From ignacio@openservices.net Wed Aug 29 12:24:00 2001 From: ignacio@openservices.net (Ignacio Vazquez-Abrams) Date: Wed, 29 Aug 2001 07:24:00 -0400 (EDT) Subject: [Tutor] NT/2000 Administration In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66BEED@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <Pine.LNX.4.33.0108290717520.18216-100000@terbidium.openservices.net> On Wed, 29 Aug 2001 alan.gauld@bt.com wrote: > > The ability to compile these > > scripts into tamper-proof .exe's is very important. > > NT includes an encrypted script facility - not an exe but > the WSH interpreter can execute encrypted scripts... It depends on what "tamper-proof" means. If it means "can not be modified or overwritten" then it's simply a matter of putting it on an NTFS volume and only giving it read and execute access. If it means "the operation can not be determined" then the only way to tamper-proof it is to keep it on a floppy. Even .exe's can be decompiled with not that much effort. From there it's just a few days' work for a talented programmer to figure out what's going on. If you can live with an intermediate between generating a full-fledged .exe and a plain-text .py script, you could always compile it to a .pyc or .pyo file, both of which are executable by passing the filename as an argument to python*.exe. -- Ignacio Vazquez-Abrams <ignacio@openservices.net> From alan.gauld@bt.com Wed Aug 29 12:23:28 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 29 Aug 2001 12:23:28 +0100 Subject: [Tutor] Functions ! Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BEEF@mbtlipnt02.btlabs.bt.co.uk> > They are similar. I never did enough BASIC programming to really call > it programming, but from other posts on this list I believe that BASIC > subroutines have no local variables or arguments -- everything is > global instead. True of old BASICs, certainly of Commodore C64 vintage! Modern BASICs (c1985 on) allow both parameter passing and local variables. Minor clarification of no direct relevance :-) Alan g From alan.gauld@bt.com Wed Aug 29 12:30:20 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 29 Aug 2001 12:30:20 +0100 Subject: [OT] BASIC Factoid (was Re: [Tutor] Functions !) Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BEF0@mbtlipnt02.btlabs.bt.co.uk> > > They are similar. I never did enough BASIC programming to > > There's actually a reason for that. All versions of BASIC on > early PCs were written by, licensed from, and "maintained" > by Microsoft. And you thought BASIC was public domain :P Gosh, I can't believe I'm aplogising for either MS or BASIC! However in the pre IBM PC days BASICs were split about 50/50 between MS BASIC - A triuly dire but very small ROM version(4K?) and various proprietary ones. Commodore used Comodore BASIC which was all their own. Similarly the Sinclaiir(aka Timex) ZX81 had its own version. THE Texas Instruments PC of the time (TI/99?) had a very sophisticated BASIC(16K/32K?) Most of the Japanese home computers of the '80s used the oldest MS version (mandatory line numbers and only single character variable namess etc!). ISTR BASIC itself was invented by Gary Kildall and AN.Other? Mr Kildall of course went on to give us CP/M and GEM :-) Ah nostalgia... Alan g From ignacio@openservices.net Wed Aug 29 12:40:17 2001 From: ignacio@openservices.net (Ignacio Vazquez-Abrams) Date: Wed, 29 Aug 2001 07:40:17 -0400 (EDT) Subject: [OT] BASIC Factoid (was Re: [Tutor] Functions !) In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66BEF0@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <Pine.LNX.4.33.0108290738290.18216-100000@terbidium.openservices.net> On Wed, 29 Aug 2001 alan.gauld@bt.com wrote: > ISTR BASIC itself was invented by Gary Kildall and AN.Other? > Mr Kildall of course went on to give us CP/M and GEM :-) Not quite, although the last name of both creators also starts with a 'K' :) http://www.phys.uu.nl/~bergmann/history.html -- Ignacio Vazquez-Abrams <ignacio@openservices.net> From scarblac@pino.selwerd.nl Wed Aug 29 12:47:53 2001 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Wed, 29 Aug 2001 13:47:53 +0200 Subject: [OT] BASIC Factoid (was Re: [Tutor] Functions !) In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66BEF0@mbtlipnt02.btlabs.bt.co.uk>; from alan.gauld@bt.com on Wed, Aug 29, 2001 at 12:30:20PM +0100 References: <5104D4DBC598D211B5FE0000F8FE7EB20E66BEF0@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <20010829134753.A15360@pino.selwerd.nl> On 0, alan.gauld@bt.com wrote: > > > They are similar. I never did enough BASIC programming to > > > > There's actually a reason for that. All versions of BASIC on > > early PCs were written by, licensed from, and "maintained" > > by Microsoft. And you thought BASIC was public domain :P > > Gosh, I can't believe I'm aplogising for either MS or BASIC! > > However in the pre IBM PC days BASICs were split about 50/50 > between MS BASIC - A triuly dire but very small ROM version(4K?) > and various proprietary ones. Commodore used Comodore BASIC > which was all their own. I'm not sure. The Commodore 128's startup screen looks like this: COMMODORE BASIC V7.0 122365 BYTES FREE (C)1985 COMMODORE ELECTRONICS, LTD. (C)1977 MICROSOFT CORP. ALL RIGHTS RESERVED > Similarly the Sinclaiir(aka Timex) > ZX81 had its own version. THE Texas Instruments PC of the > time (TI/99?) had a very sophisticated BASIC(16K/32K?) > Most of the Japanese home computers of the '80s used > the oldest MS version (mandatory line numbers and only > single character variable namess etc!). Many of them were MSX computers, which was neat because games were compatible between different brands (if I recall correctly). MSX BASIC was Microsoft's. Sinclair's may have been their own. Of course, I was a kid back then, so I can't really remember, have to use web searches :) BASIC was meant as an easy language for beginners, like Python is now. I can't really imagine why they believe it would be good for beginners. (see! referred to python!) -- Remco Gerlich From ak@silmarill.org Wed Aug 29 13:12:05 2001 From: ak@silmarill.org (Andrei Kulakov) Date: Wed, 29 Aug 2001 08:12:05 -0400 Subject: [Tutor] Functions ! In-Reply-To: <Pine.SOL.3.96.1010828232214.24245B-100000@lilrc1> References: <20010828142853.C6011@harmony.cs.rit.edu> <Pine.SOL.3.96.1010828232214.24245B-100000@lilrc1> Message-ID: <20010829081204.A10242@sill.silmarill.org> On Tue, Aug 28, 2001 at 11:23:52PM -0400, Dutch wrote: > I have a question about functions. I hope I can ask this clearly (and get > a clear answer too!) > The last programming I did was in basic on my Commoidore 64 and functions > almost seem like what I remember as "subroutines"... > > Im following a pretty good online tutorial called "Non-Programmers > Tutorial For Python > " (http://www.honors.montana.edu/~jjc/easytut/easytut/easytut.html). > > Anyway, Im reading through and typing in the examples. Below is one such > example and it works fine... > > I dont understand the variables "c_temp" or "f_temp" since they are not > used anywhere else. > > 1. > I am -guessing- that the part of the program that calls on the function is > sending a variable to be processed in the function and it is getting > dumped in c_temp or f_temp. If thats the case, they why is it that the > original variable is not used, in this case "temp"? > > 2. > I'm guessing here too that many parts of a program with all their > different variables can call the funtion so no one absolute vaiable can be > used so this "dummy" (c_temp or f_temp) is used and I must therefore be > careful not to use the same label (variable) anywhere else in my program. > > Im trying to follow the program (reading it) and understand what is > happening. It just wasnt clear where this 2 new lables came from and how > the program "knows" what is to be used there. > ...Are my guess at least close? And would addeding "exit" at the end be > helpful in anyway? > > #converts temperature to fahrenheit or celsius > > def print_options(): > print "Options:" > print " 'p' print options" > print " 'c' convert from celsius" > print " 'f' convert from fahrenheit" > print " 'q' quit the program" > > def celsius_to_fahrenheit(c_temp): > return 9.0/5.0*c_temp+32 > > def fahrenheit_to_celsius(f_temp): > return (f_temp - 32.0)*5.0/9.0 > > choice = "p" > while choice != "q": > if choice == "c": > temp = input("Celsius temperature:") Here, you *could* use c_temp instead, like this: c_temp = input("Celsius temperature:") I guess the tutorial uses a different name so as not to give a wrong idea that the name has to be the same. Variable values get sort of "transferred" between a caller and a function itself. def func(var1, blah, temp_var, dracula): [...] func(3.14, some_var, another, Variable14) And inside func(), var1 is 3.14, blah has the value of some_var, temp_var has the value of another, and finally dracula has the value of Variable14. I'd say this is a failure of your tutorial, this is a very important mechanism and it should have been explained in detail. In the example they give, it's not necessary to have different names for caller and callee, but they have anyway and don't explain why they're different. - Andrei [snip] -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From wheelege@tsn.cc Wed Aug 29 13:20:49 2001 From: wheelege@tsn.cc (Glen Wheeler) Date: Wed, 29 Aug 2001 22:20:49 +1000 Subject: [OT] BASIC Factoid (was Re: [Tutor] Functions !) References: <5104D4DBC598D211B5FE0000F8FE7EB20E66BEF0@mbtlipnt02.btlabs.bt.co.uk> <20010829134753.A15360@pino.selwerd.nl> Message-ID: <019601c13085$0d35d560$0ea616ca@ACE> > On 0, alan.gauld@bt.com wrote: > > > > They are similar. I never did enough BASIC programming to > > > > > > There's actually a reason for that. All versions of BASIC on > > > early PCs were written by, licensed from, and "maintained" > > > by Microsoft. And you thought BASIC was public domain :P > > > > Gosh, I can't believe I'm aplogising for either MS or BASIC! > > > > However in the pre IBM PC days BASICs were split about 50/50 > > between MS BASIC - A triuly dire but very small ROM version(4K?) > > and various proprietary ones. Commodore used Comodore BASIC > > which was all their own. > > I'm not sure. The Commodore 128's startup screen looks like this: > > COMMODORE BASIC V7.0 122365 BYTES FREE > (C)1985 COMMODORE ELECTRONICS, LTD. > (C)1977 MICROSOFT CORP. > ALL RIGHTS RESERVED > But what about the C64? I don't have that great a memory but I don't recall a microsoft tag on it's BASIC. Of course I am probably wrong :) > > Similarly the Sinclaiir(aka Timex) > > ZX81 had its own version. THE Texas Instruments PC of the > > time (TI/99?) had a very sophisticated BASIC(16K/32K?) > > Most of the Japanese home computers of the '80s used > > the oldest MS version (mandatory line numbers and only > > single character variable namess etc!). > > Many of them were MSX computers, which was neat because games were > compatible between different brands (if I recall correctly). MSX BASIC was > Microsoft's. > > Sinclair's may have been their own. > > Of course, I was a kid back then, so I can't really remember, have to use > web searches :) > > BASIC was meant as an easy language for beginners, like Python is now. I > can't really imagine why they believe it would be good for beginners. > (see! referred to python!) > Ha ha, yes yes the good old days...man you have me winding back the clock. I was but a little 'un all the way back then too. I still remember being about 10 years old pumping in a hexadecimal Q-Bert game from a C64 mag :) Damn, wish I still had that thing. From dutch@lilrc.org Wed Aug 29 14:39:56 2001 From: dutch@lilrc.org (Dutch) Date: Wed, 29 Aug 2001 09:39:56 -0400 (EDT) Subject: [Tutor] RE: THANKS (Functions !) In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66BEEE@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <Pine.SOL.3.96.1010829092754.25348A-100000@lilrc1> I just wnated to thank everyone for their help with my functions question (I will has it all out today). I have never had as helpful support from any other source. Having messed with C, Perl, and Bash scripting (and never really staying with it past page ~50), I am having fun with Python. C seemed nice with its power & small number of commands, Perl seemed popular but was confusing in that there were far too many ways of doing things, Bash seemed useful, but I never really knew of anyone "programming" in Bash. Not a professional programmer or any formal training, I'm finding Python is perfect for me. -World-wide popularity; that is, Im not wasting my time -Broad enough scope to write tiny scripts or all out OOP -Easy to learn (hey - Im still with it and THAT says something!) -Its a lot of fun: I have fun writing little examples I'll have fun writing bigger programs later I can use it under windows and of course Linux I feel like I'm doing something real Anyway, thanks and I'm sure I'll have more questions as I dive deeper. -David ______________________________________________________________________ David van Popering slackware Linux Only Microsoft could come up with the following Zen diagnostic message, more appropriate for a fortune cookie than a computer: "An unnamed file contains an invalid path." From alan.gauld@bt.com Wed Aug 29 14:26:59 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 29 Aug 2001 14:26:59 +0100 Subject: [OT] BASIC Factoid (was Re: [Tutor] Functions !) Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BEF1@mbtlipnt02.btlabs.bt.co.uk> > > ISTR BASIC itself was invented by Gary Kildall and AN.Other? > > Mr Kildall of course went on to give us CP/M and GEM :-) > > Not quite, although the last name of both creators also > starts with a 'K' :) > > http://www.phys.uu.nl/~bergmann/history.html Quite right, I was 10 years too late and thinking of the first BASIC for CP/M, as shown from this snippet about Kildall: ---------- In 1973 Shugart gave Intel a sample 8" floppy disk. Gary was immediately intrigued by the device and with a friend, John Torode, built a controller interface to an Intellec-80. Gary, and his students, wrote a small control program, which he called CP/M (Control Program/Microcomputer). It enabled him to read and write files to and from the disk. Gary copied the commands and file-naming conventions from the DEC PDP-10 VMS operating system. Gordon Eubanks, one of Gary's students, created a BASIC interpreter for the system. ----------- So endeth the history lesson :-) Alan g. From alan.gauld@bt.com Wed Aug 29 14:39:58 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 29 Aug 2001 14:39:58 +0100 Subject: [OT] BASIC Factoid (was Re: [Tutor] Functions !) Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BEF2@mbtlipnt02.btlabs.bt.co.uk> > > and various proprietary ones. Commodore used Comodore BASIC > > which was all their own. > > I'm not sure. The Commodore 128's startup screen looks like this: > > COMMODORE BASIC V7.0 122365 BYTES FREE > (C)1985 COMMODORE ELECTRONICS, LTD. > (C)1977 MICROSOFT CORP. > ALL RIGHTS RESERVED Oops! I never noticed that last bit... I stand corrected. > > Most of the Japanese home computers of the '80s used > > MSX BASIC was Microsoft's. It's the MSX ranges I merant but couldn't remember the 'catchy' abbreviation ;-) > can't really imagine why they believe it would be good for beginners. Well, its easier than COBOL(*) and FORTRAN were at the time. Lisp would have almost usable but required big amounts of machine resources to run. Alan g. (*) And COBOL was supposed to be so easy to use business men would write their own programs! Shades of CP4E there... From alan.gauld@bt.com Wed Aug 29 14:42:59 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 29 Aug 2001 14:42:59 +0100 Subject: [OT] BASIC Factoid (was Re: [Tutor] Functions !) Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BEF3@mbtlipnt02.btlabs.bt.co.uk> > Sinclair's may have been their own. > > Of course, I was a kid back then, so I can't really remember, Unfortunately I was trying to write a stock control system in machine code by using lots of PEEK/POKE instructions - it had to fit in the 1K of RAM that was all Sinclair gave you... Alan g. From pythonpython@hotmail.com Wed Aug 29 15:10:17 2001 From: pythonpython@hotmail.com (HY) Date: Wed, 29 Aug 2001 23:10:17 +0900 Subject: [Tutor] A question on tkFileDialog's askopenfilename Message-ID: <OE38pTljBOh8s4KWiGt0000212b@hotmail.com> Hi there, I want to use tkFileDialog's askopenfilename to let user to choose a file. I want to print the file path,and then I want to open file. Say, the file a user wants to open is c:\py\something.txt I know: #------------------------------------ from tkFileDialog import askopenfilename filePath=askopenfilename() print "This is the file you chose",filePath #------------------------------------ BUT how can use filePath to open the actual file? Also I found out that: On Windows OS, askopenfilename() returns c:/py/something.txt instead of c:\py\something.txt (The \ become /) Why? Thanks for your help. HY From rmunn@pobox.com Wed Aug 29 16:13:37 2001 From: rmunn@pobox.com (Robin Munn) Date: Wed, 29 Aug 2001 10:13:37 -0500 Subject: [Tutor] A question on tkFileDialog's askopenfilename In-Reply-To: <OE38pTljBOh8s4KWiGt0000212b@hotmail.com>; from pythonpython@hotmail.com on Wed, Aug 29, 2001 at 11:10:17PM +0900 References: <OE38pTljBOh8s4KWiGt0000212b@hotmail.com> Message-ID: <20010829101337.A24079@resin.csoft.net> On Wed, Aug 29, 2001 at 11:10:17PM +0900, HY wrote: > Hi there, > > I want to use tkFileDialog's askopenfilename to let user to choose a file. I > want to print the file path,and then I want to open file. > Say, the file a user wants to open is c:\py\something.txt > I know: > #------------------------------------ > from tkFileDialog import askopenfilename > filePath=askopenfilename() > print "This is the file you chose",filePath > #------------------------------------ > > BUT how can use filePath to open the actual file? Simply use Python's built-in open() function: ### from tkFileDialog import askopenfilename filePath=askopenfilename() print "This is the file you chose",filePath file = open(filePath, "rb") ### The second parameter is "rb" for reading or "wb" for writing. The "b" means to open the file in binary mode (as opposed to text mode): text mode will convert CR/LF combinations to single LF's automatically. This is handy if the file you're wanting to open is actually text, but it will corrupt non-text files (such as .jpg or .doc files, for instance). If you *really* want to use text mode, do: ### file = open(filePath, "r") ### But on Windows, you should always use binary mode unless you have a specific reason not to. > > Also I found out that: > On Windows OS, askopenfilename() returns > c:/py/something.txt instead of > c:\py\something.txt > (The \ become /) > Why? The / character is the standard path-separator on Unix, and most programming languages are therefore designed to recognize / as the path separator and use it by default. You can call the os.path.normpath() function to change / to \ if you want: ### from tkFileDialog import askopenfilename import os filePath = askopenfilename() filePath = os.path.normpath(filePath) print "This is the file you chose",filePath file = open(filePath, "rb") ### Hope this helps. -- Robin Munn rmunn@pobox.com From csmith@blakeschool.org Wed Aug 29 18:13:03 2001 From: csmith@blakeschool.org (Christopher Smith) Date: Wed, 29 Aug 2001 12:13:03 -0500 Subject: [Tutor] Re: class uncertainty In-Reply-To: <E15bvnl-0007We-00@mail.python.org> References: <E15bvnl-0007We-00@mail.python.org> Message-ID: <fc.004c4b6b007985923b9aca00fd13d3e4.7985a1@blakeschool.org> tutor@python.org writes: >Dear Chris, >Christopher Smith wrote: >> I've created a class which keeps track of the uncertainty in a number >> and subsequent calculations performed with that number. It works like >> this: > As has been said before, Neat! :-) Can we see it? Would you >give us a URL for it, or post it on the list? I would really like to try >it >out. > I'm still trying to resolve a power/log issue right now but will post when that is finished. /c From bsass@freenet.edmonton.ab.ca Wed Aug 29 20:16:25 2001 From: bsass@freenet.edmonton.ab.ca (Bruce Sass) Date: Wed, 29 Aug 2001 13:16:25 -0600 (MDT) Subject: [OT] BASIC Factoid (was Re: [Tutor] Functions !) In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66BEF3@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <Pine.LNX.4.33.0108291309120.26504-100000@bms> On Wed, 29 Aug 2001 alan.gauld@bt.com wrote: > > Sinclair's may have been their own. > > > > Of course, I was a kid back then, so I can't really remember, > > Unfortunately I was trying to write a stock control system in > machine code by using lots of PEEK/POKE instructions - it had > to fit in the 1K of RAM that was all Sinclair gave you... 2K on the ZX81, unless you bought one of the RAM expanders (16, 32 and 64k sizes). PEEKs and POKEs were good for fiddling with the system; the best way to do ML on the ZX81 was to construct a REM as long as the ML, place the REM as the first statement in a basic program, then SYS to it. - Bruce From bsass@freenet.edmonton.ab.ca Wed Aug 29 20:21:31 2001 From: bsass@freenet.edmonton.ab.ca (Bruce Sass) Date: Wed, 29 Aug 2001 13:21:31 -0600 (MDT) Subject: [OT] BASIC Factoid (was Re: [Tutor] Functions !) In-Reply-To: <019601c13085$0d35d560$0ea616ca@ACE> Message-ID: <Pine.LNX.4.33.0108291316440.26504-100000@bms> On Wed, 29 Aug 2001, Glen Wheeler wrote: > > On 0, alan.gauld@bt.com wrote: > > > > > They are similar. I never did enough BASIC programming to > > > > > > > > There's actually a reason for that. All versions of BASIC on > > > > early PCs were written by, licensed from, and "maintained" > > > > by Microsoft. And you thought BASIC was public domain :P > > > > > > Gosh, I can't believe I'm aplogising for either MS or BASIC! > > > > > > However in the pre IBM PC days BASICs were split about 50/50 > > > between MS BASIC - A triuly dire but very small ROM version(4K?) > > > and various proprietary ones. Commodore used Comodore BASIC > > > which was all their own. > > > > I'm not sure. The Commodore 128's startup screen looks like this: > > > > COMMODORE BASIC V7.0 122365 BYTES FREE > > (C)1985 COMMODORE ELECTRONICS, LTD. > > (C)1977 MICROSOFT CORP. > > ALL RIGHTS RESERVED > > > > But what about the C64? I don't have that great a memory but I don't > recall a microsoft tag on it's BASIC. Of course I am probably wrong :) It didn't say MS, but it was written by MS... not sure about the VIC20 though. > Ha ha, yes yes the good old days...man you have me winding back the clock. > I was but a little 'un all the way back then too. I still remember being > about 10 years old pumping in a hexadecimal Q-Bert game from a C64 mag :) > Damn, wish I still had that thing. What's it worth to you... I got three sitting around (one even has a RTC, extra I/O hacked into the address space, and all the bits needed to bump it up to a C256 or C512. :-) - Bruce From csmith@blakeschool.org Wed Aug 29 23:50:13 2001 From: csmith@blakeschool.org (Christopher Smith) Date: Wed, 29 Aug 2001 17:50:13 -0500 Subject: [Tutor] uncertainty pre-release and new 'round' PEP suggestion Message-ID: <fc.004c4b6b00799177004c4b6b00799177.799205@blakeschool.org> OK, here's a binhex of a sit compression of the class which works with numbers and their uncertainty. (Sorry, no web site that I can send it to yet.) I'm still not exactly sure what the best arrangement of the math functions is: 1) both method and function syntax allowed for as pat present 2) just function syntax where all the definitions of methods would have to be moved up into the functions. One pro for this is less likelihood for user error when dooing something like a**b.log()--does the user know if this does (a**b).log() or a**(b.log())? The function syntax removes one level of user error. I'm having difficulty figuring out how to use coerce and float successfully. Bassically I would like to handle addition of regular numberics and the PHYS class (formerly called uncertain, but I haven't finalized on a name yet). If I define coerce then I get a complaint about not having __float__defined. And if I put in an additional float definition then I get an infinite loop. I just don't have a lot of time right now to solve this problem...if anyone hsa some suggestions I could use the help. When this is done I think it would be nice to add to something like the SCIENTIFIC package. Any other ideas? Also, I have a suggestion for a PEP. In addition to ROUND with a +/- argument, allow for a decimal argument which would round x to the dth digit after the first one. Often in science I just want the first 3 digits wherever they occur. Here is how the function would behave: from math import floor,log10 def Round(x,n): d=n%1 if d==0: return round(x,n) else: # going to treat everything after the decimal like an integer d=str(d) d=int(d[d.find('.')+1:]) return round(x,d-1-int(floor(log10(abs(x))))) x=1.23456 print Round(x,2) #1.23 print Round(x,0) #1.0 print Round(x,.2) #1.2 print Round(10*x,-1) #10.0 print Round(10*x,.2) #12.0 print Round(1000*x,.2) #1200.0 Any comments on this for a PEP? /c (This file must be converted with BinHex 4.0) :$A"SHA-ZF(NZFfPd,M%!8dP8090*9#%!N!33r`#3"1+68h4eCQC*G#!SBbNa16N h,6%j16JJ3@aKC'4TEL"6HA0dC@ec,#"*EQ-Z,#"SG(4`1Lm[Gj!$,Q&XB@4ND@j cHA-ZBfpY,e0dG@CQ5A3[$3SD!!83!!!3r`#3!h)!!3#3!h)cY3fPT9*PFf9bGQ9 NTD8!TC!%!3!!0`!3Yl#%KlHbdq`!N!d(hiS!!#`%!!!0p3#3"!m!F'KjFbj`H3! "`NT849K88LTMD!%!rj!%!*!+J!#3"85i!!!'V!!!!Lm!N!32!%,"e-H`M)5VVp4 ll%VS,ek!R3l!qEqEd'$b&LVC5r"B5+$0B6#JSl3QXBD#F-+mVFrQRhZU4S34#*j lCkCLE+IXA+EVQ@ZQiKA1()"3&*0`M(GDiScqY(IT'1e*2+L+U`K"D-f3!1Uqc@m AZH#0)83PHIljkhqBZ$8V!qdkVc)*6SUlj(K60`5-R[j4iST8$20HL6dL#l[k-H* CbbGaf5RR&RGV#fiZq3R!aiIP,3)1$ZmFE0BJ`KDTabSX6H$P+M#Nc%65d('!Q15 ElIqNf1S`FT9YPhiC#2jZ66Zh"Xm&)+)pB"4UHRj`Apmm2G5ar@SB"qrK"$pCfJ+ @"'EQa"P92Rk2p9qBe+1-GN!5f9cQ*QkmCLV'EM@[CHIDdlS3D%3S4@dY4lD('NB !mmmj6Z2TEjBmXXj*qIViq9HMlN2e8qA'4iS"jP)9Abm23Fm5!PBF$UQ$8qbX`"0 Mk15mXr+rFCN(,,P4(Ka03Gj9qQ+Y"p+d*MZL[-2S+i2IlRDhkecEY3#!*A*TkTH N2YkZ9H(jD66V$51,CSZK'd)SC6q`Ak5$mEZTV-IZj5L3!&rULMM%ejKD)i20h-P rZjA'KJrXS0252HBA&UICD$'`emEHAa(3!HXR$k)CJZCMr2EqKS1'Pbp,%!9K)Td lmeP##N3Ha(qAZh1G(6&[h1Ga%(+qLZ03S(VAJEXL42d9LaH2R'&YA(jC'Jb4CMc cY4!4,63T+T8'*cmmVk143LdSA(h'6%,"e38dPA`'b[1'"1AINh[5S0,S0El!cGM d2C'TLU+1`)'K"5%C%6,(&qc[DLG$aQXAERhE0N5Nj`(BcLQUGAP4%,%KM1Tr3ri !f-diphCNc+iA@Ha1!bP`F%)fMpZBBZ2YibGLb1&5pl1EP9)I+HpIi)fYUbI2A$P TSZlU(C1INL)AJmD+4ijk1U0[4aK56kHX#9&USk8M,bXfc,@GH!c,HPZ$qm&hVQ( R15(2YSeDC`HAI!+rkLKD[$3'*5T6I@+XljA9'mqFiK+-I[5IHkH%%,),jVZQCJI Zdrel!rVc[AL5j,2pTa&BJLrf"0YaFR5$jF4A'jiKMTT)mZ&'i8c)L@Dm)mp#PAR #FrdGY1&Hr)JHJ-&TE@Gd10Qe#1I%EPdC!Grif88'r#3emGCUi!B#9%X`R#BNdIR EK2`HNkcD9f%cbmQ&d5q('!5"2K*f8!hL4cRb5mN4phTaSJ95a6ImZhRPRC)A-%V CM0054CQA6l1P&+rE1l6*`Q18#Ifqj$2L%@#Rrc6&P+S#6"DjHCNaqKFNKFjeib& "CQE9Ie&i`PJXH5F9JKZ3!)X[d8"')i6qaIM9`m'H(R`kPFdp$6(h9i$!+iD%%F3 h@PK4A)QQfX`QAXiQJN5J+6SMM,AhY59RbVBA2f8k1XKPIC2+Z!DCEFChT[NYQic &#)9&U5`RNMdU"pG&"qBmTb8Kqqa'60F&9K2)Mkf[-F8@fk4j$4"Kf[DiqZU2rV( !$DTL6185(bR$`,bS5%,d`dfA0#P%19lG3[KKQU[lHdRI3`G,4rXbCJ"P)0XDU11 KF"`K!8k5,`M+"Ne&5"'LAQ-)FjTU#N2[GZSA&VHj#m%YE%4(mhDQI*!!4c$m@pX 1D#VMi()GT6JDCKUr1GY-`1@0p5d@6IiRFDVd!keS![ECfGq(R+aH[CE+rKfd4iQ BRa'iNhiV(3Elf$XD"@GRE,r"NhRb3+qDajB*Sf66rPqjEj*+L@hA-LTkRC(mL5b f"eAZ3GU2Xk5Ep"8IjrT!rEp5bE$PRq6f,L,#2CrLS3eI-)'1PHG4NDk[4A"hK6D *`i%l(qmRiC4k+CV2RjGL0cMUY5rr@b4@G[GeI54S4eQVN!"2Lf#L3qB'+cdC##r 925E@G'fkHFj[&9JBP&%-0+,CifAk-md3i@Gp'@E!9rP3cFC&+#)R68VmG)-2Xap U$)f(LV$ZZY,C321--#UDNSP2bTQH*J0"+)Q"fLB!D[Z$$Gf!%460P6Y!V6r-Ndl 5G[SiUJ"(r[hFj`qki9%kqX[jPhM5l1FH@1!Y9-NDIjk0qi#m6k2E"dJDpK(ZN!$ EMbc5kppE6'-P6QNQrXaaLClD0R0[qZ()cL2lM4(5Qrc%#@fmCJF(SrK,k"9!lA1 *K!DHVk6q#"laE4I8SbMpV'5ljEDk(M3DKaJe1294Eh&KpBEX&BUYIMd[(,Q2-cc QQ(hcJE5e3b2qldfFTmA+ZD'3!!(a"il[F!epUa"KaEY"cH0$))clDP592[fp'f2 9'S5aDrak"F"Rp#BNFc6ZF)L6Jr*PI*3'+"Ae+IdAp9!3h!bCBN3P(*M9Aq-e#U1 (Sb+FV85rU*Mkf'R%0Q9+hYYDV#j2a"HZ'334dPmp4cqr$`RA1DEP)5F5cbI5pjB 6XLX@(@(!T$&'XdpGl`SM)H`q5k2r&19,%RANp9kYB2f+)%PXAfZl!*8YTlj9(lK 8PP+@5YQpKH!Z13l[GSYDqF9*'bZ)LBHX6+8QfdlCNQ$b4mXi')*R4MKkTZNAfHH $Q`%G)q)m)9CA!$4,'e$#h`9[C"kF3(50f(8*(,PAQU)*fkc!c68VP3MT-(fGdLf P"i!MpM`'JQ1bTj!!Ni9aH$jF@@1J-k@SrBUm@ikrZ62Gp#r2Vh+1"Ih"DcVISUI 2KrfjICjLR1#Aq8Drqr)@e8a8&j*GRQ,Pp[&0)XUrE)Q"[B$Q)IrK%lYANR$8L8Y d%84mZiTMPG$9fmY!ZQD*ZrPF!'bE%ZcArpaa2f#kP&A[!Ijf9+e5qKIJ%ZQ8qda qQL'N9E8)E1hNZ5C1,qm@[#'MS("qF,FfkJj!@![HU$k"bVCFhm&#[rAejD44XH[ $,kiikqFZC8"'&M$%lE[CP5"H*+U4IA"idYjGC-YM[V,8V!cVe(kAZ[qke,`V*AS Ui#9HG`h5+SpMHRYG@9-GDpRRFrY+&%G%-%Y,9!GC5c[@68Lq%#00Bj%ArceZ')* VZq-0'8'$QjC14ip'HCBVIi0U3'Ab'l3Zf+Kd6@$14,3I2CVm-l2Nk!DDl9dLiUM bVS%1d3HLiE[AP2LNDGheh,YKb0qpe+*KG+[4IP8A-LC`1Par!0T3i`MLQ&"*GPp $&2+'HLK#V'lM+X)LXQAXSHX1U&a0+dZfjBSp&aT4`QbYGMqdp`%QZLX$Nc`(hBp U!JPY*dY`e'Nf63lC"64lNcV&[%jfrQm+YNYQN8`#CS5eBf+aS!"9&SK0P!G`$r1 eq(8d&lN61SN#f*iKqLkK!4hhA6P14"*1FR#b+EQTZ(*Ui&U5VbE"cQMjPPrkbfI PQh9UR@ekB@5h$,ml`TeeB-U02Z*L%&$5bPAZ'h0+bk9i(N9cSZe3EjUAB4-+6!I 0!XS'"lAI#5+@Cf313N&%H['fTLI"m"-9FrH',k84(pL3!0lYa194(@F'&ReLJG, T9!!Yk*`qbhf%9B*dBB&ZViq&3EP%BkPGZepUl1b%&V#Gq3eS*'DD28`If3p,6"# 8hGF,@R58!Jaf35bS[l316kIq8!fmYaN,A!G+&H(Q"%-"lAplL'qEHTGXl+f0JiD KHY`fP3FQhE3EIkCEJJ-piY(6MjDZ1Xq("$$rDdlMq)`@MTJ'L,U9hf$!Ka$h-4- C0MXejD(6[R3,8G(rF0e"GhRhZ([S'd0G`"[08Xdc53TM,+LBi68$1qbbd2p`[2( Df"GeBT[heJ!D$%VV&mi[CNjTKk#Mc&LVMmZMLHE%iQG#ml,3fi"Dij(ed%VL9++ 4ml[THYY1)@R'm5IEE!GcA3EU)#XU+*9GHkLKSBZ5#YLB#@)eb5h&bhe9#U&RTP! [-rLIeNiL#8"dB53m1D4(0UiCaPN(V&6(9aMUi(F8')iN"R8YI-9`9JpH6m-!K5i 3fl$Qf4Z)"0S%d!*`0kbFjR3-H2lG"$fIfEh2VGf8'V+@j[k)(9dkqhUB9&ZX+Ei F["bIA(0-HN,Arqc926@Xj)5+V*jj2Ph')[Ubr3G)%9IMe8(R!Q&V3JE&Z"F`3dJ !dMH[r4!Xk+0Y,DY)Ul1X[",LCAraRV859i6S3U,JbG!Ck@EpR`ihqeCTq$UAAK' a@F1p-@GZAi"pFdM2$qjPBh*TH1NlDVRIJ%j#cp)@@$rE0,CPjGh*6CIk#2bl0MM 4r+j%@+DTQQVrE66K38CafkaTe$,DKjGNV)'G"dB1mc*@BK+mRH'6L$D@U#p090q plD28K#J)#rqEb*8h"V)Dqr+p(aF"!cFUqiB@chA&e'3CiKNN#6m`hY32VK5MpTS #'q`,4&1CbkLaLjkBU(8`pCf#QZ'[5+*S90'q4&8A8"U!F2A'U(`TTVeY@S@5$lM 1hfVYA(Zm6QF*iV+2Y9rQV#U(k4KLI!2#H-)fUB4ED@K'"+N*RD(Kbm,QlEVY+%G S'`FN-L#VX08ba0`*'J1Ka9j9hNSYS9H+FCVV5k[pJXX0MXZQ-1!Icbmj,Z)iEpH UdD[XUBQ-0mU`H!e6BSk,Em&m(EDHDJ`-rh6DphjNV!qLaMFBYpC9Ed8*PD@`IY! hTYD@+N%ZE$U@lceZKU00,C!!UJD-!%c4RdT6IZMQReH"er`*`q)c*3+!$KDVh02 6$!)RPF0$S[JI)IJ`Z"&p'l-mlT!!+6$40P"bq0CSRG8Q6VGShQBE(IV1)&f9IPK fUURCKGBK6"T`fr'3!'$eGH)9G6I0435(L5[diR)qf1YrGj0cIfm6b8XmRjRH1hU f5U)!H(2(Pf)`(dEX)h*rRd`"*0G5$beG3"KJ8*%BU["DIY[`Veq+0@3ITPiE&rP X602+8B!TeG)Sh6UF+#!p`a'#0)YlKiM1EBC3XFSIlRCLZJGiEbU#k6Nk3hHILZQ l!b5B@UQ-lmEYB0,r9l1b5H%p#RHf-H*b!h0VTURiT(PKqQ8lK2C'arUVpiXAA$Y Ri)FqSqX$[LPGQF51LF@GqDY$KSebC5"TNYd'mIQhq*`0&G'i'3rUF9-b"c1FS34 PYTBYUQDf%H&6F@",i[(Y0U2"M`)(@LP3Lhd0GLEiZC4hV&&P1FbJlAk(U@Ka!MG mL#1&3DbpRMPV5-8V!5A[CAf3!!hiPM4*6UI2HjhcMciLTAe##-j-,l5U23SSB+N dBZKXN53Lb4X1AU4L(jI+c*frhZ8Th+8iSTi#9k,6bc45'&,%816PBRl5%YH!,"# IV!&ZG&8b5"P3VKCm$l(L'1AdjC!!GhFB&-XcIa3akDAe+J4fhFem53`4+C&GQ)$ TPZ,`$9XZafek$%ZGHV6cfR"90`H4I63M6K3ATb%)P&S14HRNb6E)ScdqU#%5-hH KZF!#YUqe0!EQdIp-X"DiCD'UbMi[f9BrLdTCmp#l4-Xh8GTRr-[eTRe6hIq!`(H @dM84`kL[$2'ZSX(VqQTqiXbkV3i9'qZ&QA51$V$Sb@)dpYiMq$55TVJ-GK2rbQ0 jM[m9HS`(3jRjrR6UmeCa'*&BSeT+Z%Pa00dZVl8)Zf`BbKS[b"(M4idbABlVmC' 1fGfIBm#)!j!!D36l+EB&r#-r2r&V9j+*Np5l@Yml%d8b5V9i5T6N"1VRpAL9"pb `Nc#2EQ-K!!#D93!!: From wheelege@tsn.cc Thu Aug 30 04:02:24 2001 From: wheelege@tsn.cc (Glen Wheeler) Date: Thu, 30 Aug 2001 13:02:24 +1000 Subject: [Tutor] A question on tkFileDialog's askopenfilename References: <OE38pTljBOh8s4KWiGt0000212b@hotmail.com> <20010829101337.A24079@resin.csoft.net> Message-ID: <005201c13100$32600880$08a616ca@ACE> > <..> > > > > Also I found out that: > > On Windows OS, askopenfilename() returns > > c:/py/something.txt instead of > > c:\py\something.txt > > (The \ become /) > > Why? > > The / character is the standard path-separator on Unix, and most > programming languages are therefore designed to recognize / as the path > separator and use it by default. You can call the os.path.normpath() > function to change / to \ if you want: > Just to chip in here - if it was \ then the characters would be interpreted as escape codes, as you no doubt found out if you tried to use \'s instead of /'s. Windows is a little sneaky and will actually accept both :) Glen. From wheelege@tsn.cc Thu Aug 30 04:07:57 2001 From: wheelege@tsn.cc (Glen Wheeler) Date: Thu, 30 Aug 2001 13:07:57 +1000 Subject: [OT] BASIC Factoid (was Re: [Tutor] Functions !) References: <Pine.LNX.4.33.0108291316440.26504-100000@bms> Message-ID: <006701c13100$f84f6b80$08a616ca@ACE> ----- Original Message ----- From: "Bruce Sass" <bsass@freenet.edmonton.ab.ca> To: "Glen Wheeler" <wheelege@tsn.cc> Cc: <tutor@python.org> Sent: Thursday, August 30, 2001 5:21 AM Subject: Re: [OT] BASIC Factoid (was Re: [Tutor] Functions !) > > > Ha ha, yes yes the good old days...man you have me winding back the clock. > > I was but a little 'un all the way back then too. I still remember being > > about 10 years old pumping in a hexadecimal Q-Bert game from a C64 mag :) > > Damn, wish I still had that thing. > > What's it worth to you... I got three sitting around (one even has a > RTC, extra I/O hacked into the address space, and all the bits needed > to bump it up to a C256 or C512. :-) > Well, it's not worth as much as that beast will probably cost me :) But seriously, I've already got somebody offering me a C64 just for shipping - and since I did read his e-mail first...well, ya know. I'm sure another nostalgic python-er will come along wanting a C64 in no time. Thanks anyway, Glen. From haiyang_yang@hotmail.com Thu Aug 30 07:26:23 2001 From: haiyang_yang@hotmail.com (Haiyang) Date: Thu, 30 Aug 2001 15:26:23 +0900 Subject: [Tutor] a question regarding os.system() Message-ID: <LAW2-OE75LyGqOs28ev00001a83@hotmail.com> Hi there, I know that we can use os.system() to lauch applications. Say, I want to use notepad to open a file - data.txt I should do os.system('notepad data.txt') BUT what if the string 'data.txt' is stored in a variable, how can use notepad to open it? file='c:\data\data.txt' os.system('notepad and What? Or, is there anyway to lauch application rather than os.system() Thanks a million. Hy From bsass@freenet.edmonton.ab.ca Thu Aug 30 07:34:01 2001 From: bsass@freenet.edmonton.ab.ca (Bruce Sass) Date: Thu, 30 Aug 2001 00:34:01 -0600 (MDT) Subject: [Tutor] a question regarding os.system() In-Reply-To: <LAW2-OE75LyGqOs28ev00001a83@hotmail.com> Message-ID: <Pine.LNX.4.33.0108300030280.30302-100000@bms> On Thu, 30 Aug 2001, Haiyang wrote: > I know that we can use os.system() to lauch applications. > Say, I want to use notepad to open a file - data.txt > I should do > os.system('notepad data.txt') > > BUT what if the string 'data.txt' is stored in a variable, how can use > notepad to open it? > > file='c:\data\data.txt' > os.system('notepad and What? os.system('notepad %s' % file) - Bruce From dyoo@hkn.eecs.berkeley.edu Thu Aug 30 09:11:30 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 30 Aug 2001 01:11:30 -0700 (PDT) Subject: [Tutor] a question regarding os.system() In-Reply-To: <Pine.LNX.4.33.0108300030280.30302-100000@bms> Message-ID: <Pine.LNX.4.21.0108300057180.28885-100000@hkn.eecs.berkeley.edu> On Thu, 30 Aug 2001, Bruce Sass wrote: > On Thu, 30 Aug 2001, Haiyang wrote: > > I know that we can use os.system() to lauch applications. > > Say, I want to use notepad to open a file - data.txt > > I should do > > os.system('notepad data.txt') > > > > BUT what if the string 'data.txt' is stored in a variable, how can use > > notepad to open it? > > > > file='c:\data\data.txt' > > os.system('notepad and What? > > os.system('notepad %s' % file) Another way to do it is to stick together strings with addition: ### >>> command = "notepad" >>> file = "data.txt" >>> command + file 'notepaddata.txt' ### ... although it does require a little extra effort to make sure we don't squeeze the words together: ### >>> command + ' ' + file 'notepad data.txt' ### Bruce's approach to building up strings is called "String Formatting", and we can think of it sorta like Madlibs: string formatting will substitute in strings whereever it sees a "%s". In fact, there's a variation on this formatting that looks very much like Madlibs: ### >>> story = """Once upon a %(noun1)s, there lived a %(adjective1)s ... %(noun2)s, and the %(noun1)s %(verb1)sed it every day.""" >>> story % { 'noun1' : 'Tim', ... 'adjective1' : 'holy', ... 'noun2' : 'Hand Grenade', ... 'verb1' : 'bless' } 'Once upon a Tim, there lived a holy\nHand Grenade, and the Tim blessed it every day.' ### You can find more about in the "Fancier Output Formatting" section of the tutorial here: http://www.python.org/doc/current/tut/node9.html#SECTION009100000000000000000 Also, there are some formal docs here: http://www.python.org/doc/current/lib/typesseq-strings.html if you need to go to sleep anytime soon. *grin* Talk to you later! From SBrunning@trisystems.co.uk Thu Aug 30 10:12:53 2001 From: SBrunning@trisystems.co.uk (Simon Brunning) Date: Thu, 30 Aug 2001 10:12:53 +0100 Subject: [OT] BASIC Factoid (was Re: [Tutor] Functions !) Message-ID: <31575A892FF6D1118F5800600846864D78C05D@intrepid> > From: Bruce Sass [SMTP:bsass@freenet.edmonton.ab.ca] > 2K on the ZX81, unless you bought one of the RAM expanders (16, 32 and > 64k sizes). PEEKs and POKEs were good for fiddling with the system; > the best way to do ML on the ZX81 was to construct a REM as long as > the ML, place the REM as the first statement in a basic program, then > SYS to it. It was *definitely* only 1K on mine. I ended up getting a 16K Ram pack, but if I typed too hard, it would wobble, and the ZX81 would crash. Sigh. Those were the days! Cheers, Simon Brunning TriSystems Ltd. sbrunning@trisystems.co.uk ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From printers@sendme.cz Thu Aug 30 13:03:00 2001 From: printers@sendme.cz (A) Date: Thu, 30 Aug 2001 14:03:00 +0200 Subject: [Tutor] Is Python powerful enough for this? Message-ID: <3B8E4794.9988.1181E6F@localhost> Hi, I have some webpages that contain FORMS. Each form has input fields and also some hidden fields. How can I easily get urlencoded string from all these fields like Key1=Value1&Key2=Value2&Key3=Value3 For example: I have a following web page <html> <head> </head> <body> <form method="POST" action="c.cgi"> <p><input type="text" name="T1" size="20"></p> <p><input type="checkbox" name="C1" value="ON"></p> <p><textarea rows="2" name="S1" cols="20"></textarea></p> <p><input type="submit" value="Submit" name="B1"><input type="reset" value="Reset" name="B2"></p> </form> </body> </html> >From the above I would like to receive T1=&S1=&C1=&B1=Submit Thank you for help. Ladislav From bill_tolbert@bigfoot.com Thu Aug 30 15:27:42 2001 From: bill_tolbert@bigfoot.com (Bill Tolbert) Date: Thu, 30 Aug 2001 10:27:42 -0400 (EDT) Subject: [Tutor] Why I'm learning Python (OT and long) Message-ID: <Pine.GSO.4.21L1.0108300840130.28609-100000@sunny> I spent some time reading Useless Python last night and went to bed totally depressed. I feel that even Useless is above my skill level. So, what follows is the story of why I'm trying to learn Python. Perhaps some will understand; some may be in a similar situation; some may want to send me money. Maybe it can become an installment for the soapbox on Useless. ====================================================== So here I sit, pretending that I know a little something about Python. I own 5 Python books; I have been attempting to program in Python for over a year; my title is something like "systems analyst"; I have a wife, many children and a dog. Allow me to explain how this all happened... I never pretended to be a programmer. I was trained to do public health research. But, the tight job market of recent years forced me to take on various computer tasks in the course of my research. It started with WordPerfect. I was something of a WordPerfect wonder kid. I could somehow do anything in WordPerfect. Looking back, I guess this was my first programming - WordPerfect macros. I just grokked other macros and read the help files. Massively complicated mail merges, text manipulation, complex and tedious tasks rendered trivial in the wake of my macros. I began to build solutions for the secretaries, co-workers, people on the street. Then M$ began pushing that third-rate wannabe word processor of theirs and nothing was ever the same. So, I sorta learned MS Access the same way. Of course I knew Access was just a desktop database. But it was fine around the office. I wrote a few simple applications, and that was fine; after all, I'm a researcher not a programmer. But guess what? People started coming to be with requests for Access applications. And before I knew it, I was writing a very complex accounting system for my employer. I was being labeled, and I knew it. I tried to resist but it was futile. I thought long and hard about going back to school for a PhD in epidemiology; I was trying to escape becoming a programmer. All the while there were bills to pay and groceries to buy and mouths to feed. I didn't have time go back to school. I couldn't afford it. And then one day I was offered a real job as a programmer... Some folks in the private research world had decided to build a large system in Access. I was doing some part time work for this company because as a university employee, I couldn't make ends meet. They knew me as a WordPerfect and Access guy, and asked me to join the project full time. I was flattered but declined; after all, I'm a researcher not a programmer. I told them repeatedly "I'm not a programmer". But they were desperate. I knew they were desperate. I was the only person they could find. And even though the university didn't pay very well, I still loved my job there. So one day they asked, "What would it take?". Have you ever been asked that question? I was 29 years old and driving a worn out car I paid 450 dollars for. Three kids. Working a full time job and a part time job. So, I told them what it would take and they said ok. Of course my wife was happy. This meant financial freedom. Perhaps we could have a normal life. But I was afraid. The day would come when they would learn the truth and I would be thrown out like the pitiful code I write. Well, it's been nearly four years and I haven't been thrown out yet. I was assigned the title systems analyst by the people who were in charge of making up the business cards. I guess I've fooled them so far. But I haven't fooled myself. Sure I can get by in Access/VB. But I know Access is kid stuff compared to Oracle and MySQL. I want to write solutions for non-MS platforms; I want to understand the difference between bound and unbound methods; I want to understand other people's code; I want to be Danny Yoo!!! So that's why I'm trying to learn Python. To bring legitimacy to an otherwise illegitimate career. Some of my Python scripts seem ok. They do useful work on a daily basis. And yet, even a blind squirrel finds a nut sometimes. I'm plagued by the feeling that I am a blind squirrel. Thanks folks. This has been therapeutic. Python people are the best and this list is fantastic. Today I'm going to make one of my useful scripts run from a Tk button widget. And I'll stumble through. Perhaps I'll get lucky and find a nut. Bill From 2canadians@nppo.net Thu Aug 30 15:54:05 2001 From: 2canadians@nppo.net (2Canadians) Date: Thu, 30 Aug 2001 10:54:05 -0400 Subject: [Tutor] WindowsSE/Python User Need Help With Dictionaries Message-ID: <000e01c13163$a035faa0$4cb71704@tospec> This is a multi-part message in MIME format. ------=_NextPart_000_000B_01C13142.16310B40 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable I am working on a type of menu program using Python. I have created a = menu and want a user to be able to input names which would go into a = dictionary. I have created a dictionary and can't get the input to add = another unit to the dictionary. It will only take the last entered = value. If you have a hard time understanding this, here is a sample(not = verbatum): import blah def menu1(): getConstantValue1=3Draw_input("BLAHBLAH") getConstantValue2=3Draw_input("BLAHBLAH") GetAmount=3Dinput("BLAHBLAH") while GetAmount>0: getNameList=3Draw_input("BLAH") dictionary=3D{"A":getConstantValue1 "B":getConstantValue2, = "List":getNameList} #THIS IS PART OF THE DICTIONARY = NOT A NEW LINE!! GetAmount=3DGetAmount - 1 print dictionary{} print menu1() Thanks, Specs ------=_NextPart_000_000B_01C13142.16310B40 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML><HEAD> <META content=3D"text/html; charset=3Diso-8859-1" = http-equiv=3DContent-Type> <META content=3D"MSHTML 5.00.2614.3500" name=3DGENERATOR> <STYLE></STYLE> </HEAD> <BODY bgColor=3D#ffffff> <DIV><FONT face=3DArial size=3D2>I am working on a type of menu program = using=20 Python.  I have created a menu and want a user to be able to input = names=20 which would go into a dictionary.  I have created a dictionary and = can't=20 get the input to add another unit to the dictionary.  It will only = take the=20 last entered value.  If you have a hard time understanding this, = here is a=20 sample(not verbatum):</FONT></DIV> <DIV> </DIV> <DIV><FONT face=3DArial size=3D2>import blah</FONT></DIV> <DIV> </DIV> <DIV><FONT face=3DArial size=3D2>def menu1():</FONT></DIV> <DIV><FONT face=3DArial size=3D2>   =20 getConstantValue1=3Draw_input("BLAHBLAH")</FONT></DIV> <DIV><FONT face=3DArial size=3D2>   =20 getConstantValue2=3Draw_input("BLAHBLAH")</FONT></DIV> <DIV><FONT face=3DArial size=3D2>   =20 GetAmount=3Dinput("BLAHBLAH")</FONT></DIV> <DIV><FONT face=3DArial size=3D2>    while=20 GetAmount>0:</FONT></DIV> <DIV><FONT face=3DArial size=3D2>       =20 getNameList=3Draw_input("BLAH")</FONT></DIV> <DIV><FONT face=3DArial = size=3D2>       =20 dictionary=3D{"A":getConstantValue1 "B":getConstantValue2, =    =20             =20       "List":getNameList}  #THIS IS PART = OF THE=20 DICTIONARY NOT A NEW LINE!!</FONT></DIV> <DIV><FONT face=3DArial = size=3D2>       =20 GetAmount=3DGetAmount - 1</FONT></DIV> <DIV><FONT face=3DArial size=3D2>    print = dictionary{}</FONT></DIV> <DIV><FONT face=3DArial size=3D2>print menu1()</FONT></DIV> <DIV> </DIV> <DIV><FONT face=3DArial size=3D2>Thanks,</FONT></DIV> <DIV><FONT face=3DArial size=3D2>Specs</FONT></DIV></BODY></HTML> ------=_NextPart_000_000B_01C13142.16310B40-- From ignacio@openservices.net Thu Aug 30 15:51:26 2001 From: ignacio@openservices.net (Ignacio Vazquez-Abrams) Date: Thu, 30 Aug 2001 10:51:26 -0400 (EDT) Subject: [Tutor] WindowsSE/Python User Need Help With Dictionaries In-Reply-To: <000e01c13163$a035faa0$4cb71704@tospec> Message-ID: <Pine.LNX.4.33.0108301048440.29615-100000@terbidium.openservices.net> On Thu, 30 Aug 2001, 2Canadians wrote: > I am working on a type of menu program using Python. I have created a menu and want a user to be able to input names which would go into a dictionary. I have created a dictionary and can't get the input to add another unit to the dictionary. It will only take the last entered value. If you have a hard time understanding this, here is a sample(not verbatum): > > import blah > > def menu1(): > getConstantValue1=raw_input("BLAHBLAH") > getConstantValue2=raw_input("BLAHBLAH") > GetAmount=input("BLAHBLAH") > while GetAmount>0: > getNameList=raw_input("BLAH") > dictionary={"A":getConstantValue1 "B":getConstantValue2, "List":getNameList} #THIS IS PART OF THE DICTIONARY NOT A NEW LINE!! > GetAmount=GetAmount - 1 > print dictionary{} > print menu1() > > Thanks, > Specs The problem is that you're overwriting the dicitonary through each loop: --- def menu1(): v1=raw_input('...') v2=raw_input('...') c=raw_input('...') l=[] while c>0: n=raw_input('...') d={'a':v1, 'b':v2, 'c':n} c=c-1 l.append(d) return d print menu1() --- -- Ignacio Vazquez-Abrams <ignacio@openservices.net> From uselesspython@yahoo.com Thu Aug 30 15:52:06 2001 From: uselesspython@yahoo.com (Rob) Date: Thu, 30 Aug 2001 09:52:06 -0500 Subject: [Tutor] Why I'm learning Python (OT and long) References: <Pine.GSO.4.21L1.0108300840130.28609-100000@sunny> Message-ID: <3B8E5316.1080409@yahoo.com> Bill Tolbert wrote: > I spent some time reading Useless Python last night and went to bed > totally depressed. I feel that even Useless is above my skill level. So, I can honestly say that you could send in helloworld.py to Useless Python and see it posted (probably with some odd form of recognition, since I've been waiting for a 'hello world' for months now, albeit secretly). Why not try something really odd (like I would do), such as a 35-line 'hello world' script that checks to make sure that 1 == 1 and such before printing the string. I'm one of the worst programmers alive, and make sure that Useless Python is an oasis for people nearly as awful as I am. Over the last several months, extra stuff has been added (Python Challenges, programming contest problems, etc.) to give people ideas to play with. But the core purpose of the whole thing was a collection of Python scripts "of dubious applicability" and just for fun. > what follows is the story of why I'm trying to learn Python. Perhaps some > will understand; some may be in a similar situation; some may want to send > me money. Maybe it can become an installment for the soapbox on Useless. > > ====================================================== > > So here I sit, pretending that I know a little something about > Python. I own 5 Python books; I have been attempting to program in Python > for over a year; my title is something like "systems analyst"; I have a > wife, many children and a dog. Allow me to explain how this > all happened... > > I never pretended to be a programmer. I was trained to do public health > research. But, the tight job market of recent years forced me to take on > various computer tasks in the course of my research. It started with > WordPerfect. I was something of a WordPerfect wonder kid. I could somehow > do anything in WordPerfect. Looking back, I guess this was my first > programming - WordPerfect macros. I just grokked other macros and read the > help files. Massively complicated mail merges, text manipulation, complex > and tedious tasks rendered trivial in the wake of my macros. I began to > build solutions for the secretaries, co-workers, people on the street. > Then M$ began pushing that third-rate wannabe word processor of theirs and > nothing was ever the same. > > So, I sorta learned MS Access the same way. Of course I knew Access was > just a desktop database. But it was fine around the office. I wrote a few > simple applications, and that was fine; after all, I'm a researcher not a > programmer. But guess what? People started coming to be with requests for > Access applications. And before I knew it, I was writing a very complex > accounting system for my employer. I was being labeled, and I knew it. I > tried to resist but it was futile. I thought long and hard about going > back to school for a PhD in epidemiology; I was trying to escape becoming > a programmer. All the while there were bills to pay and groceries to buy > and mouths to feed. I didn't have time go back to school. I couldn't afford > it. And then one day I was offered a real job as a programmer... > > Some folks in the private research world had decided to build a large > system in Access. I was doing some part time work for this company because > as a university employee, I couldn't make ends meet. They knew me as a > WordPerfect and Access guy, and asked me to join the project full time. I > was flattered but declined; after all, I'm a researcher not a > programmer. I told them repeatedly "I'm not a programmer". But they > were desperate. I knew they were desperate. I was the only person > they could find. And even though the university didn't pay very > well, I still loved my job there. So one day they asked, "What > would it take?". Have you ever been asked that question? I was 29 > years old and driving a worn out car I paid 450 dollars for. Three > kids. Working a full time job and a part time job. So, I told them > what it would take and they said ok. Of course my wife was > happy. This meant financial freedom. Perhaps we could have a > normal life. But I was afraid. The day would come when they would > learn the truth and I would be thrown out like the pitiful code I > write. > > Well, it's been nearly four years and I haven't been thrown out yet. I was > assigned the title systems analyst by the people who were in charge of > making up the business cards. I guess I've fooled them so far. But I > haven't fooled myself. Sure I can get by in Access/VB. But I know > Access is kid stuff compared to Oracle and MySQL. I want to write > solutions for non-MS platforms; I want to understand the difference between > bound and unbound methods; I want to understand other people's code; I > want to be Danny Yoo!!! > I can feel Danny blush from 3,000 miles away right about now. > So that's why I'm trying to learn Python. To bring legitimacy to an > otherwise illegitimate career. > > Some of my Python scripts seem ok. They do useful work on a daily basis. > And yet, even a blind squirrel finds a nut sometimes. I'm plagued by the > feeling that I am a blind squirrel. > I won't add my own tedious story to your own actually interesting one. But I'm degreed in Psychology and Philosophy ("Would you like fries with that?") and can do amazing things with PC-related hardware that others had written off as dead. I picked up a tiny little bit of Pascal in college when the professor literally begged me to sign up for the class in front of 300 people. (I wasn't that promising. He just had zero people sign up for it, and he knew I would cave in to make him stop humiliating himself.) I managed to get through college without *utterly* destroying any major equipment, and breathed a sigh of relief until the student loan bills started piling up. Since then, I've added the occasional trick to my bag here and there. But the night I downloaded Python, I discovered some magic I'd missed sorely and searched for nearly to the point of giving up. You, Bill, are the kind of person Useless Python dreams of when it sleeps. You have the courage to do this stuff at all, and the combination of insight and good luck to have found Python and the Tutor list. > Thanks folks. This has been therapeutic. Python people are the best and > this list is fantastic. Today I'm going to make one of my useful scripts > run from a Tk button widget. And I'll stumble through. Perhaps I'll get > lucky and find a nut. > > Bill > Happy Whatever Day It Is, Rob -- A {} is a terrible thing to waste. Useless Python! http://www.lowerstandard.com/python From ignacio@openservices.net Thu Aug 30 15:56:24 2001 From: ignacio@openservices.net (Ignacio Vazquez-Abrams) Date: Thu, 30 Aug 2001 10:56:24 -0400 (EDT) Subject: [Tutor] WindowsSE/Python User Need Help With Dictionaries In-Reply-To: <Pine.LNX.4.33.0108301048440.29615-100000@terbidium.openservices.net> Message-ID: <Pine.LNX.4.33.0108301054470.29615-100000@terbidium.openservices.net> On Thu, 30 Aug 2001, Ignacio Vazquez-Abrams wrote: > The problem is that you're overwriting the dicitonary through each loop: > > --- > def menu1(): > v1=raw_input('...') > v2=raw_input('...') > c=raw_input('...') > l=[] > while c>0: > n=raw_input('...') > d={'a':v1, 'b':v2, 'c':n} > c=c-1 > l.append(d) > return d > > print menu1() > --- Whoops! My bad. --- def menu1(): v1=raw_input('...') v2=raw_input('...') c=raw_input('...') d={'a':v1, 'b':v2, 'c':[]} while c>0: n=raw_input('...') c=c-1 d['c'].append(n) return d print menu1() --- -- Ignacio Vazquez-Abrams <ignacio@openservices.net> From lkvam@venix.com Thu Aug 30 16:41:03 2001 From: lkvam@venix.com (Lloyd Kvam) Date: Thu, 30 Aug 2001 11:41:03 -0400 Subject: [Tutor] Why I'm learning Python (OT and long) References: <Pine.GSO.4.21L1.0108300840130.28609-100000@sunny> Message-ID: <3B8E5E8F.A21534E6@venix.com> Please don't sell yourself short. Logically, Access, MySQL and Oracle are not that far apart. For a DataBase Administrator they are very different. But a lot of those differences do not impact your programs. Most of the Systems Analysts that I know are terrible programmers. They can not manage the nitty-gritty details that clutter up the big picture when you actually code in C or COBOL or VB or whatever. Their job is really to make sure the programmers actually wrote code that does what was intended. Python's nice in that the details are MUCH easier to manage than almost any other language that I have used. If you can describe what you are doing in reasonable English, you are half way to having a Python program - just turn the English into an indented outline, get rid of articals and extra words, stick in the :'s where needed and it can be amazingly close to working code. When you find yourself repeating the same stuff, you know you should be making a class or function to hold that stuff. Small Python programs almost seem to tell me how to code them. I would be happy to review a reasonable chunk of code and offer my opinions and suggestions. Just remember (as they say in Perl land), there really is more than way to do it. Any suggestions that I offer should be taken as reflecting my habbits and style of doing things. Don't feel bound to take them too seriously. Bill Tolbert wrote: > ..... > haven't fooled myself. Sure I can get by in Access/VB. But I know > Access is kid stuff compared to Oracle and MySQL. I want to write > solutions for non-MS platforms; I want to understand the difference between > bound and unbound methods; I want to understand other people's code; I > want to be Danny Yoo!!! > > Bill > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From kalle@gnupung.net Thu Aug 30 16:47:11 2001 From: kalle@gnupung.net (Kalle Svensson) Date: Thu, 30 Aug 2001 17:47:11 +0200 Subject: [Tutor] Is Python powerful enough for this? In-Reply-To: <3B8E4794.9988.1181E6F@localhost>; from printers@sendme.cz on Thu, Aug 30, 2001 at 02:03:00PM +0200 References: <3B8E4794.9988.1181E6F@localhost> Message-ID: <20010830174711.A26982@gandalf> [A] > Hi, > I have some webpages that contain FORMS. Each form has input > fields and also some hidden fields. > How can I easily get urlencoded string from all these fields > like > Key1=Value1&Key2=Value2&Key3=Value3 Use the cgi module. From the FieldStorage class there, you can get all the fields and format them as an URL-encoded string if you want to. Perhaps you can get the raw string from somewhere within cgi too, but I'm not sure. Peace, Kalle -- [ kalle@gnupung.net ][ Thought control, brought to you by the WIPO! ] [ http://gnupung.net/ ][ http://anti-dmca.org/ http://eurorights.org/ ] From dsh8290@rit.edu Thu Aug 30 16:43:19 2001 From: dsh8290@rit.edu (dman) Date: Thu, 30 Aug 2001 11:43:19 -0400 Subject: [Tutor] Is Python powerful enough for this? In-Reply-To: <3B8E4794.9988.1181E6F@localhost>; from printers@sendme.cz on Thu, Aug 30, 2001 at 02:03:00PM +0200 References: <3B8E4794.9988.1181E6F@localhost> Message-ID: <20010830114319.B9508@harmony.cs.rit.edu> On Thu, Aug 30, 2001 at 02:03:00PM +0200, A wrote: | Hi, | I have some webpages that contain FORMS. Each form has input | fields and also some hidden fields. | How can I easily get urlencoded string from all these fields | like | Key1=Value1&Key2=Value2&Key3=Value3 You're looking to write some CGI scripts that will receive the form submisison and then process it, right? See the 'cgi' module, it parses the url string for you and provides the data as a dictionary. Really easy to use. http://www.python.org/doc/current/lib/module-cgi.html -D From lkvam@venix.com Thu Aug 30 16:44:38 2001 From: lkvam@venix.com (Lloyd Kvam) Date: Thu, 30 Aug 2001 11:44:38 -0400 Subject: [Tutor] Re: Is Python powerful enough for this? References: <3B8E4794.9988.1181E6F@localhost> Message-ID: <3B8E5F66.8C785DB1@venix.com> Python is a terrific CGI scripting language. Make sure your web server is properly configured for running Python. A good starting point for how to do Python CGI scripts is: http://www.python.org/doc/essays/ppt/sd99east/ A wrote: > > Hi, > I have some webpages that contain FORMS. Each form has input > fields and also some hidden fields. > How can I easily get urlencoded string from all these fields > like > Key1=Value1&Key2=Value2&Key3=Value3 > > For example: > I have a following web page > <html> > > <head> > </head> > <body> > <form method="POST" action="c.cgi"> > <p><input type="text" name="T1" size="20"></p> > <p><input type="checkbox" name="C1" value="ON"></p> > <p><textarea rows="2" name="S1" cols="20"></textarea></p> > <p><input type="submit" value="Submit" name="B1"><input > type="reset" value="Reset" name="B2"></p> > </form> > </body> > </html> > > >From the above > I would like to receive > T1=&S1=&C1=&B1=Submit > > Thank you for help. > Ladislav > _______________________________________________ > ActivePython mailing list > ActivePython@listserv.ActiveState.com > http://listserv.ActiveState.com/mailman/listinfo/activepython -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From uselesspython@yahoo.com Thu Aug 30 16:59:24 2001 From: uselesspython@yahoo.com (Rob) Date: Thu, 30 Aug 2001 10:59:24 -0500 Subject: [Tutor] Is Python powerful enough for this? References: <3B8E4794.9988.1181E6F@localhost> Message-ID: <3B8E62DC.4090305@yahoo.com> A wrote: > Hi, > I have some webpages that contain FORMS. Each form has input > fields and also some hidden fields. > How can I easily get urlencoded string from all these fields > like > Key1=Value1&Key2=Value2&Key3=Value3 > > For example: > I have a following web page > <html> > > <head> > </head> > <body> > <form method="POST" action="c.cgi"> > <p><input type="text" name="T1" size="20"></p> > <p><input type="checkbox" name="C1" value="ON"></p> > <p><textarea rows="2" name="S1" cols="20"></textarea></p> > <p><input type="submit" value="Submit" name="B1"><input > type="reset" value="Reset" name="B2"></p> > </form> > </body> > </html> > >>From the above > I would like to receive > T1=&S1=&C1=&B1=Submit > > > Thank you for help. > Ladislav > I've got an example of one way to do this sort of thing here: http://www.lowerstandard.com/python/uselesspython1.html It's the bottom entry on the page, labeled: "Useless Comment System". It consists of a working example, and you can view all the Python and HTML. Rob -- A {} is a terrible thing to waste. Useless Python! http://www.lowerstandard.com/python From dell2100@prodigy.net Thu Aug 30 18:09:26 2001 From: dell2100@prodigy.net (David L. Lerner) Date: Thu, 30 Aug 2001 13:09:26 -0400 Subject: [Tutor] Why I'm learning Python (OT and long) Message-ID: <002f01c13176$8ea27d00$19e1fcd1@prodigy.net> Hey, I sent a program in to Useless, and I haven't even _started_ on Tk widgets. Can anyone recommend a good Tk widgets tutorial?. >I spent some time reading Useless Python last night and went to bed >totally depressed. I feel that even Useless is above my skill level. >Today I'm going to make one of my useful scripts >run from a Tk button widget. Thank you David L. Lerner dell2100@prodigy.net Often, the most striking and innovative solutions come from realizing that your concept of the problem was wrong. Eric Steven Raymond From bsass@freenet.edmonton.ab.ca Thu Aug 30 18:23:13 2001 From: bsass@freenet.edmonton.ab.ca (Bruce Sass) Date: Thu, 30 Aug 2001 11:23:13 -0600 (MDT) Subject: [OT] BASIC Factoid (was Re: [Tutor] Functions !) In-Reply-To: <31575A892FF6D1118F5800600846864D78C05D@intrepid> Message-ID: <Pine.LNX.4.33.0108301115330.30302-100000@bms> On Thu, 30 Aug 2001, Simon Brunning wrote: > > From: Bruce Sass [SMTP:bsass@freenet.edmonton.ab.ca] > > 2K on the ZX81, unless you bought one of the RAM expanders (16, 32 and > > It was *definitely* only 1K on mine. I ended up getting a 16K Ram pack, but > if I typed too hard, it would wobble, and the ZX81 would crash. I stand corrected, it was only 1k. - Bruce From aschmidt@nv.cc.va.us Thu Aug 30 18:17:11 2001 From: aschmidt@nv.cc.va.us (Schmidt, Allen J.) Date: Thu, 30 Aug 2001 13:17:11 -0400 Subject: [Tutor] Why I'm learning Python (OT and long) Message-ID: <5CDFEBB60E7FD311B9E30000F6D6090608CB8C71@novamail2.nv.cc.va.us> <SNIP> Bill, While reading this, I thought I was reading my own autobiography! Very spooky. I just sort of stumbled into programming (COBOL) from a PC hardware and networking gig. I was a Certified WordPerfect Resource! Impressive, huh? Most don't even remember WP anymore. I knew what EVERY 'F' key did and could walk someone through the screens without even seeing them. Also, when you think about it, Reveal Codes was the same as HTML! I feel like I am stumbling in Python too. I have only learned enough to get me through using small parts of it within Zope. When I really need a small Python program done, I will consult my experts I work with and they build a basic, working structure and I build it out from there. One line at a time. So far so good, but I don't feel I have learned what I need yet. That's it. Just had to comment when I saw the WP reference. Good luck to you! Allen Schmidt Programmer/Analyst Northern Virginia Community College From sheila@thinkspot.net Thu Aug 30 18:33:28 2001 From: sheila@thinkspot.net (Sheila King) Date: Thu, 30 Aug 2001 10:33:28 -0700 Subject: A good Tk widgets tutorial (was: Re: [Tutor] Why I'm learning Python (OT and long)) In-Reply-To: <002f01c13176$8ea27d00$19e1fcd1@prodigy.net> References: <002f01c13176$8ea27d00$19e1fcd1@prodigy.net> Message-ID: <152A35C80829@kserver.org> On Thu, 30 Aug 2001 13:09:26 -0400, "David L. Lerner" <dell2100@prodigy.net> wrote about [Tutor] Why I'm learning Python (OT and long): :Hey, I sent a program in to Useless, and I haven't even _started_ on Tk :widgets. : :Can anyone recommend a good Tk widgets tutorial?. I've looked at (I think) all the Tk tutorials on the web (both of them ;)) and I had Core Python Programming and the Quick Python book (both of which have only a small "intro" chapter on Tkinter). But, when I finally got my copy of Programming Python, ...WOW!. Four whole chapters devoted to Tkinter, and then it weaves its way into much of the rest of the book, as well. And I have to say, the nicest, clearest explanations that *I've* seen on Tkinter. (Granted, I don't have the Grayson book that always seems to get mentioned when someone asks about Tkinter...probably because it is the only book exclusively on the topic of Tkinter. I can't compare that to Programming Python.) Anyhow, that's what helped me finally figure out how to do Tkinter. I have a small app that I'm working on, that has been set aside for a while. But I've even been teaching my son how to do some stuff with Tkinter. -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From sheila@thinkspot.net Thu Aug 30 18:42:30 2001 From: sheila@thinkspot.net (Sheila King) Date: Thu, 30 Aug 2001 10:42:30 -0700 Subject: [Tutor] Why I'm learning Python (OT and long) In-Reply-To: <Pine.GSO.4.21L1.0108300840130.28609-100000@sunny> References: <Pine.GSO.4.21L1.0108300840130.28609-100000@sunny> Message-ID: <15327686230F@kserver.org> On Thu, 30 Aug 2001 10:27:42 -0400 (EDT), Bill Tolbert <bill_tolbert@bigfoot.com> wrote about [Tutor] Why I'm learning Python (OT and long): :Sure I can get by in Access/VB. But I know :Access is kid stuff compared to Oracle and MySQL. I want to write :solutions for non-MS platforms; I want to understand the difference between :bound and unbound methods; I want to understand other people's code; I :want to be Danny Yoo!!! Heh. Who wouldn't want to be Danny Yoo? ;) Just the other night I was saying to my husband, how discouraged I was, because the more I learn, the more I realize that I don't know. I wondered how do people learn all this stuff about how the operating systems work, and file locking and sockets and servers and ... Lots of stuff I'd like to know, but it took me a whole week (with lots of help) to write a file-locking module that works cross-platform on Win32/Unix. (And has only been tested under win98 and Linux.) I know I need to learn some database stuff as well, but SQL seems a bit intimidating. And I don't really have anything to practice on. (Or time to do so, either, it seems.) In my search for code to help me with file locking, I tried reading other people's code and couldn't understand it, either. (That's partly why I write my own. At least I understand my own code!) Here's some code I was looking at today that I COMPLETELY DON'T GET: http://www.sabren.com/code/python/crypt/md5crypt.py (I'm wanting to learn how to do session management and cookies... http://www.cs.virginia.edu/~lab2q/lesson_7/ So what am I saying here? Basically, Bill, you aren't the only one who feels this way. I'm stumbling through, as well. So, hang in there. The best thing about Python, I think, is the supportive community. If you've managed to fool those guys you work with for four years, you must have something going for ya! ;) -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From uselesspython@yahoo.com Thu Aug 30 18:51:26 2001 From: uselesspython@yahoo.com (Rob) Date: Thu, 30 Aug 2001 12:51:26 -0500 Subject: A good Tk widgets tutorial (was: Re: [Tutor] Why I'm learning Python (OT and long)) References: <002f01c13176$8ea27d00$19e1fcd1@prodigy.net> <152A35C80829@kserver.org> Message-ID: <3B8E7D1E.7010002@yahoo.com> Sheila King wrote: > On Thu, 30 Aug 2001 13:09:26 -0400, "David L. Lerner" > <dell2100@prodigy.net> wrote about [Tutor] Why I'm learning Python (OT > and long): > > :Hey, I sent a program in to Useless, and I haven't even _started_ on Tk > :widgets. > : > :Can anyone recommend a good Tk widgets tutorial?. > > I've looked at (I think) all the Tk tutorials on the web > (both of them ;)) > On Useless Python, we have links to a couple of the Tk resources available on the web: http://www.lowerstandard.com/python/tutoriallinks.html I want to say I've found a few more out there that didn't make it to the Useless links pages. Anyone's free to send these handy links in to Useless at any time, by the way. > and I had Core Python Programming and the Quick Python book (both of > which have only a small "intro" chapter on Tkinter). But, when I finally > got my copy of Programming Python, ...WOW!. Four whole chapters devoted > to Tkinter, and then it weaves its way into much of the rest of the > book, as well. And I have to say, the nicest, clearest explanations that > *I've* seen on Tkinter. (Granted, I don't have the Grayson book that > always seems to get mentioned when someone asks about Tkinter...probably > because it is the only book exclusively on the topic of Tkinter. I can't > compare that to Programming Python.) > Teach Yourself Python In 24 Hours (pub. by SAMS) also has a pretty darn nice introduction to Tkinter. It spans a massive percentage of the book. And the upcoming Python How To Program (pub. by Prentice Hall in a few months) has a few fine chapters on the subject as well. And then there are the examples at Useless (as well as the Vaults of Parnassus and the Python Cookbook, I assume). In my *copious free time*, I plan to continue adding small examples of GUI programming in Tkinter, wxPython, Jython/Swing, CGI (yeah, I consider it a GUI, at least in part), etc. to Useless for people to scoff at. Anyone's invited to contribute this sort of thing, as well. I do love having a public place to put examples of working code that doesn't have to be anything in particular. Rob -- A {} is a terrible thing to waste. Useless Python! http://www.lowerstandard.com/python From dyoo@hkn.eecs.berkeley.edu Thu Aug 30 19:29:07 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 30 Aug 2001 11:29:07 -0700 (PDT) Subject: [Tutor] Why I'm learning Python (OT and long) In-Reply-To: <15327686230F@kserver.org> Message-ID: <Pine.LNX.4.21.0108301122350.4302-100000@hkn.eecs.berkeley.edu> On Thu, 30 Aug 2001, Sheila King wrote: > Here's some code I was looking at today that I COMPLETELY DON'T GET: > http://www.sabren.com/code/python/crypt/md5crypt.py Don't worry too much about it --- neither does the author. """ There are actually two versions of crypt() out there. The older one uses DES encryption, and the newer one uses an MD5 hash. I don't really understand either of them. """ http://www.sabren.net/code/python/crypt/ Hmmm. *grin* Anyway, there's a book by Bruce Schneier called "Applied Cryptography" that has a introduction to MD5 hashing: http://www.counterpane.com/applied.html I've only glanced at it, but it looks like good reading. From ignacio@openservices.net Thu Aug 30 19:41:14 2001 From: ignacio@openservices.net (Ignacio Vazquez-Abrams) Date: Thu, 30 Aug 2001 14:41:14 -0400 (EDT) Subject: [Tutor] Why I'm learning Python (OT and long) In-Reply-To: <15327686230F@kserver.org> Message-ID: <Pine.LNX.4.33.0108301428541.29615-100000@terbidium.openservices.net> On Thu, 30 Aug 2001, Sheila King wrote: > Just the other night I was saying to my husband, how discouraged I was, > because the more I learn, the more I realize that I don't know. I > wondered how do people learn all this stuff about how the operating > systems work, and file locking and sockets and servers and ... > Lots of stuff I'd like to know, but it took me a whole week (with lots > of help) to write a file-locking module that works cross-platform on > Win32/Unix. (And has only been tested under win98 and Linux.) The whole OS innards thing can take a LOOOONG time to learn Trust me, I have almost a decade and I still have a lot to learn. > I know I need to learn some database stuff as well, but SQL seems a bit > intimidating. And I don't really have anything to practice on. (Or time > to do so, either, it seems.) It only looks intimidating because it's big. It actually follows certain rules so it's very predictable. Plus, there are many many many tools out there to help you. <plug> If you're using MySQL (http://www.mysql.com/), there is a tool written in PHP called phpMyAdmin (http://sourceforge.net/projects/phpmyadmin/) which will help you use it. It can do almost anything with it. Plus, I've been helping out with it, so it can't be THAT bad ;) Version 2.2.0 is coming out RSN; it's going to be SLICK. </plug> > In my search for code to help me with file locking, I tried reading > other people's code and couldn't understand it, either. (That's partly > why I write my own. At least I understand my own code!) Understanding other people's code only comes after months of working with your own, because you need a point of reference for yourself. > Here's some code I was looking at today that I COMPLETELY DON'T GET: > http://www.sabren.com/code/python/crypt/md5crypt.py > (I'm wanting to learn how to do session management and cookies... > http://www.cs.virginia.edu/~lab2q/lesson_7/ The MD5 message-digest algorithm (RFC 1321, ftp://ftp.isi.edu/in-notes/rfc1321.txt) isn't something that _anybody_ gets; it's enough that it works ;) > So what am I saying here? Basically, Bill, you aren't the only one who > feels this way. I'm stumbling through, as well. So, hang in there. The > best thing about Python, I think, is the supportive community. If you've > managed to fool those guys you work with for four years, you must have > something going for ya! ;) Meh. I think Bill here is just still a little uncomfortable with Python. I remember feeling that way when first starting out with Python (and PHP, and XSLT, etc...) > -- > Sheila King > http://www.thinkspot.net/sheila/ > http://www.k12groups.org/ -- Ignacio Vazquez-Abrams <ignacio@openservices.net> From csmith@blakeschool.org Thu Aug 30 19:42:51 2001 From: csmith@blakeschool.org (Christopher Smith) Date: Thu, 30 Aug 2001 13:42:51 -0500 Subject: [Tutor] Pythonica (symbolic algebra) In-Reply-To: <a0433010bb7b400b92880@[24.30.141.233]> References: <a0433010bb7b400b92880@[24.30.141.233]> Message-ID: <fc.004c4b6b0079a705004c4b6b00799c87.79a726@blakeschool.org> joe@strout.net writes: >At 9:29 AM -0500 8/30/01, Christopher Smith wrote: > >>I've been looking for something like Pythonica...glad I found it! >>Thanks for the work that you've done on this. A few comments >>about it and some bugs have been made on the tutor list: >> >>http://mail.python.org/pipermail/tutor/2001-August/subject.html >> >>Look for the subject line containing "algebraic". > >OK. Please feel free to add to this discussion that I don't use >Python much any more, and am looking for someone to take over >maintenance of Pythonica (including fixing those known bugs). It looks like you had made some significant progress on Python and provided some useful tools (I am using the patched editor, for example). Thank you. Do you have a list of errors that have been reported for Pythonica? I passed along your comments to the tutor and mac lists. /c From joe@strout.net Thu Aug 30 20:11:40 2001 From: joe@strout.net (Joseph J. Strout) Date: Thu, 30 Aug 2001 12:11:40 -0700 Subject: [Tutor] Re: Pythonica (symbolic algebra) In-Reply-To: <fc.004c4b6b0079a705004c4b6b00799c87.79a726@blakeschool.org> References: <a0433010bb7b400b92880@[24.30.141.233]> <fc.004c4b6b0079a705004c4b6b00799c87.79a726@blakeschool.org> Message-ID: <a04330104b7b440541a37@[24.30.141.233]> At 1:42 PM -0500 8/30/01, Christopher Smith wrote: >It looks like you had made some significant progress >on Python and provided some useful tools (I am using >the patched editor, for example). Thank you. Quite happy to have contributed; Python is great (as is the community). >Do you have a list of errors that have been reported for Pythonica? Sorry, I don't. >I passed along your comments to the tutor and mac lists. Thanks, - Joe -- ,------------------------------------------------------------------. | Joseph J. Strout Check out the Mac Web Directory: | | joe@strout.net http://www.macwebdir.com/ | `------------------------------------------------------------------' From vcardon@siue.edu Thu Aug 30 20:53:27 2001 From: vcardon@siue.edu (Victor R. Cardona) Date: Thu, 30 Aug 2001 14:53:27 -0500 Subject: [Tutor] a question regarding os.system() In-Reply-To: <LAW2-OE75LyGqOs28ev00001a83@hotmail.com>; from haiyang_yang@hotmail.com on Thu, Aug 30, 2001 at 03:26:23PM +0900 References: <LAW2-OE75LyGqOs28ev00001a83@hotmail.com> Message-ID: <20010830145327.B30158@client156-52.ll.siue.edu> On Thu, Aug 30, 2001 at 03:26:23PM +0900, Haiyang wrote: > Hi there, > > I know that we can use os.system() to lauch applications. > Say, I want to use notepad to open a file - data.txt > I should do > os.system('notepad data.txt') > > BUT what if the string 'data.txt' is stored in a variable, how can use > notepad to open it? > > file='c:\data\data.txt' > os.system('notepad and What? You could use os.system("notepad %s" % file) HTH, Victor -- Victor R. Cardona 2:52pm up 5 days, 21:23, 2 users, load average: 1.07, 1.03, 1.01 Powered by SuSE Linux 7.1 (i386) 2.4.5-64GB-SMP From mkhan12@kornet.net Fri Aug 31 00:43:12 2001 From: mkhan12@kornet.net (???) Date: Fri, 31 Aug 2001 08:43:12 +0900 Subject: [Tutor] How to change Windows Environment Variable In-Reply-To: <3B8E62DC.4090305@yahoo.com> Message-ID: <IJEELFALFHIMIADKKAPOCELICCAA.mkhan12@kornet.net> RGVhciBhbGwsDQoNCkhvdyB0byBjaGFuZ2UgZW52aXJvbm1lbnQgdmFyaWFibGUgb24gV2luZG93 cyBOVCBvciAyMDAwIGJ5IHB5dGhvbj8NCg0KSW4gVmlzdWFsIEJhc2ljIGNhc2UgY2FuIHNldHRp bmcgYXMgYmVsb3c6DQoNClByaXZhdGUgRGVjbGFyZSBGdW5jdGlvbiBHZXRFbnZpcm9ubWVudFZh cmlhYmxlIExpYiAia2VybmVsMzIiIF8NCiAgICBBbGlhcyAiR2V0RW52aXJvbm1lbnRWYXJpYWJs ZUEiIChCeVZhbCBscE5hbWUgQXMgU3RyaW5nLCBfDQogICAgQnlWYWwgbHBCdWZmZXIgQXMgU3Ry aW5nLCBCeVZhbCBuU2l6ZSBBcyBMb25nKSBBcyBMb25nDQoNClByaXZhdGUgRGVjbGFyZSBGdW5j dGlvbiBTZXRFbnZpcm9ubWVudFZhcmlhYmxlIExpYiAia2VybmVsMzIiIF8NCiAgICBBbGlhcyAi U2V0RW52aXJvbm1lbnRWYXJpYWJsZUEiIChCeVZhbCBscE5hbWUgQXMgU3RyaW5nLCBfDQogICAg QnlWYWwgbHBWYWx1ZSBBcyBTdHJpbmcpIEFzIExvbmcNCg0KSSB3aWxsIHdhaXRpbmcgZm9yIGdv b2QgbmV3cy4NClRoYW5rcy4NCk15ZW9uZ0tpIEhhbg0KLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0t LS0tLS0tLS0tLS0tLS0tLS0tLS0tLQ0KTXllb25nS2kgSGFuIA0KU2VjdGlvbiBNYW5hZ2VyLCBI dWxsIFBhcnQsIENBRCBVbmlmaWNhdGlvbiBUZWFtDQpEQUVXT08gU2hpcGJ1aWxkaW5nICYgTWFy Z2luIEVuZ2luZWVyaW5nIENvLiwgTHRkLg0KMSwgQWp1LURvbmcsIEtvamUtU2ksIEt5dW5nbmFt LCA2NTYtNzE0LCBSZXAuIG9mIEtvcmVhDQpUZWw6ICs4MiA1NSA2ODAgNDAzOSwgICAgRmF4OiAr ODIgNTUgNjgwIDIxNDINCk1vYmlsZTogKzgyIDE3IDg1NyA1ODQ0LCBFLW1haWw6IG1raGFuQGR3 c2hpcC5jb20NCldlYjogaHR0cDovL3d3dy5kYWV3b29zaGlwYnVpbGRpbmcuY28ua3INCg0KLS0t LS1PcmlnaW5hbCBNZXNzYWdlLS0tLS0NCkZyb206IGFjdGl2ZXB5dGhvbi1hZG1pbkBsaXN0c2Vy di5BY3RpdmVTdGF0ZS5jb20gW21haWx0bzphY3RpdmVweXRob24tYWRtaW5AbGlzdHNlcnYuQWN0 aXZlU3RhdGUuY29tXU9uIEJlaGFsZiBPZiBSb2INClNlbnQ6IEZyaWRheSwgQXVndXN0IDMxLCAy MDAxIDEyOjU5IEFNDQpUbzogcHJpbnRlcnNAc2VuZG1lLmN6DQpDYzogcHl0aG9uLWxpc3RAcHl0 aG9uLm9yZzsgYWN0aXZlcHl0aG9uQGxpc3RzZXJ2LkFjdGl2ZVN0YXRlLmNvbTsgdHV0b3JAcHl0 aG9uLm9yZw0KU3ViamVjdDogUmU6IFtUdXRvcl0gSXMgUHl0aG9uIHBvd2VyZnVsIGVub3VnaCBm b3IgdGhpcz8NCg0KQSB3cm90ZToNCg0KPiBIaSwNCj4gSSBoYXZlIHNvbWUgd2VicGFnZXMgdGhh dCBjb250YWluIEZPUk1TLiBFYWNoIGZvcm0gaGFzIGlucHV0DQo+IGZpZWxkcyBhbmQgYWxzbyBz b21lIGhpZGRlbiBmaWVsZHMuDQo+IEhvdyBjYW4gSSBlYXNpbHkgZ2V0IHVybGVuY29kZWQgc3Ry aW5nIGZyb20gYWxsIHRoZXNlIGZpZWxkcw0KPiBsaWtlDQo+IEtleTE9VmFsdWUxJktleTI9VmFs dWUyJktleTM9VmFsdWUzDQo+DQo+IEZvciBleGFtcGxlOg0KPiBJIGhhdmUgYSBmb2xsb3dpbmcg d2ViIHBhZ2UNCj4gPGh0bWw+DQo+DQo+IDxoZWFkPg0KPiA8L2hlYWQ+DQo+IDxib2R5Pg0KPiA8 Zm9ybSBtZXRob2Q9IlBPU1QiIGFjdGlvbj0iYy5jZ2kiPg0KPiAgIDxwPjxpbnB1dCB0eXBlPSJ0 ZXh0IiBuYW1lPSJUMSIgc2l6ZT0iMjAiPjwvcD4NCj4gICA8cD48aW5wdXQgdHlwZT0iY2hlY2ti b3giIG5hbWU9IkMxIiB2YWx1ZT0iT04iPjwvcD4NCj4gICA8cD48dGV4dGFyZWEgcm93cz0iMiIg bmFtZT0iUzEiIGNvbHM9IjIwIj48L3RleHRhcmVhPjwvcD4NCj4gICA8cD48aW5wdXQgdHlwZT0i c3VibWl0IiB2YWx1ZT0iU3VibWl0IiBuYW1lPSJCMSI+PGlucHV0DQo+IHR5cGU9InJlc2V0IiB2 YWx1ZT0iUmVzZXQiIG5hbWU9IkIyIj48L3A+DQo+IDwvZm9ybT4NCj4gPC9ib2R5Pg0KPiA8L2h0 bWw+DQo+DQo+PkZyb20gdGhlIGFib3ZlDQo+IEkgd291bGQgbGlrZSB0byByZWNlaXZlDQo+IFQx PSZTMT0mQzE9JkIxPVN1Ym1pdA0KPg0KPg0KPiBUaGFuayB5b3UgZm9yIGhlbHAuDQo+IExhZGlz bGF2DQo+DQoNCg0KSSd2ZSBnb3QgYW4gZXhhbXBsZSBvZiBvbmUgd2F5IHRvIGRvIHRoaXMgc29y dCBvZiB0aGluZyBoZXJlOg0KDQpodHRwOi8vd3d3Lmxvd2Vyc3RhbmRhcmQuY29tL3B5dGhvbi91 c2VsZXNzcHl0aG9uMS5odG1sDQoNCkl0J3MgdGhlIGJvdHRvbSBlbnRyeSBvbiB0aGUgcGFnZSwg bGFiZWxlZDogIlVzZWxlc3MgQ29tbWVudCBTeXN0ZW0iLiBJdA0KY29uc2lzdHMgb2YgYSB3b3Jr aW5nIGV4YW1wbGUsIGFuZCB5b3UgY2FuIHZpZXcgYWxsIHRoZSBQeXRob24gYW5kIEhUTUwuDQoN ClJvYg0KLS0NCkEge30gaXMgYSB0ZXJyaWJsZSB0aGluZyB0byB3YXN0ZS4NClVzZWxlc3MgUHl0 aG9uIQ0KaHR0cDovL3d3dy5sb3dlcnN0YW5kYXJkLmNvbS9weXRob24NCg0KX19fX19fX19fX19f X19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX18NCkFjdGl2ZVB5dGhvbiBtYWlsaW5n IGxpc3QNCkFjdGl2ZVB5dGhvbkBsaXN0c2Vydi5BY3RpdmVTdGF0ZS5jb20NCmh0dHA6Ly9saXN0 c2Vydi5BY3RpdmVTdGF0ZS5jb20vbWFpbG1hbi9saXN0aW5mby9hY3RpdmVweXRob24gDQo= From ignacio@openservices.net Fri Aug 31 01:14:06 2001 From: ignacio@openservices.net (Ignacio Vazquez-Abrams) Date: Thu, 30 Aug 2001 20:14:06 -0400 (EDT) Subject: [Tutor] Re: How to change Windows Environment Variable In-Reply-To: <IJEELFALFHIMIADKKAPOCELICCAA.mkhan12@kornet.net> Message-ID: <Pine.LNX.4.33.0108302010000.25646-100000@terbidium.openservices.net> On Fri, 31 Aug 2001, ??? wrote: > Dear all, > > How to change environment variable on Windows NT or 2000 by python? > > In Visual Basic case can setting as below: > > Private Declare Function GetEnvironmentVariable Lib "kernel32" _ > Alias "GetEnvironmentVariableA" (ByVal lpName As String, _ > ByVal lpBuffer As String, ByVal nSize As Long) As Long > > Private Declare Function SetEnvironmentVariable Lib "kernel32" _ > Alias "SetEnvironmentVariableA" (ByVal lpName As String, _ > ByVal lpValue As String) As Long > > I will waiting for good news. > Thanks. > MyeongKi Han Good news: There is a GetEnvironmentVariable() function in the win32api module. Bad news: There is no SetEnvironmentVariable() function. Good news: The source code for win32api is available via CVS (http://starship.python.net/crew/mhammond/cvs.html) so you can add the function. Bad News: You'll need Visual Studio 6 to compile it. -- Ignacio Vazquez-Abrams <ignacio@openservices.net> From dsh8290@rit.edu Fri Aug 31 01:17:15 2001 From: dsh8290@rit.edu (dman) Date: Thu, 30 Aug 2001 20:17:15 -0400 Subject: [Tutor] How to change Windows Environment Variable In-Reply-To: <IJEELFALFHIMIADKKAPOCELICCAA.mkhan12@kornet.net>; from mkhan12@kornet.net on Fri, Aug 31, 2001 at 08:43:12AM +0900 References: <3B8E62DC.4090305@yahoo.com> <IJEELFALFHIMIADKKAPOCELICCAA.mkhan12@kornet.net> Message-ID: <20010830201715.A10315@harmony.cs.rit.edu> When you ask a new question, just start a new mail, don't reply to a totally unrelated post. On Fri, Aug 31, 2001 at 08:43:12AM +0900, ??? wrote: | Dear all, | | How to change environment variable on Windows NT or 2000 by python? >>> import os >>> print os.putenv.__doc__ putenv(key, value) -> None Change or add an environment variable. >>> You want os.putenv. Note that it only affects the python process, not any parent processes (ie a shell). HTH, -D From SBrunning@trisystems.co.uk Fri Aug 31 10:59:47 2001 From: SBrunning@trisystems.co.uk (Simon Brunning) Date: Fri, 31 Aug 2001 10:59:47 +0100 Subject: A good Tk widgets tutorial (was: Re: [Tutor] Why I'm learning Python (OT and long)) Message-ID: <31575A892FF6D1118F5800600846864D78C081@intrepid> > From: Sheila King [SMTP:sheila@thinkspot.net] > and I had Core Python Programming and the Quick Python book (both of > which have only a small "intro" chapter on Tkinter). But, when I finally > got my copy of Programming Python, ...WOW!. Four whole chapters devoted > to Tkinter, and then it weaves its way into much of the rest of the > book, as well. And I have to say, the nicest, clearest explanations that > *I've* seen on Tkinter. (Granted, I don't have the Grayson book that > always seems to get mentioned when someone asks about Tkinter...probably > because it is the only book exclusively on the topic of Tkinter. I can't > compare that to Programming Python.) Seconded. FWIW, I got the Greyson book first, and I couldn't make head nor tail of it. After reading Programming Python, and having a play[1], I got that hang of basic Tkinter programming, *then* the Greyson book made sense. It's got lots of good staff in it, towards the advanced end. Also, the Tkinter and PMW reference is good to have to hand. Seems to me that the Greyson book would be good if you already know how GUI programming works, and want to learn how to do it using Python and Tkinter. Programming Python works even if you've never programmed a GUI before. Cheers, Simon Brunning TriSystems Ltd. sbrunning@trisystems.co.uk [1] BTW, don't underestimate the importance of playing. Play a *lot*. ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From Charlie@begeistert.org Fri Aug 31 11:16:25 2001 From: Charlie@begeistert.org (Charlie Clark) Date: Fri, 31 Aug 2001 12:16:25 +0200 Subject: [Tutor] Help with cgi Message-ID: <999252985_PM_BeOS.Charlie@begeistert.org> Dear all, is there a quick and easy way to deal with *all* the name/value pairs in a form? Charlie From python.tutorial@jarava.org Fri Aug 31 11:20:34 2001 From: python.tutorial@jarava.org (Javier JJ) Date: Fri, 31 Aug 2001 12:20:34 +0200 Subject: [Tutor] Why I'm learning Python (OT and long) References: <Pine.GSO.4.21L1.0108300840130.28609-100000@sunny> <15327686230F@kserver.org> Message-ID: <004c01c13206$929adde0$0124a8c0@uno> > On Thu, 30 Aug 2001 10:27:42 -0400 (EDT), Bill Tolbert > <bill_tolbert@bigfoot.com> wrote about [Tutor] Why I'm learning Python > (OT and long): > > :Sure I can get by in Access/VB. But I know > :Access is kid stuff compared to Oracle and MySQL. I want to write > :solutions for non-MS platforms; I want to understand the difference between > :bound and unbound methods; I want to understand other people's code; I > :want to be Danny Yoo!!! > > Heh. Who wouldn't want to be Danny Yoo? ;) > > Just the other night I was saying to my husband, how discouraged I was, > because the more I learn, the more I realize that I don't know. I > wondered how do people learn all this stuff about how the operating > systems work, and file locking and sockets and servers and ... Well... I'd say you learn it bit by bit. The important thing (IMO), is not so much as to know "lots and lots", but much more important is to be aware of your limits. I am an student of Engineering (OK, so we do have to use computers, in some classes... but we only have I Pascal programming course in the whole 6 years), and I kind of enjoy "tinkering" in PCs... I was quite a WPerfect wizz on its day, and I could (kind of) make MS-DOS sit up and beg. Then came Win95, and I started to feel how much I didn't know... and when I discovered "real" OSs (Server OS, multi-user, etc, like Win2000, Linux...) I started to feel I don't know _anything_... but you go on picking bits and pieces, and going on. Now I _know_ there are plenty of things I _think_ I should know to be proficient as a "computer" or "programmer" guy... but it turns out I'm the one to whom almost everybody around me turns for advice!!. I know a number of people who know lots more than I do, so I was quite amazed that people would ask me (I mean, why use a spoonful of knoweldge if you can go to the fountain), so I asked... and I was told that it's the "attitude" that matters. I may not know a lot, or to be precise I might not think I know enough... but as long as you've been "at this" for some time, and interested in learning (_that's_ the key issue), you end up knowing more than most people... and the fact that you don't believe yourself to know too much, means that you'll probably be better at it (even in the things you think you're not ready to handle, because you'll do all you can to learn), that those who are packing a few "certs" from MS and the like and believe they know it all :-)) So take things bit by bit, learn as you need... and don't let the sheer size of all you *might* learn stop you from enjoying what you _do_ learn. After all, _nobody_ knows everything about computers nowadays... as nobody knows all about physics, or about Biology, or.... but the "catch" is that too many people still believe that if you know something about a computer system, you have to know everything about all of them, and assorted periferials (not kidding; once I was in a temp. job, and one of the employees there got quite crossed 'cause I couldn't fix his printer; he said that if I "knew" computers, I ought to know that! :-) My $ 0,0002 Javier > Lots of stuff I'd like to know, but it took me a whole week (with lots > of help) to write a file-locking module that works cross-platform on > Win32/Unix. (And has only been tested under win98 and Linux.) > > I know I need to learn some database stuff as well, but SQL seems a bit > intimidating. And I don't really have anything to practice on. (Or time > to do so, either, it seems.) > > In my search for code to help me with file locking, I tried reading > other people's code and couldn't understand it, either. (That's partly > why I write my own. At least I understand my own code!) > > Here's some code I was looking at today that I COMPLETELY DON'T GET: > http://www.sabren.com/code/python/crypt/md5crypt.py > (I'm wanting to learn how to do session management and cookies... > http://www.cs.virginia.edu/~lab2q/lesson_7/ > > So what am I saying here? Basically, Bill, you aren't the only one who > feels this way. I'm stumbling through, as well. So, hang in there. The > best thing about Python, I think, is the supportive community. If you've > managed to fool those guys you work with for four years, you must have > something going for ya! ;) > > -- > Sheila King > http://www.thinkspot.net/sheila/ > http://www.k12groups.org/ > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From kalle@gnupung.net Fri Aug 31 11:40:44 2001 From: kalle@gnupung.net (Kalle Svensson) Date: Fri, 31 Aug 2001 12:40:44 +0200 Subject: [Tutor] Help with cgi In-Reply-To: <999252985_PM_BeOS.Charlie@begeistert.org>; from Charlie@begeistert.org on Fri, Aug 31, 2001 at 12:16:25PM +0200 References: <999252985_PM_BeOS.Charlie@begeistert.org> Message-ID: <20010831124044.A31547@gandalf> [Charlie Clark] > Dear all, > > is there a quick and easy way to deal with *all* the name/value pairs in > a form? Quick and untested: form = cgi.FieldStorage() for key in form.keys(): dosomething(key, form[key].value) Peace, Kalle -- [ kalle@gnupung.net ][ Thought control, brought to you by the WIPO! ] [ http://gnupung.net/ ][ http://anti-dmca.org/ http://eurorights.org/ ] From GADGILP@INFOTECH.ICICI.com Fri Aug 31 12:21:30 2001 From: GADGILP@INFOTECH.ICICI.com (GADGIL PRASAD /INFRA/INFOTECH) Date: Fri, 31 Aug 2001 16:51:30 +0530 Subject: [Tutor] [OT? -URGENT] how to tell a tcl/tk prog abt the installed tcl/tk8 .3 in python2.0 on windowsNT ? Message-ID: <E1B786DCFA6ED511A0390008C7289E47634F34@ICICIBACK3> This message is in MIME format. Since your mail reader does not understand this format, some or all of this message may not be legible. ------_=_NextPart_001_01C1320F.150C7240 Content-Type: text/plain; charset="iso-8859-1" hi, Need to get a visual regex builder working... it's written tcl/tk. It's a single 50k tcl prog file. I need to pass it to 'wish'. There is no wish or any other interpreter exe in tcl or tk subdirectory of python 2.0 install on windows. what should I do? do I need to download and install the entire tcl ? /prasad . -- "This e-mail message may contain confidential, proprietary or legally privileged information. It should not be used by anyone who is not the original intended recipient. If you have erroneously received this message, please delete it immediately and notify the sender. The recipient acknowledges that ICICI or its subsidiaries and associated companies (including ICICI Bank) "ICICI Group", are unable to exercise control or ensure or guarantee the integrity of/over the contents of the information contained in e-mail transmissions and further acknowledges that any views expressed in this message are those of the individual sender and no binding nature of the message shall be implied or assumed unless the sender does so expressly with due authority of ICICI Group. Before opening any attachments please check them for viruses and defects." ------_=_NextPart_001_01C1320F.150C7240 Content-Type: text/html; charset="iso-8859-1" <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN"> <HTML> <HEAD> <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1"> <META NAME="Generator" CONTENT="MS Exchange Server version 5.5.2653.12"> <TITLE>[OT? -URGENT] how to tell a tcl/tk prog abt the installed tcl/tk8.3 in python2.0 on windowsNT ?

    hi,

    Need to get a visual regex builder working... it's written tcl/tk.
    It's a single 50k tcl prog file. I need to pass it to 'wish'.
    There is no wish or any other interpreter exe in tcl or tk subdirectory
    of python 2.0 install on windows.

    what should I do? do I need to download and install the entire tcl ?

    /prasad


    ..

    "This e-mail message may contain confidential, proprietary or legally privileged information. It should not be used by anyone who is not the original intended recipient. If you have erroneously received this message, please delete it immediately and notify the sender. The recipient acknowledges that ICICI or its subsidiaries and associated companies (including ICICI Bank) "ICICI Group", are unable to exercise control or ensure or guarantee the integrity of/over the contents of the information contained in e-mail transmissions and further acknowledges that any views expressed in this message are those of the individual sender and no binding nature of the message shall be implied or assumed unless the sender does so expressly with due authority of ICICI Group. Before opening any attachments please check them for viruses and defects."

    ------_=_NextPart_001_01C1320F.150C7240-- From curtishorn@home.com Fri Aug 31 12:28:59 2001 From: curtishorn@home.com (curtis horn) Date: Fri, 31 Aug 2001 04:28:59 -0700 Subject: Fwd: Re: [Tutor] Why I'm learning Python (OT and long) Message-ID: <5.1.0.14.0.20010831042756.029d3390@mail> Ooops sent this to author and not list: >2 things helped me allot in the beginning: > >http://www.amazon.com/exec/obidos/ASIN/0201709384/qid%3D999222727/102-2476128-5486528 > >and: > >http://www.amazon.com/exec/obidos/ASIN/0672318539/qid=999222803/sr=2-1/102-2476128-5486528 > >Once I "got" object oriented programming I reread Alan's book then started >over with all the rest (about 5 also) and felt I understood MUCH >better. Don't know if this is a common sticking point, but understanding >what OO is really about helped me tremendously. Now I'm looking for a >cheap laptop so I can practice coding wherever I am :) > > >..................Curtis > > > >At 10:27 AM 8/30/01 -0400, you wrote: >>I spent some time reading Useless Python last night and went to bed >>totally depressed. I feel that even Useless is above my skill level. So, >>what follows is the story of why I'm trying to learn Python. Perhaps some >>will understand; some may be in a similar situation; some may want to send >>me money. Maybe it can become an installment for the soapbox on Useless. >> >>====================================================== >> >>So here I sit, pretending that I know a little something about >>Python. I own 5 Python books; I have been attempting to program in Python >>for over a year; my title is something like "systems analyst"; I have a >>wife, many children and a dog. Allow me to explain how this >>all happened... >> >>I never pretended to be a programmer. I was trained to do public health >>research. But, the tight job market of recent years forced me to take on >>various computer tasks in the course of my research. It started with >>WordPerfect. I was something of a WordPerfect wonder kid. I could somehow >>do anything in WordPerfect. Looking back, I guess this was my first >>programming - WordPerfect macros. I just grokked other macros and read the >>help files. Massively complicated mail merges, text manipulation, complex >>and tedious tasks rendered trivial in the wake of my macros. I began to >>build solutions for the secretaries, co-workers, people on the street. >>Then M$ began pushing that third-rate wannabe word processor of theirs and >>nothing was ever the same. >> >>So, I sorta learned MS Access the same way. Of course I knew Access was >>just a desktop database. But it was fine around the office. I wrote a few >>simple applications, and that was fine; after all, I'm a researcher not a >>programmer. But guess what? People started coming to be with requests for >>Access applications. And before I knew it, I was writing a very complex >>accounting system for my employer. I was being labeled, and I knew it. I >>tried to resist but it was futile. I thought long and hard about going >>back to school for a PhD in epidemiology; I was trying to escape becoming >>a programmer. All the while there were bills to pay and groceries to buy >>and mouths to feed. I didn't have time go back to school. I couldn't afford >>it. And then one day I was offered a real job as a programmer... >> >>Some folks in the private research world had decided to build a large >>system in Access. I was doing some part time work for this company because >>as a university employee, I couldn't make ends meet. They knew me as a >>WordPerfect and Access guy, and asked me to join the project full time. I >>was flattered but declined; after all, I'm a researcher not a >>programmer. I told them repeatedly "I'm not a programmer". But they >>were desperate. I knew they were desperate. I was the only person >>they could find. And even though the university didn't pay very >>well, I still loved my job there. So one day they asked, "What >>would it take?". Have you ever been asked that question? I was 29 >>years old and driving a worn out car I paid 450 dollars for. Three >>kids. Working a full time job and a part time job. So, I told them >>what it would take and they said ok. Of course my wife was >>happy. This meant financial freedom. Perhaps we could have a >>normal life. But I was afraid. The day would come when they would >>learn the truth and I would be thrown out like the pitiful code I >>write. >> >>Well, it's been nearly four years and I haven't been thrown out yet. I was >>assigned the title systems analyst by the people who were in charge of >>making up the business cards. I guess I've fooled them so far. But I >>haven't fooled myself. Sure I can get by in Access/VB. But I know >>Access is kid stuff compared to Oracle and MySQL. I want to write >>solutions for non-MS platforms; I want to understand the difference between >>bound and unbound methods; I want to understand other people's code; I >>want to be Danny Yoo!!! >> >>So that's why I'm trying to learn Python. To bring legitimacy to an >>otherwise illegitimate career. >> >>Some of my Python scripts seem ok. They do useful work on a daily basis. >>And yet, even a blind squirrel finds a nut sometimes. I'm plagued by the >>feeling that I am a blind squirrel. >> >>Thanks folks. This has been therapeutic. Python people are the best and >>this list is fantastic. Today I'm going to make one of my useful scripts >>run from a Tk button widget. And I'll stumble through. Perhaps I'll get >>lucky and find a nut. >> >>Bill >> >> >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor From dsh8290@rit.edu Fri Aug 31 17:01:15 2001 From: dsh8290@rit.edu (dman) Date: Fri, 31 Aug 2001 12:01:15 -0400 Subject: [Tutor] Why I'm learning Python (OT and long) In-Reply-To: ; from bill_tolbert@bigfoot.com on Thu, Aug 30, 2001 at 10:27:42AM -0400 References: Message-ID: <20010831120115.H10562@harmony.cs.rit.edu> On Thu, Aug 30, 2001 at 10:27:42AM -0400, Bill Tolbert wrote: | I spent some time reading Useless Python last night and went to bed | totally depressed. I feel that even Useless is above my skill level. So, | what follows is the story of why I'm trying to learn Python. Perhaps some | will understand; some may be in a similar situation; some may want to send | me money. Maybe it can become an installment for the soapbox on Useless. [...] As Javier said, you learn it little by little. You read docs, you experiement, and practice and you end up knowing the stuff that is interesting to you. None of us know everything. In fact, computers and software are so complex nowadays that nobody can ever know everything about any given system, and certainly not everything about all (or even several) systems. Just keep on working and learning things as you go. Study the things that you find interesting. You can learn a lot on the web or mailing lists like this, and even discuss the exact issue you are having difficulty with. If you want to learn SQL, get a Linux sytem and try out PostgreSQL or MySQL. (I don't think they are availble for Windows, but they are Free). Then you can tinker with it with no fear of losing data (only store data you want to tinker with and don't care if you accidentally destroy it). Get the manuals and tutorials and work it one step of the way. Find something the you think would be useful and try and get it to work. For example, take some snippet of a database that you work with at work and try toying with it in a SQL database. There are even python bindings for PostgreSQL and MySQL. Little by little you'll start to understand it. I read/skimmed through the Postgres docs, and I understand very little right now. However I know where I would start if I had a need (or stronger desire) to learn SQL. Whenever you sit back and think of all the things that various gurus who have had formal training and decades of experience know you will invariably realize that there is lots you don't know. However if you consider the things you do know that the "average" person doesn't, you will realize that it is significant. The ability to read docs and learn (by trial and error usually) goes a long way to increasing your knowledge and experience in incremental steps. If you have some python code that you think could be designed better don't hesitate to share it and illicit other people's opinions and styles. (Unless you signed some sort of NDA regarding it ;-)). -D From uselesspython@yahoo.com Fri Aug 31 17:21:45 2001 From: uselesspython@yahoo.com (Rob) Date: Fri, 31 Aug 2001 11:21:45 -0500 Subject: [Tutor] Why I'm learning Python (OT and long) References: <20010831120115.H10562@harmony.cs.rit.edu> Message-ID: <3B8FB999.8050100@yahoo.com> dman wrote: > On Thu, Aug 30, 2001 at 10:27:42AM -0400, Bill Tolbert wrote: > | I spent some time reading Useless Python last night and went to bed > | totally depressed. I feel that even Useless is above my skill level. So, > | what follows is the story of why I'm trying to learn Python. Perhaps some > | will understand; some may be in a similar situation; some may want to send > | me money. Maybe it can become an installment for the soapbox on Useless. > [...] > > As Javier said, you learn it little by little. You read docs, you > experiement, and practice and you end up knowing the stuff that is > interesting to you. None of us know everything. In fact, computers > and software are so complex nowadays that nobody can ever know > everything about any given system, and certainly not everything about > all (or even several) systems. Just keep on working and learning > things as you go. Study the things that you find interesting. You > can learn a lot on the web or mailing lists like this, and even > discuss the exact issue you are having difficulty with. > > If you want to learn SQL, get a Linux sytem and try out PostgreSQL or > MySQL. (I don't think they are availble for Windows, but they are > Free). I recently managed to get mySQL installed (painlessly, to my surprise) on Win 98 SE and on Win2K. The Win98 SE box had to be rebooted several times per day of mySQL use, which isn't surprising (since 98 was designed with home users in mind), but this was really not a problem. > Then you can tinker with it with no fear of losing data (only > store data you want to tinker with and don't care if you accidentally > destroy it). Get the manuals and tutorials and work it one step of > the way. Find something the you think would be useful and try and get > it to work. For example, take some snippet of a database that you > work with at work and try toying with it in a SQL database. There are > even python bindings for PostgreSQL and MySQL. Little by little > you'll start to understand it. I read/skimmed through the Postgres > docs, and I understand very little right now. However I know where I > would start if I had a need (or stronger desire) to learn SQL. > One good way to learn some SQL is to let Access help you out. Access 2000 (not sure about earlier Access versions) uses a fairly standard set of SQL language. You can take the queries you created in Access, and choose to view them in *SQL View* (or something like that). Look at the SQL statements Access generated from your queries, and try to determine which parts mean what. This should prove easier than it even sounds. devshed.com and a host of other sites on the web have good SQL and mySQL tutorials and references available. It's a short-ish hop from there to using Python to interface with your SQL database. > Whenever you sit back and think of all the things that various gurus > who have had formal training and decades of experience know you will > invariably realize that there is lots you don't know. However if you > consider the things you do know that the "average" person doesn't, you > will realize that it is significant. The ability to read docs and > learn (by trial and error usually) goes a long way to increasing your > knowledge and experience in incremental steps. > > If you have some python code that you think could be designed better > don't hesitate to share it and illicit other people's opinions and > styles. (Unless you signed some sort of NDA regarding it ;-)). > > -D > Rob -- A {} is a terrible thing to waste. Useless Python! http://www.lowerstandard.com/python From epoch7@charter.net Fri Aug 31 17:51:33 2001 From: epoch7@charter.net (epoch7) Date: Fri, 31 Aug 2001 12:51:33 -0400 Subject: [Tutor] Thank you for all your help. Message-ID: <000a01c1323d$30e9ff40$92b1f018@p3550> I thought it would be nice of me to post my program that all of you helped me write. Maybe you won't have to write one now! I'm a big believer in doing something right once, so other don't have to :) I added comments in it for all the other newbies out there like me :) ---------------------------- ###################### # URL Smasher # # by # # Will Olbrys # # completed 8/29/2001 # #This program eats up #urls out of html source(or anywhere #for that matter and spits them #back out with a specific port #attached if you want. ###################### import re import string import os file1 = raw_input("Name of file to convert: ") file2 = raw_input("Name of file to output to: ") in_file = open(file1, "r") out_file = open(file2, "w") temp_file = open("temp", "w") file_text = in_file.read() regex = re.compile('url=(.*)&') #This line tells how to find the url. in this case, in between 'url=' and &' matches = regex.findall(file_text) temp_file.write(string.join(matches,"\n")) in_file.close() temp_file.close() temp_file = open("temp", "r") file_text = temp_file.read() out_file.write(string.replace(file_text,'com','com:8045')) #the previous lineadds a port to it, if you dont want to add a port then change com:8045 to com #or whatever depending on how the name address ends. temp_file.close() out_file.close() os.remove("temp") From urnerk@qwest.net Fri Aug 31 17:52:03 2001 From: urnerk@qwest.net (Kirby Urner) Date: Fri, 31 Aug 2001 09:52:03 -0700 Subject: [Tutor] MySQL for Windows In-Reply-To: <20010831120115.H10562@harmony.cs.rit.edu> References: Message-ID: <4.2.0.58.20010831094330.00bbf760@pop3.norton.antivirus> >If you want to learn SQL, get a Linux sytem and try >out PostgreSQL or MySQL. (I don't think they are availble for >Windows, but they are Free). Note: MySQL *is* available for Windows, including 95/98/Me (i.e. not just NT). I have MySQL on my Windows box and have successfully used in with Python. Windows 95/98/Me users might also want to check out Savant as a personal web server (free), for playing around with Python cgi etc. (I don't recommend serving on the open internet with these insecure OSes). I find Savant cleaner and easier the PWS 4.0 (personal web server), which 95/98/Me users can extract from one of the NT service packs (see MSFT website) for free (and IIS costs of course). PWS has some install glitches in ME especially. SQL by itself doesn't require Python of course and many MSFT/Windows products use it in some way, often a variant or dialect. Kirby From aschmidt@nv.cc.va.us Fri Aug 31 17:58:20 2001 From: aschmidt@nv.cc.va.us (Schmidt, Allen J.) Date: Fri, 31 Aug 2001 12:58:20 -0400 Subject: [Tutor] MySQL for Windows Message-ID: <5CDFEBB60E7FD311B9E30000F6D6090608CB8C7C@novamail2.nv.cc.va.us> A great PC based tool I found for MySQL is called mysqlfront. Wonderful! ...and free! And if you use the MyODBC part also, another very handy ODBC-anything tool is called AQT - Advanced Query Tool. It costs a few bucks but WELL worth it. The combo of the two tools makes working with MySQL a pleasure. MySQL plays very nicely with Zope too. $.02 Allen -----Original Message----- From: Kirby Urner [mailto:urnerk@qwest.net] Sent: Friday, August 31, 2001 12:52 PM To: tutor@python.org Subject: [Tutor] MySQL for Windows >If you want to learn SQL, get a Linux sytem and try >out PostgreSQL or MySQL. (I don't think they are availble for >Windows, but they are Free). Note: MySQL *is* available for Windows, including 95/98/Me (i.e. not just NT). I have MySQL on my Windows box and have successfully used in with Python. Windows 95/98/Me users might also want to check out Savant as a personal web server (free), for playing around with Python cgi etc. (I don't recommend serving on the open internet with these insecure OSes). I find Savant cleaner and easier the PWS 4.0 (personal web server), which 95/98/Me users can extract from one of the NT service packs (see MSFT website) for free (and IIS costs of course). PWS has some install glitches in ME especially. SQL by itself doesn't require Python of course and many MSFT/Windows products use it in some way, often a variant or dialect. Kirby _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From dsh8290@rit.edu Fri Aug 31 18:10:41 2001 From: dsh8290@rit.edu (dman) Date: Fri, 31 Aug 2001 13:10:41 -0400 Subject: [Tutor] Apache (was MySQL) for Windows In-Reply-To: <4.2.0.58.20010831094330.00bbf760@pop3.norton.antivirus>; from urnerk@qwest.net on Fri, Aug 31, 2001 at 09:52:03AM -0700 References: <20010831120115.H10562@harmony.cs.rit.edu> <4.2.0.58.20010831094330.00bbf760@pop3.norton.antivirus> Message-ID: <20010831131041.B10781@harmony.cs.rit.edu> On Fri, Aug 31, 2001 at 09:52:03AM -0700, Kirby Urner wrote: | | >If you want to learn SQL, get a Linux sytem and try | >out PostgreSQL or MySQL. (I don't think they are availble for | >Windows, but they are Free). | | Note: MySQL *is* available for Windows, including | 95/98/Me (i.e. not just NT). I have MySQL on my | Windows box and have successfully used in with | Python. Ok, MySQL is available for windows. Linux is still a good platform to get :-). | Windows 95/98/Me users might also want to check out | Savant as a personal web server (free), for playing | around with Python cgi etc. (I don't recommend serving | on the open internet with these insecure OSes). FWIW Apache is also available for windows. I had set it up once (win98) but didn't do much with it. I think it may require cygwin, but I'm not sure (it can be run from inetd if you do have cygwin though). | SQL by itself doesn't require Python of course and many | MSFT/Windows products use it in some way, often a | variant or dialect. Right, PostgreSQL comes with a little app called 'psql' which is a shell that can be used to practice SQL commands. -D From sheila@thinkspot.net Fri Aug 31 18:21:01 2001 From: sheila@thinkspot.net (Sheila King) Date: Fri, 31 Aug 2001 10:21:01 -0700 Subject: [Tutor] Apache (was MySQL) for Windows References: <20010831120115.H10562@harmony.cs.rit.edu> <4.2.0.58.20010831094330.00bbf760@pop3.norton.antivirus> <20010831131041.B10781@harmony.cs.rit.ed Message-ID: u> In-Reply-To: <20010831131041.B10781@harmony.cs.rit.edu> X-Mailer: Forte Agent 1.8/32.548 MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit Message-ID: <7337DE4933@kserver.org> On Fri, 31 Aug 2001 13:10:41 -0400, dman wrote about Re: [Tutor] Apache (was MySQL) for Windows: :FWIW Apache is also available for windows. I had set it up once :(win98) but didn't do much with it. I think it may require cygwin, :but I'm not sure (it can be run from inetd if you do have cygwin :though). Apache for windows does not require cygwin. I have it set up on my Win98 machine (I use it for testing my website before I FTP it over to my web host--especially the cgi scripts). It comes with the usual windows installer and everything is pretty easy. -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From urnerk@qwest.net Fri Aug 31 15:58:37 2001 From: urnerk@qwest.net (Kirby Urner) Date: Fri, 31 Aug 2001 10:58:37 -0400 Subject: [Tutor] Is Python powerful enough for this? In-Reply-To: <3B8E4794.9988.1181E6F@localhost> References: <3B8E4794.9988.1181E6F@localhost> Message-ID: <01083110583700.02044@ktu> The POST method itself creates the urlencoded string and sets the environment variable CONTENT_LENGTH to the length of this string. The string itself is sent via standard input, not as part of the URL itself, as in GET. The job, then, is to get the name/value pairs back out from the string, which is something the cgi module will do for you. Others have mentioned FieldStorage(). There's also cgi.parse(). Here's a cgi script set up to handle the example HTML you posted: ============================== #!/usr/local/bin/python import cgi import sys import traceback sys.stderr = sys.stdout print "Content-Type: text/html\n" try: print """ Feedback \n""" vars = cgi.parse() for i in vars.keys(): # or just 'in vars' in 2.2+ print "

    Name: %s Value: %s

    " % (i,vars[i]) print """ """ except: print "\n\n
    "
          traceback.print_exc()
          print "\n
    " ЖЖЖ ============================== Note the trick of putting debugging code at the end. This helps you initially when trying to figure out why a script fails. You can strip this stuff out later (see what happens if you divide by 0 in the try block -- the browser will give you Python's informative error message instead of some useless "internal error" message). Minor footnote: dictionaries before Python 2.2 weren't iterable directly; you had to go for i in mydict.keys(): But now dictionaries are directly iterable, so you can just go for i in mydict: Kirby On Thursday 30 August 2001 08:03, A wrote: > Hi, > I have some webpages that contain FORMS. Each form has input > fields and also some hidden fields. > How can I easily get urlencoded string from all these fields > like > Key1=Value1&Key2=Value2&Key3=Value3 > > For example: > I have a following web page > > > > > > >

    >

    >

    >

    type="reset" value="Reset" name="B2">

    > > > > > From the above > I would like to receive > T1=&S1=&C1=&B1=Submit > > > Thank you for help. > Ladislav > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From dyoo@hkn.eecs.berkeley.edu Fri Aug 31 19:28:06 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 31 Aug 2001 11:28:06 -0700 (PDT) Subject: [Tutor] [OT? -URGENT] how to tell a tcl/tk prog abt the installed tcl/tk8 .3 in python2.0 on windowsNT ? In-Reply-To: Message-ID: On Fri, 31 Aug 2001, GADGIL PRASAD /INFRA/INFOTECH wrote: > Need to get a visual regex builder working... it's written tcl/tk. > It's a single 50k tcl prog file. I need to pass it to 'wish'. > There is no wish or any other interpreter exe in tcl or tk subdirectory > of python 2.0 install on windows. The Tk stuff packaged with Python isn't quite complete --- it's only there to support the Tkinter gui interface --- so you might not be able to get the regex builder to working with it. Try installing the Tk/Tcl interpreter at: http://www.scriptics.com/ Good luck! From curtishorn@home.com Fri Aug 31 20:09:25 2001 From: curtishorn@home.com (curtis horn) Date: Fri, 31 Aug 2001 12:09:25 -0700 Subject: [Tutor] MySQL for Windows In-Reply-To: <4.2.0.58.20010831094330.00bbf760@pop3.norton.antivirus> References: <20010831120115.H10562@harmony.cs.rit.edu> Message-ID: <5.1.0.14.0.20010831120825.00ab6ec0@mail> This is where I went when I was taking my first tentative steps, into learning SQL: http://www.sqlcourse.com/ I highly recommend it. Curtis At 09:52 AM 8/31/01 -0700, Kirby Urner wrote: >>If you want to learn SQL, get a Linux sytem and try >>out PostgreSQL or MySQL. (I don't think they are availble for >>Windows, but they are Free). > >Note: MySQL *is* available for Windows, including >95/98/Me (i.e. not just NT). I have MySQL on my >Windows box and have successfully used in with >Python. > >Windows 95/98/Me users might also want to check out >Savant as a personal web server (free), for playing >around with Python cgi etc. (I don't recommend serving >on the open internet with these insecure OSes). > >I find Savant cleaner and easier the PWS 4.0 (personal >web server), which 95/98/Me users can extract from one >of the NT service packs (see MSFT website) for free >(and IIS costs of course). PWS has some install glitches >in ME especially. > >SQL by itself doesn't require Python of course and many >MSFT/Windows products use it in some way, often a >variant or dialect. > >Kirby > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From droux@tuks.co.za Wed Aug 8 20:36:24 2001 From: droux@tuks.co.za (Danie Roux) Date: Wed, 8 Aug 2001 21:36:24 +0200 Subject: [Tutor] gdbm and locking Message-ID: <20010808213624.A3982@maple.up.ac.za> Can I trust on Python/OS to ensure proper locking for gdbm databases? If two programs is trying to write at the same time, will the data still be valid? Thank you! -- Danie Roux *shuffle* Adore Unix From rob@jam.rr.com Mon Aug 13 22:52:31 2001 From: rob@jam.rr.com (Rob Andrews) Date: Mon, 13 Aug 2001 16:52:31 -0500 Subject: [Tutor] Threads References: <3B785873.12539.9AFE1@localhost> Message-ID: <3B784C1F.74921BD0@jam.rr.com> A wrote: > > Hi, > > I am a newbie with Python.I want to use threads in my application. > Can you please let me know what is the best way of programming > threads under Win32 systems? > What modules shall I use? > Is it better to use the thread module or the threading module or the > stackless Python? What are differences? > Can you please give any example? > Take a look at these modules: -threading -thread You can find out about them here: http://www.python.org/doc/current/modindex.html Threads are discussed in some detail in *Programming Python, 2nd ed.* and in *Core Python Programming*, as well. Rob -- A {} is a terrible thing to waste. Useless Python! http://www.lowerstandard.com/python _______________________________________________ ActivePython mailing list ActivePython@listserv.ActiveState.com http://listserv.ActiveState.com/mailman/listinfo/activepython From printers@sendme.cz Mon Aug 13 21:45:07 2001 From: printers@sendme.cz (A) Date: Mon, 13 Aug 2001 22:45:07 +0200 Subject: [Tutor] Threads Message-ID: <3B785873.12539.9AFE1@localhost> Hi, I am a newbie with Python.I want to use threads in my application. Can you please let me know what is the best way of programming threads under Win32 systems? What modules shall I use? Is it better to use the thread module or the threading module or the stackless Python? What are differences? Can you please give any example? Thanks for help. Ladislav _______________________________________________ ActivePython mailing list ActivePython@listserv.ActiveState.com http://listserv.ActiveState.com/mailman/listinfo/activepython From ignacio@openservices.net Tue Aug 28 14:39:20 2001 From: ignacio@openservices.net (Ignacio Vazquez-Abrams) Date: Tue, 28 Aug 2001 09:39:20 -0400 (EDT) Subject: [Tutor] Questions about threads In-Reply-To: <3B8BA84E.12547.1408A1A@localhost> Message-ID: On Tue, 28 Aug 2001, A wrote: > Hi, > Can anybody please answer my questions? > > 1. In my application I need one function to run in threads. The > number of threads is chosen by user and numbers of threads can > not be higher at one time. > This function writes to a file also.How can I prevent other threads > from writting to this file when the file is open by another thread ? Use a threading.Lock or treading.Semaphore to control access to it. > 2. How can one process control another? For example: my > program tries to connect to a server over phone. I want to cancel > dial up connection if there is timeout. How can that be done in > Python? It depends on the process. If it's pppd, then sending it a SIGHUP should do. > Thank you very much for help. > Ladislav -- Ignacio Vazquez-Abrams _______________________________________________ ActivePython mailing list ActivePython@listserv.ActiveState.com http://listserv.ActiveState.com/mailman/listinfo/activepython From mkhan12@kornet.net Fri Aug 31 00:43:12 2001 From: mkhan12@kornet.net (???) Date: Fri, 31 Aug 2001 08:43:12 +0900 Subject: [Tutor] How to change Windows Environment Variable In-Reply-To: <3B8E62DC.4090305@yahoo.com> Message-ID: RGVhciBhbGwsDQoNCkhvdyB0byBjaGFuZ2UgZW52aXJvbm1lbnQgdmFyaWFi bGUgb24gV2luZG93cyBOVCBvciAyMDAwIGJ5IHB5dGhvbj8NCg0KSW4gVmlz dWFsIEJhc2ljIGNhc2UgY2FuIHNldHRpbmcgYXMgYmVsb3c6DQoNClByaXZh dGUgRGVjbGFyZSBGdW5jdGlvbiBHZXRFbnZpcm9ubWVudFZhcmlhYmxlIExp YiAia2VybmVsMzIiIF8NCiAgICBBbGlhcyAiR2V0RW52aXJvbm1lbnRWYXJp YWJsZUEiIChCeVZhbCBscE5hbWUgQXMgU3RyaW5nLCBfDQogICAgQnlWYWwg bHBCdWZmZXIgQXMgU3RyaW5nLCBCeVZhbCBuU2l6ZSBBcyBMb25nKSBBcyBM b25nDQoNClByaXZhdGUgRGVjbGFyZSBGdW5jdGlvbiBTZXRFbnZpcm9ubWVu dFZhcmlhYmxlIExpYiAia2VybmVsMzIiIF8NCiAgICBBbGlhcyAiU2V0RW52 aXJvbm1lbnRWYXJpYWJsZUEiIChCeVZhbCBscE5hbWUgQXMgU3RyaW5nLCBf DQogICAgQnlWYWwgbHBWYWx1ZSBBcyBTdHJpbmcpIEFzIExvbmcNCg0KSSB3 aWxsIHdhaXRpbmcgZm9yIGdvb2QgbmV3cy4NClRoYW5rcy4NCk15ZW9uZ0tp IEhhbg0KLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0t LS0tLS0tLQ0KTXllb25nS2kgSGFuIA0KU2VjdGlvbiBNYW5hZ2VyLCBIdWxs IFBhcnQsIENBRCBVbmlmaWNhdGlvbiBUZWFtDQpEQUVXT08gU2hpcGJ1aWxk aW5nICYgTWFyZ2luIEVuZ2luZWVyaW5nIENvLiwgTHRkLg0KMSwgQWp1LURv bmcsIEtvamUtU2ksIEt5dW5nbmFtLCA2NTYtNzE0LCBSZXAuIG9mIEtvcmVh DQpUZWw6ICs4MiA1NSA2ODAgNDAzOSwgICAgRmF4OiArODIgNTUgNjgwIDIx NDINCk1vYmlsZTogKzgyIDE3IDg1NyA1ODQ0LCBFLW1haWw6IG1raGFuQGR3 c2hpcC5jb20NCldlYjogaHR0cDovL3d3dy5kYWV3b29zaGlwYnVpbGRpbmcu Y28ua3INCg0KLS0tLS1PcmlnaW5hbCBNZXNzYWdlLS0tLS0NCkZyb206IGFj dGl2ZXB5dGhvbi1hZG1pbkBsaXN0c2Vydi5BY3RpdmVTdGF0ZS5jb20gW21h aWx0bzphY3RpdmVweXRob24tYWRtaW5AbGlzdHNlcnYuQWN0aXZlU3RhdGUu Y29tXU9uIEJlaGFsZiBPZiBSb2INClNlbnQ6IEZyaWRheSwgQXVndXN0IDMx LCAyMDAxIDEyOjU5IEFNDQpUbzogcHJpbnRlcnNAc2VuZG1lLmN6DQpDYzog cHl0aG9uLWxpc3RAcHl0aG9uLm9yZzsgYWN0aXZlcHl0aG9uQGxpc3RzZXJ2 LkFjdGl2ZVN0YXRlLmNvbTsgdHV0b3JAcHl0aG9uLm9yZw0KU3ViamVjdDog UmU6IFtUdXRvcl0gSXMgUHl0aG9uIHBvd2VyZnVsIGVub3VnaCBmb3IgdGhp cz8NCg0KQSB3cm90ZToNCg0KPiBIaSwNCj4gSSBoYXZlIHNvbWUgd2VicGFn ZXMgdGhhdCBjb250YWluIEZPUk1TLiBFYWNoIGZvcm0gaGFzIGlucHV0DQo+ IGZpZWxkcyBhbmQgYWxzbyBzb21lIGhpZGRlbiBmaWVsZHMuDQo+IEhvdyBj YW4gSSBlYXNpbHkgZ2V0IHVybGVuY29kZWQgc3RyaW5nIGZyb20gYWxsIHRo ZXNlIGZpZWxkcw0KPiBsaWtlDQo+IEtleTE9VmFsdWUxJktleTI9VmFsdWUy JktleTM9VmFsdWUzDQo+DQo+IEZvciBleGFtcGxlOg0KPiBJIGhhdmUgYSBm b2xsb3dpbmcgd2ViIHBhZ2UNCj4gPGh0bWw+DQo+DQo+IDxoZWFkPg0KPiA8 L2hlYWQ+DQo+IDxib2R5Pg0KPiA8Zm9ybSBtZXRob2Q9IlBPU1QiIGFjdGlv bj0iYy5jZ2kiPg0KPiAgIDxwPjxpbnB1dCB0eXBlPSJ0ZXh0IiBuYW1lPSJU MSIgc2l6ZT0iMjAiPjwvcD4NCj4gICA8cD48aW5wdXQgdHlwZT0iY2hlY2ti b3giIG5hbWU9IkMxIiB2YWx1ZT0iT04iPjwvcD4NCj4gICA8cD48dGV4dGFy ZWEgcm93cz0iMiIgbmFtZT0iUzEiIGNvbHM9IjIwIj48L3RleHRhcmVhPjwv cD4NCj4gICA8cD48aW5wdXQgdHlwZT0ic3VibWl0IiB2YWx1ZT0iU3VibWl0 IiBuYW1lPSJCMSI+PGlucHV0DQo+IHR5cGU9InJlc2V0IiB2YWx1ZT0iUmVz ZXQiIG5hbWU9IkIyIj48L3A+DQo+IDwvZm9ybT4NCj4gPC9ib2R5Pg0KPiA8 L2h0bWw+DQo+DQo+PkZyb20gdGhlIGFib3ZlDQo+IEkgd291bGQgbGlrZSB0 byByZWNlaXZlDQo+IFQxPSZTMT0mQzE9JkIxPVN1Ym1pdA0KPg0KPg0KPiBU aGFuayB5b3UgZm9yIGhlbHAuDQo+IExhZGlzbGF2DQo+DQoNCg0KSSd2ZSBn b3QgYW4gZXhhbXBsZSBvZiBvbmUgd2F5IHRvIGRvIHRoaXMgc29ydCBvZiB0 aGluZyBoZXJlOg0KDQpodHRwOi8vd3d3Lmxvd2Vyc3RhbmRhcmQuY29tL3B5 dGhvbi91c2VsZXNzcHl0aG9uMS5odG1sDQoNCkl0J3MgdGhlIGJvdHRvbSBl bnRyeSBvbiB0aGUgcGFnZSwgbGFiZWxlZDogIlVzZWxlc3MgQ29tbWVudCBT eXN0ZW0iLiBJdA0KY29uc2lzdHMgb2YgYSB3b3JraW5nIGV4YW1wbGUsIGFu ZCB5b3UgY2FuIHZpZXcgYWxsIHRoZSBQeXRob24gYW5kIEhUTUwuDQoNClJv Yg0KLS0NCkEge30gaXMgYSB0ZXJyaWJsZSB0aGluZyB0byB3YXN0ZS4NClVz ZWxlc3MgUHl0aG9uIQ0KaHR0cDovL3d3dy5sb3dlcnN0YW5kYXJkLmNvbS9w eXRob24NCg0KX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19f X19fX19fX19fX18NCkFjdGl2ZVB5dGhvbiBtYWlsaW5nIGxpc3QNCkFjdGl2 ZVB5dGhvbkBsaXN0c2Vydi5BY3RpdmVTdGF0ZS5jb20NCmh0dHA6Ly9saXN0 c2Vydi5BY3RpdmVTdGF0ZS5jb20vbWFpbG1hbi9saXN0aW5mby9hY3RpdmVw eXRob24gDQo= _______________________________________________ ActivePython mailing list ActivePython@listserv.ActiveState.com http://listserv.ActiveState.com/mailman/listinfo/activepython From lkvam@venix.com Thu Aug 30 16:44:38 2001 From: lkvam@venix.com (Lloyd Kvam) Date: Thu, 30 Aug 2001 11:44:38 -0400 Subject: [Tutor] Re: Is Python powerful enough for this? References: <3B8E4794.9988.1181E6F@localhost> Message-ID: <3B8E5F66.8C785DB1@venix.com> Python is a terrific CGI scripting language. Make sure your web server is properly configured for running Python. A good starting point for how to do Python CGI scripts is: http://www.python.org/doc/essays/ppt/sd99east/ A wrote: > > Hi, > I have some webpages that contain FORMS. Each form has input > fields and also some hidden fields. > How can I easily get urlencoded string from all these fields > like > Key1=Value1&Key2=Value2&Key3=Value3 > > For example: > I have a following web page > > > > > >
    >

    >

    >

    >

    type="reset" value="Reset" name="B2">

    >
    > > > > >From the above > I would like to receive > T1=&S1=&C1=&B1=Submit > > Thank you for help. > Ladislav > _______________________________________________ > ActivePython mailing list > ActivePython@listserv.ActiveState.com > http://listserv.ActiveState.com/mailman/listinfo/activepython -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 _______________________________________________ ActivePython mailing list ActivePython@listserv.ActiveState.com http://listserv.ActiveState.com/mailman/listinfo/activepython From uselesspython@yahoo.com Thu Aug 30 16:59:24 2001 From: uselesspython@yahoo.com (Rob) Date: Thu, 30 Aug 2001 10:59:24 -0500 Subject: [Tutor] Is Python powerful enough for this? References: <3B8E4794.9988.1181E6F@localhost> Message-ID: <3B8E62DC.4090305@yahoo.com> A wrote: > Hi, > I have some webpages that contain FORMS. Each form has input > fields and also some hidden fields. > How can I easily get urlencoded string from all these fields > like > Key1=Value1&Key2=Value2&Key3=Value3 > > For example: > I have a following web page > > > > > >
    >

    >

    >

    >

    type="reset" value="Reset" name="B2">

    >
    > > > >>From the above > I would like to receive > T1=&S1=&C1=&B1=Submit > > > Thank you for help. > Ladislav > I've got an example of one way to do this sort of thing here: http://www.lowerstandard.com/python/uselesspython1.html It's the bottom entry on the page, labeled: "Useless Comment System". It consists of a working example, and you can view all the Python and HTML. Rob -- A {} is a terrible thing to waste. Useless Python! http://www.lowerstandard.com/python _______________________________________________ ActivePython mailing list ActivePython@listserv.ActiveState.com http://listserv.ActiveState.com/mailman/listinfo/activepython From printers@sendme.cz Thu Aug 30 13:03:00 2001 From: printers@sendme.cz (A) Date: Thu, 30 Aug 2001 14:03:00 +0200 Subject: [Tutor] Is Python powerful enough for this? Message-ID: <3B8E4794.9988.1181E6F@localhost> Hi, I have some webpages that contain FORMS. Each form has input fields and also some hidden fields. How can I easily get urlencoded string from all these fields like Key1=Value1&Key2=Value2&Key3=Value3 For example: I have a following web page

    >From the above I would like to receive T1=&S1=&C1=&B1=Submit Thank you for help. Ladislav _______________________________________________ ActivePython mailing list ActivePython@listserv.ActiveState.com http://listserv.ActiveState.com/mailman/listinfo/activepython From printers@sendme.cz Tue Aug 28 13:18:54 2001 From: printers@sendme.cz (A) Date: Tue, 28 Aug 2001 14:18:54 +0200 Subject: [Tutor] Questions about threads Message-ID: <3B8BA84E.12547.1408A1A@localhost> Hi, Can anybody please answer my questions? 1. In my application I need one function to run in threads. The number of threads is chosen by user and numbers of threads can not be higher at one time. This function writes to a file also.How can I prevent other threads from writting to this file when the file is open by another thread ? 2. How can one process control another? For example: my program tries to connect to a server over phone. I want to cancel dial up connection if there is timeout. How can that be done in Python? Thank you very much for help. Ladislav _______________________________________________ ActivePython mailing list ActivePython@listserv.ActiveState.com http://listserv.ActiveState.com/mailman/listinfo/activepython From printers@sendme.cz Tue Aug 28 13:18:54 2001 From: printers@sendme.cz (A) Date: Tue, 28 Aug 2001 14:18:54 +0200 Subject: [Tutor] Py2exe and wxPython Message-ID: <3B8BA84E.4003.1408A42@localhost> Hi, Does anyone have any experience with Py2exe converting python source into exe if there is wxPython used in source? Thanks for reply Ladislav _______________________________________________ ActivePython mailing list ActivePython@listserv.ActiveState.com http://listserv.ActiveState.com/mailman/listinfo/activepython From ignacio@openservices.net Fri Aug 31 01:14:06 2001 From: ignacio@openservices.net (Ignacio Vazquez-Abrams) Date: Thu, 30 Aug 2001 20:14:06 -0400 (EDT) Subject: [Tutor] Re: How to change Windows Environment Variable In-Reply-To: Message-ID: On Fri, 31 Aug 2001, ??? wrote: > Dear all, > > How to change environment variable on Windows NT or 2000 by python? > > In Visual Basic case can setting as below: > > Private Declare Function GetEnvironmentVariable Lib "kernel32" _ > Alias "GetEnvironmentVariableA" (ByVal lpName As String, _ > ByVal lpBuffer As String, ByVal nSize As Long) As Long > > Private Declare Function SetEnvironmentVariable Lib "kernel32" _ > Alias "SetEnvironmentVariableA" (ByVal lpName As String, _ > ByVal lpValue As String) As Long > > I will waiting for good news. > Thanks. > MyeongKi Han Good news: There is a GetEnvironmentVariable() function in the win32api module. Bad news: There is no SetEnvironmentVariable() function. Good news: The source code for win32api is available via CVS (http://starship.python.net/crew/mhammond/cvs.html) so you can add the function. Bad News: You'll need Visual Studio 6 to compile it. -- Ignacio Vazquez-Abrams _______________________________________________ ActivePython mailing list ActivePython@listserv.ActiveState.com http://listserv.ActiveState.com/mailman/listinfo/activepython