From wescpy at gmail.com Sat Apr 1 01:26:57 2006 From: wescpy at gmail.com (w chun) Date: Fri, 31 Mar 2006 15:26:57 -0800 Subject: [Tutor] removing file from zip archive. In-Reply-To: <200603291442.13643.keosophon@khmeros.info> References: <200603291442.13643.keosophon@khmeros.info> Message-ID: <78b3a9580603311526p3b24a28fgef835cd123917af5@mail.gmail.com> > How can we remove one file inside of a zip archive? > > import zipfile > ziparchive = zipfile.ZipFile('test.odt', 'r') > xmldata = ziparchive.read('content.xml') > ziparchive.close <--- ADD "( )" HERE TOO Sophon, You can remove any number of files from a ZIP file, but it has to be processed manually by you. When you read() a file from a ZIP archive, you actually have all the data with you, i.e. xmldata. All you have to do is to open another file to write it out to disk, i.e., f = open('content.xml', 'w') f.write(xmldata) f.close() hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From broek at cc.umanitoba.ca Sat Apr 1 02:32:16 2006 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Fri, 31 Mar 2006 18:32:16 -0600 Subject: [Tutor] request for sugestions on fragement of code for generating truth-tables Message-ID: <442DCA10.9020104@cc.umanitoba.ca> Hi all, I've been too busy with life to do much Python of late. So, I am a bit rusty. :-( I've got some code that does what it needs to but I think I might be overlooking a much smoother way to get what I need. The code takes a list of strings and returns a list of dictionaries, where each dictionary uses the strings from the list as keys and booleans as values. The dictionary list contains a dictionary exhibiting each possible combination of booleans over the keys, where these combinations are listed in a systematic way. This code works: def tva_dict_maker(atoms): tvas = [] val = False for k in range(2**len(atoms)): tvas.append(dict()) for i in range(len(atoms)): key = atoms[i] for j in range(2**len(atoms)): if j % ( len(tvas) / 2.0 ** (i+1) ) == 0: val = not val tvas[j][key]=val return tvas The output I desire is easier to see with a bit of processing (to impose order on the dicts). So, def display_tvas(tvas): for i in tvas: for j in sorted(i): print "%s:%s\t" %(j, i[j]), print Then, the output is like so: >>> atoms = ["a","b","c"] >>> tvas = tva_dict_maker(atoms) >>> display_tvas(tvas) a:True b:True c:True a:True b:True c:False a:True b:False c:True a:True b:False c:False a:False b:True c:True a:False b:True c:False a:False b:False c:True a:False b:False c:False >>> As desired :-) But, I can't shake the feeling I'm doing this in a harder than necessary way :-| [This is in the context of writing a program to generate truth-tables for sentential logic, so that I can easily create answered exercises for a critical thinking course I've been teaching. (As it is for a Philosophy class, the truth-values are listed in the opposite order than in a CompSci context.)] Any suggestions would be welcome. Best to all, Brian vdB From srini_iyyer_bio at yahoo.com Sat Apr 1 02:39:30 2006 From: srini_iyyer_bio at yahoo.com (Srinivas Iyyer) Date: Fri, 31 Mar 2006 16:39:30 -0800 (PST) Subject: [Tutor] Python + PostGreSQL In-Reply-To: <78b3a9580603311526p3b24a28fgef835cd123917af5@mail.gmail.com> Message-ID: <20060401003930.76138.qmail@web38109.mail.mud.yahoo.com> Dear group, I want to connect python to postgresql. My python dist. is 2.4.2 My postgres: 8.1.2 My system: Linux Enterprise Linux, Intel Xeon, 4GB RAM. I tried to install pygresql: version: 3.8, it failed throwing exception : Exception: pg_config tool is not available. I gave another try on google and Postgres site and found Pypgsql, PoPy and psycopg1. I am confused now. Which is the most promising connection between Python and Postgres now. Aplogies, if this question is inappropriate on this forum. Srini __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From ilias at lazaridis.com Sat Apr 1 02:48:19 2006 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Sat, 01 Apr 2006 03:48:19 +0300 Subject: [Tutor] Looking for Constructs to Remove Redundant Code In-Reply-To: <442D2FCF.3000704@tds.net> References: <442D2FCF.3000704@tds.net> Message-ID: Kent Johnson wrote: ... Thank you for your comments. I realize that my request was not very clear. I make a 2nd attemp, more simplified: I have this python code: class Car(BaseClass) : manufacturer = stringFactory() model = stringFactory() modelYear = integerFactory() def __str__(self): return '%s %s %s' % (self.modelYear, self.manufacturer, self.model) def stringFactory(self) s = String() # creates a string object #... # does several things return s # returns the string object - and would like to see it e.g. this way: class Car(BaseClass): manufacturer = stringFactory(2) model = stringFactory(3) modelYear = integerFactory(1) def stringFactory(self, position) s = String() # creates a string object ... # does several things # creates somehow the __str__ functionality... return s # returns the string object - hope this is now more clear. . -- http://lazaridis.com From bill at celestial.net Sat Apr 1 03:01:57 2006 From: bill at celestial.net (Bill Campbell) Date: Fri, 31 Mar 2006 17:01:57 -0800 Subject: [Tutor] Python + PostGreSQL In-Reply-To: <20060401003930.76138.qmail@web38109.mail.mud.yahoo.com> References: <78b3a9580603311526p3b24a28fgef835cd123917af5@mail.gmail.com> <20060401003930.76138.qmail@web38109.mail.mud.yahoo.com> Message-ID: <20060401010157.GA59681@alexis.mi.celestial.com> On Fri, Mar 31, 2006, Srinivas Iyyer wrote: >Dear group, > >I want to connect python to postgresql. >My python dist. is 2.4.2 >My postgres: 8.1.2 >My system: Linux Enterprise Linux, Intel Xeon, 4GB >RAM. > >I tried to install pygresql: version: 3.8, it failed >throwing exception : Exception: pg_config tool is not >available. > >I gave another try on google and Postgres site and >found Pypgsql, PoPy and psycopg1. I think that psycopg is generally considered the preferred package. I have been using it with several systems including Zope, and sqlobject. So far I haven't tried psycopg2. Bill -- INTERNET: bill at Celestial.COM Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 A child can go only so far in life without potty training. It is not mere coincidence that six of the last seven presidents were potty trained, not to mention nearly half of the nation's state legislators. -- Dave Barry From dyoo at hkn.eecs.berkeley.edu Sat Apr 1 04:27:02 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 31 Mar 2006 18:27:02 -0800 (PST) Subject: [Tutor] request for sugestions on fragement of code for generating truth-tables In-Reply-To: <442DCA10.9020104@cc.umanitoba.ca> Message-ID: > Then, the output is like so: > > >>> atoms = ["a","b","c"] > >>> tvas = tva_dict_maker(atoms) > >>> display_tvas(tvas) > a:True b:True c:True > a:True b:True c:False > a:True b:False c:True > a:True b:False c:False > a:False b:True c:True > a:False b:True c:False > a:False b:False c:True > a:False b:False c:False Hi Brian, We might be able to take advantage of the recursive nature of this problem. I'll sketch out the idea and try to fight the temptation to write it out in full. *grin* If you haven't encountered recursion before, please shout out and ask for more details. When we look above, we're looking at the solution for tva_dict_maker-ing the list ['a', 'b', 'c']. But let's imagine what tva_dict_maker() looks like for a slightly smaller problem, for ['b', 'c']: b:True c:True b:True c:False b:False c:True b:False c:False If we look at this and use our pattern-matching abilities, we might say that the solution for ['b', 'c'] really looks like half of the solution for ['a', 'b', 'c'] That is, to get: tva_dict_maker(['a', 'b', 'c']) all we really need are the results of tva_dict_maker(['b', 'c']). We can then twiddle two copies of the samller solution to make 'a' either True or False, combine them together, and we've got it. Recursive approachs have two parts to them, a "base" case and an "inductive" case: 1. Figure out solutions for really simple examples. For example, in the problem above, We know that something like: tva_dict_maker(['c']) has a very simple solution, since we're only dealing with a list of one element. ([{'c': True}, {'c' : False}]) 2. And for larger problems, let's figure out a way to break the problem into something smaller. We might be able to take the solution of the smaller problem and make it scale up. So a recursive approach will typically fit some template like this: ## Pseduocode ######################################################### def recursive_problem(some_problem): if some_problem is really obviously simple: return the obviously simple answer to some_problem otherwise: smaller_problem = some way of making some_problem slightly smaller. On lists, usually attack list[1:]. small_solution = recursive_problem(smaller_problem) full_solution = twiddle small_solution somehow to make it solve some_problem return full_solution ####################################################################### If you have more questions, please feel free to ask! From wescpy at gmail.com Sat Apr 1 04:38:58 2006 From: wescpy at gmail.com (w chun) Date: Fri, 31 Mar 2006 18:38:58 -0800 Subject: [Tutor] Python + PostGreSQL In-Reply-To: <20060401010157.GA59681@alexis.mi.celestial.com> References: <78b3a9580603311526p3b24a28fgef835cd123917af5@mail.gmail.com> <20060401003930.76138.qmail@web38109.mail.mud.yahoo.com> <20060401010157.GA59681@alexis.mi.celestial.com> Message-ID: <78b3a9580603311838l5affda5fub6c634a2ae4e678@mail.gmail.com> > >I tried to install pygresql: version: 3.8, it failed > >throwing exception : Exception: pg_config tool is not > >available. > > > >I gave another try on google and Postgres site and > >found Pypgsql, PoPy and psycopg1. > > I think that psycopg is generally considered the preferred > package. as bill has suggested, it does appear that psycopg is the preferred from what i've seen. popy is outdated and (i believe) merged with PyGreSQL which is the one that PostgreSQL has in their tree as it's been around the longest. however rather than just talking about another adapter because your current one doesn't work, i'm more curious as to why you are having problems with PyGreSQL. i've never had a problem with it... how did you do your installation? (yes, we're lucky that PostgreSQL has multiple adapters available as other RDBMSs don't have these options.) --wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From srini_iyyer_bio at yahoo.com Sat Apr 1 05:00:43 2006 From: srini_iyyer_bio at yahoo.com (Srinivas Iyyer) Date: Fri, 31 Mar 2006 19:00:43 -0800 (PST) Subject: [Tutor] Python + PostGreSQL In-Reply-To: <78b3a9580603311838l5affda5fub6c634a2ae4e678@mail.gmail.com> Message-ID: <20060401030043.77787.qmail@web38106.mail.mud.yahoo.com> Thanks Bill, and wesley, Psycopg worked for me. I had to use setup.cfg . Regular setup.py did not work. AFA, pygresql I did used this some 2 years back. However, the install was pretty easy due to proper redhat rpm updates. I felt more comfortable with PyGreSQL. I liked it somehow. tar -xvf PyGreSQL.tar cd PyGreSQL-3.8/ sudo python setup.py build sh: pg_config: command not found Traceback (most recent call last): File "setup.py", line 77, in ? pg_include_dir = pg_config('includedir') File "setup.py", line 47, in pg_config raise Exception, "pg_config tool is not available." Exception: pg_config tool is not available. My pg_config is in : /usr/local/pgsql/bin/pg_config thanks Srini --- w chun wrote: > > >I tried to install pygresql: version: 3.8, it > failed > > >throwing exception : Exception: pg_config tool is > not > > >available. > > > > > >I gave another try on google and Postgres site > and > > >found Pypgsql, PoPy and psycopg1. > > > > I think that psycopg is generally considered the > preferred > > package. > > > as bill has suggested, it does appear that psycopg > is the preferred > from what i've seen. popy is outdated and (i > believe) merged with > PyGreSQL which is the one that PostgreSQL has in > their tree as it's > been around the longest. > > however rather than just talking about another > adapter because your > current one doesn't work, i'm more curious as to why > you are having > problems with PyGreSQL. i've never had a problem > with it... how did > you do your installation? (yes, we're lucky that > PostgreSQL has > multiple adapters available as other RDBMSs don't > have these options.) > > --wesley > - - - - - - - - - - - - - - - - - - - - - - - - - - > - - - - > "Core Python Programming", Prentice Hall, > (c)2007,2001 > http://corepython.com > > wesley.j.chun :: wescpy-at-gmail.com > cyberweb.consulting : silicon valley, ca > http://cyberwebconsulting.com > __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From wescpy at gmail.com Sat Apr 1 08:03:33 2006 From: wescpy at gmail.com (w chun) Date: Fri, 31 Mar 2006 22:03:33 -0800 Subject: [Tutor] Python + PostGreSQL In-Reply-To: <20060401030043.77787.qmail@web38106.mail.mud.yahoo.com> References: <78b3a9580603311838l5affda5fub6c634a2ae4e678@mail.gmail.com> <20060401030043.77787.qmail@web38106.mail.mud.yahoo.com> Message-ID: <78b3a9580603312203r1829906fq57bc3ec1d177f512@mail.gmail.com> hi srini, i don't know what your system configuration was like for the installation, but from what i saw in your post (below), it just seems like /usr/local/pgsql/bin was not in your path since it looks like "sh" could not find the pg_config command, not Python (which choked afterwards). anyway, if you got psycopg working for you, then just leave it. :-) cheers, -wesley > sh: pg_config: command not found > : > My pg_config is in : /usr/local/pgsql/bin/pg_config From sanelson at gmail.com Sat Apr 1 09:10:10 2006 From: sanelson at gmail.com (Steve Nelson) Date: Sat, 1 Apr 2006 08:10:10 +0100 Subject: [Tutor] Inverted Index Algorithm In-Reply-To: <442DA17E.9020800@tds.net> References: <442DA17E.9020800@tds.net> Message-ID: On 3/31/06, Kent Johnson wrote: > Steve Nelson wrote: > > Do you need help getting started with Python or with inverted indexing > in particular? Sorry - I should have been clearer. I'm reasonably confident in Python, and if I get stuck with that side of things will ask for help. I was more struggling with the Inverted Indexing bit. I think I want to write a program that will do text searches on documents, to learn about and compare the two approaches I've heard of - Inverted Indexing and Signature Files. SO I think I am asking for help at the logical / implementation level. My understanding so far goes something like this: Suppose I have three documents - as a trivial but fun example, we could make them song lyrics. The simplest thing that could possibly work would be to supply one or two words and literally scan every word in the song for a match. This has two disadvantages - firstly it is likely to produce false positives, and secondly it is likely to be very inefficient. The next step would be to introduce an index. I think again, the simplest thing that could possibly work would be a literal index of every word and every document in which it appears. This would save processing time, but wouldn't be very intelligent. This is where I think the inverted indexing comes in. As I understand it we can now produce an index of key words, with document name and location in document for each key word. This makes the search more involved, and more intelligent. Finally we could have some logic that did some set analysis to return only results that make sense. Am I thinking along the right lines, or have I misunderstood? Could someone perhaps come up with some code snippets that make clearer examples? I also need to think about signature files, but I havn't really any idea how these work. Thanks all! S. > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From aguffabuff at hotmail.com Sat Apr 1 09:18:34 2006 From: aguffabuff at hotmail.com (Ars) Date: Fri, 31 Mar 2006 23:18:34 -0800 Subject: [Tutor] Capture keyboard input even without python in focus Message-ID: What commands could capture input from the keyboard (and the mouse while we're at it) even when the running python program isn't the program in focus? Sorta like a keylogger, though that's not my goal (wouldn't be very secret with a python console running anyways lol.) -Jack -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060331/82cce315/attachment.html From dyoo at hkn.eecs.berkeley.edu Sat Apr 1 09:42:57 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 31 Mar 2006 23:42:57 -0800 (PST) Subject: [Tutor] Inverted Index Algorithm In-Reply-To: Message-ID: > The next step would be to introduce an index. I think again, the > simplest thing that could possibly work would be a literal index of > every word and every document in which it appears. This would save > processing time, but wouldn't be very intelligent. Yes, that's right, that's the idea of an inverted index. > This is where I think the inverted indexing comes in. As I understand > it we can now produce an index of key words, with document name and > location in document for each key word. This makes the search more > involved, and more intelligent. Finally we could have some logic that > did some set analysis to return only results that make sense. Location information would help allow you to do things like phrase or proximity matching. Another thing that might help is term frequency (tf). You might want to check out documentation about Lucene: http://lucene.apache.org/java/docs/index.html as they're the premier open source search library. They have a presentation that gives a good overview of the techniques used in a fast search engine: http://lucene.sourceforge.net/talks/inktomi/ If you want to reuse their engine, the OSAF folks have even written Python bindings to the library: http://pylucene.osafoundation.org/ From francois.schnell at gmail.com Sat Apr 1 10:31:04 2006 From: francois.schnell at gmail.com (francois schnell) Date: Sat, 1 Apr 2006 10:31:04 +0200 Subject: [Tutor] Capture keyboard input even without python in focus In-Reply-To: References: Message-ID: <13a83ca10604010031o4eb19716jc869288c763abb9e@mail.gmail.com> Hello, On windows OS I'm using the nice pyhook module: "The pyHook library wraps the low-level mouse and keyboard hooks in the Windows Hooking API for use in Python applications. " See tutorial here: http://www.cs.unc.edu/~parente/tech/tr08.shtml francois On 01/04/06, Ars wrote: > > What commands could capture input from the keyboard (and the mouse while > we're at it) even when the running python program isn't the program in > focus? Sorta like a keylogger, though that's not my goal (wouldn't be very > secret with a python console running anyways lol.) > > -Jack > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060401/ad66735a/attachment.htm From kent37 at tds.net Sat Apr 1 13:12:02 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 01 Apr 2006 06:12:02 -0500 Subject: [Tutor] BeautifulSoup - getting cells without new line characters In-Reply-To: References: <442D4E38.9050508@tds.net> <442D54DD.3070605@tds.net> <442D5B05.5020607@tds.net> <442D608E.9080102@tds.net> Message-ID: <442E6002.7010207@tds.net> jonasmg at softhome.net wrote: > Kent Johnson writes: > > >>jonasmg at softhome.net wrote: >> >> >>>List of states: >>>http://en.wikipedia.org/wiki/U.S._state >>> >>>: soup = BeautifulSoup(html) >>>: # Get the second table (list of states). >>>: table = soup.first('table').findNext('table') >>>: print table >>> >>>... >>> >>>WY >>>Wyo. >>>Wyoming >>>Cheyenne >>>Cheyenne >>>>>src="http://upload.wikimedia.org/wikipedia/commons/thumb/b/bc/Flag_of_Wyomin >>>g.svg/45px-Flag_of_Wyoming.svg.png" width="45" alt="" height="30" >>>longdesc="/wiki/Image:Flag_of_Wyoming.svg" /> >>> >>> >>> >>>Of each row (tr), I want to get the cells (td): 1,3,4 >>>(postal,state,capital). But cells 3 and 4 have anchors. >> >>So dig into the cells and get the data from the anchor. >> >>cells = row('td') >>cells[0].string >>cells[2]('a').string >>cells[3]('a').string >> >>Kent >> >>_______________________________________________ >>Tutor maillist - Tutor at python.org >>http://mail.python.org/mailman/listinfo/tutor > > > for row in table('tr'): > cells = row('td') > print cells[0] > > IndexError: list index out of range It works for me: In [1]: from BeautifulSoup import BeautifulSoup as bs In [2]: soup=bs(''' ...: WY ...: Wyo. ...: Wyoming ...: Cheyenne ...: Cheyenne ...: ...: ...: ''' ...: ...: ...: ...: ) In [18]: rows=soup('tr') In [19]: rows Out[19]: [ WY Wyo. Wyoming Cheyenne Cheyenne Wyoming, Cheyenne, Cheyenne, It may be that Python isn't the best solution for you here. Are there >extended-precision libraries for Visual Basic? Alas, none that I know of that are reliable and not incredibly expensive, been looking for years, plus Im hooped because I have to work with VB 4.0 instead of 6 +, guh.... >Regards, >Matt Matt..... good name, why do I always seem to get along with Matts, you people keep popping up in my life and its always a blast! Best regards, D

_______________________________________________________________
Get the FREE email that has everyone talking at
http://www.mail2world.com
Unlimited Email Storage – POP3 – Calendar – SMS – Translator – Much More!
-------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060331/7ba4da51/attachment.html From jonasmg at softhome.net Sat Apr 1 14:22:23 2006 From: jonasmg at softhome.net (jonasmg at softhome.net) Date: Sat, 01 Apr 2006 05:22:23 -0700 Subject: [Tutor] BeautifulSoup - getting cells without new line characters In-Reply-To: <442E6002.7010207@tds.net> References: <442D4E38.9050508@tds.net> <442D54DD.3070605@tds.net> <442D5B05.5020607@tds.net> <442D608E.9080102@tds.net> <442E6002.7010207@tds.net> Message-ID: Kent Johnson writes: > jonasmg at softhome.net wrote: >> Kent Johnson writes: >> >> >>>jonasmg at softhome.net wrote: >>> >>> >>>>List of states: >>>>http://en.wikipedia.org/wiki/U.S._state >>>> >>>>: soup = BeautifulSoup(html) >>>>: # Get the second table (list of states). >>>>: table = soup.first('table').findNext('table') >>>>: print table >>>> >>>>... >>>> >>>>WY >>>>Wyo. >>>>Wyoming >>>>Cheyenne >>>>Cheyenne >>>>>>>src="http://upload.wikimedia.org/wikipedia/commons/thumb/b/bc/Flag_of_Wyomin >>>>g.svg/45px-Flag_of_Wyoming.svg.png" width="45" alt="" height="30" >>>>longdesc="/wiki/Image:Flag_of_Wyoming.svg" /> >>>> >>>> >>>> >>>>Of each row (tr), I want to get the cells (td): 1,3,4 >>>>(postal,state,capital). But cells 3 and 4 have anchors. >>> >>>So dig into the cells and get the data from the anchor. >>> >>>cells = row('td') >>>cells[0].string >>>cells[2]('a').string >>>cells[3]('a').string >>> >>>Kent >>> >>>_______________________________________________ >>>Tutor maillist - Tutor at python.org >>>http://mail.python.org/mailman/listinfo/tutor >> >> >> for row in table('tr'): >> cells = row('td') >> print cells[0] >> >> IndexError: list index out of range > > It works for me: > > > In [1]: from BeautifulSoup import BeautifulSoup as bs > > In [2]: soup=bs(''' > ...: WY > ...: Wyo. > ...: Wyoming > ...: Cheyenne > ...: Cheyenne > ...: title=""> ...: > src="http://upload.wikimedia.org/wikipedia/commons/thumb/b/bc/Flag_of_Wyomin > ...: g.svg/45px-Flag_of_Wyoming.svg.png" width="45" alt="" height="30" > ...: longdesc="/wiki/Image:Flag_of_Wyoming.svg" /> > ...: > ...: ''' > ...: > ...: > ...: > ...: ) > > In [18]: rows=soup('tr') > > In [19]: rows > Out[19]: > [ > WY > Wyo. > Wyoming > Cheyenne > Cheyenne > title=""> longdesc="/wiki/Image:Flag_ > ] > > In [21]: cells=rows[0]('td') > > In [22]: cells > Out[22]: > [WY, > Wyo., > Wyoming, > Cheyenne, > Cheyenne, > title=""> longdesc="/wiki/Image:Flag_ > > In [23]: cells[0].string > Out[23]: 'WY' > > In [24]: cells[2].a.string > Out[24]: 'Wyoming' > > In [25]: cells[3].a.string > > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor Yes, ok. But so, it is only possible get data from a row (rows[0]) cells=rows[0]('td') And I want get data from all rows. I have trying with several 'for' setences but i can not. From kent37 at tds.net Sat Apr 1 14:50:53 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 01 Apr 2006 07:50:53 -0500 Subject: [Tutor] BeautifulSoup - getting cells without new line characters In-Reply-To: References: <442D4E38.9050508@tds.net> <442D54DD.3070605@tds.net> <442D5B05.5020607@tds.net> <442D608E.9080102@tds.net> <442E6002.7010207@tds.net> Message-ID: <442E772D.9020409@tds.net> jonasmg at softhome.net wrote: > Yes, ok. But so, it is only possible get data from a row (rows[0]) > > cells=rows[0]('td') > > And I want get data from all rows. I have trying with several 'for' setences > but i can not. Can you show us what you tried? Have you read a Python tutorial? It seems like some of the things you are struggling with might be addressed in general Python material. Kent From kent37 at tds.net Sat Apr 1 14:56:23 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 01 Apr 2006 07:56:23 -0500 Subject: [Tutor] Python, VB math simple problem In-Reply-To: <0db901c65545$92b249a0$70cb010a@mail2world.com> References: <0db901c65545$92b249a0$70cb010a@mail2world.com> Message-ID: <442E7877.8080904@tds.net> Mr X wrote: > > > Hi looking for help with what should be a fairly simple Python problem, > relating to VB inter-operability. > Got a great response from a fellow named Matt at help at python.org, > pointed me in some good directions - some areas, concerns still foggy > on, the below thread is included.... any feedback on this simple dilemma > would be very appreciated. You can use py2exe to make an executable from a python program. Or the VB program could invoke a command line like "python prog.py data.txt" without needing to use py2exe. You can also write COM servers in Python. Kent > > Thanks, > > D > > thread follows below; > > ------------------------------------ > > To: help at python.org > Subject: Problem with Python math functions and VB > Date: 3/30/2006 9:39:28 PM > Download Message Display Headers Printer Friendly > Previous | Next > > Wondering if you might either know how to solve the following. > > I've a background in Visual Basic, and am using an old version, 4.0, it > compiles to a smaller executable which I prefer. I find myself in an odd > situation, needing a very simple yet powerful capability of Python for a > VB app > Im working on. > > Simply, a large 300 digit number is divided by a smaller number ranging > from 1 to 3 digits. I.e; > > This large 300 digit number is generated as a string from the VB app, > and I want to input this somehow > from the VB app directly to Python for simple math operations. > > Where; x = 300 digit number, y = divisor ( say '37') > > > x / 37 > > I want to divide x by y but I want the remainder of this division to at > least 3 or 4 decimal places, so my Python script at the command line; > > x %y /y. = z > > So now I want to take the resultant, the full number plus its remainder, > and I want to round this number up > to the next highest number and divide it by the same constant; > > z rounded up to next highest number (never the lowest) > > so > > z /y = z Long > > Remove the 'L' at the end, round up the last digit of z = Z > > Then; > > Z %y /y. = a > > Then I want the last five digits of z (not Z) and a truncated at the > end, so the last digit before > the decimal point and the four digits past the decimal point printed to > a text file. > > I want to be able to open the text file with the VB app and use this > data as inputs. > ========== > > Ok, so here is my dilemma, I know VERY litle about Python and a fair bit > about VB. > > Ideally, I'd love to be able to simply have some extremely small > executable that just accepts inputs > does the calculations above and then spits out the outputs. If it were > possible to write some > simple lines of math code in Python and then compile these scripts in > Python to a Windows > compatible executable,that would be fantastic. > > If I could simply have my VB app, 'call' the name of the tiny Python > executable, and then the Python executable > just automatically looked for a named text file (created by the VB app) > and extracted the 300 digit number from this, then performed the calcs, > then spit this data out as a new text file name it created, which I > could then use the VB app to open and read from, THAT would be ideal. > > However, I don't know if Python can compile scripts to an exe? If it can > how could I find out how to do this? > > If it doesn't, how could I get VB to directly pass commands to the > Python command line and then automatically > extract the outputs? Shelling out from VB to Python would be tough to > the command line I think, since the Python command line uses the 'Edit / > Mark, Paste' approach to inserting, copy inputs, outputs and this would > be virtually untenable, as far as I can tell to automate in a VB shell > out routine. > > So basically, how the heck can I access Pythons ability to perform > simple calculations on very large numbers, easily, from within VB 4.0 ? > There must be a way, it seems like such a simple think to do, especially > since the actual math operations are so simple, straight forward, and > would never change..... > > Any ideas? > > > > ------ > Matthew, thanks for your response. > > <-----Original Message-----> > >From: Matthew Dixon Cowles > >Sent: 3/31/2006 9:41:18 AM > >To: durango at mail2world.com > >Cc: help at python.org > >Subject: Re: [Python-Help] Problem with Python math functions and VB > > >I'm sure that there's a way to do that, but I'm not familiar with > >Visual Basic and I don't know what inter-process communication > >facilities it offers. > > Is there a person or group you might direct me to that has worked with this > inter-process communication between VB and Python? > > >I don't think that Python is going to be able to do that for you out > >of the box. Hundreds of digits of floating-point precision is a lot. > > Could you explain that a bit more, sorry Im not sure what you mean > by 'out of the box' ? If I run the Python command line screen in windows > and manually type out a very large number, say 180 digits; where 'X' = > very large number; > > X %37 /37. > > returns what Im after, value wise..... but of course I don't want to do > this manually each time > for every dividend. > > >You might find that one of the Python modules that let you use an > >extended-precision library would do what you want. GMPY is one: > > >http://gmpy.sourceforge.net/ > > Hey, thats interesting, wonder if these modules can be operated on with > VB..... > > >> So now I want to take the resultant, the full number plus its > >> remainder, and I want to round this number up > >> to the next highest number and divide it by the same constant; > > > >That's easy enough. > > > >> I want to be able to open the text file with the VB app and use this > >> data as inputs. > > > >Python can write to a file without any trouble, so it that form of > >inter-process communication suits you, you shouldn't have much > >trouble. I assume that Visual Basic has an easy way to start a > >program and supply it with arguments, so you could have your Python > >program get its inputs from sys.argv. > > What is sys.argv ? Thats really good news. In fact, all I really need > for the moment is > a python executable that; > > ================ > PYTHON ALGORITHM ABSTRACT > > a) opens a text file > b) reads a string from the file, which is a very large number > c) performs simple arithmetic operations; > > X %37 /37. = y (four digit remainder after decimal point) > X /37 = w (quotient as long, the resulting output is stored as a > variable, the 'L' suffix tagged on the end of this resultant then gets > removed. > then the last digit in the quotient resultant string is increased in > value by one, rounded upwards = 'Z' > > then > > Z %37 /37. = a > > then, y and a are printed to a text file with hard returns between them. > Thats it, thats all I need to do. > =================== > >Alas, it's not going to be extremely small. There isn't a compiler > >from Python to machine code. Py2exe will bundle a Python program, > >with everything that it needs to run, into a single executable > >archive. But the archive isn't small. Py2exe is at: > > > >http://www.py2exe.org/ > > the most important thing is the functionality, I'll sacrifice size if I > have to. My guess is this should work based on your comments, because > perhaps all I really have to do is have VB dump out the value of the > Very large number, `180 to 300 digits or so', to a text file, which then > becomes the input data for the Python executable, and then if I simply > call the name of the Python executable from VB as an instance, > then the Python App runs, spits out the data as a new text file, then > the VB app goes and opens the new text file and reads in the values, > and voila! There it is. I'm pretty sure I can call the Python app from > VB....... the alternative to all this would be to try and feed Python > scripts > directly to Python from VB, which I have NO idea how to do or where to > begin.... and am guessing would be much more messy... > > I haven't programmed in Python, how would the "PYTHON ALGORITHM > ABSTRACT" I describe above look like, code wise? > Is this fairly easy for you to describe? > > >It may be that Python isn't the best solution for you here. Are there > >extended-precision libraries for Visual Basic? > > Alas, none that I know of that are reliable and not incredibly > expensive, been looking for years, plus Im hooped because I have to work > with VB 4.0 instead of 6 +, guh.... > > >Regards, > >Matt > > Matt..... good name, why do I always seem to get along with Matts, you > people keep popping up in my life and its always a blast! > > Best regards, > > D > > _______________________________________________________________ > Get the FREE email that has everyone talking at http://www.mail2world.com > Unlimited Email Storage ? POP3 ? Calendar ? SMS ? Translator ? Much More! > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From alan.gauld at freenet.co.uk Sat Apr 1 19:06:43 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 1 Apr 2006 18:06:43 +0100 Subject: [Tutor] i need help please read (fwd) References: <015d01c64e7d$d0d31210$0b01a8c0@xp> <4ce40aaa0603241927n3aba0f68wd018216f9f750995@mail.gmail.com> Message-ID: <000f01c655ae$a6d5ae90$0b01a8c0@xp> Tom, I'm still struggling, but based on what Danny Yoo deduced I'll assume you are talking anbout a dialog box or window of some sort rather than drawing a graphical box? > ok ill tell you want im doing i want to make a box using python that if > you > put the box over a number on the computer screen it pops up inside the box Do you mean a bit like the magnifier applet that ships with Windows? It magnifies whatever is underneath it on the main screen? If so thats a really tough task. It is possible in Python but it requires an in-depth knowledge of how Windows works - much more than I have! > and the number can be altered in the box and however you alter it on the > box > it turns into that or show what you altered in place of the number you put > it over get what im saying And modifying the number underneath is much much harder again. It might not even be possible! You can alter it in your own program but to make that take effect on the underlying application would require that you find out what application was diswplaying the number and then find a way to write to that application. These are very deep and difficult programming tasks! Its theoretically possible in Python, but its very difficult. Even in C++ it would be a real challenge. Alan G. Just back from a week's vacation in Spain. From jonasmg at softhome.net Sat Apr 1 19:39:21 2006 From: jonasmg at softhome.net (jonasmg at softhome.net) Date: Sat, 01 Apr 2006 10:39:21 -0700 Subject: [Tutor] BeautifulSoup - getting cells without new line characters In-Reply-To: <442E772D.9020409@tds.net> References: <442D4E38.9050508@tds.net> <442D54DD.3070605@tds.net> <442D5B05.5020607@tds.net> <442D608E.9080102@tds.net> <442E6002.7010207@tds.net> <442E772D.9020409@tds.net> Message-ID: Kent Johnson writes: > jonasmg at softhome.net wrote: >> Yes, ok. But so, it is only possible get data from a row (rows[0]) >> >> cells=rows[0]('td') >> >> And I want get data from all rows. I have trying with several 'for' setences >> but i can not. > > Can you show us what you tried? > > Have you read a Python tutorial? It seems like some of the things you > are struggling with might be addressed in general Python material. > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor You consider a thing about me. If I ask something it is because I cannot find the solution. I do not it by whim. Yes, I have read tutorials about python, and I have looked for this problem in this mail list using a web searcher as alltheweb, and I have even looked for in the google groups about python. * for rows in table('tr'): print rows('td') it fails when i'm going to get data of each cell using: for rows in table('tr'): print rows('td')[0] * for rows in table('tr'): for cell in rows('td'): print cell The same, using print cell[0] From nospamformeSVP at gmail.com Sat Apr 1 21:25:47 2006 From: nospamformeSVP at gmail.com (Don Taylor) Date: Sat, 01 Apr 2006 14:25:47 -0500 Subject: [Tutor] Doctest, object references and the use of ellipses Message-ID: Hi: I am trying to use Doctest and am having trouble using the ellipsis feature when trying to match an object reference. Here is the code: def add_change_listener(self, listener): ''' Returns list of listeners just for testing. >>> def mock_listener(): ... pass >>> model = Model() >>> model.add_change_listener(mock_listener) #doctest: +ELLIPSIS [] ''' self.listeners.append(listener) return self.listeners This is what I get back: Trying: model.add_change_listener(mock_listener) #doctest: +ELLIPSIS Expecting: [] ********************************************************************** File "D:\ProgrammingProjects\MVCExperiments\src\mvcmodel.py", line 14, in __main__.Model.add_change_listener Failed example: model.add_change_listener(mock_listener) #doctest: +ELLIPSIS Expected: [] Got: [] As far as I can tell from the Doctest documentation this test should have passed. Any help on what I am doing wrong would be much appreciated. Thanks, Don. From kent37 at tds.net Sat Apr 1 21:51:33 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 01 Apr 2006 14:51:33 -0500 Subject: [Tutor] Doctest, object references and the use of ellipses In-Reply-To: References: Message-ID: <442ED9C5.8070007@tds.net> Don Taylor wrote: > Hi: > > I am trying to use Doctest and am having trouble using the ellipsis > feature when trying to match an object reference. What version of Python are you using? The ELLIPSIS comment was added in Python 2.4. Kent > > Here is the code: > > def add_change_listener(self, listener): > ''' > > Returns list of listeners just for testing. > >>> def mock_listener(): > ... pass > >>> model = Model() > >>> model.add_change_listener(mock_listener) #doctest: +ELLIPSIS > [] > > ''' > > self.listeners.append(listener) > return self.listeners > > This is what I get back: > > Trying: > model.add_change_listener(mock_listener) #doctest: +ELLIPSIS > Expecting: > [] > ********************************************************************** > File "D:\ProgrammingProjects\MVCExperiments\src\mvcmodel.py", line 14, > in __main__.Model.add_change_listener > Failed example: > model.add_change_listener(mock_listener) #doctest: +ELLIPSIS > Expected: > [] > Got: > [] > > As far as I can tell from the Doctest documentation this test should > have passed. > > Any help on what I am doing wrong would be much appreciated. > > Thanks, > > Don. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From ukc802591034 at btconnect.com Sat Apr 1 22:32:25 2006 From: ukc802591034 at btconnect.com (Alan Gauld) Date: Sat, 1 Apr 2006 21:32:25 +0100 Subject: [Tutor] Python tutor References: <26346.203.145.176.76.1143532255.squirrel@members.hcoop.net> Message-ID: "Noufal Ibrahim" wrote in message news:26346.203.145.176.76.1143532255.squirrel at members.hcoop.net... > Greetings all, Greetings, > the reader learns stuff). Another example that comes to mind is the > tcltutor program to learn TCL. It contains an instruction window, a > code window and an output window. The user is told something, they try > it and the output is visible. I personally used it when I was learning > TCL. The tcltutor is fabulous and I've often toyed with the idea of trying to build a Pythonic version. I particularly like the way you can toggle from newbie view to expert view and get the same feature described in friendly English prose through to the bare man pages. > The python tutorial is great and probably all one needs to learn the > language but I think a more interactive program to teach it might be I tried at one stage producing JavaScripted versions of the code in my tutor where you could step through the code with the active line being highlighted in colour - like a debugger. But after struggling for ages to get one short example to work it seemed too much like hard work! > Do you all think it'll be a worthwhile project? I think it would be a great project. The other one in similar vein is to do a demo program of the Tkinter (and the Tix widgets too) similar to the Tcl/Tk demo program. Again I've had it on my list of 'things to do' for several years now! Alan G. (Back from a weeks vacation in sunny Spain! :-) From dyoo at hkn.eecs.berkeley.edu Sat Apr 1 22:37:41 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 1 Apr 2006 12:37:41 -0800 (PST) Subject: [Tutor] BeautifulSoup - getting cells without new line characters In-Reply-To: Message-ID: > > Have you read a Python tutorial? It seems like some of the things you > > are struggling with might be addressed in general Python material. > > > You consider a thing about me. If I ask something it is because I cannot > find the solution. I do not it by whim. Hello Jonas, Yes, but don't take Kent's question as a personal insult --- he's asking because it looks like you're having trouble interpreting error messages or considering border cases. If you're doing HTML parsing, there's an unspoken assumption that you've already mastered basic programming. After reading the questions you're asking, I agree with Kent; you're struggling with things that you should have already covered in tutorials. Out of curiosity, what tutorials have you looked at? Give us links, and we'll take a look and evaluate them for accuracy. Some Python tutorials are good, but some of them out there are quite bad too. The ones linked from: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers and: http://wiki.python.org/moin/BeginnersGuide/Programmers should be ok. > * for rows in table('tr'): print rows('td') > > it fails when i'm going to get data of each cell using: > > for rows in table('tr'): print rows('td')[0] Just to clarify: when you say it "fails", please try to be more specific. What exactly does Python report as the error? I see that you mention the error message here: http://mail.python.org/pipermail/tutor/2006-March/046103.html But are you looking at the error message and trying to understand what it's saying? It says that the cell doesn't have a zeroth element. And this is probably true! I wouldn't disbelieve the computer on this one. *grin* TD elements probably won't have nested sub-elements. But they may have a 'string' attribute, though, which is what Kent's example used to pull the text out of the TD. But your reply to his message doesn't look like it even responds to Kent's example. It is unclear to us why you're not reading or understanding his example, and just going off and doing something else. If you don't understand a reply, try asking a question about it: we'll be happy to elaborate. Try not to go off so quickly and ignore responses: it gives the impression that you don't care enough to read through things. Anyway, the program snippet above makes assumptions, so let's get those out of the way. Concretely: for rows in table('tr'): print rows('td')[0] makes an assumption that is not necessarely true: * It assumes that each row has a td element. Do you understand the border case here? In particular: * What if you hit a TR table row that does not have any TD columns? >From viewing the wiki web page you gave as an example, I can see several TR's in the page's content that do not have TD's, but only TH's. I'm not certain what BeautifulSoup will do in this situtation --- I suspect that it'll return None --- but in any case, your code has to account for this possibility. From singingxduck at gmail.com Sat Apr 1 23:04:29 2006 From: singingxduck at gmail.com (Orri Ganel) Date: Sat, 01 Apr 2006 16:04:29 -0500 Subject: [Tutor] request for sugestions on fragement of code for generating truth-tables In-Reply-To: <442DCA10.9020104@cc.umanitoba.ca> References: <442DCA10.9020104@cc.umanitoba.ca> Message-ID: <442EEADD.7040705@gmail.com> Brian van den Broek wrote: >Hi all, > >I've been too busy with life to do much Python of late. So, I am a bit >rusty. :-( > >I've got some code that does what it needs to but I think I might be >overlooking a much smoother way to get what I need. > >The code takes a list of strings and returns a list of dictionaries, >where each dictionary uses the strings from the list as keys and >booleans as values. The dictionary list contains a dictionary >exhibiting each possible combination of booleans over the keys, where >these combinations are listed in a systematic way. > >This code works: > >def tva_dict_maker(atoms): > > tvas = [] > val = False > > for k in range(2**len(atoms)): > tvas.append(dict()) > > for i in range(len(atoms)): > key = atoms[i] > > for j in range(2**len(atoms)): > if j % ( len(tvas) / 2.0 ** (i+1) ) == 0: > val = not val > tvas[j][key]=val > > return tvas > >The output I desire is easier to see with a bit of processing (to >impose order on the dicts). So, > >def display_tvas(tvas): > for i in tvas: > for j in sorted(i): > print "%s:%s\t" %(j, i[j]), > print > >Then, the output is like so: > > >>> atoms = ["a","b","c"] > >>> tvas = tva_dict_maker(atoms) > >>> display_tvas(tvas) >a:True b:True c:True >a:True b:True c:False >a:True b:False c:True >a:True b:False c:False >a:False b:True c:True >a:False b:True c:False >a:False b:False c:True >a:False b:False c:False > >>> > >As desired :-) > >But, I can't shake the feeling I'm doing this in a harder than >necessary way :-| > >[This is in the context of writing a program to generate truth-tables >for sentential logic, so that I can easily create answered exercises >for a critical thinking course I've been teaching. (As it is for a >Philosophy class, the truth-values are listed in the opposite order >than in a CompSci context.)] > >Any suggestions would be welcome. > >Best to all, > >Brian vdB >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > > What this shouts immediately to me, at least, is binary numbers and bool(). Just use your favorite binary conversion recipe, and count down from int(len(atoms)*"1",2), converting as you go. And then you take the boolean value of each digit of the binary number. If you need help, let me know as I've completed a working model. HTH, Orri -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. From nospamformeSVP at gmail.com Sat Apr 1 23:12:33 2006 From: nospamformeSVP at gmail.com (Don Taylor) Date: Sat, 01 Apr 2006 16:12:33 -0500 Subject: [Tutor] Doctest, object references and the use of ellipses In-Reply-To: <442ED9C5.8070007@tds.net> References: <442ED9C5.8070007@tds.net> Message-ID: <442EECC1.8040801@gmail.com> Kent Johnson wrote: > Don Taylor wrote: > >>Hi: >> >>I am trying to use Doctest and am having trouble using the ellipsis >>feature when trying to match an object reference. > > > What version of Python are you using? The ELLIPSIS comment was added in > Python 2.4. > I am using 2.4.2 Don. From ukc802591034 at btconnect.com Sat Apr 1 23:28:44 2006 From: ukc802591034 at btconnect.com (Alan Gauld) Date: Sat, 1 Apr 2006 22:28:44 +0100 Subject: [Tutor] Apple Remote "Mouse" References: <20060331042331.75343.qmail@web50405.mail.yahoo.com> Message-ID: "Johnston Jiaa" wrote in message > I recently bought a Macbook Pro from Apple. I'm jealous already... > As it comes with a remote, I thought it would be great to use it as > a mouse when not in Front Row. ... > Is there any way to manipulate the cursor position on the screen using > Python? This is really about programming Cocoa more than it is about Python. You need to look at how you would do this in Objective C first then translate that to Python using the Cocoa wrappers for MacPython. It should all be feasible but I'd start looking on the Apple development sites first - have you checked the fantastic programmer's pages on the Apple site at: http://developer.apple.com/ If you haven't already done so sogn up to the developers email list. Not only do you get advance news of developments in Apple land but they post new articles and how-tos every week or so. Also worth keeping an eye on is O'Reilly's MacDevCenter http://www.macdevcenter.com/ And finally Stepwise's Vermont recipes are great: http://www.stepwise.com/ Look in particular at the starting Cocoa and Articles links. For your purpose you will need to create mouse events and then post them to the applications event queue using the postEvent method. There are several factory methods available for creating events. Warning: This is not a trivial task and will involve some fairly deep reading about the Apple event model and the mouse event definitions in particular. But it is doable. HTH, -- Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From nospamformeSVP at gmail.com Sat Apr 1 23:33:45 2006 From: nospamformeSVP at gmail.com (Don Taylor) Date: Sat, 01 Apr 2006 16:33:45 -0500 Subject: [Tutor] Python tutor In-Reply-To: <26346.203.145.176.76.1143532255.squirrel@members.hcoop.net> References: <26346.203.145.176.76.1143532255.squirrel@members.hcoop.net> Message-ID: Noufal Ibrahim wrote: > Greetings all, > Are there any programs for python that offer an "interactive" tutorial? > Something on the lines of the builtin emacs tutorial (which is While it is not really what you had in mind, I have just discovered the Python Challenge - and it is a lot of fun. http://www.pythonchallenge.com/ Don. From ukc802591034 at btconnect.com Sat Apr 1 23:30:49 2006 From: ukc802591034 at btconnect.com (Alan Gauld) Date: Sat, 1 Apr 2006 22:30:49 +0100 Subject: [Tutor] how to get the content of an XML elements. References: <200603311906.26110.keosophon@khmeros.info> Message-ID: "Keo Sophon" wrote in message news:200603311906.26110.keosophon at khmeros.info... > Is there anyway to get the content of an XML elements. I am using xml.dom. For true XML I think ElemTree (by Fred Lundh?) is the best approach. Try a Google search. Kent uses it as I recall. Alan G. From kent37 at tds.net Sat Apr 1 23:47:06 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 01 Apr 2006 16:47:06 -0500 Subject: [Tutor] how to get the content of an XML elements. In-Reply-To: References: <200603311906.26110.keosophon@khmeros.info> Message-ID: <442EF4DA.4050304@tds.net> Alan Gauld wrote: > "Keo Sophon" wrote in message > news:200603311906.26110.keosophon at khmeros.info... > > >>Is there anyway to get the content of an XML elements. I am using xml.dom. > > > For true XML I think ElemTree (by Fred Lundh?) is the best approach. > Try a Google search. Yes, it's ElementTree though. Keo, what do you mean, "get the content of an XML elements"? Kent From jonasmg at softhome.net Sat Apr 1 23:51:36 2006 From: jonasmg at softhome.net (jonasmg at softhome.net) Date: Sat, 01 Apr 2006 14:51:36 -0700 Subject: [Tutor] BeautifulSoup - getting cells without new line characters In-Reply-To: References: Message-ID: Danny Yoo writes: > > >> > Have you read a Python tutorial? It seems like some of the things you >> > are struggling with might be addressed in general Python material. >> >> >> You consider a thing about me. If I ask something it is because I cannot >> find the solution. I do not it by whim. > > Hello Jonas, > > Yes, but don't take Kent's question as a personal insult --- he's asking > because it looks like you're having trouble interpreting error messages or > considering border cases. > Sorry Kent if my answer was very rude. I very was tired to try many things without no good result. > Anyway, the program snippet above makes assumptions, so let's get those > out of the way. Concretely: > > for rows in table('tr'): > print rows('td')[0] > > makes an assumption that is not necessarely true: > > * It assumes that each row has a td element. > > Do you understand the border case here? In particular: > > * What if you hit a TR table row that does not have any TD columns? > Danny, you give me the idea. The problem is that the first row has TH columns (not TD). So: for row in table('tr'): if row('td'): print row('td')[0].string From nospamformeSVP at gmail.com Sat Apr 1 23:51:37 2006 From: nospamformeSVP at gmail.com (Don Taylor) Date: Sat, 01 Apr 2006 16:51:37 -0500 Subject: [Tutor] Python tutor In-Reply-To: References: <26346.203.145.176.76.1143532255.squirrel@members.hcoop.net> Message-ID: Alan Gauld wrote: > > I tried at one stage producing JavaScripted versions of the code in my > tutor where you could step through the code with the active line being > highlighted in colour - like a debugger. But after struggling for ages to > get > one short example to work it seemed too much like hard work! > I found this site the other day and I thought that it would not be too difficult to generalize this technique into a simple tool for authoring tutorials. http://www.jorendorff.com/toys/ Don. From jonasmg at softhome.net Sun Apr 2 00:14:14 2006 From: jonasmg at softhome.net (jonasmg at softhome.net) Date: Sat, 01 Apr 2006 15:14:14 -0700 Subject: [Tutor] BeautifulSoup - getting cells without new line characters In-Reply-To: References: Message-ID: And the solution to get the state and capital columns (where there are anchors): for row in table('tr'): for cell in row.fetch('a')[0:2]: print cell.string From alan.gauld at freenet.co.uk Sun Apr 2 00:49:16 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 1 Apr 2006 23:49:16 +0100 Subject: [Tutor] Python tutor References: <26346.203.145.176.76.1143532255.squirrel@members.hcoop.net> Message-ID: <013001c655de$81750b70$0b01a8c0@xp> >> I tried at one stage producing JavaScripted versions of the code in my > > I found this site the other day and I thought that it would not be too > difficult to generalize this technique into a simple tool for authoring > tutorials. > > http://www.jorendorff.com/toys/ Yes, this is similar to something else I tried which was a collapsing editor style presentation where you could collapse or expand functions. The problem was that I found it difficult to get a version that worked properly on all browsers and the amount of code to get it universal was too much for me to tolerate in a web page! (I'm a minimalist when it comes to HTML!) Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From tim.peters at gmail.com Sun Apr 2 01:12:04 2006 From: tim.peters at gmail.com (Tim Peters) Date: Sat, 1 Apr 2006 18:12:04 -0500 Subject: [Tutor] Doctest, object references and the use of ellipses In-Reply-To: References: Message-ID: <1f7befae0604011512m4d169e3ft3ca776ef352b50df@mail.gmail.com> [Don Taylor] > I am trying to use Doctest and am having trouble using the ellipsis > feature when trying to match an object reference. > > Here is the code: > > def add_change_listener(self, listener): > ''' > > Returns list of listeners just for testing. > >>> def mock_listener(): > ... pass > >>> model = Model() > >>> model.add_change_listener(mock_listener) #doctest: +ELLIPSIS > [] > > ''' > > self.listeners.append(listener) > return self.listeners > > This is what I get back: > > Trying: > model.add_change_listener(mock_listener) #doctest: +ELLIPSIS > Expecting: > [] > ********************************************************************** > File "D:\ProgrammingProjects\MVCExperiments\src\mvcmodel.py", line 14, > in __main__.Model.add_change_listener > Failed example: > model.add_change_listener(mock_listener) #doctest: +ELLIPSIS > Expected: > [] > Got: > [] That "should work", provided there aren't differences in whitespace that are invisible to us in this medium. For example, if, in your source file, there's actually a (one or more) trailing space on your line of expected output, then it would _not_ match the actual output. Try adding +REPORT_NDIFF to your #doctest options; that will point out all differences (including whitespace). From artificiallystupid at yahoo.com Sun Apr 2 01:13:55 2006 From: artificiallystupid at yahoo.com (Johnston Jiaa) Date: Sat, 1 Apr 2006 15:13:55 -0800 (PST) Subject: [Tutor] Apple Remote "Mouse" Message-ID: <20060401231355.36011.qmail@web50409.mail.yahoo.com> Hey Alan, I'm fairly new to programming and this is my first Apple computer. It arrives on Monday, I've been waiting for ages. Amazon took forever shipping it out. Anyway, this will ultimately be a true learning experience -- I'll tell you how it turns out! Many thanks for giving me these pointers, I'll check out all the sites and be immersed in all these Apple pages the next couple of weeks or so. Johnston Jiaa (artificiallystupid at yahoo.com) --------------------------------- Blab-away for as little as 1?/min. Make PC-to-Phone Calls using Yahoo! Messenger with Voice. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060401/a7732018/attachment.htm From nospamformeSVP at gmail.com Sun Apr 2 01:30:07 2006 From: nospamformeSVP at gmail.com (Don Taylor) Date: Sat, 01 Apr 2006 18:30:07 -0500 Subject: [Tutor] Doctest, object references and the use of ellipses In-Reply-To: <1f7befae0604011512m4d169e3ft3ca776ef352b50df@mail.gmail.com> References: <1f7befae0604011512m4d169e3ft3ca776ef352b50df@mail.gmail.com> Message-ID: Tim Peters wrote: > That "should work", provided there aren't differences in whitespace > that are invisible to us in this medium. For example, if, in your > source file, there's actually a (one or more) trailing space on your > line of expected output, then it would _not_ match the actual output. > Try adding +REPORT_NDIFF to your #doctest options; that will point out > all differences (including whitespace). Oh, thank you! Yes, there was a trailing whitespace. And yes I did read the manual that warned about this but I guess it did not register deep enough into my reptile brain (you know, the Python brain). I will try not to do this again (and I probably won't). Don. From tim.peters at gmail.com Sun Apr 2 01:42:29 2006 From: tim.peters at gmail.com (Tim Peters) Date: Sat, 1 Apr 2006 18:42:29 -0500 Subject: [Tutor] Doctest, object references and the use of ellipses In-Reply-To: References: <1f7befae0604011512m4d169e3ft3ca776ef352b50df@mail.gmail.com> Message-ID: <1f7befae0604011542j615906a8wa5904635bfd0840@mail.gmail.com> [Tim Peters] >> That "should work", provided there aren't differences in whitespace >> that are invisible to us in this medium. For example, if, in your >> source file, there's actually a (one or more) trailing space on your >> line of expected output, then it would _not_ match the actual output. >> Try adding +REPORT_NDIFF to your #doctest options; that will point out >> all differences (including whitespace). [Don Taylor] > Oh, thank you! Cool -- glad it worked! > Yes, there was a trailing whitespace. And yes I did read the manual > that warned about this but I guess it did not register deep enough into > my reptile brain (you know, the Python brain). > > I will try not to do this again (and I probably won't). I'll share a secret :-) I work on Python development, and a few times per week I run this from the root of a Python checkout (this is on Windows, BTW): python \Python24\Tools\Scripts\reindent.py -r . reindent.py is in your distribution too. It ensures (by rewriting files as needed) that all .py files reachable from "." conform to core Python's whitespace standards, which includes things like 4-space indentation, no hard tab characters, and no trailing whitespace on any lines. All the .py files in a distribution are automatically kept free of "whitespace surprises" this way. You're allowed to run that on your code too ;-) From dyoo at hkn.eecs.berkeley.edu Sun Apr 2 03:54:37 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 1 Apr 2006 17:54:37 -0800 (PST) Subject: [Tutor] BeautifulSoup - getting cells without new line characters In-Reply-To: Message-ID: > And the solution to get the state and capital columns (where there are > anchors): > > for row in table('tr'): > for cell in row.fetch('a')[0:2]: > print cell.string Hi Jonas, That's good to hear! So does everything work for you then? From jonasmg at softhome.net Sun Apr 2 10:46:35 2006 From: jonasmg at softhome.net (jonasmg at softhome.net) Date: Sun, 02 Apr 2006 01:46:35 -0700 Subject: [Tutor] BeautifulSoup - getting cells without new line characters In-Reply-To: References: Message-ID: Danny Yoo writes: > > >> And the solution to get the state and capital columns (where there are >> anchors): >> >> for row in table('tr'): >> for cell in row.fetch('a')[0:2]: >> print cell.string > > Hi Jonas, > > That's good to hear! So does everything work for you then? > Now yes, this problem has been resolved. Thanks! From k.r.fry at durham.ac.uk Mon Apr 3 13:36:12 2006 From: k.r.fry at durham.ac.uk (k r fry) Date: Mon, 03 Apr 2006 12:36:12 +0100 Subject: [Tutor] oserror [errno 20] Message-ID: <443108AC.2000205@durham.ac.uk> Hi, I am new to this list, and also to Python. I am trying to get Python to loop through the directory DATADIR which contains the data I want to read. I get an error: "oserror [errno 20] : Not a directory: "Katiescint.py" The section of code is shown below: for subdir in os.listdir(DATADIR): #loop through list of strings file=FITS.Read(DATADIR+'/'+subdir+'/flux.fits') #opens flux.fits file and reads summation=open(DATADIR+'/'+subdir+'/flux.dat','w') #opens the summation results file for writing to spotbyspot=open(DATADIR+'/'+subdir+'/spotflux.dat','w') #opens the spot-by-spot file for writing to output='' print'\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n'+sys.argv[1]+' '+subdir+'\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n' I would be very grateful if anyone could help me. Thanks! From ewald.ertl at hartter.com Mon Apr 3 15:11:55 2006 From: ewald.ertl at hartter.com (Ewald Ertl) Date: Mon, 03 Apr 2006 15:11:55 +0200 Subject: [Tutor] oserror [errno 20] In-Reply-To: <443108AC.2000205@durham.ac.uk> References: <443108AC.2000205@durham.ac.uk> Message-ID: <44311F1B.7000501@hartter.com> Hi, k r fry wrote: > Hi, I am new to this list, and also to Python. > I am trying to get Python to loop through the directory DATADIR which > contains the data I want to read. I get an error: "oserror [errno 20] > : Not a directory: "Katiescint.py" > > The section of code is shown below: > > for subdir in os.listdir(DATADIR): #loop through list of os.listdir() lists the content of the directory referenced by DATADIR. If regular files are in this directory, these are also listed. You have to check, if subdir is really a directory before using this any further. > strings > > file=FITS.Read(DATADIR+'/'+subdir+'/flux.fits') #opens > flux.fits file and reads > > summation=open(DATADIR+'/'+subdir+'/flux.dat','w') #opens the > summation results file for writing to > > spotbyspot=open(DATADIR+'/'+subdir+'/spotflux.dat','w') #opens the > spot-by-spot file for writing to > > output='' > print'\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n'+sys.argv[1]+' > '+subdir+'\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n' > > I would be very grateful if anyone could help me. Thanks! > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > HTH Ewald From janos.juhasz at VELUX.com Mon Apr 3 17:14:16 2006 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Mon, 3 Apr 2006 17:14:16 +0200 Subject: [Tutor] defined() In-Reply-To: Message-ID: An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060403/5058fac0/attachment.html From tim.golden at viacom-outdoor.co.uk Mon Apr 3 17:23:12 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Mon, 3 Apr 2006 16:23:12 +0100 Subject: [Tutor] defined() Message-ID: [J?nos Juh?sz] | I can't find the defined() function in python, so I used | | 'variable name' in dir() | | for check if the variable defined. | | >>> name = 'Joe' | >>> if 'name' in dir(): | ... print name | ... I'm not entirely sure where you'd want to use this, but probably the most Pythonic way of doing this would be: name = "Joe" try: name except NameError: print "name not defined" else: print "name defined" I suspect that your idea of variable definition doesn't quite match Python's concept. In short, it's impossible to "declare" a variable in Python without binding it to *something*. ie a variable is always a binding to an object, not a hole waiting to be filled. You could, if you wanted, initialise name to None (or some other sentinel value) and then check against that, either explicitly: if name is None: print "name unitialised" or by taking advantage of the fact that several empty objects in Python are considered False: if not Name: print "name unitialised" Hope that helps more than it confuses. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From stvsmth at gmail.com Mon Apr 3 17:26:37 2006 From: stvsmth at gmail.com (stv) Date: Mon, 3 Apr 2006 11:26:37 -0400 Subject: [Tutor] List methods/comps Best Practices Message-ID: <9493d0340604030826q4aa24faatc176d8d205382d95@mail.gmail.com> I just thumped my head against the wall for a few hours on something, and I was wondering if it's just my green-ness in Python, or if I'm doing something unsavory. I had several list comprehensions that I was mucking with; these lists are working on a simple subclass of the built-in list object. They looked liked this: filelist = getFilesToAdd() filelist2 = getFilesToDel() adds = MyList('foo') dels = MyList('bar') [adds.add_changes('foo', path) for path in filelist] [dels.add_changes('bar', path) for path in filelist2] # return all changes, deletes first return dels.extend(adds) Since extend returns None, I ran into a lot of not-iterable errors when calling this code. So I fixed this with dels.extend(adds) return dels And all is good, although it took way more head scratching than typing . (In writing this, I now vaguely remember one of my tutorials warning me about something ... maybe this was that? :) So my question is this: Is this just one of those things that I learn the hard way in Pthon & that's it, or am I doing something weird? I shoulda figured this out when I was debugging the method in the interpreter and my original list comprehensions returned [adds.add_changes('foo', path) for path in filelist] >>> [None, None, None] as each call to add_changes returned no value. Alas, I'm not that smart. Is it bad form to not have an "assignment" for the list comps? From khp at pflaesterer.de Mon Apr 3 18:20:06 2006 From: khp at pflaesterer.de (Karl =?iso-8859-1?Q?Pfl=E4sterer?=) Date: Mon, 03 Apr 2006 18:20:06 +0200 Subject: [Tutor] List methods/comps Best Practices In-Reply-To: <9493d0340604030826q4aa24faatc176d8d205382d95@mail.gmail.com> (stv's message of "Mon, 3 Apr 2006 11:26:37 -0400") References: <9493d0340604030826q4aa24faatc176d8d205382d95@mail.gmail.com> Message-ID: On 3 Apr 2006, stvsmth at gmail.com wrote: > I had several list comprehensions that I was mucking with; these lists > are working on a simple subclass of the built-in list object. They > looked liked this: > > filelist = getFilesToAdd() > filelist2 = getFilesToDel() > > adds = MyList('foo') > dels = MyList('bar') > > [adds.add_changes('foo', path) for path in filelist] > [dels.add_changes('bar', path) for path in filelist2] > > # return all changes, deletes first > return dels.extend(adds) > > Since extend returns None, I ran into a lot of not-iterable errors > when calling this code. So I fixed this with > > dels.extend(adds) > return dels > > And all is good, although it took way more head scratching than typing > . (In writing this, I now vaguely remember one of my tutorials warning > me about something ... maybe this was that? :) > > So my question is this: Is this just one of those things that I learn > the hard way in Pthon & that's it, or am I doing something weird? I > shoulda figured this out when I was debugging the method in the > interpreter and my original list comprehensions returned > > [adds.add_changes('foo', path) for path in filelist] > >>> [None, None, None] > > as each call to add_changes returned no value. Alas, I'm not that > smart. Is it bad form to not have an "assignment" for the list comps? In short: IMO yes it's not good practice; the list comprehension is used to create a list. If you don't need the list write a loop. So don't write: [adds.add_changes('foo', path) for path in filelist] but: for path in filelist: adds.add_changes('foo', path) Or show us more explicitly what you want to achieve, sice you don't tell us what add_changes() does. Karl -- Please do *not* send copies of replies to me. I read the list From ukc802591034 at btconnect.com Mon Apr 3 19:07:26 2006 From: ukc802591034 at btconnect.com (Alan Gauld) Date: Mon, 3 Apr 2006 18:07:26 +0100 Subject: [Tutor] defined() References: Message-ID: > I can't find the defined() function in python, so I used >'variable name' in dir() > Is it really missing, or I am just so simple ? It is really missing, just as it is for most programming languages. Which language(s) do you know that has such a feature? And why do you consider it so useful that you expect to find it in Python? The main place where I could see such a thing being useful would be in dynamically loaded code but then the usual approach is to load a dictionary and an 'in' check suffices. I'm interested in what use you would make of such a thing? -- Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From ukc802591034 at btconnect.com Mon Apr 3 19:57:33 2006 From: ukc802591034 at btconnect.com (Alan Gauld) Date: Mon, 3 Apr 2006 18:57:33 +0100 Subject: [Tutor] oserror [errno 20] References: <443108AC.2000205@durham.ac.uk> Message-ID: "k r fry" wrote in message news:443108AC.2000205 at durham.ac.uk... > Hi, I am new to this list, and also to Python. > I am trying to get Python to loop through the directory DATADIR which > contains the data I want to read. I get an error: "oserror [errno 20] > : Not a directory: "Katiescint.py" That tells you that the code is finding a file called Katiescint.py in DATADIR and that youy are trying to treat it as a directory when it clearly isn't. But it's better to send the whole stacktrace error message in future since that tells us *where* the problem lies as well as what it is! > for subdir in os.listdir(DATADIR): #loop through list of listdir lists files as well as directories. > file=FITS.Read(DATADIR+'/'+subdir+'/flux.fits') > #opens flux.fits file and reads I'll need to take your word for that. I assume FITS is a module? and Read is a function within that module? All caps normally indicates a constant in Python - its only a convention but a pretty common one. And functions usually start in lowercase (and classes in uppercase) but again thats a convention and less rigorously followed. Also 'file' is a function (actually an alias for open() ) so using it as a variable name could cause confusion. > summation=open(DATADIR+'/'+subdir+'/flux.dat','w') #opens the > spotbyspot=open(DATADIR+'/'+subdir+'/spotflux.dat','w') #opens the And here is where you use the file as a directory and cause the error. HTH, -- Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From victor at grupocdm.com Mon Apr 3 17:40:59 2006 From: victor at grupocdm.com (Victor Bouffier) Date: Mon, 03 Apr 2006 10:40:59 -0500 Subject: [Tutor] Bigrams and nested dictionaries In-Reply-To: <6FD8FE0A-2A38-4611-A207-5743FF863C5A@columbus.rr.com> References: <6FD8FE0A-2A38-4611-A207-5743FF863C5A@columbus.rr.com> Message-ID: <1144078859.20791.4.camel@elrond> On Wed, 2006-03-29 at 00:15 -0500, Michael Broe wrote: > Aha! John wrote: > > "Are you sure you haven't mistakenly assigned something other than a > dict to D or D['d'] ?" > > Thanks for the tip! Yup that was it (and apologies for not reporting > the problem more precisely). I hadn't initialized the nested > dictionary before trying to assign to it. (I think Perl doesn't > require initialization of dictionaries prior to assignment, which in > this case, would be a nice thing...) > > >>> D['c']['a'] = 1 #ooops > Traceback (most recent call last): > File "", line 1, in ? > KeyError: 'c' > >>> D['c'] = {} > >>> D['c']['a'] = 1 > >>> D > {'a': {'a': 1, 'b': 2}, 'c': {'a': 1}} > You can check if the dictionary key exists prior to assigning to it: >>> if not D.has_key('c'): ... D['c'] = {} >>> D['c']['a'] = 1 From dyoo at hkn.eecs.berkeley.edu Mon Apr 3 20:39:56 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 3 Apr 2006 11:39:56 -0700 (PDT) Subject: [Tutor] Bigrams and nested dictionaries In-Reply-To: <1144078859.20791.4.camel@elrond> Message-ID: > You can check if the dictionary key exists prior to assigning to it: > > >>> if not D.has_key('c'): > ... D['c'] = {} > >>> D['c']['a'] = 1 Hi Victor, Another approach is to use the badly-named "setdefault()" method which is a close analogue to Perl's "autovivification" feature: ###### >>> D = {} >>> D.setdefault('c', {})['a'] = 1 >>> D {'c': {'a': 1}} ###### Good luck! From kent37 at tds.net Mon Apr 3 20:57:07 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 03 Apr 2006 14:57:07 -0400 Subject: [Tutor] List methods/comps Best Practices In-Reply-To: <9493d0340604030826q4aa24faatc176d8d205382d95@mail.gmail.com> References: <9493d0340604030826q4aa24faatc176d8d205382d95@mail.gmail.com> Message-ID: <44317003.8060007@tds.net> stv wrote: > # return all changes, deletes first > return dels.extend(adds) > > Since extend returns None, I ran into a lot of not-iterable errors > when calling this code. So I fixed this with > > dels.extend(adds) > return dels > > And all is good, although it took way more head scratching than typing > . (In writing this, I now vaguely remember one of my tutorials warning > me about something ... maybe this was that? :) > > So my question is this: Is this just one of those things that I learn > the hard way in Pthon & that's it, or am I doing something weird? In general, mutating methods return None. For example list.append(), list.sort(), list.extend() all return None. This is an intentional design choice in Python. The idea is it keeps you from mistakenly mutating an object. Kent From alan.gauld at freenet.co.uk Mon Apr 3 21:38:08 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 3 Apr 2006 20:38:08 +0100 Subject: [Tutor] Bigrams and nested dictionaries References: <6FD8FE0A-2A38-4611-A207-5743FF863C5A@columbus.rr.com> <1144078859.20791.4.camel@elrond> Message-ID: <005301c65756$22f91130$0b01a8c0@xp> > On Wed, 2006-03-29 at 00:15 -0500, Michael Broe wrote: > You can check if the dictionary key exists prior to assigning to it: > >>>> if not D.has_key('c'): > ... D['c'] = {} >>>> D['c']['a'] = 1 And since 2.4? if 'c' in D: ... Alan G. From victor at grupocdm.com Tue Apr 4 00:08:00 2006 From: victor at grupocdm.com (Victor Bouffier) Date: Mon, 03 Apr 2006 17:08:00 -0500 Subject: [Tutor] Bigrams and nested dictionaries In-Reply-To: References: Message-ID: <1144102080.20791.8.camel@elrond> On Mon, 2006-04-03 at 11:39 -0700, Danny Yoo wrote: > > You can check if the dictionary key exists prior to assigning to it: > > > > >>> if not D.has_key('c'): > > ... D['c'] = {} > > >>> D['c']['a'] = 1 > > > Hi Victor, > > Another approach is to use the badly-named "setdefault()" method which is > a close analogue to Perl's "autovivification" feature: > > ###### > >>> D = {} > >>> D.setdefault('c', {})['a'] = 1 > >>> D > {'c': {'a': 1}} > ###### > > Good luck! > Thanks to both Danny and Alan. Great tips. Victor From stvsmth at gmail.com Tue Apr 4 00:19:59 2006 From: stvsmth at gmail.com (stv) Date: Mon, 3 Apr 2006 18:19:59 -0400 Subject: [Tutor] List methods/comps Best Practices In-Reply-To: References: <9493d0340604030826q4aa24faatc176d8d205382d95@mail.gmail.com> Message-ID: <9493d0340604031519i1621185u2c6bdb4c5d7b881a@mail.gmail.com> > So don't write: > [adds.add_changes('foo', path) for path in filelist] > but: > for path in filelist: adds.add_changes('foo', path) Excellent point; new toy, got carrid away :) I feel silly on that one. And now that I've made the return list.extend(foo) mistake, I'll surely neve- ... er, wait a long time before I make that mistake again. Thanks folks. On 4/3/06, Karl Pfl?sterer wrote: From hugonz-lists at h-lab.net Tue Apr 4 01:00:14 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Mon, 03 Apr 2006 17:00:14 -0600 Subject: [Tutor] defined() In-Reply-To: References: Message-ID: <4431A8FE.7060100@h-lab.net> Alan Gauld wrote: > Which language(s) do you know that has such a feature? > And why do you consider it so useful that you expect to find > it in Python? I'm not the original poster, but being a perlhead before, I can say it exists in Perl. It is very often used too. I used to miss it at first, but normally I now do the right thing semantically. Counting on the variable being defined or not is simply another bit of information. Assigning a value for that case is much cleaner. It is not used for black magic in Perl, AFAIK. Just normal testing. Hugo From bgailer at alum.rpi.edu Tue Apr 4 03:10:34 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon, 03 Apr 2006 18:10:34 -0700 Subject: [Tutor] defined() In-Reply-To: <4431A8FE.7060100@h-lab.net> References: <4431A8FE.7060100@h-lab.net> Message-ID: <4431C78A.8010702@alum.rpi.edu> Hugo Gonz?lez Monteverde wrote: > Alan Gauld wrote: > > >> Which language(s) do you know that has such a feature? >> And why do you consider it so useful that you expect to find >> it in Python? >> > > I'm not the original poster, but being a perlhead before, I can say it > exists in Perl. It is very often used too. > And you can "roll your own" in Python: def defined(name): return name in globals() > I used to miss it at first, but normally I now do the right thing > semantically. Counting on the variable being defined or not is simply > another bit of information. Assigning a value for that case is much cleaner. > > It is not used for black magic in Perl, AFAIK. Just normal testing. > > Hugo > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From tim at johnsons-web.com Tue Apr 4 03:10:05 2006 From: tim at johnsons-web.com (Tim Johnson) Date: Mon, 3 Apr 2006 17:10:05 -0800 Subject: [Tutor] defined() In-Reply-To: References: Message-ID: <20060404011005.GJ13866@johnsons-web.com> * Alan Gauld [060403 09:10]: > > > I can't find the defined() function in python, so I used > >'variable name' in dir() > > > Is it really missing, or I am just so simple ? > > It is really missing, just as it is for most programming languages. > Which language(s) do you know that has such a feature? > And why do you consider it so useful that you expect to find > it in Python? In rebol, there is a predicate called value? Sample console session below: >> test: [a 1 b 2 c 3] == [one 1 two 2 three 3] >> value? test/1 == false >> value? test/2 == true == [a 1 b 2 c 3] >> test/a == 1 Don't as much about lisp as I do rebol and python, but lisp has symbols, which don't necessarily have values. > The main place where I could see such a thing being useful > would be in dynamically loaded code but then the usual > approach is to load a dictionary and an 'in' check suffices. > Rebol doesn't have dictionaries (it should IMHO), you could also use value? after importing a module to check if some word existed in the module namespace. Kind of like hasattr() > I'm interested in what use you would make of such a thing? My business partner is a perl programmer. He uses defined() a lot, I think, I've seen it in his code.... I use value? a lot in rebol. I like python's in operator. Very handy tim -- Tim Johnson http://www.alaska-internet-solutions.com From dyoo at hkn.eecs.berkeley.edu Tue Apr 4 04:06:28 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 3 Apr 2006 19:06:28 -0700 (PDT) Subject: [Tutor] defined() In-Reply-To: <20060404011005.GJ13866@johnsons-web.com> Message-ID: > > I'm interested in what use you would make of such a thing? > My business partner is a perl programmer. He uses defined() a lot, I > think, I've seen it in his code.... Hello! The common idiom in Perl, I think, is to at least declare the variable, even if one doesn't give an initial value, like this: ############################################# ## Perl pseudocode ## use strict; my $name; ## do things here that should initialize name if (! defined($name)) { # handle degenerate case here } ############################################# But this is very different than: ############################################# ## Perl pseudocode that doesn't use strict ## do things here that should initialize name if (! defined($name)) { # handle degenerate case here } ############################################# Now, if your business partner doesn't have the line 'use strict' in their code, then give them a good kick and tell them to use it! It's criminal for a professonal Perl programmer not to "use strict", and I feel almost foolish about bringing this up. But it has to be said, just in case. *grin* In Python, the first assignment to a variable name has the same effect as declaration, so the first Perl snippet has a translation like: ############################################# ## Python pseudocode name = None ## do things here that should initialize name if name is None: ## handle degenerate case here ############################################# where we can use None as our uninitialized value. Hope this helps! From tim at johnsons-web.com Tue Apr 4 04:26:04 2006 From: tim at johnsons-web.com (Tim Johnson) Date: Mon, 3 Apr 2006 18:26:04 -0800 Subject: [Tutor] defined() In-Reply-To: References: <20060404011005.GJ13866@johnsons-web.com> Message-ID: <20060404022604.GK13866@johnsons-web.com> * Danny Yoo [060403 18:14]: > > > > I'm interested in what use you would make of such a thing? > > My business partner is a perl programmer. He uses defined() a lot, I > > think, I've seen it in his code.... > > Now, if your business partner doesn't have the line 'use strict' in their > code, then give them a good kick and tell them to use it! It's criminal > for a professonal Perl programmer not to "use strict", I'm sure he has his "stay out of jail card". I know he always uses it. -- Tim Johnson http://www.alaska-internet-solutions.com From tim at johnsons-web.com Tue Apr 4 04:28:46 2006 From: tim at johnsons-web.com (Tim Johnson) Date: Mon, 3 Apr 2006 18:28:46 -0800 Subject: [Tutor] defined() In-Reply-To: <4431C78A.8010702@alum.rpi.edu> References: <4431A8FE.7060100@h-lab.net> <4431C78A.8010702@alum.rpi.edu> Message-ID: <20060404022846.GL13866@johnsons-web.com> * Bob Gailer [060403 17:12]: > > def defined(name): > return name in globals() > Hah! Good tip. I'll call it value() I think "language wars" are a waste of time, but I like the way that using different languages inform the programmer. cheers tj -- Tim Johnson http://www.alaska-internet-solutions.com From hokkakada at khmeros.info Tue Apr 4 04:32:25 2006 From: hokkakada at khmeros.info (kakada) Date: Tue, 04 Apr 2006 09:32:25 +0700 Subject: [Tutor] file? Message-ID: <4431DAB9.3050405@khmeros.info> Hi all, How can we know that one specific file is already exist in filesystem? for instance, I want to read zipfile by issuing code: import zipfile ziparchive = zipfile.ZipFile(inputfilename, "r") if the inputfilename doesn't exist then an error would be occurred. I want to catch up this special case first. Thanks, da From john at fouhy.net Tue Apr 4 04:39:12 2006 From: john at fouhy.net (John Fouhy) Date: Tue, 4 Apr 2006 14:39:12 +1200 Subject: [Tutor] file? In-Reply-To: <4431DAB9.3050405@khmeros.info> References: <4431DAB9.3050405@khmeros.info> Message-ID: <5e58f2e40604031939q6aceceafi5f525a90084a7ffe@mail.gmail.com> On 04/04/06, kakada wrote: > How can we know that one specific file is already exist in filesystem? Have a look in the os and os.path modules. In this case, os.path.exists is probably what you want: if not os.path.exists(inputfilename): print 'Oops, file does not exist!' sys.exit() ziparchive = zipfile.ZipFile(inputfilename, 'r') # ... -- John. From kent37 at tds.net Tue Apr 4 04:41:45 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 03 Apr 2006 22:41:45 -0400 Subject: [Tutor] file? In-Reply-To: <4431DAB9.3050405@khmeros.info> References: <4431DAB9.3050405@khmeros.info> Message-ID: <4431DCE9.5060908@tds.net> kakada wrote: > Hi all, > > How can we know that one specific file is already exist in filesystem? > for instance, I want to read zipfile by issuing code: > > import zipfile > ziparchive = zipfile.ZipFile(inputfilename, "r") > > if the inputfilename doesn't exist then an error would be occurred. > I want to catch up this special case first. if os.path.isfile(inputfilename): # file exists Kent From david at graniteweb.com Tue Apr 4 05:26:06 2006 From: david at graniteweb.com (David Rock) Date: Mon, 3 Apr 2006 22:26:06 -0500 Subject: [Tutor] file? In-Reply-To: <4431DAB9.3050405@khmeros.info> References: <4431DAB9.3050405@khmeros.info> Message-ID: <20060404032606.GA8068@wdfs.graniteweb.com> * kakada [2006-04-04 09:32]: > Hi all, > > How can we know that one specific file is already exist in filesystem? > for instance, I want to read zipfile by issuing code: > > import zipfile > ziparchive = zipfile.ZipFile(inputfilename, "r") > > if the inputfilename doesn't exist then an error would be occurred. > I want to catch up this special case first. The key here is to actually "catch" the exception. Python is very good at assuming something will work, and then deal only with the exceptions: import zipfile try: ziparchive = zipfile.ZipFile(inputfilename, "r") except: print "error accessing file" You could get fancy and deal with various exceptions or read traceback info, too. Using the try block is generally considered a more Pythonic way of handling the problem. :-) -- David Rock david at graniteweb.com From mbroe at columbus.rr.com Tue Apr 4 06:37:21 2006 From: mbroe at columbus.rr.com (Michael Broe) Date: Tue, 4 Apr 2006 00:37:21 -0400 Subject: [Tutor] Bigrams and nested dictionaries In-Reply-To: References: Message-ID: Well coming up with this has made me really love Python. I worked on this with my online pythonpenpal Kyle, and here is what we came up with. Thanks to all for input so far. My first idea was to use a C-type indexing for-loop, to grab a two- element sequence [i, i+1]: dict = {} for i in range(len(t) - 1): if not dict.has_key(t[i]): dict[t[i]] = {} if not dict[t[i]].has_key(t[i+1]): dict[t[i]][t[i+1]] = 1 else: dict[t[i]][t[i+1]] += 1 Which works, but. Kyle had an alternative take, with no indexing, and after we worked on this strategy it seemed very Pythonesque, and ran almost twice as fast. ---- #!/usr/local/bin/python import sys file = open(sys.argv[1], 'rb').read() # We imagine a 2-byte 'window' moving over the text from left to right # # +-------+ # L o n | d o | n . M i c h a e l m a s t e r m ... # +-------+ # # At any given point, we call the leftmost byte visible in the window 'L', and the # rightmost byte 'R'. # # +-----------+ # L o n | L=d R=o | n . M i c h a e l m a s t e r m ... # +-----------+ # # When the program begins, the first byte is preloaded into L, and we position R # at the second byte of the file. # dict = {} L = file[0] for R in file[1:]: # move right edge of window across the file if not L in dict: dict[L] = {} if not R in dict[L]: dict[L][R] = 1 else: dict[L][R] += 1 L = R # move character in R over to L # that's it. here's a printout strategy: for entry in dict: print entry, ':', sum(dict[entry].values()) print dict[entry] print ---- From singingxduck at gmail.com Tue Apr 4 06:52:53 2006 From: singingxduck at gmail.com (Orri Ganel) Date: Tue, 4 Apr 2006 00:52:53 -0400 Subject: [Tutor] Bigrams and nested dictionaries In-Reply-To: References: Message-ID: <3449428f0604032152p43e4412fk38bb2ca2ffe38d81@mail.gmail.com> My only comment is that this considers spaces and punctuation (like parentheses, brackets, etc.), too, which I assume you don't want seeing as how that has little to do with natural languages. My suggestion would be to remove the any punctuation or whitespace keys from the dictionary after you've built the dictionary. Unless, of course, you're interested in what letter words start with, in which case you could somehow merge them into a single key? Cheers, Orri On 4/4/06, Michael Broe wrote: > > Well coming up with this has made me really love Python. I worked on > this with my online pythonpenpal Kyle, and here is what we came up > with. Thanks to all for input so far. > > My first idea was to use a C-type indexing for-loop, to grab a two- > element sequence [i, i+1]: > > dict = {} > for i in range(len(t) - 1): > if not dict.has_key(t[i]): > dict[t[i]] = {} > if not dict[t[i]].has_key(t[i+1]): > dict[t[i]][t[i+1]] = 1 > else: > dict[t[i]][t[i+1]] += 1 > > Which works, but. Kyle had an alternative take, with no indexing, and > after we worked on this strategy it seemed very Pythonesque, and ran > almost twice as fast. > > ---- > > #!/usr/local/bin/python > > import sys > file = open(sys.argv[1], 'rb').read() > > # We imagine a 2-byte 'window' moving over the text from left to right > # > # +-------+ > # L o n | d o | n . M i c h a e l m a s t e > r m ... > # +-------+ > # > # At any given point, we call the leftmost byte visible in the window > 'L', and the > # rightmost byte 'R'. > # > # +-----------+ > # L o n | L=d R=o | n . M i c h a e l m a s t > e r m ... > # +-----------+ > # > # When the program begins, the first byte is preloaded into L, and we > position R > # at the second byte of the file. > # > > dict = {} > > L = file[0] > for R in file[1:]: # move right edge of window across the file > if not L in dict: > dict[L] = {} > > if not R in dict[L]: > dict[L][R] = 1 > else: > dict[L][R] += 1 > > L = R # move character in R over to L > > # that's it. here's a printout strategy: > > for entry in dict: > print entry, ':', sum(dict[entry].values()) > print dict[entry] > print > > ---- > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060404/9873c3f4/attachment.html From kaushalshriyan at gmail.com Tue Apr 4 08:22:04 2006 From: kaushalshriyan at gmail.com (Kaushal Shriyan) Date: Tue, 4 Apr 2006 11:52:04 +0530 Subject: [Tutor] Hi Message-ID: <6b16fb4c0604032322u390f7e73y5a22477acd534002@mail.gmail.com> Hi ALL A simple query is that the python mailing List is python powered What does "python powered" means thanks Regards Kaushal From janos.juhasz at VELUX.com Tue Apr 4 08:44:35 2006 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Tue, 4 Apr 2006 08:44:35 +0200 Subject: [Tutor] defined() In-Reply-To: Message-ID: Dear Tim, Dear Alan, >> I can't find the defined() function in python, so I used >>'variable name' in dir() > >> Is it really missing, or I am just so simple ? > > It is really missing, just as it is for most programming languages. > Which language(s) do you know that has such a feature? I should came from Marco Cantu's Delphi 2005 book, that I have read just recently. But I am unable to find it again. > And why do you consider it so useful that you expect to find > it in Python? I don't miss it. It was just a foggy engram, that I couldn't find in the help :) > The main place where I could see such a thing being useful > would be in dynamically loaded code but then the usual > approach is to load a dictionary and an 'in' check suffices. > > I'm interested in what use you would make of such a thing? I just started to make a .leo file, where I wanted to place my scripts. http://webpages.charter.net/edreamleo/front.html I just tried to collect all of my scripts (sql, wmi, admin, snmp ...), and html references, admin knowledge, passwords for active devices... into one place, that can be shared with my colleagues with detailed description about the usage and the reasons to use of them. Leo seems to be a very good candidate for that. An sql script seems to be like this. --------- << ScalaDB >> data = Query(<< Sql >>) << Show Data >> ------------ In the leo file the << ScalaDB >> is simple replaced by the << ScalaDB >> subtree. The script is created dinamically from the texts in the tree. So I just wanted to check in the << Show Data >> part, if the data is defined previously or not. Yours sincerely, ______________________________ Janos Juhasz From alan.gauld at freenet.co.uk Tue Apr 4 09:47:07 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 4 Apr 2006 08:47:07 +0100 Subject: [Tutor] file? References: <4431DAB9.3050405@khmeros.info> Message-ID: <00a501c657bb$f9658a40$0b01a8c0@xp> > How can we know that one specific file is already exist in filesystem? > for instance, I want to read zipfile by issuing code: Take a look in the os.path module. There is explanation of how to check for various aspects of files (including existence) in my web tutor Operating System topic. > if the inputfilename doesn't exist then an error would be occurred. > I want to catch up this special case first. The other approach, implied in your question is simply to *try* to *open* for read: try: open(inputfilename) except IOError: # it presumably didn't exist, so deal with it HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From sanelson at gmail.com Tue Apr 4 10:35:33 2006 From: sanelson at gmail.com (Steve Nelson) Date: Tue, 4 Apr 2006 09:35:33 +0100 Subject: [Tutor] Hi In-Reply-To: <6b16fb4c0604032322u390f7e73y5a22477acd534002@mail.gmail.com> References: <6b16fb4c0604032322u390f7e73y5a22477acd534002@mail.gmail.com> Message-ID: On 4/4/06, Kaushal Shriyan wrote: > Hi ALL > > A simple query is that the python mailing List is python powered > > What does "python powered" means The list, and many like it, use a piece of software called Mailman, which is written in Python. A few years back, the tool of choice was Majordomo, but Mailman is now very popular, partly because of its easy-to-use web interface. > Kaushal S. From titvirak at khmeros.info Tue Apr 4 10:56:27 2006 From: titvirak at khmeros.info (=?UTF-8?B?4Z6R4Z634Z6P4Z+S4Z6Z4Z6c4Z634Z6a4Z+I?=) Date: Tue, 04 Apr 2006 15:56:27 +0700 Subject: [Tutor] how to get data from xml Message-ID: <443234BB.8040703@khmeros.info> Dear all Pythoners, I am quiet new to python and now working with xml. I have an xml like this: 0x6B 0x78 0x4B 0x58 0x67 0x63 0x71 0x43 0x51 0x6A and I want to get data for KA, KHA, KO and so on. Can you guide me a way. Btw, I'm using dom for xml. Thanks, Titvirak From kent37 at tds.net Tue Apr 4 11:57:54 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 04 Apr 2006 05:57:54 -0400 Subject: [Tutor] Bigrams and nested dictionaries In-Reply-To: References: Message-ID: <44324322.8060906@tds.net> Michael Broe wrote: > dict = {} dict is the name of the builtin dictionary class, so you shouldn't use it as the name of your dict - you shadow the built-in name. file is also a built-in name. > > L = file[0] > for R in file[1:]: # move right edge of window across the file > if not L in dict: > dict[L] = {} > > if not R in dict[L]: > dict[L][R] = 1 > else: > dict[L][R] += 1 I might write it this way: dictL = dict.setdefault(L, {}) dictL[R] = dictL.setdefault(R, 0) + 1 though I'm not sure which way will be faster. Kent From kent37 at tds.net Tue Apr 4 12:06:24 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 04 Apr 2006 06:06:24 -0400 Subject: [Tutor] how to get data from xml In-Reply-To: <443234BB.8040703@khmeros.info> References: <443234BB.8040703@khmeros.info> Message-ID: <44324520.1060103@tds.net> ????????? wrote: > Dear all Pythoners, > > I am quiet new to python and now working with xml. I have an xml like this: > > > >
> > 0x6B > 0x78 > 0x4B > 0x58 > 0x67 > 0x63 > 0x71 > 0x43 > 0x51 > 0x6A > > > and I want to get data for KA, KHA, KO and so on. Can you guide me a > way. Btw, I'm using dom for xml. I don't know much about xml.dom but it is easy with ElementTree: data = '''
0x6B 0x78 0x4B 0x58 0x67 0x63 0x71 0x43 0x51 0x6A
''' from elementtree import ElementTree as ET doc = ET.fromstring(data) consonants = doc.find('.//CONSONANTS') for consonant in consonants: print consonant.tag, consonant.text Kent From python at kapitalisten.no Tue Apr 4 12:55:28 2006 From: python at kapitalisten.no (=?iso-8859-1?Q?=D8yvind?=) Date: Tue, 4 Apr 2006 12:55:28 +0200 (CEST) Subject: [Tutor] Bits Message-ID: <35105.193.71.38.142.1144148128.squirrel@mail.sporck.net> Hello. Is it possible to read the bits (the 0's and 1's) of a string or a file with Python? What module would I use? Thanks in advance, ?yvind -- This email has been scanned for viruses & spam by Decna as - www.decna.no Denne e-posten er sjekket for virus & spam av Decna as - www.decna.no From kent37 at tds.net Tue Apr 4 13:51:46 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 04 Apr 2006 07:51:46 -0400 Subject: [Tutor] Bits In-Reply-To: <35105.193.71.38.142.1144148128.squirrel@mail.sporck.net> References: <35105.193.71.38.142.1144148128.squirrel@mail.sporck.net> Message-ID: <44325DD2.70809@tds.net> ?yvind wrote: > Hello. > > Is it possible to read the bits (the 0's and 1's) of a string or a file > with Python? What module would I use? I don't know exactly what you mean by "read the bits" but you can use data = open('afile', 'b').read() to get the data into a string byte1=ord(data[1]) to get a character as binary data byte1 & 1 to extract a single bit You might also be interested in the struct module which lets you extract larger data (e.g. ints and floats) from a string. Kent From ktalanet at yahoo.es Tue Apr 4 15:40:44 2006 From: ktalanet at yahoo.es (Miquel Oliete) Date: Tue, 04 Apr 2006 15:40:44 +0200 Subject: [Tutor] Protected methods/variables Message-ID: <4432775C.2050806@yahoo.es> Hello everybody I have been programming in object oriented languages for several years and I'm learning python now. I have missed protected method/variables in Python. How do you declare methods/variables used only by a class and their derived classes? Thanks in advance -- Miquel Oliete (a.k.a. Ktal?) http://apetite4destruction.org/blog Powered by Debian GNU/Linux Sid ______________________________________________ LLama Gratis a cualquier PC del Mundo. Llamadas a fijos y m?viles desde 1 c?ntimo por minuto. http://es.voice.yahoo.com From ukc802591034 at btconnect.com Tue Apr 4 18:47:29 2006 From: ukc802591034 at btconnect.com (Alan Gauld) Date: Tue, 4 Apr 2006 17:47:29 +0100 Subject: [Tutor] defined() References: Message-ID: >> Which language(s) do you know that has such a feature? > > I should came from Marco Cantu's Delphi 2005 book, that I have read just > recently. > But I am unable to find it again. I'd be very surprised if it came from Delphi for two reasons: a) I used Delphi a lot for several years and never came across it! :-) b) Delphi (or Object Pascal) is strictly statically typed and wouldn't even compile with any undefined values in the code. BUT... I just checked and it *is* in Delphi - a new feature in Delphi 6. BUT it's not a language feature rather it is a compiler directive like the C #ifdef. (And starts with uppercase D BTW). His example: //-------------------- const debugControl = 2 {$IF Defined(DEBUG) and DebugControl > 3} // do stuff here {$IFEND} //--------------------- There is also a Declared directive too. These are not primarily intended for determining whether a variable is defined or declared but to determine whether a particular language feature has been defined or constant declared in the current version of Delphi (post version 6 of course!) Now that's an entirely different question in terms of how we do that in Python! Which I'll lreave as an excercise for the readers ;-) -- Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From ukc802591034 at btconnect.com Tue Apr 4 19:07:06 2006 From: ukc802591034 at btconnect.com (Alan Gauld) Date: Tue, 4 Apr 2006 18:07:06 +0100 Subject: [Tutor] Protected methods/variables References: <4432775C.2050806@yahoo.es> Message-ID: "Miquel Oliete" wrote in message news:4432775C.2050806 at yahoo.es... > I have been programming in object oriented languages for several years > and I'm learning python now. Congratulations :-) > I have missed protected method/variables in Python. In what sense have you missed them? Have you been hitting a lot of bugs because you didn't have them? OIr do you just mean you are having withdrawal symptoms after working in more conservative OOP languages like C++/Java etc? > How do you declare methods/variables used only by a class > and their derived classes? You don't. Protected was a scheme introduced by Bjarne Stroustrup at the behest of Mark Linton to support Mark's Interviews GUI library in C++ (version 1.2) and subsequently copied in Java. They are part of the statically and strictly typed idioms of OOP used in those languages. However Stroustrup writes in his book "The Design & Evolution of C++" : "In retrospect, I think that protected is a case where "good arguments" and fashion overcame my better judgement..." And Linton himself withdrew support for protected members from Interviews around the same time - they were causing bugs and maintenance problems! Most OOP languages and especially dynamic OOP languages prefer the freedom of expression and flexibility that dynamic typing (or duck typing as its sometimes called) affords. Objective C tries to combine boith with mixed results. But in practice I can honestly say I have never missed having the protected keyword (I do occasionally like to use private - for which there is a convention in Python) but never have I missed protected. What do you find you need it for? -- Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From wescpy at gmail.com Tue Apr 4 19:21:48 2006 From: wescpy at gmail.com (w chun) Date: Tue, 4 Apr 2006 10:21:48 -0700 Subject: [Tutor] Protected methods/variables In-Reply-To: <4432775C.2050806@yahoo.es> References: <4432775C.2050806@yahoo.es> Message-ID: <78b3a9580604041021g64409eb4g2d2063f2dfe7af1e@mail.gmail.com> > I have missed protected method/variables in Python. How do you declare > methods/variables used only by a class and their derived classes? hi Ktal?, welcome to Python! you missed "protection" in OOP with Python bceause there are no such declarations in Python! 1) there is a privacy *hint*, which is using "__" to start a variable or method name with, e.g., def __myMaybePrivateMethod(self,...). this does name-mangle the attribute at run-time, however the algorithm is fairly well-known and easy to crack: self._CLASS__myMaybePrivateMethod(). for more on this see,: http://docs.python.org/tut/node11.html#SECTION0011600000000000000000 2) however, with Python's new-style classes introduced back in 2.2, there are much more powerful security mechanisms you can employ so that you can customize any or all of your attributes (data attributes [variables] or methods) to give it the most fine-grained security you can imagine. - you can use property() for your attributes to assign a getter, setter, and deleter method that get executed every time someone tries to access, set, and delete an instance attribute: | class C(object): | def getx(self): return self.__x | def setx(self, value): self.__x = value | def delx(self): del self.__x | x = property(getx, setx, delx, "I'm the 'x' property.") - you can use descriptors (__get__, __set__, __delete__) that get executed every time someone tries to access, set, and remove your object... this allows you to really customize instances and how attribute access occurs. using descriptors, you can bypass the regular way of attribute search, i.e., x.foo normally looks at object 'x' for 'foo', and if not found, searches type(x) for 'foo', and then it progresses this search to ancestor classes. with descriptors, you can override this default behavior to make instances differ from one another. in fact, properties (as seen above) is an example of a descriptor! - you can use __slots__ to restrict arbirtrary creation of (dynamic) instrance attributes - you can even customize how classes are created (by using metaclasses and __metaclass__) so as you can see, you can do a lot more with Python classes than what you can do with 'private', 'protected', 'friend', or 'protected friend'. hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From kent37 at tds.net Tue Apr 4 19:43:01 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 04 Apr 2006 13:43:01 -0400 Subject: [Tutor] Protected methods/variables In-Reply-To: <78b3a9580604041021g64409eb4g2d2063f2dfe7af1e@mail.gmail.com> References: <4432775C.2050806@yahoo.es> <78b3a9580604041021g64409eb4g2d2063f2dfe7af1e@mail.gmail.com> Message-ID: <4432B025.3080805@tds.net> w chun wrote: >> I have missed protected method/variables in Python. How do you declare >> methods/variables used only by a class and their derived classes? > > hi Ktal?, > > welcome to Python! you missed "protection" in OOP with Python bceause > there are no such declarations in Python! > > 1) there is a privacy *hint*, which is using "__" to start a variable > or method name with, e.g., def __myMaybePrivateMethod(self,...). > this does name-mangle the attribute at run-time, however the algorithm > is fairly well-known and easy to crack: > self._CLASS__myMaybePrivateMethod(). for more on this see,: > http://docs.python.org/tut/node11.html#SECTION0011600000000000000000 1a) start a variable name with _ which is a hint to users of the class that the variable is for internal use only. > - you can use __slots__ to restrict arbirtrary creation of (dynamic) > instrance attributes You can do this, but it is generally considered a misuse of __slots__ and potentially problematic. Python takes the attitude that "we're all adults here" and doesn't try to hide anything. The _ naming convention is part of this culture - you tell the users to keep hands off, but if they don't, on their head be it! Kent From mhansen at cso.atmel.com Tue Apr 4 21:09:32 2006 From: mhansen at cso.atmel.com (Mike Hansen) Date: Tue, 04 Apr 2006 13:09:32 -0600 Subject: [Tutor] Protected methods/variables In-Reply-To: <4432B025.3080805@tds.net> Message-ID: <000001c6581b$4dfbb2a0$28645f0a@mikehansen> > > - you can use __slots__ to restrict arbirtrary creation of > (dynamic) > > instrance attributes > > You can do this, but it is generally considered a misuse of > __slots__ and potentially problematic. > I'll bite. What is the proper/intended use of __slots__? Does it have something to do with memory? Mike From kent37 at tds.net Tue Apr 4 21:25:05 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 04 Apr 2006 15:25:05 -0400 Subject: [Tutor] Protected methods/variables In-Reply-To: <000001c6581b$4dfbb2a0$28645f0a@mikehansen> References: <000001c6581b$4dfbb2a0$28645f0a@mikehansen> Message-ID: <4432C811.3050908@tds.net> Mike Hansen wrote: >>> - you can use __slots__ to restrict arbirtrary creation of >> (dynamic) >>> instrance attributes >> You can do this, but it is generally considered a misuse of >> __slots__ and potentially problematic. >> > > I'll bite. What is the proper/intended use of __slots__? Does it have > something to do with memory? Yes, it is intended specifically to reduce memory consumption of objects that are going to be instantiated a lot. I'm not sure how many counts as a lot, but in the thousands at least. Using __slots__ saves the cost of the attribute dict for each instance. Kent From john.corry at ntlworld.com Tue Apr 4 23:33:18 2006 From: john.corry at ntlworld.com (John Corry) Date: Tue, 4 Apr 2006 22:33:18 +0100 Subject: [Tutor] Space the final frontier! Message-ID: Dear All, I am having difficulty removing white spaces from my file. The file is 999 lines long and looks like the sample below: 001, new field,dial= 028 90 79 0154, dial= 002, borfiled, dial= 02890 618521, dial= 003, newcomp, dial=02890419689, dial= The program, I am using to import the file does not like the spaces around the numbers. The number should look like the "dial=02890419689" in the third line. Thus the sample above should look like: 001,newfield,dial=02890790154,dial= 002,borfiled,dial=02890618521,dial= 003,newcomp,dial=02890419689,dial= I have searched the tutor mailbag already and have picked up some good tips on join, split and re but I can't seem to get it to work. I am using the following code. filename = "c:/test.txt" import string import os import re listy = [] input = open( filename, 'r') #read access for line in input.readlines(): y = line listy.append(y) print listy x = listy.pop() re.sub(r'\s', '', x) print y,x del input It produces the output: ['001, new field,dial= 028 90 79 0154, dial=\n'] 001, new field,dial= 028 90 79 0154, dial= 001, new field,dial= 028 90 79 0154, dial= ['002, borfiled, dial= 02890 618521, dial=\n'] 002, borfiled, dial= 02890 618521, dial= 002, borfiled, dial= 02890 618521, dial= ['003, newcomp, dial=02890419689, dial='] 003, newcomp, dial=02890419689, dial= 003, newcomp, dial=02890419689, dial= Any help would be greatly appreciated. Regards, John. From derobins at scs.uiuc.edu Wed Apr 5 01:06:25 2006 From: derobins at scs.uiuc.edu (Dana Robinson) Date: Tue, 4 Apr 2006 18:06:25 -0500 Subject: [Tutor] Question about large numbers of arguments Message-ID: Hello, Suppose you have a situation where you have a large number of command-line options that you will parse with getopt. You want to keep track of these as you move around in the code and do various things. Is it more Pythonic to: Have the functions take large numbers of parameters. or Create an options class to pass the options around. I personally think the latter would look a lot cleaner once the number of options got up to around a half dozen, but I usually see the "large number of parameters" style in other people's code. I suppose I can lessen some of the noise by using Python's rules for argument defaults, but I think that just adds to the confusion. Thanks, Dana Robinson From mwhite3 at ttsd.k12.or.us Wed Apr 5 01:28:38 2006 From: mwhite3 at ttsd.k12.or.us (Matthew White) Date: Tue, 4 Apr 2006 16:28:38 -0700 Subject: [Tutor] Space the final frontier! In-Reply-To: References: Message-ID: <20060404232837.GD2730@ttsd.k12.or.us> Hi John, It would be easier to do all of your whitespace elimination before you append the string to your list(s). Something like this I should get you started: for line in input.readlines(): line = re.sub('[\s]+', '', line) listy.append(line) print listy bonus points for appending the return from re.sub to your list. :) -mtw On Tue, Apr 04, 2006 at 10:33:18PM +0100, John Corry (john.corry at ntlworld.com) wrote: > Dear All, > > I am having difficulty removing white spaces from my file. The file is 999 > lines long and looks like the sample below: > > 001, new field,dial= 028 90 79 0154, dial= > 002, borfiled, dial= 02890 618521, dial= > 003, newcomp, dial=02890419689, dial= > > The program, I am using to import the file does not like the spaces around > the numbers. The number should look like the "dial=02890419689" in the > third line. Thus the sample above should look like: > > 001,newfield,dial=02890790154,dial= > 002,borfiled,dial=02890618521,dial= > 003,newcomp,dial=02890419689,dial= > > I have searched the tutor mailbag already and have picked up some good tips > on join, split and re but I can't seem to get it to work. > > I am using the following code. > > filename = "c:/test.txt" > import string > import os > import re > listy = [] > input = open( filename, 'r') #read access > for line in input.readlines(): > y = line > listy.append(y) > print listy > x = listy.pop() > > re.sub(r'\s', '', x) > print y,x > > del input > > It produces the output: > > ['001, new field,dial= 028 90 79 0154, dial=\n'] > 001, new field,dial= 028 90 79 0154, dial= > 001, new field,dial= 028 90 79 0154, dial= > > ['002, borfiled, dial= 02890 618521, dial=\n'] > 002, borfiled, dial= 02890 618521, dial= > 002, borfiled, dial= 02890 618521, dial= > > ['003, newcomp, dial=02890419689, dial='] > 003, newcomp, dial=02890419689, dial= 003, newcomp, dial=02890419689, dial= > > Any help would be greatly appreciated. > > Regards, > > John. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Matthew White - District Systems Administrator Tigard/Tualatin School District 503.431.4128 "The greatest thing in this world is not so much where we are, but in what direction we are moving." -Oliver Wendell Holmes From bgailer at alum.rpi.edu Wed Apr 5 01:30:37 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Tue, 04 Apr 2006 16:30:37 -0700 Subject: [Tutor] Question about large numbers of arguments In-Reply-To: References: Message-ID: <4433019D.4050201@alum.rpi.edu> Dana Robinson wrote: > Hello, > > Suppose you have a situation where you have a large number of command-line > options that you will parse with getopt. You want to keep track of these > as you move around in the code and do various things. > > Is it more Pythonic to: > > Have the functions take large numbers of parameters. > > or > > Create an options class to pass the options around. > IMHO the above or a dictionary. > > I personally think the latter would look a lot cleaner once the number of > options got up to around a half dozen, but I usually see the "large number > of parameters" style in other people's code. I suppose I can lessen some > of the noise by using Python's rules for argument defaults, but I think > that just adds to the confusion. > > Thanks, > > Dana Robinson > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From ryang at gol.com Wed Apr 5 02:22:27 2006 From: ryang at gol.com (Ryan Ginstrom) Date: Wed, 5 Apr 2006 09:22:27 +0900 Subject: [Tutor] Space the final frontier! In-Reply-To: Message-ID: <002601c65847$058bfb20$030ba8c0@RYAN> [Sorry for the initial misfire, John] > [mailto:tutor-bounces at python.org] On Behalf Of John Corry > 001,newfield,dial=02890790154,dial= > 002,borfiled,dial=02890618521,dial= > 003,newcomp,dial=02890419689,dial= Hi John: I believe the common idiom in this case is ''.join( theString.split( ' ' ) ) >>> theLines = [ '001,newfield,dial=02890790154,dial=', '002,borfiled,dial=02890618521,dial=', '003,newcomp,dial=02890419689,dial='] >>> for line in theLines: print ''.join( line.split( ' ' ) ) 001,newfield,dial=02890790154,dial= 002,borfiled,dial=02890618521,dial= 003,newcomp,dial=02890419689,dial= Regards, Ryan --- Ryan Ginstrom http://ginstrom.com From Carlo.Capuano at iter.org Wed Apr 5 09:39:52 2006 From: Carlo.Capuano at iter.org (Carlo Capuano) Date: Wed, 5 Apr 2006 09:39:52 +0200 Subject: [Tutor] Space the final frontier! Message-ID: <0F4FBAD10465E047ADB7E8C74B4C189B35B99C@de-iws-xch01.iter.org> Hi! > I am having difficulty removing white spaces from my file. The file is > 999 line = line.replace(' ','') should do the work Carlo. From info at harrycorry.com Wed Apr 5 09:46:51 2006 From: info at harrycorry.com (John Corry) Date: Wed, 5 Apr 2006 08:46:51 +0100 Subject: [Tutor] Space the final frontier Message-ID: Dear All, Thanks for the prompt replies. I have now processed my file with 999 lines and it took seconds. It was beautiful. Your advice was spot on. I have enclosed the code that I ended up with. Instead of appending it to a list, I just wrote it to another file in the corrected format. filename = "a:/calllist.csv" filename2 = "c:/calllist.csv" import string import os import re listy = [] input = open( filename, 'r') #read access input2 = open(filename2, 'w') for line in input.readlines(): line = re.sub('[\s]+', '', line) y = line x = "\n" z = y + x input2.write(z) del input del input2 Thanks again, John. From kent37 at tds.net Wed Apr 5 12:03:26 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 05 Apr 2006 06:03:26 -0400 Subject: [Tutor] Space the final frontier In-Reply-To: References: Message-ID: <443395EE.1020504@tds.net> John Corry wrote: > Your advice was spot on. I have enclosed the code that I ended up with. > Instead of appending it to a list, I just wrote it to another file in the > corrected format. A few notes below: > > > filename = "a:/calllist.csv" > filename2 = "c:/calllist.csv" > import string > import os > import re > listy = [] You don't use string, os or listy so these lines can be removed > input = open( filename, 'r') #read access > input2 = open(filename2, 'w') > for line in input.readlines(): > line = re.sub('[\s]+', '', line) > y = line > x = "\n" > z = y + x > input2.write(z) I would write either line += "\n" input2.write(line) or input2.write(line) input2.write("\n") BTW input2 is not such a good name for an output file! > > del input > del input2 del is not needed here, you should use input.close() # not really needed input2.close() I say "not really needed" because for an input file you probably don't care exactly when it is closed. For an output file I always close it as soon as I am done writing. But maybe I am just teaching my own bad habits here! Kent From wescpy at gmail.com Wed Apr 5 12:46:47 2006 From: wescpy at gmail.com (w chun) Date: Wed, 5 Apr 2006 03:46:47 -0700 Subject: [Tutor] Protected methods/variables In-Reply-To: <4432C811.3050908@tds.net> References: <000001c6581b$4dfbb2a0$28645f0a@mikehansen> <4432C811.3050908@tds.net> Message-ID: <78b3a9580604050346u43c7f4b0m5fafe1313af1cce0@mail.gmail.com> On 4/4/06, Kent Johnson wrote: > Mike Hansen wrote: > >>> - you can use __slots__ to restrict arbirtrary creation of > >> (dynamic) > >>> instrance attributes > >> You can do this, but it is generally considered a misuse of > >> __slots__ and potentially problematic. what specific problems were you thinking of? i would say that's it's clumsy to use during development because you're constantly changing __dict__ by adding new instance attributes, etc., so i only add a __slots__ when i'm finally done with the coding and want to prevent others from creating (dynamically) more instance attributes. it's too bad, because it sort goes against Zen#19 (namespaces are a honking good idea). > > I'll bite. What is the proper/intended use of __slots__? Does it have > > something to do with memory? > > Yes, it is intended specifically to reduce memory consumption of objects > that are going to be instantiated a lot. I'm not sure how many counts as > a lot, but in the thousands at least. Using __slots__ saves the cost of > the attribute dict for each instance. right, a class will either have __slots__ or __dict__ but not both. -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From janos.juhasz at VELUX.com Wed Apr 5 13:06:58 2006 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Wed, 5 Apr 2006 13:06:58 +0200 Subject: [Tutor] Space the final frontier! In-Reply-To: Message-ID: Hi John, what do you think about this? def InplaceReplace(filename): lines = open(filename, 'r').readlines() lines = [line.replace(' ', '') for line in lines] open(filename, 'wt').writelines(lines) It works well on so small files. Yours sincerely, ______________________________ J?nos Juh?sz > Message: 2 > Date: Tue, 4 Apr 2006 22:33:18 +0100 > From: "John Corry" > Subject: [Tutor] Space the final frontier! > To: > Message-ID: > Content-Type: text/plain; charset="iso-8859-1" > Dear All, > I am having difficulty removing white spaces from my file. The file is 999 > lines long and looks like the sample below: > 001, new field,dial= 028 90 79 0154, dial= > 002, borfiled, dial= 02890 618521, dial= > 003, newcomp, dial=02890419689, dial= > The program, I am using to import the file does not like the spaces around > the numbers. The number should look like the "dial=02890419689" in the > third line. Thus the sample above should look like: > 001,newfield,dial=02890790154,dial= > 002,borfiled,dial=02890618521,dial= > 003,newcomp,dial=02890419689,dial= From alan.gauld at freenet.co.uk Wed Apr 5 13:34:17 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 5 Apr 2006 12:34:17 +0100 Subject: [Tutor] Question about large numbers of arguments References: Message-ID: <01ab01c658a4$dffb0a50$0b01a8c0@xp> > Suppose you have a situation where you have a large number of command-line > options that you will parse with getopt. You want to keep track of these > as you move around in the code and do various things. > > Is it more Pythonic to: > > Have the functions take large numbers of parameters. > > Create an options class to pass the options around. Neither, the most Pythonic way IMHO is to use a dictionary and possibly combine with Pythons variable arguments syntax as described in section 4.7.3/4 of the official tutor. > I personally think the latter would look a lot cleaner once the number of > options got up to around a half dozen, but I usually see the "large number > of parameters" style in other people's code. Classes without behaviour are really just glorified dictionaries so I prefer to use a dictionary. The **args mechanism provides a good way to pass these to functions. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From keosophon at khmeros.info Wed Apr 5 13:32:56 2006 From: keosophon at khmeros.info (Keo Sophon) Date: Wed, 5 Apr 2006 18:32:56 +0700 Subject: [Tutor] convert decimal to hexa, to octal and vice versa. Message-ID: <200604051832.56959.keosophon@khmeros.info> Hi, How to convert a decimal number to hexadecimal, octal and vice versa? Thanks, phon From keosophon at khmeros.info Wed Apr 5 13:35:17 2006 From: keosophon at khmeros.info (Keo Sophon) Date: Wed, 5 Apr 2006 18:35:17 +0700 Subject: [Tutor] convert an integer number to string. Message-ID: <200604051835.17577.keosophon@khmeros.info> hi, how to convert an integer number to string? thanks, phon From alan.gauld at freenet.co.uk Wed Apr 5 13:41:56 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 5 Apr 2006 12:41:56 +0100 Subject: [Tutor] Space the final frontier References: Message-ID: <01b301c658a5$f145f620$0b01a8c0@xp> > Thanks for the prompt replies. I have now processed my file with 999 > lines > and it took seconds. It was beautiful. Glad it works, a couple of tweaks: > filename = "a:/calllist.csv" > filename2 = "c:/calllist.csv" > import string > import os You don't use os or string so don't need to import them > import re And you don't really need re either, see below... > listy = [] > input = open( filename, 'r') #read access > input2 = open(filename2, 'w') input is a builtin function so using it as a variable name could cause confusion - input1 would be more consistent. Although calling the second one output might be more accurate? > for line in input.readlines(): > line = re.sub('[\s]+', '', line) you can just use the string replace method which for simple replacements is faster than re and much less complex. line = line.replace(' ','') > y = line > x = "\n" > z = y + x you don't really need all that > input2.write(z) input2.write(line + '\n') is just as clear if not clearer! At least I think so! :-) > del input > del input2 You should use close on a file not del. input1.close() input2.close() HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From keosophon at khmeros.info Wed Apr 5 13:42:37 2006 From: keosophon at khmeros.info (Keo Sophon) Date: Wed, 5 Apr 2006 18:42:37 +0700 Subject: [Tutor] how to get the content of an XML elements. In-Reply-To: <442EF4DA.4050304@tds.net> References: <200603311906.26110.keosophon@khmeros.info> <442EF4DA.4050304@tds.net> Message-ID: <200604051842.37211.keosophon@khmeros.info> On Sunday 02 April 2006 04:47, Kent Johnson wrote: > Alan Gauld wrote: > > "Keo Sophon" wrote in message > > news:200603311906.26110.keosophon at khmeros.info... > > > >>Is there anyway to get the content of an XML elements. I am using > >> xml.dom. > > > > For true XML I think ElemTree (by Fred Lundh?) is the best approach. > > Try a Google search. > > Yes, it's ElementTree though. > > Keo, what do you mean, "get the content of an XML elements"? > > Kent for example: ..... someone at email.com ..... I would like to get "someone at email.com" of . How to do that? Phon From purple.meteor at gmail.com Wed Apr 5 13:45:03 2006 From: purple.meteor at gmail.com (Olivier D.) Date: Wed, 5 Apr 2006 13:45:03 +0200 Subject: [Tutor] convert an integer number to string. In-Reply-To: <200604051835.17577.keosophon@khmeros.info> References: <200604051835.17577.keosophon@khmeros.info> Message-ID: <1a4188f0604050445k170e434cw8016ea2cfb7ab051@mail.gmail.com> On 4/5/06, Keo Sophon wrote: > > how to convert an integer number to string? Use str(object) to convert an object to a string. For example: >>> str(42) '42' The reverse function is int(x) to convert a string to an integer: >>> int('42') 42 From ukc802591034 at btconnect.com Wed Apr 5 13:48:08 2006 From: ukc802591034 at btconnect.com (Alan Gauld) Date: Wed, 5 Apr 2006 12:48:08 +0100 Subject: [Tutor] convert decimal to hexa, to octal and vice versa. References: <200604051832.56959.keosophon@khmeros.info> Message-ID: "Keo Sophon" wrote in message news:200604051832.56959.keosophon at khmeros.info... > How to convert a decimal number to hexadecimal, octal and vice versa? The number is stored in binary on the computer so you never convert the number itself, what you convert is the representation of that number as a string. The easiest way (and the one with most control) is to use string formatting: number = 42 print "%X" % number print "%x" % number print "%05x" % number print "%o" % number etc. HTH, -- Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From noufal at nibrahim.net.in Wed Apr 5 13:50:14 2006 From: noufal at nibrahim.net.in (Noufal Ibrahim) Date: Wed, 5 Apr 2006 17:20:14 +0530 (IST) Subject: [Tutor] convert decimal to hexa, to octal and vice versa. In-Reply-To: <200604051832.56959.keosophon@khmeros.info> References: <200604051832.56959.keosophon@khmeros.info> Message-ID: <44362.203.145.176.76.1144237814.squirrel@members.hcoop.net> On Wed, April 5, 2006 5:02 pm, Keo Sophon wrote: > Hi, > > How to convert a decimal number to hexadecimal, octal and vice versa? >>> foo = 2 >>> str(foo) # Integer to string '2' >>> oct(15) # Integer to octal '017' >>> hex(15) # Integer to hex '0xf' >>> int(0xf) # Hex to decimal integer -- -NI From kent37 at tds.net Wed Apr 5 14:15:33 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 05 Apr 2006 08:15:33 -0400 Subject: [Tutor] Protected methods/variables In-Reply-To: <78b3a9580604050346u43c7f4b0m5fafe1313af1cce0@mail.gmail.com> References: <000001c6581b$4dfbb2a0$28645f0a@mikehansen> <4432C811.3050908@tds.net> <78b3a9580604050346u43c7f4b0m5fafe1313af1cce0@mail.gmail.com> Message-ID: <4433B4E5.4030105@tds.net> w chun wrote: > On 4/4/06, Kent Johnson wrote: >> Mike Hansen wrote: >>>>> - you can use __slots__ to restrict arbirtrary creation of >>>> (dynamic) >>>>> instrance attributes >>>> You can do this, but it is generally considered a misuse of >>>> __slots__ and potentially problematic. > > what specific problems were you thinking of? i would say that's it's > clumsy to use during development because you're constantly changing > __dict__ by adding new instance attributes, etc., so i only add a > __slots__ when i'm finally done with the coding and want to prevent > others from creating (dynamically) more instance attributes. it's too > bad, because it sort goes against Zen#19 (namespaces are a honking > good idea). The main problem seems to be that it can be broken by inheritance. A base or derived class can have a __dict__ which then allows additional attributes to be added even if the derived or base class uses __slots__. I admit to arguing from authority here but the consistent message on c.l.py from those who should know is, don't use __slots__ to restrict assignment, use __setattr__ instead; __slots__ should be used as a memory optimization only. Search c.l.py for discussion. >>> I'll bite. What is the proper/intended use of __slots__? Does it have >>> something to do with memory? >> Yes, it is intended specifically to reduce memory consumption of objects >> that are going to be instantiated a lot. I'm not sure how many counts as >> a lot, but in the thousands at least. Using __slots__ saves the cost of >> the attribute dict for each instance. > > right, a class will either have __slots__ or __dict__ but not both. As noted above, that is not necessarily true when inheritance is involved. Kent From kent37 at tds.net Wed Apr 5 14:28:53 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 05 Apr 2006 08:28:53 -0400 Subject: [Tutor] how to get the content of an XML elements. In-Reply-To: <200604051842.37211.keosophon@khmeros.info> References: <200603311906.26110.keosophon@khmeros.info> <442EF4DA.4050304@tds.net> <200604051842.37211.keosophon@khmeros.info> Message-ID: <4433B805.2000101@tds.net> Keo Sophon wrote: > On Sunday 02 April 2006 04:47, Kent Johnson wrote: >> Alan Gauld wrote: >>> "Keo Sophon" wrote in message >>> news:200603311906.26110.keosophon at khmeros.info... >>> >>>> Is there anyway to get the content of an XML elements. I am using >>>> xml.dom. >>> For true XML I think ElemTree (by Fred Lundh?) is the best approach. >>> Try a Google search. >> Yes, it's ElementTree though. >> >> Keo, what do you mean, "get the content of an XML elements"? >> >> Kent > > for example: > > ..... > someone at email.com > ..... > > I would like to get "someone at email.com" of . With ElementTree it would be something like doc = ElementTree.parse('file.xml') to = doc.find('//to') print to.text Kent From python at venix.com Wed Apr 5 14:57:28 2006 From: python at venix.com (Python) Date: Wed, 05 Apr 2006 08:57:28 -0400 Subject: [Tutor] Question about large numbers of arguments In-Reply-To: <01ab01c658a4$dffb0a50$0b01a8c0@xp> References: <01ab01c658a4$dffb0a50$0b01a8c0@xp> Message-ID: <1144241849.6491.1370.camel@www.venix.com> On Wed, 2006-04-05 at 12:34 +0100, Alan Gauld wrote: > > Suppose you have a situation where you have a large number of command-line > > options that you will parse with getopt. You want to keep track of these > > as you move around in the code and do various things. > > > > Is it more Pythonic to: > > > > Have the functions take large numbers of parameters. > > > > Create an options class to pass the options around. > > Neither, the most Pythonic way IMHO is to use a dictionary and > possibly combine with Pythons variable arguments syntax as > described in section 4.7.3/4 of the official tutor. > > > I personally think the latter would look a lot cleaner once the number of > > options got up to around a half dozen, but I usually see the "large number > > of parameters" style in other people's code. > > Classes without behaviour are really just glorified dictionaries so > I prefer to use a dictionary. The **args mechanism provides a > good way to pass these to functions. Just to expand on that a little bit, one useful coding trick where you use only a few of the parameters is to define the function as: def myfunc(param6, param11, param17, **extra): # The parameters you care about are unpacked for you # The rest are in extra # use the ** syntax to pass the dictionary in to your function myfunc( **param_dict) Coming up with better names is left as an exercise for the reader. I mostly use this when dealing with HTML forms with many variables. > > Alan G > Author of the learn to program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From ray.allen at sant.ox.ac.uk Wed Apr 5 16:07:37 2006 From: ray.allen at sant.ox.ac.uk (Ray Allen) Date: Wed, 5 Apr 2006 15:07:37 +0100 Subject: [Tutor] date conversion Message-ID: <004601c658ba$5c4e8950$1fe801a3@sant.ox.ac.uk> I would like Python to convert a date returned by MySQL (2006-04-05) to a user readable format such as 05-Apr-2006 for display and then to convert it back to ISO format for update. What is the most convenient way of doing this? I'm struggling to understand the datetime module's functionality. Ray Allen From kent37 at tds.net Wed Apr 5 16:50:33 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 05 Apr 2006 10:50:33 -0400 Subject: [Tutor] date conversion In-Reply-To: <004601c658ba$5c4e8950$1fe801a3@sant.ox.ac.uk> References: <004601c658ba$5c4e8950$1fe801a3@sant.ox.ac.uk> Message-ID: <4433D939.3030007@tds.net> Ray Allen wrote: > I would like Python to convert a date returned by MySQL (2006-04-05) to a > user readable format such as 05-Apr-2006 for display and then to convert it > back to ISO format for update. Here's one way: In [1]: from datetime import date In [2]: data = '2006-04-05' Use split() and int() to convert to a list of year, month, day In [4]: ymd = map(int, data.split('-')) In [5]: ymd Out[5]: [2006, 4, 5] Turn it into a date. The * makes the list act like individual parameters. In [6]: d=date(*ymd) In [7]: d Out[7]: datetime.date(2006, 4, 5) See the docs for the time module for info about strftime() format codes In [8]: d.strftime('%d-%b-%Y') Out[8]: '05-Apr-2006' ISO format is built-in. In [9]: d.isoformat() Out[9]: '2006-04-05' For other input formats you might have to use time.strptime() to convert to a time tuple, then pass the first three elements do date(): In [10]: import time In [15]: t=time.strptime(data, '%Y-%m-%d') In [16]: t Out[16]: (2006, 4, 5, 0, 0, 0, 2, 95, -1) In [17]: date(*t[:3]) Out[17]: datetime.date(2006, 4, 5) Kent From brian at daviesinc.com Wed Apr 5 16:56:00 2006 From: brian at daviesinc.com (Brian Gustin) Date: Wed, 05 Apr 2006 10:56:00 -0400 Subject: [Tutor] date conversion In-Reply-To: <004601c658ba$5c4e8950$1fe801a3@sant.ox.ac.uk> References: <004601c658ba$5c4e8950$1fe801a3@sant.ox.ac.uk> Message-ID: <4433DA80.5080704@daviesinc.com> I wrote something similar on my blog some time back.. http://phplogix.com/codefool/?postid=13 This is for converting Apache logfiles to a ISO formatted date for mysql.. It could easily be reversed, with a little tweaking.. :) to wit: def mreplace(s, chararray, newchararray): for a, b in zip(chararray, newchararray): s = s.replace(a, b) return s olddatestring = ('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec') newdatestring = ('01','02','03','04','05','06','07','08','09','10','11','12') def clftosql(date): ttime = date.split(":",1) time = ttime[1] datelist = ttime[0].split('/') #should be , E.G DD,MM,YYYY we need YYYY-MM-DD for sql day = datelist[0] month = datelist[1] year = datelist[2] newdate = year+'-'+month+'-'+day+' '+time return newdate then you can take a date stamp from an Apache CLF log like this : 01/Oct/2000:00:00:00 (after you regex it out of the log with: datechk = re.compile('([0-9]+/.../[0-9][0-9][0-9][0-9]:[0-9][0-9]:[0-9][0-9]:[0-9][0-9])') of course) and run the functions thus: mydate = mreplace(dated,olddatestring,newdatestring) mydate1 = clftosql(mydate) Ray Allen wrote: > I would like Python to convert a date returned by MySQL (2006-04-05) to a > user readable format such as 05-Apr-2006 for display and then to convert it > back to ISO format for update. What is the most convenient way of doing > this? I'm struggling to understand the datetime module's functionality. > Ray Allen > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > !DSPAM:4433d45e204351006614580! > > From brian at daviesinc.com Wed Apr 5 17:11:08 2006 From: brian at daviesinc.com (Brian Gustin) Date: Wed, 05 Apr 2006 11:11:08 -0400 Subject: [Tutor] date conversion In-Reply-To: <4433DA80.5080704@daviesinc.com> References: <004601c658ba$5c4e8950$1fe801a3@sant.ox.ac.uk> <4433DA80.5080704@daviesinc.com> Message-ID: <4433DE0C.4030106@daviesinc.com> Oh yeah - you can also simply use Mysql's date_format() function when you query the database ?? select date_format(column_name,'%d-%b-%Y') as formatted_date from table where blah; would output the date as 05-Apr-2006 http://dev.mysql.com/doc/refman/4.1/en/date-and-time-functions.html Brian Gustin wrote: > I wrote something similar on my blog some time back.. > http'://phplogix.com/codefool/?postid=13 > This is for converting Apache logfiles to a ISO formatted date for > mysql.. It could easily be reversed, with a little tweaking.. :) > > > to wit: > def mreplace(s, chararray, newchararray): > for a, b in zip(chararray, newchararray): > s = s.replace(a, b) > return s > > olddatestring = > ('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec') > > newdatestring = > ('01','02','03','04','05','06','07','08','09','10','11','12') > > def clftosql(date): > ttime = date.split(":",1) > time = ttime[1] > datelist = ttime[0].split('/') > #should be , E.G DD,MM,YYYY we need YYYY-MM-DD for sql > day = datelist[0] > month = datelist[1] > year = datelist[2] > newdate = year+'-'+month+'-'+day+' '+time > return newdate > > then you can take a date stamp from an Apache CLF log like this : > 01/Oct/2000:00:00:00 (after you regex it out of the log with: > > datechk = > re.compile('([0-9]+/.../[0-9][0-9][0-9][0-9]:[0-9][0-9]:[0-9][0-9]:[0-9][0-9])') > > of course) > > and run the functions thus: > > mydate = mreplace(dated,olddatestring,newdatestring) > mydate1 = clftosql(mydate) > > > Ray Allen wrote: > >>I would like Python to convert a date returned by MySQL (2006-04-05) to a >>user readable format such as 05-Apr-2006 for display and then to convert it >>back to ISO format for update. What is the most convenient way of doing >>this? I'm struggling to understand the datetime module's functionality. >>Ray Allen >> >>_______________________________________________ >>Tutor maillist - Tutor at python.org >>http://mail.python.org/mailman/listinfo/tutor >> >> >> >> > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > !DSPAM:4433db1a224961964068235! > > From rfquerin at gmail.com Wed Apr 5 17:16:14 2006 From: rfquerin at gmail.com (Richard Querin) Date: Wed, 5 Apr 2006 11:16:14 -0400 Subject: [Tutor] preliminary app design question Message-ID: <7d81675b0604050816v4f0ee8e4y599ccd91365f0a1a@mail.gmail.com> I am planning to write a program (or series of programs) and want some advice beforehand. I've written a few small programs with Python and wxPython, but nothing very complex. I want to write a suite of in-house structural engineering design programs for my own purposes. I want to do the following: - write each program independently as a standalone structural design app - design and write the programs in such a way that in the future I can create a project app that would link all these smaller apps together (to store a bunch of these different designs under a single project for instance) - I want the input/output of each program to be easily adaptable and readable by the 'project app' in the future - I would want the individual programs to have file formats that are easily extensible as I add features to them - The 'project app' would have to be extensible in that I could link smaller apps to it as I create them and it should be able to handle revisions to these smaller apps as I make them. Obviously this won't happen right away, I would likely develop each small design app as a standalone and then when I've got 3 or 4 done I would tie them together with the project app. My question before I start is whether or not using an XML format for the individual file formats is the way to go, and if I have to anticipate every little thing in the file formats before hand. I don't want to do this, I would rather like to be able to just add and modify things as I go with the least amount of hassle along the way. Any ideas on how to generally approach the file formats? Any suggestions would be greatly appreciated. I have zero experience with XML at this point, and very modest experience with Python/wxPython, but necessity is the mother of invention and I can learn what I need to know I think. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060405/9005006a/attachment.htm From srini_iyyer_bio at yahoo.com Wed Apr 5 19:03:56 2006 From: srini_iyyer_bio at yahoo.com (Srinivas Iyyer) Date: Wed, 5 Apr 2006 10:03:56 -0700 (PDT) Subject: [Tutor] Mapping elements in various lists - walking over lists and their elements In-Reply-To: <4433DA80.5080704@daviesinc.com> Message-ID: <20060405170357.9274.qmail@web38110.mail.mud.yahoo.com> Dear Tutors, I have a huge string and 2 lists. List A consists of tabed elements, where first tab represents entry somewhere in string(ndat). ndat has 'Contig27915_RC' and List A [nbat]has 'Contig27915_RC\tXM_945977'. List B [nmlist]has elements, for instance ['XM_945977\tNM_152513']. Now my task, is to take each element in nbat(listA) search in string ndat and nmlist, if found in nmlist, replace with its tabed counterpart in ndat string. How did I choose to solve: 1. I could not think in the most smartest way as said easily above. Say take element from nbat, see if modified version of it available in nmlist, if found replace that modifed element in string. So I chose to take element from listA (nbat), search in string ndat. If found replace with it tabed element(Contig27915_RC\tXM_945977 => XM_945977) and store that in a new list. Now loop over this new list for each element check if a new version available in nmlist. If so replace and print. One of the proble is that, Contig27915_RC is seen associated with many XM entries in nbat. However, with the above script I could replace only once in xta. I could not print Contig27915_RC with many XM_ guys in nbat. How can this be done. Finally, this whole process seems to be more cumbersome to me. Could any one tip me with a new way of dealing this 3 way mapping. Thanks Script: xt = '' for m in nbat: cols = m.split('\t') old = cols[0] new = cols[1] if ndat.find(old): xt = ndat.replace(old,new) xta = xt.split('\n') >>> for x in xta: ... for m in nmlist: ... cols = m.split('\t') ... colold = cols[0] ... colnew = cols[1] ... if x == colold: ... print x+'\t'+colnew ... XM_945977 NM_152513 -XTA result --- snip--- Contig25622_RC Contig13475_RC Contig40179_RC XM_945977 <- <- <- ['Contig27915_RC\tXM_945977'] Contig44682_RC Contig35934_RC -------------- ndat = """Pro25G\nvariant_gridline\nG3PDH_570\nPro25G_onG3PDH570_20bp\nPro25G_onG3PDH570_10Ts\nr60_1\nr60_3\nr60_n9\nr60_a22\nr60_a104\nr60_a107\nr60_a135\nr60_a97\nr60_a20\nr60_n11\nContig45645_RC\nContig44916_RC\nD25272\nJ00129\nContig29982_RC\nContig26811\nD25274\nContig36292\nContig42854\nContig34839\nContig8376_RC\nContig42014_RC\nD49958\nContig25622_RC\nContig13475_RC\nContig40179_RC\nContig27915_RC\nContig44682_RC\nContig35934_RC\nContig29373_RC\nAF155648\nContig46975_RCx""" nbat = ['Contig45645_RC\tNM_022469', 'Contig44916_RC\tNM_080764', 'J00129\tNM_005141', 'Contig29982_RC\tNM_173833', 'D25274\tNM_006908', 'D25274\tNM_018890', 'D25274\tNM_198829', 'D49958\tNM_201591', 'D49958\tNM_005277', 'D49958\tNM_201592', 'Contig13475_RC\tNM_212555', 'Contig40179_RC\tNM_138570', 'Contig27915_RC\tXM_934912', 'Contig27915_RC\tXM_934911', 'Contig27915_RC\tXM_934908', 'Contig27915_RC\tXM_934906', 'Contig27915_RC\tXM_934902', 'Contig27915_RC\tXM_934901', 'Contig27915_RC\tXM_934899', 'Contig27915_RC\tXM_934897', 'Contig27915_RC\tXM_934896', 'Contig27915_RC\tXM_945989', 'Contig27915_RC\tXM_945987', 'Contig27915_RC\tXM_945986', 'Contig27915_RC\tXM_945985', 'Contig27915_RC\tXM_945983', 'Contig27915_RC\tXM_945982', 'Contig27915_RC\tXM_945980', 'Contig27915_RC\tXM_945978', 'Contig27915_RC\tXM_945977'] nmlist = ['XM_929405\tNM_001039615', 'XM_934896\tNM_152513', 'XM_934897\tNM_152513', 'XM_934899\tNM_152513', 'XM_934901\tNM_152513', 'XM_934902\tNM_152513', 'XM_934904\tNM_152513', 'XM_934906\tNM_152513', 'XM_934908\tNM_152513', 'XM_934911\tNM_152513', 'XM_934912\tNM_152513', 'XM_945977\tNM_152513', 'XM_945978\tNM_152513', 'XM_945980\tNM_152513', 'XM_945982\tNM_152513', 'XM_945983\tNM_152513', 'XM_945984\tNM_152513', 'XM_945985\tNM_152513', 'XM_945986\tNM_152513', 'XM_945987\tNM_152513', 'XM_945989\tNM_152513', 'XM_085261\tNM_001039958', 'XM_938609\tNM_001039958', 'XM_373868\tNM_001009931', 'NM_001012239\tNM_173683', 'XM_929314\tNM_001609', 'XM_940521\tNM_001609', 'XM_932741\tNM_001262', 'XM_945305\tNM_001262', 'XM_928890\tNM_152830'] __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From srini_iyyer_bio at yahoo.com Wed Apr 5 19:09:39 2006 From: srini_iyyer_bio at yahoo.com (Srinivas Iyyer) Date: Wed, 5 Apr 2006 10:09:39 -0700 (PDT) Subject: [Tutor] Mapping elements in various lists - In-Reply-To: <20060405170357.9274.qmail@web38110.mail.mud.yahoo.com> Message-ID: <20060405170939.55189.qmail@web38108.mail.mud.yahoo.com> Sorry for the very long email. and I my brain is dead to create some related generic snippet. Thus, I shrunk the string and lists into as short as I could. apologies again. srini --- Srinivas Iyyer wrote: > Dear Tutors, > I have a huge string and 2 lists. List A consists > of > tabed elements, where first tab represents entry > somewhere in string(ndat). > ndat has 'Contig27915_RC' and List A [nbat]has > 'Contig27915_RC\tXM_945977'. List B [nmlist]has > elements, for instance ['XM_945977\tNM_152513']. > Now > my task, is to take each element in nbat(listA) > search > in string ndat and nmlist, if found in nmlist, > replace > with its tabed counterpart in ndat string. > > How did I choose to solve: > 1. I could not think in the most smartest way as > said > easily above. Say take element from nbat, see if > modified version of it > available in nmlist, if found replace that modifed > element in string. > > So I chose to take element from listA (nbat), search > in string ndat. If found replace with it tabed > element(Contig27915_RC\tXM_945977 => XM_945977) and > store that in a new list. Now loop over this new > list > for each element check if a new version available in > nmlist. If so replace and print. > > One of the proble is that, Contig27915_RC is seen > associated with many XM entries in nbat. However, > with the above script I could replace only once in > xta. I could not print Contig27915_RC with many XM_ > guys in nbat. How can this be done. > > Finally, this whole process seems to be more > cumbersome to me. Could any one tip me with a new > way > of dealing this 3 way mapping. > > Thanks > > Script: > > xt = '' > for m in nbat: > cols = m.split('\t') > old = cols[0] > new = cols[1] > if ndat.find(old): > xt = ndat.replace(old,new) > > xta = xt.split('\n') > >>> for x in xta: > ... for m in nmlist: > ... cols = m.split('\t') > ... colold = cols[0] > ... colnew = cols[1] > ... if x == colold: > ... print x+'\t'+colnew > ... > XM_945977 NM_152513 > > > -XTA result --- snip--- > Contig25622_RC > Contig13475_RC > Contig40179_RC > XM_945977 <- <- <- ['Contig27915_RC\tXM_945977'] > Contig44682_RC > Contig35934_RC > -------------- > > > > > > > ndat = > """Pro25G\nvariant_gridline\nG3PDH_570\nPro25G_onG3PDH570_20bp\nPro25G_onG3PDH570_10Ts\nr60_1\nr60_3\nr60_n9\nr60_a22\nr60_a104\nr60_a107\nr60_a135\nr60_a97\nr60_a20\nr60_n11\nContig45645_RC\nContig44916_RC\nD25272\nJ00129\nContig29982_RC\nContig26811\nD25274\nContig36292\nContig42854\nContig34839\nContig8376_RC\nContig42014_RC\nD49958\nContig25622_RC\nContig13475_RC\nContig40179_RC\nContig27915_RC\nContig44682_RC\nContig35934_RC\nContig29373_RC\nAF155648\nContig46975_RCx""" > > > nbat = ['Contig45645_RC\tNM_022469', > 'Contig44916_RC\tNM_080764', 'J00129\tNM_005141', > 'Contig29982_RC\tNM_173833', 'D25274\tNM_006908', > 'D25274\tNM_018890', 'D25274\tNM_198829', > 'D49958\tNM_201591', 'D49958\tNM_005277', > 'D49958\tNM_201592', 'Contig13475_RC\tNM_212555', > 'Contig40179_RC\tNM_138570', > 'Contig27915_RC\tXM_934912', > 'Contig27915_RC\tXM_934911', > 'Contig27915_RC\tXM_934908', > 'Contig27915_RC\tXM_934906', > 'Contig27915_RC\tXM_934902', > 'Contig27915_RC\tXM_934901', > 'Contig27915_RC\tXM_934899', > 'Contig27915_RC\tXM_934897', > 'Contig27915_RC\tXM_934896', > 'Contig27915_RC\tXM_945989', > 'Contig27915_RC\tXM_945987', > 'Contig27915_RC\tXM_945986', > 'Contig27915_RC\tXM_945985', > 'Contig27915_RC\tXM_945983', > 'Contig27915_RC\tXM_945982', > 'Contig27915_RC\tXM_945980', > 'Contig27915_RC\tXM_945978', > 'Contig27915_RC\tXM_945977'] > > nmlist = ['XM_929405\tNM_001039615', > 'XM_934896\tNM_152513', 'XM_934897\tNM_152513', > 'XM_934899\tNM_152513', 'XM_934901\tNM_152513', > 'XM_934902\tNM_152513', 'XM_934904\tNM_152513', > 'XM_934906\tNM_152513', 'XM_934908\tNM_152513', > 'XM_934911\tNM_152513', 'XM_934912\tNM_152513', > 'XM_945977\tNM_152513', 'XM_945978\tNM_152513', > 'XM_945980\tNM_152513', 'XM_945982\tNM_152513', > 'XM_945983\tNM_152513', 'XM_945984\tNM_152513', > 'XM_945985\tNM_152513', 'XM_945986\tNM_152513', > 'XM_945987\tNM_152513', 'XM_945989\tNM_152513', > 'XM_085261\tNM_001039958', > 'XM_938609\tNM_001039958', > 'XM_373868\tNM_001009931', > 'NM_001012239\tNM_173683', > 'XM_929314\tNM_001609', 'XM_940521\tNM_001609', > 'XM_932741\tNM_001262', 'XM_945305\tNM_001262', > 'XM_928890\tNM_152830'] > > > > __________________________________________________ > Do You Yahoo!? > Tired of spam? Yahoo! Mail has the best spam > protection around > http://mail.yahoo.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From python at venix.com Wed Apr 5 19:32:38 2006 From: python at venix.com (Python) Date: Wed, 05 Apr 2006 13:32:38 -0400 Subject: [Tutor] date conversion In-Reply-To: <4433D939.3030007@tds.net> References: <004601c658ba$5c4e8950$1fe801a3@sant.ox.ac.uk> <4433D939.3030007@tds.net> Message-ID: <1144258358.6491.1409.camel@www.venix.com> On Wed, 2006-04-05 at 10:50 -0400, Kent Johnson wrote: > Ray Allen wrote: > > I would like Python to convert a date returned by MySQL (2006-04-05) Kent's advice below is of course correct, but I'd bet your variable is already a datetime.date (or mx.DateTime.Date with older Python releases). In that case you'd already be at step 7. When executing your update statement use the args field. cursor.execute("UPDATE table SET mydate=%s WHERE id=%s", (date_variable, recordID)) You should not have to worry about getting your date into the proper string format for the database SQL syntax. Here's the help from MySQLdb: help(curs.execute) execute(self, query, args=None) method of MySQLdb.cursors.Cursor instance Execute a query. query -- string, query to execute on server args -- optional sequence or mapping, parameters to use with query. Note: If args is a sequence, then %s must be used as the parameter placeholder in the query. If a mapping is used, %(key)s must be used as the placeholder. Returns long integer rows affected, if any > to a > > user readable format such as 05-Apr-2006 for display and then to convert it > > back to ISO format for update. > > Here's one way: > > In [1]: from datetime import date > > In [2]: data = '2006-04-05' > > Use split() and int() to convert to a list of year, month, day > In [4]: ymd = map(int, data.split('-')) > > In [5]: ymd > Out[5]: [2006, 4, 5] > > Turn it into a date. The * makes the list act like individual parameters. > In [6]: d=date(*ymd) > > In [7]: d > Out[7]: datetime.date(2006, 4, 5) > > See the docs for the time module for info about strftime() format codes > In [8]: d.strftime('%d-%b-%Y') > Out[8]: '05-Apr-2006' > > ISO format is built-in. > In [9]: d.isoformat() > Out[9]: '2006-04-05' > > > For other input formats you might have to use time.strptime() to convert > to a time tuple, then pass the first three elements do date(): > > In [10]: import time > > In [15]: t=time.strptime(data, '%Y-%m-%d') > > In [16]: t > Out[16]: (2006, 4, 5, 0, 0, 0, 2, 95, -1) > > In [17]: date(*t[:3]) > Out[17]: datetime.date(2006, 4, 5) > > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 320-210-3409 -- Lloyd Kvam Venix Corp From kent37 at tds.net Wed Apr 5 19:50:06 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 05 Apr 2006 13:50:06 -0400 Subject: [Tutor] date conversion In-Reply-To: <1144258358.6491.1409.camel@www.venix.com> References: <004601c658ba$5c4e8950$1fe801a3@sant.ox.ac.uk> <4433D939.3030007@tds.net> <1144258358.6491.1409.camel@www.venix.com> Message-ID: <4434034E.9050200@tds.net> Python wrote: > On Wed, 2006-04-05 at 10:50 -0400, Kent Johnson wrote: >> Ray Allen wrote: >>> I would like Python to convert a date returned by MySQL (2006-04-05) > > Kent's advice below is of course correct, but I'd bet your variable is > already a datetime.date (or mx.DateTime.Date with older Python > releases). In that case you'd already be at step 7. > > When executing your update statement use the args field. > > cursor.execute("UPDATE table SET mydate=%s WHERE id=%s", (date_variable, recordID)) > > > You should not have to worry about getting your date into the proper > string format for the database SQL syntax. Good point. You may well be getting some kind of date object back from MySQL, too, rather than a string. Kent From alan.gauld at freenet.co.uk Wed Apr 5 20:44:19 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 5 Apr 2006 19:44:19 +0100 Subject: [Tutor] preliminary app design question References: <7d81675b0604050816v4f0ee8e4y599ccd91365f0a1a@mail.gmail.com> Message-ID: <020b01c658e0$f2ebdc20$0b01a8c0@xp> > wxPython, but nothing very complex. I want to write a suite of in-house > structural engineering design programs for my own purposes. Sounds emminently pythonic. > - write each program independently as a standalone structural design app > - design and write the programs in such a way that in the future I can > create a project app that would link all these smaller apps together Sounds like creating each app as a class which can be instantiated on demand by the master application would be a possible design option. > - I want the input/output of each program to be easily adaptable and > readable by the 'project app' in the future > - I would want the individual programs to have file formats that are > easily > extensible as I add features to them Almost a definition of what XML is good for. A data format that can be changed without breaking legacy code. > - The 'project app' would have to be extensible in that I could link > smaller apps to it as I create them and it should be able to handle > revisions to these smaller apps as I make them. The class approach coupled to a config XML file would do this. Define a file that looks something like My Foo App Foo MyName AnotherName My Bar App Bar SomeName Then you can read that and use it to construct a menu or set of buttons or toolbar or whatever. > Obviously this won't happen right away, I would likely develop each > small design app as a standalone and then when I've got 3 or 4 done > I would tie them together with the project app. Why wait for 3 or 4 just add them one by one! Its just aase of editing the config file... In fact you could eveb make a config applet to create the xml entries as your first project! > My question before I start is whether or not using an XML format for the > individual file formats is the way to go, I'd say definitely its exactly ythe kind of thing XML is good at. > if I have to anticipate every little thing in the file formats before > hand. The whole point of XML is you can modify the file content and the legacy applications will parse out the bits they need and the new apps will read both the old bits and the new bits. XML is often over-hyped and over-used but for this kind of task it is absolutely perfect IMHO. > I have zero experience with XML at this point, Investigate ElementTree - its much easier than the standard xml dom and sax parsers that ship with Python. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Wed Apr 5 20:48:27 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 5 Apr 2006 19:48:27 +0100 Subject: [Tutor] Mapping elements in various lists - walking over lists andtheir elements References: <20060405170357.9274.qmail@web38110.mail.mud.yahoo.com> Message-ID: <020f01c658e1$870363b0$0b01a8c0@xp> > One of the proble is that, Contig27915_RC is seen > associated with many XM entries in nbat. However, > with the above script I could replace only once in > xta. I could not print Contig27915_RC with many XM_ > guys in nbat. How can this be done. > > Finally, this whole process seems to be more > cumbersome to me. Could any one tip me with a new way > of dealing this 3 way mapping. A common generic way to deal with this is to construct an intermediate data model such as a dictionary that contains the key element and a list of the keyed items in the file. The list could be the items themselves ort a tuple containing such info as their index (or seek position). Then you can iterate over the data making multiple changes as defined in the data structure. This is somewhat similar to a thread last month, take a look in the archives for more ideas. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From srini_iyyer_bio at yahoo.com Wed Apr 5 21:49:30 2006 From: srini_iyyer_bio at yahoo.com (Srinivas Iyyer) Date: Wed, 5 Apr 2006 12:49:30 -0700 (PDT) Subject: [Tutor] Mapping elements in various lists In-Reply-To: <020f01c658e1$870363b0$0b01a8c0@xp> Message-ID: <20060405194930.71006.qmail@web38110.mail.mud.yahoo.com> Hi Alan, Thank you again. I did not give a try by using dictionary power. It works now. Thanks again for tip. -srini. dida = {} for m in nbat: cols = m.split('\t') old = cols[0] dida.setdefault(old,[]).append(cols[1]) lista = ndat.split('\n') result = [] for i in lista: items = dida.get(i) if items is None: result.append(i) else: for x in items: result.append(i+'\t'+x) for x in result: tabs = x.split('\t') if len(tabs)>1: for m in nmlist: cols = m.split('\t') colold = cols[0] colnew = cols[1] if tabs[1] == colold: print x+'\t'+colnew else: print x :-)) RESULT: Contig34839 Contig8376_RC Contig42014_RC Contig25622_RC Contig27915_RC XM_934912 NM_152513 Contig27915_RC XM_934911 NM_152513 Contig27915_RC XM_934908 NM_152513 Contig27915_RC XM_934906 NM_152513 Contig27915_RC XM_934902 NM_152513 Contig27915_RC XM_934901 NM_152513 Contig27915_RC XM_934899 NM_152513 Contig27915_RC XM_934897 NM_152513 Contig27915_RC XM_934896 NM_152513 Contig27915_RC XM_945989 NM_152513 Contig27915_RC XM_945987 NM_152513 Contig27915_RC XM_945986 NM_152513 Contig27915_RC XM_945985 NM_152513 Contig27915_RC XM_945983 NM_152513 Contig27915_RC XM_945982 NM_152513 Contig27915_RC XM_945980 NM_152513 Contig27915_RC XM_945978 NM_152513 Contig27915_RC XM_945977 NM_152513 Contig44682_RC Contig35934_RC Contig29373_RC --- Alan Gauld wrote: > > One of the proble is that, Contig27915_RC is seen > > associated with many XM entries in nbat. However, > > with the above script I could replace only once in > > xta. I could not print Contig27915_RC with many > XM_ > > guys in nbat. How can this be done. > > > > Finally, this whole process seems to be more > > cumbersome to me. Could any one tip me with a new > way > > of dealing this 3 way mapping. > > A common generic way to deal with this is to > construct an > intermediate data model such as a dictionary that > contains > the key element and a list of the keyed items in the > file. > The list could be the items themselves ort a tuple > containing > such info as their index (or seek position). Then > you can iterate > over the data making multiple changes as defined in > the > data structure. > > This is somewhat similar to a thread last month, > take a look > in the archives for more ideas. > > Alan G > Author of the learn to program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld > > > __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From hugonz-lists at h-lab.net Thu Apr 6 00:01:25 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Wed, 05 Apr 2006 16:01:25 -0600 Subject: [Tutor] preliminary app design question In-Reply-To: <7d81675b0604050816v4f0ee8e4y599ccd91365f0a1a@mail.gmail.com> References: <7d81675b0604050816v4f0ee8e4y599ccd91365f0a1a@mail.gmail.com> Message-ID: <44343E35.9060306@h-lab.net> Richard Querin wrote: > My question before I start is whether or not using an XML format for the > individual file formats is the way to go, and if I have to anticipate > every little thing in the file formats before hand. I don't want to do > this, I would rather like to be able to just add and modify things as I > go with the least amount of hassle along the way. Any ideas on how to > generally approach the file formats? > To quote PJE in http://dirtsimple.org/2004/12/python-is-not-java.html (Python is not JAVA) --- XML is not the answer. It is not even the question. To paraphrase Jamie Zawinski on regular expressions, "Some people, when confronted with a problem, think "I know, I'll use XML." Now they have two problems." --- Now seriously. Are there file formats meant to be used and understood by other programs in principle (we know it is a nice feature, but is it necessary?)? If the answer is yes, then XML may be the solution. Looks like what you are trying to accomplish can be done wrapping functionality into modules, then adding them together (classes, functions, etc) using a GUI master program. Saving complex data structures to files in Python is easy. Let it be pickling or using a Python database, like Kirbybase or Gadfly. If you need to communicate this to other applications, you may use simple extensions like those in XML-RPC(still no XML design and/or parsing). As for anticipating every single thing in the file format, this depends on whether you need to have fancy things like backwards compatibility. I would guess some dynamic data structure that allows for extension (like a dictionary of attributes, where you can always add new attributes) will do. hope this rant helps a bit Hugo > Any suggestions would be greatly appreciated. > > I have zero experience with XML at this point, and very modest > experience with Python/wxPython, but necessity is the mother of > invention and I can learn what I need to know I think. > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From hugonz-lists at h-lab.net Thu Apr 6 00:03:41 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Wed, 05 Apr 2006 16:03:41 -0600 Subject: [Tutor] Question about large numbers of arguments In-Reply-To: References: Message-ID: <44343EBD.4000205@h-lab.net> Dana Robinson wrote: > > Have the functions take large numbers of parameters. > > or > > Create an options class to pass the options around. > > Pythonically, I heard the distinct scream of DICTIONARYYYY in my head. Hugo From falcon3166 at hotmail.com Thu Apr 6 00:58:58 2006 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Wed, 5 Apr 2006 16:58:58 -0600 Subject: [Tutor] What's the invalid syntax? Message-ID: Hey all, What's the invalid syntax in the following code? I tried figuring it out by myself, and I couldn't. # This program finds the date of Easter Sunday between the years 1900 & 2099. # By Nathan Pinno # Inspired by Programming and Problem Solving with Java, 1st ed., question 3, page 207. def date(): int year year = int(raw_input("Year please: ")) if (year < 1900 || year > 2099): print year, " is invalid. Please enter a year between 1900 & 2099." else: if (year == 1954 || year == 1981 || year == 2049 || year == 2076): # For the years when the calculation would be 1 week late. int a, b, c, d, e, f a = year % 19 b = year % 4 c = year % 7 d = (19 * a + 24) % 30 e = (2 * b + 4 * c + 6 * d + 5) % 7 f = (22 + d + e) - 7 if (f < 31): # To see if the date is in March or April. print "Easter Sunday is March ", f, "." else: print "Easter Sunday is April ", (f-31), "." else: # For all other years. int a, b, c, d, e, f a = year % 19 b = year % 4 c = year % 7 d = (19 * a + 24) % 30 e = (2 * b + 4 * c + 6 * d + 5) % 7 f = (22 + d + e) if (f < 31): # Same as above. print "Easter Sunday is March ", f, "." else: print "Easter Sunday is April ", (f-31), "." date() The editor highlights the word year in the line: int year after I hit okay when this message pops up: Invalid syntax. Thanks in advance, Nathan Pinno Web Surfer's Store http://www.websurfstore.ca MSN Messenger: falcon3166 at hotmail.com Yahoo! Messenger: spam_swatter31 ICQ: 199020705 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060405/79c94f33/attachment.htm -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: image/gif Size: 862 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20060405/79c94f33/attachment.gif From dyoo at hkn.eecs.berkeley.edu Thu Apr 6 01:26:01 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 5 Apr 2006 16:26:01 -0700 (PDT) Subject: [Tutor] What's the invalid syntax? In-Reply-To: Message-ID: > What's the invalid syntax in the following code? I tried figuring it out > by myself, and I couldn't. > > The editor highlights the word year in the line: > > int year > > after I hit okay when this message pops up: > > Invalid syntax. Hi Nathan, I would believe the editor. *grin* Python doesn't support saying declarative things like "int year": that's something that just doesn't translate from Java to Python. Just for your understanding: your environment is highlighting the word 'year' only because it really doesn't know what you're trying to do. In this particular case, Python thinks that you might be trying to apply the int() function on year, but in that case, you'd need parens, like: int(year) So that's why it's highlighting year: you're missing parens under this interpretation of the situation. But, as you know, it's completely misunderstanding things. Still, even though the error message is slightly inaccurate, it's correct in the sense that the problem is on that line: you don't predeclare variable or their types in Python. From brian at daviesinc.com Thu Apr 6 01:30:22 2006 From: brian at daviesinc.com (Brian Gustin) Date: Wed, 05 Apr 2006 19:30:22 -0400 Subject: [Tutor] What's the invalid syntax? In-Reply-To: References: Message-ID: <4434530E.5050000@daviesinc.com> define year first I.E. year=0 int(year) or leave the int year out of your code completely - you do not need to typecast - it is set as an integer in the following line. Nathan Pinno wrote: > Hey all, > > What's the invalid syntax in the following code? I tried figuring it out > by myself, and I couldn't. > > # This program finds the date of Easter Sunday between the years 1900 & > 2099. > # By Nathan Pinno > # Inspired by Programming and Problem Solving with Java, 1st ed., > question 3, page 207. > def date(): > int year > year = int(raw_input("Year please: ")) > if (year < 1900 || year > 2099): > print year, " is invalid. Please enter a year between 1900 & 2099." > else: > if (year == 1954 || year == 1981 || year == 2049 || year == > 2076): # For the years when the calculation would be 1 week late. > int a, b, c, d, e, f > a = year % 19 > b = year % 4 > c = year % 7 > d = (19 * a + 24) % 30 > e = (2 * b + 4 * c + 6 * d + 5) % 7 > f = (22 + d + e) - 7 > if (f < 31): # To see if the date is in March or April. > print "Easter Sunday is March ", f, "." > else: > print "Easter Sunday is April ", (f-31), "." > else: # For all other years. > int a, b, c, d, e, f > a = year % 19 > b = year % 4 > c = year % 7 > d = (19 * a + 24) % 30 > e = (2 * b + 4 * c + 6 * d + 5) % 7 > f = (22 + d + e) > if (f < 31): # Same as above. > print "Easter Sunday is March ", f, "." > else: > print "Easter Sunday is April ", (f-31), "." > date() > > The editor highlights the word year in the line: > > int year > > after I hit okay when this message pops up: > > Invalid syntax. > > Thanks in advance, > Nathan Pinno > Web Surfer's Store http://www.websurfstore.ca > > MSN Messenger: falcon3166 at hotmail.com > Yahoo! Messenger: spam_swatter31 > ICQ: 199020705 > !DSPAM:443450a9253311285612896! > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > !DSPAM:443450a9253311285612896! From rozdaniel at hotmail.com Thu Apr 6 02:22:53 2006 From: rozdaniel at hotmail.com (Ros Daniel) Date: Wed, 05 Apr 2006 20:22:53 -0400 Subject: [Tutor] Urgent question about program debugging Message-ID: An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060405/04f325b0/attachment-0001.htm From blackspeckpotato at frontiernet.net Thu Apr 6 03:46:48 2006 From: blackspeckpotato at frontiernet.net (Charles Bartley) Date: Wed, 5 Apr 2006 18:46:48 -0700 Subject: [Tutor] Urgent question about program debugging References: Message-ID: <005501c6591b$f847ec50$01fea8c0@silver> Hi, I'm a Python newbie, but I went over the code, and I think the problem is in choice number 2. ### for father_son in father_son: print father_son ### father_son becomes a string here. Regards, Charles B. ----- Original Message ----- From: Ros Daniel To: tutor at python.org Sent: Wednesday, April 05, 2006 5:22 PM Subject: [Tutor] Urgent question about program debugging I just created a "who's your daddy?" program--one of the challenges in the michael dawson book. It was working well, and I tested all the different instructions, and then for some reason, it stopped working. Specifically, whenever I enter the name of a father, it tells me it doesn't exist, although it does, because when you list all the fathers, you can see it exists, and I set it up in the dictionary. It may be that I've missed something. I know I saved this program so many times, maybe I changed something without realising it, although I've been through every line of code numerous times. I don't know how to use the IDLE debugger, which could be part of my problem. The help file doesn't seem to help. Here's the code: # This program lets the user enter the first and last name of a male # and produces the name of his son. The user will also be able # to add, replace, and delete son-father pairs. father_son = {"Kirk Douglas" : "Michael Douglas", "James Brolin" : "Josh Brolin", "Marlon Brando" : "Christian Brando", "George Best" : "Calum Best", "David Beckham" : "Brooklyn Beckham", "Bob Dylan" : "Jakob Dylan"} choice = None while choice != "0": print \ """ Welcome to Who's Your Daddy? A mini database of fathers and sons. When entering names, please use both the first name and the last name. 0 - Exit 1 - List all Father-Son Pairs 2 - List all Fathers 3 - Look Up Father-Son Pairs 4 - Add a Father-Son Pair 5 - Delete a Father-Son Pair 6 - Replace the Son of a Father-Son Pair 7 - Replace a Father-Son Pair """ choice = raw_input("Choice: ") print # exit program if choice == "0": print "\nGoodbye." # list all father-son pairs elif choice == "1": print "\nLIST OF ALL FATHER-SON PAIRS\n" print father_son # list all fathers elif choice == "2": print "LIST OF ALL FATHERS\n" for father_son in father_son: print father_son # look up father-son pairs elif choice == "3": term = raw_input("Type in the name of the father of this pair: ") if term in father_son: definition = father_son[term] print term, "is the father of", definition else: print "\nSorry,", term, "doesn't exist." # add a father-son pair elif choice == "4": term = raw_input("Type in the name of the father you want to add: ") if term not in father_son: definition = raw_input("Type in the name of this person's son: ") father_son[term] = definition print "\nThank you. Your new father-son pair has been added." print term, "is the father of", definition else: print term, "already exists in the database. Try updating the entry." # delete a father-son pair elif choice == "5": term = raw_input("Type in the name of the father which corresponds \ to the father-son pair you want to delete: ") if term in father_son: definition = father_son[term] del father_son[term] print term, "and his son", definition, "have been removed from the database." else: print "\nI don't recognise this name. Try adding it as an entry." # replace the son of a father-son pair elif choice == "6": term = raw_input("Type in the name of the father whose son you want \ to replace: ") if term in father_son: definition = raw_input("Type in the name of this person's son: ") father_son[term] = definition print "\nThank you. Your change has been made.", term, "is now \ the father of", definition else: print "\nSorry, that name doesn't exist." # replace a father-son pair elif choice == "7": term = raw_input("Type in the name of the father which corresponds \ to the father-son pair you want to replace: ") if term in father_son: term = raw_input("Type in name of this 'replacement' father: ") definition = raw_input("Type in the name of this person's son: ") father_son[term] = definition print "A new father-son pair has been added.", term, "is the \ father of", definition else: print "\nSorry, but", choice, "isn't a valid choice." raw_input("\n\nPress the enter key to exit") ------------------------------------------------------------------------------ _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060405/94ce10e6/attachment.html From blackspeckpotato at frontiernet.net Thu Apr 6 04:43:09 2006 From: blackspeckpotato at frontiernet.net (Charles Bartley) Date: Wed, 5 Apr 2006 19:43:09 -0700 Subject: [Tutor] Urgent question about program debugging References: Message-ID: <008a01c65923$d7328ea0$01fea8c0@silver> Hi Ros, I placed two new lines of code in your choices 2 and 7. The new lines have comments trailing them. In choice 7, you forgot to delete the previous father_son pair (as you had done in choice 5). Regards, Charles ####### # list all fathers elif choice == "2": print "LIST OF ALL FATHERS\n" print father_son.keys() # print fathers - their the keys # replace a father-son pair elif choice == "7": term = raw_input("Type in the name of the father which corresponds \ to the father-son pair you want to replace: ") if term in father_son: del father_son[term] # delete previous father_son pair term = raw_input("Type in name of this 'replacement' father: ") definition = raw_input("Type in the name of this person's son: ") father_son[term] = definition print "A new father-son pair has been added.", term, "is the \ father of", definition else: print "\nSorry, but", choice, "isn't a valid choice." -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060405/74a25874/attachment.htm From justin.mailinglists at gmail.com Thu Apr 6 05:23:29 2006 From: justin.mailinglists at gmail.com (Justin Ezequiel) Date: Thu, 6 Apr 2006 11:23:29 +0800 Subject: [Tutor] regular expressions - backslashes Message-ID: <3c6718980604052023o47368cd5m31d87d9af0bbe01@mail.gmail.com> a colleague demonstrated a problem he had with regular expressions >>> apppath = os.path.abspath(os.curdir) >>> apppath 'C:\\napp_and_author_query\\napp_and_author_query\\a b c d' >>> template = r'\files' >>> template '\\files' >>> re.sub(r'(?i)', apppath, template) 'C:\napp_and_author_query\napp_and_author_query\x07 b c d\\files' >>> print re.sub(r'(?i)', apppath, template) C: app_and_author_query app_and_author_query b c d\files >>> for this particular use-case, I myself prefer using string formatting but I still would like to know what's wrong with the above usage of re.sub Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on win32 From keosophon at khmeros.info Thu Apr 6 05:22:07 2006 From: keosophon at khmeros.info (Keo Sophon) Date: Thu, 6 Apr 2006 10:22:07 +0700 Subject: [Tutor] testing u=unicode(str, 'utf-8') and u = str.decode('utf-8') Message-ID: <200604061022.07601.keosophon@khmeros.info> Hi, Today i tested u=unicode(str,'utf-8') and u=str.decode('utf-8'). Then in both case I used: if isinstance(u,str): print "just string" else: print "unicode" the result of both case are "unicode". So it seems u=unicode(str,'utf-8') and u=str.decode('utf-8') are the same. How about the processing inside? is it same? Phon From titvirak at khmeros.info Thu Apr 6 06:23:10 2006 From: titvirak at khmeros.info (=?UTF-8?B?4Z6R4Z634Z6P4Z+S4Z6Z4Z6c4Z634Z6a4Z+I?=) Date: Thu, 06 Apr 2006 11:23:10 +0700 Subject: [Tutor] OR operator? Message-ID: <443497AE.9050107@khmeros.info> Hi, I'm trying with this operator, could it possible? fruit1 = 'apple' fruit2 = 'orange' fruits = fruit1 or fruit2 is 'orange' = fruits ? From blackspeckpotato at frontiernet.net Thu Apr 6 07:50:30 2006 From: blackspeckpotato at frontiernet.net (Charles Bartley) Date: Wed, 5 Apr 2006 22:50:30 -0700 Subject: [Tutor] OR operator? References: <443497AE.9050107@khmeros.info> Message-ID: <00b501c6593e$036ff0b0$01fea8c0@silver> > > I'm trying with this operator, could it possible? > > fruit1 = 'apple' > fruit2 = 'orange' > > fruits = fruit1 or fruit2 > > is 'orange' = fruits ? Maybe this: ####### fruit1 = 'apple' fruit2 = 'orange' fruits = [fruit1, fruit2] print 'orange' in fruits # prints the boolean result of 'orange in fruits' ####### Regards, Charles B. From alan.gauld at freenet.co.uk Thu Apr 6 09:40:02 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 6 Apr 2006 08:40:02 +0100 Subject: [Tutor] What's the invalid syntax? References: Message-ID: <025001c6594d$518396d0$0b01a8c0@xp> > What's the invalid syntax in the following code? I tried figuring it out > by > myself, and I couldn't. > > # Inspired by Programming and Problem Solving with Java, 1st ed., question > def date(): > int year > year = int(raw_input("Year please: ")) > The editor highlights the word year in the line: > > int year That'd be because int year is invalid syntax in Python. You don't need to decalre variables prior to use in Python as you do in Java. Also names in Python are not typed. Alan G From alan.gauld at freenet.co.uk Thu Apr 6 09:48:49 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 6 Apr 2006 08:48:49 +0100 Subject: [Tutor] Urgent question about program debugging References: Message-ID: <025501c6594e$8d18ed20$0b01a8c0@xp> > father_son = {"Kirk Douglas" : "Michael Douglas", > "James Brolin" : "Josh Brolin", > "Bob Dylan" : "Jakob Dylan"} > > elif choice == "2": > print "LIST OF ALL FATHERS\n" > for father_son in father_son: > print father_son You are replacing the reference to the dictionary with a single key entry here. You probably intended for father in father_son: print father > # look up father-son pairs > elif choice == "3": > term = raw_input("Type in the name of the father of this pair: ") > if term in father_son: father_son is no longer the dictionary but refers to the last father! It should work if you don't list the fathers first! :-) > elif choice == "4": > term = raw_input("Type in the name of the father you want to add: > ") > if term not in father_son: > definition = raw_input("Type in the name of this person's son: > ") > father_son[term] = definition As a wee point, its usually considered a bad idea to name variables after their syntax meaning rather than their meaning in the program. Thus this would be better written: father = raw_input(...) if father not in father_son: son = raw_input(...) father_son[father] = son HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Thu Apr 6 11:54:41 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 06 Apr 2006 05:54:41 -0400 Subject: [Tutor] regular expressions - backslashes In-Reply-To: <3c6718980604052023o47368cd5m31d87d9af0bbe01@mail.gmail.com> References: <3c6718980604052023o47368cd5m31d87d9af0bbe01@mail.gmail.com> Message-ID: <4434E561.3050800@tds.net> Justin Ezequiel wrote: > a colleague demonstrated a problem he had with regular expressions > >>>> apppath = os.path.abspath(os.curdir) >>>> apppath > 'C:\\napp_and_author_query\\napp_and_author_query\\a b c d' >>>> template = r'\files' >>>> template > '\\files' >>>> re.sub(r'(?i)', apppath, template) > 'C:\napp_and_author_query\napp_and_author_query\x07 b c d\\files' >>>> print re.sub(r'(?i)', apppath, template) > C: > app_and_author_query > app_and_author_query b c d\files The problem is that the re engine itself is interpreting the backslashes in the replacement pattern. Here is a simpler example: In [34]: import re In [35]: text = 'abcabc' With a single slash you get a newline even though the slash is a literal in the replacement string: In [36]: re.sub('a', r'\n', text) Out[36]: '\nbc\nbc' So if you want a literal \ in your replacement text you have to escape the \, even in a raw string: In [37]: re.sub('a', r'\\n', text) Out[37]: '\\nbc\\nbc' If it isn't a raw string, you need four \! In [39]: re.sub('a', '\\\\n', text) Out[39]: '\\nbc\\nbc' You can use re.escape() to introduce the needed slashes: In [38]: re.sub('a', re.escape(r'\n'), text) Out[38]: '\\nbc\\nbc' Kent From kent37 at tds.net Thu Apr 6 12:01:58 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 06 Apr 2006 06:01:58 -0400 Subject: [Tutor] testing u=unicode(str, 'utf-8') and u = str.decode('utf-8') In-Reply-To: <200604061022.07601.keosophon@khmeros.info> References: <200604061022.07601.keosophon@khmeros.info> Message-ID: <4434E716.7060906@tds.net> Keo Sophon wrote: > Hi, > > Today i tested u=unicode(str,'utf-8') and u=str.decode('utf-8'). Then in both > case I used: > > if isinstance(u,str): > print "just string" > else: > print "unicode" > > the result of both case are "unicode". So it seems u=unicode(str,'utf-8') and > u=str.decode('utf-8') are the same. How about the processing inside? is it > same? I don't know the details of how they are implemented but they do have the same result. As far as I know you can use whichever form you find more readable. There are a few special-purpose encodings for which the result of decode() is a byte string rather than a unicode string; for these encodings, you have to use str.decode(). For example: In [42]: 'abc'.decode('string_escape') Out[42]: 'abc' In [44]: unicode('abc', 'string_escape') ------------------------------------------------------------ Traceback (most recent call last): File "", line 1, in ? TypeError: decoder did not return an unicode object (type=str) Kent From kaushalshriyan at gmail.com Thu Apr 6 12:36:11 2006 From: kaushalshriyan at gmail.com (Kaushal Shriyan) Date: Thu, 6 Apr 2006 16:06:11 +0530 Subject: [Tutor] Logical Operators Message-ID: <6b16fb4c0604060336p74dbe676jb88838d0d9aa5b23@mail.gmail.com> Hi I am referring to http://www.ibiblio.org/obp/thinkCSpy/chap04.htm about Logical operators I didnot understood >>> x = 5 >>> x and 1 1 >>> y = 0 >>> y and 1 0 How 5 and 1 means 1 and 0 and 1 means 0 Thanks Regards Kaushal From rfquerin at gmail.com Thu Apr 6 12:39:31 2006 From: rfquerin at gmail.com (Richard Querin) Date: Thu, 6 Apr 2006 06:39:31 -0400 Subject: [Tutor] preliminary app design question In-Reply-To: <020b01c658e0$f2ebdc20$0b01a8c0@xp> References: <7d81675b0604050816v4f0ee8e4y599ccd91365f0a1a@mail.gmail.com> <020b01c658e0$f2ebdc20$0b01a8c0@xp> Message-ID: <7d81675b0604060339k13a975a7lf11511b2c41d765b@mail.gmail.com> On 4/5/06, Alan Gauld wrote: > > > Sounds like creating each app as a class which can be instantiated on > demand by the master application would be a possible design option. I guess writing the master program (or some simplified version of it) would be required from the start in order to make launching the separate design programs possible (for testing, debugging etc..). The class approach coupled to a config XML file would do this. > Define a file that looks something like > > > > My Foo App > Foo > > > > MyName > > > > AnotherName > > > > > > My Bar App > Bar > > > > SomeName > > > > > > > Then you can read that and use it to construct a menu or set of buttons > or toolbar or whatever. So for the master program this makes sense. However, what about the input/output data of each individual design app. All the different programs will share some common data but each one may have different components, and some will be large arrays of numbers, is XML still applicable for that type of file data? I think my first task will likely be settling on what I need each component of the system to do and how they will interact. It's becoming more complex the more I discuss it.. ;) > Obviously this won't happen right away, I would likely develop each > > small design app as a standalone and then when I've got 3 or 4 done > > I would tie them together with the project app. > > Why wait for 3 or 4 just add them one by one! Its just aase of editing > the config file... In fact you could eveb make a config applet to create > the xml entries as your first project! Ease myself into it. ;) Investigate ElementTree - its much easier than the standard xml dom > and sax parsers that ship with Python. I have the documentation printed out for study. Thanks for the help. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060406/e07c327b/attachment.html From rfquerin at gmail.com Thu Apr 6 12:42:04 2006 From: rfquerin at gmail.com (Richard Querin) Date: Thu, 6 Apr 2006 06:42:04 -0400 Subject: [Tutor] preliminary app design question In-Reply-To: <44343E35.9060306@h-lab.net> References: <7d81675b0604050816v4f0ee8e4y599ccd91365f0a1a@mail.gmail.com> <44343E35.9060306@h-lab.net> Message-ID: <7d81675b0604060342h27710530p71425d6a17d18746@mail.gmail.com> On 4/5/06, Hugo Gonz?lez Monteverde wrote: > > > Now seriously. Are there file formats meant to be used and understood by > other programs in principle (we know it is a nice feature, but is it > necessary?)? There will be input data and output results from program A that may be utilized by program B. If the two independent designs are linked to the same project then they will share this data, if they aren't part of the same project they wouldn't. I would assume that would mean that the file formats of all the design programs would have to be readable and changeable by the master program. Not sure if this necessitates XML, but to me it seems like standardizing the formats will make things simpler. hope this rant helps a bit It did. Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060406/7a42538e/attachment.htm From alan.gauld at freenet.co.uk Thu Apr 6 13:36:06 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 6 Apr 2006 12:36:06 +0100 Subject: [Tutor] preliminary app design question References: <7d81675b0604050816v4f0ee8e4y599ccd91365f0a1a@mail.gmail.com> <020b01c658e0$f2ebdc20$0b01a8c0@xp> <7d81675b0604060339k13a975a7lf11511b2c41d765b@mail.gmail.com> Message-ID: <027901c6596e$4b89bb30$0b01a8c0@xp> >> The class approach coupled to a config XML file would do this. > > Define a file that looks something like >> >> >> >> My Foo App >> >> >> MyName >> >So for the master program this makes sense. However, what about the >input/output data of each individual design app. OK The params can be used to point at some common database or file. > will share some common data but each one may have different > components, and some will be large arrays of numbers, is XML > till applicable for that type of file data? Personally I wouldn't use XML for content data which is repeated in large volume - the overheads are too high. This is where I'd consider using a shared class or dictionary to define the data and then pickle and/or shelve to save instances. Either that or go with a lightweight database such as SqlLite. > I think my first task will likely be settling on what I need > each component of the system to do and how they will interact. There are two sepoarate areas of concern. 1) The master app and its applet launching mechanism 2) The common data between applets The solutions are likely to be different. For the common data look at each common class and its responsibilities. What should that class be able to provide in the way of sertvices for the applets to consume. The applets then become a fairly simple set of scenarios stitching together the services provided by the shared classes. Without more specific knowledge of your problem domain I can't be more specififc but this is afaily common approach used in Financial and Customer Handling applications for example. > It's becoming more complex the more I discuss it.. ;) They always do! Sometimes its better to just make a start on the bits you think you do understand and see how it hangs together. A very rough master application laiunching a single applet using a minimal set of shared data would be a good goal for starters. HTH, Alan G. From alan.gauld at freenet.co.uk Thu Apr 6 13:46:37 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 6 Apr 2006 12:46:37 +0100 Subject: [Tutor] OR operator? References: <443497AE.9050107@khmeros.info> Message-ID: <028601c6596f$c382a9c0$0b01a8c0@xp> > I'm trying with this operator, could it possible? > > fruit1 = 'apple' > fruit2 = 'orange' > > fruits = fruit1 or fruit2 > > is 'orange' = fruits ? Why not just try it at the python prompt?! And you would find that no, fruits = 'apple' (The order is because fruits is a name which references a value. orange is a value so cannot reference anything else, so 'orange' = fruits is actually an impossible concept!). The reason for the result is the way Python evaluates 'or' expressions. Python considers non-empty strings (like 'apple') to be true. Python also evaluates an 'or' by evaluating the first element and, if it is true then it doesn't bother evaluating the second element since the 'or' must be true if the first part is true. This is known as "short-circuit evaluation". If you did fruit3 = "" fruits = fruit3 or fruit2 this time fruits would equal 'orange' because the first item was an empty string which Python considers to be false so it had to evaluate the second item. Finally, it could be argued that the 'or' should return 'true' or 'false but because Python considers values to be either true or false it just returns the value. I suspect that if boolean values had been in Python at the beginning the result would be different but they weren't and it isn't! :-) HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Thu Apr 6 14:31:52 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 06 Apr 2006 08:31:52 -0400 Subject: [Tutor] preliminary app design question In-Reply-To: <7d81675b0604060339k13a975a7lf11511b2c41d765b@mail.gmail.com> References: <7d81675b0604050816v4f0ee8e4y599ccd91365f0a1a@mail.gmail.com> <020b01c658e0$f2ebdc20$0b01a8c0@xp> <7d81675b0604060339k13a975a7lf11511b2c41d765b@mail.gmail.com> Message-ID: <44350A38.2000604@tds.net> Richard Querin wrote: > > On 4/5/06, *Alan Gauld* > wrote: > > Sounds like creating each app as a class which can be instantiated on > demand by the master application would be a possible design option. > > I guess writing the master program (or some simplified version of it) > would be required from the start in order to make launching the separate > design programs possible (for testing, debugging etc..). Not really. You just have to write the separate design programs in a way that they can be integrated with a larger whole. This means, write the functional part of the program with an API that can be easily be invoked to make it do the work. The API can be class-based, as Alan suggests, or standalone functions, whichever is simpler. Then for a standalone program you can write a main() function that works from the command line or a GUI. For your master program you can invoke the API from whatever framework you come up with. > > The class approach coupled to a config XML file would do this. > Define a file that looks something like > > > Then you can read that and use it to construct a menu or set of buttons > or toolbar or whatever. XML is obviously a bit controversial, you have several contrasting opinions already. I have successfully used XML and a DOM data model in several applications and I would do it again. For configuration I would look at something simpler, possibly a Python module that configures other modules or maybe a plug-in mechanism. Or possibly you just write your master program to call the subprograms as libraries without any dynamic configuration at all - just hard-code it. I should note that my experience with XML data models is from using the excellent dom4j library with Jython. I haven't found any Python XML packages available for Windows that have the same combination of power and ease-of-use as dom4j. > I think my first task will likely be settling on what I need each > component of the system to do and how they will interact. It's becoming > more complex the more I discuss it.. ;) I would say your first task is to write some code that does something useful. Then write some more and make them work together. Repeat as necessary. Don't try to figure it all out up front. > > > Obviously this won't happen right away, I would likely develop each > > small design app as a standalone and then when I've got 3 or 4 done > > I would tie them together with the project app. When you have two standalone apps then you can reasonably think about how to tie them together. Before then too soon - you don't know what the standalone apps are going to look like until you make them. After you have three is getting to be too late - when you integrate the apps you will discover things you want to change about them to make the integration easier, and that will inform the way you create the next app. Don't leave out the unit tests - when you want to change your apps for integration (or any other reason) the unit tests will give you confidence that you haven't broken anything. Also writing the apps to be testable will help make them usable from another app. Kent From kaushalshriyan at gmail.com Thu Apr 6 15:06:53 2006 From: kaushalshriyan at gmail.com (Kaushal Shriyan) Date: Thu, 6 Apr 2006 18:36:53 +0530 Subject: [Tutor] Logical Operaor Message-ID: <6b16fb4c0604060606p5ce8c00fv25b21f2d800fe09e@mail.gmail.com> Hi I am referring to http://www.ibiblio.org/obp/thinkCSpy/chap04.htm about Logical operators I didnot understood >>> x = 5 >>> x and 1 1 >>> y = 0 >>> y and 1 0 How 5 and 1 means 1 and 0 and 1 means 0 Thanks Regards Kaushal From jasonkeen at gmail.com Thu Apr 6 15:40:11 2006 From: jasonkeen at gmail.com (Jason Keen) Date: Thu, 6 Apr 2006 09:40:11 -0400 Subject: [Tutor] Logical Operaor In-Reply-To: <6b16fb4c0604060606p5ce8c00fv25b21f2d800fe09e@mail.gmail.com> References: <6b16fb4c0604060606p5ce8c00fv25b21f2d800fe09e@mail.gmail.com> Message-ID: <889f4f6f0604060640v1346e08al3dfc7a993af24847@mail.gmail.com> In python, any nonzero number is considered to mean "True". Zero is considered to be "False". The "and" logical operation evaluates to "True" only if both terms are true. On 4/6/06, Kaushal Shriyan wrote: > Hi > > I am referring to http://www.ibiblio.org/obp/thinkCSpy/chap04.htm > about Logical operators > > I didnot understood > > >>> x = 5 > >>> x and 1 > 1 > >>> y = 0 > >>> y and 1 > 0 > > How 5 and 1 means 1 and 0 and 1 means 0 > > Thanks > > Regards > > Kaushal > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From RPhillips at engineer.co.summit.oh.us Thu Apr 6 16:15:03 2006 From: RPhillips at engineer.co.summit.oh.us (Ron Phillips) Date: Thu, 06 Apr 2006 10:15:03 -0400 Subject: [Tutor] preliminary app design question Message-ID: You might also consider JSON (http://www.json.org), which is generally lighter weight than XML, fairly human-readable, and useful in several languages (most, anymore) . Python, Javascript, and ECMAScript use it natively through Eval(), if you don't have security concerns; or through a wrapper if security is an issue. Python's pprint module will be a help if you go that route. I find it useful in development, so even if I am going to use some other storage, I'll leave any toJSON() and fromJSON() functions I write in place, anyway. Ron From alan.gauld at freenet.co.uk Thu Apr 6 17:53:06 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 6 Apr 2006 16:53:06 +0100 Subject: [Tutor] Logical Operators References: <6b16fb4c0604060336p74dbe676jb88838d0d9aa5b23@mail.gmail.com> Message-ID: <02ab01c65992$4b8e6bc0$0b01a8c0@xp> > I am referring to http://www.ibiblio.org/obp/thinkCSpy/chap04.htm > about Logical operators > You might find the functional programming topic in my tutorial interesting for a comparison. Look at the subsection "Short Circuit Evaluation" for some relevant examples. > I did not understood >>> x = 5 >>> x and 1 >1 >>> y = 0 >>> y and 1 >0 > > How 5 and 1 means 1 and 0 and 1 means 0 In Python any non zero value is considered True. So 5 and 1 are two true values and True and True = True whereas 0 and 1 means: False and True = False (ie zero) Are you familiar with Trutrh tables and the concepts of Boolean Logic? If not you may need some further explanation. If so a reasonable explanation appears on Wikipedia: http://en.wikipedia.org/wiki/Truth_table HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From Barry.Carroll at psc.com Thu Apr 6 18:44:26 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Thu, 6 Apr 2006 09:44:26 -0700 Subject: [Tutor] Logical Operators Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C3641@eugsrv400.psc.pscnet.com> Greetings, Kaushal: There are two topics to understand here: 1. what "TRUE" and "FALSE" mean in Python, and 2. how Python evaluates "X and Y". The tutorial "Instant Python" by Magnus Lie Hetland has good, short descriptions of these two topics, so I'll borrow from it. You can find the document at: http://www.hetland.org/python/instant-python.php 1. "All values in Python can be used as logic values. Some of the more "empty" ones, like [], 0, "" and None represent logical falsity, while most other values (like [0], 1 or "Hello, world") represent logical truth." In your examples, 5 and 1 are both considered 'TRUE', while 0, of course, is considered "FALSE". 2. "Now, logical expressions like a and b are evaluated like this: First, check if a is true. If it is not, then simply return it. If it is, then simply return b (which will represent the truth value of the expression.) The corresponding logic for a or b is: If a is true, then return it. If it isn't, then return b." Python evaluates your example expressions like this: a. Get the first sub-expression. x Get the value of x. 5 Is 5 a "TRUE" value? Yes Since the operator is "and", get the second sub-expression. 1 Is 1 a "TRUE" value? Yes Return it. 1 b. Get the first sub-expression. y Get the value of y. 0 Is 0 a "TRUE" value? No Since the operator is "and", STOP and return the sub-expression. 0 Does this help? Try this: change the 'and' operator in your examples to 'or'. What would the return value be now? 5 or 1 = ??? 0 or 1 = ??? Regards, Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed > -----Original Message----- > Date: Thu, 6 Apr 2006 16:06:11 +0530 > From: "Kaushal Shriyan" > Subject: [Tutor] Logical Operators > To: tutor at python.org > Message-ID: > <6b16fb4c0604060336p74dbe676jb88838d0d9aa5b23 at mail.gmail.com> > Content-Type: text/plain; charset=ISO-8859-1 > > Hi > > I am referring to http://www.ibiblio.org/obp/thinkCSpy/chap04.htm > about Logical operators > > I didnot understood > > >>> x = 5 > >>> x and 1 > 1 > >>> y = 0 > >>> y and 1 > 0 > > How 5 and 1 means 1 and 0 and 1 means 0 > > Thanks > > Regards > > Kaushal From tiagosaboga at terra.com.br Thu Apr 6 20:08:26 2006 From: tiagosaboga at terra.com.br (Tiago Saboga) Date: Thu, 6 Apr 2006 15:08:26 -0300 Subject: [Tutor] mysql store directory information Message-ID: <200604061508.26844.tiagosaboga@terra.com.br> Hi! As a first part of a project, I need to store a directory tree in a mysql db. I'm wondering if there is a canonical way of doing that. I don't know if it's an appropriate question for this list, but I think it's not only a choice of db design, but also a choice of appropriate python tools. My first approach is a table with the following columns: id - path - file name - size I'm starting to code it, and I'd like to know if you have a better suggestion... thanks. Tiago. From dyoo at hkn.eecs.berkeley.edu Thu Apr 6 20:41:39 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 6 Apr 2006 11:41:39 -0700 (PDT) Subject: [Tutor] mysql store directory information In-Reply-To: <200604061508.26844.tiagosaboga@terra.com.br> Message-ID: On Thu, 6 Apr 2006, Tiago Saboga wrote: > As a first part of a project, I need to store a directory tree in a > mysql db. I'm wondering if there is a canonical way of doing that. I > don't know if it's an appropriate question for this list, but I think > it's not only a choice of db design, but also a choice of appropriate > python tools. Hi Tiago, What are the interesting features of a directory? You might want to first model what you want, and then figure out an appropriate database table structure to represent that model. > My first approach is a table with the following columns: > id - path - file name - size So maybe we can say that a Directory can be modeled as: ###### class Directory: def __init__(self, id, path, file_name, size): self.id = id self.path = path self.file_name = file_name self.size = size ###### But why will you want to store this structure in the database, if it's already available on disk? Why not query the directory directly? > I'm starting to code it, and I'd like to know if you have a better > suggestion... I'd flesh out a few more of the requirements first; the requirement to store the directory in the database is slightly vague, so you probably will want to ask more questions about what the problem's really about. You might find something like SQLObject useful: http://www.sqlobject.org/ http://www.turbogears.org/about/sqlobject.html where you go fairly directly from data model to SQL table structure with SQLObject providing the default mapping strategy. From broek at cc.umanitoba.ca Thu Apr 6 02:51:33 2006 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Wed, 05 Apr 2006 19:51:33 -0500 Subject: [Tutor] request for sugestions on fragement of code for generating truth-tables In-Reply-To: <442EEADD.7040705@gmail.com> References: <442DCA10.9020104@cc.umanitoba.ca> <442EEADD.7040705@gmail.com> Message-ID: <44346615.5030205@cc.umanitoba.ca> Orri Ganel said unto the world upon 01/04/06 03:04 PM: > Brian van den Broek wrote: >> Then, the output is like so: >> >> >>> atoms = ["a","b","c"] >> >>> tvas = tva_dict_maker(atoms) >> >>> display_tvas(tvas) >> a:True b:True c:True >> a:True b:True c:False >> a:True b:False c:True >> a:True b:False c:False >> a:False b:True c:True >> a:False b:True c:False >> a:False b:False c:True >> a:False b:False c:False >> >>> > What this shouts immediately to me, at least, is binary numbers and > bool(). Just use your favorite binary conversion recipe, and count down > from int(len(atoms)*"1",2), converting as you go. And then you take the > boolean value of each digit of the binary number. If you need help, let > me know as I've completed a working model. > > HTH, > Orri Hi Orri, thanks for the suggestion, and apologies for the delayed response. I absolutely agree that the problem is connected to binary representations of integers as you suggest. The problem -- given my needs -- with your suggested approach is in "use your favo[u*]rite binary conversion recipe". I want my code to be stand alone and I feel fairly safe in asserting that if I implemented your suggestion in a self-contained chunk of code, I'd end up with something more complex than the code I originally posted. In effect, my original code exploited the same principle, without actually going through the binary representation. I am of course open to the possibility that my suspicion is ill-grounded ;-) But, thanks! Best, Brian vdB [*] I'm Canadian, eh! ;-) From broek at cc.umanitoba.ca Thu Apr 6 02:40:14 2006 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Wed, 05 Apr 2006 19:40:14 -0500 Subject: [Tutor] request for sugestions on fragement of code for generating truth-tables In-Reply-To: References: Message-ID: <4434636E.5020308@cc.umanitoba.ca> Danny Yoo said unto the world upon 31/03/06 08:27 PM: > >>Then, the output is like so: >> >> >>> atoms = ["a","b","c"] >> >>> tvas = tva_dict_maker(atoms) >> >>> display_tvas(tvas) >>a:True b:True c:True >>a:True b:True c:False >>a:True b:False c:True >>a:True b:False c:False >>a:False b:True c:True >>a:False b:True c:False >>a:False b:False c:True >>a:False b:False c:False > > > Hi Brian, > > We might be able to take advantage of the recursive nature of this > problem. > > I'll sketch out the idea and try to fight the temptation to write it out > in full. *grin* If you haven't encountered recursion before, please shout > out and ask for more details. Hi Danny and all, thanks for the response and my apologies for the delayed reply. (No internet at home and end of academic term death-march conspired :-) My first thought about how to tackle the problem was indeed to do it recursively. I got bogged down and ended up with the alternate approach I posted in the original post. Your post got me to take another bash and I obtained a recursive solution. But, subject to the caveat that my recursive solution might well be non-optimal, the non-recursive approach seems a bit better to me. Opinions welcome :-) My recursive solution: def recursive_tva_dict_maker(atoms, recursed=False): tvas = [{atoms[0]:True}, {atoms[0]:False}] if atoms[1:]: temp = [] rest = recursive_tva_dict_maker(atoms[1:], True) for r in rest: for tva in tvas: new = tva.copy() new.update(r) temp.append(new) tvas = temp if not recursed: # if test seemed cheaper than pointless sorting tvas.sort(key = lambda x: [x[y] for y in sorted(x)], reverse=True) return tvas My non-recursive solution: def tva_dict_maker(atoms): tvas = [] val = False for k in range(2**len(atoms)): tvas.append(dict()) for i in range(len(atoms)): key = atoms[i] for j in range(2**len(atoms)): if j % ( len(tvas) / 2.0 ** (i+1) ) == 0: val = not val tvas[j][key]=val return tvas The two functions have identical output. I don't much care about time or resources, as atoms will in practice never be more than 4 or 5 items long. (So, the recursive solution could be simplified by getting rid of the if guard on the sorting. That the ultimate output be so sorted is essential, however.) I'm more concerned with style and clarity. Best, Brian vdB From dyoo at hkn.eecs.berkeley.edu Thu Apr 6 23:38:24 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 6 Apr 2006 14:38:24 -0700 (PDT) Subject: [Tutor] request for sugestions on fragement of code for generating truth-tables In-Reply-To: <4434636E.5020308@cc.umanitoba.ca> Message-ID: > Your post got me to take another bash and I obtained a recursive > solution. But, subject to the caveat that my recursive solution might > well be non-optimal, the non-recursive approach seems a bit better to > me. Opinions welcome :-) > > My recursive solution: > > def recursive_tva_dict_maker(atoms, recursed=False): > > tvas = [{atoms[0]:True}, {atoms[0]:False}] > > if atoms[1:]: > temp = [] > rest = recursive_tva_dict_maker(atoms[1:], True) > > for r in rest: > for tva in tvas: > new = tva.copy() > new.update(r) > temp.append(new) > tvas = temp > > if not recursed: # if test seemed cheaper than pointless sorting > tvas.sort(key = lambda x: [x[y] for y in sorted(x)], > reverse=True) > > return tvas Hi Brian, One way to get rid of the 'recursed' flag is to refactor slightly, and break out the sorting in another helper function, like this: ################################################################## def tva_dict_maker(atoms): tvas = tiva_helper(atoms) tvas.sort(key = lambda x: [x[y] for y in sorted(x)], reverse=True) return tvas def tva_helper(atoms): tvas = [{atoms[0]:True}, {atoms[0]:False}] if atoms[1:]: temp = [] rest = recursive_tva_dict_maker(atoms[1:]) for r in rest: for tva in tvas: new = tva.copy() new.update(r) temp.append(new) tvas = temp return tvas ################################################################## This way, tva_helper() doesn't have to care about sorting, since tva_dict_maker() will do it instead. Here's a slightly wordier version of what you have, but taken to a far extreme. *grin* ################################################################## ## In the comments below, an "assignment" is a dictionary ## that maps atoms to booleans. def make_truth_table(atoms): """make_truth_table: (listof atoms) -> (listof assignment) Builds a small truth table of all possibilities.""" if atoms == []: ## the empty case is one with the "empty" assignment! return [{}] else: sub_assignments = make_truth_table(atoms[1:]) return (extend_all(sub_assignments, {atoms[0] : True}) + extend_all(sub_assignments, {atoms[0] : False})) def extend_all(assignments, extension): """extend_all: (listof assignment) assignment -> (listof assignment) Takes each assignment in the list of assignments, and enhances it with the extension. """ return [extend_assignment(single, extension) for single in assignments] def extend_assignment(assignment, extension): """extend_assignment: assignment assignment -> assignment Takes the assignment and creates a new one that extends the first with the extension.""" extended = assignment.copy() extended.update(extension) return extended ################################################################## As you can tell, I really like helper functions. *grin* I've tried to document as best I can to make it clearer how the recursive approach breaks things down. [non-recursive code cut] > The two functions have identical output. I don't much care about time or > resources, as atoms will in practice never be more than 4 or 5 items > long. (So, the recursive solution could be simplified by getting rid of > the if guard on the sorting. That the ultimate output be so sorted is > essential, however.) > > I'm more concerned with style and clarity. Yes, I agree that the readability of the code is primary. Understandng the recursive approach depends on the reader's comfort with recursive functions, and the non-recursive code depends on the reader's comfort with arithmetic operators. Best of wishes to you! From dyoo at hkn.eecs.berkeley.edu Thu Apr 6 23:56:16 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 6 Apr 2006 14:56:16 -0700 (PDT) Subject: [Tutor] request for sugestions on fragement of code for generating truth-tables In-Reply-To: Message-ID: > One way to get rid of the 'recursed' flag is to refactor slightly, and > break out the sorting in another helper function, like this: > > ################################################################## > def tva_dict_maker(atoms): > tvas = tiva_helper(atoms) ^^^^^^^^^^^ > tvas.sort(key = lambda x: [x[y] for y in sorted(x)], > reverse=True) > return tvas > > def tva_helper(atoms): > tvas = [{atoms[0]:True}, {atoms[0]:False}] > if atoms[1:]: > temp = [] > rest = recursive_tva_dict_maker(atoms[1:]) ^^^^^^^^^^^^^^^^^^^^^^^^ > for r in rest: > for tva in tvas: > new = tva.copy() > new.update(r) > temp.append(new) > tvas = temp > return tvas > ################################################################## Hi Brian, Gaaa. When I renamed 'recursive_tva_dict_maker' to tva_helper, I forgot to rename the recursive call too, and I left a few misspellings in there too! My apologies: I must must test code before posting... *sigh* The code above should have been: ######################################################## def tva_dict_maker(atoms): tvas = tva_helper(atoms) tvas.sort(key = lambda x: [x[y] for y in sorted(x)], reverse=True) return tvas def tva_helper(atoms): tvas = [{atoms[0]:True}, {atoms[0]:False}] if atoms[1:]: temp = [] rest = tva_helper(atoms[1:]) for r in rest: for tva in tvas: new = tva.copy() new.update(r) temp.append(new) tvas = temp return tvas ######################################################## From jramakrishnan at neuropace.com Fri Apr 7 02:16:04 2006 From: jramakrishnan at neuropace.com (Janesh Ramakrishnan) Date: Thu, 6 Apr 2006 17:16:04 -0700 Subject: [Tutor] Tutor Digest, Vol 25, Issue 83 Message-ID: <405EDF2FA0855E43B27EA6DAFA1C78CEE66D42@laguna.neuropace.com> Hi Kent: Thanks for your response. The Grep function does a really good job of searching across .py files in a directory or subdirectories for the specific keyword/string. In the PythonWin interpreter 2.1, Go to File -> New -> Grep and the search string can be entered. It is useful in searching strings across multiple files, especially in large projects. ~Janesh Message: 1 Date: Thu, 30 Mar 2006 21:22:39 -0500 From: Kent Johnson Subject: Re: [Tutor] Searching across .Py files for a particular string/ character Cc: tutor at python.org Message-ID: <442C926F.3080007 at tds.net> Content-Type: text/plain; charset=ISO-8859-1; format=flowed Janesh Ramakrishnan wrote: > Hi Folks, > > I was wondering what would be the best way to look up a string across > different files in the Python interpreter (PythonWin 2.4). The find function only finds files within currently open files. If I have a folder of .py scripts and need to look up a specific keyword or string among all these files within the project folder, is there any method that you'd recommend? I would do that in my editor, probably. But Python can get a list of files in a directory with os.listdir(). Loop over the files, use os.path.join() to make a full path, open the file, read the data, look for the string in the data. Kent From broek at cc.umanitoba.ca Fri Apr 7 02:19:42 2006 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Thu, 06 Apr 2006 19:19:42 -0500 Subject: [Tutor] Logical Operaor In-Reply-To: <6b16fb4c0604060606p5ce8c00fv25b21f2d800fe09e@mail.gmail.com> References: <6b16fb4c0604060606p5ce8c00fv25b21f2d800fe09e@mail.gmail.com> Message-ID: <4435B01E.8020607@cc.umanitoba.ca> Kaushal Shriyan said unto the world upon 06/04/06 08:06 AM: > Hi > > I am referring to http://www.ibiblio.org/obp/thinkCSpy/chap04.htm > about Logical operators > > I didnot understood > > >>>> x = 5 >>>> x and 1 > > 1 > >>>> y = 0 >>>> y and 1 > > 0 > > How 5 and 1 means 1 and 0 and 1 means 0 > > Thanks > > Regards > > Kaushal Kaushal, as Jason pointed out, any non-zero number evaluates to True. Also, any non-empty list, string, dict, etc. Witness: >>> bool(6) True >>> bool(0) False >>> bool("non-empty string") True >>> bool(' ') True >>> bool('') False The other part of the puzzle is that 'and' and 'or' are "short-circuit" operators. 'or' works like this: return the first value flanking the or if that evaluates to True. Otherwise return the second value: >>> 42 or 0 42 >>> 0 or 42 42 >>> 7 or 42 7 >>> 42 or 7 42 >>> 0 or [] [] >>> [] or 0 0 >>> 'and' works similarly. It returns the first value if that evaluates to False. Otherwise, it returns the second: >>> 42 and 7 7 >>> 7 and 42 42 >>> 0 and [] 0 >>> [] and 0 [] >>> HTH, Brian vdB From broek at cc.umanitoba.ca Fri Apr 7 02:27:59 2006 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Thu, 06 Apr 2006 19:27:59 -0500 Subject: [Tutor] request for sugestions on fragement of code for generating truth-tables In-Reply-To: References: Message-ID: <4435B20F.8040709@cc.umanitoba.ca> Danny Yoo said unto the world upon 06/04/06 04:38 PM: > Yes, I agree that the readability of the code is primary. Understandng > the recursive approach depends on the reader's comfort with recursive > functions, and the non-recursive code depends on the reader's comfort with > arithmetic operators. But all arithmetical operations are recursively definable from 0 and sucessorship, so what's the difference? ;-) In all seriousness, though: thanks for the further comments and the helper-function-intense sample code. I'll have a think before I try to decide which I prefer -- I like the division of responsibilities, but worry that the conceptual units have become a bit too small for taste. And, fret not over the typos that you followed up about. I parsed as intended just fine. :-) Thanks again, Brian vdB From justin.mailinglists at gmail.com Fri Apr 7 02:40:32 2006 From: justin.mailinglists at gmail.com (Justin Ezequiel) Date: Fri, 7 Apr 2006 08:40:32 +0800 Subject: [Tutor] regular expressions - backslashes Message-ID: <3c6718980604061740p1461ae00wd5ed0d6815e7ffa7@mail.gmail.com> Kent wrote: """The problem is that the re engine itself is interpreting the backslashes in the replacement pattern. With a single slash you get a newline even though the slash is a literal in the replacement string: So if you want a literal \ in your replacement text you have to escape the \, even in a raw string: """ Thanks. will try to convince my colleague to use string formatting if he insists on regexp then he can do re.sub(r'(?i)', apppath.replace('\\', '\\\\'), template) re.escape does not quite work for my example >>> re.sub(r'(?i)', re.escape(apppath), template) 'C\\:\\napp\\_and\\_author\\_query\\napp\\_and\\_author\\_query\\a\\ b\\ c\\ d\\files' >>> print re.sub(r'(?i)', re.escape(apppath), template) C\:\napp\_and\_author\_query\napp\_and\_author\_query\a\ b\ c\ d\files From tiagosaboga at terra.com.br Fri Apr 7 03:54:01 2006 From: tiagosaboga at terra.com.br (Tiago Saboga) Date: Thu, 6 Apr 2006 22:54:01 -0300 Subject: [Tutor] mysql store directory information In-Reply-To: References: Message-ID: <200604062254.01725.tiagosaboga@terra.com.br> Em Qui 06 Abr 2006 15:41, Danny Yoo escreveu: > On Thu, 6 Apr 2006, Tiago Saboga wrote: > > As a first part of a project, I need to store a directory tree in a > > mysql db. I'm wondering if there is a canonical way of doing that. I > > don't know if it's an appropriate question for this list, but I think > > it's not only a choice of db design, but also a choice of appropriate > > python tools. > > Hi Tiago, > > What are the interesting features of a directory? You might want to first > model what you want, and then figure out an appropriate database table > structure to represent that model. Hi, and thank you. I knew I had to explain longer what I wanted, but I was kind of frustrated by the difficulty of writing in english. But I'll try to think less about it, and go further. As I said, this is part of a project. For each of these files, I'll have a database of informations, and this is what really matters, and I have a data model for that. But I want also to able to find these files, which are on removable media (cds and dvds). As I'll have to store where's the file, I thought I could as well store some other basic infos, at least the size (I really don't know yet what else could be useful later). > > My first approach is a table with the following columns: > > id - path - file name - size > > So maybe we can say that a Directory can be modeled as: > > ###### > class Directory: > def __init__(self, id, path, file_name, size): > self.id = id > self.path = path > self.file_name = file_name > self.size = size > ###### > > But why will you want to store this structure in the database, if it's > already available on disk? Why not query the directory directly? See above. > > > I'm starting to code it, and I'd like to know if you have a better > > suggestion... > > I'd flesh out a few more of the requirements first; the requirement to > store the directory in the database is slightly vague, so you probably > will want to ask more questions about what the problem's really about. > > > > You might find something like SQLObject useful: > > http://www.sqlobject.org/ > http://www.turbogears.org/about/sqlobject.html > > where you go fairly directly from data model to SQL table structure with > SQLObject providing the default mapping strategy. Hey, this is *really* great ;-) Hey, I love it. OK, but now why would I use such a directory class as you proposed above? (preliminar question: isn't it rather a file class, as it has only one filename? Anyway, I see your point.) I would make a SQLobject class for files, and feed it with something like def get_dirtree(path): tree = [] for dirpath, dirnames, filenames in os.walk(path): if filenames: for file in filenames: size = os.path.getsize(os.path.join(dirpath,file)) tree.append((dirpath,file,size)) return tree What do you think? Of course, it could be the __init__ function of class, but I don't see why. Thanks, again. Tiago. From amonroe at columbus.rr.com Fri Apr 7 04:10:48 2006 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Thu, 6 Apr 2006 22:10:48 -0400 Subject: [Tutor] mysql store directory information In-Reply-To: <200604062254.01725.tiagosaboga@terra.com.br> References: <200604062254.01725.tiagosaboga@terra.com.br> Message-ID: <187954756196.20060406221048@columbus.rr.com> > Em Qui 06 Abr 2006 15:41, Danny Yoo escreveu: > model for that. But I want also to able to find these files, which are on > removable media (cds and dvds). As I'll have to store where's the file, I > thought I could as well store some other basic infos, at least the size (I > really don't know yet what else could be useful later). You could cheat and just use "Cathy" from this site: http://rvas.webzdarma.cz/ :^) It's one of my favorite utilities. Alan From tiagosaboga at terra.com.br Fri Apr 7 04:36:08 2006 From: tiagosaboga at terra.com.br (Tiago Saboga) Date: Thu, 6 Apr 2006 23:36:08 -0300 Subject: [Tutor] mysql store directory information In-Reply-To: <187954756196.20060406221048@columbus.rr.com> References: <200604062254.01725.tiagosaboga@terra.com.br> <187954756196.20060406221048@columbus.rr.com> Message-ID: <200604062336.08641.tiagosaboga@terra.com.br> Em Qui 06 Abr 2006 23:10, R. Alan Monroe escreveu: > > Em Qui 06 Abr 2006 15:41, Danny Yoo escreveu: > > > > model for that. But I want also to able to find these files, which are on > > removable media (cds and dvds). As I'll have to store where's the file, I > > thought I could as well store some other basic infos, at least the size > > (I really don't know yet what else could be useful later). > > You could cheat and just use "Cathy" from this site: > http://rvas.webzdarma.cz/ Looks like an interesting piece of software, but as far as I can see it's only for windows and it's not open-source (and hence, not portable). And it still lacks some nice features I'd like to have. Finally, I chose this project because I'll use tools I want to learn. So I'll stick with it ;-) Thanks! TIago. From kent37 at tds.net Fri Apr 7 04:47:18 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 06 Apr 2006 22:47:18 -0400 Subject: [Tutor] regular expressions - backslashes In-Reply-To: <3c6718980604061740p1461ae00wd5ed0d6815e7ffa7@mail.gmail.com> References: <3c6718980604061740p1461ae00wd5ed0d6815e7ffa7@mail.gmail.com> Message-ID: <4435D2B6.9040900@tds.net> Justin Ezequiel wrote: > will try to convince my colleague to use string formatting > if he insists on regexp then he can do > re.sub(r'(?i)', apppath.replace('\\', '\\\\'), template) > > re.escape does not quite work for my example > >>>> re.sub(r'(?i)', re.escape(apppath), template) > 'C\\:\\napp\\_and\\_author\\_query\\napp\\_and\\_author\\_query\\a\\ > b\\ c\\ d\\files' >>>> print re.sub(r'(?i)', re.escape(apppath), template) > C\:\napp\_and\_author\_query\napp\_and\_author\_query\a\ b\ c\ d\files OK, I didn't realize re.escape() was so aggressive. Depending on how you are going to use the file paths, another alternative is just to use / instead of \, that will work fine within Python even on Windows. Kent From ml.cyresse at gmail.com Fri Apr 7 14:24:46 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Sat, 8 Apr 2006 00:24:46 +1200 Subject: [Tutor] Python performance resources & resouce usage hints Message-ID: Hi, I've developed what would be my largest Python app to date. And, going from the crude Windows Task Manager, it's trying to use as much CPU time as it can get when it's idle. This, no doub,t is due to my design. I have an UDP socket server, a packet cruncher, and a DAO. Each resides in it's own thread, and each thread is connected to the next by a Queue. So it's server ---> cruncher --> DAO. Each thread's run() method basically looks like this - while True: try: data = self.queue.get(False) self.DAO.send_data(data) except Empty: if self.shutdown: print "\DAO closing" return continue i.e. each thread is looping endlessly until data arrives via the queue. I can't believe it chews the CPU time the way it does, but I suppose it's easy to do so. My query to the list is twofold - First, if anyone knows of any websites with articles on Python threading optimisation/pitfalls websites, I'd be greatly appreciative. I've been reading the Performance tips on the official wiki, so if there's anything similar I'd be keen to look at it. Okay, the 2nd piece of advice I'm seeking, is what would be the most efficient path here? My initial thoughts are along three lines: Either: A) Increase the queue size of the socket servers B) Use timer threads to 'pulse' my threads. Or: A) Increase the queue size of the socket servers B) Use blocking queues Or: A) Use blocking queues with a timeout B) Use the socket servers to "wake" processing threads As Python doesn't have sleeping threads etc, the third option is my current measure of last resort, as there'll be some substantial rejigging, and I'm not overly experienced with threads. On the wiki http://wiki.python.org/moin/PythonSpeed/PerformanceTips#periodic, I read that "There is a function in the sys module, setcheckinterval, which you can call to tell the interpreter how often to perform these periodic checks." Should I even think about that? I'm not after performance so much as less utilisation of system resources... Much thanks for any guidance offered. Regards, Liam Clarke From josipl2000 at yahoo.com Fri Apr 7 12:51:39 2006 From: josipl2000 at yahoo.com (josip) Date: Fri, 7 Apr 2006 03:51:39 -0700 (PDT) Subject: [Tutor] function caller Message-ID: <20060407105139.89245.qmail@web60819.mail.yahoo.com> Hi, Can someone explain me function and caller relationship when passing arguments? Thanks --------------------------------- How low will we go? Check out Yahoo! Messenger?s low PC-to-Phone call rates. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060407/7b00a92d/attachment.htm From carlos at carlosbenevides.com Fri Apr 7 16:53:00 2006 From: carlos at carlosbenevides.com (Carlos Benevides) Date: Fri, 07 Apr 2006 09:53:00 -0500 Subject: [Tutor] Quick question, Message-ID: <44367CCC.6010309@carlosbenevides.com> Hi, Can someone tell me what the r before the expression means, as in "re.compile(r'(\.exe|\.zip|\.pif|\.scr|\.ps|\.pdf|\.ppt)$')"? I've seen regular expressions both ways, and I've seen them work with or without the r. Just wondering what it does, or if it makes a difference. Thanks. From kent37 at tds.net Fri Apr 7 18:10:37 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 07 Apr 2006 12:10:37 -0400 Subject: [Tutor] Python performance resources & resouce usage hints In-Reply-To: References: Message-ID: <44368EFD.4090303@tds.net> Liam Clarke wrote: > Hi, > > I've developed what would be my largest Python app to date. And, going > from the crude Windows Task Manager, it's trying to use as much CPU > time as it can get when it's idle. > > This, no doub,t is due to my design. > > I have an UDP socket server, a packet cruncher, and a DAO. > Each resides in it's own thread, and each thread is connected to the > next by a Queue. > > So it's server ---> cruncher --> DAO. > > Each thread's run() method basically looks like this - > > while True: > try: > data = self.queue.get(False) > self.DAO.send_data(data) > except Empty: > if self.shutdown: > print "\DAO closing" > return > continue > > > i.e. each thread is looping endlessly until data arrives via the > queue. I can't believe it chews the CPU time the way it does, but I > suppose it's easy to do so. Yes, it's easy. You have basically told the thread to check the queue as often as possible. So it is running as fast as it can, checking the queue and handling whatever comes its way. > > My query to the list is twofold - > > First, if anyone knows of any websites with articles on Python > threading optimisation/pitfalls websites, I'd be greatly appreciative. There's not much. This might help: http://linuxgazette.net/107/pai.html This book is excellent for teaching some of the tools that are used for communication and synchronization between threads: http://greenteapress.com/semaphores/ There are many threading related recipes in the Python Cookbook, both online and printed. http://aspn.activestate.com/ASPN/Cookbook/Python > Okay, the 2nd piece of advice I'm seeking, is what would be the most > efficient path here? > My initial thoughts are along three lines: > > Either: > > A) Increase the queue size of the socket servers I don't see how that would help. > B) Use timer threads to 'pulse' my threads. That's a lot of additional complexity. > A) Increase the queue size of the socket servers > B) Use blocking queues > > Or: > > A) Use blocking queues with a timeout > B) Use the socket servers to "wake" processing threads These are all better. > > As Python doesn't have sleeping threads etc, the third option is my > current measure of last resort, as there'll be some substantial > rejigging, and I'm not overly experienced with threads. Use time.sleep() to sleep a thread. The simplest fix is to add a time.sleep() into your loops. Then the thread will check the queue, process any work, and sleep for a little while. (This is called a busy loop.) The disadvantage of this solution is that there is a trade off between CPU usage and responsiveness. If the sleep is very short, the thread will be very responsive but it will still run a lot and use CPU when idling. If you make the timeout long, the idle CPU will be very low but responsiveness will be poor. If you can live with a response delay of 0.05 or 0.1 second, try that, it should cut the CPU usage dramatically. Even a 0.01 delay might make a big difference. A better fix is to use blocking queues or other blocking events. In this approach, a thread will block until there is something to do, then wake up, do its work and go back to sleep. The hitch here is you need to find another way to signal the thread to exit. One possibility is just to mark them as daemon threads, then they will exit when your app exits. This is a very simple solution if you don't have any cleanup actions you want to do in the threads. Another possibility might be to send a "quit" message in the queue. When the thread sees the special quit message, it forwards it to the next thread and exits. If neither of these work then you could use a queue.get() with a timeout so you check the done flag periodically. Kent From noufal at nibrahim.net.in Fri Apr 7 18:19:09 2006 From: noufal at nibrahim.net.in (Noufal Ibrahim) Date: Fri, 7 Apr 2006 21:49:09 +0530 (IST) Subject: [Tutor] Quick question, In-Reply-To: <44367CCC.6010309@carlosbenevides.com> References: <44367CCC.6010309@carlosbenevides.com> Message-ID: <46680.203.145.176.76.1144426749.squirrel@members.hcoop.net> On Fri, April 7, 2006 8:23 pm, Carlos Benevides wrote: > Hi, > > Can someone tell me what the r before the expression means, as in > "re.compile(r'(\.exe|\.zip|\.pif|\.scr|\.ps|\.pdf|\.ppt)$')"? r is the way of making a string "raw". This means that escape characters will not be interpreted. Here is an example that should make it clear. >>> foo = "This is \t me" >>> print foo This is me >>> foo = r"This is \t me" >>> print foo This is \t me >>> Since slashes are used often for writing regexps, it's useful to make the strings raw. Peace. -- -NI From hugonz-lists at h-lab.net Fri Apr 7 18:42:37 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Fri, 07 Apr 2006 10:42:37 -0600 Subject: [Tutor] Python performance resources & resouce usage hints In-Reply-To: References: Message-ID: <4436967D.1080106@h-lab.net> Liam Clarke wrote: > Each thread's run() method basically looks like this - > > while True: > try: > data = self.queue.get(False) > self.DAO.send_data(data) > except Empty: > if self.shutdown: > print "\DAO closing" > return > continue > > Hi Liam, I checked the response by Kent. I completely agree with him in that the problem is the endless polling you have. However, you do not have to implement a sleep in your loop; the main issue may be that you are not using the facilities of the 'get' method in the queue. From the queue docs: get( [block[, timeout]]) Remove and return an item from the queue. If optional args block is true and timeout is None (the default), block if necessary until an item is available. If timeout is a positive number, it blocks at most timeout seconds and raises the Empty exception if no item was available within that time. Otherwise (block is false), return an item if one is immediately available, else raise the Empty exception (timeout is ignored in that case). You are not using the optional timeout and blocking which 'get' provides (!) Try setting it and see your CPU usage go down. This will implement blocking, and the queue will be used as soon as data is there. Set block to True and a timeout if you need to use it (looks like you only need blocking) while True: try: data = self.queue.get(True) self.DAO.send_data(data) Hope that helps, Hugo From hugonz-lists at h-lab.net Fri Apr 7 18:51:29 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Fri, 07 Apr 2006 10:51:29 -0600 Subject: [Tutor] function caller In-Reply-To: <20060407105139.89245.qmail@web60819.mail.yahoo.com> References: <20060407105139.89245.qmail@web60819.mail.yahoo.com> Message-ID: <44369891.90005@h-lab.net> josip wrote: > Can someone explain me function and caller relationship when passing > arguments? Hi... what do you mean? Is there something specific you're not getting if you take a look at: http://www.ibiblio.org/obp/thinkCSpy/chap03.htm http://docs.python.org/tut/node6.html#SECTION006600000000000000000 We'd be glad to help with that, but we need the doubt to be more specific. Hugo From hugonz-lists at h-lab.net Fri Apr 7 19:06:40 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Fri, 07 Apr 2006 11:06:40 -0600 Subject: [Tutor] Quick question, In-Reply-To: <44367CCC.6010309@carlosbenevides.com> References: <44367CCC.6010309@carlosbenevides.com> Message-ID: <44369C20.7050909@h-lab.net> Carlos Benevides wrote: > Hi, > > Can someone tell me what the r before the expression means, as in > "re.compile(r'(\.exe|\.zip|\.pif|\.scr|\.ps|\.pdf|\.ppt)$')"? It is not specific to regular expressions, it is called a raw string. http://docs.python.org/tut/node5.html From jjabson at yahoo.com Fri Apr 7 19:15:03 2006 From: jjabson at yahoo.com (Jerome Jabson) Date: Fri, 7 Apr 2006 10:15:03 -0700 (PDT) Subject: [Tutor] string formatting question Message-ID: <20060407171503.17438.qmail@web53710.mail.yahoo.com> Hello, I'm trying to replace some strings in a line of text, using some regex functions. My question is: If there's more then one regex grouping I want to replace in one line of a file, how can I use the String Formatting operator (%s) in two places? Here's the line it matches in the file: Here's the regex: m_sock = re.compile('(portNumber=)"\d+" (tcpORudp=)"[A-Z]+"') My replace should look like this: \1 "112" \2 "TCP" (obviously "112" and "TCP" would be varibles) My problem now is how do I construct the replace statement? twork = m_sock.sub('\1 %s \2 %s', % port_num % proto, twork) But of course this does not work! :-( Is there a better way to do this? Or am I just doing this all wrong? Thanks in advance! __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From kent37 at tds.net Fri Apr 7 19:45:28 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 07 Apr 2006 13:45:28 -0400 Subject: [Tutor] string formatting question In-Reply-To: <20060407171503.17438.qmail@web53710.mail.yahoo.com> References: <20060407171503.17438.qmail@web53710.mail.yahoo.com> Message-ID: <4436A538.8070502@tds.net> Jerome Jabson wrote: > Hello, > > I'm trying to replace some strings in a line of text, > using some regex functions. My question is: If there's > more then one regex grouping I want to replace in one > line of a file, how can I use the String Formatting > operator (%s) in two places? Hi Jerome, I don't understand your question. Can you give a complete example of the line from the file and the new line you want to create? > > Here's the line it matches in the file: > > address="64.41.134.60"/> > > Here's the regex: > m_sock = re.compile('(portNumber=)"\d+" > (tcpORudp=)"[A-Z]+"') You have put parentheses around fixed strings, so your groups will always be the same. Is that what you want? > > My replace should look like this: > \1 "112" \2 "TCP" > (obviously "112" and "TCP" would be varibles) This looks like you want to make the string portNumber= 112 tcpORudp= TCP but that doesn't have any variable text from the original string so I think I must not understand. Kent > > My problem now is how do I construct the replace > statement? > twork = m_sock.sub('\1 %s \2 %s', % port_num % proto, > twork) > > But of course this does not work! :-( Is there a > better way to do this? Or am I just doing this all > wrong? > > Thanks in advance! > > __________________________________________________ > Do You Yahoo!? > Tired of spam? Yahoo! Mail has the best spam protection around > http://mail.yahoo.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From kent37 at tds.net Fri Apr 7 19:53:38 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 07 Apr 2006 13:53:38 -0400 Subject: [Tutor] Python performance resources & resouce usage hints In-Reply-To: <4436967D.1080106@h-lab.net> References: <4436967D.1080106@h-lab.net> Message-ID: <4436A722.4040707@tds.net> Hugo Gonz?lez Monteverde wrote: > You are not using the optional timeout and blocking which 'get' provides (!) > > Try setting it and see your CPU usage go down. This will implement > blocking, and the queue will be used as soon as data is there. Set block > to True and a timeout if you need to use it (looks like you only need > blocking) > > while True: > try: > data = self.queue.get(True) > self.DAO.send_data(data) I think he will need the timeout too, otherwise the shutdown flag will only be checked when there is work which is probably not what he wants. I agree, this is a good solution. Kent From alan.gauld at freenet.co.uk Fri Apr 7 20:10:43 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 7 Apr 2006 19:10:43 +0100 Subject: [Tutor] string formatting question References: <20060407171503.17438.qmail@web53710.mail.yahoo.com> Message-ID: <032801c65a6e$966965f0$0b01a8c0@xp> > My problem now is how do I construct the replace > statement? > twork = m_sock.sub('\1 %s \2 %s', % port_num % proto, > twork) The format operator takes a tuple: twork = m_sock.sub('\1 %s \2 %s' % (port_num, proto), twork) So I removed the comma after the string, used a single percent operator and I put the two variables in a tuple HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Fri Apr 7 20:14:00 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 7 Apr 2006 19:14:00 +0100 Subject: [Tutor] function caller References: <20060407105139.89245.qmail@web60819.mail.yahoo.com> Message-ID: <033201c65a6f$0bd75950$0b01a8c0@xp> > Hi, Hi, > Can someone explain me function and caller relationship when passing > arguments? There is an explanation of this in vitually any tutorial on Python. Haver you read any of these? Have you any experience in other languages that we can relate an explanation too? For example, you could read the Modules and Functions topic in my tutor. If you still don't undeerstand come back with a specific question and we can try to help some more. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From jjabson at yahoo.com Fri Apr 7 20:18:18 2006 From: jjabson at yahoo.com (Jerome Jabson) Date: Fri, 7 Apr 2006 11:18:18 -0700 (PDT) Subject: [Tutor] string formatting question Message-ID: <20060407181818.43293.qmail@web53713.mail.yahoo.com> Hi Kent, Sorry I didn't make my question clearer. Bascially I want to replace this line: With: So the regex grouping are that I want to keep portNumber= and tcpORudp= and replace the values. Which will be varibles in my code. The question is more on the string formatting in the replace. How do use two %s in one statement? i.e.: re.sub('\1 %s \2 %s' % var1 % var2, line) Thanks again! > Hello, > > I'm trying to replace some strings in a line of text, > using some regex functions. My question is: If there's > more then one regex grouping I want to replace in one > line of a file, how can I use the String Formatting > operator (%s) in two places? Hi Jerome, I don't understand your question. Can you give a complete example of the line from the file and the new line you want to create? > > Here's the line it matches in the file: > > address="64.41.134.60"/> > > Here's the regex: > m_sock = re.compile('(portNumber=)"\d+" > (tcpORudp=)"[A-Z]+"') You have put parentheses around fixed strings, so your groups will always be the same. Is that what you want? > > My replace should look like this: > \1 "112" \2 "TCP" > (obviously "112" and "TCP" would be varibles) This looks like you want to make the string portNumber= 112 tcpORudp= TCP but that doesn't have any variable text from the original string so I think I must not understand. Kent > > My problem now is how do I construct the replace > statement? > twork = m_sock.sub('\1 %s \2 %s', % port_num % proto, > twork) > > But of course this does not work! :-( Is there a > better way to do this? Or am I just doing this all > wrong? > > Thanks in advance! > __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From dyoo at hkn.eecs.berkeley.edu Fri Apr 7 20:27:50 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 7 Apr 2006 11:27:50 -0700 (PDT) Subject: [Tutor] Python performance resources & resouce usage hints In-Reply-To: <4436A722.4040707@tds.net> Message-ID: On Fri, 7 Apr 2006, Kent Johnson wrote: > Hugo González Monteverde wrote: > > You are not using the optional timeout and blocking which 'get' provides (!) > > > > Try setting it and see your CPU usage go down. This will implement > > blocking, and the queue will be used as soon as data is there. Set block > > to True and a timeout if you need to use it (looks like you only need > > blocking) > > > > while True: > > try: > > data = self.queue.get(True) > > self.DAO.send_data(data) > > I think he will need the timeout too, otherwise the shutdown flag will > only be checked when there is work which is probably not what he wants. This could be fixed: when setting the 'shutdown' flag, also push a sentinel piece of data into the queue. That'll wake the thread back up, and that'll give it the opportunity to process a shutdown. The thread here: http://mail.python.org/pipermail/tutor/2006-January/044557.html has some more examples of this. Hope this helps! From kent37 at tds.net Fri Apr 7 20:28:54 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 07 Apr 2006 14:28:54 -0400 Subject: [Tutor] string formatting question In-Reply-To: <20060407181818.43293.qmail@web53713.mail.yahoo.com> References: <20060407181818.43293.qmail@web53713.mail.yahoo.com> Message-ID: <4436AF66.307@tds.net> Jerome Jabson wrote: > Hi Kent, > > Sorry I didn't make my question clearer. Bascially I > want to replace this line: > > address="64.41.134.60"/> > > With: > > address="64.41.134.60"/> > > So the regex grouping are that I want to keep > portNumber= and tcpORudp= and replace the values. > Which will be varibles in my code. > > The question is more on the string formatting in the > replace. How do use two %s in one statement? > > i.e.: re.sub('\1 %s \2 %s' % var1 % var2, line) Ok, actually now I can reread your original question and it makes sense :-) I think I'm having an off day for answering questions. I'm glad Alan is with it :-) he gave the answer you need. Kent From Barry.Carroll at psc.com Fri Apr 7 20:56:51 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Fri, 7 Apr 2006 11:56:51 -0700 Subject: [Tutor] Unittest not running all test cases Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C3644@eugsrv400.psc.pscnet.com> Greetings: I'm not certain this is the right forum for this question. If not, please point me to the correct one. I am using the unittest module to test a package our team is writing. I presently have three modules of test cases and a top level module to run the entire suite. The hierarchy looks like this: testsymgen top level testsymc39 61 test cases testsym25 44 test cases testsymc93 0 test cases (so far) testsymgen is a very simple file. Here it is: >>>>> import unittest from testsymc39 import * from testsym25 import * from testsymc93 import * if __name__=='__main__': unittest.main( ) >>>>> Each of the sub-modules runs correctly, but when I run testsymgen, only 99 test cases are executed. Can anyone tell me why this should happen. Is there some sort of limit on the number of test cases that can be run in a batch? Thanks in advance for your help. Regards, Barry Regards, ? Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed From kent37 at tds.net Fri Apr 7 21:42:15 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 07 Apr 2006 15:42:15 -0400 Subject: [Tutor] Unittest not running all test cases In-Reply-To: <2BBAEE949D384D40A2B851287ADB6A432C3644@eugsrv400.psc.pscnet.com> References: <2BBAEE949D384D40A2B851287ADB6A432C3644@eugsrv400.psc.pscnet.com> Message-ID: <4436C097.8080406@tds.net> Carroll, Barry wrote: > Greetings: > > I'm not certain this is the right forum for this question. If not, please point me to the correct one. > > I am using the unittest module to test a package our team is writing. > I presently have three modules of test cases and a top level module to run the entire suite. The hierarchy looks like this: > testsymgen top level > testsymc39 61 test cases > testsym25 44 test cases > testsymc93 0 test cases (so far) > > testsymgen is a very simple file. Here it is: > > import unittest > from testsymc39 import * > from testsym25 import * > from testsymc93 import * > > > if __name__=='__main__': > unittest.main( ) > > Each of the sub-modules runs correctly, but when I run testsymgen, only 99 test cases are executed. Can anyone tell me why this should happen. Is there some sort of limit on the number of test cases that can be run in a batch? I don't think there is a limit like this. I wonder, do you have any name collisions? For example if testsymc39 and testsym25 both contain class TestSym then only the second one will run because it will shadow the name from the first module. If this is the case you need a more sophisticated way of accumulating tests. You might want to look into using nose or one of the other test-discovery frameworks listed here: http://pycheesecake.org/wiki/PythonTestingToolsTaxonomy#UnitTestingTools Kent From khp at pflaesterer.de Fri Apr 7 22:28:28 2006 From: khp at pflaesterer.de (Karl =?iso-8859-1?Q?Pfl=E4sterer?=) Date: Fri, 07 Apr 2006 22:28:28 +0200 Subject: [Tutor] string formatting question In-Reply-To: <20060407181818.43293.qmail@web53713.mail.yahoo.com> (Jerome Jabson's message of "Fri, 7 Apr 2006 11:18:18 -0700 (PDT)") References: <20060407181818.43293.qmail@web53713.mail.yahoo.com> Message-ID: On 7 Apr 2006, jjabson at yahoo.com wrote: > Sorry I didn't make my question clearer. Bascially I > want to replace this line: > > address="64.41.134.60"/> > > With: > > address="64.41.134.60"/> > > So the regex grouping are that I want to keep > portNumber= and tcpORudp= and replace the values. > Which will be varibles in my code. > > The question is more on the string formatting in the > replace. How do use two %s in one statement? > > i.e.: re.sub('\1 %s \2 %s' % var1 % var2, line) You could write it simply like that: Python> s = '' Python> re.sub('".*?"','"%s"',s,2) '' Python> re.sub('".*?"','"%s"',s,2) % ('1000', 'TCP') '' Or you could exploit the fact that you can use a function instead of a simply string as substitution; in that function you can do really complicated things. Karl -- Please do *not* send copies of replies to me. I read the list From ml.cyresse at gmail.com Sat Apr 8 00:11:28 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Sat, 8 Apr 2006 10:11:28 +1200 Subject: [Tutor] Python performance resources & resouce usage hints In-Reply-To: References: <4436A722.4040707@tds.net> Message-ID: Thanks very much all. :) I'll have a crack this afternoon and let you know. Kent - the increase in the queue size for the socket server is to allow for any delay in processing packets; it has a default queue size of 5 and then it starts rejecting packets; more of a safety policy when reducing CPU usage than a direct attempt to reduce CPU usage. Once again, thanks for the input! On 4/8/06, Danny Yoo wrote: > > > On Fri, 7 Apr 2006, Kent Johnson wrote: > > > Hugo Gonz?lez Monteverde wrote: > > > You are not using the optional timeout and blocking which 'get' provides (!) > > > > > > Try setting it and see your CPU usage go down. This will implement > > > blocking, and the queue will be used as soon as data is there. Set block > > > to True and a timeout if you need to use it (looks like you only need > > > blocking) > > > > > > while True: > > > try: > > > data = self.queue.get(True) > > > self.DAO.send_data(data) > > > > I think he will need the timeout too, otherwise the shutdown flag will > > only be checked when there is work which is probably not what he wants. > > > This could be fixed: when setting the 'shutdown' flag, also push a > sentinel piece of data into the queue. That'll wake the thread back up, > and that'll give it the opportunity to process a shutdown. > > The thread here: > > http://mail.python.org/pipermail/tutor/2006-January/044557.html > > has some more examples of this. > > > Hope this helps! > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From Barry.Carroll at psc.com Sat Apr 8 00:34:33 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Fri, 7 Apr 2006 15:34:33 -0700 Subject: [Tutor] Unittest not running all test cases Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C3646@eugsrv400.psc.pscnet.com> Kent: I just rechecked my class names, and there are no duplicates. I was careful to preface all of the classes in testsymc39 with 'C39...', and used 'S25...' in testsym25. Likewise, the classes in each module have names that describe the type of data being tested, so names are unique within each module as well. Is there a maximum length for class names? Some of my class names are pretty long, and only differ in the last few characters. I'd be surprised if that were the case in Python, but I'm short on other ideas. Thanks for your help. Regards, Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed > -----Original Message----- > Date: Fri, 07 Apr 2006 15:42:15 -0400 > From: Kent Johnson > Subject: Re: [Tutor] Unittest not running all test cases > Cc: tutor at python.org > Message-ID: <4436C097.8080406 at tds.net> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > <> > > I don't think there is a limit like this. I wonder, do you have any name > collisions? For example if testsymc39 and testsym25 both contain class > TestSym then only the second one will run because it will shadow the > name from the first module. > > If this is the case you need a more sophisticated way of accumulating > tests. You might want to look into using nose or one of the other > test-discovery frameworks listed here: > http://pycheesecake.org/wiki/PythonTestingToolsTaxonomy#UnitTestingTools > > Kent From ml.cyresse at gmail.com Sat Apr 8 01:34:22 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Sat, 8 Apr 2006 11:34:22 +1200 Subject: [Tutor] Python performance resources & resouce usage hints In-Reply-To: References: <4436A722.4040707@tds.net> Message-ID: Well, thanks very much Kent, Hugo and Danny. I went with the "never-ending blocking queues" and sentinel data approach. When running tests with a continual stream of packets being received 3ms apart, CPU usage peaked at 15%, was usually around 7-9%, and when deployed the packets will separated by seconds rather than milliseconds. Thanks for the assistance, I've now overcome my fear of blocking I/O :). Regards, Lia, Clarke On 4/8/06, Liam Clarke wrote: > Thanks very much all. :) I'll have a crack this afternoon and let you know. > > Kent - the increase in the queue size for the socket server is to > allow for any delay in processing packets; it has a default queue size > of 5 and then it starts rejecting packets; more of a safety policy > when reducing CPU usage than a direct attempt to reduce CPU usage. > > Once again, thanks for the input! > > On 4/8/06, Danny Yoo wrote: > > > > > > On Fri, 7 Apr 2006, Kent Johnson wrote: > > > > > Hugo Gonz?lez Monteverde wrote: > > > > You are not using the optional timeout and blocking which 'get' provides (!) > > > > > > > > Try setting it and see your CPU usage go down. This will implement > > > > blocking, and the queue will be used as soon as data is there. Set block > > > > to True and a timeout if you need to use it (looks like you only need > > > > blocking) > > > > > > > > while True: > > > > try: > > > > data = self.queue.get(True) > > > > self.DAO.send_data(data) > > > > > > I think he will need the timeout too, otherwise the shutdown flag will > > > only be checked when there is work which is probably not what he wants. > > > > > > This could be fixed: when setting the 'shutdown' flag, also push a > > sentinel piece of data into the queue. That'll wake the thread back up, > > and that'll give it the opportunity to process a shutdown. > > > > The thread here: > > > > http://mail.python.org/pipermail/tutor/2006-January/044557.html > > > > has some more examples of this. > > > > > > Hope this helps! > > > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > From intermezzoooh at gmail.com Sat Apr 8 01:36:53 2006 From: intermezzoooh at gmail.com (Jesse) Date: Fri, 7 Apr 2006 17:36:53 -0600 Subject: [Tutor] Beginner question (variables, namespaces...) Message-ID: Why is it that when one variable is assigned a value in terms of another variable, assigning a new value to the first doesn't change the value of the second? This is giving me a huge headache, since I have a bunch of variables defined in terms of one another, and I want to be able to dynamically update them (I did not include the definitions of the functions overstock and roundup, but they work): stock = float(raw_input("Enter stock (in terms of portions: ")) container = float(raw_input("Enter portions per container: ")) price_per_container = float(raw_input("Enter price per container: ")) weekly_quota = float(raw_input("Enter quota (in terms of portions): ")) extra = overstock(stock, weekly_quota) # overstock returns 0 if the first argument is less than the second; otherwise it returns the difference between the first argument and the second. need = weekly_quota - extra buy_containers = roundup(need/container) # roundup rounds a non-integer to the next highest integer buy_portions = buy_containers * container leftover = buy_portions - need cost = price_per_container * buy_containers I would like to write a function that will update the values of the above variables given an increase in only the stock variable. Otherwise I'd have to repeat a bunch of code...:( Jesse -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060407/ef87eacb/attachment.html From dyoo at hkn.eecs.berkeley.edu Sat Apr 8 02:02:54 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 7 Apr 2006 17:02:54 -0700 (PDT) Subject: [Tutor] Beginner question (variables, namespaces...) In-Reply-To: Message-ID: On Fri, 7 Apr 2006, Jesse wrote: > Why is it that when one variable is assigned a value in terms of another > variable, assigning a new value to the first doesn't change the value of > the second? Hi Jesse, If you have a "variable" that depends on the values of other parameters, that's just begging to be represented as a function. Let's look at some of those computations: > stock = float(raw_input("Enter stock (in terms of portions: ")) > container = float(raw_input("Enter portions per container: ")) > price_per_container = float(raw_input("Enter price per container: ")) > weekly_quota = float(raw_input("Enter quota (in terms of portions): ")) > extra = overstock(stock, weekly_quota) > need = weekly_quota - extra > buy_containers = roundup(need/container) # roundup rounds a non-integer to > the next highest integer > buy_portions = buy_containers * container > leftover = buy_portions - need > cost = price_per_container * buy_containers Yeah, rather than code these as explicit variables, I'd strongly recommend rewriting each of these as functions. Concretely: #################################################### def extra(stock, weekly_quota): return overstock(stock, weekly_quota) def need(stock, weekly_quota): return weekly_quota - extra(stock, weekly_quota) def buy_containers(stock, weekly_quota, container): return roundup(need(stock, weekly_quota) - extra(stock, weekly_quota)) ... #################################################### It's a little ugly, but this coding explicitely defines the dependencies between the inputs into our system and the expected outputs. When we look at buy_containers(), we can easily see that any change in the stock, weekly_quote, or container parameters may have some profound affect on the output to buy_containers(). That dependency between input and output is what we try to capture when we write a function. So if you recode your assignment statements as function definitions, you should be better able to handle changes to your input. If we think of the names we use for these concepts, there's something ironic that functions behave better on varying data than variables. Oh well. As an advanced aside: the "equations" that you're writing into Python, unfortunately, aren't treated as real math equations, but as separate, independent assignment statements. I think I know what you want, but Python doesn't provide it out of the box. What I think you want is called "constraint" programming. Such systems do exist. For example: http://www.logilab.org/projects/constraint I can't vouch for the maturity of logilab's "constraint" module; I haven't played with it yet. But if you're interested, you may want to look at the treatment of simple constraint systems in the classic textbook "Structure and Interpretation of Computer Programs": http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-22.html#%_sec_3.3.5 It should be very possible to adapt the material there into Python, although it might take a fair bit of work if you're not familiar with Scheme. Good luck to you! From bgailer at alum.rpi.edu Sat Apr 8 02:09:41 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri, 07 Apr 2006 17:09:41 -0700 Subject: [Tutor] Beginner question (variables, namespaces...) In-Reply-To: References: Message-ID: <4436FF45.5010303@alum.rpi.edu> Jesse wrote: > Why is it that when one variable is assigned a value in terms of > another variable, assigning a new value to the first doesn't change > the value of the second? This is giving me a huge headache, since I > have a bunch of variables defined in terms of one another, and I want > to be able to dynamically update them (I did not include the > definitions of the functions overstock and roundup, but they work): > > stock = float(raw_input("Enter stock (in terms of portions: ")) > container = float(raw_input("Enter portions per container: ")) > price_per_container = float(raw_input("Enter price per container: ")) > weekly_quota = float(raw_input("Enter quota (in terms of portions): ")) > extra = overstock(stock, weekly_quota) # overstock returns 0 if the > first argument is less than the second; otherwise it returns the > > difference between the first argument and the second. > need = weekly_quota - extra > buy_containers = roundup(need/container) # roundup rounds a > non-integer to the next highest integer > buy_portions = buy_containers * container > leftover = buy_portions - need > cost = price_per_container * buy_containers > > I would like to write a function that will update the values of the > above variables given an increase in only the stock variable. > Otherwise I'd have to repeat a bunch of code...:( def recalculate(): global extra, need, buy_containers, buy_portions, leftover, cost extra = overstock(stock, weekly_quota) need = weekly_quota - extra buy_containers = roundup(need/container) buy_portions = buy_containers * container leftover = buy_portions - need cost = price_per_container * buy_containers That's all there is to it. From dyoo at hkn.eecs.berkeley.edu Sat Apr 8 02:09:41 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 7 Apr 2006 17:09:41 -0700 (PDT) Subject: [Tutor] Beginner question (variables, namespaces...) In-Reply-To: Message-ID: > > buy_containers = roundup(need/container) > > > Yeah, rather than code these as explicit variables, I'd strongly recommend > rewriting each of these as functions. Concretely: > > def buy_containers(stock, weekly_quota, container): > return roundup(need(stock, weekly_quota) - extra(stock, weekly_quota)) Gaaa. I don't know where the heck that function came from. *grin* Let me try that again: ######################################################### def buy_containers(stock, weekly_quota, container): return roundup(need(stock, weekly_quota) / container) ######################################################### Sorry; my eyes must have been wandering when I was writing that code. From Barry.Carroll at psc.com Sat Apr 8 02:23:45 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Fri, 7 Apr 2006 17:23:45 -0700 Subject: [Tutor] Unittest not running all test cases Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C3649@eugsrv400.psc.pscnet.com> Kent: > -----Original Message----- > From: Kent Johnson [mailto:kent37 at tds.net] > Sent: Friday, April 07, 2006 3:59 PM > To: Carroll, Barry > Subject: Re: [Tutor] Unittest not running all test cases > > Carroll, Barry wrote: > > Kent: > > > > I just rechecked my class names, and there are no duplicates. I was > > careful to preface all of the classes in testsymc39 with 'C39...', and > > used 'S25...' in testsym25. Likewise, the classes in each module have > > names that describe the type of data being tested, so names are unique > > within each module as well. > > > > Is there a maximum length for class names? Some of my class names are > > pretty long, and only differ in the last few characters. I'd be > > surprised if that were the case in Python, but I'm short on other ideas. > > I don't know of any limits on class names. They are just strings in > dictionaries after all. > > Try running your tests in verbose mode, you should at least be able to > figure out which ones aren't running. Try > > unittest.main(argv=['', '-v']) > > Kent > I tried your suggestion. Lo and behold, all the test cases ran! So I tried the terse mode again. All the test cases STILL ran! So the problem has vanished without a trace. Or a good reason. Having a problem just disappear like that bothers me almost more than the original problem. (It's also a little embarrassing.) =8^( Anyway, thanks for your help. Regards, Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed From billburns at pennswoods.net Sat Apr 8 04:49:14 2006 From: billburns at pennswoods.net (Bill Burns) Date: Fri, 07 Apr 2006 22:49:14 -0400 Subject: [Tutor] Watch and control access to an executable Message-ID: <443724AA.90802@pennswoods.net> Hi Tutors! I have a problem that I've solved using Python, and I want to know if I've done a good job :-) Here's the problem: At my work we have a Windows network. On a network drive lives a program that a couple people need to access (there's a shortcut on each user's Desktop to the executable). The problem is, only *one* person at a time should run the program. For various reasons, it's possible for information to get corrupted if two people are using the program at the same time. Here's the old solution to the problem: Pick-up the phone. Dial Dave's extension. Dave this is Bill, I'm going to use the program. Use the program. Call Dave again and tell him I'm done using the program. And Dave does the same for me. Putting it mildly - this is a less than ideal way to run software ;-) Now here's my solution: 1. Create a program let's call it 'myProg' that spawns 'otherProg'. 2. 'myProg' will utilize a config file. 3. When 'myProg' is started it looks in the config file to see if 'otherProg' is running. 4. If 'otherProg' is not running, start it and write to the config file that 'otherProg' is running (also write who is running it). 5. 'myProg' continues to run on the user's computer, continuously checking the PID (of 'otherProg') to see if the process is still alive. 6. When we don't find the PID anymore, write to the config file that 'otherProg' isn't running. 7. Shutdown 'myProg'. Now in step #3 above - if 'myProg' reads the config file and finds that the 'otherProg' is currently running, the user is warned that 'The program is currently in use by !' And 'otherProg' is not started. Couple of other things..... 1. I'm taking 'myProg' and creating a single-file executable using py2exe. 2. 'myProg.exe' and the config file live on the network in the same directory as 'otherProg'. 3. User's have a shortcut on the Desktop to 'myProg.exe' instead of 'otherProg'. BTW, I've never stopped to consider if there was a simple 'Windows networking / permissions' type solution to the problem. I just went straight to Python :-) Here's my code. I'd appreciate any critiques! Thanks, Bill import time import os import sys import getpass from ConfigParser import ConfigParser import win32pdhutil import win32con import win32api CONFIG_FILE = 'WatchProc.ini' # Is there a better way to deal with this # default config file data? defaultConfigData = \ """ [Process] proc = [Current User] user = [Executable] exe = [Process Status] running = [Shutdown Status] ok = """ class WatchProc: def __init__(self): self.config = Config() self.user = getpass.getuser() self.checkConfig() def checkConfig(self): """ Check the config file and see if a process is listed. If nothing is listed throw an error, else do checkStatus(). """ proc = self.config.getConfig('Process', 'proc') if proc == '': self.configFileError() else: self.checkStatus() def checkStatus(self): """ Check the config file to see if the process is running or not. If running throw an error, else start the app. """ status = self.config.getConfig('Process Status', 'running') if status == 'True': # App is in use. self.usageError() elif status == 'False': # App not in use. self.startApp() else: # Config file is not setup properly. self.configFileError() def startApp(self): """ Write the user's name to the config file. Start the executable. Then monitor the process. """ self.config.setConfig('Current User', 'user', self.user) self.startExe() time.sleep(1) self.monitorProcess() def monitorProcess(self): """ Get the process name from the config file then continuously check to see if the process is running. When the process dies, call cleanup(). """ procname = self.config.getConfig('Process', 'proc') self.config.setConfig('Shutdown Status', 'ok', False) CHECK = True while CHECK: try: pid = \ win32pdhutil.FindPerformanceAttributesByName(procname) time.sleep(.5) except: # App has stopped running. CHECK = False self.cleanup() def startExe(self): """ Grab the name of the executable to start. Write to the config file that we're running. Spawn. """ exe = self.config.getConfig('Executable', 'exe') self.config.setConfig('Process Status', 'running', True) os.spawnv(os.P_NOWAIT, exe, []) def cleanup(self): """ Set the config file to the proper values (for a clean shutdown) and then exit. """ self.config.setConfig('Shutdown Status', 'ok', True) self.config.setConfig('Process Status', 'running', False) self.config.setConfig('Current User', 'user', '') sys.exit() def configFileError(self): """ Error message that gets called when a value in the config file is missing. """ errMsg = 'The configuration file is not setup properly!' win32api.MessageBox(0, errMsg, 'Config File Error', win32con.MB_ICONEXCLAMATION) def usageError(self): """ Error message that gets called when somebody else is currently running the "watched" program. """ user = self.config.getConfig('Current User', 'user') errMsg = 'The program is currently in use by %s!' % (user) win32api.MessageBox(0, errMsg, 'Start Program Error', win32con.MB_ICONEXCLAMATION) class Config: def __init__(self): # Check to see if the config file exists, # if not create one. if not os.path.exists(CONFIG_FILE): self.writeDefaultConfig() self.cp = ConfigParser() self.cp.read(CONFIG_FILE) def setConfig(self, section, option, value): """ Method used to set config options and values in the ini file. """ self.cp.set(section, option, value) f = open(CONFIG_FILE, 'w') self.cp.write(f) f.close() def getConfig(self, section, option): """ Returns a value from the config file. """ return self.cp.get(section, option) def writeDefaultConfig(self): """ Writes the 'default' config file. Will only get called if one does not exist. """ f = open(CONFIG_FILE, "w") f.write(defaultConfigData) f.close() if __name__ == '__main__': watcher = WatchProc() From dyoo at hkn.eecs.berkeley.edu Sat Apr 8 05:09:18 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 7 Apr 2006 20:09:18 -0700 (PDT) Subject: [Tutor] Beginner question (variables, namespaces...) (fwd) Message-ID: ---------- Forwarded message ---------- Date: Fri, 7 Apr 2006 21:05:33 -0600 From: Jesse To: Danny Yoo Subject: Re: [Tutor] Beginner question (variables, namespaces...) I tried redefining the "higher-order" variables as functions, but it didn't quite work. Here's a simplified example: var1 = 2 def timestwo(x): return x*2 var2 = timestwo(var1) print var1, var2 var1 = 3 print var1, var2 This results in the output: 2, 4 3,4 ..which is not what I'm aiming for. Maybe I'll have to follow Bob's advice and just store all of the variable assignments in a function, and then call the function every time I change one of the variables (based on user input). I could still leave the higher-order variables as functions as per your advice, but that alone doesn't seem to do the trick. Unless I've missed something. Jesse From alan.gauld at freenet.co.uk Sat Apr 8 09:52:47 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 8 Apr 2006 08:52:47 +0100 Subject: [Tutor] Beginner question (variables, namespaces...) References: Message-ID: <001801c65ae1$6db09bb0$0b01a8c0@xp> Others have provided workarounds I'll attempt to answer the rationale part... > Why is it that when one variable is assigned a value in terms of another > variable, assigning a new value to the first doesn't change the value of > the > second? Python variables are just names that refer to a value. The value can be any kind of object that python recognises but it is a single value. When you assign an expression to a variable Python evaluates the current value of the expression before assigning it, it does not understand the concept of an expression as a value in its own right. The only way to store an expression is to place it in a function as the others have shown. The function can then be cxalled as needed, but it must be called explicitly, you cannot call it by implication when one of the terms of the expression changes. There is a way to fake this a little using properties of a class. If you create a class that has all your variables as properties, then you can write get/set methods for those properties such that when changed they automatically update the other properties, thus rippling the changes through your system. But using properties like this is a slightly esoteric technique in Python. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Sat Apr 8 13:51:33 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 08 Apr 2006 07:51:33 -0400 Subject: [Tutor] Beginner question (variables, namespaces...) (fwd) In-Reply-To: References: Message-ID: <4437A3C5.1020200@tds.net> > From: Jesse > > I tried redefining the "higher-order" variables as functions, but it didn't > quite work. Here's a simplified example: > > > var1 = 2 > > def timestwo(x): > return x*2 > > > var2 = timestwo(var1) > print var1, var2 > var1 = 3 > print var1, var2 > > This results in the output: > 2, 4 > 3,4 You still have to call the function whenever you need the value. print var1, timestwo(var1) var1 = 3 print var1, timestwo(var1) > > ..which is not what I'm aiming for. Maybe I'll have to follow Bob's advice > and just store all of the variable assignments in a function, and then call > the function every time I change one of the variables (based on user input). > I could still leave the higher-order variables as functions as per your > advice, but that alone doesn't seem to do the trick. Unless I've missed > something. Danny's suggestion of using class properties is a good one, it allows you to automate the recalculation of the variables, and also protect against directly assigning one of the calculated values. Here is a class that has two attributes, val and val2. val can be assigned normally. val2 is read-only and always equal to twice val. Whenever a new value is assigned to val, the internal _recalculate() method is called. This is slightly more complex than needed for this example (_set_val()) could calculate val2 directly) but it extends easily to multiple settable and calculated values. The only problem with this approach is that it is not really beginner material, you need some understanding of classes and properties. I don't know of any beginner references for properties but you could try this: http://users.rcn.com/python/download/Descriptor.htm#properties Anyway here is the code: ##################### class AutoCompute(object): def __init__(self, val): self.val = val # Create a property named val # Setting val triggers recomputation def _set_val(self, val): self._val = val self._recompute() def _get_val(self): return self._val val = property(_get_val, _set_val) # Create a read-only property named val2 def _get_val2(self): return self._val2 val2 = property(_get_val2) def _recompute(self): self._val2 = self._val * 2 ac = AutoCompute(3) print ac.val, ac.val2 # Assigning to ac.val changes ac.val2 also ac.val = 4 print ac.val, ac.val2 # This raises AttributeError, val2 is read-only ac.val2 = 5 ################################### When run, the output is 3 6 4 8 Traceback (most recent call last): File "F:\Tutor\ComputedProperty.py", line 33, in ? ac.val2 = 5 AttributeError: can't set attribute From bgibson at us.ibm.com Sat Apr 8 14:01:47 2006 From: bgibson at us.ibm.com (Bob Gibson) Date: Sat, 8 Apr 2006 06:01:47 -0600 Subject: [Tutor] Bob Gibson is out of the office. Message-ID: I will be out of the office starting 03/31/2006 and will not return until 04/10/2006. I will respond to your message when I return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060408/494af4c3/attachment.html From alan.gauld at freenet.co.uk Sat Apr 8 15:10:31 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 8 Apr 2006 14:10:31 +0100 Subject: [Tutor] Watch and control access to an executable References: <443724AA.90802@pennswoods.net> Message-ID: <002d01c65b0d$d0cf8040$0b01a8c0@xp> > Desktop to the executable). The problem is, only *one* person at a time > should run the program. > Now here's my solution: > 1. Create a program let's call it 'myProg' that spawns 'otherProg'. > 2. 'myProg' will utilize a config file. > 3. When 'myProg' is started it looks in the config file to see if > 'otherProg' is running. The usual way of doing this is simply to create an empty file when the program starts and delete it when the program closes In python: ############## # File : exRun.py ''' usage python exRun.py foo.exe prevents more than one copy of the guarded program running ''' import os, sys if len(sys.argv) != 2: print "Usage: python exRun.py " sys.exit() prog = sys.argv[1] fname = prog+'running.dat' try: open(fname,'w').close() # create an empty file. os.system(prog) os.remove(fname) except IOError: print prog, 'is already running, try again later' sys.exit() ################ > 4. If 'otherProg' is not running, start it and write to the config file > that 'otherProg' is running (also write who is running it). > 5. 'myProg' continues to run on the user's computer, continuously > checking the PID (of 'otherProg') to see if the process is still alive. > 6. When we don't find the PID anymore, write to the config file that > 'otherProg' isn't running. > 7. Shutdown 'myProg'. The design above will work too of course but uses more CPU cycles and may be slightly harder to fix if the machine crashes while the app is running sincve the open config file could be corrupted. > Now in step #3 above - if 'myProg' reads the config file and finds that > the 'otherProg' is currently running, the user is warned that 'The > program is currently in use by !' And > 'otherProg' is not started. The current user name can be obtained from getpass.getuser() if you need it. > Couple of other things..... > 1. I'm taking 'myProg' and creating a single-file executable using py2exe. Thats fair enough > 2. 'myProg.exe' and the config file live on the network in the same > directory as 'otherProg'. There's no real need for that. My version usually lives in a common area since it can be used to control multiple apps, and it usually writes its file into a semi-hidden folder to avoid unscrupulous users deleting the file!. > 3. User's have a shortcut on the Desktop to 'myProg.exe' instead of > 'otherProg'. Yes, or in my case several shortcuts with the app names hard coded in the shortcut. > BTW, I've never stopped to consider if there was a simple 'Windows > networking / permissions' type solution to the problem. I just went > straight to Python :-) You can do it all using DOS style BAT files if you use my approach. > Here's my code. I'd appreciate any critiques! Its longer than mine :-) Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From andre.roberge at gmail.com Sat Apr 8 15:33:25 2006 From: andre.roberge at gmail.com (Andre Roberge) Date: Sat, 8 Apr 2006 10:33:25 -0300 Subject: [Tutor] Watch and control access to an executable In-Reply-To: <002d01c65b0d$d0cf8040$0b01a8c0@xp> References: <443724AA.90802@pennswoods.net> <002d01c65b0d$d0cf8040$0b01a8c0@xp> Message-ID: <7528bcdd0604080633t63f3f6e8gbb832f496b4be352@mail.gmail.com> On 4/8/06, Alan Gauld wrote: > > Desktop to the executable). The problem is, only *one* person at a time > > should run the program. [snip] > > The usual way of doing this is simply to create an empty file > when the program starts and delete it when the program closes > In python: > Couldn't this approach cause problems if the Python program crashes, leaving behind the empty file? However, there is a Cookbook solution that does, I believe, that what the original poster asked: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/67663 It is actually so short that I can even reproduce it below. ========= from win32event import CreateMutex from win32api import GetLastError from winerror import ERROR_ALREADY_EXISTS from sys import exit handle = CreateMutex ( None, 1, 'A unique mutex name' ) if GetLastError ( ) == ERROR_ALREADY_EXISTS: # take appropriate action if this is the second # instance of this script; for example, print 'Oh! dear, I exist already.' exit ( 1 ) ============ A detailed explanation (of a slightly modified version) can be found in the second edition of the Python Cookbook [Recipe 9.9]. Andr? From alan.gauld at freenet.co.uk Sat Apr 8 16:51:53 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 8 Apr 2006 15:51:53 +0100 Subject: [Tutor] Watch and control access to an executable References: <443724AA.90802@pennswoods.net> <002d01c65b0d$d0cf8040$0b01a8c0@xp> <7528bcdd0604080633t63f3f6e8gbb832f496b4be352@mail.gmail.com> Message-ID: <003101c65b1b$f9dc5950$0b01a8c0@xp> > > The usual way of doing this is simply to create an empty file > > when the program starts and delete it when the program closes > Couldn't this approach cause problems if the Python program crashes, > leaving behind the empty file? Yes, but its very easy for the administrator to delete the rogue file. This is how most Unix tools do it, using /tmp as the storage folder - /tmp can be purged at each reboot so ensuring a clean startup. This is simple to manage and better than writing entries to files which can get corrupted - that's much more difficult to manage. (This technique is also a mainstay of Mainframe computing and has been for over 40 years! :-) > However, there is a Cookbook solution that does, > I believe, that what the original poster asked: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/67663 The Mutex version is nice, I haven't seen that before. Although it will only work on Windows but since that's what the OP uses, it's not a problem. Alan G. From billburns at pennswoods.net Sat Apr 8 18:02:41 2006 From: billburns at pennswoods.net (Bill Burns) Date: Sat, 08 Apr 2006 12:02:41 -0400 Subject: [Tutor] Watch and control access to an executable In-Reply-To: <002d01c65b0d$d0cf8040$0b01a8c0@xp> References: <443724AA.90802@pennswoods.net> <002d01c65b0d$d0cf8040$0b01a8c0@xp> Message-ID: <4437DEA1.4000707@pennswoods.net> [Bill] >> Desktop to the executable). The problem is, only *one* person at a time >> should run the program. > [Alan] > The usual way of doing this is simply to create an empty file > when the program starts and delete it when the program closes > In python: > > ############## > # File : exRun.py > ''' usage python exRun.py foo.exe > > prevents more than one copy of the guarded program running > ''' > > import os, sys > > if len(sys.argv) != 2: > print "Usage: python exRun.py " > sys.exit() > > prog = sys.argv[1] > fname = prog+'running.dat' > try: > open(fname,'w').close() # create an empty file. > os.system(prog) > os.remove(fname) > except IOError: > print prog, 'is already running, try again later' > sys.exit() > ################ Alan, Thank you for the code above . I'll take a look at it. Much shorter than my approach :-) [Bill] >> 4. If 'otherProg' is not running, start it and write to the config file >> that 'otherProg' is running (also write who is running it). >> 5. 'myProg' continues to run on the user's computer, continuously >> checking the PID (of 'otherProg') to see if the process is still alive. >> 6. When we don't find the PID anymore, write to the config file that >> 'otherProg' isn't running. >> 7. Shutdown 'myProg'. [Alan] > The design above will work too of course but uses more CPU cycles > and may be slightly harder to fix if the machine crashes while the app > is running sincve the open config file could be corrupted. My first attempt at continuously checking the PID was using a lot of CPU time. Then I added a sleep(.5) in my loop and the CPU % dropped to about 0% (at least according to Task Manager). [Bill] >> Now in step #3 above - if 'myProg' reads the config file and finds that >> the 'otherProg' is currently running, the user is warned that 'The >> program is currently in use by !' And >> 'otherProg' is not started. [Alan] > The current user name can be obtained from getpass.getuser() if you need > it. Yeah, my code uses that too. [Bill] >> 2. 'myProg.exe' and the config file live on the network in the same >> directory as 'otherProg'. [Alan] > There's no real need for that. My version usually lives in a common > area since it can be used to control multiple apps, and it usually writes > its file into a semi-hidden folder to avoid unscrupulous users deleting > the file!. I think I was just trying to make it easy for my program to find the program to start (since it'll look in the current directory first). I didn't want to hard-code any paths. But it looks like with your approach, I just issue the path to the executable on the command line and be done with it. Regarding the config file deletion - I've set the permissions on the .ini so that users can read & write to the file, but not delete it. But certainly a user with Admin privs could still delete it. Also , if my program doesn't find the .ini file - it creates a new one (although it must be setup again). [Bill] >> BTW, I've never stopped to consider if there was a simple 'Windows >> networking / permissions' type solution to the problem. I just went >> straight to Python :-) [Alan] > You can do it all using DOS style BAT files if you use my approach. I just knew someone would come up with an easier way :-) Thanks again, Alan! I'll play around with the code you posted. Bill From billburns at pennswoods.net Sat Apr 8 18:08:42 2006 From: billburns at pennswoods.net (Bill Burns) Date: Sat, 08 Apr 2006 12:08:42 -0400 Subject: [Tutor] Watch and control access to an executable In-Reply-To: <7528bcdd0604080633t63f3f6e8gbb832f496b4be352@mail.gmail.com> References: <443724AA.90802@pennswoods.net> <002d01c65b0d$d0cf8040$0b01a8c0@xp> <7528bcdd0604080633t63f3f6e8gbb832f496b4be352@mail.gmail.com> Message-ID: <4437E00A.2080005@pennswoods.net> [Bill] >>>Desktop to the executable). The problem is, only *one* person at a time >>>should run the program. > [Snip some good advise about file problems (that I'll look in to)] [Andr?] > However, there is a Cookbook solution that does, I believe, that what > the original poster asked: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/67663 > > It is actually so short that I can even reproduce it below. > ========= > from win32event import CreateMutex > from win32api import GetLastError > from winerror import ERROR_ALREADY_EXISTS > from sys import exit > > handle = CreateMutex ( None, 1, 'A unique mutex name' ) > > if GetLastError ( ) == ERROR_ALREADY_EXISTS: > # take appropriate action if this is the second > # instance of this script; for example, > print 'Oh! dear, I exist already.' > exit ( 1 ) > ============ > A detailed explanation (of a slightly modified version) can be found > in the second edition of the Python Cookbook [Recipe 9.9]. Andr?, Thanks for the pointer to this recipe! If I'm not mistaken (and I certainly could be) I believe this recipe is used to control instances of an already running *script*. While I'm trying to control a completely different executable (program) written by someone else. Maybe I'm reading the recipe wrong?? I'll take a better look at it and see if it will work for my situation. Thanks for the reply!! Bill From dyoo at hkn.eecs.berkeley.edu Sat Apr 8 18:14:02 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 8 Apr 2006 09:14:02 -0700 (PDT) Subject: [Tutor] Beginner question (variables, namespaces...) (fwd) In-Reply-To: Message-ID: > I tried redefining the "higher-order" variables as functions, but it > didn't quite work. Here's a simplified example: > > > var1 = 2 > > def timestwo(x): > return x*2 > > var2 = timestwo(var1) > print var1, var2 > var1 = 3 > print var1, var2 Try: ###### print 2, timestwo(2) print 3, timestwo(3) ###### Alternatively, try: ###### var1 = 2 print var1, timestwo(var1) var1 = 3 print var1, timestwo(var1) ###### What do you expect to see? > ..which is not what I'm aiming for. Maybe I'll have to follow Bob's > advice and just store all of the variable assignments in a function, and > then call the function every time I change one of the variables (based > on user input). I could still leave the higher-order variables as > functions as per your advice, but that alone doesn't seem to do the > trick. Unless I've missed something. You're missing something. *wink* Play with this a little more. It's something basic in Python, and you'll want to get this squared away so it doesn't cause you grief later. The model you have about how variables behave in Python is slightly off still: I think you're still thinking of them like math equations. But Python's model for assigning variable names to values don't work like equality: it's more of a "this box now contains the value described by the right hand side at this particular time." So if we see: a = 3 b = 4 a = a + b we can model this as: [a : 3] (after stmt: a = 3) [a : 3, b : 4] (after stmt: b = 4) [a : 7, b : 4] (after stmt: a = a + b) where we keep a list of names and their current values. (I'm just using an ad-hoc notation for the stuff in the brackets.) Assignment erases the old value and replaces it with a new one as we flow through our program. From dyoo at hkn.eecs.berkeley.edu Sat Apr 8 18:21:00 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 8 Apr 2006 09:21:00 -0700 (PDT) Subject: [Tutor] Beginner question (variables, namespaces...) (fwd) In-Reply-To: <4437A3C5.1020200@tds.net> Message-ID: > > ..which is not what I'm aiming for. Maybe I'll have to follow Bob's > > advice and just store all of the variable assignments in a function, > > and then call the function every time I change one of the variables > > (based on user input). I could still leave the higher-order variables > > as functions as per your advice, but that alone doesn't seem to do the > > trick. Unless I've missed something. > > Danny's suggestion of using class properties is a good one, it allows > you to automate the recalculation of the variables, and also protect > against directly assigning one of the calculated values. Just wanted to clarify that this is not my suggestion: Alan proposed this. But I think we should steer away a little away from full-fledged classes at the moment. The "professional" solution would be to do this, but I'm not sure how appropriate it is for Jesse to do this yet. Jesse is still confused about how variables work. In which case, suggesting him to look at classes will just make things worse. *grin* From alan.gauld at freenet.co.uk Sat Apr 8 18:44:48 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 8 Apr 2006 17:44:48 +0100 Subject: [Tutor] Watch and control access to an executable References: <443724AA.90802@pennswoods.net> <002d01c65b0d$d0cf8040$0b01a8c0@xp> <7528bcdd0604080633t63f3f6e8gbb832f496b4be352@mail.gmail.com> <4437E00A.2080005@pennswoods.net> Message-ID: <003701c65b2b$c0352eb0$0b01a8c0@xp> > If I'm not mistaken (and I certainly could be) I believe this recipe is > used to control instances of an already running *script*. While I'm > trying to control a completely different executable (program) written by > someone else. Nope, its si8mply creating an arbitrary Mutex, which is like a flag in the OS itself. If the flag gets set OK - no errors - then you can go ahead and launch your app, if theres an error the most likely reason is that the app is already running. Its exactly the same principle as using a blank file but tidier since theres no file to delete(*) if things go wrong - although you might need to reboot since I',m not sure how to delete a Mutex created by another process, in fact I've only used a Mutex within a single multi-threading app, but in principle theres no reason not to use it this way too... (*) Having the file has advantages since the administrator can easily check with explorer to see if the app is in use, or manually create one to block access to the app temporarily, but its a minimal advantage I suspect. Alan g. From billburns at pennswoods.net Sat Apr 8 19:02:42 2006 From: billburns at pennswoods.net (Bill Burns) Date: Sat, 08 Apr 2006 13:02:42 -0400 Subject: [Tutor] Watch and control access to an executable In-Reply-To: <003701c65b2b$c0352eb0$0b01a8c0@xp> References: <443724AA.90802@pennswoods.net> <002d01c65b0d$d0cf8040$0b01a8c0@xp> <7528bcdd0604080633t63f3f6e8gbb832f496b4be352@mail.gmail.com> <4437E00A.2080005@pennswoods.net> <003701c65b2b$c0352eb0$0b01a8c0@xp> Message-ID: <4437ECB2.5050900@pennswoods.net> [Bill] >> If I'm not mistaken (and I certainly could be) I believe this recipe >> is used to control instances of an already running *script*. While I'm >> trying to control a completely different executable (program) written >> by someone else. [Alan] > Nope, its si8mply creating an arbitrary Mutex, which is like a flag in > the OS itself. If the flag gets set OK - no errors - then you can go > ahead and launch your app, if theres an error the most likely reason is > that the app is already running. > > Its exactly the same principle as using a blank file but tidier since > theres no file to delete(*) if things go wrong - although you might need > to reboot since I',m not sure how to delete a Mutex created by another > process, in fact I've only used a Mutex within a single multi-threading > app, but in principle theres no reason not to use it this way too... > > (*) Having the file has advantages since the administrator can easily > check with explorer to see if the app is in use, or manually create one > to block access to the app temporarily, but its a minimal advantage I > suspect. OK. I understand a little better and will definitely look into this!! The description of the recipe states: "A script can use this code to determine whether another instance of itself is already in execution. 32-bit MSW only." So I assumed it meant - you could use the recipe in your own scripts to determine if the user was trying to start multiple instances of your program. My apologies to Andr?!!! Thanks for the explanation! Bill From payal-python at scriptkitchen.com Mon Apr 10 15:33:42 2006 From: payal-python at scriptkitchen.com (Payal Rathod) Date: Mon, 10 Apr 2006 09:33:42 -0400 Subject: [Tutor] failing to learn python Message-ID: <20060410133342.GA7045@tranquility.scriptkitchen.com> Hi, I am trying to learn Python seriously for almost 2 months but have not gotten far at all. Infact, it seems I have not understood even the basic concepts itself. I know some shell, sed and awk programming. I have tried reading Learning Python - Mark Lutz Think C Spy A byte of Python Non-Programmers Tutorial For Python etc. But I have not got anything from them. I am feeling that they are superficial and do not touch real life problems. Also, not enough examples are provided which can help newbies like me. Can anyone help me, it is pretty pretty frustating thing for last couple of months? With warm regards, -Payal From kent37 at tds.net Mon Apr 10 16:05:45 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 10 Apr 2006 10:05:45 -0400 Subject: [Tutor] failing to learn python In-Reply-To: <20060410133342.GA7045@tranquility.scriptkitchen.com> References: <20060410133342.GA7045@tranquility.scriptkitchen.com> Message-ID: <443A6639.1050703@tds.net> Payal Rathod wrote: > Hi, > I am trying to learn Python seriously for almost 2 months but have not > gotten far at all. Infact, it seems I have not understood even the basic > concepts itself. I know some shell, sed and awk programming. > I have tried reading Learning Python - Mark Lutz > Think C Spy > A byte of Python > Non-Programmers Tutorial For Python > etc. > But I have not got anything from them. I am feeling that they are > superficial and do not touch real life problems. Also, not enough > examples are provided which can help newbies like me. Hi Payal, Beginner's material teaches the basics of the language. These are the building blocks you will use to solve your problems. You need to understand the basics like loops, functions, lists and dictionaries to solve most real-world problems. When you have questions about basic concepts you can ask for help on this list. You might like to look at "Python Programming for the absolute beginner". It is oriented to beginners and has many examples and exercises. http://premierpressbooks.com/ptr_detail.cfm?group=Programming&subcat=Other%20Programming&isbn=1%2D59863%2D112%2D8 What kind of real life problems are you interested in? You might like "Beginning Python", it has several real-life projects. http://apress.com/book/bookDisplay.html?bID=10013 When you have questions about basic concepts you can ask for help on this list. We do best with questions that are very specific. From payal-python at scriptkitchen.com Mon Apr 10 18:52:00 2006 From: payal-python at scriptkitchen.com (Payal Rathod) Date: Mon, 10 Apr 2006 12:52:00 -0400 Subject: [Tutor] failing to learn python In-Reply-To: <443A6639.1050703@tds.net> References: <20060410133342.GA7045@tranquility.scriptkitchen.com> <443A6639.1050703@tds.net> Message-ID: <20060410165200.GA15376@tranquility.scriptkitchen.com> On Mon, Apr 10, 2006 at 10:05:45AM -0400, Kent Johnson wrote: > You might like to look at "Python Programming for the absolute > beginner". It is oriented to beginners and has many examples and > exercises. I might not be able to afford another book, due to high dollar-to-ruppee rate. > What kind of real life problems are you interested in? You might like I am a parttime sys admin so I want system admin problem which usually I do through shell scripts like parsing logs, generating reports, greping with regexes etc. The only thing I don't want is silly problems like generate fibonnacci series, add numbers frm 0-n etc. non required silly stuff. With warm regards, -Payal From bgailer at alum.rpi.edu Mon Apr 10 19:20:57 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon, 10 Apr 2006 10:20:57 -0700 Subject: [Tutor] failing to learn python In-Reply-To: <20060410165200.GA15376@tranquility.scriptkitchen.com> References: <20060410133342.GA7045@tranquility.scriptkitchen.com> <443A6639.1050703@tds.net> <20060410165200.GA15376@tranquility.scriptkitchen.com> Message-ID: <443A93F9.8050103@alum.rpi.edu> Payal Rathod wrote: > On Mon, Apr 10, 2006 at 10:05:45AM -0400, Kent Johnson wrote: > >> You might like to look at "Python Programming for the absolute >> beginner". It is oriented to beginners and has many examples and >> exercises. >> > > I might not be able to afford another book, due to high dollar-to-ruppee > rate. > > >> What kind of real life problems are you interested in? You might like >> > > I am a parttime sys admin so I want system admin problem which usually I > do through shell scripts like parsing logs, generating reports, greping > with regexes etc. > The only thing I don't want is silly problems like generate fibonnacci > series, add numbers frm 0-n etc. non required silly stuff. When I hear the word "silly" I assume that you are comfortable with programming in Python, and do not need the examples that are useful to beginners, and want access to libraries of code for doing the tasks you described. So I suggest you look at Python's remarkable set of modules. In the docs you'll find Global Module Index. Start with re for regular expressions, glob & shutil for some file management, os for more file and process management. Some of these have some example code. Select ONE task of interest to you, make your best stab at writing a Python program using the module, then come back with the program and tell us how we can help you with it. If my assumption is inaccurate, and you do need help with the fundamentals of Python, then I suggest you tackle some of the assignments in the references you have *as a way of becoming comfortable with Python*, then tackle the modules I mentioned. Someone else on this list may point you to online learning resources that will meet your need for more information at low-to-no cost. HTH From kent37 at tds.net Mon Apr 10 19:22:19 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 10 Apr 2006 13:22:19 -0400 Subject: [Tutor] failing to learn python In-Reply-To: <20060410165200.GA15376@tranquility.scriptkitchen.com> References: <20060410133342.GA7045@tranquility.scriptkitchen.com> <443A6639.1050703@tds.net> <20060410165200.GA15376@tranquility.scriptkitchen.com> Message-ID: <443A944B.1070304@tds.net> Payal Rathod wrote: >> What kind of real life problems are you interested in? You might like > > I am a parttime sys admin so I want system admin problem which usually I > do through shell scripts like parsing logs, generating reports, greping > with regexes etc. > The only thing I don't want is silly problems like generate fibonnacci > series, add numbers frm 0-n etc. non required silly stuff. Take a look at the Python Cookbook: http://aspn.activestate.com/ASPN/Cookbook/Python Dive into Python is not targeted at beginners but it is available online and does have real-world examples: http://diveintopython.org/ Kent From gslindstrom at gmail.com Mon Apr 10 21:19:08 2006 From: gslindstrom at gmail.com (Greg Lindstrom) Date: Mon, 10 Apr 2006 14:19:08 -0500 Subject: [Tutor] Decorators Message-ID: <57aa55060604101219t242c9fe9p142eecb0e9829502@mail.gmail.com> Hello- For some reason I have decided to learn about decorators; I heard them talked up at Pycon the past two years and want to know what all the fuss is about. I might even use them in my code :-) My problem, and this is after reading PEP 318 and other items found when I "Googled" for decorators, is that I can't figure out the practical use for them. This surely means that I do not understand the concept because Python does not waste my time or energy. Can any of you gurus either explain what all the excitement is about or point me to examples of how/why I would want to use decorators? Thanks for your attention... -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060410/39ee66c1/attachment.htm From kent37 at tds.net Mon Apr 10 21:44:21 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 10 Apr 2006 15:44:21 -0400 Subject: [Tutor] Decorators In-Reply-To: <57aa55060604101219t242c9fe9p142eecb0e9829502@mail.gmail.com> References: <57aa55060604101219t242c9fe9p142eecb0e9829502@mail.gmail.com> Message-ID: <443AB595.8090804@tds.net> Greg Lindstrom wrote: > Hello- > > For some reason I have decided to learn about decorators; I heard them > talked up at Pycon the past two years and want to know what all the > fuss is about. I might even use them in my code :-) > > My problem, and this is after reading PEP 318 and other items found when > I "Googled" for decorators, is that I can't figure out the practical use > for them. This surely means that I do not understand the concept > because Python does not waste my time or energy. Can any of you gurus > either explain what all the excitement is about or point me to examples > of how/why I would want to use decorators? http://wiki.python.org/moin/PythonDecoratorLibrary From oasf2004 at yahoo.com Tue Apr 11 00:29:23 2006 From: oasf2004 at yahoo.com (Hoffmann) Date: Mon, 10 Apr 2006 15:29:23 -0700 (PDT) Subject: [Tutor] Question about list Message-ID: <20060410222923.4535.qmail@web60020.mail.yahoo.com> Hello, I have a list: list1 = [ 'spam!', 2, ['Ted', 'Rock'] ] and I wrote the script below: i = 0 while i < len(list1): print list1[i] i += 1 Ok. This script will generate as the output each element of the original list, one per line: spam! 2 ['Ted', 'Rock'] I also would like to print the length of each element of that list: spam! = 1 element 2 = 1 element ['Ted', 'Rock'] = 2 elements Could anyone, please, give me some hints? Thanks, Hoffmann __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From john at fouhy.net Tue Apr 11 00:42:42 2006 From: john at fouhy.net (John Fouhy) Date: Tue, 11 Apr 2006 10:42:42 +1200 Subject: [Tutor] Question about list In-Reply-To: <20060410222923.4535.qmail@web60020.mail.yahoo.com> References: <20060410222923.4535.qmail@web60020.mail.yahoo.com> Message-ID: <5e58f2e40604101542t4483c642q46fe41af5f7fd9@mail.gmail.com> Hi Hoffmann, On 11/04/06, Hoffmann wrote: > I have a list: list1 = [ 'spam!', 2, ['Ted', 'Rock'] ] > and I wrote the script below: > > i = 0 > while i < len(list1): > print list1[i] > i += 1 Have you read about "for" loops? The pythonic way of looping through a list is to do something like this: for item in list1: print item This will produce the same output as your code above, but is much nicer to read :-) > I also would like to print the length of each element > of that list: > > spam! = 1 element > 2 = 1 element > ['Ted', 'Rock'] = 2 elements The challenge here is that your list contains a mixture of different types. For example, the len() function will tell us that ['Ted', 'Rock'] has two elements. But it would also tell us that 'spam!' has five elements, and it would raise an exception if we tried to find the length of 2. So you will need to ask python about the type of element you're looking at. One possibility that might work for you is this: for item in list1: if isinstance(item, (tuple, list)): print len(item) else: print 1 May I ask why you're doing this? This feels like a situation where you need to think clearly what your goals are before you go diving towards a solution :-) -- John. From adam.jtm30 at gmail.com Tue Apr 11 00:42:54 2006 From: adam.jtm30 at gmail.com (Adam) Date: Mon, 10 Apr 2006 23:42:54 +0100 Subject: [Tutor] Question about list In-Reply-To: <20060410222923.4535.qmail@web60020.mail.yahoo.com> References: <20060410222923.4535.qmail@web60020.mail.yahoo.com> Message-ID: On 10/04/06, Hoffmann wrote: > Hello, > > I have a list: list1 = [ 'spam!', 2, ['Ted', 'Rock'] > ] > and I wrote the script below: > > i = 0 > while i < len(list1): > print list1[i] > i += 1 > > Ok. This script will generate as the output each > element of the original list, one per line: > > spam! > 2 > ['Ted', 'Rock'] > > I also would like to print the length of each element > of that list: > > spam! = 1 element > 2 = 1 element > ['Ted', 'Rock'] = 2 elements > > Could anyone, please, give me some hints? > Thanks, > Hoffmann instead of just print list1[i] you could use print list1[i], len(list1[i]). I'd like to point out that the usual way to iterate through objects in a list like that would be using a for loop like so. for item in list1: print item, len(item) as you can see this is much easier to understand and is also a lot shorter. HTH. From oasf2004 at yahoo.com Tue Apr 11 00:48:01 2006 From: oasf2004 at yahoo.com (Hoffmann) Date: Mon, 10 Apr 2006 15:48:01 -0700 (PDT) Subject: [Tutor] Question about list In-Reply-To: Message-ID: <20060410224801.54752.qmail@web60021.mail.yahoo.com> --- Adam wrote: > On 10/04/06, Hoffmann wrote: > > Hello, > > > > I have a list: list1 = [ 'spam!', 2, ['Ted', > 'Rock'] > > ] > > and I wrote the script below: > > > > i = 0 > > while i < len(list1): > > print list1[i] > > i += 1 > > > > Ok. This script will generate as the output each > > element of the original list, one per line: > > > > spam! > > 2 > > ['Ted', 'Rock'] > > > > I also would like to print the length of each > element > > of that list: > > > > spam! = 1 element > > 2 = 1 element > > ['Ted', 'Rock'] = 2 elements > > > > Could anyone, please, give me some hints? > > Thanks, > > Hoffmann > > instead of just print list1[i] you could use print > list1[i], len(list1[i]). > I'd like to point out that the usual way to iterate > through objects in > a list like that would be using a for loop like so. > > for item in list1: > print item, len(item) > > as you can see this is much easier to understand and > is also a lot shorter. > HTH. > Hi Adam, In the previous email, I forgot to mention that I have already tried: i = 0 while i < len(list1): print list1[i], len(list1[i]) i += 1 However, I got: soam! 5 1 Traceback (most recent call last): File "list1.py", line 11, in ? print list1[i], len(list1[i]) TypeError: len() of unsized object Could I hear from you again? Hoffmann __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From mwhite3 at ttsd.k12.or.us Tue Apr 11 00:49:45 2006 From: mwhite3 at ttsd.k12.or.us (Matthew White) Date: Mon, 10 Apr 2006 15:49:45 -0700 Subject: [Tutor] Question about list In-Reply-To: <20060410222923.4535.qmail@web60020.mail.yahoo.com> References: <20060410222923.4535.qmail@web60020.mail.yahoo.com> Message-ID: <20060410224945.GB16865@ttsd.k12.or.us> Hi Hoffman, It is often useful to use the "for" construct to process items in a list. e.g.: >>> list1 = [ 'spam!', 2, ['Ted', 'Rock']] >>> for item in list: ... print item spam! 2 ['Ted', 'Rock'] If you pass a list to the len() function, it will return the number of elenents in the list. e.g.: >>> x = ['a', 'b', 'c'] >>> len(x) 3 Now if you pass len() a string it will return the length of a string: >>> y = 'hello' >>> len(y) 5 Given your list below, len() will return what you're looking for when it encounters the third element of the list, but won't for the first and second elements. One way to solve this problem is to use the type() function to figure out if your item is a string or list and use len() as appropriate. I hope this provides enough of a hint. -mtw On Mon, Apr 10, 2006 at 03:29:23PM -0700, Hoffmann (oasf2004 at yahoo.com) wrote: > Hello, > > I have a list: list1 = [ 'spam!', 2, ['Ted', 'Rock'] > ] > and I wrote the script below: > > i = 0 > while i < len(list1): > print list1[i] > i += 1 > > Ok. This script will generate as the output each > element of the original list, one per line: > > spam! > 2 > ['Ted', 'Rock'] > > I also would like to print the length of each element > of that list: > > spam! = 1 element > 2 = 1 element > ['Ted', 'Rock'] = 2 elements > > Could anyone, please, give me some hints? > Thanks, > Hoffmann > > > __________________________________________________ > Do You Yahoo!? > Tired of spam? Yahoo! Mail has the best spam protection around > http://mail.yahoo.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Matthew White - District Systems Administrator Tigard/Tualatin School District 503.431.4128 "The greatest thing in this world is not so much where we are, but in what direction we are moving." -Oliver Wendell Holmes From oasf2004 at yahoo.com Tue Apr 11 00:52:22 2006 From: oasf2004 at yahoo.com (Hoffmann) Date: Mon, 10 Apr 2006 15:52:22 -0700 (PDT) Subject: [Tutor] Question about list In-Reply-To: <5e58f2e40604101542t4483c642q46fe41af5f7fd9@mail.gmail.com> Message-ID: <20060410225222.98520.qmail@web60022.mail.yahoo.com> --- John Fouhy wrote: > Hi Hoffmann, > > On 11/04/06, Hoffmann wrote: > > I have a list: list1 = [ 'spam!', 2, ['Ted', > 'Rock'] ] > > and I wrote the script below: > > > > i = 0 > > while i < len(list1): > > print list1[i] > > i += 1 > > Have you read about "for" loops? The pythonic way > of looping through > a list is to do something like this: > > for item in list1: > print item > > This will produce the same output as your code > above, but is much > nicer to read :-) > > > I also would like to print the length of each > element > > of that list: > > > > spam! = 1 element > > 2 = 1 element > > ['Ted', 'Rock'] = 2 elements > > The challenge here is that your list contains a > mixture of different types. > > For example, the len() function will tell us that > ['Ted', 'Rock'] has > two elements. But it would also tell us that > 'spam!' has five > elements, and it would raise an exception if we > tried to find the > length of 2. > > So you will need to ask python about the type of > element you're > looking at. One possibility that might work for you > is this: > > for item in list1: > if isinstance(item, (tuple, list)): > print len(item) > else: > print 1 > > May I ask why you're doing this? This feels like a > situation where > you need to think clearly what your goals are before > you go diving > towards a solution :-) > > -- > John. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Hi John, This is just a version of a book exercise (How to think like a computer scientist - learning with python, by Downey, Elkner, and Meyers), page 84. Thanks, Hoffmann __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From carroll at tjc.com Tue Apr 11 00:58:05 2006 From: carroll at tjc.com (Terry Carroll) Date: Mon, 10 Apr 2006 15:58:05 -0700 (PDT) Subject: [Tutor] Question about list In-Reply-To: <20060410222923.4535.qmail@web60020.mail.yahoo.com> Message-ID: On Mon, 10 Apr 2006, Hoffmann wrote: > Hello, > > I have a list: list1 = [ 'spam!', 2, ['Ted', 'Rock'] > ] > and I wrote the script below: > > i = 0 > while i < len(list1): > print list1[i] > i += 1 > > Ok. This script will generate as the output each > element of the original list, one per line: > > spam! > 2 > ['Ted', 'Rock'] > > I also would like to print the length of each element > of that list: > > spam! = 1 element > 2 = 1 element > ['Ted', 'Rock'] = 2 elements Well, the length of "spam!" is 5. Lengths of strings express the number of characters. You could check to see if it's a grouping-type of element -- i.e., a list, tuple or set -- but I think your better approach is that, if this is something you need, make all of the elements lists, some of which are single-item lists; for example, instead of: list1 = [ 'spam!', 2, ['Ted', 'Rock'] ] use: list1 = [ ['spam!'], [2], ['Ted', 'Rock'] ] >>> list1 = [ ['spam!'], [2], ['Ted', 'Rock'] ] >>> for item in list1: ... print item, len(item) ... ['spam!'] 1 [2] 1 ['Ted', 'Rock'] 2 If your heart is set on the other approach, though, it can be done: >>> list1 = [ 'spam!', 2, ['Ted', 'Rock'] ] >>> for item in list1: ... if isinstance(item,(list, tuple, set)): ... print item, len(item) ... else: ... print item, 1 ... spam! 1 2 1 ['Ted', 'Rock'] 2 >>> From dyoo at hkn.eecs.berkeley.edu Tue Apr 11 00:44:09 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 10 Apr 2006 15:44:09 -0700 (PDT) Subject: [Tutor] Question about list In-Reply-To: <20060410222923.4535.qmail@web60020.mail.yahoo.com> References: <20060410222923.4535.qmail@web60020.mail.yahoo.com> Message-ID: On Mon, 10 Apr 2006, Hoffmann wrote: > I also would like to print the length of each element > of that list: > > spam! = 1 element > 2 = 1 element > ['Ted', 'Rock'] = 2 elements > > Could anyone, please, give me some hints? The problem is slightly weird, just because you need to clarify what it means to take the length of a non-list. From the examples above, it sounds like we'd like to define the "length" of a non-list to be one. Is that right? Can you write a function called length() that takes a thing and returns the "length" of that thing? ###### def length(something): ... ## fill me in ###### For example, we'd like to see: length("spam!") ==> 1 length(2) ==> 1 length(['Ted', 'Rock']) ==> 2 If you can define this you should be able to use this to solve your problem. When you're defining length(), you may find the built-in function "type()" useful. For example: ###### >>> type(5) >>> type([1, 2, 3]) ###### Good luck! From oasf2004 at yahoo.com Tue Apr 11 01:10:41 2006 From: oasf2004 at yahoo.com (Hoffmann) Date: Mon, 10 Apr 2006 16:10:41 -0700 (PDT) Subject: [Tutor] Question about list In-Reply-To: Message-ID: <20060410231041.93988.qmail@web60014.mail.yahoo.com> --- Terry Carroll wrote: > On Mon, 10 Apr 2006, Hoffmann wrote: > > > Hello, > > > > I have a list: list1 = [ 'spam!', 2, ['Ted', > 'Rock'] > > ] > > and I wrote the script below: > > > > i = 0 > > while i < len(list1): > > print list1[i] > > i += 1 > > > > Ok. This script will generate as the output each > > element of the original list, one per line: > > > > spam! > > 2 > > ['Ted', 'Rock'] > > > > I also would like to print the length of each > element > > of that list: > > > > spam! = 1 element > > 2 = 1 element > > ['Ted', 'Rock'] = 2 elements > > Well, the length of "spam!" is 5. Lengths of > strings express the number > of characters. > > You could check to see if it's a grouping-type of > element -- i.e., a list, > tuple or set -- but I think your better approach is > that, if this is > something you need, make all of the elements lists, > some of which are > single-item lists; for example, instead of: > > list1 = [ 'spam!', 2, ['Ted', 'Rock'] ] > > use: > list1 = [ ['spam!'], [2], ['Ted', 'Rock'] ] > > >>> list1 = [ ['spam!'], [2], ['Ted', 'Rock'] ] > >>> for item in list1: > ... print item, len(item) > ... > ['spam!'] 1 > [2] 1 > ['Ted', 'Rock'] 2 > > If your heart is set on the other approach, though, > it can be done: > > >>> list1 = [ 'spam!', 2, ['Ted', 'Rock'] ] > >>> for item in list1: > ... if isinstance(item,(list, tuple, set)): > ... print item, len(item) > ... else: > ... print item, 1 > ... > spam! 1 > 2 1 > ['Ted', 'Rock'] 2 > >>> > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Hi Terry, Your aproaches (mainly the last one!) answered my question. After following your last approach, I got what I was looking for. Up to the page I am (page 84 of "How to think like a computer scientist - learning with Python"), I didn't see that nice approach. Thanks! Hoffmann __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From oasf2004 at yahoo.com Tue Apr 11 01:17:08 2006 From: oasf2004 at yahoo.com (Hoffmann) Date: Mon, 10 Apr 2006 16:17:08 -0700 (PDT) Subject: [Tutor] Question about list In-Reply-To: <20060410224945.GB16865@ttsd.k12.or.us> Message-ID: <20060410231708.65281.qmail@web60021.mail.yahoo.com> --- Matthew White wrote: > Hi Hoffman, > > It is often useful to use the "for" construct to > process items in a list. > e.g.: > > >>> list1 = [ 'spam!', 2, ['Ted', 'Rock']] > >>> for item in list: > ... print item > spam! > 2 > ['Ted', 'Rock'] > > If you pass a list to the len() function, it will > return the number of > elenents in the list. e.g.: > > >>> x = ['a', 'b', 'c'] > >>> len(x) > 3 > > Now if you pass len() a string it will return the > length of a string: > >>> y = 'hello' > >>> len(y) > 5 > > Given your list below, len() will return what you're > looking for when it > encounters the third element of the list, but won't > for the first and > second elements. One way to solve this problem is > to use the type() > function to figure out if your item is a string or > list and use len() > as appropriate. I hope this provides enough of a > hint. > > -mtw > > > On Mon, Apr 10, 2006 at 03:29:23PM -0700, Hoffmann > (oasf2004 at yahoo.com) wrote: > > Hello, > > > > I have a list: list1 = [ 'spam!', 2, ['Ted', > 'Rock'] > > ] > > and I wrote the script below: > > > > i = 0 > > while i < len(list1): > > print list1[i] > > i += 1 > > > > Ok. This script will generate as the output each > > element of the original list, one per line: > > > > spam! > > 2 > > ['Ted', 'Rock'] > > > > I also would like to print the length of each > element > > of that list: > > > > spam! = 1 element > > 2 = 1 element > > ['Ted', 'Rock'] = 2 elements > > > > Could anyone, please, give me some hints? > > Thanks, > > Hoffmann > > > > > > __________________________________________________ > > Do You Yahoo!? > > Tired of spam? Yahoo! Mail has the best spam > protection around > > http://mail.yahoo.com > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > -- > Matthew White - District Systems Administrator > Tigard/Tualatin School District > 503.431.4128 > > "The greatest thing in this world is not so much > where we are, but in > what direction we are moving." -Oliver Wendell > Holmes > > Hi Matthew, Thanks for the nice information! I am learning a lot with all of the hints you guys are sending to me. Hoffmann __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From dyoo at hkn.eecs.berkeley.edu Tue Apr 11 01:20:37 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 10 Apr 2006 16:20:37 -0700 (PDT) Subject: [Tutor] failing to learn python In-Reply-To: <20060410165200.GA15376@tranquility.scriptkitchen.com> References: <20060410133342.GA7045@tranquility.scriptkitchen.com> <443A6639.1050703@tds.net> <20060410165200.GA15376@tranquility.scriptkitchen.com> Message-ID: > I am a parttime sys admin so I want system admin problem which usually I > do through shell scripts like parsing logs, generating reports, greping > with regexes etc. Hi Payal, You might also find David Mertz's book "Text Processing With Python" to be useful for you: http://gnosis.cx/TPiP/ I agree with the other recommendation on "Dive into Python": it provides a lot of good practical programming knowledge. http://diveintopython.org/ > The only thing I don't want is silly problems like generate fibonnacci > series, add numbers from 0-n etc. non required silly stuff. Just as a counterpoint: some of those silly things aren't useful in their own right, but they're finger exercises to help one really get mastery over the language. Recursion is one of those things that are core concepts, and most Python tutorials try to cover it by talking about factorials. It's very unfortunate that fibonacci numbers are one of the "classical" examples of recursion, since they are useless to most people. But don't discount recursion altogether. We can look at concrete example of recursion that might be more applicable. One common system administration question that pops up every once in a while is: "How do I do [some_action] to every file in my directory?" We can either know magically that os.walk() will do the hard work for us, or we can use a combination of os.listdir() and os.path.isdir(): ############################################# ### pseudocode def my_walk(some_action, dir_or_file): if os.path.isfile(dir_or_file): some_action(dir_or_file) else: for thing in os.listdir(dir_or_file): my_walk(some_action, thing) ############################################# in which there's a specific "base" case for handling regular files, and an "inductive" case for handling directories. Another example of this kind of processing involves things like XML or HTML processing. If we wanted to get all the anchor link elements in an HTML document, how would we do this? We again break it into two cases: one to handle anchor elements, and another to handle anything else: ############################################## ## Pseudocode def get_anchors(element): if element is an anchor: return [element] else: anchors = [] for child in element.children: anchors.extend(get_anchors(child)) return anchors ############################################## We're in a slightly different domain, but if we look at this with a critical eye, we should see that the code structure is similar to the directory-walking example. There's a case for handling really simple problems, and another case for handling slightly harder problems. That's the key insight you should have been getting. If the tutorials that you're reading haven't been delving into this, that means that those tutorials aren't doing a good job. The fact that factorial() looks like: ################################ def factorial(n): if n == 0: return 1 else: return n * factorial(n-1) ################################ is pretty darn worthless in itself. But the idea that we can break things down into two categories (simple cases, slightly complex cases) and handle them in some structured way is a valuable concept. If you see something that's looks trivially un-useful when you're reading a tutorial, bring it up on this list. They're bound to be some kind of real application for it. *grin* And if you have any other questions, feel free to ask. Good luck! From Barry.Carroll at psc.com Tue Apr 11 02:00:03 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Mon, 10 Apr 2006 17:00:03 -0700 Subject: [Tutor] Python for sysadmins (Was: failing to learn python) Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C364A@eugsrv400.psc.pscnet.com> Payal: I agree with Kent: the Python Cookbook is an excellent resource. And, it has a whole section on System Administration. try this URL: http://aspn.activestate.com/ASPN/Cookbook/Python?kwd=System You can also try Google. I entered 'Python sysadmin'. Here are just a few potentially interesting sites that came back: http://www.samag.com/documents/s=8964/sam0312a/0312a.htm http://www.unixreview.com/documents/s=8989/sam0401d/ http://www.linuxdevcenter.com/pub/a/linux/2002/05/09/sysadminguide.html Look through these and other resources, choose an example function that relates to one of your tasks and try it out. Post questions and problems here. Good luck Regards, Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed > -----Original Message----- > Message: 5 > Date: Mon, 10 Apr 2006 13:22:19 -0400 > From: Kent Johnson > Subject: Re: [Tutor] failing to learn python > Cc: tutor at python.org > Message-ID: <443A944B.1070304 at tds.net> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Payal Rathod wrote: > >> What kind of real life problems are you interested in? You might like > > > > I am a parttime sys admin so I want system admin problem which usually I > > do through shell scripts like parsing logs, generating reports, greping > > with regexes etc. > > The only thing I don't want is silly problems like generate fibonnacci > > series, add numbers frm 0-n etc. non required silly stuff. > > Take a look at the Python Cookbook: > http://aspn.activestate.com/ASPN/Cookbook/Python > > Dive into Python is not targeted at beginners but it is available online > and does have real-world examples: > http://diveintopython.org/ > > Kent From gslindstrom at gmail.com Tue Apr 11 05:04:51 2006 From: gslindstrom at gmail.com (Greg Lindstrom) Date: Mon, 10 Apr 2006 22:04:51 -0500 Subject: [Tutor] failing to learn python Message-ID: <57aa55060604102004o27ccf8e6ibdd27dca31f83536@mail.gmail.com> Paypal- I do a lot of system admin type work with Python. If you'd like, drop me a line and let me know what you're interested in learning...perhaps I could help you work through a project or two. Greg Lindstrom gslindstrom at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060410/7513e9cc/attachment.html From keosophon at khmeros.info Tue Apr 11 06:44:34 2006 From: keosophon at khmeros.info (Keo Sophon) Date: Tue, 11 Apr 2006 11:44:34 +0700 Subject: [Tutor] input with default value option Message-ID: <200604111144.34644.keosophon@khmeros.info> Hi, With raw_input(), it allows to input value. Can it be used to input value with default value option? Phon From bgailer at alum.rpi.edu Tue Apr 11 07:03:20 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon, 10 Apr 2006 22:03:20 -0700 Subject: [Tutor] input with default value option In-Reply-To: <200604111144.34644.keosophon@khmeros.info> References: <200604111144.34644.keosophon@khmeros.info> Message-ID: <443B3898.3030909@alum.rpi.edu> Keo Sophon wrote: > Hi, > > With raw_input(), it allows to input value. Can it be used to input value with default value option? > response = raw_input("Enter some data:") if not response: response = "default value" From dyoo at hkn.eecs.berkeley.edu Tue Apr 11 08:38:20 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 10 Apr 2006 23:38:20 -0700 (PDT) Subject: [Tutor] input with default value option In-Reply-To: <200604111144.34644.keosophon@khmeros.info> References: <200604111144.34644.keosophon@khmeros.info> Message-ID: > With raw_input(), it allows to input value. Can it be used to input > value with default value option? Hi Phon, We can build your own function to do this. Bob showed how to set up code so that the default's taken if the user just presses enter in his reply. Let's take a look at it again: ########################################### response = raw_input("Enter some data:") if not response: response = "default value" ########################################### We can capture this as a function that takes in a question and a default answer: ################################## def ask(question, default): response = raw_input(question) if not response: response = default return response ################################## And now we have something that acts like raw_input(), but also gives the user the ability to get a default: ###### >>> ask("favorite color?", "Blue. No yellow -- aaaugh!") favorite color?red 'red' >>> ask("favorite color?", "Blue. No yellow -- aaaugh!") favorite color? 'Blue. No yellow -- aaaugh!' >>> ###### (In the second call to ask(), I just pressed enter.) Does this make sense? From alan.gauld at freenet.co.uk Tue Apr 11 09:33:07 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 11 Apr 2006 08:33:07 +0100 Subject: [Tutor] failing to learn python References: <20060410133342.GA7045@tranquility.scriptkitchen.com><443A6639.1050703@tds.net> <20060410165200.GA15376@tranquility.scriptkitchen.com> Message-ID: <009e01c65d3a$2d916ef0$0a01a8c0@xp> >> What kind of real life problems are you interested in? You might like > > I am a parttime sys admin so I want system admin problem which usually I > do through shell scripts like parsing logs, generating reports, greping > with regexes etc. My tutor is specifdically targetted at computer power users invcluding sys admins. It has examples of parsing files and creating reports (albeit very simple ones since its for beginners) and using regex. It also has side bars on topics like using WSH on Windows and other OS specific topics. There are also specific topics on using the OS and IPC comms etc being written. > The only thing I don't want is silly problems like generate fibonnacci > series, add numbers frm 0-n etc. non required silly stuff. None of the above are silly stuff, they are all needed in various real world computing and scientific problems. However I do agree that they are not what most beginners will be doing and I try to avoid any math type exercises. (I do use factorials as an example of recursion alongside another more practical example) I don't think my tutor was in your list so you might like to give it a go... Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Tue Apr 11 09:36:42 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 11 Apr 2006 08:36:42 +0100 Subject: [Tutor] Decorators References: <57aa55060604101219t242c9fe9p142eecb0e9829502@mail.gmail.com> Message-ID: <00a801c65d3a$ad6b3b10$0a01a8c0@xp> > My problem, and this is after reading PEP 318 and other items found when I > "Googled" for decorators, is that I can't figure out the practical use for There is no practical use for decorators IMHO They are syntactic sugar added to the language to make some things that were already possible a little tidier looking (things like class/static methods etc) I don;t think there is anything that you need decorators to achieve that you can'tdo without them. In that respect they are like python's support for lambdas - nice to have but not essential to the language. Others may feel differently! :-) Alan G. From kaushalshriyan at gmail.com Tue Apr 11 11:19:37 2006 From: kaushalshriyan at gmail.com (Kaushal Shriyan) Date: Tue, 11 Apr 2006 14:49:37 +0530 Subject: [Tutor] Tuple Message-ID: <6b16fb4c0604110219ua5dce4cva483482a6cbd318a@mail.gmail.com> Hi All I am referring to http://www.ibiblio.org/obp/thinkCSpy/chap09.htm >>> tuple = ('a', 'b', 'c', 'd', 'e') >>> tuple[0] 'a' And the slice operator selects a range of elements. >>> tuple[1:3] ('b', 'c') But if we try to modify one of the elements of the tuple, we get a error: >>> tuple[0] = 'A' TypeError: object doesn't support item assignment Of course, even if we can't modify the elements of a tuple, we can replace it with a different tuple: >>> tuple = ('A',) + tuple[1:] >>> tuple ('A', 'b', 'c', 'd', 'e') How does tuple = ('A',) + tuple[1:] this work ???? Please explain me with an example Thanks Regards Kaushal From noufal at nibrahim.net.in Tue Apr 11 11:38:53 2006 From: noufal at nibrahim.net.in (Noufal Ibrahim) Date: Tue, 11 Apr 2006 15:08:53 +0530 (IST) Subject: [Tutor] Tuple In-Reply-To: <6b16fb4c0604110219ua5dce4cva483482a6cbd318a@mail.gmail.com> References: <6b16fb4c0604110219ua5dce4cva483482a6cbd318a@mail.gmail.com> Message-ID: <18135.203.145.176.76.1144748333.squirrel@members.hcoop.net> On Tue, April 11, 2006 2:49 pm, Kaushal Shriyan wrote: > Hi All > > I am referring to http://www.ibiblio.org/obp/thinkCSpy/chap09.htm > >>>> tuple = ('a', 'b', 'c', 'd', 'e') >>>> tuple[0] > 'a' > > > And the slice operator selects a range of elements. > >>>> tuple[1:3] > ('b', 'c') > > > But if we try to modify one of the elements of the tuple, we get a error: > >>>> tuple[0] = 'A' > TypeError: object doesn't support item assignment > > > Of course, even if we can't modify the elements of a tuple, we can > replace it with a different tuple: > >>>> tuple = ('A',) + tuple[1:] >>>> tuple > ('A', 'b', 'c', 'd', 'e') > > How does tuple = ('A',) + tuple[1:] this work ???? One question mark is enough. ;) ('A',) creates a tuple with a single element. The comma at the end is to differentiate between a tuple and just grouping brackets. tuple[1:] returns all elements of the tuple except the first. So what do you have? A tuple ('A') and another tuple ('b', 'c', 'd', 'e'). Now, the + operator concatenates these two into a new tuple. What do you get? ('A','b','c','d','e'). This is returned by the expression on the right hand side. And it's assigned to the variable "tuple". When you print it, you get the value. I think you're getting confused between changing a tuple itself and creating a new one with pieces of others. On a side note, it's not a good idea to call a variable "tuple" since there is a python builtin by the same name. -- -NI From kaushalshriyan at gmail.com Tue Apr 11 11:45:35 2006 From: kaushalshriyan at gmail.com (Kaushal Shriyan) Date: Tue, 11 Apr 2006 15:15:35 +0530 Subject: [Tutor] Tuple In-Reply-To: <18135.203.145.176.76.1144748333.squirrel@members.hcoop.net> References: <6b16fb4c0604110219ua5dce4cva483482a6cbd318a@mail.gmail.com> <18135.203.145.176.76.1144748333.squirrel@members.hcoop.net> Message-ID: <6b16fb4c0604110245l56eca033q2a22a05a8c70fce7@mail.gmail.com> On 4/11/06, Noufal Ibrahim wrote: > > On Tue, April 11, 2006 2:49 pm, Kaushal Shriyan wrote: > > Hi All > > > > I am referring to http://www.ibiblio.org/obp/thinkCSpy/chap09.htm > > > >>>> tuple = ('a', 'b', 'c', 'd', 'e') > >>>> tuple[0] > > 'a' > > > > > > And the slice operator selects a range of elements. > > > >>>> tuple[1:3] > > ('b', 'c') > > > > > > But if we try to modify one of the elements of the tuple, we get a error: > > > >>>> tuple[0] = 'A' > > TypeError: object doesn't support item assignment > > > > > > Of course, even if we can't modify the elements of a tuple, we can > > replace it with a different tuple: > > > >>>> tuple = ('A',) + tuple[1:] > >>>> tuple > > ('A', 'b', 'c', 'd', 'e') > > > > How does tuple = ('A',) + tuple[1:] this work ???? > > One question mark is enough. ;) > > ('A',) creates a tuple with a single element. The comma at the end is to > differentiate between a tuple and just grouping brackets. > tuple[1:] returns all elements of the tuple except the first. > So what do you have? > A tuple ('A') and another tuple ('b', 'c', 'd', 'e'). > > Now, the + operator concatenates these two into a new tuple. What do you get? > ('A','b','c','d','e'). > > This is returned by the expression on the right hand side. And it's > assigned to the variable "tuple". When you print it, you get the value. > > I think you're getting confused between changing a tuple itself and > creating a new one with pieces of others. > > On a side note, it's not a good idea to call a variable "tuple" since > there is a python builtin by the same name. > -- > -NI > > Thanks Noufal for the explanation Appreciate it Kaushal From singletoned at gmail.com Tue Apr 11 12:10:16 2006 From: singletoned at gmail.com (Ed Singleton) Date: Tue, 11 Apr 2006 11:10:16 +0100 Subject: [Tutor] failing to learn python In-Reply-To: <20060410133342.GA7045@tranquility.scriptkitchen.com> References: <20060410133342.GA7045@tranquility.scriptkitchen.com> Message-ID: <34bb7f5b0604110310k38bc5a6bm85c2b38407aa0982@mail.gmail.com> On 10/04/06, Payal Rathod wrote: > Hi, > I am trying to learn Python seriously for almost 2 months but have not > gotten far at all. Infact, it seems I have not understood even the basic > concepts itself. I know some shell, sed and awk programming. > I have tried reading Learning Python - Mark Lutz > Think C Spy > A byte of Python > Non-Programmers Tutorial For Python > etc. > But I have not got anything from them. I am feeling that they are > superficial and do not touch real life problems. Also, not enough > examples are provided which can help newbies like me. > > Can anyone help me, it is pretty pretty frustating thing for last couple > of months? > > With warm regards, > -Payal You might find reading real code to be more useful than a tutorial: Fredrik Lundh's Guide to the Standard Library contains thousands of examples: http://effbot.org/zone/librarybook-index.htm PLEAC contains loads of examples to show how to do things: http://pleac.sourceforge.net/pleac_python/index.html It all depends what kind of learner you are: Learn by being taught (read the tutorials) Learn by doing (think of a project, start trying to do it, then ask here when you get stuck) Learn by example (read lots of examples of other people's code to see how they do it) I'm very much the kind of person who likes to learn to swim by jumping as far into the water as he can, then trying to get back to the side. It's amazing how well you can do something when you don't have any choice. ;-) Ed From kent37 at tds.net Tue Apr 11 12:15:54 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 11 Apr 2006 06:15:54 -0400 Subject: [Tutor] Decorators In-Reply-To: <00a801c65d3a$ad6b3b10$0a01a8c0@xp> References: <57aa55060604101219t242c9fe9p142eecb0e9829502@mail.gmail.com> <00a801c65d3a$ad6b3b10$0a01a8c0@xp> Message-ID: <443B81DA.90709@tds.net> Alan Gauld wrote: >> My problem, and this is after reading PEP 318 and other items found when I >> "Googled" for decorators, is that I can't figure out the practical use for > > There is no practical use for decorators IMHO > They are syntactic sugar added to the language to make some things > that were already possible a little tidier looking (things like class/static > methods etc) It's true that decorators are syntactic sugar and don't add any new functional capabilities to the language. @foo def bar(): pass is equivalent to def bar(): pass bar = foo(bar) However this doesn't mean that there is no practical use for decorators. After all, list comprehension is mostly syntactic sugar too! Decorators add expressiveness and clarity to Python rather than functionality. If you read the PEP you see this is the primary motivation. Decorators are used widely so apparently many people agree that they add to the expressiveness of the language. Here is another example - decorators are used in the implementation of a proposal for dynamic function overloading: http://www.artima.com/weblogs/viewpost.jsp?thread=155514 Kent From kaushalshriyan at gmail.com Tue Apr 11 12:17:20 2006 From: kaushalshriyan at gmail.com (Kaushal Shriyan) Date: Tue, 11 Apr 2006 15:47:20 +0530 Subject: [Tutor] Emailid Message-ID: <6b16fb4c0604110317n2fc75f2bt3164517a0b590946@mail.gmail.com> Hi All I am a ardent fan of python can I have email address for me I mean For example for me it would be kaushal at python.org Regards Kaushal From kaushalshriyan at gmail.com Tue Apr 11 12:26:16 2006 From: kaushalshriyan at gmail.com (Kaushal Shriyan) Date: Tue, 11 Apr 2006 15:56:16 +0530 Subject: [Tutor] Tuple (Section 9.3) Message-ID: <6b16fb4c0604110326q7059fb31rcc4f6f267498a8e9@mail.gmail.com> Hi All I am reading this http://www.ibiblio.org/obp/thinkCSpy/chap09.htm and did not understood the Section 9.3 at all, Please explain me with an example so the idea become clear and understood #################################################################### 9.3 Tuples as return values Functions can return tuples as return values. For example, we could write a function that swaps two parameters: def swap(x, y): return y, x Then we can assign the return value to a tuple with two variables: a, b = swap(a, b) In this case, there is no great advantage in making swap a function. In fact, there is a danger in trying to encapsulate swap, which is the following tempting mistake: def swap(x, y): # incorrect version x, y = y, x If we call this function like this: swap(a, b) then a and x are aliases for the same value. Changing xinside swap makes x refer to a different value, but it has no effect on a in __main__. Similarly, changing y has no effect on b. This function runs without producing an error message, but it doesn't do what we intended. This is an example of a semantic error. As an exercise, draw a state diagram for this function so that you can see why it doesn't work. #################################################################### Thanks in Advance Regards Kaushal From alan.gauld at freenet.co.uk Tue Apr 11 13:27:17 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 11 Apr 2006 12:27:17 +0100 Subject: [Tutor] input with default value option References: <200604111144.34644.keosophon@khmeros.info> <443B3898.3030909@alum.rpi.edu> Message-ID: <00f301c65d5a$e5a6ee00$0a01a8c0@xp> >> With raw_input(), it allows to input value. Can it be used to input value >> with default value option? >> > response = raw_input("Enter some data:") > if not response: response = "default value" This is one of the few places where I do use the short-circuit evaluation trick: val = raw_input('> ') or myDefault I reads well (IMHO) and works pretty much safely. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Tue Apr 11 13:36:29 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 11 Apr 2006 12:36:29 +0100 Subject: [Tutor] Tuple References: <6b16fb4c0604110219ua5dce4cva483482a6cbd318a@mail.gmail.com> Message-ID: <00fb01c65d5c$2dc22370$0a01a8c0@xp> >>> tuple = ('A',) + tuple[1:] >>> tuple >('A', 'b', 'c', 'd', 'e') > > How does tuple = ('A',) + tuple[1:] this work ???? > > Please explain me with an example OK, we will use the example you gave us! tuple is a bad name since Python has an internal type called tuple usd for converting a list etc to a tuple so I'll use t1: >>> t1 = ('a','b','c','d','e') >>> t2 = ('A',) + t1[1:] We construct a new tuple by creating a single element tuple ('A',) and adding to it the contents of the original tuple starting with the second element (t1[1:]). We can add tuples together quite easily: >>> t3 = (1,2,3) + (4,5,6) >>> t3 (1,2,3,4,5,6) The result is a new tuple. The only difference in your example is that instead of using a new name (t2) you replaced the original tuple with the new one in t1. This is just the same as when you do x = x +1 Now which specific bit of that did you not understand and we can expand on it if necessary? Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From kaushalshriyan at gmail.com Tue Apr 11 13:48:06 2006 From: kaushalshriyan at gmail.com (Kaushal Shriyan) Date: Tue, 11 Apr 2006 17:18:06 +0530 Subject: [Tutor] comp.lang.python newsgroup Message-ID: <6b16fb4c0604110448k477f3f58t3904d043d7f1e70@mail.gmail.com> Hi All I went to a http://www.python.org/community/lists.html and found the below newsgroup How do i use this news group and access the information I need comp.lang.python newsgroup Thanks in Advance Regards Kaushal From kent37 at tds.net Tue Apr 11 14:22:28 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 11 Apr 2006 08:22:28 -0400 Subject: [Tutor] comp.lang.python newsgroup In-Reply-To: <6b16fb4c0604110448k477f3f58t3904d043d7f1e70@mail.gmail.com> References: <6b16fb4c0604110448k477f3f58t3904d043d7f1e70@mail.gmail.com> Message-ID: <443B9F84.6060909@tds.net> Kaushal Shriyan wrote: > Hi All > > I went to a http://www.python.org/community/lists.html and found the > below newsgroup > > How do i use this news group and access the information I need > > comp.lang.python newsgroup You can use Google groups http://groups.google.com/groups?group=comp.lang.python You can subscribe to the email version: http://www.python.org/mailman/listinfo/python-list Both of these and a few more options are listed in the web page you referenced! Kent From kent37 at tds.net Tue Apr 11 14:24:20 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 11 Apr 2006 08:24:20 -0400 Subject: [Tutor] Emailid In-Reply-To: <6b16fb4c0604110317n2fc75f2bt3164517a0b590946@mail.gmail.com> References: <6b16fb4c0604110317n2fc75f2bt3164517a0b590946@mail.gmail.com> Message-ID: <443B9FF4.2070605@tds.net> Kaushal Shriyan wrote: > Hi All > > I am a ardent fan of python can I have email address for me > I mean For example for me it would be > > kaushal at python.org I don't know how you get a python.org mailing address but I'm sure it's not by asking here! Kent From singletoned at gmail.com Tue Apr 11 15:19:57 2006 From: singletoned at gmail.com (Ed Singleton) Date: Tue, 11 Apr 2006 14:19:57 +0100 Subject: [Tutor] Emailid In-Reply-To: <443B9FF4.2070605@tds.net> References: <6b16fb4c0604110317n2fc75f2bt3164517a0b590946@mail.gmail.com> <443B9FF4.2070605@tds.net> Message-ID: <34bb7f5b0604110619i547cbb4aq3f5d6667f8e961a8@mail.gmail.com> On 11/04/06, Kent Johnson wrote: > Kaushal Shriyan wrote: > > Hi All > > > > I am a ardent fan of python can I have email address for me > > I mean For example for me it would be > > > > kaushal at python.org > > I don't know how you get a python.org mailing address but I'm sure it's > not by asking here! Actually, I can probably help. If you give your bank details to my friend in Nigeria, he can get you one. Ed From doug.shawhan at gmail.com Tue Apr 11 16:33:12 2006 From: doug.shawhan at gmail.com (doug shawhan) Date: Tue, 11 Apr 2006 09:33:12 -0500 Subject: [Tutor] Scan Codes, Character Sets: Any Modules? Message-ID: <5e1ceb8a0604110733n4341d0b9s3c86da0275a39cea@mail.gmail.com> The difficulty I have may or may not be something that may be easily handled with pyserial and some other mystery module. I am attempting to screen scrape SuperDOS, an extremely closed system that uses wyse 60 terminals to communicate with a dos machine. I have not been able to communicate properly with superdos until trying the handy miniterm.py example from the pyserial package in conjunction with Markus Gutschke's wy60 emulator which translates input through an xterm into wyse 60 commands. These programs together allow me to interact with superdos pretty well ... with the exception of the arrow keys: for those I must fall back to the old cntl-letter combos to get the cursor to behave (actually cntl-letter x 2.. for some reason it likes an extra prod). This is fine, as now I have a way to debug my eventual script. My big problem is, I am completely unable to get SuperDos to respond to my carriage returns from within the script! I can watch the script work via miniterm.py. I have sent the return and newline characters in various combinations starting with "\n,\r", "\x0a\x0d", but they respond weirdly, putting the cursor *above* the existing command line, changing the cursor to an outline and generally letting me know that I am on the wrong track. Has some clever human alread created a handy module to handle wyse60 and other terminal emulation from within a python program? I have looked over the curses module, but it seems to be aimed at drawing proper screens for the user, not translation. PySerial's ability to suck up the output via readlines() is awesome, and I can see how I *think* it should all be done, but the weirdness has got me stymied! I am going to look at Mr. Gutscheke's source to see how he does it, but I am barely conversant in python and fear that exposure to that much C code may cause dizziness! Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060411/54068229/attachment-0001.htm From pkraus at pelsupply.com Tue Apr 11 16:29:25 2006 From: pkraus at pelsupply.com (Paul Kraus) Date: Tue, 11 Apr 2006 10:29:25 -0400 Subject: [Tutor] unpack/regexp Message-ID: <200604111029.25408.pkraus@pelsupply.com> Ok sorry for the perl refernce but I can't figure out how to do this. I have a fixed width text file i need to parse. so lets say I want an array to containt the pieces i need. if the fields I want are lengths from left to right. 10 10 13 12345678901234567890123456789012 I want to turn this into an array that has these elements. 1234567890 1234567890 123456789012 <--notice white space In Perl its a simple my @array = unpack ( "A10 A10 A13" , $line ) this extracts it and removes the whitespace after doing so. or if i wanted i could do my @array = ( $1, $2, $3 ) if ( $line =~ m/^(.{10})(.{10})(.{13}) ) -- Paul Kraus =-=-=-=-=-=-=-=-=-=-= PEL Supply Company Network Administrator 216.267.5775 Voice 216.267.6176 Fax www.pelsupply.com =-=-=-=-=-=-=-=-=-=-= From kaushalshriyan at gmail.com Tue Apr 11 16:50:19 2006 From: kaushalshriyan at gmail.com (Kaushal Shriyan) Date: Tue, 11 Apr 2006 20:20:19 +0530 Subject: [Tutor] Database Connectivity Message-ID: <6b16fb4c0604110750g2fc01fcal44dc1a4c398690e4@mail.gmail.com> Hi ALL How do i connect my python program to MySQL DB or Oracle DB or can you please specify the URL which gives a detailed explanation on this. Thanks in Advance Regards Kaushal From singletoned at gmail.com Tue Apr 11 17:01:02 2006 From: singletoned at gmail.com (Ed Singleton) Date: Tue, 11 Apr 2006 16:01:02 +0100 Subject: [Tutor] Database Connectivity In-Reply-To: <6b16fb4c0604110750g2fc01fcal44dc1a4c398690e4@mail.gmail.com> References: <6b16fb4c0604110750g2fc01fcal44dc1a4c398690e4@mail.gmail.com> Message-ID: <34bb7f5b0604110801q48511c8ana120d54ee16e0044@mail.gmail.com> On 11/04/06, Kaushal Shriyan wrote: > Hi ALL > > How do i connect my python program to MySQL DB or Oracle DB or can you > please specify the URL which gives a detailed explanation on this. SQLObject is your best bet: http://www.sqlobject.org/ If you're using MySQL, you will need MySQLdb as well: http://sourceforge.net/projects/mysql-python Any questions, just ask. Ed From kent37 at tds.net Tue Apr 11 17:08:44 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 11 Apr 2006 11:08:44 -0400 Subject: [Tutor] unpack/regexp In-Reply-To: <200604111029.25408.pkraus@pelsupply.com> References: <200604111029.25408.pkraus@pelsupply.com> Message-ID: <443BC67C.7010004@tds.net> Paul Kraus wrote: > Ok sorry for the perl refernce but I can't figure out how to do this. > I have a fixed width text file i need to parse. > > so lets say I want an array to containt the pieces i need. > if the fields I want are lengths from left to right. > 10 10 13 > 12345678901234567890123456789012 > I want to turn this into an array that has these elements. > 1234567890 > 1234567890 > 123456789012 <--notice white space > > In Perl its a simple > my @array = unpack ( "A10 A10 A13" , $line ) > this extracts it and removes the whitespace after doing so. struct.unpack() is a direct analog: In [10]: line = "12345678901234567890123456789012 " In [16]: struct.unpack('10s10s13s', line) Out[16]: ('1234567890', '1234567890', '123456789012 ') You can also use string slicing: In [14]: line[:10], line[10:20], line[20:] Out[14]: ('1234567890', '1234567890', '123456789012 ') > > or if i wanted i could do > my @array = ( $1, $2, $3 ) if ( $line =~ m/^(.{10})(.{10})(.{13}) ) Python regex is a bit more verbose than Perl but you can do the same thing: In [2]: import re In [11]: m=re.match("(.{10})(.{10})(.{13})", line) In [13]: m.group(1, 2, 3) Out[13]: ('1234567890', '1234567890', '123456789012 ') Kent From kent37 at tds.net Tue Apr 11 17:11:00 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 11 Apr 2006 11:11:00 -0400 Subject: [Tutor] Database Connectivity In-Reply-To: <6b16fb4c0604110750g2fc01fcal44dc1a4c398690e4@mail.gmail.com> References: <6b16fb4c0604110750g2fc01fcal44dc1a4c398690e4@mail.gmail.com> Message-ID: <443BC704.5010203@tds.net> Kaushal Shriyan wrote: > Hi ALL > > How do i connect my python program to MySQL DB or Oracle DB or can you > please specify the URL which gives a detailed explanation on this. Basic connectivity is through modules that implement the DB-API standard. Read the spec and find implementations here: http://www.python.org/doc/topics/database/ There are several popular packages that layer on top of this basic functionality such as SQLObject and SQLAlchemy. Kent From pkraus at pelsupply.com Tue Apr 11 17:17:31 2006 From: pkraus at pelsupply.com (Paul Kraus) Date: Tue, 11 Apr 2006 11:17:31 -0400 Subject: [Tutor] unpack/regexp In-Reply-To: <443BC67C.7010004@tds.net> References: <200604111029.25408.pkraus@pelsupply.com> <443BC67C.7010004@tds.net> Message-ID: <200604111117.32127.pkraus@pelsupply.com> > Python regex is a bit more verbose than Perl but you can do the same thing: > > In [2]: import re > > In [11]: m=re.match("(.{10})(.{10})(.{13})", line) > > In [13]: m.group(1, 2, 3) > Out[13]: ('1234567890', '1234567890', '123456789012 ') That work great. Regex tend to be "expensive" is there a "better" way to do it? From doug.shawhan at gmail.com Tue Apr 11 17:32:41 2006 From: doug.shawhan at gmail.com (doug shawhan) Date: Tue, 11 Apr 2006 10:32:41 -0500 Subject: [Tutor] unpack/regexp In-Reply-To: <200604111029.25408.pkraus@pelsupply.com> References: <200604111029.25408.pkraus@pelsupply.com> Message-ID: <5e1ceb8a0604110832p3d59a675q5b746654cf761af@mail.gmail.com> I always slice the string in this sort of situation: s = "12345678901234567890123456789012 " t = s[:10],s[10:20],s[20:-1] print t ('1234567890', '1234567890', '123456789012') One could always bracket it to make a list or whatever. Hope this helps! On 4/11/06, Paul Kraus wrote: > > Ok sorry for the perl refernce but I can't figure out how to do this. > I have a fixed width text file i need to parse. > > so lets say I want an array to containt the pieces i need. > if the fields I want are lengths from left to right. > 10 10 13 > 12345678901234567890123456789012 > I want to turn this into an array that has these elements. > 1234567890 > 1234567890 > 123456789012 <--notice white space > > In Perl its a simple > my @array = unpack ( "A10 A10 A13" , $line ) > this extracts it and removes the whitespace after doing so. > > or if i wanted i could do > my @array = ( $1, $2, $3 ) if ( $line =~ m/^(.{10})(.{10})(.{13}) ) > > > -- > Paul Kraus > =-=-=-=-=-=-=-=-=-=-= > PEL Supply Company > Network Administrator > 216.267.5775 Voice > 216.267.6176 Fax > www.pelsupply.com > =-=-=-=-=-=-=-=-=-=-= > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060411/6fd722a7/attachment.html From payal-python at scriptkitchen.com Tue Apr 11 18:06:45 2006 From: payal-python at scriptkitchen.com (Payal Rathod) Date: Tue, 11 Apr 2006 12:06:45 -0400 Subject: [Tutor] failing to learn python In-Reply-To: References: <20060410133342.GA7045@tranquility.scriptkitchen.com> <443A6639.1050703@tds.net> <20060410165200.GA15376@tranquility.scriptkitchen.com> Message-ID: <20060411160645.GB5242@tranquility.scriptkitchen.com> On Mon, Apr 10, 2006 at 04:20:37PM -0700, Danny Yoo wrote: > http://gnosis.cx/TPiP/ I will read that and Alan's tutorial too (isn't that MS-Windows specific ???) The reason I am disgrunted with Python is because lack of good documentation. Shell programming has great text and so do sed and awk but Python texts are rather boring and just hooting that Python is cool without proving it at all. All the examples I wanted were done better in shell/sed/awk. But anyways thanks for the support I will dive into it again with fresh vigour. I will get back with any stupid queries I have. With warm regards, -Payal From hugonz at h-lab.net Tue Apr 11 18:08:46 2006 From: hugonz at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Tue, 11 Apr 2006 10:08:46 -0600 Subject: [Tutor] Tuple (Section 9.3) In-Reply-To: <6b16fb4c0604110326q7059fb31rcc4f6f267498a8e9@mail.gmail.com> References: <6b16fb4c0604110326q7059fb31rcc4f6f267498a8e9@mail.gmail.com> Message-ID: <443BD48E.5040004@h-lab.net> Hi Kaushal, I might have to do a little guessing and see what is not clear from the explanation. The whole point of returning a tuple as opposed to, say, returning a list, is the fact that tuples are NON mutable. That is, *apparently* you would not be returning a reference, but the values themselves. There is no better example I can think of, than the one you already read. If you want a function tu return multiple parameters so that you can do. ret1, ret2 = func() then have func return a tuple. That's the whole point of the chapter you read. Maybe there is too much information in the discussion that does not look useful to you if you have not run into a problem where you need it. I hope this is not some kind of homework :) Hugo From josipl2000 at yahoo.com Tue Apr 11 18:13:40 2006 From: josipl2000 at yahoo.com (josip) Date: Tue, 11 Apr 2006 09:13:40 -0700 (PDT) Subject: [Tutor] for loops Message-ID: <20060411161340.72598.qmail@web60819.mail.yahoo.com> I have problem with this question. Can someone show me the code and than explain it? >>Write a Python program to print out the following shape. You are expected to use two for loops (these must be nested) to solve this problem. output: * * * * * * * * * * * * * * Thanks --------------------------------- Love cheap thrills? Enjoy PC-to-Phone calls to 30+ countries for just 2?/min with Yahoo! Messenger with Voice. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060411/bc549895/attachment.htm From python at kapitalisten.no Tue Apr 11 18:31:41 2006 From: python at kapitalisten.no (=?iso-8859-1?Q?=D8yvind?=) Date: Tue, 11 Apr 2006 18:31:41 +0200 (CEST) Subject: [Tutor] Webbrowser Message-ID: <4760.193.71.156.197.1144773101.squirrel@mail.sporck.net> Hello. I have recently discovered the Webbrowser module, and have started using it instead of just using IE thru win32com. But, have a few questions: 1) Is it possible to give it an adress, and if the browser gets a redirect to a different adress, I can override it? For example, I tell the browser to open a site. The browser tries, but gets redirected to a spam-site. I would therefore like to send the user somewhere else. Is it possible? 2) It doesn't seem like open(url[, new=0][, autoraise=1]) new and autoraise work with Firefox. I have tried all possible comboes, but the site is opened in a new tab in Firefox regardless. Any suggestions? Thanks in advance, ?yvind -- This email has been scanned for viruses & spam by Decna as - www.decna.no Denne e-posten er sjekket for virus & spam av Decna as - www.decna.no From alan.gauld at freenet.co.uk Tue Apr 11 18:33:34 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 11 Apr 2006 17:33:34 +0100 Subject: [Tutor] Scan Codes, Character Sets: Any Modules? References: <5e1ceb8a0604110733n4341d0b9s3c86da0275a39cea@mail.gmail.com> Message-ID: <012f01c65d85$ad781740$0a01a8c0@xp> Hi Doug, > I am attempting to screen scrape SuperDOS, uses wyse 60 terminals > I must fall back to the old cntl-letter combos to get the cursor to behave Sounds like you need to find a tech spec for the Wyse 60. That should give you all of the Ctrl character combos to control the screen. If you have access to a Unix box you might find the info you need in the termcap or terminfo databases. But Wyse should have the spec sheet on their web site somewhere... Alan G. From alan.gauld at freenet.co.uk Tue Apr 11 18:43:10 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 11 Apr 2006 17:43:10 +0100 Subject: [Tutor] Decorators References: <57aa55060604101219t242c9fe9p142eecb0e9829502@mail.gmail.com><00a801c65d3a$ad6b3b10$0a01a8c0@xp> <443B81DA.90709@tds.net> Message-ID: <013301c65d87$0603d380$0a01a8c0@xp> >> There is no practical use for decorators IMHO > It's true that decorators are syntactic sugar and don't add any new > functional capabilities to the language. Which is all I intended to imply. > However this doesn't mean that there is no practical use for decorators. Nor did I mean that, after all I am a big advocate of lambdas and they too are sugar. They have no practical use but are nice for conveying certain concepts in code. Similarly with decorators (although I do hate the syntax!) > After all, list comprehension is mostly syntactic sugar too! Absolutely and also add no practical functionality they are just shorthand, albeit with a small performance advantage in many cases - which is not true of decorators or lambdas! > proposal for dynamic function overloading: > http://www.artima.com/weblogs/viewpost.jsp?thread=155514 I really don't like this proposal nor many of the others that currently exist to seemingly turn Python into Java and C++! If people want to code in the Java porridge let them use Java not try to turn Python into the same sludge. (And yes, I do realise that it's Guido who's doing the work in this case! :-) Alan G. From doug.shawhan at gmail.com Tue Apr 11 19:14:13 2006 From: doug.shawhan at gmail.com (doug shawhan) Date: Tue, 11 Apr 2006 12:14:13 -0500 Subject: [Tutor] Scan Codes, Character Sets: Any Modules? In-Reply-To: <5e1ceb8a0604111001u7a87f60ax65257cc22afb35d8@mail.gmail.com> References: <5e1ceb8a0604110733n4341d0b9s3c86da0275a39cea@mail.gmail.com> <012f01c65d85$ad781740$0a01a8c0@xp> <5e1ceb8a0604111001u7a87f60ax65257cc22afb35d8@mail.gmail.com> Message-ID: <5e1ceb8a0604111014ldf51cccw36e4cb854d74727d@mail.gmail.com> Oho! http://www.wyse.com/service/support/kbase/Keydetl1.asp?Q=7&R=6 has the hex codes! Thanks! Perhaps this will fix what ails me. On 4/11/06, doug shawhan wrote: > > Yeah, termca was were I looked first. > > The OpenBSD 3.8 termcap shows: > :cr=^M:ct=\E0:dc=\EW:dl=\ER:do=^J:ds=\EF\r:ei=\Er:fs=^M:\ for the carriage > return, but then I can't find the hex code for ^M! :-) At that point I > thought I'd ask if there was some sort of termcapesque module available. > > I will scope the wyse website again, perhaps I can locate it this time! > > Thanks > > > On 4/11/06, Alan Gauld wrote: > > > > Hi Doug, > > > > > I am attempting to screen scrape SuperDOS, uses wyse 60 terminals > > > I must fall back to the old cntl-letter combos to get the cursor to > > behave > > > > Sounds like you need to find a tech spec for the Wyse 60. That should > > give you all of the Ctrl character combos to control the screen. > > If you have access to a Unix box you might find the info you need > > in the termcap or terminfo databases. But Wyse should have the > > spec sheet on their web site somewhere... > > > > Alan G. > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060411/7c561fc9/attachment.htm From david at graniteweb.com Tue Apr 11 19:47:11 2006 From: david at graniteweb.com (David Rock) Date: Tue, 11 Apr 2006 12:47:11 -0500 Subject: [Tutor] for loops In-Reply-To: <20060411161340.72598.qmail@web60819.mail.yahoo.com> References: <20060411161340.72598.qmail@web60819.mail.yahoo.com> Message-ID: <20060411174711.GB2865@wdfs.graniteweb.com> * josip [2006-04-11 09:13]: > I have problem with this question. > Can someone show me the code and than explain it? > > >>Write a Python program to print out the following shape. You are expected to use two for loops (these must be nested) to solve this problem. > > output: > * * * * * > * * > * * > * * * * * That looks a lot like homework. If you have a specific question about a _part_ of code _you_ have written, we'll be glad to help out explaining those specifics. We generally try to stay away from doing the work for you :-) -- David Rock david at graniteweb.com From ms at cerenity.org Tue Apr 11 20:03:15 2006 From: ms at cerenity.org (Michael) Date: Tue, 11 Apr 2006 19:03:15 +0100 Subject: [Tutor] Decorators In-Reply-To: <013301c65d87$0603d380$0a01a8c0@xp> References: <57aa55060604101219t242c9fe9p142eecb0e9829502@mail.gmail.com> <443B81DA.90709@tds.net> <013301c65d87$0603d380$0a01a8c0@xp> Message-ID: <200604111903.15240.ms@cerenity.org> On Tuesday 11 April 2006 17:43, Alan Gauld wrote: > >> There is no practical use for decorators IMHO > > > > It's true that decorators are syntactic sugar and don't add any new > > functional capabilities to the language. > > Which is all I intended to imply. You have a different meaning of "practical use" from common usage then. Something that makes it easier to: * Understand that a function has been modified * Make it clear that a function is a staticmethod/classmethod/etc *right at the beginning of a function* without having to read the entire body. * Reduce typing * Allow hinting of types for integration with tools like PyObjC * Make it clear when reading the definition of a method/function is memoised, traced etc * Simplifying augmentation of generators with arbitrary extra communications attributes. ... are all practical benefits. That means they have practical use in my book :-) Syntactic sugar *IS* a practical benefit. After all, every language above assember is syntactic sugar, and by your definition of no practical use. Michael. From dyoo at hkn.eecs.berkeley.edu Tue Apr 11 20:04:15 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 11 Apr 2006 11:04:15 -0700 (PDT) Subject: [Tutor] comp.lang.python newsgroup In-Reply-To: <6b16fb4c0604110448k477f3f58t3904d043d7f1e70@mail.gmail.com> References: <6b16fb4c0604110448k477f3f58t3904d043d7f1e70@mail.gmail.com> Message-ID: [taking help at python.org out of CC] Hi Kaushal, Please do not crosspost between help at python.org and tutor at python.org. They are different mailing lists. > I went to a http://www.python.org/community/lists.html and found the > below newsgroup > > How do i use this news group and access the information I need Did you really read the page? I don't mean to be facetious, but the content is all right there from your link. What part about that page is confusing to you? I'm baffled, so if you can explain what difficulty you had in reading it, that may help us better understand. Also, I've noticed you're asking a lot of rapid-fire questions. You may want to take a look at: http://www.catb.org/~esr/faqs/smart-questions.html so that you get a better idea of asking questions that have a good chance of getting answered well. From python at venix.com Tue Apr 11 20:03:40 2006 From: python at venix.com (Python) Date: Tue, 11 Apr 2006 14:03:40 -0400 Subject: [Tutor] failing to learn python In-Reply-To: <20060411160645.GB5242@tranquility.scriptkitchen.com> References: <20060410133342.GA7045@tranquility.scriptkitchen.com> <443A6639.1050703@tds.net> <20060410165200.GA15376@tranquility.scriptkitchen.com> <20060411160645.GB5242@tranquility.scriptkitchen.com> Message-ID: <1144778620.25186.36.camel@www.venix.com> On Tue, 2006-04-11 at 12:06 -0400, Payal Rathod wrote: > The reason I am disgrunted with Python is because lack of good > documentation. http://www.python.org/doc/ The Python Docs - possibly you missed this because of the plethora of links. The Library Reference used to have the tag line: (keep this under your pillow) The Module Index is the other key starting point. http://rgruet.free.fr/PQR24/PQR2.4.html A very handy quick reference. I think Python has incredibly good documentation. Fred Drake and the other folks who write, edit and maintain the documentation do a wonderful job of keeping it fresh and current as the language changes. There are very few rough spots within the thousands of pages of text. It's been a while since I looked at the Tutorial. Is that where you felt let down? I felt compelled to respond to your post. I think the quality and quantity of Python documentation is hard to beat. -- Lloyd Kvam Venix Corp From kent37 at tds.net Tue Apr 11 20:21:22 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 11 Apr 2006 14:21:22 -0400 Subject: [Tutor] Decorators In-Reply-To: <013301c65d87$0603d380$0a01a8c0@xp> References: <57aa55060604101219t242c9fe9p142eecb0e9829502@mail.gmail.com><00a801c65d3a$ad6b3b10$0a01a8c0@xp> <443B81DA.90709@tds.net> <013301c65d87$0603d380$0a01a8c0@xp> Message-ID: <443BF3A2.9070107@tds.net> Alan Gauld wrote: >> proposal for dynamic function overloading: >> http://www.artima.com/weblogs/viewpost.jsp?thread=155514 > > I really don't like this proposal nor many of the others that currently > exist to seemingly turn Python into Java and C++! If people want to > code in the Java porridge let them use Java not try to turn Python > into the same sludge. FWIW there is enough perceived need for this (and adapters or protocols) that it has been invented already two or three times, in PEAK (by Philip J Eby, author of a popular "Python is not Java" rant*), Zope and twisted IIRC. The PEAK version has been adopted by TurboGears. I think twisted has abandoned its own effort and adopted Zope's. So I don't think it is necessarily people who want to turn Python into Java, but meeting a need that comes up in large projects. Kent * http://dirtsimple.org/2004/12/python-is-not-java.html From alan.gauld at freenet.co.uk Tue Apr 11 20:35:15 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 11 Apr 2006 19:35:15 +0100 Subject: [Tutor] failing to learn python References: <20060410133342.GA7045@tranquility.scriptkitchen.com><443A6639.1050703@tds.net><20060410165200.GA15376@tranquility.scriptkitchen.com> <20060411160645.GB5242@tranquility.scriptkitchen.com> Message-ID: <015201c65d96$ad311370$0a01a8c0@xp> > On Mon, Apr 10, 2006 at 04:20:37PM -0700, Danny Yoo wrote: >> http://gnosis.cx/TPiP/ > > I will read that and Alan's tutorial too (isn't that MS-Windows specific > ???) Nope, it usually mentions *nix workarounds etc Most of it is OS neutral. The OS and IPC topic are mainly Unix centric. > without proving it at all. All the examples I wanted were done better in > shell/sed/awk. I use Python a lot but I still use sed and awk for what they are good at. Using the Right Tool for the Job is still a sound maxim. Python is a general programmjing language great for bigger jobs. If you just want to run a sequience of unix commands shell is better. If you want simple but bulk text manipulation awk or sed are best. Alan G. From doug.shawhan at gmail.com Tue Apr 11 20:56:04 2006 From: doug.shawhan at gmail.com (doug shawhan) Date: Tue, 11 Apr 2006 13:56:04 -0500 Subject: [Tutor] Scan Codes, Character Sets: Any Modules? In-Reply-To: <5e1ceb8a0604111014ldf51cccw36e4cb854d74727d@mail.gmail.com> References: <5e1ceb8a0604110733n4341d0b9s3c86da0275a39cea@mail.gmail.com> <012f01c65d85$ad781740$0a01a8c0@xp> <5e1ceb8a0604111001u7a87f60ax65257cc22afb35d8@mail.gmail.com> <5e1ceb8a0604111014ldf51cccw36e4cb854d74727d@mail.gmail.com> Message-ID: <5e1ceb8a0604111156m21242e77gb44a8191bdf8260d@mail.gmail.com> No luck. I think I am missing something utterly basic, and completely unrelated to python. :-) I'll quit filling everyone's mailbox with cheese and move on to a terminal newsgroup for my future pesterances. Thanks for the help folks! On 4/11/06, doug shawhan wrote: > > Oho! http://www.wyse.com/service/support/kbase/Keydetl1.asp?Q=7&R=6 has > the hex codes! > > Thanks! Perhaps this will fix what ails me. > > > On 4/11/06, doug shawhan wrote: > > > > Yeah, termca was were I looked first. > > > > The OpenBSD 3.8 termcap shows: > > :cr=^M:ct=\E0:dc=\EW:dl=\ER:do=^J:ds=\EF\r:ei=\Er:fs=^M:\ for the carriage > > return, but then I can't find the hex code for ^M! :-) At that point I > > thought I'd ask if there was some sort of termcapesque module available. > > > > I will scope the wyse website again, perhaps I can locate it this time! > > > > Thanks > > > > > > On 4/11/06, Alan Gauld < alan.gauld at freenet.co.uk> wrote: > > > > > > Hi Doug, > > > > > > > I am attempting to screen scrape SuperDOS, uses wyse 60 terminals > > > > I must fall back to the old cntl-letter combos to get the cursor to > > > behave > > > > > > Sounds like you need to find a tech spec for the Wyse 60. That should > > > give you all of the Ctrl character combos to control the screen. > > > If you have access to a Unix box you might find the info you need > > > in the termcap or terminfo databases. But Wyse should have the > > > spec sheet on their web site somewhere... > > > > > > Alan G. > > > > > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060411/b6cbd965/attachment-0001.htm From mhansen at cso.atmel.com Tue Apr 11 21:19:40 2006 From: mhansen at cso.atmel.com (Mike Hansen) Date: Tue, 11 Apr 2006 13:19:40 -0600 Subject: [Tutor] Database Connectivity In-Reply-To: <443BC704.5010203@tds.net> Message-ID: <002601c65d9c$e19d94c0$28645f0a@mikehansen> > Kaushal Shriyan wrote: > > Hi ALL > > > > How do i connect my python program to MySQL DB or Oracle DB > or can you > > please specify the URL which gives a detailed explanation on this. > > Basic connectivity is through modules that implement the > DB-API standard. Read the spec and find implementations here: > http://www.python.org/doc/topics/database/ > > There are several popular packages that layer on top of this > basic functionality such as SQLObject and SQLAlchemy. > > Kent The DB-API spec would go a long way if it had a couple of examples. Poking around the database topics, I came across an article in Linux Journal that seems to help http://www.linuxjournal.com/article/2605 Also, the MySQLdb module has some examples http://sourceforge.net/docman/display_doc.php?docid=32071&group_id=22307#som e-examples The module for Postgre called psycopg has a nice PDF about the DB-API http://initd.org/pub/software/psycopg/dbapi20programming.pdf Mike From alan.gauld at freenet.co.uk Tue Apr 11 21:58:10 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 11 Apr 2006 20:58:10 +0100 Subject: [Tutor] Decorators References: <57aa55060604101219t242c9fe9p142eecb0e9829502@mail.gmail.com><443B81DA.90709@tds.net> <013301c65d87$0603d380$0a01a8c0@xp> <200604111903.15240.ms@cerenity.org> Message-ID: <017e01c65da2$42ac96d0$0a01a8c0@xp> > Syntactic sugar *IS* a practical benefit. After all, every language above > assember is syntactic sugar, and by your definition of no practical use. Ah, but by that standard even assembler is syntactic sugar, now where are those hex codes and my keypunch? :-) By practical use I mean adding function to the language. I agree decorators add a modicum of readability, but they also remove a large slice of Python's readability by introducing more line noise characters to the language, and that's a really bad feature from my perspective. As to your list of benefits: * Understand that a function has been modified I'm not sure I see how decorators do that? Can you give an example to explain what you mean? * Make it clear that a function is a staticmethod/classmethod/etc *right at the beginning of a function* without having to read the entire body. Not been an issue, I found the previous explicit statement to be just as useful. * Reduce typing Never a good reason for introducing features if the feature introduces line noise in my book! I'd rather type a few more characters than contend with $@% type crud. * Allow hinting of types for integration with tools like PyObjC Too esoteric for mainstream, if I want to program in ObjC (and I do!) I'll use ObjC. Its never worth corrupting one language just to integrate with another (The only exception I've ever been happy with in that regard is the asm/endasm directives in C/Pascal/Cobol/Fortran etc) * Make it clear when reading the definition of a method/function is memoised, traced etc I use a debugger for that kind of thing. * Simplifying augmentation of generators with arbitrary extra communications attributes. Never ventured into this area yet so can't comment. Alan G From alan.gauld at freenet.co.uk Tue Apr 11 22:08:12 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 11 Apr 2006 21:08:12 +0100 Subject: [Tutor] Decorators References: <57aa55060604101219t242c9fe9p142eecb0e9829502@mail.gmail.com><00a801c65d3a$ad6b3b10$0a01a8c0@xp><443B81DA.90709@tds.net> <013301c65d87$0603d380$0a01a8c0@xp> <443BF3A2.9070107@tds.net> Message-ID: <018401c65da3$a9b34b70$0a01a8c0@xp> >> I really don't like this proposal nor many of the others that currently >> exist to seemingly turn Python into Java and C++! If people want to > > FWIW there is enough perceived need for this (and adapters or protocols) > that it has been invented already two or three times, in PEAK (by Philip > ... > So I don't think it is necessarily people who want to turn Python into > Java, but meeting a need that comes up in large projects. Just because there is a perceived need doesn't make it good. C++ started out as a neat elegant extension to C that enabled it to do things that vanilla C couldn't. Then 'perceived need' added features to support just about every OOP concept and flavour going, plus adding a few new ones. The end result is a nightmare language with so many holes gaping that it is almost impossible to use effectively. The result of that was the brain-dead Java v1 language which is now being frantically patched and is rapidly turning into another rotting pile of syntax. Unfortunately there is a real danger of Python going the same way.What was an easy to learn and use, ideal language for medium sized to fairly large scripting projects is trying to turn into an all encompassing general purpose language which will be increasingly difficult to use without falling down some new syntax hole. I would hate for that to happen to Python simply because people are trying to stretch it beyond its natural envelope. Sadly Lisp appears to be the only language so far that has succeeded in extending without losing its inherent simplicity of structure and syntax. Unfortunately Lisp's simplicity is only apparent to mathemeticians! :-) Alan G From alan.gauld at freenet.co.uk Tue Apr 11 22:15:30 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 11 Apr 2006 21:15:30 +0100 Subject: [Tutor] for loops References: <20060411161340.72598.qmail@web60819.mail.yahoo.com> <20060411174711.GB2865@wdfs.graniteweb.com> Message-ID: <018e01c65da4$ae381ad0$0a01a8c0@xp> >> >>Write a Python program to print out the following shape. >> >>You are expected to use two for loops (these must be nested) to solve >> this problem. >> >> output: >> * * * * * >> * * >> * * >> * * * * * > > That looks a lot like homework. I agree and very poor homework too. I certainly wouldn't expect to use two for loops, I'd only use one. (And that assumes the more general problem of drawing an arbitrary sized square, for the specific case I'd use a single print statement and triple quoted string!) Any homework which implies that only one design is acceptable is a bad assignment in my book! > We generally try to stay away from doing the work for you :-) But the advice stays good. Tell us how far you got and what's sticking you and we will try to help... Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From bgailer at alum.rpi.edu Tue Apr 11 22:42:20 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Tue, 11 Apr 2006 13:42:20 -0700 Subject: [Tutor] Decorators In-Reply-To: <017e01c65da2$42ac96d0$0a01a8c0@xp> References: <57aa55060604101219t242c9fe9p142eecb0e9829502@mail.gmail.com><443B81DA.90709@tds.net> <013301c65d87$0603d380$0a01a8c0@xp> <200604111903.15240.ms@cerenity.org> <017e01c65da2$42ac96d0$0a01a8c0@xp> Message-ID: <443C14AC.5020302@alum.rpi.edu> Alan Gauld wrote: >> Syntactic sugar *IS* a practical benefit. After all, every language above >> assember is syntactic sugar, and by your definition of no practical use. >> > > Ah, but by that standard even assembler is syntactic sugar, now > where are those hex codes and my keypunch? :-) Only those of us who keyed the bin loader into a PDP-8 by toggling switches, each representing one bit, can claim to be the most free of syntactic sugar. "Real programmers eschew languages. They do it on the bare metal." From hugonz-lists at h-lab.net Tue Apr 11 22:44:00 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Tue, 11 Apr 2006 14:44:00 -0600 Subject: [Tutor] Tuple (Section 9.3) In-Reply-To: <6b16fb4c0604110326q7059fb31rcc4f6f267498a8e9@mail.gmail.com> References: <6b16fb4c0604110326q7059fb31rcc4f6f267498a8e9@mail.gmail.com> Message-ID: <443C1510.2000308@h-lab.net> Hi Kaushal, I might have to do a little guessing and see what is not clear from the explanation. The whole point of returning a tuple as opposed to, say, returning a list, is the fact that tuples are NON mutable. That is, *apparently* you would not be returning a reference, but the values themselves. There is no better example I can think of, than the one you already read. If you want a function tu return multiple parameters so that you can do. ret1, ret2 = func() then have func return a tuple. That's the whole point of the chapter you read. Maybe there is too much information in the discussion that does not look useful to you if you have not run into a problem where you need it. I hope this is not some kind of homework :) Hugo From fant at pobox.com Tue Apr 11 23:24:32 2006 From: fant at pobox.com (Andrew D. Fant) Date: Tue, 11 Apr 2006 17:24:32 -0400 Subject: [Tutor] Decorators In-Reply-To: <017e01c65da2$42ac96d0$0a01a8c0@xp> References: <57aa55060604101219t242c9fe9p142eecb0e9829502@mail.gmail.com><443B81DA.90709@tds.net> <013301c65d87$0603d380$0a01a8c0@xp> <200604111903.15240.ms@cerenity.org> <017e01c65da2$42ac96d0$0a01a8c0@xp> Message-ID: <443C1E90.7020105@pobox.com> Alan Gauld wrote: >>Syntactic sugar *IS* a practical benefit. After all, every language above >>assember is syntactic sugar, and by your definition of no practical use. > > > Ah, but by that standard even assembler is syntactic sugar, now > where are those hex codes and my keypunch? :-) > > By practical use I mean adding function to the language. > I agree decorators add a modicum of readability, but > they also remove a large slice of Python's readability > by introducing more line noise characters to the language, > and that's a really bad feature from my perspective. > *chomp* (sorry for introducing perl constructs here 8) > Alan G Alan, May I just say AMEN? One of the reasons I started using python is that it was the first programming language I had seen since Fortran that didn't make my eyes cross from line noise characters stuck in among the text. Has anyone ever studied the effect of decorators on code readability? Personally, I think that if we want to add a bunch of unpronounceable characters to our code, we should go back to using APL. (for those who miss it, A+ is a fairly decent modern update of the concept) Now if you REALLY want to get funky. try crossing lisp with APL for a mathematically pure language that nobody can ever read. Andy -- Andrew Fant | And when the night is cloudy | This space to let Molecular Geek | There is still a light |---------------------- fant at pobox.com | That shines on me | Disclaimer: I don't Boston, MA | Shine until tomorrow, Let it be | even speak for myself From bgailer at alum.rpi.edu Wed Apr 12 00:10:20 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Tue, 11 Apr 2006 15:10:20 -0700 Subject: [Tutor] Decorators In-Reply-To: <443C1E90.7020105@pobox.com> References: <57aa55060604101219t242c9fe9p142eecb0e9829502@mail.gmail.com><443B81DA.90709@tds.net> <013301c65d87$0603d380$0a01a8c0@xp> <200604111903.15240.ms@cerenity.org> <017e01c65da2$42ac96d0$0a01a8c0@xp> <443C1E90.7020105@pobox.com> Message-ID: <443C294C.1050205@alum.rpi.edu> Andrew D. Fant wrote: > [snip] try crossing lisp > with APL for a mathematically pure language that nobody can ever read. > One problem is that APL allowed unbalanced parentheses (as in )SAVE), whereas LISP does not. And of course there is the right-to-left vs left-to-right issue... I do miss the incredible succinctness of APL. One "line noise" character was worth (say) 10 lines of (say) Fortran. I'd like to see some APL-ness added to Python, as I struggle to write a comprehension equivalent to one APL character. From victor at grupocdm.com Wed Apr 12 00:15:58 2006 From: victor at grupocdm.com (Victor Bouffier) Date: Tue, 11 Apr 2006 17:15:58 -0500 Subject: [Tutor] Extending a list within a list comprehension Message-ID: <1144793758.6561.108.camel@elrond> Hi all, I have solved my problem, but would like to know if what I accomplished can be done with different data using list comprehensions. the list I want to sort has the following format: elements = [ (codigo, [ cant, importe, porc]), (codigo, [ cant, importe, porc]), ... ] Actual data is: In [129]: elements[0:5] Out[129]: [('2712', [22.0, 3618.8099999999999, 0.0032389476163069883]), ('2713', [19.0, 6551.8100000000004, 0.0058640739309320719]), ('2710', [21.0, 2553.5799999999999, 0.0022855336019435113]), ('2716', [19.0, 8215.2700000000004, 0.0073529224203034461]), ('4305', [4.0, 348.37, 0.00031180199598565978])] And I want to sort descending on 'importe', which is x[1][1] for x in elements. What I did was the following, following the Schwarzian Transform: temporal = [] temporal = [ [x[1][1], (x[0], description[x[0]], x[1][0], x[1][1], x[1][2] ) ] for x in elements ] temporal.sort() temporal.reverse() # sort descending elements = [ x[1] for x in temporal ] If the second element in each array passed as x is of variable length (that is, it has a different element count than three, in this case), the program needs to extend the list instead. Without list comprehensions, and the added capability to utilize and sized list as a second element, my code ended up looking like the following: temporal = [] for x in elements: lst = [x[0], description[x[0]]] lst.extend(x[1]) temporal.append([x[1][1], lst]) temporal.sort() temporal.reverse() # sort descending elements = [ x[1] for x in temporal ] Is there a way to use list comprehensions to append or extend the array as needed by the second code listing? Thanks. Victor From john at fouhy.net Wed Apr 12 00:29:55 2006 From: john at fouhy.net (John Fouhy) Date: Wed, 12 Apr 2006 10:29:55 +1200 Subject: [Tutor] Extending a list within a list comprehension In-Reply-To: <1144793758.6561.108.camel@elrond> References: <1144793758.6561.108.camel@elrond> Message-ID: <5e58f2e40604111529m5849bc6o1f2ba0fd27e5d6a0@mail.gmail.com> On 12/04/06, Victor Bouffier wrote: > elements = [ > (codigo, [ cant, importe, porc]), > (codigo, [ cant, importe, porc]), > ... > ] > > And I want to sort descending on 'importe', which is x[1][1] for x in > elements. In python 2.4, you could achieve this by saying: elements.sort(key=lambda x: x[1][1]) In earlier versions of python, you can do: elements.sort(lambda x, y: cmp(x[1][1], y[1][1])) (but this is less efficient than key= in 2.4) There's also the decorate-sort-undecorate idiom: dec = [(x[1][1], x) for x in elements] dec.sort() elements = [x[1] for x in dec] -- John. From alan.gauld at freenet.co.uk Wed Apr 12 00:34:51 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 11 Apr 2006 23:34:51 +0100 Subject: [Tutor] Decorators References: <57aa55060604101219t242c9fe9p142eecb0e9829502@mail.gmail.com><443B81DA.90709@tds.net> <013301c65d87$0603d380$0a01a8c0@xp> <200604111903.15240.ms@cerenity.org><017e01c65da2$42ac96d0$0a01a8c0@xp> <443C14AC.5020302@alum.rpi.edu> Message-ID: <01a401c65db8$2704cef0$0a01a8c0@xp> >> Ah, but by that standard even assembler is syntactic sugar, now >> where are those hex codes and my keypunch? :-) > Only those of us who keyed the bin loader into a PDP-8 by toggling > switches, each representing one bit, can claim to be the most free of > syntactic sugar. Never used a PDP 8 (but I did use a PDP 11), but I have keyed binary boot sequences into a Data General machine in the late '70s using the front panel DIP switches Alan G. From alan.gauld at freenet.co.uk Wed Apr 12 00:42:29 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 11 Apr 2006 23:42:29 +0100 Subject: [Tutor] Extending a list within a list comprehension References: <1144793758.6561.108.camel@elrond> Message-ID: <01ae01c65db9$385a6920$0a01a8c0@xp> Hi Victor, I've gotta say that I much prefer the second version here. > temporal = [] > temporal = [ [x[1][1], (x[0], description[x[0]], > x[1][0], x[1][1], x[1][2] ) ] for x in elements ] > temporal.sort() > temporal.reverse() # sort descending > elements = [ x[1] for x in temporal ] > > > temporal = [] > for x in elements: > lst = [x[0], description[x[0]]] > lst.extend(x[1]) > temporal.append([x[1][1], lst]) > temporal.sort() > temporal.reverse() # sort descending > elements = [ x[1] for x in temporal ] > That looks a lot easier to rtead (and debug) and will I suspect be easier to maintain. Copmprehensions are great but unfortunately can rapidly become incomprehensible! > Is there a way to use list comprehensions to append or extend the array > as needed by the second code listing? There may be but I wouldn't try. I might however look at using a simple list or dictionary of objects based on a class... It might be easier. Alan G From victor at grupocdm.com Wed Apr 12 01:14:41 2006 From: victor at grupocdm.com (Victor Bouffier) Date: Tue, 11 Apr 2006 18:14:41 -0500 Subject: [Tutor] [Fwd: Re: Extending a list within a list comprehension] Message-ID: <1144797282.6561.126.camel@elrond> I sent this to John directly. Posting to the list. -------- Forwarded Message -------- From: Victor Bouffier To: John Fouhy Subject: Re: [Tutor] Extending a list within a list comprehension Date: Tue, 11 Apr 2006 18:03:41 -0500 On Wed, 2006-04-12 at 10:29 +1200, John Fouhy wrote: > On 12/04/06, Victor Bouffier wrote: > > elements = [ > > (codigo, [ cant, importe, porc]), > > (codigo, [ cant, importe, porc]), > > ... > > ] > > > > And I want to sort descending on 'importe', which is x[1][1] for x in > > elements. > > In python 2.4, you could achieve this by saying: > > elements.sort(key=lambda x: x[1][1]) > > In earlier versions of python, you can do: > > elements.sort(lambda x, y: cmp(x[1][1], y[1][1])) > > (but this is less efficient than key= in 2.4) > > There's also the decorate-sort-undecorate idiom: > > dec = [(x[1][1], x) for x in elements] > dec.sort() > elements = [x[1] for x in dec] Hi John, Thanks for your help. This is very nice and I will definitely use it when sorting a fixed list. However, I forgot to point out I am including an extra element: item description from a dict, where its key=codigo (x[0]). This is why I write the whole list as a single element. Still I could follow your suggestion and do: dec = [(x[1][1], x, description[x[0]]) for x in elements] dec.sort() elements = [x[1], x[2] for x in dec] It is still better, but not quite there. Any feedback will be gladly taken. Victor From victor at grupocdm.com Wed Apr 12 01:18:03 2006 From: victor at grupocdm.com (Victor Bouffier) Date: Tue, 11 Apr 2006 18:18:03 -0500 Subject: [Tutor] Extending a list within a list comprehension In-Reply-To: <01ae01c65db9$385a6920$0a01a8c0@xp> References: <1144793758.6561.108.camel@elrond> <01ae01c65db9$385a6920$0a01a8c0@xp> Message-ID: <1144797483.6561.131.camel@elrond> On Tue, 2006-04-11 at 23:42 +0100, Alan Gauld wrote: > Hi Victor, > > I've gotta say that I much prefer the second version here. > > > temporal = [] > > temporal = [ [x[1][1], (x[0], description[x[0]], > > x[1][0], x[1][1], x[1][2] ) ] for x in elements ] > > temporal.sort() > > temporal.reverse() # sort descending > > elements = [ x[1] for x in temporal ] > > > > > > temporal = [] > > for x in elements: > > lst = [x[0], description[x[0]]] > > lst.extend(x[1]) > > temporal.append([x[1][1], lst]) > > temporal.sort() > > temporal.reverse() # sort descending > > elements = [ x[1] for x in temporal ] > > > > That looks a lot easier to rtead (and debug) and will I suspect be > easier to maintain. Copmprehensions are great but unfortunately > can rapidly become incomprehensible! > > > Is there a way to use list comprehensions to append or extend the array > > as needed by the second code listing? > > There may be but I wouldn't try. > I might however look at using a simple list or dictionary of objects based > on a class... It might be easier. > > Alan G > > Hi Alan, I believe you are right. The most pythonic way is not always the most "perlish" way ;-) (no offense intended to Perl-comers, but Perl does tend to promote nesting of expressions). It is much easier to read and maintain, which is what I will need to do eventually. Thanks for the feedback. Victor From victor at grupocdm.com Wed Apr 12 01:35:11 2006 From: victor at grupocdm.com (Victor Bouffier) Date: Tue, 11 Apr 2006 18:35:11 -0500 Subject: [Tutor] Decorators In-Reply-To: <018401c65da3$a9b34b70$0a01a8c0@xp> References: <57aa55060604101219t242c9fe9p142eecb0e9829502@mail.gmail.com> <00a801c65d3a$ad6b3b10$0a01a8c0@xp><443B81DA.90709@tds.net> <013301c65d87$0603d380$0a01a8c0@xp> <443BF3A2.9070107@tds.net> <018401c65da3$a9b34b70$0a01a8c0@xp> Message-ID: <1144798511.6561.141.camel@elrond> On Tue, 2006-04-11 at 21:08 +0100, Alan Gauld wrote: > What was an easy to learn and use, ideal language > for medium sized to fairly large scripting projects is trying to turn > into > an all encompassing general purpose language which will be > increasingly difficult to use without falling down some new syntax > hole. Alan, I could not agree more. Python's has both simplicity in its syntax and very powerful constructs like generators and object orientation included. I would hate to eventually need a Python reference book by my side for even the simplest of projects because I could not remember $#& meant a returned value from a function when the value was a particular type (I used to work with Perl and you can get into that pretty quickly). From rfquerin at gmail.com Wed Apr 12 03:47:05 2006 From: rfquerin at gmail.com (Richard Querin) Date: Tue, 11 Apr 2006 21:47:05 -0400 Subject: [Tutor] Question About Function Arguments and Returned Results Message-ID: <7d81675b0604111847p4e407104h27638c53d1e97547@mail.gmail.com> I'm a relative newbie writing a function that carries out a bunch of calculations. The function requires about 4 or 5 numeric arguments as input but the data returned from the function call is about a dozen numbers in addition to a list of strings and a fairly long list of numbers (200+). My question is whether to create an class object beforehand and pass this into and out of the function, or to just keep things simple and pass in the 4 arguments and return a simple list object containing the numbers and lists of strings and numbers. Is there any benefit to using an class object for this? I don't want to limit what I can do with the returned data later. I want to be able to display the results of this function in different ways later on. I'm going to have a lot of functions of this type and I know I will have to keep the format of the results list object well documented in order to keep track of what is returned when I look at the code 6 months from now. Is a simple list the best way? or a class object? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060411/5a70883f/attachment.htm From hokkakada at khmeros.info Wed Apr 12 03:51:03 2006 From: hokkakada at khmeros.info (kakada) Date: Wed, 12 Apr 2006 08:51:03 +0700 Subject: [Tutor] encoding Message-ID: <443C5D07.90607@khmeros.info> Hi all, Does anybody know how to decode to Windows Latin ("ANSI") I know how to decode to utf-8: stringinput = stringinput.decode('utf-8') but while I use stringinput = stringinput.decode('ANSI') LookupError: unknown encoding: ANSI so what is the correct way to do it? Thanks and !Happy Khmer New Year! kakada From kent37 at tds.net Wed Apr 12 04:17:50 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 11 Apr 2006 22:17:50 -0400 Subject: [Tutor] Extending a list within a list comprehension In-Reply-To: <1144793758.6561.108.camel@elrond> References: <1144793758.6561.108.camel@elrond> Message-ID: <443C634E.2050804@tds.net> Victor Bouffier wrote: > If the second element in each array passed as x is of variable length > (that is, it has a different element count than three, in this case), > the program needs to extend the list instead. Without list > comprehensions, and the added capability to utilize and sized list as a > second element, my code ended up looking like the following: > > temporal = [] > for x in elements: > lst = [x[0], description[x[0]]] > lst.extend(x[1]) > temporal.append([x[1][1], lst]) > temporal.sort() > temporal.reverse() # sort descending > elements = [ x[1] for x in temporal ] > > Is there a way to use list comprehensions to append or extend the array > as needed by the second code listing? I think you are looking for temporal = [ [x[0], description[x[0]]] + x[1] for x in elements ] but I would make two steps, one for the sort using just [ (x[0], x) for x in elements ] then when you pick the data back out you can format it how you like. Kent PS to John: the original solution is using DSU, aka Schwarzian Transform From rfquerin at gmail.com Wed Apr 12 04:27:26 2006 From: rfquerin at gmail.com (Richard Querin) Date: Tue, 11 Apr 2006 22:27:26 -0400 Subject: [Tutor] Question About Function Arguments and Returned Results In-Reply-To: <443C63D5.9060406@tds.net> References: <7d81675b0604111847p4e407104h27638c53d1e97547@mail.gmail.com> <443C63D5.9060406@tds.net> Message-ID: <7d81675b0604111927r133ad3ebvf2c9b49b375efd29@mail.gmail.com> On 4/11/06, Kent Johnson wrote: > > There is no need to pass the class object in to the function, you can > create it in the function and return it. A class might be nice because > it gives names to the various values. A dict can also be used for this. > Do what feels right :-) To be more specific, I'm going to have probably 6 functions that do similar things. They all take slightly different arguments, they all do slightly different calculations, but the results of all the functions are the same format. So I guess it makes sense to use a class. Now, when you say 'create it in the function', you mean create the class instance inside the function and return that instance? The class itself is defined somewhere else in the module containing the functions so that all the functions have access to it. (Total newb to python and classes so sorry if that's a stupid question). -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060411/349c4c84/attachment.htm From kent37 at tds.net Wed Apr 12 04:32:35 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 11 Apr 2006 22:32:35 -0400 Subject: [Tutor] Question About Function Arguments and Returned Results In-Reply-To: <7d81675b0604111927r133ad3ebvf2c9b49b375efd29@mail.gmail.com> References: <7d81675b0604111847p4e407104h27638c53d1e97547@mail.gmail.com> <443C63D5.9060406@tds.net> <7d81675b0604111927r133ad3ebvf2c9b49b375efd29@mail.gmail.com> Message-ID: <443C66C3.40101@tds.net> Richard Querin wrote: > > > On 4/11/06, *Kent Johnson* > wrote: > > > There is no need to pass the class object in to the function, you can > create it in the function and return it. A class might be nice because > it gives names to the various values. A dict can also be used for this. > Do what feels right :-) > > > To be more specific, I'm going to have probably 6 functions that do > similar things. They all take slightly different arguments, they all do > slightly different calculations, but the results of all the functions > are the same format. So I guess it makes sense to use a class. Now, when Yes, that's a good argument for a class. > you say 'create it in the function', you mean create the class instance > inside the function and return that instance? The class itself is > defined somewhere else in the module containing the functions so that > all the functions have access to it. (Total newb to python and classes > so sorry if that's a stupid question). Right, create the class instance in the function. class ReturnedValue(object): def __init__(self, value): self.value = value def myFunction(x, y, z, w): return ReturnedValue(x+y+z+w) Season to taste ;) Kent From hokkakada at khmeros.info Wed Apr 12 05:19:22 2006 From: hokkakada at khmeros.info (kakada) Date: Wed, 12 Apr 2006 10:19:22 +0700 Subject: [Tutor] dictionary datatype Message-ID: <443C71BA.3040608@khmeros.info> Hello all, For example, I have a dictionary: dict1 = { 0x2018:u'k', 0x2019:u'd'} I assign: n = 0x2018 print dict1[n] Then: KeyError: '0x2018' But I can call directly: print dict1[0x2018] So, what is wrong with this? How can I solve it? Thx kakada From jason.massey at gmail.com Wed Apr 12 05:37:59 2006 From: jason.massey at gmail.com (Jason Massey) Date: Tue, 11 Apr 2006 22:37:59 -0500 Subject: [Tutor] dictionary datatype In-Reply-To: <443C71BA.3040608@khmeros.info> References: <443C71BA.3040608@khmeros.info> Message-ID: <7e3eab2c0604112037m4e00810ck7f3d526a9dafa8cc@mail.gmail.com> Works for me: >>> dict1 = { 0x2018:u'k', 0x2019:u'd'} >>> n = 0x2018 >>> print dict1[n] k >>> On 4/11/06, kakada wrote: > > Hello all, > > For example, I have a dictionary: > dict1 = { 0x2018:u'k', 0x2019:u'd'} > > I assign: > n = 0x2018 > print dict1[n] > > Then: > KeyError: '0x2018' > > But I can call directly: > print dict1[0x2018] > > So, what is wrong with this? How can I solve it? > > Thx > > kakada > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060411/2a70a60e/attachment.htm From victor at grupocdm.com Wed Apr 12 07:17:35 2006 From: victor at grupocdm.com (Victor Bouffier) Date: Wed, 12 Apr 2006 00:17:35 -0500 Subject: [Tutor] Extending a list within a list comprehension In-Reply-To: <443C634E.2050804@tds.net> References: <1144793758.6561.108.camel@elrond> <443C634E.2050804@tds.net> Message-ID: <1144819055.12108.15.camel@elrond> On Tue, 2006-04-11 at 22:17 -0400, Kent Johnson wrote: > Victor Bouffier wrote: > > > If the second element in each array passed as x is of variable length > > (that is, it has a different element count than three, in this case), > > the program needs to extend the list instead. Without list > > comprehensions, and the added capability to utilize and sized list as a > > second element, my code ended up looking like the following: > > > > temporal = [] > > for x in elements: > > lst = [x[0], description[x[0]]] > > lst.extend(x[1]) > > temporal.append([x[1][1], lst]) > > temporal.sort() > > temporal.reverse() # sort descending > > elements = [ x[1] for x in temporal ] > > > > Is there a way to use list comprehensions to append or extend the array > > as needed by the second code listing? > > I think you are looking for > temporal = [ [x[0], description[x[0]]] + x[1] for x in elements ] > Hi Kent, I try this one and get the following error: TypeError: list objects are unhashable I figured it is because of the x[0] element being used as a dict key. Can you explain further where this error comes from? Are you getting it too? > but I would make two steps, one for the sort using just > [ (x[0], x) for x in elements ] > You are right. This is cleaner and not a big deal to do in two steps. However for the issue at hand, it still keeps x as a two element list: [codigo, [ cant, importe, porc]], which I would like to have extended: [codigo, cant, importe, porc] It is not a big deal. That is why I finally went with the longer version Alan suggested. Before the sort I get a two element list, the second element being the list I finally want as output. > then when you pick the data back out you can format it how you like. > Right. After the sort I just get that second element in another list comprehension lines = [ x[1] for x in temp ] Thanks for your help. Victor > > Kent > > PS to John: the original solution is using DSU, aka Schwarzian Transform > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From victor at grupocdm.com Wed Apr 12 07:30:56 2006 From: victor at grupocdm.com (Victor Bouffier) Date: Wed, 12 Apr 2006 00:30:56 -0500 Subject: [Tutor] dictionary datatype In-Reply-To: <7e3eab2c0604112037m4e00810ck7f3d526a9dafa8cc@mail.gmail.com> References: <443C71BA.3040608@khmeros.info> <7e3eab2c0604112037m4e00810ck7f3d526a9dafa8cc@mail.gmail.com> Message-ID: <1144819856.12108.26.camel@elrond> On Tue, 2006-04-11 at 22:37 -0500, Jason Massey wrote: > Works for me: > > >>> dict1 = { 0x2018:u'k', 0x2019:u'd'} > >>> n = 0x2018 > >>> print dict1[n] > k > >>> > > On 4/11/06, kakada wrote: > Hello all, > > For example, I have a dictionary: > dict1 = { 0x2018:u'k', 0x2019:u'd'} > > I assign: > n = 0x2018 > print dict1[n] > > Then: > KeyError: '0x2018' > > But I can call directly: > print dict1[0x2018] > > So, what is wrong with this? How can I solve it? > > Thx > > kakada > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor Look into the value of n after assignment: In [285]: n = 0x2018 In [286]: n Out[286]: 8216 n is taken as an integer containing the decimal number 8216, which in hex is represented as 0x2018. Try again to see if you did not mistakenly typed dict1['0x2018'] or else defined n as such. If you try dict1[n], dict1[0x2018], or dict1[8216] you get a correct result, since the integer variable 'n' contains that value. Trying dict1['0x2016'] gives you the error because the key does not exist. define dict1 as: dict1 = { 0x2018:u'k', 0x2019:u'd'} and then display it whole: In [299]: print dict1 {8216: u'k', 8217: u'd'} Can you see your '0x2018' key anywhere? HTH Victor From kaushalshriyan at gmail.com Wed Apr 12 07:46:50 2006 From: kaushalshriyan at gmail.com (Kaushal Shriyan) Date: Wed, 12 Apr 2006 11:16:50 +0530 Subject: [Tutor] Tuples Message-ID: <6b16fb4c0604112246m745f4e03ya59d6fe45eb6fe8f@mail.gmail.com> Hi All I am referring to http://www.ibiblio.org/obp/thinkCSpy/chap09.htm I did not understood the below Section at all :( 9.3 Tuples as return values Functions can return tuples as return values. For example, we could write a function that swaps two parameters: def swap(x, y): return y, x Then we can assign the return value to a tuple with two variables: a, b = swap(a, b) In this case, there is no great advantage in making swap a function. In fact, there is a danger in trying to encapsulate swap, which is the following tempting mistake: def swap(x, y): # incorrect version x, y = y, x If we call this function like this: swap(a, b) then a and x are aliases for the same value. Changing xinside swap makes x refer to a different value, but it has no effect on a in __main__. Similarly, changing y has no effect on b. This function runs without producing an error message, but it doesn't do what we intended. This is an example of a semantic error. As an exercise, draw a state diagram for this function so that you can see why it doesn't work. Thanks in Advance Regards Kaushal From dyoo at hkn.eecs.berkeley.edu Wed Apr 12 10:44:07 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 12 Apr 2006 01:44:07 -0700 (PDT) Subject: [Tutor] Tuples / Critique of How to Think like a Computer Scientist [Was: Re: Tuples] In-Reply-To: <6b16fb4c0604112246m745f4e03ya59d6fe45eb6fe8f@mail.gmail.com> References: <6b16fb4c0604112246m745f4e03ya59d6fe45eb6fe8f@mail.gmail.com> Message-ID: On Wed, 12 Apr 2006, Kaushal Shriyan wrote: > I am referring to http://www.ibiblio.org/obp/thinkCSpy/chap09.htm > I did not understood the below Section at all :( Hi Kaushal, Ok, let's trying starting somewhere else and see at what point you get stuck. It'll also give you a chance to practice what you do understand so far. Are you comfortable about being able to return things besides numbers or strings from a function? In particular, do you have any experience writing functions that return tuples? For example, could you write a function that takes two elements, and wraps its input in a tuple? Let's call this function something, like wrap(). We'd expect wrap() to do something like this: wrap(5, 6) --> (5, 6) wrap("hello", "world") --> ("hello", "world") Would you be able to write a definition of wrap()? Let's start from there and see if we can isolate where you're getting stuck. Also, if you are having trouble with How to Think Like a Computer Scientist, I wouldn't be ashamed; I'm not such a big fan of it myself anymore. You might want to take a look at the other tutorials on: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers --- I'm going to rant, but not at you, but at that particular tutorial you're reading. To the others on the list: frankly, I really do not like the approach that "How to Think like a Computer Scientist" uses in marching through all the concepts it tries to teach; in a critical eye, I would say that it's doesn't do such a good job in integrating concepts, nor does it have natural flow. Am I alone in thinking this? Chapter Nine seems especially problematic in terms of flow. It's as if they say: "Here are tuples, a data structure. You should learn them. Ok, next up: here's something else you have to learn called random numbers. They have nothing to do with those tuple things what we just talked about, but we have to hurry if we're going to finish covering all the things in the glossary." Maybe I'm just reading too pessimistically into it, but the tutorial just seems to go out of its way to avoid flowing one concept into another, but instead jolting the student across the landscape. When I read part of that section you pointed out, there's one particular thing I strongly disagree with, that is, when they throw a rocky curveball with the introduction of the "broken" swap() function: ######################################## def swap(x, y): # broken x, y = y, x ######################################## The issue they try to tackle here really has nothing to do with tuples. The same "bug" occurs with: ###### def broken_swap(x, y): t = x x = y y = t ###### or, for that matter: ###### def broken_double(x): x = x * 2 ###### So I'm actually not quite sure why the tutorial is trying to make a point about this. It's an issue that should have been touched on much earlier in Chapter Five or Six, when functions and "multiple assignment" were introduced, so mixing it in with the tuple stuff just seems off-track and deliberately bewildering. And mixing it in haphazardly here risks the student thinking: "does the issue here have anything to do with this 'immutability' thing I just read about a few paragraphs ago?" From kaushalshriyan at gmail.com Wed Apr 12 11:12:15 2006 From: kaushalshriyan at gmail.com (Kaushal Shriyan) Date: Wed, 12 Apr 2006 14:42:15 +0530 Subject: [Tutor] Explanation of Lists data Type Message-ID: <6b16fb4c0604120212j75c03d54vc5e93fa576951c09@mail.gmail.com> Hi All I am referring to http://www.ibiblio.org/obp/thinkCSpy/chap08.htm 8.7 List slices -------------------------------------------- >>> list = ['a', 'b', 'c', 'd', 'e', 'f'] >>> list[1:3] ['b', 'c'] -----> I understood this >>> list[:4] --> Does this mean its list[0:4] ['a', 'b', 'c', 'd'] ----> I didnot understood this >>> list[3:] --> Does this mean its list[3:0] ['d', 'e', 'f'] ----> I didnot understood this >>> list[:] --> Does this mean its list[0:0] ['a', 'b', 'c', 'd', 'e', 'f'] ----> I didnot understood this Please explain me Thanks in Advance Regards Kaushal From ajikoe at gmail.com Wed Apr 12 11:32:10 2006 From: ajikoe at gmail.com (Pujo Aji) Date: Wed, 12 Apr 2006 11:32:10 +0200 Subject: [Tutor] Explanation of Lists data Type In-Reply-To: <6b16fb4c0604120212j75c03d54vc5e93fa576951c09@mail.gmail.com> References: <6b16fb4c0604120212j75c03d54vc5e93fa576951c09@mail.gmail.com> Message-ID: Hello, On 4/12/06, Kaushal Shriyan wrote: > > Hi All > > I am referring to http://www.ibiblio.org/obp/thinkCSpy/chap08.htm > > 8.7 List slices > -------------------------------------------- > >>> list = ['a', 'b', 'c', 'd', 'e', 'f'] > >>> list[1:3] > ['b', 'c'] -----> I understood this >>> list[:4] --> Does this mean its list[0:4] ':' here means --> from the first element to element index 4 > ['a', 'b', 'c', 'd'] ----> I didnot understood this >>> list[3:] --> Does this mean its list[3:0] ':' here means --> from element index 3 to the last element ['d', 'e', 'f'] ----> I didnot understood this >>> list[:] --> Does this mean its list[0:0] ':' here means --> from the first element to the last element > ['a', 'b', 'c', 'd', 'e', 'f'] ----> I didnot understood this Please explain me > > Thanks in Advance > > Regards > > Kaushal Hope, this helps pujo _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060412/10110cd1/attachment.html From ajikoe at gmail.com Wed Apr 12 11:34:31 2006 From: ajikoe at gmail.com (Pujo Aji) Date: Wed, 12 Apr 2006 11:34:31 +0200 Subject: [Tutor] Explanation of Lists data Type In-Reply-To: References: <6b16fb4c0604120212j75c03d54vc5e93fa576951c09@mail.gmail.com> Message-ID: Sorry for the last explanations....there is a correction! On 4/12/06, Pujo Aji wrote: > > Hello, > > > On 4/12/06, Kaushal Shriyan wrote: > > > > Hi All > > > > I am referring to http://www.ibiblio.org/obp/thinkCSpy/chap08.htm > > > > 8.7 List slices > > -------------------------------------------- > > >>> list = ['a', 'b', 'c', 'd', 'e', 'f'] > > >>> list[1:3] > > ['b', 'c'] -----> I understood this > > > > > >>> list[:4] --> Does this mean its list[0:4] > > ':' here means --> from the first element to element index 3 # > corrected > > > ['a', 'b', 'c', 'd'] ----> I didnot understood this > > > > > >>> list[3:] --> Does this mean its list[3:0] > > ':' here means --> from element index 3 to the last element > ['d', 'e', 'f'] ----> I didnot understood this > > > > >>> list[:] --> Does this mean its list[0:0] > > ':' here means --> from the first element to the last element > > > ['a', 'b', 'c', 'd', 'e', 'f'] ----> I didnot understood this > > > > > Please explain me > > > > Thanks in Advance > > > > Regards > > > > Kaushal > > > > > Hope, this helps > pujo > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060412/25042de8/attachment.htm From noufal at nibrahim.net.in Wed Apr 12 11:43:11 2006 From: noufal at nibrahim.net.in (Noufal Ibrahim) Date: Wed, 12 Apr 2006 15:13:11 +0530 (IST) Subject: [Tutor] Explanation of Lists data Type In-Reply-To: <6b16fb4c0604120212j75c03d54vc5e93fa576951c09@mail.gmail.com> References: <6b16fb4c0604120212j75c03d54vc5e93fa576951c09@mail.gmail.com> Message-ID: <38291.203.145.176.76.1144834991.squirrel@members.hcoop.net> On Wed, April 12, 2006 2:42 pm, Kaushal Shriyan wrote: >>>> list[:] --> Does this mean its list[0:0] > ['a', 'b', 'c', 'd', 'e', 'f'] ----> I didnot understood this I remember you once asked another question related to sequence slices and I mentioned the effects of slicing with no indices. You sure you're reading the replies? ;) When you leave an index in the slice argument, it will assume that you meant the maximum (or minimum as the case may be) possible. For example. >>> foo = ['a','b','c','d','e'] >>> foo[2] #Element at index 2 'c' >>> foo[2:] #Elements from index two till the end ['c', 'd', 'e'] >>> foo[:2] #Elements from the beginning till index 2. ['a', 'b'] >>> Now, when you give a [:] to the slice operator, you get a copy of the original list. This is shown below >>> bar = foo[:] #bar contains a copy of foo >>> baz = foo #baz is an alias for foo (not a copy) >>> baz is foo #Are baz and foo the same? True #Yes they are >>> bar is foo #Are bar and foo the same? False #No they're not. It's a copy remember? >>> bar[2]="test" #Change element at index 2 of bar to "test" >>> bar # Print it ['a', 'b', 'test', 'd', 'e'] # It's changed >>> foo # Has foo changed as well? ['a', 'b', 'c', 'd', 'e'] # Nope. Because bar is a copy of foo. >>> baz[2]="test" # Now we change element at index 2 of baz. >>> baz # Has baz changed? ['a', 'b', 'test', 'd', 'e'] # Of course. :) >>> foo # Has foo changed? ['a', 'b', 'test', 'd', 'e'] # Yes. Since baz was an alias of foo. >>> I trust this clears things up. Also, try not to use "list" as a variable name since it's a builtin. -- -NI From kent37 at tds.net Wed Apr 12 12:08:12 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 12 Apr 2006 06:08:12 -0400 Subject: [Tutor] Extending a list within a list comprehension In-Reply-To: <1144819055.12108.15.camel@elrond> References: <1144793758.6561.108.camel@elrond> <443C634E.2050804@tds.net> <1144819055.12108.15.camel@elrond> Message-ID: <443CD18C.2030802@tds.net> Victor Bouffier wrote: > On Tue, 2006-04-11 at 22:17 -0400, Kent Johnson wrote: >> Victor Bouffier wrote: >> >>> If the second element in each array passed as x is of variable length >>> (that is, it has a different element count than three, in this case), >>> the program needs to extend the list instead. Without list >>> comprehensions, and the added capability to utilize and sized list as a >>> second element, my code ended up looking like the following: >>> >>> temporal = [] >>> for x in elements: >>> lst = [x[0], description[x[0]]] >>> lst.extend(x[1]) >>> temporal.append([x[1][1], lst]) >>> temporal.sort() >>> temporal.reverse() # sort descending >>> elements = [ x[1] for x in temporal ] >>> >>> Is there a way to use list comprehensions to append or extend the array >>> as needed by the second code listing? >> I think you are looking for >> temporal = [ [x[0], description[x[0]]] + x[1] for x in elements ] >> > > Hi Kent, > I try this one and get the following error: > > TypeError: list objects are unhashable It's helpful if you show the traceback as well as the error message. > > I figured it is because of the x[0] element being used as a dict key. > Can you explain further where this error comes from? Are you getting it > too? No, I don't know what is causing it. Isn't x[0] a string? What is description? I didn't run the code myself. Kent From hokkakada at khmeros.info Wed Apr 12 12:20:18 2006 From: hokkakada at khmeros.info (kakada) Date: Wed, 12 Apr 2006 17:20:18 +0700 Subject: [Tutor] dictionary datatype In-Reply-To: <7e3eab2c0604112037m4e00810ck7f3d526a9dafa8cc@mail.gmail.com> References: <443C71BA.3040608@khmeros.info> <7e3eab2c0604112037m4e00810ck7f3d526a9dafa8cc@mail.gmail.com> Message-ID: <443CD462.7010103@khmeros.info> It also works for me now:) First i tried it with Konsole in Kate and it's not working. It sometimes happen with assignment statement: i += 1 (not working) i+= 1(working) but later on I tested it again and both are working. Thanks for your help, though. da Jason Massey wrote: > Works for me: > > >>> dict1 = { 0x2018:u'k', 0x2019:u'd'} > >>> n = 0x2018 > >>> print dict1[n] > k > >>> > > On 4/11/06, * kakada* > wrote: > > Hello all, > > For example, I have a dictionary: > dict1 = { 0x2018:u'k', 0x2019:u'd'} > > I assign: > n = 0x2018 > print dict1[n] > > Then: > KeyError: '0x2018' > > But I can call directly: > print dict1[0x2018] > > So, what is wrong with this? How can I solve it? > > Thx > > kakada > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From payal-python at scriptkitchen.com Wed Apr 12 16:02:01 2006 From: payal-python at scriptkitchen.com (Payal Rathod) Date: Wed, 12 Apr 2006 10:02:01 -0400 Subject: [Tutor] failing to learn python In-Reply-To: <015201c65d96$ad311370$0a01a8c0@xp> References: <20060411160645.GB5242@tranquility.scriptkitchen.com> <015201c65d96$ad311370$0a01a8c0@xp> Message-ID: <20060412140201.GA8795@tranquility.scriptkitchen.com> On Tue, Apr 11, 2006 at 07:35:15PM +0100, Alan Gauld wrote: > Python is a general programmjing language great for bigger jobs. If But what does Python excel at. That si my main question. Whatevfer I think of I can already do or know a way to do in shell. I am not getting where would I need Python. e.g. for parsing log files with regex I rather use egrep than Python. For counting the number of mails received for a user I use awk, where can I use Python. Everyone says it is a "general programming language", but what in the world is a "general programming language"? The Python video said that one can take this language to good level in 1 afternoon, for me it has been 2 months and more. What is wrong? With warm regards, -Payal From kent37 at tds.net Wed Apr 12 16:23:16 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 12 Apr 2006 10:23:16 -0400 Subject: [Tutor] failing to learn python In-Reply-To: <20060412140201.GA8795@tranquility.scriptkitchen.com> References: <20060411160645.GB5242@tranquility.scriptkitchen.com> <015201c65d96$ad311370$0a01a8c0@xp> <20060412140201.GA8795@tranquility.scriptkitchen.com> Message-ID: <443D0D54.7090105@tds.net> Payal Rathod wrote: > On Tue, Apr 11, 2006 at 07:35:15PM +0100, Alan Gauld wrote: >> Python is a general programmjing language great for bigger jobs. If > > But what does Python excel at. That si my main question. Whatevfer I > think of I can already do or know a way to do in shell. I am not getting > where would I need Python. > e.g. for parsing log files with regex I rather use egrep than Python. > For counting the number of mails received for a user I use awk, where It's possible that for the jobs you need to do, you are already using the best tools. If you know shell, egrep and awk, they are probably better than Python at doing the things they do. For me, I don't know those specialized tools and I have chosen not to learn them because I don't often need their capabilities and Python can do what they do. Maybe not as easily to one fluent in both, but I would rather learn one tool that is widely useful than several narrow ones that I would use rarely. > can I use Python. Everyone says it is a "general programming language", > but what in the world is a "general programming language"? A programming language that can be used for a wide variety of tasks, rather than being specialized to a particular domain. Some things that Python can be used for that might be hard with the tools you know: mailing list manager (Mailman) spam filter (SpamBayes) distributed file sharing (BitTorrent) dynamic web site (Django, TurboGears, etc, etc) web scraping (urllib, BeautifulSoup) XML processing (ElementTree, etc) GUIs (Tkinter, wxPython, etc) Also take a look at some of the case studies here: http://www.python.org/about/success/ or search sourceforge.net for Python projects. Kent From hugonz-lists at h-lab.net Wed Apr 12 16:57:13 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Wed, 12 Apr 2006 08:57:13 -0600 Subject: [Tutor] encoding In-Reply-To: <443C5D07.90607@khmeros.info> References: <443C5D07.90607@khmeros.info> Message-ID: <443D1549.6010802@h-lab.net> kakada wrote: > LookupError: unknown encoding: ANSI > > so what is the correct way to do it? > stringinput.encode('latin_1') works for me. Do a Google search for Python encodings, and you will find what the right names for the encodings are. http://docs.python.org/lib/standard-encodings.html Hugo From hugonz-lists at h-lab.net Wed Apr 12 17:00:27 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Wed, 12 Apr 2006 09:00:27 -0600 Subject: [Tutor] dictionary datatype In-Reply-To: <443C71BA.3040608@khmeros.info> References: <443C71BA.3040608@khmeros.info> Message-ID: <443D160B.4040403@h-lab.net> kakada wrote: > I assign: > n = 0x2018 > print dict1[n] > > Then: > KeyError: '0x2018' > Notice the error menstions a *string*. You probably mistyped it, not in the email, but in your actual program. Hugo From alan.gauld at freenet.co.uk Wed Apr 12 19:01:15 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 12 Apr 2006 18:01:15 +0100 Subject: [Tutor] dictionary datatype References: <443C71BA.3040608@khmeros.info> Message-ID: <01fc01c65e52$b5fc0700$0a01a8c0@xp> > For example, I have a dictionary: > dict1 = { 0x2018:u'k', 0x2019:u'd'} > > I assign: > n = 0x2018 > print dict1[n] > > Then: > KeyError: '0x2018' The error is complaining that you are using a string as a key. Are you sure you aren't assigning n = '0x2018' Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Wed Apr 12 19:07:59 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 12 Apr 2006 18:07:59 +0100 Subject: [Tutor] Tuples / Critique of How to Think like a Computer Scientist[Was: Re: Tuples] References: <6b16fb4c0604112246m745f4e03ya59d6fe45eb6fe8f@mail.gmail.com> Message-ID: <020601c65e53$a6d5e510$0a01a8c0@xp> > I'm going to rant, but not at you, but at that particular tutorial you're > reading. To the others on the list: frankly, I really do not like the > approach that "How to Think like a Computer Scientist" uses in marching > through all the concepts it tries to teach; in a critical eye, I would say > that it's doesn't do such a good job in integrating concepts, nor does it > have natural flow. Am I alone in thinking this? I shouldn't comment at all I suppose but I personally think CSpy is a reasonable CS text if you were using it with a (human) tutor to provide context. That is, it teaches the CS concepts well enough but doesn't provide much context. But living in a glass house as I do, I don't like to throw stones at other tutorials so I'll leave it at that! Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Wed Apr 12 19:17:17 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 12 Apr 2006 18:17:17 +0100 Subject: [Tutor] Explanation of Lists data Type References: <6b16fb4c0604120212j75c03d54vc5e93fa576951c09@mail.gmail.com> Message-ID: <020a01c65e54$f31a51d0$0a01a8c0@xp> Kaushal, > 8.7 List slices You might find it worth going through the official tutor section on slicing, it explains the various forms quite well. >>> list[:4] --> Does this mean its list[0:4] Sort of, it means from *the beginning* to 4. >>> list[3:] --> Does this mean its list[3:0] No it means from 3 to *the end* >>> list[:] --> Does this mean its list[0:0] No, it means from *the beginning* to *the end* These are all just shortcut conventions that you need to learn. Another one that can be confusing is negative slices: list[-3:] means from the -3 position(ie 3 from the end) to the end list[3:-3] means from the 3rd position to the -3 position I find it helps to thingk of the collection organised as a ring with the counter sitting between the items. Thus zero sits between the first and last items. Unfortunately this breaks down if you do list [-3:3] which is an error but is not reported as such, rathger it returns an empty list! Basically, play with them a lot and you will get used to their little oddities, the huge benefits outweigh the occasional confusion. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From dyoo at hkn.eecs.berkeley.edu Wed Apr 12 21:23:01 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 12 Apr 2006 12:23:01 -0700 (PDT) Subject: [Tutor] failing to learn python In-Reply-To: <20060412140201.GA8795@tranquility.scriptkitchen.com> References: <20060411160645.GB5242@tranquility.scriptkitchen.com> <015201c65d96$ad311370$0a01a8c0@xp> <20060412140201.GA8795@tranquility.scriptkitchen.com> Message-ID: On Wed, 12 Apr 2006, Payal Rathod wrote: > can I use Python. Everyone says it is a "general programming language", > but what in the world is a "general programming language"? One idea behind a "general purpose programming language" is that it's not specialized toward anything in particular. It's meant to be malliable and a bit formless. A programmer makes what one can with it. > e.g. for parsing log files with regex I rather use egrep than Python. > For counting the number of mails received for a user I use awk And for text parsing and processing, I think that's perfectly right, and you're using the best tools for that application. (Actually, you might want to look into Perl, which integrates regexes very deeply into its language.) You're more effective with those tools because awk and sed are domain-specific: they are specifically designed to do text processing very well. You can think of Python as a tool-maker. If you already are working in solely in one domain, where there are already plenty of tools already written for you, then you may not get so much out of a general-purpose language. This point is made in an amusing way in Literate Programming: http://www-cs-faculty.stanford.edu/~uno/lp.html The story goes that Knuth, when given the common-words problem, wrote up beautiful algorithm, designed a cool data structure to support it, and wrote it all in literate programming style. Bentley, on the other hand, used awk and other shell utilities, and in a few minutes, got a more correct solution. *grin* > But what does Python excel at. That si my main question. Whatevfer I > think of I can already do or know a way to do in shell. I am not getting > where would I need Python. But _someone_ had to write awk and sed: they didn't come fully-formed from the head of Zeus. That's what a general-purpose language like Python is for. You wouldn't write a web application in sed or awk because those two languages have limitations on what they're allowed to touch. > The Python video said that one can take this language to good level in 1 > afternoon, for me it has been 2 months and more. What is wrong? No, you're not wrong. Anyone who says that programming can be learned in an afternoon is selling something. *grin* From intermezzoooh at gmail.com Wed Apr 12 22:17:46 2006 From: intermezzoooh at gmail.com (Jesse) Date: Wed, 12 Apr 2006 14:17:46 -0600 Subject: [Tutor] n00b question: dictionaries and functions. Message-ID: Hey, this should be an easy question for you guys. I'm writing my first program (which Bob, Alan, and Danny have already helped me with--thanks, guys!), and I'm trying to create a simple command-line interface. I have a good portion of the program's "core functions" already written, and I want to create a dictionary of functions. When the program starts up, a global variable named command will be assigned the value of whatever the user types: command = raw_input("Cmd > ") If command is equivalent to a key in the dictionary of functions, that key's function will be called. Here's an example that I wrote for the sake of isolating the problem: def add(): x = float(raw_input("Enter a number: ")) y = float(raw_input("And a second number: ")) print x + y def subtract(): x = float(raw_input("Enter a number: ")) y = float(raw_input("And a second number: ")) print x - y commands = {"add": add(), "subtract": subtract()} Now, before I could even get to writing the while loop that would take a command and call the function associated with that command in the commands dictionary, I ran this bit of code and, to my dismay, both add() and subtract() were called. So I tried the following: def add(x, y): x = float(raw_input("Enter a numer: ")) y = float(raw_input("And a second number: ")) add = add() When I ran this, add() was called. I don't understand why, though. Surely I didn't call add(), I merely stored the function call in the name add. I would expect the following code to call add: def add(x, y): x = float(raw_input("Enter a numer: ")) y = float(raw_input("And a second number: ")) add = add() add Can someone clear up my misunderstanding here? I don't want to end up writing a long while loop of conditional statements just to effect a command-line interface. -Jesse -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060412/d91a79de/attachment.htm From dyoo at hkn.eecs.berkeley.edu Wed Apr 12 22:37:13 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 12 Apr 2006 13:37:13 -0700 (PDT) Subject: [Tutor] n00b question: dictionaries and functions. In-Reply-To: References: Message-ID: On Wed, 12 Apr 2006, Jesse wrote: > def add(): > x = float(raw_input("Enter a number: ")) > y = float(raw_input("And a second number: ")) > print x + y > def subtract(): > x = float(raw_input("Enter a number: ")) > y = float(raw_input("And a second number: ")) > print x - y > > > commands = {"add": add(), "subtract": subtract()} > > > Now, before I could even get to writing the while loop that would take a > command and call the function associated with that command in the > commands dictionary, I ran this bit of code and, to my dismay, both > add() and subtract() were called. Hi Jesse, Ah! Yes, that's happening because there are parens in there that are causing the functions to fire off prematurely. For example, let's say we have defined a function: ###### >>> def test_function(x): ... return x * x ... ###### (I should give it a better name like square(), but let's ignore that for the moment.) If we just name the function, we'll get back a function value: ###### >>> test_function ###### This is a value that can be stored in containers, just like any other Python value. But as soon as we do use parentheses, Python will try to call the function: ###### >>> test_function() Traceback (most recent call last): File "", line 1, in TypeError: test_function() takes exactly 1 argument (0 given) ###### If we go back to the place where the commands dictionary is being built: commands = {"add": add(), "subtract": subtract()} do you see what needs to be fixed to associate those strings to function values? Best of wishes! From bgailer at alum.rpi.edu Wed Apr 12 22:40:56 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed, 12 Apr 2006 13:40:56 -0700 Subject: [Tutor] n00b question: dictionaries and functions. In-Reply-To: References: Message-ID: <443D65D8.5030104@alum.rpi.edu> Jesse wrote: > Hey, this should be an easy question for you guys. I'm writing my > first program (which Bob, Alan, and Danny have already helped me > with--thanks, guys!), and I'm trying to create a simple command-line > interface. I have a good portion of the program's "core functions" > already written, and I want to create a dictionary of functions. When > the program starts up, a global variable named command will be > assigned the value of whatever the user types: > > command = raw_input("Cmd > ") > > If command is equivalent to a key in the dictionary of functions, that > key's function will be called. Here's an example that I wrote for the > sake of isolating the problem: > > > def add(): > x = float(raw_input("Enter a number: ")) > y = float(raw_input("And a second number: ")) > print x + y > def subtract(): > x = float(raw_input("Enter a number: ")) > y = float(raw_input("And a second number: ")) > print x - y > > > commands = {"add": add(), "subtract": subtract()} > > > > Now, before I could even get to writing the while loop that would take > a command and call the function associated with that command in the > commands dictionary, I ran this bit of code and, to my dismay, both > add() and subtract() were called. So I tried the following: > > def add(x, y): > x = float(raw_input("Enter a numer: ")) > y = float(raw_input("And a second number: ")) > add = add() > > When I ran this, add() was called. I don't understand why, though. > Surely I didn't call add(), I merely stored the function call in the > name add. I would expect the following code to call add: > > def add(x, y): > x = float(raw_input("Enter a numer: ")) > y = float(raw_input("And a second number: ")) > add = add() > add > > Can someone clear up my misunderstanding here? I don't want to end up > writing a long while loop of conditional statements just to effect a > command-line interface. "stored the function call" NO - this mixing 2 things. What you want is to store a reference to the function, then call the function thru its reference in response to user input. add is a reference to the function. add() calls (runs) the function. commands = {"add": add, "subtract": subtract} # stores function references command = raw_input("Cmd > ") if command in commands: commands[command]() # retrieve a function reference and calls it. From patriciap.gu at gmail.com Wed Apr 12 22:56:12 2006 From: patriciap.gu at gmail.com (Patricia) Date: Wed, 12 Apr 2006 20:56:12 +0000 (UTC) Subject: [Tutor] Problems when displaying numbers Message-ID: Hi, This is my code: conn = MySQLdb.connect(host = "localhost", user = "root", passwd = "", db ="mydb") cursor = conn.cursor() cursor.execute("""SELECT h, k, l, m, s, t FROM targets WHERE target_name = %s""", (target)) result = cursor.fetchone() alist = helperfunc.calc_numbers(list(result)) # read below cursor.close() conn.close() for li in alist: if li == '': s = s + "" else: s = s + "%s" % li # problem here calc_numbers is a method in helperfunc.py that takes the list of values that I retrieved from the database and then does some calculations (addition & division) and also replaces a specific number with ''. When I display the results, most of the times everything looks right, BUT sometimes I get i.e. 15%% instead of 15. I don't understand why %% is added to some of the numbers being displayed. I've noticed that the numbers that show %% are the ones that have been modified in the calc_numbers method. The numbers that are not touched in that method, don't show it. When I printed the list obatined from the calc_numbers method, the numbers that have not been touched have an L at the end (i'm assuming it stands for long). As I said these numbers are displayed correctly all the time. I'm really hoping someone can point me to the right direction because I've tried different things and nothing seems to work. Another quick question, my page shows several drop down boxes with pre-selected values. When I submit the form or open the page, the preselected values appear, but when I press the reload button, they don't. (Mozilla) Thanks, Patricia From alan.gauld at freenet.co.uk Wed Apr 12 23:15:59 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 12 Apr 2006 22:15:59 +0100 Subject: [Tutor] failing to learn python References: <20060411160645.GB5242@tranquility.scriptkitchen.com><015201c65d96$ad311370$0a01a8c0@xp> <20060412140201.GA8795@tranquility.scriptkitchen.com> Message-ID: <024401c65e76$4c013fe0$0a01a8c0@xp> > can I use Python. Everyone says it is a "general programming language", > but what in the world is a "general programming language"? Others have already answered this. I'll add a few other comments. A general purpose language is one that in theory means you don't need any others. It can do anything. It may not do everything as well as special purppose tools like sed but it can do anything. Where sys admins typically use tools like Python is in producing well formatted reports, particularly nowadays on web pages. Or maybe you have to do a lot of SQL admin on a database and python's database links will allow you to write a single script which is easier to maintain than lots of separate ones. Where python is likely to be more useful to you is where you have long shell scripts rather than long awk/sed scripts. Shell scripts are fine as application launchers but if you need to process the output of commands and have long multi way if/else chains the Python may offer better facilities. But if you are working exclusively on Unix and you know the 400+ Unix commands well you may very well have little use for Python. I certainly don;t use it for much sys admin stuff, I tend to use it to write GUI front ends for the tools, or for writing networking applications or testing new protocols. One example where a tool like Python may be of use to you would be in building an interactive diff tool. The standard diff tools in Unix only allow comparison of 3 files, but if you have 6 or 8 versions you need to compare then using python you can build your own diff tool to compare 8 files if needed. And with the low cost of disk space file management of concurrent versions is becoming an issue for many admins... > The Python video said that one can take this language to good level in 1 > afternoon, for me it has been 2 months and more. What is wrong? Probably nothing. That claim refers to someone who is already fluent in another general purpose language like C or Java. Such a programmer can indeed get to the point where they can write a reasonable program in Python after a few hours with the official tutorial. A beginner will take more like 4-6 months to get really comfortable. You probably fit somewhere in the middle depending on your awk or shell skill level. If your awk action clauses run to 10s of lines then you probably do know enough to learn Python quickly but if you typically only write 3 or 4 lines in an action clause then Python will be more challenging. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Wed Apr 12 23:52:09 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 12 Apr 2006 22:52:09 +0100 Subject: [Tutor] failing to learn python References: <20060411160645.GB5242@tranquility.scriptkitchen.com> <015201c65d96$ad311370$0a01a8c0@xp><20060412140201.GA8795@tranquility.scriptkitchen.com> <443D0D54.7090105@tds.net> Message-ID: <024a01c65e7b$59452590$0a01a8c0@xp> > the best tools. If you know shell, egrep and awk, they are probably better > than Python at doing the things they do. > > For me, I don't know those specialized tools and I have chosen not to > learn them because I don't often need their capabilities and Python can do > what they do. I must admit I use a myriad of tools, including several text editors. Its one of the few areas where I disagree with Hunt & Thomas in "the Pragmatic Programmer", they advocate choosing one editor and using it exclusively, I use emacs, vim, xedit and even ed on a daily basis (OK ed only once a month or so!) But I also use awk and sed weekly. I've also don't think I've ever worked on a production project that used less than 5 languages and some have used 12 or more. Awk in particular is one that I think every programmer should know, at least at a basic level, in the same way as everyone should learn a little Tcl and a little Lisp(*). These languages are sufficiently different to mainstream in structure that we can learn a lot about how to create programs by looking at their approach. It's fair to say that we probably wouldn't have ElementTree, BeautifulSoup, SAX or any other event driven parsers today if it weren't for awk and its elegant approach to working with text files. (*)For those building business apps I'd add COBOL to the list. It's not just history that makes it still the most widely used language on the planet according to Infoweek. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From carlos at carlosbenevides.com Thu Apr 13 01:45:47 2006 From: carlos at carlosbenevides.com (Carlos Benevides) Date: Wed, 12 Apr 2006 16:45:47 -0700 Subject: [Tutor] String question. In-Reply-To: <44367CCC.6010309@carlosbenevides.com> References: <44367CCC.6010309@carlosbenevides.com> Message-ID: <443D912B.7060108@carlosbenevides.com> All, I have a problem/question I'd like to pose to you guys on how best to accomplish the following. I have a string that will vary in size, what I would like to do is split into n size chunks. I am also not sure how best to represent the chunks. For example, say I have a len(s) = 200 chars. I'd like to get one chunk with 160 of those chars and the remaining 40 in a second. Likewise, if I have a len(s) = 350, I'd like two chunks of 160 and a 3rd with the remainder. I don't know what it would best way to accomplish this. I have the idea of converting the string to a list of chars loop through it until size is met, create a new string with s=s[:160], then start again, and so on. Is this the only way to accomplish this? Or is there a more elegant/clever way? Thank you :) From kent37 at tds.net Thu Apr 13 03:06:19 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 12 Apr 2006 21:06:19 -0400 Subject: [Tutor] String question. In-Reply-To: <443D912B.7060108@carlosbenevides.com> References: <44367CCC.6010309@carlosbenevides.com> <443D912B.7060108@carlosbenevides.com> Message-ID: <443DA40B.8020004@tds.net> Carlos Benevides wrote: > All, > > I have a problem/question I'd like to pose to you guys on how best to > accomplish the following. I have a string that will vary in size, what > I would like to do is split into n size chunks. I am also not sure how > best to represent the chunks. For example, say I have a len(s) = 200 > chars. I'd like to get one chunk with 160 of those chars and the > remaining 40 in a second. Likewise, if I have a len(s) = 350, I'd like > two chunks of 160 and a 3rd with the remainder. > > I don't know what it would best way to accomplish this. I have the idea > of converting the string to a list of chars loop through it until size > is met, create a new string with s=s[:160], then start again, and so > on. Is this the only way to accomplish this? Or is there a more > elegant/clever way? Here is a good way and links to more ideas: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/425044 Kent From wescpy at gmail.com Thu Apr 13 05:24:20 2006 From: wescpy at gmail.com (w chun) Date: Wed, 12 Apr 2006 20:24:20 -0700 Subject: [Tutor] Problems when displaying numbers In-Reply-To: References: Message-ID: <78b3a9580604122024o2a16627fu8fae0d2fe32c13a1@mail.gmail.com> hi patricia, it would be really helpful to see an example of 'result' before and after the call to calc_numbers() as well as the code for calc_numbers if possible. this will likely reveal the problem that you are having. thanks, -wesley On 4/12/06, Patricia wrote: > Hi, > > This is my code: > > conn = MySQLdb.connect(host = "localhost", user = "root", passwd = "", > db ="mydb") > cursor = conn.cursor() > cursor.execute("""SELECT h, k, l, m, s, t > FROM targets WHERE target_name = %s""", (target)) > result = cursor.fetchone() > > alist = helperfunc.calc_numbers(list(result)) # read below > > cursor.close() > conn.close() > > for li in alist: > if li == '': > s = s + "" > else: > s = s + "%s" % li # problem here > > > calc_numbers is a method in helperfunc.py that takes the list of values > that I retrieved from the database and then does some calculations > (addition & division) and also replaces a specific number with ''. > > When I display the results, most of the times everything looks right, BUT > sometimes I get i.e. 15%% instead of 15. I don't understand why %% is > added to some of the numbers being displayed. I've noticed that the numbers > that show %% are the ones that have been modified in the calc_numbers > method. The numbers that are not touched in that method, don't show it. > When I printed the list obatined from the calc_numbers method, the > numbers that have not been touched have an L at the end (i'm assuming > it stands for long). As I said these numbers are displayed correctly > all the time. I'm really hoping someone can point me to the right direction > because I've tried different things and nothing seems to work. > > Another quick question, my page shows several drop down boxes with > pre-selected values. When I submit the form or open the page, the > preselected values appear, but when I press the reload button, > they don't. (Mozilla) > > Thanks, > Patricia > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From oasf2004 at yahoo.com Thu Apr 13 05:28:39 2006 From: oasf2004 at yahoo.com (Hoffmann) Date: Wed, 12 Apr 2006 20:28:39 -0700 (PDT) Subject: [Tutor] Python video? Message-ID: <20060413032839.86688.qmail@web60012.mail.yahoo.com> Hi, I read this week on this forum about a kind of Python video in its website. Which view is that, and where could I find it? I search in Python website, but I didn't find it. Is it a 'demo' of the language? Thanks, Hoffmann __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From samrobertsmith at gmail.com Thu Apr 13 09:07:20 2006 From: samrobertsmith at gmail.com (linda.s) Date: Thu, 13 Apr 2006 00:07:20 -0700 Subject: [Tutor] underscore function Message-ID: <1d987df30604130007r723dee14ge146ee917c976a03@mail.gmail.com> I got a sample code and found some function definition looks like def _abc There is one underscore before the function name "abc", what does it mean? From sean.x.lee at gmail.com Thu Apr 13 09:15:30 2006 From: sean.x.lee at gmail.com (Sean Lee) Date: Thu, 13 Apr 2006 02:15:30 -0500 Subject: [Tutor] Meaning of %g ? Message-ID: What is the exact meaning of %g in Python ? >From Python ducumentation: %g: Same as "e" if exponent is greater than -4 or less than precision, "f" otherwise. But if %.mg is used, I don't see the rules. See the following example: So here it follows the above rule: >>> print "%.16g" % 0.00010481234567890 0.0001048123456789 >>> print "%.16g" % 0.000010481234567890 1.048123456789e-005 But I do not know the rules below: >>> print "%.g" % 111111111110.000010481234567890 1e+011 >>> print "%.15g" % 111111111110.000010481234567890 111111111110 >>> print "%.16g" % 111111111110.000010481234567890 111111111110 >>> print "%.17g" % 111111111110.000010481234567890 111111111110.00002 >>> print "%.32g" % 111111111110.000010481234567890 111111111110.00002 What is the difference for each %g ? >>> print "%.f" % 111111111110.000010481234567890 111111111110 >>> print "%.15f" % 111111111110.000010481234567890 111111111110.000020000000000 >>> print "%.16f" % 111111111110.000010481234567890 111111111110.0000200000000000 >>> print "%.17f" % 111111111110.000010481234567890 111111111110.00002000000000000 Why "%.15g", "%.16g", "%.17g", "%.f", "%.16f" are different ? Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060413/5e17404f/attachment.html From tim.golden at viacom-outdoor.co.uk Thu Apr 13 09:36:15 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 13 Apr 2006 08:36:15 +0100 Subject: [Tutor] underscore function Message-ID: [linda.s] | I got a sample code and found some | function definition looks like def _abc | There is one underscore before the function name "abc", | what does it mean? It's a convention which indicates to any user of the code (including the original developer) that the function is not intended to be used externally to the module (or class, or whatever) in which it is defined. Note that this is a convention only: there's absolutely nothing to stop you calling _abc (args) within your code. But the original developer intended that this function be an implementation detail that might change, or be refactored, or which assumes a particular state of data which might not obtain when called from elsewhere, etc. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From ajikoe at gmail.com Thu Apr 13 09:36:56 2006 From: ajikoe at gmail.com (Pujo Aji) Date: Thu, 13 Apr 2006 09:36:56 +0200 Subject: [Tutor] underscore function In-Reply-To: <1d987df30604130007r723dee14ge146ee917c976a03@mail.gmail.com> References: <1d987df30604130007r723dee14ge146ee917c976a03@mail.gmail.com> Message-ID: Python programmers prefer to use name convention to make method of class "looks" private. Usually they use of '_' before the private method or private attribute name. This private method like the one you mentioned def _abc is not intentionaly used outside the class other then it is used among other class methods privately. Example: class A: def __init__(self, myvar): self._myvar = myvar def _makedouble(self): '''this method is private''' self._myvar = self._myvar * 2 def printvarADouble(self): self._makedouble() print self._myvar def main(): o = A(2) o.printvarADouble() # 4 You may use def abc instead of def _abc, again it is only a convention. Hope this helps, pujo On 4/13/06, linda.s wrote: > > I got a sample code and found some > function definition looks like def _abc > There is one underscore before the function name "abc", > what does it mean? > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060413/132989e2/attachment.htm From john.brokaw at gmail.com Thu Apr 13 07:06:33 2006 From: john.brokaw at gmail.com (John Brokaw) Date: Thu, 13 Apr 2006 01:06:33 -0400 Subject: [Tutor] Can anyone help me plz Message-ID: <3e31560604122206u15c1b8eau9b16ebdf0192401b@mail.gmail.com> I'am very new to pygame, and python and any help would help me so much thx. I have no idea whats wrong the chimp.py ex. works perfect, but when I get to http://rene.f0o.com/mywiki/*LECTURETHREE* *, *I get so stuck becuz the call window = pygame.display.set_mode((468, 60)) makes a window like it should be its always not responding. Can someone please tell my why this is happending. Thanks again. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060413/b4f89d69/attachment.htm From adam.jtm30 at gmail.com Thu Apr 13 12:24:52 2006 From: adam.jtm30 at gmail.com (Adam) Date: Thu, 13 Apr 2006 11:24:52 +0100 Subject: [Tutor] String question. In-Reply-To: <443D912B.7060108@carlosbenevides.com> References: <44367CCC.6010309@carlosbenevides.com> <443D912B.7060108@carlosbenevides.com> Message-ID: How's this?: >>> s = """All, ... ... I have a problem/question I'd like to pose to you guys on how best to ... accomplish the following. I have a string that will vary in size, what ... I would like to do is split into n size chunks. I am also not sure how ... best to represent the chunks. For example, say I have a len(s) = 200 ... chars. I'd like to get one chunk with 160 of those chars and the ... remaining 40 in a second. Likewise, if I have a len(s) = 350, I'd like ... two chunks of 160 and a 3rd with the remainder. ... ... I don't know what it would best way to accomplish this. I have the idea ... of converting the string to a list of chars loop through it until size ... is met, create a new string with s=s[:160], then start again, and so ... on. Is this the only way to accomplish this? Or is there a more ... elegant/clever way? ... ... Thank you :)""" >>> l = [] >>> start = 0 >>> for i in range(160, len(s)+160, 160): ... l.append(s[start:i]) ... start = i ... >>>l ["All,\n\nI have a problem/question I'd like to pose to you guys on how best to\naccomplish the following. I have a string that will vary in size, what\nI would like", " to do is split into n size chunks. I am also not sure how\nbest to represent the chunks. For example, say I have a len(s) = 200\nchars. I'd like to get one ch", "unk with 160 of those chars and the\nremaining 40 in a second. Likewise, if I have a len(s) = 350, I'd like\ntwo chunks of 160 and a 3rd with the remainder.\n\nI d", "on't know what it would best way to accomplish this. I have the idea\nof converting the string to a list of chars loop through it until size\nis met, create a ne", '', " to do is split into n size chunks. I am also not sure how\nbest to represent the chunks. For example, say I have a len(s) = 200\nchars. I'd like to get one ch", "unk with 160 of those chars and the\nremaining 40 in a second. Likewise, if I have a len(s) = 350, I'd like\ntwo chunks of 160 and a 3rd with the remainder.\n\nI d", "on't know what it would best way to accomplish this. I have the idea\nof converting the string to a list of chars loop through it until size\nis met, create a ne", 'w string with s=s[:160], then start again, and so\non. Is this the only way to accomplish this? Or is there a more\nelegant/clever way?\n\nThank you :)'] From rschroev_nospam_ml at fastmail.fm Thu Apr 13 12:29:02 2006 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Thu, 13 Apr 2006 12:29:02 +0200 Subject: [Tutor] Explanation of Lists data Type In-Reply-To: <020a01c65e54$f31a51d0$0a01a8c0@xp> References: <6b16fb4c0604120212j75c03d54vc5e93fa576951c09@mail.gmail.com> <020a01c65e54$f31a51d0$0a01a8c0@xp> Message-ID: Alan Gauld schreef: > list [-3:3] > > which is an error but is not reported as such, rathger it returns > an empty list! I don't think this is an error, and whether it returns an empty list or not depends on the length of the list: >>> for i in range(10): print i, range(i)[-3:3] 0 [] 1 [0] 2 [0, 1] 3 [0, 1, 2] 4 [1, 2] 5 [2] 6 [] 7 [] 8 [] 9 [] -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From singletoned at gmail.com Thu Apr 13 13:51:51 2006 From: singletoned at gmail.com (Ed Singleton) Date: Thu, 13 Apr 2006 12:51:51 +0100 Subject: [Tutor] Force a value to int Message-ID: <34bb7f5b0604130451y1bb00d92p43cb591f905d1899@mail.gmail.com> Is there a particular way to force a value to be an int by either converting it with int() or returning a default value. I've ended up writing my own function to do it, but it seems like the kind of thing that would be built-in somewhere. Ed From patriciap.gu at gmail.com Thu Apr 13 13:56:36 2006 From: patriciap.gu at gmail.com (Patty) Date: Thu, 13 Apr 2006 11:56:36 +0000 (UTC) Subject: [Tutor] Problems when displaying numbers References: <78b3a9580604122024o2a16627fu8fae0d2fe32c13a1@mail.gmail.com> Message-ID: Hi: >it would be really helpful to see an example of 'result' before and >after the call to calc_numbers() as well as the code for calc_numbers if >possible. An example of result before the call to calc_numbers is: [50L, -1, 1, -1] an example after the call is: [50L, 25, ' ', 25] the code: def calc_numbers(alist): sum = 0 count = 0 for li in alist: # in the database, -1 is unspecified and 1 is null if li >= 0 and li != 1: sum = sum + int(li) if li == -1: count = count + 1 temp = 100 - sum if count != 0: number = temp/count else: number = temp for li, pos in enumerate(alist): if pos == -1: alist[li] = number elif pos == 1: alist[li] = '' return alist Thanks, Patricia From kent37 at tds.net Thu Apr 13 14:01:25 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 13 Apr 2006 08:01:25 -0400 Subject: [Tutor] Can anyone help me plz In-Reply-To: <3e31560604122206u15c1b8eau9b16ebdf0192401b@mail.gmail.com> References: <3e31560604122206u15c1b8eau9b16ebdf0192401b@mail.gmail.com> Message-ID: <443E3D95.50402@tds.net> John Brokaw wrote: > I'am very new to pygame, and python and any help would help me so much thx. > I have no idea whats wrong the chimp.py ex. works perfect, but when I > get to http://rene.f0o.com/mywiki/*LECTURETHREE* > *, *I get so stuck becuz the > call window = pygame.display.set_mode((468, 60)) makes a window like it > should be its always not responding. Can someone please tell my why this > is happending. You will increase your chance of getting an answer by doing some or all of these: - post the code you are using - post a working URL to the lecture - post on the pygame mailing list (http://www.pygame.org/wiki/info) Kent From kent37 at tds.net Thu Apr 13 14:06:34 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 13 Apr 2006 08:06:34 -0400 Subject: [Tutor] Force a value to int In-Reply-To: <34bb7f5b0604130451y1bb00d92p43cb591f905d1899@mail.gmail.com> References: <34bb7f5b0604130451y1bb00d92p43cb591f905d1899@mail.gmail.com> Message-ID: <443E3ECA.2060108@tds.net> Ed Singleton wrote: > Is there a particular way to force a value to be an int by either > converting it with int() or returning a default value. > > I've ended up writing my own function to do it, but it seems like the > kind of thing that would be built-in somewhere. No, there is no built-in for this but it's easy to write your own: def my_int(value, default): try: return int(value) except ValueError: return default Kent From alan.gauld at freenet.co.uk Thu Apr 13 14:28:54 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 13 Apr 2006 13:28:54 +0100 Subject: [Tutor] Meaning of %g ? References: Message-ID: <029001c65ef5$d4640140$0a01a8c0@xp> > What is the exact meaning of %g in Python ? Same as in C. Its the shorter of the Scientific notation (%e) or Floating Point(%f) representations. In 20 years of using C I've never needed it, I wouldn't worry too much! :-) >From Python ducumentation: > %g: Same as "e" if exponent is greater than -4 or less than > precision, "f" otherwise. Yeah, thats not very clear. > Why "%.15g", "%.16g", "%.17g", "%.f", "%.16f" are different ? Why? Because Kernighan & Ritchie made them different in C. Why? Because they did a lot of sacientific calculations and wanted the subtle variations I suspect. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From patriciap.gu at gmail.com Thu Apr 13 15:38:09 2006 From: patriciap.gu at gmail.com (Patricia) Date: Thu, 13 Apr 2006 13:38:09 +0000 (UTC) Subject: [Tutor] Problems when displaying numbers References: <78b3a9580604122024o2a16627fu8fae0d2fe32c13a1@mail.gmail.com> Message-ID: > An example of result before the call to calc_numbers is: [50L, -1, 1, -1] An example of result before the call is: [50L, -1L, 1L, -1L] Sorry about that. Thanks, Patricia From davholla2002 at yahoo.co.uk Thu Apr 13 18:53:20 2006 From: davholla2002 at yahoo.co.uk (David Holland) Date: Thu, 13 Apr 2006 17:53:20 +0100 (BST) Subject: [Tutor] Show us some code Message-ID: <20060413165320.39006.qmail@web25911.mail.ukl.yahoo.com> John, Can you please post your code and the exact error message. ------------------------------------------------------------------------------------------------------------------------------------ First they came for the Danes, but I did not speak out because I am not a Dane. --------------------------------- Yahoo! Messenger NEW - crystal clear PC to PC calling worldwide with voicemail -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060413/59716233/attachment.html From Barry.Carroll at psc.com Thu Apr 13 18:55:35 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Thu, 13 Apr 2006 09:55:35 -0700 Subject: [Tutor] failing to learn python Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C3651@eugsrv400.psc.pscnet.com> Greetings: The discussion surrounding this topic (by Payal, Kent, Alan and others) has been very interesting. It illustrates the fact that software engineering remains very much a craft. As with all crafts, is heavily influenced by the preferences (style if you will) of the individual artisan. There are very few 'right or wrong' answers here. The tool that works well and feels comfortable when used is the one that should be used. When a new tool comes along, try it out. If it makes the work easier or faster, or the product better, then use it. If not, forget it. The product is the goal, not the tool. Regards, Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed > -----Original Message----- <> > > For me, I don't know those specialized tools and I have chosen not to > > learn them because I don't often need their capabilities and Python can > do > > what they do. > > I must admit I use a myriad of tools, including several text editors. > Its one of the few areas where I disagree with Hunt & Thomas > in "the Pragmatic Programmer", they advocate choosing one editor > and using it exclusively, I use emacs, vim, xedit and even ed on > a daily basis (OK ed only once a month or so!) But I also use > awk and sed weekly. <> > From dyoo at hkn.eecs.berkeley.edu Thu Apr 13 20:18:51 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 13 Apr 2006 11:18:51 -0700 (PDT) Subject: [Tutor] Python video? In-Reply-To: <20060413032839.86688.qmail@web60012.mail.yahoo.com> References: <20060413032839.86688.qmail@web60012.mail.yahoo.com> Message-ID: On Wed, 12 Apr 2006, Hoffmann wrote: > I read this week on this forum about a kind of Python video in its > website. Which view is that, and where could I find it? I search in > Python website, but I didn't find it. Is it a 'demo' of the language? It's a video with gushing praise over Python, made in the style of a Monty Python skit. There's a link to it from here: http://wiki.python.org/moin/PythonCdFun From oasf2004 at yahoo.com Thu Apr 13 20:53:10 2006 From: oasf2004 at yahoo.com (Hoffmann) Date: Thu, 13 Apr 2006 11:53:10 -0700 (PDT) Subject: [Tutor] failing to learn python In-Reply-To: <2BBAEE949D384D40A2B851287ADB6A432C3651@eugsrv400.psc.pscnet.com> Message-ID: <20060413185310.16849.qmail@web60014.mail.yahoo.com> --- "Carroll, Barry" wrote: > Greetings: > > The discussion surrounding this topic (by Payal, > Kent, Alan and others) > has been very interesting. It illustrates the fact > that software > engineering remains very much a craft. As with all > crafts, is heavily > influenced by the preferences (style if you will) of > the individual > artisan. There are very few 'right or wrong' > answers here. > > The tool that works well and feels comfortable when > used is the one that > should be used. When a new tool comes along, try it > out. If it makes > the work easier or faster, or the product better, > then use it. If not, > forget it. The product is the goal, not the tool. > > Regards, > > Barry > barry.carroll at psc.com > 541-302-1107 > ________________________ > We who cut mere stones must always be envisioning > cathedrals. > > -Quarry worker's creed > > > > -----Original Message----- > > <> > > > > For me, I don't know those specialized tools and > I have chosen not > to > > > learn them because I don't often need their > capabilities and Python > can > > do > > > what they do. > > > > I must admit I use a myriad of tools, including > several text editors. > > Its one of the few areas where I disagree with > Hunt & Thomas > > in "the Pragmatic Programmer", they advocate > choosing one editor > > and using it exclusively, I use emacs, vim, xedit > and even ed on > > a daily basis (OK ed only once a month or so!) But > I also use > > awk and sed weekly. > > <> > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Hi Barry, I do agree with you. I also would add the Linux/Windows 'dispute'. I am a BIG FAN of linux. Even at home I use linux 90% of the time. However, in some cases I use Windows, as well (to watch DVDs (movies), for example). Due to the stability of Windows in this (multimidia) case, I do prefer using it for watching movies. So. There is no reason to use just one programming language. I am a BIG FAN of Python, but I am studying Python, Shell programming, and MATLAB in paralell. Moreover, I am very interested in both Fortran and C. Hoffmann __________________________________________________ Do